Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass a variable from python to shell script

Tags:

python

bash

shell

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.

like image 719
The Nightman Avatar asked Aug 19 '15 03:08

The Nightman


1 Answers

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.

like image 60
Austin A Avatar answered Oct 12 '22 00:10

Austin A