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.
-
1What do you mean you cannot get it to work? What else are you getting ?Anand S Kumar– Anand S Kumar2015年08月19日 03:28:00 +00:00Commented Aug 19, 2015 at 3:28
-
Possible duplicate of How to pass variables from python script to bash scriptjww– jww2018年09月23日 00:32:59 +00:00Commented Sep 23, 2018 at 0:32
4 Answers 4
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.
Comments
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))
Comments
use subprocess to call your shell script
subprocess.Popen(['run.sh %s %s' % (var1, var2)], shell = True).
1 Comment
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.import os
def run():
os.system('C:\\scrips\\mybash.bat')
run()