在Python中转义一个用于shell命令的字符串 [英] escape a string for shell commands in Python

查看:514
本文介绍了在Python中转义一个用于shell命令的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有兴趣在Python3.x中转义一个字符串,例如:

  SOME_MACRO(a,b)

into ...

  SOME_MACRO\(a,\ b\)

...所以它可以传递给一个程序(在这种情况下不是gcc)作为一个定义,



例如,

  some_program -DSOME_MACRO\(a,\ b\)=某些表达式

我希望 shlex 将具有此功能,但我没有找到如何做到这一点,并检查了许多类似的问题。 >

我不介意写一些简单的函数来做到这一点,但这似乎是Python将包含的一种东西。



注意:

c $ c> -DSOME_MACRO(a,b)=某些表达式

它期望第一个字符是一个ident ifier。

解决方案

在Python 3.3中,您可以使用 shlex.quote 返回一个shell转义的字符串版本。它是 pipes.quote 的继承者,自Python 1.6。请注意,如另一答案中所建议的那样,文档建议不要使用列表的。另外根据文档,引用与UNIX shell兼容。我不能保证它适用于您的案例,但是使用 rm ,使用管道进行快速测试,因为我没有Python 3.3:

  $ touch \(a\ b\)
$ ls
(ab)

>>>导入子流程,管道
>>> filename = pipes.quote((a b))
>>> command ='rm {}'。format(filename)
>>> subprocess.Popen(command,shell = True)

$ ls
$


I'm interested to escape a string in Python3.x, such as:

SOME_MACRO(a, b)

into...

SOME_MACRO\(a,\ b\)

... so that it can be passed to a program (not gcc in this case) as a define,

eg,

some_program -DSOME_MACRO\(a,\ b\)="some expression"

I would expect shlex would have this functionality but I didn't find how to do this and checked many similar questions already.

I don't mind to write some simple function to do this, but this seems the kind of thing Python would include.

Note: the program I'm passing the argument to wont accept:

-D"SOME_MACRO(a, b)"="some expression"

... it expects the first character to be an identifier.

解决方案

In Python 3.3 you can use shlex.quote to return a shell-escaped version of a string. It is the successor of pipes.quote, which was deprecated since Python 1.6. Note that the documentation recommends this for cases where you cannot use a list, as suggested in another answer. Also according to the documentation, the quoting is compatible with UNIX shells. I can't guarantee that it will work for your case, but a quick test with rm, using pipes because I don't have Python 3.3:

$ touch \(a\ b\)
$ ls
(a b)

>>> import subprocess, pipes
>>> filename = pipes.quote("(a b)")
>>> command = 'rm {}'.format(filename)
>>> subprocess.Popen(command, shell=True)

$ ls
$

这篇关于在Python中转义一个用于shell命令的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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