how to avoid shell=True in subprocess(如何在子进程中避免 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)
来自 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.
这篇关于如何在子进程中避免 shell=True的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在子进程中避免 shell=True


基础教程推荐
- Python,确定字符串是否应转换为 Int 或 Float 2022-01-01
- kivy 应用程序中的一个简单网页作为小部件 2022-01-01
- Kivy 使用 opencv.调整图像大小 2022-01-01
- Python 中是否有任何支持将长字符串转储为块文字或折叠块的 yaml 库? 2022-01-01
- matplotlib 设置 yaxis 标签大小 2022-01-01
- 对多索引数据帧的列进行排序 2022-01-01
- 比较两个文本文件以找出差异并将它们输出到新的文本文件 2022-01-01
- 在 Django Admin 中使用内联 OneToOneField 2022-01-01
- 在 Python 中将货币解析为数字 2022-01-01
- 究竟什么是“容器"?在蟒蛇?(以及所有的 python 容器类型是什么?) 2022-01-01