Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Argparse: expected one argument

I have argparse arguments setup in the following fashion:

parser = argparse.ArgumentParser(description='foobar')
parser.add_argument('url', metavar='URL')
parser.add_argument('-k', dest='kindle_type', default='kindle3')
parser.add_argument('-n', dest='gallery_name', default='Gallery')
parser.add_argument('-d', dest='dropbox_dir')
args = parser.parse_args()

print parser.parse_args(['imgur_url', '-k'])

However, when I run script.py -k kindledx http://url.com, I get the following error: gallery2kindle.py: error: argument -k: expected one argument

Wasn't an argument called when I used 'kindledx' after flag '-k'?

like image 605
Randall Ma Avatar asked Jun 12 '12 15:06

Randall Ma


2 Answers

Wasn't an argument called when I used 'kindledx' after flag '-k'?

It was, and if you add a print args after args = parser.parse_args(), you can see the parsing works:

~/coding$ python ap.py -k kindledx http://url.com
Namespace(dropbox_dir=None, gallery_name='Gallery', kindle_type='kindledx', url='http://url.com')

but in this line

print parser.parse_args(['imgur_url', '-k'])

you don't pass an argument to k. Compare

print parser.parse_args(['imgur_url', '-k', 'kindledx'])

which produces

Namespace(dropbox_dir=None, gallery_name='Gallery', kindle_type='kindledx', url='imgur_url')
like image 70
DSM Avatar answered Nov 15 '22 19:11

DSM


Since this is the first result of googling this error, I want to share that it can happen if you follow advice to compatible with Windows / in Linux:

arg_parser = argparse.ArgumentParser(
    prefix_chars='-+/', description='desc')

This causes -option /path/path throws expected one argument even though it looks like valid. You need quotes it to be -option '/path/path' or remove the / in the prefix_chars above to fix it.

like image 41
林果皞 Avatar answered Nov 15 '22 17:11

林果皞