#!python # -*- mode: python; Encoding: utf-8; coding: utf-8 -*- # Last updated: <2019/09/16 09:35:47 +0900> """ display time and ping send. Windows10 x64 + Python 2.7.16 32bit """ import subprocess import curses import os import time from datetime import datetime import sys import argparse def is_connectable(host): """Ping.""" copt = "-c" tmout = "3" if os.name == "nt": # Windows NT copt = "-n" tmout = "3000" ping = subprocess.Popen( ["ping", "-w", tmout, copt, "1", host], stdin=subprocess.PIPE, stdout=subprocess.PIPE ) ping.communicate() return ping.returncode == 0 def get_hms(t): """Get HH:MM:SS.""" h = int(t / 3600) m = int((t / 60) % 60) s = int(t % 60) return h, m, s def win_main(win): """Main.""" curses.curs_set(0) win.nodelay(True) key = "" win.clear() tm = time.time() while True: n = time.time() t = "%s" % datetime.fromtimestamp(n) win.addstr(0, 0, starttimestr) d = n - tm if d >= 1.0: win.addstr(3, 0, "ping") result = is_connectable(host) if result is not True: win.addstr(1, 0, "%s - %s is dead." % (t, host)) break else: win.addstr(1, 0, "%s - %s is alive." % (t, host)) h, m, s = get_hms(n - starttime) win.addstr(2, 0, "%d:%02d:%02d" % (h, m, s)) tm = time.time() elif d >= 0.4: win.move(3, 0) win.clrtoeol() try: key = win.getkey() if key == os.linesep or key == "q" or ord(key) == 27: break except Exception as e: # No input pass time.sleep(0.2) parser = argparse.ArgumentParser(description="Send ping.") parser.add_argument("hostname", metavar="HOSTNAME", help="host name") args = parser.parse_args() host = args.hostname starttime = time.time() starttimestr = "%s - start" % datetime.fromtimestamp(starttime) curses.wrapper(win_main) print(starttimestr) endtime = time.time() t = "%s" % datetime.fromtimestamp(endtime) print("%s - %s is dead." % (t, host)) h, m, s = get_hms(endtime - starttime) print("%d:%02d:%02d" % (h, m, s)) sys.exit()