我正在嘗試使用 subprocess.Popen() 通過 Python 運行 shell 腳本。
shell 腳本只有以下幾行:
#!/bin/sh
echo Hello World
以下是 Python 代碼:
print("RUNNNING SHELL SCRIPT NOW")
shellscript = subprocess.Popen(['km/example/example1/source/test.sh'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
shellscript.wait()
for line in shellscript.stdout.readlines():
print(line)
print("SHELL SCRIPT RUN ENDED")
但是,在運行它時,我只得到以下輸出:
RUNNNING SHELL SCRIPT NOW
SHELL SCRIPT RUN ENDED
即我沒有在這兩行之間獲得 shell 腳本輸出。
此外,當我stderr=subprocess.PIPE從子流程中洗掉部件時,我得到以下輸出:
RUNNNING SHELL SCRIPT NOW
'km' is not defined as an internal or external command.
SHELL SCRIPT RUN ENDED
我無法理解如何解決此問題并正確運行 shell 腳本。請指導。謝謝。
更新:
我還嘗試了以下更改:
print("RUNNNING SHELL SCRIPT NOW")
shellscript = subprocess.Popen(['km/example/example1/source/test.sh'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
out, err = shellscript.communicate()
print(out)
print("SHELL SCRIPT RUN ENDED")
我得到以下輸出:
RUNNNING SHELL SCRIPT NOW
b''
SHELL SCRIPT RUN ENDED
uj5u.com熱心網友回復:
簡單而直接的解決方法是不要Popen為此使用裸機。
您也不需要 shell 來運行子行程;如果子行程是一個 shell 腳本,則該子行程本身就是一個 shell,但是您不需要 shell 的幫助來運行該腳本。
proc = subprocess.run(
['km/example/example1/source/test.sh'],
check=True, capture_output=True, text=True)
out = proc.stdout
如果真的需要使用Popen,就需要了解它的處理模型。但是,如果您只是想完成作業,那么簡單的答案是不要使用Popen.
錯誤訊息實際上看起來像您在 Windows 上,并且它嘗試km通過cmd它認為斜杠是選項分隔符而不是目錄分隔符來運行。洗掉shell=True避免了這種復雜性,只需使用請求的名稱啟動一個行程。(這當然仍然要求該檔案存在于您指定的相對檔案名中。也許另請參閱當前作業目錄究竟是什么?也可能切換到本機 Windows 反斜杠,并帶有一個r'...'字串以防止 Python 嘗試解釋反斜杠.)
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/368553.html
