2011-08-19 141 views
3

我有使用perl编写脚本的经验,这使我可以轻松地使用back-ticks执行linux命令。我想知道,我该怎么做这个Python?捕获命令(输出)的结果是否有特殊的方法?在python中执行系统命令

谢谢:)

回答

6

为了增加urschrei的答案,这里是一个例子(Windows)中:

>>> import subprocess 
>>> p = subprocess.Popen(['ping', '192.168.111.198'], stdout=subprocess.PIPE, st 
derr=subprocess.PIPE) 
>>> out, err = p.communicate() 
>>> print out 

Pinging 192.168.111.198 with 32 bytes of data: 
Reply from 192.168.111.198: bytes=32 time<1ms TTL=128 
Reply from 192.168.111.198: bytes=32 time<1ms TTL=128 
Reply from 192.168.111.198: bytes=32 time<1ms TTL=128 
Reply from 192.168.111.198: bytes=32 time<1ms TTL=128 

Ping statistics for 192.168.111.198: 
    Packets: Sent = 4, Received = 4, Lost = 0 (0% loss), 
Approximate round trip times in milli-seconds: 
    Minimum = 0ms, Maximum = 0ms, Average = 0ms 

>>> print err 

>>> print p.returncode 
0