2012-11-22 214 views
0

如何解析python中的(shell)反引號字符串?Python解析shell反引號字符串

說,我有字符串"`cat /etc/hosts | grep hostname`",我想獲得它的shell解釋,例如:「0.0.0.0主機名\ n」。我怎樣才能做到這一點?

回答

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爲我解釋它。

+1

有人需要溜你一些百憂解(我不會打擾張貼呢!)+1 –

+0

也許我的問題不夠清楚,我不想解析它,我想得到的結果,如果我在shell中輸入了字符串。 – kaspersky

+0

@ gg.kaspersky:前面的路,看我最後的編輯。 –