Python解析shell反引号字符串

时间:2012-11-22 12:04:34

标签: python shell

如何在python中解析(shell)后引用的字符串?

说,我有字符串"`cat /etc/hosts | grep hostname`",我想获得它的shell解释,例如:“0.0.0.0 hostname \ n”。我怎么能这样做?

1 个答案:

答案 0 :(得分:3)

使用shlex.split()

>>> import shlex
>>> shlex.split('cat /etc/hosts | grep hostname')
['cat', '/etc/hosts', '|', 'grep', 'hostname']

但是,如果您要在反引号中查找命令的输出,则需要使用subprocess module代替:

>>> import subprocess
>>> subprocess.check_output('cat /etc/hosts | grep dahn', shell=True)
'127.0.0.1\tdahnlocal.internal.int\n'

请注意,我将shell设置为True以让shell为我解释。