问题:如何为Popen指定工作目录

有没有一种方法可以在Python的目录中指定命令的运行目录subprocess.Popen()

例如:

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

我的Python脚本位于 C:\programs\python

是否可以C:\mytool\tool.exe在目录中运行D:\test\local

如何设置子流程的工作目录?

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?


回答 0

subprocess.Popen 接受一个cwd参数来设置当前工作目录;您还需要转义反斜杠('d:\\test\\local'),或使用,r'd:\test\local'以便Python不会将反斜杠解释为转义序列。按照您编写的方式,\t零件将被翻译为tab

因此,您的新行应如下所示:

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

要将Python脚本路径用作cwd,import os并使用以下命令定义cwd:

os.path.dirname(os.path.realpath(__file__)) 

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

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。