Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

An exception in Argparse

I have the following code for reading the arguments from a file and process them using argparse, but I am getting an error, why is this the case?

import argparse
from ConfigParser import ConfigParser
import shlex

parser = argparse.ArgumentParser(description='Short sample app',
                                 fromfile_prefix_chars='@')

parser.add_argument('--abool', action="store_true", default=False)
parser.add_argument('--bunit', action="store", dest="bunit",type=int)
parser.add_argument('--cpath', action="store", dest="c", type=str)

print parser.parse_args(['@argparse_fromfile_prefix_chars.txt']) #name of the file is argparse_fromfile_prefix_chars.txt

Error:

usage: -c [-h] [--abool] [--bunit BUNIT] [--cpath C]
-c: error: unrecognized arguments: --bunit 289 --cpath /path/to/file.txt
To exit: use 'exit', 'quit', or Ctrl-D.

Contents of the file argparse_fromfile_prefix_chars.txt

--abool
--bunit 289
--cpath /path/to/file.txt
like image 563
Lanc Avatar asked Mar 15 '26 18:03

Lanc


1 Answers

argparse expects arguments from files to be one per line. Meaning the whole line is one quoted argument. So your current args file is interpreted as

python a.py '--abool' '--bunit 289' '--cpath /path/to/file.txt'

which causes the error. Instead, your args file should look like this

--abool
--bunit
289
--cpath
/path/to/file.txt
like image 72
Andrew Johnson Avatar answered Mar 17 '26 08:03

Andrew Johnson