使用pythonw.exe时Python subprocess.call()失败 [英] Python subprocess.call() fails when using pythonw.exe
问题描述
当我使用python.exe运行它时,我有一些Python代码可以正常运行,但是如果使用pythonw.exe,则失败.
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()
我收到的消息是:
Exception thrown: [Error 6] The handle is invalid
但是,如果我不指定'stdout'参数,subprocess.call()会开始正常.
However, if I don't specify the 'stdout' parameter, subprocess.call() starts okay.
我可以看到pythonw.exe可能正在重定向输出本身,但是我看不到为什么我被阻止为新线程指定stdout.
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
和sys.stdout
句柄无效,因为pythonw作为守护进程运行时不提供控制台支持,因此subprocess.call()
的默认参数失败
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程序有意关闭stdin/stdout/stderr并改用日志记录,因此您必须自己进行管理:我建议使用subprocess.PIPE.
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.
如果您真的不在乎子流程对错误和所有内容的说法,则可以使用os.devnull
(我不确定它的可移植性吗?),但是我不会不建议这样做.
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.
这篇关于使用pythonw.exe时Python subprocess.call()失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!