Чтобы напечатать в stderr в Python, вы можете указать функции print() на файл sys.stderr .
Содержание
Для Python 3
|
1 2 3 4 5 6 7 8 9 10 |
import sys def print_to_stderr(*a): # Here a is the array holding the objects # passed as the arguement of the function print(*a, file = sys.stderr) print_to_stderr("That's an error") |
Выход
|
1 |
That's an error |
Как видите, мы напечатали его для stderr.
Также можно обратиться к гораздо более доступным и гибким, чем другие методы.
|
1 2 3 4 5 6 7 8 9 10 |
from __future__ import print_function import sys def modified_print(*args, **kwargs): print(*args, file=sys.stderr, **kwargs) modified_print("asian", "paints", "indigo", "paints", sep="||") |
Выход
|
1 |
asian||paints||indigo||paints |
Здесь функция mod_print() работает так же, как и функция print() в Python.
Для Python 2
В Python 2 мы можем использовать синтаксис print >> sys.stderr, который устарел в Python 3, поскольку в Python 3 print — это функция, а не инструкция.
|
1 2 3 4 |
import sys print >> sys.stderr, 'Hello world' |
Другие методы
sys.stderr — это файловый объект как в Python 2, так и в Python 3, и вы можете использовать метод write().
|
1 2 3 4 |
import sys sys.stderr.write('Bart Simposon') |
Выход
|
1 |
Bart Simposon |
