Python Popen 成功卻回傳非 0

現象

有位 user 使用 Python subprocess.Popen() 來執行程式時,明明該程式顯示成功,且回傳 0,但是在 Python 中卻拿到非 0 回傳值,這是為什麼哩?

# 範例程式
import subprocess
proc = subprocess.Popen("calc.exe", shell=True)
proc.communicate()
print(proc.returncode)

調查

該 Python 腳本不是我寫的,但是可以看到 Popen 帶了參數 shell=True,根據官方文件說明,這會帶起系統 shell 來執行指定的程式,這樣就可以用到一些 shell 自帶的功能,如 pipe、萬用字元等。

If shell is True, the specified command will be executed through the shell. This can be useful if you are using Python primarily for the enhanced control flow it offers over most system shells and still want convenient access to other shell features such as shell pipes, filename wildcards, environment variable expansion, and expansion of ~ to a user’s home directory.

看到這邊,不難想到是不是 shell 做了一些事情,於是請該 user 在他的終端機中輸入 cmd,果然看到錯誤訊息!

img

從 registry 可以看到 shell 會預先載入一支程式,但是該程式已經被使用者刪除,找不到該程式 cmd 才報錯,進而影響到 Popen。

img

經詢問,是該 user 當初有裝過 Anaconda,後來移除後,沒想到 registry 這邊沒刪乾淨。

因此,把 AutoRun 刪掉就解決囉~


comments powered by Disqus