Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use python's argparse with a predefined argument string?

Tags:

I want to use the pythons argparse module to parse my cli parameter string. This works for the parameters a pass from terminal, but not with a given string.

import argparse  parser = argparse.ArgumentParser(description='Argparse Test script') parser.add_argument("param", help='some parameter')  argString = 'someTestFile' print(argString)  args = parser.parse_args(argString) 

If I run this script I get this output:

~/someTestFile usage: argparsetest.py [-h] param argparsetest.py: error: unrecognized arguments: o m e T e s t F i l e 

The ~/someTestFile is somehow transformed in o m e T e s t F i l e. As already mentioned, it works if I pass the filename from the terminal.

I could imagine, that this has something to do with string encodings. Does someone has an idea how to fix this?

like image 559
thorink Avatar asked Jan 16 '12 10:01

thorink


People also ask

How do you pass arguments to Argparse?

First, we need the argparse package, so we go ahead and import it on Line 2. On Line 5 we instantiate the ArgumentParser object as ap . Then on Lines 6 and 7 we add our only argument, --name . We must specify both shorthand ( -n ) and longhand versions ( --name ) where either flag could be used in the command line.

How do you parse arguments in Python?

Argument Parsing using sys.Your program will accept an arbitrary number of arguments passed from the command-line (or terminal) while getting executed. The program will print out the arguments that were passed and the total number of arguments. Notice that the first argument is always the name of the Python file.

Is Argparse the default?

The argparse module will automatically allow an option -h or --help that prints a usage string for all the registered options. By default, the type is str , the default value is None , the help string is empty, and metavar is the option in upper case without initial dashes.


2 Answers

Another option is to use shlex.split. It it especially very convenient if you have real CLI arguments string:

import shlex argString = '-vvvv -c "yes" --foo bar --some_flag' args = parser.parse_args(shlex.split(argString)) 
like image 90
Serge Avatar answered Sep 17 '22 16:09

Serge


parser.parse_args() expects a sequence in the same form as sys.argv[1:]. If you treat a string like a sys.argv sequence, you get ['s', 'o', 'm', 'e', 'T', 'e', 's', 't', 'F', 'i', 'l', 'e']. 's' becomes the relevant argument, and then the rest of the string is unparseable.

Instead, you probably want to pass in parser.parse_args(['someTestFile'])

like image 24
Devin Jeanpierre Avatar answered Sep 18 '22 16:09

Devin Jeanpierre