如何使用 python 在指定目录中执行终端命令?

How to execute a terminal command within a specified directory using python?

我知道我可以使用 os 模块在终端中从 python 脚本中使用类似以下内容的操作:

import os

os.system("python execute_code.py")

但这限制了我要么专门从我的 python 所在的目录编写代码,要么编写使用文件的完整路径对文件进行操作的代码。有没有办法进入目录并从这些目录执行命令。

比如我现在的做法是:

exe_path = "/path/to/file"

os.system("python modifyFile.py " + exe_path + file)

我怎么能去:

# move to directory
os.system("python modifyFile.py " + file)

使用脚本的完整路径名。

os.system(f"python '{exe_path}/modifyFile.py'")

或使用cd命令

os.system(f"cd '{exe_path}' && python modifyFile.py")

&& 使其在 cd 失败时跳过 python 命令。