簡體   English   中英

從Python子進程執行shell腳本

[英]execute a shell-script from Python subprocess

我需要從python調用shellscript。 問題在於,shellscript將一直詢問幾個問題,直到完成為止。

我找不到使用subprocess (使用pexpect似乎有點過分,因為我只需要啟動它並向它發送幾個YES)

請不要建議需要修改shell腳本的方法!

使用subprocess庫,您可以告訴Popen類您想要管理流程的標准輸入,如下所示:

import subprocess
shellscript = subprocess.Popen(["shellscript.sh"], stdin=subprocess.PIPE)

現在shellscript.stdin是一個類似於文件的對象,可以在其上調用write

shellscript.stdin.write("yes\n")
shellscript.stdin.close()
returncode = shellscript.wait()   # blocks until shellscript is done

您還可以通過設置stdout=subprocess.PIPEstderr=subprocess.PIPE從流程中獲取標准輸出和標准錯誤,但是您不應將PIPEs用於標准輸入和標准輸出,因為這可能會導致死鎖。 (請參閱文檔 。)如果需要管道輸入和管道輸出,請使用communicate方法而不是類似文件的對象:

shellscript = subprocess.Popen(["shellscript.sh"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = shellscript.communicate("yes\n")   # blocks until shellscript is done
returncode = shellscript.returncode

暫無
暫無

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

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