entrypoint

A decorator library for argument parsing and file opening
Download

entrypoint Ranking & Summary

Advertisement

  • Rating:
  • License:
  • Python License
  • Price:
  • FREE
  • Publisher Name:
  • Conrad Irwin

entrypoint Tags


entrypoint Description

A decorator library for argument parsing and file opening entrypoint is a decorator library that helps one to write small scripts in Python. It does what it does well, but has not been designed to do everything, it is opinionated, if you will.There are three main features that it provides:1) Automatically running a function when the library has been called directly. This is conventionally done in Python using: >>> def main(): ... pass >>> if __name__ == '__main__': ... main(); And can be re-written to >>> @autorun ... def main(): ... pass There is a GOTCHA waiting in the wings, already. This must be the outermost decorator for it to work as expected. (The advanced reader may care to know that this is because any decorators applied outside of this one will not have been applied at the time the function is called for the first time)2) Automatically opening and closing files with the appropriate encoding for reading, writing, or appending (using 'r', 'w' and 'a' as open()) This is conventionally done using: >>> from __future__ import with_statement >>> def main(filename): ... with codecs.open(filename, 'r', 'utf-8') as openfile: ... pass And can be re-written to >>> @withfile('r') ... def main(openfile): ... pass It is possible to pass a codec's name as the first positional argument (or as __encoding) to @withfile: >>> @withfile('utf-16', 'w') ... def main(openfile): ... pass Or to open some files in "binary" mode, with no codec, just suffix the spec with a 'b': >>> @withfile('rb', 'a') ... def main(binaryfile, logfile): ... print >>logfile, process(binaryfile.read()) Default arguments to functions are opened and closed on each entry to that function, when a function will be called more than once used 'a' instead of 'w' so that later calls don't overwrite the contents. >>> @withfile('r', 'a') ... def main(readfile, log='/tmp/python.log'): ... log.write("Reading %s" % readfile.name) For clarity, it is possible to give keyword arguments to @withfile, and it is necessary to do so if you wish to open all the arguments provided to the function's *args or **kwargs: >>> @withfile('w', args='r', stderr='a') ... def main(catfile, *args, **kwargs): ... if args: ... catfile.write("\n".join(arg.read() for arg in args)) ... elif 'stderr' in kwargs: ... print >>kwargs, "Nothing to cat" Finally, the special filename '-' is used to refer to sys.stdin for reading, and sys.stdout for writing and appending. Again this can be a default parameter or passed in by the caller: >>> @withfile('r', 'w') ... def main(input, output='-'): ... pass The major caveat with this functionality is that files which are passed as write or append arguments are opened earlier than might be strictly necessary - which can cause the creation of empty files, or the truncation of existing files. It is thus stylistically beneficial to only use this decorator for files that will certainly be written to in the course of the function It is thus stylistically beneficial to only use this decorator for files that will certainly be written to in the course of the function.3) Automatically parsing command-line arguments from a function's signature, and, if possible, from its doc-string. Internally, this uses the argparse module, but removes the tedious syntax needed to get the most simple arguments parsed. At its most basic, it simply converts a function that takes several positional arguments (**kwargs is not supported) into a function that takes an optional array of arguments, and defaults to sys.argv >>> @acceptsargv ... def main(arg1, arg2): ... pass ... ... main() ... main(sys.argv) ... main() This can be coupled with the other magic above, so that the function is called automatically when it is defined: >>> sys.argv = >>> @entrypoint ... def main(arg1, arg2) ... pass And for full all-in goodness, some arguments can be files: >>> @entrywithfile('r', 'w') ... def main(input, output): ... pass The argument parser will abort the program if the arguments don't match, and print a usage message. More detail can be found by passing -h or --help at the command line as is normal. >>> @entrypoint ... def main(arg1, arg2): ... pass usage: test.py one two : error: too few arguments In addition to compulsary, positional, arguments as demonstrate above it is possible to add flag arguments. Flag arguments are signified by providing a default parameter to the argument, of the same type as you wish the user to input. Positional arguments, and flags with a default value of None are always decoded as unicode strings. If the type conversion fails, it is presented to the user as an error. >>> @entrypoint ... def main(filename, priority=1): ... assert isinstance(priority, int) usage: filename If the default value is True or False, the flag will be treated as a toggle to flip that value: >>> @entrypoint ... def main(filename, verbose=False): ... if verbose: ... print filename usage: filename It is also possible to use the *args of a function: >>> @entrypoint ... def main(output, *input): ... print ", ".join(filenames) usage: output ] In addition to being able to parse the arguments automatically, @acceptargv can also be used to provide user-facing documentation in the same manner as argparse. It does this by parsing the function's doc string in the following ways: >>> def main(filename, flag=True, verbosity=3): ... """ ... Introductory paragraph. ... ... Description and clarification of arguments. ... ... Epilogue ... ... ---- ... ... Internal documentation ... """ ... pass All parts are optional. The introductory paragraph and the epilogue are shown before and after the summary of arguments generated by argparse. The internal documentation (below the ----) is not displayed at all. < argument> = < clarification>:< description> < clarification> = ] --< flagname> = < argname> The description can span multiple lines, and will be re-formed when displayed. In the first case, the -< letter> gives a one-letter/number abbreviation for setting the flag: >>> def main(flag=True): ... """ ... -f --flag: Set the flag ... """ < argname>, < flagname>, < varname>, and < displayname> are limited to * The flagname and the argname should match the actual name used in the function argument definition, while the displayname and varname are simply for displaying to the user. Finally, any function that is wrapped in this manner can throw an entrypoint.UsageError, the first parameter of which will be displayed to the user as an error.Several combinations are available as pre-defined decorators: Run Signature Open Automatically Parser Files @autorun X @entrypoint X X @entrywithfile X X X* @runwithfile X X @withfile X @withuserfile X* @acceptargv X* Denotes that FileUsageErrors will be thrown instead of IOErrors to provide more user-friendly error reportingA set of tests can be run by calling "python test.py" Requirements: · Python


entrypoint Related Software