The fastest way would be using os.chdir:
import os
if __name__ == "__main__":
print "Current dir: %s" % os.getcwd()
os.chdir('/tmp/')
print "Current dir: %s" % os.getcwd()
Which outputs when called:
Current dir: /home/borrajax/Documents/Tests/StackOverflow
Current dir: /tmp
Now, you mentioned that you want to call a particular script (nii-sdcme
) within your script. You are probably going to use subprocess.Popen to do that. With the tools provided by the subprocess module, you can specify a cwd
argument so the script (executable, rather) called "sees" that cwd
path as its run directory. Be aware that this sets the directory indicated in cwd
after the executable is called... what I mean by this is that Popen
needs to find the executable's path before setting the executable's run directory. Let's say you're in your /home/
and the nii-sdcme
script is located in /tmp/
.
This:
subprocess.Popen(['nii-sdcme'], cwd='/tmp/')
will fail, because the executable is not in the directories defined in the $PATH
environment variable. On the other hand, this:
subprocess.Popen(['/tmp/nii-sdcme'], cwd='/tmp/')
will succeed.
From the subrprocess.Popen docs:
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.
EDIT (As per OP's comment to this question)
how about if i change os.chdir(desired/path) and then cann
subprocess.call('nii_sdcme %s' %a)
That'll make nii_sdcme
use desired/path
as run directory as well. os.chdir
changes the path of the current process (your current interpreter). If you subsequently call your nii_sdcme
executable without specifying a cwd
argument, the spawned subprocess will use as current directory the current directory of the parent process.
(!) Careful: Even if you change the current directory of your executable through os.chdir
, you still need to provide the full path to your nii_sdcme
executable (unless nii_sdcme
is in one of the directories specified in the $PATH
environment variable)