提问人:Charles Anderson 提问时间:12/4/2008 更新时间:8/23/2014 访问量:6449
Python subprocess.call() 在使用 pythonw.exe 时失败
Python subprocess.call() fails when using pythonw.exe
问:
我有一些 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可能正在重定向输出本身,但我不明白为什么我被阻止为新线程指定 stdout。
答:
7赞
Piotr Lesnicki
12/4/2008
#1
sys.stdin
句柄无效,因为 pythonw 在作为 deamon 运行时不提供控制台支持,因此默认参数 失败。sys.stdout
subprocess.call()
Deamon 程序有目的地关闭 stdin/stdout/stderr 并使用日志记录,因此您必须自己管理它:我建议使用子进程。管。
如果你真的不关心子进程对错误和所有内容的看法,你可以使用(我不太确定它的便携性?),但我不建议这样做。os.devnull
7赞
Charles Anderson
12/22/2008
#2
作为记录,我的代码现在如下所示:
def runStuff(commandLine):
outputFileName = 'somefile.txt'
outputFile = open(outputFileName, "w")
if guiMode:
result = subprocess.call(commandLine, shell=True, stdout=outputFile, stderr=subprocess.STDOUT)
else:
proc = subprocess.Popen(commandLine, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.PIPE)
proc.stdin.close()
proc.wait()
result = proc.returncode
outputFile.write(proc.stdout.read())
请注意,由于子进程模块中存在明显的错误,对 Popen() 的调用也必须为 stdin 指定一个管道,我们随后立即关闭该管道。
2赞
Eduardo
8/23/2014
#3
这是一个老问题,但同样的问题也发生在 pyInstaller 上。
事实上,这将发生在任何在没有控制台的情况下将 python 中的代码转换为 exe 的框架。
在我的测试中,我观察到如果我在我的规范文件(pyInstaller)中使用标志“console=True”,则不再发生错误。.
解决方案是遵循 Piotr Lesnicki 的提示。
评论
0赞
Ahmad Taha
10/2/2017
我目前遇到了同样的问题,我用 PyQt4 制作了一个大应用程序,如果没有控制台,我就无法让 selenium 工作。请告诉我如何解决这个问题。stackoverflow.com/questions/46520823/......
评论