如何在Python中转义os.system()调用? [英] How to escape os.system() calls in Python?

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

问题描述

当使用os.system()时,通常需要将文件名和作为参数传递的其他参数转义为命令。我该怎么做?最好是可以在多个操作系统/ shell上工作的东西,特别是对于bash。



我正在执行以下操作,但确定必须有一个库函数这个,或至少一个更优雅/强大/有效的选项:

  def sh_escape(s):
return s 。(,\\)替换(,\\)

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

编辑:我已经接受了使用引号的简单答案,不知道为什么我没有想到那;我想是因为我来自Windows,其中和的行为有所不同。



关于安全性,我明白了关注,但在这种情况下,我对os.system()提供的一个快速简单的解决方案,并且字符串的源不是由用户生成的,或至少由受信任的用户(我)输入。

解决方案

这是我使用的:

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

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

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


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)))

Edit: 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.

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).

解决方案

This is what I use:

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

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.

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

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

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