为什么在 python 上对服务器执行 ping 操作时子进程没有 return 任何内容?

Why does subprocess not return anything when pinging a server on python?

我正在使用 subprosess 来 ping 服务器,但我想收到完整的响应。过去我使用 os 进行 ping,但这只返回 10

我使用的代码是:

import subprocess
p = subprocess.Popen(['ping', '8.8.8.8'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = p.communicate()
print out

我想如果我从终端看到 运行 它的响应是否可见。请注意我使用 -c 而不是 -n 因为我使用 linux 作为 OS.

我很困惑为什么这不起作用,因为当我 运行 类似的代码时,它打印出预期的响应:

import subprocess
p = subprocess.Popen(['ls', '-a'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = p.communicate()
print out

上面的代码打印出 python 脚本所在目录中的文件和文件夹列表,因此我使用的代码似乎是正确的。

我的问题是,我怎样才能通过 ping 服务器获得分配给变量的响应,然后我可以像在 运行 ls.

时一样打印出来

默认ping是一个连续的过程;它不会停止,直到你打断它,例如使用 ctrl-C。当然,用subprocess,ctrl-C是不行的。

subprocess.communicate会在内存中缓冲所有的输出,直到程序结束(即永不);实际上,您可以使用它来创建内存不足错误 ;-).

如果您只喜欢几个 ping,甚至 1 个 ping,请使用 -c 选项 ping:

p = subprocess.Popen(['ping', '-c1', '8.8.8.8'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)

如果您想要连续轮询,可以将其包装在 Python.

内的 while 循环中

.communicate() waits for the child process to finish. ping with the given arguments does not exit unless you explicitly stop it e.g., .

这里有各种方法 stop reading process output in Python without hang

如果想在进程还在的时候看到输出运行;参见 Python: read streaming input from subprocess.communicate()