views:

237

answers:

2

hi all,

I there a way to specify the running directory of command in subprocess.Popen()

like

Popen('c:\mytool\tool.exe',workingdir='d:\test\local')

and my python script locates in c:\programs\python.

IS there possible i can run c:\mytool\tool.exe in 'd:\test\local' ? it seems c:\mytool\tool.exe runs in my c:\programs\python as working directory.

Thanks a lot

+4  A: 

subprocess.Popen takes a cwd argument to set the Current Working Directory; you'll also want to escape your backslashes ('d:\\test\\local'), or use r'd:\test\local' so that the backslashes aren't interpreted as escape sequences by Python. The way you have it written, the \t part will be translated to a tab.

So, your new line should look like:

subprocess.Popen(r'c:\mytool\tool.exe', cwd=r'd:\test\local')
Mark Rushakoff
What effect, if any, would adding Shell=True to the arguments have on also setting the cwd?
T. Stone
@T. Stone: For a standalone executable, it shouldn't change anything, unless the exe depends on some environment variables in the shell, maybe. But, with `shell=False`, you can't use a shell builtin such as `cd`: i.e., try this on Linux with shell both ways: `subprocess.Popen("cd /tmp; pwd")`
Mark Rushakoff
thanks a lot! it works like a charm!
xlione
+2  A: 

What you want is os.chdir(). Check out this example:

import os

f=os.popen('./checkfile.sh')
data=f.read()
f.close()
print data

os.chdir('../')
f=os.popen('tmpdir/checkfile.sh')
data=f.read()
f.close()
print data

And here's the contents of checkfile.sh:

#!/bin/bash

if [ -e testfile.txt ]
then
    echo "Yep"
else
    echo "Nope"
fi
AJ
He's using `subprocess.Popen` which includes a parameter for this, so your answer isn't quite elegant, but because it's correct you have +1 from me. Also, a link to the `os.chdir` documentation would have been nice.
Cristian Ciupitu