我有以下内容:
myscript.py
#!/usr/bin/python
from threading import Thread
import time
import subprocess
subprocess.Popen("./hello.sh 1", shell=True)
subprocess.Popen("./hello.sh 2", shell=True)
subprocess.Popen("./hello.sh 3", shell=True)
hello.sh
echo "Hello From Shell Script $1"
输出为:
Hello From Shell Script 1
Hello From Shell Script 2
Hello From Shell Script 3
我想在for循环中这样做:
for num in range(1,3):
subprocess.Popen(['./hello.sh', str(num)], shell=True)
但输出是:
Hello From Shell Script
Hello From Shell Script
Hello From Shell Script
如果我将 shell = True 放到现在:
subprocess.Popen(['./hello.sh', str(num)])
我得到以下内容:
Traceback (most recent call last):
File "./myscript.py", line 12, in <module>
subprocess.Popen(['./hello.sh', str(num)])
File "/usr/lib64/python2.6/subprocess.py", line 623, in __init__
errread, errwrite)
File "/usr/lib64/python2.6/subprocess.py", line 1141, in _execute_child
raise child_exception
OSError: [Errno 8] Exec format error
如何让它将正确的值传递给脚本?
答案 0 :(得分:1)
将其更改为如下所示:
>>> for num in range(1,3):
... subprocess.Popen(['./hello.sh '+str(num)], shell=True)
答案 1 :(得分:1)
如果要传递列表而不是字符串作为第一个参数,请不要使用shell=True
。
subprocess.Popen(['./hello.sh', str(num)])