Pergunta

I just started with python3, and im using argparse lib for parsing argument list from the console input. I have studied manual at python page and searched a lot sadly i didnt found right answer:

How to correctly parse an argument,which has voluntary part separated by other character then space. Let me explain on example:

--argument=file.txt (without space after =) I want to know when the argument has been used, and whats his 'file.txt' part(which can change).Is there some form of substitution for voluntary part?

parser.add_argument('--argument=*',action=...) #or so..

--Thanks

p.s. Sadly alternative with space is not an option.

Foi útil?

Solução

argparse handles a = joining flag and argument:

parser.add_argument('--argument',help='your help line here') 

This will accept either.

'--argument=file.txt'
'--argument file.txt'

The default is to expect one value nargs=None. If not given the default value is None.

See

16.4.4.1
For long options (options with names longer than a single character), the option and 
value can also be passed as a single command-line argument, using = to separate them:

>>> parser.parse_args('--foo=FOO'.split())
Namespace(foo='FOO', x=None)

Without the --, the argument is positional

parser.add_argument('argument',help='your help line here') 

I assume by 'voluntary' you mean 'optional' (as used in the documentation). But now is required. That is, you'll get an error if you don't provide the filename.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top