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
8,1124 gold badges57 silver badges112 bronze badges
asked Aug 19, 2015 at 3:17
2

4 Answers 4

13

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.

answered Aug 19, 2015 at 3:29
Sign up to request clarification or add additional context in comments.

Comments

7

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))
answered Aug 19, 2015 at 3:37

Comments

3

use subprocess to call your shell script

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

answered Aug 19, 2015 at 3:26

1 Comment

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.
-2
import os
def run():
 os.system('C:\\scrips\\mybash.bat')
run()
answered Aug 19, 2015 at 4:30

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.