我有使用perl编写脚本的经验,这使我通过使用反引号轻松执行Linux命令。我想知道,我该如何在Python中实现这一点?是否有一种特殊的方法来捕获命令的结果(输出)?
谢谢:)
除了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
check_output
小心一点,因为它只适用于>=2.7。在2.7之前,您可能需要使用带有subprocess.PIPE
的Popen
。 - Alex Churchill