This question already has an answer here:
- Specify working directory for popen 1 answer
I have a python script that is under this directory:
work/project/test/a.py
Inside a.py
, I use subprocess.POPEN
to launch the process from another directory,
work/to_launch/file1.pl, file2.py, file3.py, ...
Python Code:
subprocess.POPEN("usr/bin/perl ../to_launch/file1.pl")
and under work/project/, I type the following
[user@machine project]python test/a.py,
error "file2.py, 'No such file or directory'"
How can I add work/to_launch/
, so that these dependent files file2.py
can be found?
You could use this code to set the current directory:
Use paths relative to the script, not the current working directory
See also my answer to Python: get path to file in sister directory?
Your code does not work, because the relative path is seen relatively to your current location (one level above the
test/a.py
).In
sys.path[0]
you have the path of your currently running script.Use
os.path.join(os.path.abspath(sys.path[0]), relPathToLaunch)
withrelPathToLaunch = '../to_launch/file1.pl'
to get the absolute path to yourfile1.pl
and runperl
with it.EDIT: if you want to launch file1.pl from its directory and then return back, just remember your current working directory and then switch back: