【发布时间】:2019-02-21 16:47:06
【问题描述】:
我正在尝试修复的脚本使用以下范例将标准输出重定向到文件。
import os
stdio_file = 'temp.out'
flag = os.O_WRONLY | os.O_CREAT | os.O_TRUNC
stdio_fp = os.open(stdio_file, flag)
os.dup2(stdio_fp, 1)
print("hello")
在 Python 2 上,这是可行的。在 Python 3 上,您会收到 OSError
Traceback (most recent call last):
File "test.py", line 6, in <module>
print("hello")
OSError: [WinError 6] The handle is invalid
Exception ignored in: <_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>
OSError: [WinError 6] The handle is invalid
我认为通过文件路由标准输出有更可取的方法,但我想知道为什么这个方法在 Python 3 中停止工作,是否有一种简单的方法来修复它?
【问题讨论】:
-
@eryksun 您的 cmets 是一个很好的答案。为什么不合二为一呢?
-
你是对的,设置
PYTHONLEGACYWINDOWSSTDIO可以解决问题。但是,我仍在努力解决脑海中的附加评论。我对很多操作系统的东西有点陌生。
标签: python windows python-3.x operating-system