简体   繁体   English

subprocess.Popen() 不会运行 python 脚本,找不到 python 命令

[英]subprocess.Popen() won't run python script, python command not found

I'm trying to get subprocess.Popen to run a python script but I keep getting the following error: /bin/sh: python: command not found .我正在尝试让 subprocess.Popen 运行 python 脚本,但我不断收到以下错误: /bin/sh: python: command not found The script takes a yaml file as an argument.该脚本将 yaml 文件作为参数。 I've tried this line both with and without shell=True .我在有和没有shell=True的情况下都试过这条线。 The script runs fine when I run it with the python command in my Linux terminal.当我在 Linux 终端中使用 python 命令运行该脚本时,该脚本运行良好。 What am I doing wrong?我究竟做错了什么?

    process = subprocess.Popen(
        ['python', PATH_TO_PYTHON_SCRIPT, PATH_TO_CONFIG_FILE],
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT, stdin=subprocess.PIPE, shell=True)
    with process.stdout, open(processing_log, 'ab') as f_in:
        for line in iter(process.stdout.readline, b''):
            f_in.write(line)

If you want to run with the same interpreter you're currently running in, I'd suggest passing sys.executable rather than 'python' so you're not dependent on the vagaries of PATH lookup;如果您想使用当前正在运行的同一个解释器运行,我建议您传递sys.executable而不是'python' ,这样您就不会依赖于PATH查找的变幻莫测; if you want to look it up from the PATH , you might try using shutil.which to look it up at the Python layer to minimize the number of things in the way.如果您想从PATH中查找它,您可以尝试使用shutil.which在 Python 层中查找它,以最大限度地减少阻碍的数量。

Side-note: Why are you running this with shell=True ?旁注:你为什么用shell=True运行这个? That adds a number of complicating factors that you should probably avoid, and you're not taking advantage of the tiny benefits it provides anyway.这增加了许多您可能应该避免的复杂因素,而且您无论如何都没有利用它提供的微小好处。

Additionally, if all you want to do is append the output to a given file, you can always just do:此外,如果您想要做的只是 append 和 output 到给定文件,您总是可以这样做:

with open(processing_log, 'ab') as f_out:
    process = subprocess.Popen(
        ['python', PATH_TO_PYTHON_SCRIPT, PATH_TO_CONFIG_FILE],
        stdout=f_out,
        stderr=subprocess.STDOUT, stdin=subprocess.PIPE)

and let the process write to the file directly instead of acting as a passthrough layer.并让进程直接写入文件,而不是充当传递层。

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

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