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

但是,如果我不指定 '标准输出' 参数,subprocess.call()开始行。

我可以看到pythonw.exe可能会被重定向输出本身,但我不明白为什么我从指定标准输出为一个新的线程阻塞。

有帮助吗?

解决方案

sys.stdin手柄sys.stdout是无效的,因为pythonw不提供控制台支持,因为它运行作为一个后台程序,所以subprocess.call()的默认参数是失败。

守护进程程序关闭标准输入/输出/标准错误刻意的和使用记录,而不是,所以你必须要管理这个自己:我会建议使用subprocess.PIPE

如果您的真正的不关心什么子流程说的错误和一切,你可以使用os.devnull(我真的不知道它是如何携带的?),但我不会建议。

其他提示

有关的记录,我的代码现在看起来是这样的:

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的为好,这我们关闭之后立即。

这是一个老问题,但与pyInstaller同样的问题发生了。

在事实上,这将与在python为EXE转换代码,而无需任何控制台框架发生。

在测试中,我观察到,如果我用标志“=控制台真”到我的规格文件(pyInstaller)的错误不再出现。

的解决方案是遵循彼得Lesnicki的尖端。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top