1. 程式人生 > >python 使用pyinstaller打包時,subprocess失效問題

python 使用pyinstaller打包時,subprocess失效問題

使用pyinstaller將python程式打包,不使用-w引數時(如“pyinstaller -F main.py -i cat.ico”)程式執行正常,但使用-w引數去掉console後,程式便卡在了一個地方無法繼續執行,經過除錯發現,出問題的地方在subprocess.Popen語句,原來是這樣的:

popen = subprocess.Popen(cmd_list, shell=False, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    while popen.poll() is None:
        line = popen.stdout.readline().decode('utf-8').strip()
        print(line)

將subprocess.Popen的引數設為“shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT”便能正常運行了。將shell設為True後,通過shell執行指定的命令(後臺應該默默地建立了一個console?),並利用建立的管道進行輸入和輸出。

我還試了一下,若將subprocess.Popen的引數設為“shell=False, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT”,則打包執行程式後會彈出來一個console,也就是說“stdin=subprocess.PIPE”是一定要有的,shell設為Ture不會彈出console,shell設為False則會彈出一個console。

參考文獻: