如何为 popen 指定工作目录

2023-07-22Python开发问题
49

本文介绍了如何为 popen 指定工作目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

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

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

例如:

Popen('c:mytool	ool.exe', workingdir='d:	estlocal')

我的 Python 脚本位于 C:programspython

My Python script is located in C:programspython

是否可以在D: estlocal目录下运行C:mytool ool.exe?

Is is possible to run C:mytool ool.exe in the directory D: estlocal?

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

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

推荐答案

subprocess.Popen 采用 cwd 参数 来设置当前工作目录;您还需要转义反斜杠 ('d:\test\local'),或使用 r'd: estlocal' 以便Python 不会将反斜杠解释为转义序列.按照您编写的方式, 部分将被转换为 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: estlocal' so that the backslashes aren't interpreted as escape sequences by Python. The way you have it written, the part will be translated to a tab.

所以,你的新行应该是这样的:

So, your new line should look like:

subprocess.Popen(r'c:mytool	ool.exe', cwd=r'd:	estlocal')

<小时>

要将 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 指定工作目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

在xarray中按单个维度的多个坐标分组
groupby multiple coords along a single dimension in xarray(在xarray中按单个维度的多个坐标分组)...
2024-08-22 Python开发问题
15

Pandas中的GROUP BY AND SUM不丢失列
Group by and Sum in Pandas without losing columns(Pandas中的GROUP BY AND SUM不丢失列)...
2024-08-22 Python开发问题
17

pandas 有从特定日期开始的按月分组的方式吗?
Is there a way of group by month in Pandas starting at specific day number?( pandas 有从特定日期开始的按月分组的方式吗?)...
2024-08-22 Python开发问题
10

GROUP BY+新列+基于条件的前一行抓取值
Group by + New Column + Grab value former row based on conditionals(GROUP BY+新列+基于条件的前一行抓取值)...
2024-08-22 Python开发问题
18

PANDA中的Groupby算法和插值算法
Groupby and interpolate in Pandas(PANDA中的Groupby算法和插值算法)...
2024-08-22 Python开发问题
11

PANAS-基于列对行进行分组,并将NaN替换为非空值
Pandas - Group Rows based on a column and replace NaN with non-null values(PANAS-基于列对行进行分组,并将NaN替换为非空值)...
2024-08-22 Python开发问题
10