Cha*_*son 5 python multithreading subprocess
当我使用python.exe运行它时,我有一些Python代码可以正常工作,但如果我使用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.
sys.stdin和sys.stdout句柄无效,因为pythonw不提供控制台支持,因为它作为deamon运行,因此默认参数subprocess.call()失败.
Deamon程序有目的地关闭stdin/stdout/stderr并使用日志记录,因此您必须自己管理:我建议使用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())
Run Code Online (Sandbox Code Playgroud)
请注意,由于子进程模块中存在明显的错误,对Popen()的调用也必须为stdin指定一个管道,然后我们立即关闭它.