我有使用 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
您正在寻找subprocess模块,特别是subprocess.check_call()和/或subprocess.check_output()命令。