首页 > 解决方案 > 使用 python3 subprocess.run() 未检测到 Asciidoctor-pdf 属性

问题描述

在我们部门,我们将文档格式切换为 Asciidoc(tor)。出于自动化目的,我们希望使用从 .yml 文件中读取的属性/变量。

尝试子处理此属性时会出现问题。使用外壳,效果很好。

asciidoctor-pdf -a ui_host=10.10.10.10 -a ui_port=10 -a ext_host=10.11.11.11 -a ext_port=11 userman_asciidoc.adoc

将variables.yml解析为 python3 脚本,格式化它们并将它们作为解包列表附加到subprocess.run()调用将返回有效的 asciidoc-pdf。但是不包括属性。

我相信这是一个子流程问题,我做错了什么。那么,subprocess.run() 如何生成与写入命令行完全相同的输出?


variables.yml:_

ui_host: 10.10.10.10
ui_port: 10
ext_host: 10.11.11.11
ext_port: 11

asciidoc_build.py:_

import yaml
import subprocess
import argparse

parser = argparse.ArgumentParser(description="This Script builds the Asciidoc usermanual for TASTE-OS as a pdf. It can take variables as input, which yould be stored in a .yml file")
parser.add_argument("adoc_file", help="Path to the usermanual as Asciidoc (.adoc) file")
parser.add_argument("yaml_file", help="The path to the yaml file, which contains all needed variables for the TASTE-OS usermanual")

args = parser.parse_args()

with open(args.yaml_file, "r") as f:
    try:
        yaml_content = yaml.load(f)
    except yaml.YAMLError as exc:
        print(exc)

yaml_variables = []
for key, value in yaml_content.items():
    print(key, value)
    yaml_variables.append("-a " + key + "=" + str(value))

subprocess.run(["asciidoctor-pdf", *yaml_variables, args.adoc_file])

标签: pythonpython-3.xsubprocessasciidoctorasciidoctor-pdf

解决方案


参数和实际值需要在-a提供给子流程的列表中分开。

for key, value in yaml_content.items():
    print(key, value)
    yaml_variables.append("-a")
    yaml_variables.append(key + "=" + str(value))

前: [-a ui_host=10.10.10.10, -a ui_port=10, ...]

后: [-a, ui_host=10.10.10.10, -a, ui_port=10, ...]


推荐阅读