我正在尝试在 python 中使用 subprocess 模块来 ping ip 地址。这是代码。
command = ['ping', '-c', '1', 1.1.1.1]
print((subprocess.check_output(command)).decode("utf-8"))
这将为 1.1.1.1 返回正确的 ping 结果。
Ping statistics for 1.1.1.1:
Packets: Sent = 1, Received = 1, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
Minimum = 4ms, Maximum = 4ms, Average = 4ms
但是,如果要 ping 一个无效的 ip,例如 0.0.0.0
command = ['ping', '-c', '1', 0.0.0.0]
subprocess.call(command)
print((subprocess.check_output(command)).decode("utf-8"))
然后 subprocess.call(command) 会返回
Pinging 0.0.0.0 with 32 bytes of data:
PING: transmit failed. General failure.
Ping statistics for 0.0.0.0:
Packets: Sent = 1, Received = 0, Lost = 1 (100% loss)
然而,一旦代码到达 subprocess.check_output,它就不会返回任何东西,并且它后面的所有后续代码都不会运行。如何让 subprocess.check_output() 返回 subprocess.call() 抛出的完整 ping 语句?
答案 0 :(得分:1)
subprocess.check_output()
会引发异常,而 ping
在没有收到对 ping 的响应时会执行此操作。
您应该使用 subprocess.call()
而不是使用 subprocess.check_output()
和 subprocess.run()
。
command = ['ping', '-c', '1', '1.1.1.1']
print(subprocess.run(command, stdout=PIPE, stderr=STDOUT, encoding="utf-8").stdout)