Harry Boy
Harry Boy

Reputation: 4777

How to pass a value to shell script from subprocess.Popen in Python

I have the following:

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"

The output is:

Hello From Shell Script 1
Hello From Shell Script 2
Hello From Shell Script 3

I want to do this in a for loop like so:

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

But the output is:

Hello From Shell Script
Hello From Shell Script
Hello From Shell Script

If I drop the shell=True so its now:

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

I get the following:

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

How can I get this to pass in the correct value to the script?

Upvotes: 0

Views: 462

Answers (2)

chepner
chepner

Reputation: 532368

Don't use shell=True if you are passing a list instead of a string as the first argument.

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

Upvotes: 1

Rolf of Saxony
Rolf of Saxony

Reputation: 22448

Change it to read as follows:

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

Upvotes: 1

Related Questions