FAQ Database Discussion Community


Multiple level argparse subparsers

python,argparse
I have multiple levels of subparsers within subparsers, but when I run the program with help flag, I see help messages and choices only for top level options. How can I see help for all suboptions, or for specific suboption in deeper level?

Parsing limited switches with python argparse

python,argparse
Is there a way to parse only limited number of switches in a function using argparse? Say, my command is: python sample.py -t abc -r dfg -h klm -n -p qui And I want argparse to parse from -t to -h and leave the remaining, also show help for these...

how to modify “--help” in argparse

python,argparse
When you run foo.py -h OR foo.py --help, you will get a "help" message about how to use foo.py and what arguments that it takes. Is there a way I can append to this message? Printing __doc__ for example?...

How to merge this functionality with argparse? [closed]

python,python-2.7,command-line-arguments,argparse
I have this functionality: import codecs from sklearn.feature_extraction.text import TfidfVectorizer with codecs.open('/Users/user/Desktop/file.txt', encoding='utf-8') as f: spanish_stop_words = [line.strip() for line in f] print spanish_stop_words from sklearn.feature_extraction import text my_stop_words = text.ENGLISH_STOP_WORDS.union(spanish_stop_words) tfidf_vect= TfidfVectorizer(stop_words=set(my_stop_words)) I was been struggling with the argparse documentation in order to understad where I can call the...

How to change the format of subparser with argparse

python,python-3.x,argparse
I know there is max_help_position for the main parser created with the constructor but how to change subparsers format since I have some times very long command name and I want the help message to be aligned with it. #!/usr/bin/env python import argparse import subprocess parser = argparse.ArgumentParser(description="example", formatter_class=argparse.RawDescriptionHelpFormatter) subparsers...

How to localize Python's argparse module, without patching it?

python,localization,argparse
A localized command line application looks strange when some part of the messages are in the user language and some other parts, in English. I don't know if I messed up anything when I installed Python 3 from source, it seems there are no *.mo files, so argparse (among the whole)...

Can I check if a value was supplied by the default or by the user?

python,argparse
Is there a way, when using argparse, to tell whether a field has a value because the user specified it or because it was not specified and got the default value? Note: I would also like to consider the case where the user explicitly specifies the default value. I would...

argparse optional value for argument

python,python-3.x,command-line-interface,argparse
I want to distinguish between these three cases: The flag is not present at all python example.py; The flag is present but without a value python example.py -t; and The flag is present and has a value python example.py -t ~/some/path. How can I do this with Python argparse? The...

How do I check for a particular subparser?

python,argparse,subparsers
How do I check for a particular subparser? import argparse if __name__ == "__main__": mainparser = argparse.ArgumentParser() submainadder = mainparser.add_subparsers(title='subcommands') parser_ut = submainadder.add_parser('unittest') stuff = mainparser.parse_args() # if 'unittest' was selected: # do_things() ...

call method without args from argparse [closed]

python,argparse
I have a method I call from the command line using argparse. I also want to call that method from another method, in this case I get an error saying args is not defined. Is there a way around this, I have tried setting a default but I get the...

What is a common-lisp analogue of python's argparse?

python,common-lisp,argparse
What is a common-lisp analogue of python's argparse library for parsing command-line arguments?

Python argparse, provide different arguments based on parent argument value

python,dynamic,argparse,subparsers
here is what i would like to do : A command that looks like git command behavior. You don't get the same options whether you typed git commit or git checkout. But in my case i want to provide different arguments based on an argument value (a file name) like...

How can I append the values from an input file to the command line options using argparse?

python,command-line-arguments,argparse
Say I have a yaml input file (input.txt) that contains the following: names: [Bob, Jill] ages: [22, 31] county: somewhere my code to parse this: import yaml import argparse parser = argparse.ArgumentParser() parser.add_argument('--name', default=[], dest='names', action='append') parser.add_argument('--age', default=[], dest='ages', action='append') parser.add_argument('--county', dest='county') parser.add_argument( '--config-file', dest='config_file', type=argparse.FileType(mode='r')) args = parser.parse_args() print...

Using Argparse and Json together

python,json,argparse
I am a beginner to Python. I wanted to know if Argparse and JSON could be used together. Say, I have variables p,q,r I could add them to argparse as - parser.add_argument('-p','--param1',help='x variable', required=True) parser.add_argument('-q','--param2',help='y variable', required=True) parser.add_argument('-r','--param3',help='z variable', required=True) Now suppose I wanted to read the same variables from...

python argparse module AttributeError

python,argparse
I'm learning argparse module,and i write the code as follows: import argparse parser = argparse.ArgumentParser(description='Process some integers.') parser.add_argument('integers', metavar='N', type=int, nargs='+', help='an integer for the accumulator') parser.add_argument('--sum', dest='accumulate', action='store_const', const=sum, default=max, help='sum the integers (default: find the max)') args = parser.parse_args() print args.accumulate(args.integers) I saved it as argparse.py,but when i...

Python argparse boolean issue

python,arguments,argparse
I am having trouble setting a boolean value. My code is: training_pages_list_file = '' html_page_dir = '' clf_file_str = '' user_idf_param = False if __name__ == "__main__": parser = argparse.ArgumentParser(description='Classify some CraigsList Pages') parser.add_argument('csv_file', action='store') parser.add_argument('file_dir', action='store') parser.add_argument('clf_file', action='store') parser.add_argument('-i', action='store_true', help="include idf", dest=user_idf_param, default=False) args = parser.parse_args() However, this...

How can I call in2csv from a Python script?

python,csv,argparse
When I try calling the below code, I run into the following error: "You must specify a format when providing data via STDIN (pipe)." subprocess.call(["in2csv", "--format", "xls", a_file, ">", output_file], shell=True) I'm not sure why this is the case because I am telling it what the initial format is. I've...

Python3 Argparse metavar brackets parsed weirdly

python-3.x,formatting,argparse,brackets
I am using argparse in python3, and I get some strange things: A short version of code that I'm using is: argparser = argparse.ArgumentParser(description='add/remove items') argparser.add_argument('-a', action='append', metavar="Item(s)", help='add one or more items to the list') argparser.add_argument('-r', action='append', metavar="Item(s)", help='remove one or more items from the list') args = argparser.parse_args()...

Assertion when declaring required arguments with argparse and 'nargs=*' arguments

python,argparse,assertions
Here is the current code to parse the arguments : parser = argparse.ArgumentParser() parser.add_argument('-a', '--action', required=True, metavar='', nargs=1, help='{block|release|clear|show|show_extended|}') parser.add_argument('-i', '--interface', required=True, metavar='', nargs=1, help='interface name') parser.add_argument('-d', '--debug', action='store_true', help='debug prints') parser.add_argument('--ips', metavar='ips', nargs='*', help='ip addresses to block') parser.add_argument('--handles', metavar='handles', nargs='*',...

How to use top-level arguments with subparsers in argparse

python,argparse
In Python's argparse, how do you implement top-level arguments while still using commands implemented as subparsers? I'm trying to implement a --version argument to show the program's version number, but argparse is giving me error: too few arguments because I'm not specifying a sub-command for one of the subparsers. My...

argparse with different modes

python,argparse
I have some difficulties to use argparse. I have a GUI application that I want to use like this: GUI.exe => open GUI application GUI.exe -s file_directory1 => play GUIX.exe without open it GUI.exe -s file_directory1 -o file_directory2 => same as 2. It is not allowed to do : GUI.exe...

How can I avoid redundancy when I handle default arguments to modules that may also be parsed from the command line?

python,argparse
I'm trying to find a good way to avoid redundancy (that could possibly inject a risk for divergence) to my python module that can be executed from the command line. Consider a python module like this: #!/usr/bin/env python2.7 from argparse import ArgumentParser DEFAULT_A_ARG='alpha' def funky(a=DEFAULT_A_ARG, b=False): pass if __name__ ==...

Nested options with argparse

python,python-2.7,argparse
I'd like to have my python script take variable number of arguments depending on a particular choice. For example: python run.py foo python run.py bar X Y where choosing the option bar requires two additional arguments, say integer inputs, but foo requires no additional arguments. import argparse argparser = argparse.ArgumentParser()...

How can I easily create a python argparse argument with an inverse?

python-3.x,command-line-arguments,argparse
Using argparse with Python 3, I'd like to create a complementary pair of arguments: --log-file=~/some-default-log-filename.txt --no-log-file As the example implies, by default the log file arguments would have a default value (a filename). You could change that by specifying a different string value to --log-file, or remove the log file...

Change argparse usage message argument order

python,python-3.x,command-line-arguments,argparse
I'm using argparse in python3. In my script, I have some subparsers, a positional argument and some optional arguments. I have an optional argument to pass in any number of file paths, and it's using nargs='*'. The usage message for my script displays like this: usage: myprog.py subparser1 [-h] [--dir...

Parsing exclusive groups in Python

python,command-line-arguments,argparse
I have 2 group which are exclusive, you can define either arguments from group1 or group2 but group2 have to be exclusive within it's arguments too. parser = argparse.ArgumentParser() group_exclusive = parser.add_mutually_exclusive_group() sub_exclusive_1 = group_exclusive.add_argument_group() sub_exclusive_1.add_argument("-a") sub_exclusive_1.add_argument("-b") sub_exclusive_1.add_argument("-c") sub_exclusive_1.add_argument("-d") sub_exclusive_2 = group_exclusive.add_mutually_exclusive_group() sub_exclusive_2.add_argument("-AA")...

How to make a short and long version of a required argument using Python Argparse?

python,command-line-arguments,argparse
I want to specify a required argument called inputdir but I also would like to have a shorthand version of it called i. I don't see a concise solution to do this without making both optional arguments and then doing my own check. Is there a preferred practice for this...

python argparse — customizing error messages

python,error-handling,argparse
I want to generate custom error messages for particular usage errors in my command-line program that uses the argparse library. I know I can override the general presentation of the error by subclassing argparse.ArgumentParser: class HelpParser(argparse.ArgumentParser): def error(self, message): sys.stderr.write('error: %s\n' % message) sys.exit(2) parser = HelpParser(... ...) args =...

Python Subprocess Module: “Could not make directory”

python,subprocess,argparse
I have a Python script that takes in arguments from command-line using 'Argparser'. This is where I specify the location a particular file. Then, I invoke another command-line tool installed on my box, and pass on this location of the file to that tool. To function, the tool requires to...

How do I create a Python namespace (argparse.parse_args value)?

python,namespaces,argparse
To interactively test my python script, I would like to create a Namespace object, similar to what would be returned by argparse.parse_args(). The obvious way, >>> import argparse >>> parser = argparse.ArgumentParser() >>> parser.parse_args() Namespace() >>> parser.parse_args("-a") usage: [-h] : error: unrecognized arguments: - a Process Python exited abnormally with...

How to make positional argument optional in argparser based on some condition in python

python,python-2.7,argparse
I want to write a python code in which, based on some arguments passed from command line I want to make positional argument optional. For example, My python program is test.py, and with it I can give --init, --snap, --check options. Now if I have given --snap and --check option,...

Python argparse a list input

python,command-line-arguments,argparse
The code below accepts command line arguments for mode such as -m fizz and -m fizz bazz. This, as expected, passes the arguments to the main function as ['fizz', 'bazz'] (for the second example above). It seems user-unfriendly to pass command line arguments with spaces, so I'd like argparse to...

Allow argument/option to override positional argument

python,argparse
I am trying to make exclusion in my argparse parser. Basically what I want is to avoid --all option and filenames argument to be parsed (which I think succeeded). But I want to create also another check where if I only pass python reader.py read --all, the filenames argument will...

Python argparse second choices

python,python-3.x,argparse
By using Python argparse module I currently have this: usage: prog [-h] (-a {opt1,opt2} | -b {opt3,opt4}) arg. However, I would like to achieve the following (a second set of choices for option -a): usage: prog [-h] (-a {opt1,opt2} {opt5,opt6} | -b {opt3,opt4}) arg. I have not clue how to...

Specify default subcommand with positional arguments

python,argparse
I have read a similar question asked on SO, which doesn't address my own problem. For illustration purpose, say I have a Python program using argpase that provides two subcommands: copy and resume: prog copy src dest # src, dest positional, required prog resume id # id positional, required However,...

Python argparse doesn't show up help message correctly

python,arguments,argparse
I have to parse arguments where 4 of them have to be tied with each other, and last 2 have to be exclusive group 1 sub_exclusive_1 has 4 arguments where all of them must be defined if any of them have been defined. group 2 sub_exclusive_2 has 2 arguments where...

With argparse are subparsers inherently mutually exclusive?

python,python-2.7,argparse
I have a script with two primary functions, upgrade and provision. I'm using subparsers as a way to dictate the action being performed by the script but I want to avoid them being used together. This is a snippet of the code: import argparse def main(): parser = argparse.ArgumentParser() subparser...

Manage multiple following positional argument with argparse

python,command-line-arguments,argparse,args
I'm using this lib for parsing arguments in python : https://docs.python.org/2/library/argparse.html So far I have this: prog arg1 [-s arg2 [arg2 ...]] [-m arg3 [arg3 ...]] And I want this: prog arg1 -s arg2 [arg2 ...] -m arg3 [arg3 ...] Here is my python code: parser = argparse.ArgumentParser() parser.add_argument('path', type=str,...

Stop parsing after subparser

python,argparse
In my CLI script I am using argparse to take in a few optional arguments and then a positional argument. The positional argument is used to determine a subparser to use which in turn runs a function that calls an external program that takes its own arguments. So, the command-line...

argparse — requiring either 2 values or none for an optional argument

python,argparse
I'm trying to make an optional argument for a script that can either take no values or 2 values, nothing else. Can you accomplish this using argparse? # desired output: # ./script.py -a --> works # ./script.py -a val1 --> error # ./script.py -a val1 val2 --> works version 1...

Check if argparse optional argument is set or not

python,argparse
I would like to check whether an optional argparse argument has been set by the user or not. Can I safely check using isset? Something like this: if(isset(args.myArg)): #do something else: #do something else Does this work the same for float / int / string type arguments? I could set...

Python Port Scanner with arg parser doesn't properly take multiple arguments

python-2.7,argparse
I am trying to update some code from a great albeit dated book called "Violent Python." many of the examples used the deprecated optparse library and I have easily switched to argparse in MOST examples, however, my modified code doesn't work for this particular script IF I use more than...

Run python script with some of the argument that are optional

python,command-line-arguments,argparse,sys
I have gone through the sys documentation, however there is something that is still unclear to me. I have looked for some similar question on stackoverflow, but I haven't find anything useful (clearly any reference is appreciated!). I want to create a script - say foo.py - in which I...

Create parser with subcommands in argparse, customize positional argument(s)

python,command-line-arguments,argparse
I'm very new to this module so please bear with me. I have the following code: reader.py import argparse parent_parser = argparse.ArgumentParser(description="Read text files.") parent_parser.add_argument('filename', help='TXT file', type=file, nargs='+') parent_parser.add_argument('--verbose', '-v', action='store_true', help="Verbosity on") child_parser = parent_parser.add_subparsers(title="subcommand", help="Subcommand help") new_file_command = child_parser.add_parser('new', help="New text file") edit_file_command =...

Python Command Line Arguments: Calling a function

python,command-line,command-line-arguments,argparse,optparse
So I'm stuck on a project I'm working on that involves the command line in python. So basically, here's what I'm trying to accomplish: I have a set of functions in a class, say, def do_option1(self, param1, param2) : #some python code here def do_option2(self, param1): #some python code here...

How to use `--foo 1 --foo 2` style arguments with Python argparse?

python,arguments,argparse
nargs='+' doesn't work the way I expected: >>> import argparse >>> parser = argparse.ArgumentParser() >>> parser.add_argument("--name", dest='names', nargs='+') _StoreAction(option_strings=['--name'], dest='names', nargs='+', const=None, default=None, type=None, choices=None, help=None, metavar=None) >>> parser.parse_args('--name foo --name bar'.split()) Namespace(names=['bar']) I can "fix" this by using --name foo bar, but that's unlike other tools I've used, and...

Does argparse support multiple exclusive arguments?

python,argparse
Let's say I have two groups of arguments. You can use any number of arguments from each group but you cannot mix arguments between the groups. Is there a way to customize conflicting arguments in argparse module? I've tried using method add_mutually_exclusive_group but it's not what I'm looking for....

Manage arguments that receive no values

python,argparse
Hi All i am working on writing help menu for my application. Code is below import argparse parser = argparse.ArgumentParser(description="Hyla database backup application") group = parser.add_mutually_exclusive_group() group.add_argument("-g","--group",type=str,help="defines database groups") group.add_argument("-a","--all",help="backup all databases",action="store_true") group.add_argument("-D","--databases",nargs='+',help="take multiple databases as input") parser.add_argument("-r","--reference",help="backups reference...

[Python argparse]set the behaviour of an argument to be interactive if no value is given

python,default-value,argparse,interactive
I wonder if it is possible to change the behaviour of an argument depending if a value was given or not. Typically, I want to provide an interactive way to enter a password. example usages: $script.py => use the default argument value for argument 'p' $script.py -p mypass => use...

Change number of mandatory arguments depends on option (argparse)

python,argparse
I'd like to make with argparse simple command line: usage: downtime [-h] [-d] [-l | -f] [-s] host duration positional arguments: host Host to schedule. Local fqdn used if not specified. duration Duration of downtime (minutes), 15 if not specified optional arguments: -h, --help show this help message and exit...

How to set custom output handlers for argparse in Python?

python,python-2.7,logging,argparse
I have configured logger to print both onto terminal stdout and to a file so I can have an archive of logging messages that I can refer to. That is easily accomplished by adding a FileHandler to your logging object. Easy peasy. What I want to accomplish now is to...

Program along with all the switches, runs great, but argparse '--help' throws a lot of errors [closed]

python,debugging,argparse
I am using argparse in Python to handle arguments in my program. For instance, as seen below, if I use the argument '-p' a specific module is execute. Now, all arguments and the program runs great. But when I try to get the '--help' for my program it crashes horribly...

Argparse pattern where input filenames are given through a file or a list of filenames on the command line

python,python-2.7,argparse
Does argparse support a pattern such as: foo.py {-f list_of_filenames.txt|file [file ...]} I achieve this at the moment with the following argparse definition: parser = argparse.ArgumentParser() parser.add_argument("--file", "-f") parser.add_argument("files", nargs="*") and performing the mutual exclusivity + required check in my code rather than letting argparse do the check. Can argparse...

Trying to use argparse and sys.argv without sys.argv needing to be used each runtime

python,argparse
In the script I'm writing, I am using argparse for the main arguments (for --help, --todo, etc.) but trying to use sys.argv to get the name of a file given as the third argument for --add. I was using this: def parseargs(): parser = argparse.ArgumentParser(add_help=False) parser.add_argument("--help", help="Print argument usage", action="store_true")...

'ArgumentParser' object has no attribute 'parse_arg'

python,argparse
I think my code belowis correct. It attempts to make a 'checkRoot' option possible from command line. But even the simplest code does not work, with 'ArgumentParser' object has no attribute 'parse_arg' The code is shown below. #!/usr/bin/env python import argparse if __name__ == "__main__": message='[setting] ... ' parser =...

How can I list all registered arguments from an ArgumentParser instance?

python,argparse
Couldn't find any existing method for it so I wonder if there is a hack?

importing a python script from another script and running it with arguments

python,argparse
I have a python script which has been packaged up as a command line script (dbtoyaml.py in Pyrseas since you ask). I am running another python script from which I want to call this script. Is there no way to import the module and artificially populate the required arguments from...

Pass an optional list to argparse

python,argparse
Is there a more elegant way to pass an optional list of integers to argparse than to pass a delimited string and parse it later? I also have a positional argument. parser.add_argument('--ids', type=int, nargs='+') parser.add_argument('cmd') doesn't work, because argparse attempts to grab cmd and complains that it isn't an integer....

How to avoid use of a particular optional parameter in python

python,argparse
Hi All i am working on creation of help menu in python .Below is the code. __author__ = 'akthakur' import argparse import database_helper import sys import database_operations_full import withoutTransactionaldata print("Database Backup and restoration Application".center(60,'*')) parser = argparse.ArgumentParser(description="My database backup application") group = parser.add_mutually_exclusive_group() group.add_argument("-g","--group",type=str,help="defines database groups",default='nothing') group.add_argument("-a","--all",help="backup all...

python argparse always set defaults related to an optional argument

python,default,argparse,optional-parameters
I use python 3, i want to set argparse to always set the default key in relation to a predefined optional argument of my choice. E.g. I pass some input files to the script. An optional argument specify if the input file should be rotated by the script. I get...

How do I replace the built in '-h' action in python using argparse?

python,argparse
I am creating a command line tool in python, and I'm using argparse to parse my input. I want to use '-h' as an action, but that is already automatically assigned to --help. How can I override this and have an -h action?...