如何在 subprocess.run 中为参数 cwd 创建路径

How to create a path for the argument cwd in subprocess.run

我有以下路径:

airflow_home = os.path.join("opt", "airflow")
airflow_docs = os.path.join(airflow_home, "docs")

并且我希望在 bash 命令中使用 airflow_docs 路径。为此,我使用了以下代码:

subprocess.run([f"sphinx-apidoc -o ./ ../plugins"],
                       shell=True,
                       cwd=airflow_docs)

我得到一个错误 FileNotFoundError

但是,这确实有效:

subprocess.run([f"sphinx-apidoc -o ./ ../{doc_module}"],
                       shell=True,
                       cwd="/opt/airflow/docs")

看来是缺少前导斜杠导致了这个问题。我在 google 中搜索过有关向路径添加前导斜杠的信息,但没有成功。那么,是否可以为 subprocess.run 使用 os.path 包,还是我必须使用硬编码字符串?

如果你想要一个斜线,就放一个斜线。

airflow_home = os.path.join("/opt", "airflow")

当然,Python 将字符串粘在一起并不是很有用。事实上,os.path.join 的结果只是一个字符串,相当于一个硬编码的字符串。所以直接写出来:

airflow_home = "/opt/airflow"

或者如果您想在 Python 中执行此操作,也许更喜欢 pathlib:

airflow_home = pathlib.Path("/opt") / "airflow"

顺便说一句,您的 subprocess 代码已损坏;您想要传递带有 shell=True 的字符串或不带 shell=True 的标记列表。 (Windows“有用地”隐藏了这个错误,但它仍然是错误的。)

subprocess.run(
    ["sphinx-apidoc", "-o", "./", "../plugins"],
    cwd=airflow_docs)

subprocess 方便地允许您传入一个 pathlib.Path 对象作为 cwd 的值,但如果您需要支持旧版本,情况可能并非总是如此Python.

您可能想要添加 check=True 以使 Python 在子进程失败时引发错误。或许还可以参见 Running Bash commands in Python