尝试使用子进程执行 运行 命令时出错

Error while trying to run command with subprocess

我正在尝试 运行 使用 python 库子进程的控制台命令。 这是我得到的:

Python 3.8.3 (tags/v3.8.3:6f8c832, May 13 2020, 22:37:02) [MSC v.1924 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import subprocess
>>> import os
>>> os.system("echo Hello, World!")
Hello, World!
0
>>> subprocess.run(["echo", "Hello, World!"])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\trolo\AppData\Local\Programs\Python\Python38\lib\subprocess.py", line 489, in run
    with Popen(*popenargs, **kwargs) as process:
  File "C:\Users\trolo\AppData\Local\Programs\Python\Python38\lib\subprocess.py", line 854, in __init__
    self._execute_child(args, executable, preexec_fn, close_fds,
  File "C:\Users\trolo\AppData\Local\Programs\Python\Python38\lib\subprocess.py", line 1307, in _execute_child
    hp, ht, pid, tid = _winapi.CreateProcess(executable, args,
FileNotFoundError: [WinError 2] The system cannot find the file specified

FileNotFoundError表示subprocess.run参数列表中的第一个参数不存在(在这种情况下,'echo'不存在)。

echo 是一个 shell 命令(不是可执行文件)并且根据 python documentation:

Unlike some other popen functions, this implementation will never implicitly call a system shell.

要解决此问题,请添加 shell=True 参数:

subprocess.run(["echo", "Hello, World!"], shell=True)

编辑:如评论中所述,显然非Windows系统要求所有参数都是单个字符串:

subprocess.run(["echo Hello, World!"], shell=True)

subprocess.run("echo Hello, World!", shell=True)

要运行一个像echo这样的shell命令,你需要shell=True;然后第一个参数应该只是一个字符串,而不是字符串列表。

subprocess.run('echo "Hello world!"', shell=True)