How to read/process command line arguments?

后端 未结 17 2007
离开以前
离开以前 2020-11-21 05:14

I am originally a C programmer. I have seen numerous tricks and \"hacks\" to read many different arguments.

What are some of the ways Python programmers can do this

相关标签:
17条回答
  • 2020-11-21 05:22

    The docopt library is really slick. It builds an argument dict from the usage string for your app.

    Eg from the docopt readme:

    """Naval Fate.
    
    Usage:
      naval_fate.py ship new <name>...
      naval_fate.py ship <name> move <x> <y> [--speed=<kn>]
      naval_fate.py ship shoot <x> <y>
      naval_fate.py mine (set|remove) <x> <y> [--moored | --drifting]
      naval_fate.py (-h | --help)
      naval_fate.py --version
    
    Options:
      -h --help     Show this screen.
      --version     Show version.
      --speed=<kn>  Speed in knots [default: 10].
      --moored      Moored (anchored) mine.
      --drifting    Drifting mine.
    
    """
    from docopt import docopt
    
    
    if __name__ == '__main__':
        arguments = docopt(__doc__, version='Naval Fate 2.0')
        print(arguments)
    
    0 讨论(0)
  • 2020-11-21 05:24
    #set default args as -h , if no args:
    if len(sys.argv) == 1: sys.argv[1:] = ["-h"]
    
    0 讨论(0)
  • 2020-11-21 05:26
    import argparse
    
    parser = argparse.ArgumentParser(description='Process some integers.')
    parser.add_argument('integers', metavar='N', type=int, nargs='+',
                       help='an integer for the accumulator')
    parser.add_argument('--sum', dest='accumulate', action='store_const',
                       const=sum, default=max,
                       help='sum the integers (default: find the max)')
    
    args = parser.parse_args()
    print(args.accumulate(args.integers))
    
    Assuming the Python code above is saved into a file called prog.py
    $ python prog.py -h
    
    Ref-link: https://docs.python.org/3.3/library/argparse.html
    
    0 讨论(0)
  • 2020-11-21 05:28

    There is also argparse stdlib module (an "impovement" on stdlib's optparse module). Example from the introduction to argparse:

    # script.py
    import argparse
    
    if __name__ == '__main__':
        parser = argparse.ArgumentParser()
        parser.add_argument(
            'integers', metavar='int', type=int, choices=range(10),
             nargs='+', help='an integer in the range 0..9')
        parser.add_argument(
            '--sum', dest='accumulate', action='store_const', const=sum,
            default=max, help='sum the integers (default: find the max)')
    
        args = parser.parse_args()
        print(args.accumulate(args.integers))
    

    Usage:

    $ script.py 1 2 3 4
    4
    
    $ script.py --sum 1 2 3 4
    10
    
    0 讨论(0)
  • 2020-11-21 05:28

    One way to do it is using sys.argv. This will print the script name as the first argument and all the other parameters that you pass to it.

    import sys
    
    for arg in sys.argv:
        print arg
    
    0 讨论(0)
  • 2020-11-21 05:29

    My solution is entrypoint2. Example:

    from entrypoint2 import entrypoint
    @entrypoint
    def add(file, quiet=True): 
        ''' This function writes report.
    
        :param file: write report to FILE
        :param quiet: don't print status messages to stdout
        '''
        print file,quiet
    

    help text:

    usage: report.py [-h] [-q] [--debug] file
    
    This function writes report.
    
    positional arguments:
      file         write report to FILE
    
    optional arguments:
      -h, --help   show this help message and exit
      -q, --quiet  don't print status messages to stdout
      --debug      set logging level to DEBUG
    
    0 讨论(0)
提交回复
热议问题