10

I am running a shell script from inside a python script like this:

call(['bash', 'run.sh'])

And I want to pass run.sh a couple of variables from inside of the python script. It looks like I can just append variables, something like so:

call(['bash', 'run.sh', 'var1', 'var2'])

and then access them in my shell script with $1 and $2. But I can't get this to work.

zabop
  • 6,750
  • 3
  • 39
  • 84
The Nightman
  • 5,609
  • 13
  • 41
  • 74

4 Answers4

12

There are two built-in python modules you can use for this. One is os and the other is subprocess. Even though it looks like you're using subprocess, I'll show both.

Here's the example bash script that I'm using for this.

test.sh

echo $1
echo $2

Using subprocess

>>> import subprocess
>>> subprocess.call(['bash','test.sh','foo','bar'])
foo
bar

This should be working, can you show us the error or output that you're currently getting.


Using os

>>> import os
>>> os.system('bash test.sh foo bar')
foo
bar
0

Note the exit status that os prints after each call.

Austin A
  • 2,990
  • 6
  • 27
  • 42
6

If call(['bash', 'run.sh']) is working without arguments, there is no reason why it shouldn't work when additional arguments are passed.

You need to substitute the values of the variables into the command line arguments, not just pass the names of the variables as strings as does this:

call(['bash', 'run.sh', 'var1', 'var2'])

Instead, do this:

var1 = '1'
var2 = '2'
call(['bash', 'run.sh', var1, var2])

Now this will work providing that var1 and var2 are strings. If not, you need to convert them to strings:

var1 = 1
var2 = 2
call(['bash', 'run.sh', str(var1), str(var2)])

Or you can use shlex.split():

cmd = 'bash run.sh {} {}'.format(var1, var2)
call(shlex.split(cmd))
mhawke
  • 84,695
  • 9
  • 117
  • 138
3

use subprocess to call your shell script

subprocess.Popen(['run.sh %s %s' % (var1, var2)], shell = True).

Achayan
  • 5,720
  • 2
  • 39
  • 61
  • 1
    This won't work as expected if `var1` contains whitespace or one of several other shell metacharacters. There is rarely a good reason to use the single-string argument to `Popen` in place of a list. – chepner Aug 19 '15 at 03:39
-1
import os
def run():
    os.system('C:\\scrips\\mybash.bat')
run()
Denis
  • 390
  • 3
  • 14