Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I run a bash script inside Python, but act as if it's running from another directory?

subprocess.call(["/home/blah/trunk/blah/run.sh", "/tmp/ad_xml", "/tmp/video_xml"])

I do this. However, inside my run.sh, I have "relative" paths. So, I have to "cd" into that directory, and then run the shell script. How do I do that?

like image 202
TIMEX Avatar asked Jan 29 '11 02:01

TIMEX


People also ask

How do I change directory in a bash script?

To change directories, use the command cd followed by the name of the directory (e.g. cd downloads ). Then, you can print your current working directory again to check the new path.

Can you call a bash script from Python?

We can also execute an existing a bash script using Python subprocess module.


2 Answers

Use the cwd argument to subprocess.call()

From the docs here: http://docs.python.org/library/subprocess.html

If cwd is not None, the child’s current directory will be changed to cwd before it is executed. Note that this directory is not considered when searching the executable, so you can’t specify the program’s path relative to cwd.

Example:

subprocess.call(["/home/blah/trunk/blah/run.sh", "/tmp/ad_xml", "/tmp/video_xml"], cwd='/tmp')
like image 111
payne Avatar answered Sep 28 '22 00:09

payne


Well, you could use subprocess.Popen with Shell = True and cwd = "Your desired working directory"

EDIT: It appears that call has the same arguments so just setting a cwd argument would work:

subprocess.call(["/home/blah/trunk/blah/run.sh", "/tmp/ad_xml", "/tmp/video_xml"], cwd="PATH")
like image 38
AlexJF Avatar answered Sep 27 '22 22:09

AlexJF