Python: subprocess with different working directory [duplicate]

梦想的初衷 提交于 2019-11-28 02:43:59

问题


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?


回答1:


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) with relPathToLaunch = '../to_launch/file1.pl' to get the absolute path to your file1.pl and run perl 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:

origWD = os.getcwd() # remember our original working directory

os.chdir(os.path.join(os.path.abspath(sys.path[0]), relPathToLaunch))
subprocess.POPEN("usr/bin/perl ./file1.pl") 
[...]

os.chdir(origWD) # get back to our original working directory



回答2:


Use paths relative to the script, not the current working directory

os.path.join(os.path.dirname(__file__), '../../to_launch/file1.pl)

See also my answer to Python: get path to file in sister directory?




回答3:


You could use this code to set the current directory:

import os
os.chdir("/path/to/your/files")


来源:https://stackoverflow.com/questions/3762468/python-subprocess-with-different-working-directory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!