我有一段代码可以完成几乎所有我想要的事情。看起来像:
with open('./all_output.txt', 'w') as f:
sys.stdout = f
sys.stderr = f
print("hello")
subprocess.run(['pwd'], stdout=f, stderr=f)
subprocess.run(['illegal_operation'], stdout=f, stderr=f)
输出类似于:
hello
/home/johndoe/
FileNotFoundError: [Errno 2] No such file or directory: 'illegal_operation': 'illegal_operation'
我想这样做,以便TextIOWrapper f在每次向其写入一行时都打印一条消息(时间戳)。例如
5/15/19 12:30:01 hello
5/15/19 12:30:01 /home/johndoe/
5/15/19 12:30:02 FileNotFoundError: [Errno 2] No such file or directory: 'illegal_operation': 'illegal_operation'
我尝试了“ newline”参数,但是只需要\ n或\ t。