在python中执行系统命令

时间:2011-08-19 21:55:48

标签: python sys

我有使用perl编写脚本的经验,这使我可以通过使用反向标记来轻松执行linux命令。我想知道,我该怎么做这个Python?是否有一种特殊的方法来捕获命令(输出)的结果?

谢谢你:)

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:2)

您正在寻找subprocess模块,特别是subprocess.check_call()和/或subprocess.check_output()命令。

相关问题