簡體   English   中英

如何在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)

你好

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

如何獲得此值以將正確的值傳遞給腳本?

將其更改為如下:

>>> for num in range(1,3):
...     subprocess.Popen(['./hello.sh '+str(num)], shell=True)

如果要傳遞列表而不是字符串作為第一個參數,請不要使用shell=True

subprocess.Popen(['./hello.sh', str(num)])

暫無
暫無

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

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