Pass a variable from python to shell script
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.
use subprocess to call your shell script
subprocess.Popen(['run.sh %s %s' % (var1, var2)], shell = True).
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))