threadr.lostcave.ddnss.de/variable_grabbler.py

73 lines
2.3 KiB
Python
Raw Normal View History

#!/usr/bin/env python3
2020-02-23 21:40:16 +01:00
import os, sys, json, traceback
2020-04-08 02:06:32 +02:00
# Definitions
def stdout(string, end='\n', flush=False):
print(string, end=end, file=sys.stdout, flush=flush)
2020-02-23 21:40:16 +01:00
def stderr(string, end='\n', flush=False):
print(string, end=end, file=sys.stderr, flush=flush)
2020-04-08 02:06:32 +02:00
stderr("Variable Grabbler - version 5.0_pre1\n--------------------------------------------------------------------------------")
################################################################################
# Chnages in this version:
# - port to Python 3
# - output to stdout instead of rewriting the file
#===============================================================================
# Full documentation: tbd
#===============================================================================
# Exit codes:
# 0: normal exit
# 1: wrong usage
# 2: error while processing
2020-02-23 21:40:16 +01:00
# Command line input handling
usage = "Usage: python3 "+sys.argv[0]+" <macro config file> <file to be processed>"
if not len(sys.argv)==3:
stderr("E: Wrong amount of arguments.")
stderr(usage)
sys.exit(1)
if sys.argv[1] == sys.argv[2]:
stderr("E: Both input files are the same.")
stderr(usage)
sys.exit(1)
2020-04-08 03:52:18 +02:00
stderr("I: Reading macro definitions... ", end="")
macros = {}
try:
if os.path.isfile(sys.argv[1]):
macro_file = open(sys.argv[1], "r")
macros = json.loads(macro_file.read())
macro_file.close()
elif sys.argv[1] == '-':
macros = json.loads(sys.stdin.read())
2020-04-08 02:06:32 +02:00
else:
stderr("E: Not a valid file: "+sys.argv[1])
sys.exit(2)
except:
stderr("E: An exception occurred while trying to read macro definitions:")
traceback.print_exc()
sys.exit(2)
stderr("Done.")
2020-04-08 03:52:18 +02:00
try:
input_file = sys.stdin
if os.path.isfile(sys.argv[2]):
input_file = open(sys.argv[2], "r")
elif sys.argv[2] == '-':
# nothing to do here bc input_file is already set to sys.stdin
pass
else:
stderr("E: Not a valid file: "+sys.argv[2])
sys.exit(2)
for line in input_file:
stdout(line, end="")
# close input file if it's not sys.stdin, assume sys.stdin is being handled for us
if not input_file==sys.stdin:
input_file.close()
except:
stderr("E: An exception occured while processing " + input_file.name + ":")
traceback.print_exc()
sys.exit(2)