简体   繁体   English

运行带有变量的 bash 命令作为 python 子进程

[英]Run a bash command with variables as a python subprocess

I have this shell command:我有这个shell命令:

$ docker run -it --env-file=.env -e "CONFIG=$(cat /path/to/your/config.json | jq -r tostring)" algolia/docsearch-scraper

And I want to run it as a python subprocess.我想将它作为 python 子进程运行。 I thought I'll only need an equivalent of the jq -r tostring , but if I use the config.json as a normal string the " don't get escaped. I also escaped them by using json.load(config.json). With the original jq command the " don't get escaped either and it's just returning the json string.我以为我只需要相当于jq -r tostring ,但是如果我将 config.json 用作普通字符串,则 " 不会被转义。我还使用 json.load(config.json) 转义了它们. 使用原始的 jq 命令, " 也不会被转义,它只是返回 json 字符串。

When I use the json returned as a string in python subprocess i get always a FileNotFoundError on the subprocess line.当我在 python 子进程中使用作为字符串返回的 json 时,我总是在子进程行上得到一个 FileNotFoundError。

@main.command()
def algolia_scrape():
    with open(f"{WORKING_DIR}/conf_dev.json") as conf:
        CONFIG = json.load(conf)
        subprocess.Popen(f'/usr/local/bin/docker -it --env-file={WORKING_DIR}/algolia.env -e "CONFIG={json.dumps(CONFIG)}" algolia/docsearch-scraper')

You get "file not found" because (without shell=True ) you are trying to run a command whose name is /usr/local/bin/docker -it ... when you want to run /usr/local/bin/docker with some arguments.你得到“找不到文件”是因为(没有shell=True )你试图运行一个名为/usr/local/bin/docker -it ...当你想运行/usr/local/bin/docker有一些论据。 And of course it would be pretty much a nightmare to try to pass the JSON through the shell because you need to escape any shell metacharacters from the string;当然,尝试通过 shell 传递 JSON 几乎是一场噩梦,因为您需要从字符串中转义任何 shell 元字符; but just break up the command string into a list of strings, like the shell would.但只需将命令字符串分解为字符串列表,就像 shell 那样。

def algolia_scrape():
    with open(f"{WORKING_DIR}/conf_dev.json") as conf:
        CONFIG = json.load(conf)
    p = subprocess.Popen(['/usr/local/bin/docker', '-it',
        f'--env-file={WORKING_DIR}/algolia.env',
        '-e', f'CONFIG={json.dumps(CONFIG)}',
        'algolia/docsearch-scraper'])

You generally want to save the result of subprocess.Popen() because you will need to wait for the process when it terminates.您通常希望保存subprocess.Popen()的结果,因为您将需要wait进程终止时。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM