[英]Which is better way to write out and err of python
I am writing python in Linux.我正在 Linux 中编写 python。 I want to write the python output and error into different files than output them on the console.
我想将 python 输出和错误写入不同的文件而不是在控制台上输出它们。
Say if I have this python file example.py
:假设我有这个 python 文件
example.py
:
print('console output')
print(1/0)
I tried different way.我尝试了不同的方式。
1. By executing the following command 1.通过执行以下命令
python example.py >output 2>log
2. Update the example.py
2.更新
example.py
logf = open("./log", "w")
try:
print('console output')
print(1/0)
except Exception as e:
logf.write(str(e))
and execute python example.py >output
并执行
python example.py >output
The logs are different.日志不一样。 1st method:
第一种方法:
Traceback (most recent call last):
File "try.py", line 2, in <module>
print(1/0)
ZeroDivisionError: division by zero
and for 2nd method:对于第二种方法:
division by zero
So I want to ask:所以我想问:
Thanks for helping with my questions.感谢您帮助我解决问题。
Leave the script the simple, original way:让脚本保持简单、原始的方式:
# example.py
print('console output')
print(1/0)
Use easy trick in shell:在 shell 中使用简单的技巧:
$ python example.py &> log.txt
If you wanted some other custom behaviour on unhandled exceptions, set asys.excepthook
.如果您想对未处理的异常进行一些其他自定义行为,请设置
sys.excepthook
。
To combine both stdout and stderr into one file, which is also helpful when using more (or less) command将 stdout 和 stderr 合并到一个文件中,这在使用更多(或更少)命令时也很有帮助
python example.py 2>&1 > output
python example.py 2>&1 | more
To make each go into separate files使每个进入单独的文件
python example.py 2> error > output
To ignore stederr忽略 steder
python example 2>/dev/null
Hope this helps.希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.