使用 pythonw.exe 时 Python subprocess.call() 失败
问题描述
我有一些 Python 代码在我使用 python.exe 运行时可以正常工作,但如果我使用 pythonw.exe 会失败.
<上一页>def runStuff(命令行):outputFileName = 'somefile.txt'输出文件 = 打开(输出文件名,w")尝试:结果 = subprocess.call(commandLine, shell=True, stdout=outputFile)除了:print '抛出异常:', str(sys.exc_info()[1])myThread = threading.Thread(None, target=runStuff, commandLine=['whatever...'])myThread.start()我得到的信息是:
<上一页>抛出异常:[错误 6] 句柄无效但是,如果我不指定 'stdout' 参数,subprocess.call() 启动正常.
我可以看到 pythonw.exe 可能正在重定向输出本身,但我不明白为什么我无法为新线程指定 stdout.
解决方案sys.stdin
和 sys.stdout
句柄无效,因为 pythonw 不提供控制台支持作为守护进程运行,因此 subprocess.call()
的默认参数失败.
Deamon 程序故意关闭 stdin/stdout/stderr 并改用日志记录,因此您必须自己管理:我建议使用 subprocess.PIPE.
如果您真的不关心子进程对错误的说明以及所有内容,您可以使用 os.devnull
(我不太确定可移植性如何是吗?)但我不建议这样做.
I have some Python code that works correctly when I use python.exe to run it, but fails if I use pythonw.exe.
def runStuff(commandLine): outputFileName = 'somefile.txt' outputFile = open(outputFileName, "w") try: result = subprocess.call(commandLine, shell=True, stdout=outputFile) except: print 'Exception thrown:', str(sys.exc_info()[1]) myThread = threading.Thread(None, target=runStuff, commandLine=['whatever...']) myThread.start()
The message I get is:
Exception thrown: [Error 6] The handle is invalid
However, if I don't specify the 'stdout' parameter, subprocess.call() starts okay.
I can see that pythonw.exe might be redirecting output itself, but I can't see why I'm blocked from specifying stdout for a new thread.
解决方案sys.stdin
and sys.stdout
handles are invalid because pythonw does not provide console support as it runs as a deamon, so default arguments of subprocess.call()
are failing.
Deamon programs close stdin/stdout/stderr purposedly and use logging instead, so that you have to manage this yourself: I would suggest to use subprocess.PIPE.
If you really don't care about what the sub process says for errors and all, you could use os.devnull
(I'm not really sure how portable it is?) but I wouldn't recommend that.
相关文章