Specify working directory for popen

2019-01-04 22:47发布

Is there a way to specify the running directory of command in Python's subprocess.Popen()?

For example:

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

My Python script is located in C:\programs\python

Is is possible to run C:\mytool\tool.exe in the directory D:\test\local?

How do I set the working directory for a sub-process?

1条回答
smile是对你的礼貌
2楼-- · 2019-01-04 23:09

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

To use your Python script path as cwd, import os and define cwd using this:

os.path.dirname(os.path.realpath(__file__)) 
查看更多
登录 后发表回答