如何为子进程指定工作目录
有没有办法在Python的subprocess.Popen()
中指定命令的运行目录?
例如:
Popen('c:\mytool\tool.exe', workingdir='d:\test\local')
我的Python脚本位于C:\programs\python
可以在D:目录中运行
?C:\mytool\tool.exe
\测试\本地
如何设置子进程的工作目录?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
subprocess.Popen
采用cwd
参数 设置当前工作目录;您还需要转义反斜杠 ('d:\\test\\local'
),或使用r'd:\test\local'
以便Python 不会将反斜杠解释为转义序列。按照您编写的方式,\t
部分将被转换为 tab。因此,您的新行应如下所示:
要使用 Python 脚本路径作为 cwd,请导入 os 并使用以下命令定义 cwd:
subprocess.Popen
takes acwd
argument to set the Current Working Directory; you'll also want to escape your backslashes ('d:\\test\\local'
), or user'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:
To use your Python script path as cwd,
import os
and define cwd using this:其他方法就是简单地执行此
操作。如果您想依赖相对路径,例如,如果您的工具的位置是
c:\some\directory\tool.exe
,则此解决方案有效。Popen
的cwd
关键字参数不会让您执行此操作。某些脚本/工具可能依赖于您在调用它们时位于给定目录中。为了使此代码噪音更少,也称为将与更改目录相关的逻辑与“业务逻辑”分离,您可以使用装饰器。这样的装饰器可以这样使用:
Other way is to simply do this
This solution works if you want to rely on relative paths, for example, if your tool's location is
c:\some\directory\tool.exe
.cwd
keyword argument forPopen
will not let you do this. Some scripts/tools may rely on you being in the given directory while invoking them. To make this code less noisy, aka detach the logic related to changing directories from the "business logic", you can use a decorator.Such decorator can be then used in a way: