[英]Running a shell script using Subprocess in Python does not produce output
我正在嘗試使用 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")
但是,在運行它時,我只得到以下 output:
RUNNNING SHELL SCRIPT NOW
SHELL SCRIPT RUN ENDED
即我沒有在這兩行之間得到 shell 腳本 output 。
此外,當我從子進程中刪除stderr=subprocess.PIPE
subprocess.PIPE 部分時,我得到以下 output:
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")
我得到以下 output:
RUNNNING SHELL SCRIPT NOW
b''
SHELL SCRIPT RUN ENDED
簡單直接的解決方法是不為此使用裸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
,你需要了解它的處理 model。 但是,如果您只是想完成工作,簡單的答案是不要使用Popen
。
錯誤消息實際上看起來像您在 Windows 上,它嘗試通過cmd
運行km
,它認為斜杠是選項分隔符,而不是目錄分隔符。 刪除shell=True
可以避免這種復雜性,並且只需使用請求的名稱啟動一個進程。 (這當然仍然要求文件存在於您指定的相對文件名中。也許另請參閱當前工作目錄到底是什么?也可能切換到本機 Windows 反斜杠,使用r'...'
字符串來防止 Python從試圖解釋反斜杠。)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.