python - 如何在 python 中转义命令行参数?

标签 python shell shlex

我正在编写一个脚本,需要使用subprocess模块调用外部命令。问题是我需要将用户提供的文件传递给命令,因此它看起来类似于:

p = subprocess.run("command arg1 arg2 {userfile}".format(userfile=f),
                   capture_output=True, text=True, shell=True)

我必须使用 shell=True 运行命令才能使其正常工作,这就是为什么我将命令作为字符串而不是列表传递。

问题是有人可能会传递一个名为:somefile && rm -rf ~ 的文件,这是一个出于奇怪原因的有效文件名(至少在 Windows 上。不知道 mac/linux),然后就会发生不好的事情。

因此,我需要在将用户输入传递到 shell 之前对其进行转义。我想为此使用内置的 shlex.quote 函数,因此通过上面的示例,我得到: 'somefile && rm -rf ~' 并且命令变为: command arg1 arg2 'somefile && rm -rf ~cmd' 应该在 unix 系统上工作。问题是这种转义在带有命令提示符的 Windows 上不起作用,因此我的脚本在 Windows 计算机上失败。

是否有内置或第三方函数/库可以在所有平台上正确转义命令行参数,或者至少对于 Windows(因为 shlex.quote 在 unix 上工作)?

我正在 Windows 上进行开发,因此我需要此脚本在该平台上工作,并且我不认为像 "{userfile}" 这样的东西就足够了。

任何适用于 python 3 的解决方案将不胜感激。

最佳答案

将列表传递给子进程,例如

p = subprocess.run(["command", "arg1", "arg2" , f],
                   capture_output=True, text=True)

有关 Windows 的更新

使用预期二进制文件的绝对路径通常是最好的方法,将命令更改为:

p = subprocess.run(["C:\\path\\to\\binary.exe", "arg1", "arg2" , f],
                   capture_output=True, text=True)

如果绝对路径未知,则可以使用 which 来查找您的二进制文件(在最新版本的 Windows 上,我在 Windows 7 上进行了测试)。

>>> p = subprocess.run(["which", "python"], stdout=subprocess.PIPE)
>>> python_binary = p.stdout.strip().decode()  # Convert back to str
>>> python_binary
'C:\\Program Files\\Python36\\python.exe'

关于python - 如何在 python 中转义命令行参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57219801/

相关文章:

python - 使用 Notepad++ 运行 Python

python - 对 Telegram.org "Error 500: RPC_SEND_FAIL"的正确回应

Bash:欺骗程序认为 stdout 是一个交互式终端

bash - 在 Bash 中执行包含空格的命令

python - 通配符在使用 shlex 的子进程调用中不起作用

python - pip 安装 : upgrade a library in/usr without sudo

python - matplotlib 中共享轴方形子图的新 pythonic 样式?

linux - 使用 Bash 检测网关/路由器 : Functions and Variables.

python - 使用 Python 通过 ssh 将文件 cat 到远程 bash 脚本