argparse

How to add optional or once arguments?

爱⌒轻易说出口 提交于 2019-12-04 09:42:09
How can I add an argument that is optional and must not be specified multiple times? Valid: $ ./my.py $ ./my.py --arg MyArgValue Invalid: $ ./my.py --arg MyArgValue --arg ThisIsNotValid If I add an argument like: parser.add_argument('--arg', type=str) The invalid example results in a string ThisIsNotValid . I would expect a parser error. Create a custom action that raises an exception if the same argument is seen twice. When the parser catches the exception, it prints the usage and a nicely-formatted error message. import argparse class Highlander(argparse.Action): def __call__(self, parser,

max_help_position is not works in python argparse library

老子叫甜甜 提交于 2019-12-04 08:14:39
Hi colleagues I have the code (max_help_position is 2000): formatter_class=lambda prog: argparse.HelpFormatter(prog, max_help_position=2000) parser = argparse.ArgumentParser(formatter_class=formatter_class) subparsers = parser.add_subparsers(title="Commands", metavar="<command>") cmd_parser = subparsers.add_parser('long_long_long_long_long_long_long', help='- jksljdalkjda', formatter_class=formatter_class) args = parser.parse_args(['-h']) print args we have optional arguments: -h, --help show this help message and exit Commands: <command> long_long_long_long_long_long_long - jksljdalkjda small

How to design object oriented subparsers for argparse?

与世无争的帅哥 提交于 2019-12-04 07:09:51
问题 Problem I'm building a package manager that has a lot of sub-commands. I would prefer to have a class structure similar to the following. class ListCommand: def __init__(self): name = "list" alias = "ls" short_description = "A useful simple line that explains the command" def help(self): # Display help def command(self): # do stuff when command is called How do I write subparser to work with something like this ? I found an example online that does something similar without subparsers. 回答1: A

How to include one positional argument into argparse mutually exclusive group?

爱⌒轻易说出口 提交于 2019-12-04 06:51:41
I know that does not make sense multiple positional arguments into a mutually exclusive group because you can't say who is who. But I need to include ONE positional argument into that. What I need: $ myprogram -h usage: myprogram [-h] [--delete value | --update value | value] Where positional value is the default action (kind of "--include"). ( myprogram without arguments must be valid too). My first attempt (this doesn't works): parser = ArgumentParser() group = parser.add_mutually_exclusive_group() group.add_argument('--delete', metavar='value') group.add_argument('--update', metavar='value'

named argument in argparse [duplicate]

不羁的心 提交于 2019-12-04 06:14:47
This question already has answers here : Closed 3 years ago . Simple argparse example wanted: 1 argument, 3 results (10 answers) I want to send arguments to script by their name (something like kwargs). I tried something like this but it's not doing what I want: (let's say it's written in script.py) import argparse parser = argparse.ArgumentParser() parser.add_argument("name") args = parser.parse_args() and then writing in commant line: script.py name = david another thing, let's say I have few named argument in argparse If I will send them not in the order they are declared will it still work

optional python arguments without dashes but with additional parameters?

独自空忆成欢 提交于 2019-12-04 05:42:00
what I'd like to do in Python is accept arguments of the following format: script.py START | STOP | STATUS | MOVEABS <x> <y> | MOVEREL <x> <y> So in other words, I don't want to deal with hyphens; I have multiple possibilities, ONE of which is required; Each is mutually exclusive; Some of the commands (E.G. moveabs and moverel) have additional required arguments, but these args and should not be present with any other argument. Can this be done in python and would I use argparse or something else? Thanks. hpaulj add_parser with subparsers would do the trick import argparse parser = argparse

Can argparse accept argument value as key=val pairs

你说的曾经没有我的故事 提交于 2019-12-04 05:24:53
问题 I am trying to implement below option by using argparse(can't use any other tool like docopt because of project requirement):- cli.py --conf key1=value1, key2=value2, kay3=value3 or cli.py --conf key1=value1 key2=value2 key3=value3 So far I have tried type=json.loads or dict but not helping. One possible solution is to use type=str and then later parse it to dict . Do you guys know any other better solution which I am missing.. Thanks in advance. Note- Can't use --key1=value1 --key2=value2 -

Python doctest for shell scripts that test argument parsing without polluting docstring with os.popen()

一笑奈何 提交于 2019-12-04 04:41:00
Is there a way to write a python doctest string to test a script intended to be launched from the command line (terminal) that doesn't pollute the documentation examples with os.popen calls? #!/usr/bin/env python # filename: add """ Example: >>> import os >>> os.popen('add -n 1 2').read().strip() '3' """ if __name__ == '__main__': from argparse import ArgumentParser p = ArgumentParser(description=__doc__.strip()) p.add_argument('-n',type = int, nargs = 2, default = 0,help = 'Numbers to add.') p.add_argument('--test',action = 'store_true',help = 'Test script.') a = p.parse_args() if a.test:

Using Argparse with Google Admin API

我们两清 提交于 2019-12-04 04:28:14
问题 I am using Google's Python API to pull down auditing information, but I can't get the parent group arguments for argparse (which appear to be required for API access) and my own arguments (e.g. passing in a date) to work together. Code: import pprint import sys import re import httplib2 import json import collections import argparse from oauth2client import client from apiclient import sample_tools from apiclient import discovery from oauth2client.client import AccessTokenRefreshError from

Python's argparse choices constrained printing

回眸只為那壹抹淺笑 提交于 2019-12-04 04:28:14
问题 Currently I want Python's argparse module to only print out '1 - 65535' rather than {1, 2, 3, ... 65535}, but the documentation doesn't seem to provide any method for this. Any suggestions? 回答1: You can alter the way defaults are formatted by setting the formatter_class option. I'd subclass the HelpFormatter class to alter the way it formats your choices values. This class is officially an "implementation detail" but I doubt it'll change much with newer python versions. The _metavar_formatter