Why isn't fromfile-prefix-chars in Python argparse working?

前端 未结 4 736
长情又很酷
长情又很酷 2020-12-20 19:36

I\'m trying to use the fromfile-prefix-chars feature of argparse in Python to load all my command line arguments from a file, but it keeps complaining that I haven\'t specif

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-20 20:14

    I think there's a better answer to this: use shlex.

    if sys.argv[1].startswith('@'):
        args = parser.parse_args( shlex.split(open(sys.argv[1][1:]).read()) )
    else:
        args = parser.parse_args()
    

    This allows you to specify args in a file in a more natural way e.g., it allows using spaces or equals sign to specify your args on a single line as in:

    arg1
    arg2
    --opt1 'foo'
    --opt2='bar'
    

    shlex.split splits this as you would expect:

    ['arg1', 'arg2', '--opt1', 'foo', '--opt2=bar']
    

    The only thing this method doesn't have is that it expects the @file.txt to be the first argument.

提交回复
热议问题