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


基础教程推荐
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- 包装空间模型 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- 求两个直方图的卷积 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01