简化并减少显示的不需要的输出

Streamline and reduce unwanted output being displayed

这是我用来检查与主机关联的状态的代码,我只想打印状态(up/down)并避免在终端上显示整个 ping 过程。

import os
hostname = "google.com"
response = os.system("ping -c 1" + hostname)

if response == 0:
    print hostname, 'up'
else:
    print hostname, 'down'

你好,我做了一个这样的。 稍后我会自定义这个以发送电子邮件。

我让你开心os。 此致,

进口os hostname = "google.com"

如果os.name == 'nt' 或 os.name == 'NT': 响应 = os.system("ping -n 1 " + hostname) 别的: 响应 = os.system("ping -c 1 " + hostname)

如果响应 == 0: 打印(hostname,'up') 别的: 打印(hostname,'down') ''' 添加选项以在 ping 失败时发送电子邮件''

import subprocess 
import re
hostname = "google.com"  

with subprocess.Popen(["ping", "-c 1", "-t 3", hostname], stdout=subprocess.PIPE) as proc:
  match = re.findall(r'1 packets received', proc.stdout.read().decode())
  if match:
    print(hostname + ' is up')
  else:
    print(hostname + ' is down')

结果:

google.com is up

对于 python 2.7:

test = subprocess.Popen(["ping", "-c 1", "-t 3", hostname],stdout=subprocess.PIPE)
match = re.findall(r'1 packets received', test.communicate()[0])
if match:
  print(hostname + ' is up')
else: 
  print(hostname + ' is down')