我写了一些代码来ping服务器,但我不想在屏幕上输出。
但即使将输出发送到/dev/null
,我也会在屏幕上获得所有ping详细信息。
#!/usr/bin/python
import os
import sys
with open(sys.argv[1]) as servers:
for host in servers:
response = os.system("ping -q -c 1 "+host+">/dev/null 2>&1")
if response==0:
print(host)
else:
print(host+"is dead")
答案 0 :(得分:0)
使用此:
import subprocess
def myping():
with open(sys.argv[1]) as servers:
for host in servers:
p = subprocess.Popen(["ping", "-q", "-c", "1", host], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
response = p.wait()
if response==0:
print(host+"is dead")
else:
print(host+"is up")
myping()
演示
>>> import subprocess
>>> host = "google.com"
>>> p = subprocess.Popen(["ping", "-q", "-c", "1", host], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
>>> response = p.wait()
>>> print response
1
答案 1 :(得分:0)
import subprocess
p = subprocess.Popen(["ping", "-q", "-c", "1", host], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
return_code = p.wait()
避免使用os.system
。它已弃用,已过时。