如何指定Popen的工作目录 [英] How can I specify working directory for popen
问题描述
是否可以在Python的subprocess.Popen()
中指定命令的运行目录?
Is there a way to specify the running directory of command in Python's subprocess.Popen()
?
例如:
Popen('c:\mytool\tool.exe', workingdir='d:\test\local')
我的Python脚本位于C:\programs\python
My Python script is located in C:\programs\python
是否可以在目录D:\test\local
中运行C:\mytool\tool.exe
?
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?
推荐答案
subprocess.Popen
使用cwd
参数设置当前工作目录;您还需要转义反斜杠('d:\\test\\local'
),或使用r'd:\test\local'
,以便Python不会将反斜杠解释为转义序列.编写方式上,\t
部分将转换为 tab .
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')
要将您的Python脚本路径用作cwd,请import os
并使用以下命令定义cwd:
To use your Python script path as cwd, import os
and define cwd using this:
os.path.dirname(os.path.realpath(__file__))
这篇关于如何指定Popen的工作目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!