如何逃避 os.system() 调用? [英] How to escape os.system() calls?

查看:33
本文介绍了如何逃避 os.system() 调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当使用 os.system() 时,通常需要对作为参数传递给命令的文件名和其他参数进行转义.我怎样才能做到这一点?最好是可以在多个操作系统/外壳上运行的东西,但特别是对于 bash.

When using os.system() it's often necessary to escape filenames and other arguments passed as parameters to commands. How can I do this? Preferably something that would work on multiple operating systems/shells but in particular for bash.

我目前正在执行以下操作,但我确信必须为此提供一个库函数,或者至少有一个更优雅/健壮/高效的选项:

I'm currently doing the following, but am sure there must be a library function for this, or at least a more elegant/robust/efficient option:

def sh_escape(s):
   return s.replace("(","\(").replace(")","\)").replace(" ","\ ")

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

我已经接受了使用引号的简单答案,不知道为什么我没有想到;我猜是因为我来自 Windows,其中 ' 和 " 的行为略有不同.

I've accepted the simple answer of using quotes, don't know why I didn't think of that; I guess because I came from Windows where ' and " behave a little differently.

关于安全性,我理解这种担忧,但在这种情况下,我对 os.system() 提供的快速简便的解决方案感兴趣,并且字符串的来源不是用户生成的,或者至少不是用户生成的由受信任的用户(我)输入.

Regarding security, I understand the concern, but, in this case, I'm interested in a quick and easy solution which os.system() provides, and the source of the strings is either not user-generated or at least entered by a trusted user (me).

推荐答案

这是我使用的:

def shellquote(s):
    return "'" + s.replace("'", "'\''") + "'"

shell 将始终接受带引号的文件名并在将其传递给相关程序之前删除周围的引号.值得注意的是,这避免了包含空格或任何其他类型的讨厌的 shell 元字符的文件名的问题.

The shell will always accept a quoted filename and remove the surrounding quotes before passing it to the program in question. Notably, this avoids problems with filenames that contain spaces or any other kind of nasty shell metacharacter.

更新:如果您使用的是 Python 3.3 或更高版本,请使用 shlex.quote 而不是滚动你自己的.

Update: If you are using Python 3.3 or later, use shlex.quote instead of rolling your own.

这篇关于如何逃避 os.system() 调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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