2017-11-17 153 views
0

在C++中,我可以输出到coutcerr;在实践中,这会导致代码,其中我可以一次像输出重定向到两个文件:Python:输出到多个重定向

./some_program > first_file.something 2> second_file.else 

我将如何做到这一点在Python?

回答

2

E.g.在Python 3中,只需导入coutcerr的等效项,即sys.stdoutsys.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++经验的差距,它可能是一种帮助。

+0

真棒 - 感谢的人 – bordeo

1

如果你想在命令行重定向,它几乎以同样的方式,你会用C做++:

python file.py > first_file.txt 2> second_file.txt 

编程,就可以用sys.stdoutsys.stderr做到这一点,通过猴子用你选择的文件修补它们。