执行 subprocess.run() 时出现 FileNotFound 错误

FileNotFound error when executing subprocess.run()

我想 运行 python 中的命令使用 subprocess.run 我想切换工作目录只是为了执行这个命令。 另外,我需要记录输出和 return 代码。

这是我的代码:

import subprocess

result = subprocess.run("echo \"blah\"", cwd=directory, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

但这只是 returns

FileNotFoundError: [Errno 2] No such file or directory: 'echo "Running ls -la" && ls -la'

我还尝试使用以下参数:

subprocess.run(["echo", "\"blah\""], cwd=directory, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

正如 Jean-François Fabre 所说,解决方案是在调用中添加“shell=True”

import subprocess
result = subprocess.run("echo \"blah\"", cwd=directory, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)

shell=True 似乎告诉子进程使用字符串作为命令。