”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > 如何在 Python 的 `os.system()` 调用中正确转义命令参数?

如何在 Python 的 `os.system()` 调用中正确转义命令参数?

发布于2024-11-02
浏览:437

How to Properly Escape Command Arguments in Python\'s `os.system()` Calls?

转义 os.system() 调用中的命令参数

在 Python 中使用 os.system() 时,确保正确的参数处理是至关重要的。文件和其他参数通常需要转义以防止干扰 shell 的命令。以下是有效转义各种操作系统和 shell(尤其是 bash)参数的综合指南:

使用引号

最简单的解决方案是将参数括在引号中。单引号 (') 防止 shell 扩展,而双引号 (") 允许变量替换,但抑制带引号的字符串内的变量扩展。这种方法在不同平台和 shell 中得到广泛支持,包括 bash:

os.system("cat '%s' | grep something | sort > '%s'" 
          % (in_filename, out_filename))

使用shlex模块

Python提供了专门为此目的设计的shlex模块。它的 quote() 函数正确地转义字符串以在 POSIX shell 中使用,包括 bash:

import shlex

escaped_in_filename = shlex.quote(in_filename)
escaped_out_filename = shlex.quote(out_filename)
os.system("cat {} | grep something | sort > {}".format(
          escaped_in_filename, escaped_out_filename))

使用 Pipes 模块(弃用警告!)

对于 Python 版本 2.x 和 3.x 直至 3.10,pipes.quote 来自已弃用的 Pipes 模块可以用作 shlex.quote 的替代品。请注意,从 Python 3.11 开始,管道被标记为删除:

from pipes import quote

escaped_in_filename = quote(in_filename)
escaped_out_filename = quote(out_filename)
os.system("cat {} | grep something | sort > {}".format(
          escaped_in_filename, escaped_out_filename))

作为一般规则,出于安全原因,用户生成的输入不应在未经适当验证和清理的情况下直接插入系统调用中。

最新教程 更多>

免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。

Copyright© 2022 湘ICP备2022001581号-3