python - 如何为 popen 指定工作目录

有没有办法在Python的subprocess.Popen()中指定命令的运行目录?

例如:

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

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

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

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

最佳答案

subprocess.Popen takes a cwd argument设置当前工作目录;您还需要转义反斜杠 ('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__)) 

https://stackoverflow.com/questions/1685157/

相关文章:

windows - 如何让 Windows 在编译 C++ 时与 Linux 一样快?

linux - 如何在没有密码的情况下以另一个用户身份运行脚本?

python - 如何在 Python 中将字符串转换为 utf-8

linux - 如何在不覆盖 TTY 的情况下将密码传递给 su/sudo/ssh?

python - 如何用下划线替换空格?

linux - 在 Ubuntu 中轻松更改 $JAVA_HOME

linux - 如何在 Apache 服务器上自动将 HTTP 重定向到 HTTPS?

linux - 如何打印 ld(linker) 搜索路径

python - Argparse:在 "optional arguments"下列出的必需参数?

python - matplotlib 错误 - 没有名为 tkinter 的模块