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

Python subprocess.call() fails when using pythonw.exe(使用 pythonw.exe 时 Python subprocess.call() 失败)
本文介绍了使用 pythonw.exe 时 Python subprocess.call() 失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

解决方案

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

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

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

I have some Python code that works correctly when I use python.exe to run it, but fails if I use 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()

The message I get is:

    Exception thrown: [Error 6] The handle is invalid

However, if I don't specify the 'stdout' parameter, subprocess.call() starts okay.

I can see that pythonw.exe might be redirecting output itself, but I can't see why I'm blocked from specifying stdout for a new thread.

解决方案

sys.stdin and sys.stdout handles are invalid because pythonw does not provide console support as it runs as a deamon, so default arguments of subprocess.call() are failing.

Deamon programs close stdin/stdout/stderr purposedly and use logging instead, so that you have to manage this yourself: I would suggest to use subprocess.PIPE.

If you really don't care about what the sub process says for errors and all, you could use os.devnull (I'm not really sure how portable it is?) but I wouldn't recommend that.

这篇关于使用 pythonw.exe 时 Python subprocess.call() 失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Leetcode 234: Palindrome LinkedList(Leetcode 234:回文链接列表)
How do I read an Excel file directly from Dropbox#39;s API using pandas.read_excel()?(如何使用PANDAS.READ_EXCEL()直接从Dropbox的API读取Excel文件?)
subprocess.Popen tries to write to nonexistent pipe(子进程。打开尝试写入不存在的管道)
I want to realize Popen-code from Windows to Linux:(我想实现从Windows到Linux的POpen-code:)
Reading stdout from a subprocess in real time(实时读取子进程中的标准输出)
How to call type safely on a random file in Python?(如何在Python中安全地调用随机文件上的类型?)