如何避免shell = True在子过程中 [英] how to avoid shell=True in subprocess

查看:105
本文介绍了如何避免shell = True在子过程中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有子过程命令将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)

文档:

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.

这篇关于如何避免shell = True在子过程中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆