簡體   English   中英

使用pythonw.exe時,Python subprocess.call()失敗

[英]Python subprocess.call() fails when using pythonw.exe

當我使用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.stdinsys.stdout句柄無效,因為pythonw在作為deamon運行時不提供控制台支持,因此subprocess.call()默認參數失敗。

Deamon程序有目的地關閉stdin / stdout / stderr並使用日志記錄,因此您必須自己管理:我建議使用subprocess.PIPE。

如果你真的不關心子進程對錯誤和所有的os.devnull ,你可以使用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 for exe中轉換代碼。

在我的測試中,我觀察到如果我在我的spec文件(pyInstaller)中使用標志“console = True”,則不再出現錯誤。

解決方案遵循Piotr Lesnicki的提示。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM