Softpedia
 


LINUX CATEGORIES:



GLOBAL PAGES >>
NEWS ARCHIVE >>
SOFTPEDIA REVIEWS >>
MEET THE EDITORS >>
WEEK'S BEST
  • Linux Kernel 3.9.3 / 3....
  • LibreOffice 3.6.6 / 4.0.3
  • MPlayer 1.1.1
  • systemd 204
  • Arch Linux 2013.05.01
  • Blender 2.67a
  • KDE Software Compilatio...
  • CrunchBang Linux Stable...
  • Elementary OS 0.1 / 0.2...
  • SystemRescueCd 3.6.0
  • Home > Linux > Programming > Libraries

    entrypoint 0.1.3

    Download button

    No screenshots available
    Downloads: 1,563  View global page NEW!  Tell us about an update
    User Rating:
    Rated by:
    NOT RATED
    0 user(s)
    Developer:

    License / Price:

    Last Updated:

    Category:
    Conrad Irwin | More programs
    Python License / FREE
    September 18th, 2010, 19:57 GMT
    ROOT / Programming / Libraries

     Read user reviews (0)  Refer to a friend  Subscribe

    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['stderr'], "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[1:]

        >>> @acceptsargv
        ... def main(arg1, arg2):
        ...     pass
        ...
        ... main()
        ... main(sys.argv[1:])
        ... main(['arg1', 'arg2'])

        This can be coupled with the other magic above, so that the function is
        called automatically when it is defined:

        >>> sys.argv[1:] = ['arg1', 'arg2']
        >>> @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 [-h] 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: [-h] [--priority PRIORITY] 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: [-h] [--verbose] filename

        It is also possible to use the *args of a function:

        >>> @entrypoint
        ... def main(output, *input):
        ...     print ", ".join(filenames)

        usage: [-h] output [input [input ...]]

        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> = [-< letter>[,] ] --< flagname> [=< varname>]
                        = < argname> [/< displayname>]

        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
        [a-zA-Z][a-zA-Z0-9_-]*

        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 reporting

    A set of tests can be run by calling "python test.py"


    Product's homepage

    Requirements:

    · Python

      


    TAGS:

    decorator library | argument parsing | file opening | decorator | library | argument

    Go to top

    WindowsGamesDriversMacLinuxScriptsMobileHandheldNews

    SUBMIT PROGRAM   |   ADVERTISE   |   GET HELP   |   SEND US FEEDBACK   |   RSS FEEDS   |   UPDATE YOUR SOFTWARE   |   ROMANIAN FORUM