[英]Python: executing shell script with arguments(variable), but argument is not read in shell script
我正在嘗試從 python 執行一個 shell 腳本(不是命令):
main.py
-------
from subprocess import Popen
Process=Popen(['./childdir/execute.sh',str(var1),str(var2)],shell=True)
execute.sh
----------
echo $1 //does not print anything
echo $2 //does not print anything
var1 和 var2 是我用作 shell 腳本輸入的一些字符串。 我錯過了什么還是有其他方法可以做到這一點?
問題在於shell=True
。 刪除該參數,或將所有參數作為字符串傳遞,如下所示:
Process=Popen('./childdir/execute.sh %s %s' % (str(var1),str(var2),), shell=True)
shell 只會將您在Popen
的第一個參數中提供的參數傳遞給進程,因為它本身會解釋參數。 請參閱此處回答的類似問題。 實際發生的是你的 shell 腳本沒有參數,所以 $1 和 $2 是空的。
Popen 將從 python 腳本繼承 stdout 和 stderr,因此通常不需要向stdin=
提供stdin=
和stderr=
參數(除非您運行帶有輸出重定向的腳本,例如>
)。 只有當您需要讀取 python 腳本中的輸出並以某種方式對其進行操作時,才應該這樣做。
如果你需要的是讓輸出(並且不介意同步運行),我建議你嘗試check_output
,因為它更容易獲得產量比Popen
:
output = subprocess.check_output(['./childdir/execute.sh',str(var1),str(var2)])
print(output)
注意, check_output
和check_call
具有用於相同的規則shell=
參數作為Popen
。
你實際上是在發送參數......如果你的shell腳本寫了一個文件而不是打印你會看到它。 您需要進行通信以查看腳本的打印輸出...
from subprocess import Popen,PIPE
Process=Popen(['./childdir/execute.sh',str(var1),str(var2)],shell=True,stdin=PIPE,stderr=PIPE)
print Process.communicate() #now you should see your output
如果你想以一種簡單的方式從 python 腳本向 shellscript 發送參數.. 你可以使用 python os 模塊:
import os
os.system(' /path/shellscriptfile.sh {} {}' .format(str(var1), str(var2))
如果您有更多參數.. 增加花括號並添加參數.. 在 shellscript 文件中.. 這將讀取參數,您可以相應地執行命令
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.