Python Argparse: Issue with optional arguments which are negative numbers

后端 未结 7 2002
走了就别回头了
走了就别回头了 2020-12-08 13:59

I\'m having a small issue with argparse. I have an option xlim which is the xrange of a plot. I want to be able to pass numbers like <

7条回答
  •  旧巷少年郎
    2020-12-08 14:27

    As already pointed out by the comments, the problem is that a - prefix is parsed as an option instead of as an argument. One way to workaround this is change the prefix used for options with prefix_chars argument:

    #!/usr/bin/python
    import argparse
    
    parser = argparse.ArgumentParser(prefix_chars='@')
    parser.add_argument('@@xlim', nargs = 2,
                      help = 'X axis limits',
                      action = 'store', type = float,
                      default = [-1.e-3, 1.e-3])
    print parser.parse_args()
    

    Example output:

    $ ./blaa.py @@xlim -2.e-3 1e4
    Namespace(xlim=[-0.002, 10000.0])
    

    Edit: Alternatively, you can keep using - as separator, pass xlim as a single value and use a function in type to implement your own parsing:

    #!/usr/bin/python
    import argparse
    
    def two_floats(value):
        values = value.split()
        if len(values) != 2:
            raise argparse.ArgumentError
        values = map(float, values)
        return values
    
    parser = argparse.ArgumentParser()
    parser.add_argument('--xlim', 
                      help = 'X axis limits',
                      action = 'store', type=two_floats,
                      default = [-1.e-3, 1.e-3])
    print parser.parse_args()
    

    Example output:

    $ ./blaa.py --xlim "-2e-3 1e4"
    Namespace(xlim=[-0.002, 10000.0])
    

提交回复
热议问题