如何在python中解析(shell)后引用的字符串?
说,我有字符串"`cat /etc/hosts | grep hostname`"
,我想获得它的shell解释,例如:“0.0.0.0 hostname \ n”。我怎么能这样做?
答案 0 :(得分:3)
>>> 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为我解释。