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

2022-01-18 00:00:00 python shell subprocess popen

问题描述

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

I have subprocess command to check md5 checksum as

subprocess.check_output('md5 Downloads/test.txt', stderr=subprocess.STDOUT, shell=True)

它工作正常.但我读了尽量避免 shell=True但是当我运行时

It works fine. But I read try to avoid shell=True but when I run

subprocess.check_output('md5 Downloads/test.txt', stderr=subprocess.STDOUT, shell=False)

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

我可以使用 shell=False 运行上述命令或解决方法,还是可以保留 shell=True?

Can I run above command or workaround with shell=False or it's ok to keep shell=True?


解决方案

只需将参数作为 list 传递给 check_output():

Just pass the arguments to check_output() as a list:

subprocess.check_output(["md5", "Downloads/test.txt"], stderr=subprocess.STDOUT)

来自 docs:

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

args is required for all calls and should be a string, or a sequence of program arguments. Providing a sequence of arguments is generally preferred, as it allows the module to take care of any required escaping and quoting of arguments (e.g. to permit spaces in file names). If passing a single string, either shell must be True (see below) or else the string must simply name the program to be executed without specifying any arguments.

相关文章