Created
September 3, 2014 02:58
-
-
Save sposterkil/09c7fbc30f0461dde1f6 to your computer and use it in GitHub Desktop.
pr01 "binary"
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env python | |
| # -*- coding: utf-8 -*- | |
| import sys | |
| from collections import deque | |
| from pr01 import prefixParser | |
| USAGE_MESSAGE = "pr01 [file]" | |
| EXTENDED_MESSAGE = ''' | |
| Takes a file as an argument or on stdin, parses it as an expression tree, and | |
| evaluates the result. | |
| Options | |
| -h, --help print this message | |
| ''' | |
| def log(*msgs): | |
| '''log messages to stderr''' | |
| for msg in msgs: | |
| print >>sys.stderr, msg, | |
| print >>sys.stderr | |
| sys.stderr.flush() | |
| def usage(code=None): | |
| '''Prints the usage and exits with an error code specified by code. If code | |
| is not given it exits with error_codes['usage']''' | |
| log(USAGE_MESSAGE) | |
| if code is None: | |
| log(EXTENDED_MESSAGE) | |
| code = 1 | |
| sys.exit(code) | |
| def main(argv): | |
| try: | |
| # First we get the values from the file. We don't need the children | |
| # number, but we check that it's appropriate in split_line(). | |
| with sys.stdin as file_in: | |
| # Strip empty lines from the file | |
| file_lines = [l for l in (line.strip() for line in file_in) if l] | |
| # Split them into tuples (children count, value) | |
| tuple_list = [prefixParser.split_line(line) for line in file_lines] | |
| # Extract value tuples, discarding the children count | |
| value_list = [value for _, value in tuple_list] | |
| # Finally, we parse the lists into a mathematical expression, evaluate | |
| # it, and print the result. | |
| print prefixParser.parse(deque(value_list)) | |
| except ValueError, e: | |
| # Any ValueErrors raised during this process indicate failure at one | |
| # step or another, and contain suitable error messages. | |
| log(str(e)) | |
| sys.exit(1) | |
| except Exception, e: | |
| # If we get any other kind of exception, we had some serious error. | |
| # We'll just report the exception string and hope it's informative. | |
| log(str(e)) | |
| sys.exit(1) | |
| finally: | |
| # If we make it here, we're done and can exit successfully. | |
| sys.exit(0) | |
| if __name__ == "__main__": | |
| main(sys.argv[1:]) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment