当我仅使用脚本名称在 Windows 上运行 Python 脚本时无法重定向输出

问题描述

这是在 Windows 7(64 位)、Python 2.6 上运行的,带有适用于 Python 的 Win32 扩展.

我有一个简单的脚本,只打印hello world".我可以使用 python hello.py 启动它.在这种情况下,我可以将输出重定向到文件.但是,如果我通过在命令行中键入 hello.py 并重定向输出来运行它,我会得到一个异常.

C:>蟒蛇你好.py你好世界C:>python hello.py >输出C:>类型输出你好世界C:>你好.py你好世界C:>你好.py>输出在文件对象析构函数中关闭失败:sys.excepthook 中的错误:原来的例外是:

我想我是在升级到 Windows 7 后第一次遇到这个错误.我记得它应该在 XP 中工作.我见过人们谈论这个错误 python-Bugs-1012692|无法通过管道将输入输入到 python 程序.但那是很久以前的事了.它没有提到任何解决方案.

有人经历过吗?有人可以帮忙吗?

解决方案

你问这个吗?

<块引用>

Windows:使用文件类型在命令行上执行 Python 脚本时关联(即开始script.py"而不是python script.py"),除非您设置特定的注册表项,否则重定向可能不起作用.看知识库文章STDIN/STDOUT 重定向可能无法从文件关联开始.

它在 Python README 中.也许这个补丁就是你要找的.

This is running on Windows 7 (64 bit), Python 2.6 with Win32 Extensions for Python.

I have a simple script that just print "hello world". I can launch it with python hello.py. In this case I can redirect the output to a file. But if I run it by just typing hello.py on the command line and redirect the output, I get an exception.

C:> python hello.py
hello world

C:> python hello.py >output

C:> type output
hello world

C:> hello.py
hello world

C:> hello.py >output
close failed in file object destructor:
Error in sys.excepthook:

Original exception was:

I think I first get this error after upgrading to Windows 7. I remember it should work in XP. I have seen people talking about this bug python-Bugs-1012692 | Can't pipe input to a python program. But that was long time ago. And it does not mention any solution.

Have anyone experienced this? Anyone can help?

解决方案

Are you asking about this?

Windows: When executing Python scripts on the command line using file type associations (i.e. starting "script.py" instead of "python script.py"), redirects may not work unless you set a specific registry key. See the Knowledge Base article STDIN/STDOUT Redirection May Not Work If Started from a File Association.

It's in the Python README. Perhaps this patch is what you're looking for.

相关文章