【问题标题】:Python subprocess.call() fails when using pythonw.exe使用 pythonw.exe 时 Python subprocess.call() 失败
【发布时间】:2010-09-25 04:05:45
【问题描述】:

我有一些 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。

【问题讨论】:

    标签: python multithreading subprocess


    【解决方案1】:

    这是一个老问题,但同样的问题也发生在 pyInstaller 上。

    事实上,任何在没有控制台的情况下将 python 中的代码转换为 exe 的框架都会发生这种情况。

    在我的测试中,我观察到如果我在我的规范文件 (pyInstaller) 中使用标志“console=True”,则不再发生错误。 .

    解决方案是按照 Piotr Lesnicki 的建议。

    【讨论】:

    • 我目前遇到了同样的问题,我用 PyQt4 制作了一个大型应用程序,如果没有控制台,我无法让 selenium 工作。请告诉我如何解决这个问题。 stackoverflow.com/questions/46520823/…
    【解决方案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())
    

    请注意,由于 subprocess 模块中存在明显的错误,对 Popen() 的调用也必须为 stdin 指定一个管道,然后我们立即关闭它。

    【讨论】:

      【解决方案3】:

      sys.stdinsys.stdout 句柄无效,因为 pythonw 在作为守护进程运行时不提供控制台支持,因此 subprocess.call() 的默认参数失败。

      Deamon 程序故意关闭 stdin/stdout/stderr 并改用日志记录,因此您必须自己管理:我建议使用 subprocess.PIPE。

      如果你真的不关心子进程对错误和所有内容的说明,你可以使用os.devnull(我不确定它的便携性如何?)但我不会不建议这样做。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-03-29
        • 1970-01-01
        • 2014-06-09
        • 1970-01-01
        • 1970-01-01
        • 2014-07-06
        相关资源
        最近更新 更多