Browse Source

Add 'fail' function

It prints an error message to stderr and exits with status 1
check-vt100
Aleksander Kiryk 4 years ago
parent
commit
542def044b
  1. 9
      common.py
  2. 6
      graph.py
  3. 15
      sargraph.py

9
common.py

@ -12,13 +12,18 @@ import sys
import re
# Print an error message and exit with non-zero status
def fail(msg):
print(f"Error: {msg}", file=sys.stderr)
sys.exit(1)
# Run process, return subprocess object on success, exit script on failure
def run_or_fail(*argv, **kwargs):
try:
p = subprocess.Popen(argv, **kwargs)
except:
print(f"Error: '{argv[0]}' tool not found")
sys.exit(1)
fail(f"'{argv[0]}' tool not found")
return p

6
graph.py

@ -49,8 +49,7 @@ labels = []
p = run_or_fail("gnuplot", "--version", stdout=subprocess.PIPE)
version = scan(r"gnuplot (\S+)", float, p.stdout.readline().decode())
if version < GNUPLOT_VERSION_EXPECTED:
print(f"Error: Gnuplot version too low. Need at least {GNUPLOT_VERSION_EXPECTED} found {version[0]}")
sys.exit(1)
fail(f"gnuplot version too low. Need at least {GNUPLOT_VERSION_EXPECTED} found {version[0]}")
# Run a command in a running gnuplot process
@ -180,8 +179,7 @@ def graph(session, fname='plot.png'):
# Otherwise leave the default png
pass
else:
print("Error: unknown graph extension.")
sys.exit(1)
fail("unknown graph extension")
# Leave just the base name
fname = fname[:-4]

15
sargraph.py

@ -33,8 +33,7 @@ p = run_or_fail("sar", "-V", stdout=subprocess.PIPE)
p = run_or_fail("screen", "-v", stdout=subprocess.PIPE)
version = scan("Screen version (\d+)", int, p.stdout.readline().decode())
if version is None:
print("Error: 'screen' tool returned unknown output!")
sys.exit(1)
fail("'screen' tool returned unknown output")
# If the script was run with no parameters, run in background and gather data
if args.session is None:
@ -47,8 +46,7 @@ if args.session is None:
while args.fsdev is None:
args.fsdev = scan(f"^(/dev/\S+)\s+{re.escape(args.fspath)}\s+", str, f.readline())
if not args.fsdev:
print(f"Error: no device is mounted on {args.fspath}")
sys.exit(1)
fail(f"no device is mounted on {args.fspath}")
watch.watch(args.name, args.fsdev)
sys.exit(0)
@ -57,8 +55,7 @@ if args.session is None:
# Check if a command was provided
if len(args.command) <= 0:
print("Error: command not provided.")
sys.exit(1)
fail("command not provided")
# Get session name and command name
sid = args.session
@ -97,8 +94,7 @@ elif cmd[0] == "stop":
elif cmd[0] == "label":
# Check if the label name was provided
if len(cmd) < 2:
print("Error: label command requires an additional parameter")
sys.exit(1)
fail("label command requires an additional parameter")
print(f"Adding label '{cmd[1]}' to sargraph session '{sid}'.")
send(sid, f"label:{cmd[1]}")
elif cmd[0] == 'save':
@ -114,5 +110,4 @@ elif cmd[0] == 'plot':
else:
graph.graph(sid, cmd[1])
else:
print(f"Error: Unknown command '{cmd[0]}'")
sys.exit(1)
fail(f"unknown command '{cmd[0]}'")

Loading…
Cancel
Save