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

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

问题描述

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



我目前正在执行以下操作,但是请确保必须有一个库函数用于这,或者至少是一个更优雅/更强大/更有效的选择:

  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,和的行为略有不同。



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

解决方案

这是我使用的:

  def shellquote:
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.

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

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