如何在子进程中避免shell = True

use*_*518 3 python shell subprocess popen

我有子进程命令来检查md5校验和为

subprocess.check_output('md5 Downloads/test.txt', stderr=subprocess.STDOUT, shell=True)
Run Code Online (Sandbox Code Playgroud)

它工作正常.但是我试着避免,shell=True 但是当我跑的时候

subprocess.check_output('md5 Downloads/test.txt', stderr=subprocess.STDOUT, shell=False)
Run Code Online (Sandbox Code Playgroud)

我收到错误 OSError: [Errno 2] No such file or directory

我可以运行上面的命令或解决方法,shell=False或者可以保留shell=True吗?

Eug*_*ash 8

只需将参数传递check_output()列表:

subprocess.check_output(["md5", "Downloads/test.txt"], stderr=subprocess.STDOUT)
Run Code Online (Sandbox Code Playgroud)

来自文档:

所有调用都需要args,并且应该是一个字符串或一系列程序参数.通常优选提供参数序列,因为它允许模块处理任何所需的转义和引用参数(例如,允许文件名中的空格).如果传递单个字符串,则必须是shellTrue(参见下文),否则字符串必须简单地命名要执行的程序而不指定任何参数.