gpt4 book ai didi

python - 从特定目录使用 Python 运行 cmd 命令

转载 作者:行者123 更新时间:2023-12-01 05:15:05 25 4
gpt4 key购买 nike

编写Python代码时,我可以编写os.system('some cmd command')。我怎样才能让它从特定目录运行(不使用“cd”命令)?

我尝试执行此操作的原因是因为我的 cmd 命令不在我的 cmd 路径中,因此只能在其自己的目录中识别。

我正在寻找类似的东西:

p = Popen ('file.bat', cwd = 'location')
stdout, stderr = p.communicate()

无需为其创建 .bat 文件...

最佳答案

你总是可以这样做:

p = Popen ('../relative/path/to/executable.exe')
stdout, stderr = p.communicate()

或者您可以在其中硬编码绝对路径,但请务必先检查文件是否存在或捕获 popen 调用引发的任何异常(更Pythonic)。

LE:请注意,Popen 的构造函数中有一个 cwd 参数,但执行的程序的当前目录将更改为该参数,它不会在中查找可执行文件那里。

关于python - 从特定目录使用 Python 运行 cmd 命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23396167/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com