7

I am trying to run a shell script from a python script using the following:

from subprocess import call
call(['bash run.sh'])

This gives me an error, but I can successfully run other commands like:

call(['ls'])
The Nightman
  • 5,609
  • 13
  • 41
  • 74
  • 2
    possible duplicate of [Calling an external command in Python](http://stackoverflow.com/questions/89228/calling-an-external-command-in-python) – kenorb Aug 18 '15 at 23:24

3 Answers3

12

You should separate arguments:

call(['bash', 'run.sh'])
call(['ls','-l'])
Assem
  • 11,574
  • 5
  • 59
  • 97
5
from subprocess import call
import shlex
call(shlex.split('bash run.sh'))

You want to properly tokenize your command arguments. shlex.split() will do that for you.

Source: https://docs.python.org/2/library/subprocess.html#popen-constructor

Note shlex.split() can be useful when determining the correct tokenization for args, especially in complex cases:

Joe Young
  • 5,749
  • 3
  • 28
  • 27
3

When you call call() with a list, it expects every element of that list to correspond to a command line argument. In this case it is looking for bash run.sh as the executable with spaces and everything as a single string.

Try one of these:

call("bash run.sh".split())
call(["bash", "run.sh"])
ntki
  • 2,149
  • 1
  • 16
  • 19