0

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?

2
  • Since you are passing list of arguments, simply drop shell=True keyword argument. Commented Feb 9, 2016 at 15:20
  • See my edit @Rogalski Commented Feb 9, 2016 at 15:25

2 Answers 2

1

Change it to read as follows:

>>> for num in range(1,3):
...     subprocess.Popen(['./hello.sh '+str(num)], shell=True)
Sign up to request clarification or add additional context in comments.

2 Comments

There's no reason to pass a list to Popen if it only contains one string.
@chepner Is it a list?
1

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)])

3 Comments

Isn't shell=True required for "./hello.sh"?
Not necessarily. If the script is executable, execve will execute the script with /bin/sh (or whatever its shebang specifies). Specifying shell=True is just a shortcut for ["/bin/sh", "-c"] + arglist. (Where arglist is either the list you pass, or a single-element list containing the string you passed.)
I'd say just "Don't use shell=True". Period.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.