![](/img/trans.png)
[英]Error handling of python subprocess to run bash script with multiple input arguments vs successful running of bash script with hardcoded inputs
[英]Python: subprocess and running a bash script with multiple arguments
如何使用 subprocess 模塊運行 bash 腳本,我必須給它幾個參數?
這是我目前正在使用的:
subprocess.Popen(['/my/file/path/programname.sh', 'arg1 arg2 %s' % arg3], \
shell = True)
bash 腳本似乎沒有包含任何參數。非常感謝任何見解!
將參數作為列表傳遞,請參閱文檔中的第一個代碼示例:
import subprocess
subprocess.check_call(['/my/file/path/programname.sh', 'arg1', 'arg2', arg3])
如果arg3
不是字符串; 在傳遞給check_call()
之前將其轉換為字符串: arg3 = str(arg3)
。
subprocess.Popen(['/my/file/path/programname.sh arg1 arg2 %s' % arg3], shell = True).
如果您使用shell = True
腳本及其參數必須作為字符串傳遞。 args
序列中的任何其他元素都將被視為 shell 的參數。
您可以在http://docs.python.org/2/library/subprocess.html#subprocess.Popen找到完整的文檔。
再舉一個例子,上面所有的例子都沒有,
subprocess.Popen(['/your/script.sh %s %s %s' %(argument1,argument2,argument3)], shell = True)
請注意,當您鍵入%(argument1,argument2,argument3)
時, %
和(
之間不應有任何空格,例如% (argument1,argument2,argument3)
無效。
嗨,我知道這是解決方案很晚,但可以幫助某人。
例子:
import subprocess
pass_arg=[]
pass_arg[0]="/home/test.sh"
pass_arg[1]="arg1"
pass_arg[2]="arg2"
subprocess.check_call(pass_arg)
上面的示例將 arg1 和 arg2 作為參數提供給 shell 腳本 test.sh
本質上, subprocess 需要一個數組。 因此,您可以填充一個數組並將其作為參數提供。
您忘記添加args
名稱。
subprocess.Popen(args=['./test.sh', 'arg1 arg2 %s' % arg3], shell=True)
這就是它對我有用的方式
import subprocess
subprocess.Popen(["path/to/file.sh", arg1, arg2, arg3])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.