user2510173
user2510173

Reputation: 611

Running a subprocess bash script from Python in the scripts current directory

I'm looking to run a bash script in a subdirectory from a python script. This bash script should perform all its actions as if it is in its current directory. Is there any way to do this aside from passing in the directory as an argument and using it to direct all of the calls?

Basically, something along the lines of

for i in range(1,100):
     subprocess.call(['/some%s/task.sh' % i, arg1])

where the contents of the script work with the files inside of that some%s directory.

Upvotes: 2

Views: 2365

Answers (2)

Fred Foo
Fred Foo

Reputation: 363567

subprocess.call has the cwd keyword argument for this:

for i in xrange(1, 100):
    subprocess.call(["./task.sh", arg1], cwd=("/some%d" % i))

(This is documented only implicitly: "The full function signature is the same as that of the Popen constructor - this functions passes all supplied arguments directly through to that interface." cwd is listed at Popen.)

Upvotes: 3

Steve Barnes
Steve Barnes

Reputation: 28370

Yep,

Just before your loop programitically save the current working directory and change the current working directory to /some%s before the subprocess.call and then set it back to the original value when you are done.

import os
Orig = os.path.abspath('.')
for i in range(1,100):
    os.chdir('/some%s' % i)
    subprocess.call(['./task.sh' % i, arg1])
os.chdir(Orig)

Upvotes: 0

Related Questions