Python3:ValueError:I / O操作

时间:2018-01-29 07:11:24

标签: python python-3.x stdout

我只想将print输出重定向到文件。我的代码如下:

import sys

# define the log file that receives your log info
log_file = open("message.log", "w")
# redirect print output to log file
sys.stdout = log_file

print ("Now all print info will be written to message.log")
# any command line that you will execute
...

log_file.close()

print ("Now this will be presented on screen")

执行脚本后,出现错误:

[~/Liaohaifeng]$ python3 log.py
Traceback (most recent call last):
  File "log.py", line 14, in <module>
  print ("Now this will be presented on screen")
ValueError: I/O operation on closed file. 

为什么会这样?如果我更新我的脚本如下:

import sys

# make a copy of original stdout route
stdout_backup = sys.stdout
# define the log file that receives your log info
log_file = open("message.log", "w")
# redirect print output to log file
sys.stdout = log_file

print ("Now all print info will be written to message.log"
# any command line that you will execute
...

log_file.close()
# restore the output to initial pattern
sys.stdout = stdout_backup

print ("Now this will be presented on screen")

没关系。那么,请你告诉我这个问题的理论吗?

1 个答案:

答案 0 :(得分:1)

正如评论中所述,print不会打印到已关闭的文件句柄而您已关闭sys.stdout,可能会破坏关闭后引发的任何打印件。甚至在您不知情的情况下也可能发生这种情况,例如导入代码中的某处。这就是为什么你不应该使用sys.*变量(或者你没有创建的任何变量,除非你绝对需要)。有一种将print输出重定向到文件的正确方法,它是这样的:

log_file = open('message.log', 'w')
print('Stuff to print in the log', file=log_file)
log_file.close()

甚至更安全:

with open('message.log', 'w') as log_file:
    # Do stuff
    print('Stuff to print in the log', file=log_file)

with块完成时,句柄将自动刷新并关闭。