2

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.

2 Answers 2

3

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.)

Sign up to request clarification or add additional context in comments.

4 Comments

OPs question included: "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" your answer does exactly what they did not wish to do!
@SteveBarnes: I read that to mean "an argument to the script". This is the proper way of doing it in Python.
you could use ["./task.sh", arg1] the path is relative to cwd
@J.F.Sebastian: right. I figured that would require shell=True, but it doesn't.
0

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)

3 Comments

For reliability you should add some try: except control in so as to ensure that the directory and script both exist.
Remove test.sh from chdir(), otherwise the call will fail.
This is unreliable; an exception will change the directory permanently. It's also unnecessarily complicated.

Your Answer

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.