我有一些 Python 代码,当我使用 python.exe 运行它时可以正常运行,但如果我使用 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() 可以正常启动。
我可以看到 pythonw.exe 可能正在重定向输出本身,但我不明白为什么我无法为新线程指定标准输出。
最佳答案
sys.stdin
和 sys.stdout
句柄无效,因为 pythonw 不提供控制台支持,因为它作为守护进程运行,所以 子进程的默认参数。 call()
失败了。
Deamon 程序故意关闭 stdin/stdout/stderr 并改用日志记录,因此您必须自己管理:我建议使用 subprocess.PIPE。
如果您真的不关心子进程对错误和所有内容的说明,您可以使用os.devnull
(我不太确定可移植性如何是吗?)但我不推荐这样做。
关于使用 pythonw.exe 时 Python subprocess.call() 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/337870/