使用 pythonw.exe 时 Python subprocess.call() 失败

标签 python multithreading subprocess

我有一些 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.stdinsys.stdout 句柄无效,因为 pythonw 不提供控制台支持,因为它作为守护进程运行,所以 子进程的默认参数。 call() 失败了。

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

如果您真的不关心子进程对错误和所有内容的说明,您可以使用os.devnull(我不太确定可移植性如何是吗?)但我不推荐这样做。

关于使用 pythonw.exe 时 Python subprocess.call() 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/337870/

相关文章:

python - Xpath 提取某些字符之间的日期并用作日期

python - 如何在 Jenkins 环境中运行不同的 tox 命令?

c# -> 30 个线程的线程问题。 CPU 非线性扩展

python - tail 命令没有给出 subprocess.Popen 的正确答案

c++ - Boost 中是否有跨平台执行程序?

python - 压缩数组(在 Python 中)比具有一维条目的数组小吗? ([x,y] 与 [x,y,1]?)

java - 从 python 到 stdin java 的 stdout

multithreading - 如何访问 Robolectric 中的后台线程?

c - Pthread不执行函数

python - 具有子处理功能的多处理