在C++中,我可以輸出到cout
和cerr
;在實踐中,這會導致代碼,其中我可以一次像輸出重定向到兩個文件:Python:輸出到多個重定向
./some_program > first_file.something 2> second_file.else
我將如何做到這一點在Python?
在C++中,我可以輸出到cout
和cerr
;在實踐中,這會導致代碼,其中我可以一次像輸出重定向到兩個文件:Python:輸出到多個重定向
./some_program > first_file.something 2> second_file.else
我將如何做到這一點在Python?
E.g.在Python 3中,只需導入cout
和cerr
的等效項,即sys.stdout
和sys.stderr
。
from sys import stdout, stderr
print('to standard output', file=stdout)
print('to standard error', file=stderr)
然後你可以使用你的bash重定向像往常一樣:
python program.py 1>output 2>errors
如果你願意,你甚至可以爲它們命名任何你喜歡的。例如:
from sys import stdout as cout, stderr as cerr
print('to standard output', file=cout)
print('to standard error', file=cerr)
它不太「Pythonic」,但如果它幫助您彌合與C++經驗的差距,它可能是一種幫助。
https://docs.python.org/3/library/sys.html
sys.stdout
sys.stderr
如果你想在命令行重定向,它幾乎以同樣的方式,你會用C做++:
python file.py > first_file.txt 2> second_file.txt
編程,就可以用sys.stdout
和sys.stderr
做到這一點,通過猴子用你選擇的文件修補它們。
真棒 - 感謝的人 – bordeo