如何从 Python 中的 subprocess.Popen 向 shell 脚本传递值
How to pass a value to shell script from subprocess.Popen in Python
我有以下内容:
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 "
输出为:
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
如何才能将正确的值传递给脚本?
改成如下:
>>> for num in range(1,3):
... subprocess.Popen(['./hello.sh '+str(num)], shell=True)
如果您传递的是列表而不是字符串作为第一个参数,请不要使用 shell=True
。
subprocess.Popen(['./hello.sh', str(num)])
我有以下内容:
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 "
输出为:
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
如何才能将正确的值传递给脚本?
改成如下:
>>> for num in range(1,3):
... subprocess.Popen(['./hello.sh '+str(num)], shell=True)
如果您传递的是列表而不是字符串作为第一个参数,请不要使用 shell=True
。
subprocess.Popen(['./hello.sh', str(num)])