Skip to content

Instantly share code, notes, and snippets.

@GrahamCampbell
Created March 15, 2020 00:36
Show Gist options
  • Save GrahamCampbell/857b91505e0bb393a8d935e4c0659edb to your computer and use it in GitHub Desktop.
Save GrahamCampbell/857b91505e0bb393a8d935e4c0659edb to your computer and use it in GitHub Desktop.
import json
import sys
from urllib import request, error
class GP2Exception(Exception):
def __init__(self, *args):
if args:
self.message = args[0]
else:
self.message = 'An unknown error occured'
def eprint(*args, **kwargs):
print(*args, file=sys.stderr, **kwargs)
def read_inputs(program_filepath, hostgraph_filepath):
try:
with open(program_filepath, 'r') as f:
program = f.read()
try:
with open(hostgraph_filepath, 'r') as g:
hostgraph = g.read()
return program, hostgraph
except FileNotFoundError as e:
raise GP2Exception('The provided hostgraph file could not be read.')
except FileNotFoundError as e:
raise GP2Exception('The provided program file could not be read.')
def interpret(program, hostgraph):
url = 'https://gp2.gjcampbell.co.uk/interpret'
data = json.dumps({'program':program,'graph':hostgraph}).encode('utf8')
headers = {'content-type': 'application/json', 'User-Agent': 'gp2i-cli/1.0'}
try:
response = request.urlopen(request.Request(url, data=data, headers=headers))
except error.HTTPError as e:
if e.code == 400:
raise GP2Exception(json.loads(e.read().decode('utf8'))['error'])
elif e.code == 401:
raise GP2Exception('Access denied by the remote server.')
else:
raise
return json.loads(response.read().decode('utf8'))['graph']
def main(args):
if len(args) != 3:
eprint('Incorrect number of arguments. Expected two arguments <program> <hostgraph>')
return 1
try:
program, graph = read_inputs(args[1], args[2])
print(interpret(program, graph).strip())
except GP2Exception as e:
eprint(e.message.strip())
return 1
return 0
if __name__ == '__main__':
sys.exit(main(sys.argv))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment