argparse

python, argparse: enable input parameter when another one has been specified

橙三吉。 提交于 2019-11-30 17:57:58
In my python script, I want to be able to use an optional input parameter only when another optional parameter has been specified. Example: $ python myScript.py --parameter1 value1 $ python myScript.py --parameter1 value1 --parameter2 value2 But NOT: $ python myScript.py --parameter2 value2 How do I do this with argparse? Thanks! Use a custom action: import argparse foo_default=None class BarAction(argparse.Action): def __call__(self,parser,namespace,values,option_string=None): didfoo=getattr(namespace,'foo',foo_default) if(didfoo == foo_default): parser.error( "foo before bar!") else: setattr

How to modify the metavar for a positional argument in pythons argparse?

≯℡__Kan透↙ 提交于 2019-11-30 17:37:13
In the argparse package the metavar parameter modifies the displayed help message of a program. The following program is not intended to work, it is simply used to demonstrate the behavior of the metavar parameter. import argparse if __name__ == '__main__': parser = argparse.ArgumentParser(description = "Print a range.") parser.add_argument("-range1", nargs = 3, type = int, help = "Specify range with: start, stop, step.", metavar = ("start", "stop", "step")) parser.add_argument("-range2", nargs = 3, type = int, help = "Specify range with: start, stop, step.", metavar = "r2") The corresponding

argparse with required subcommands

落爺英雄遲暮 提交于 2019-11-30 16:52:13
With python's argparse, how do I make a subcommand a required argument? I want to do this because I want argparse to error out if a subcommand is not specified. I override the error method to print help instead. I have 3-deep nested subcommands, so it's not a matter of simply handling zero arguments at the top level. In the following example, if this is called like so, I get: $./simple.py $ What I want it to do instead is for argparse to complain that the required subcommand was not specified: import argparse class MyArgumentParser(argparse.ArgumentParser): def error(self, message): self.print

Restricting values of command line options

徘徊边缘 提交于 2019-11-30 16:34:19
问题 How do I restrict the values of the argparse options? In the below code sau option should only accept a number of 0 or 1 and bg should only allow an integer. How can I implement this? import os import sys, getopt import argparse def main (): parser = argparse.ArgumentParser(description='Test script') parser.add_argument('-sau','--set',action='store',dest='set',help='<Required> Set flag',required=True) parser.add_argument('-bg','--base_g',action='store',dest='base_g',help='<Required> Base g'

python argparse file extension checking

谁都会走 提交于 2019-11-30 15:56:32
can argparse be used to validate filename extensions for a filename cmd line parameter? e.g. if i have a python script i run from the cmd line: $ script.py file.csv $ script.py file.tab $ script.py file.txt i would like argparse to accept the 1st two filename cmd line options but reject the 3rd i know you can do something like this: parser = argparse.ArgumentParser() parser.add_argument("fn", choices=["csv","tab"]) args = parser.parse_args() to specify two valid choices for a cmd line option what i'd like is this: parser.add_argument("fn", choices=["*.csv","*.tab"]) to specify two valid file

(semi-) automatic generation of argparsers for functions

。_饼干妹妹 提交于 2019-11-30 15:55:01
问题 tldnr: given a function, is there a way to automatically create an ArgumentParser from its signature? I've got a bunch of functions that I'd like to expose to the command line. So basically, a module: def copy(foo, bar, baz): ... def move(from, to): ... def unlink(parrot, nomore=True): ... if __name__ == '__main__': argparse stuff which can be called from the command line like this: python commands.py move spam ham python commands.py unlink --parrot Polly Although this is pretty

(semi-) automatic generation of argparsers for functions

泪湿孤枕 提交于 2019-11-30 15:13:41
tldnr: given a function, is there a way to automatically create an ArgumentParser from its signature? I've got a bunch of functions that I'd like to expose to the command line. So basically, a module: def copy(foo, bar, baz): ... def move(from, to): ... def unlink(parrot, nomore=True): ... if __name__ == '__main__': argparse stuff which can be called from the command line like this: python commands.py move spam ham python commands.py unlink --parrot Polly Although this is pretty straightforward to implement, there's a lot of wiring involved: parser = argparse.ArgumentParser(...) subparsers =

How to make python's argparse generate Non-English text?

元气小坏坏 提交于 2019-11-30 14:11:11
问题 The argparse module "automatically generates help and usage messages". I can give Non-English names to the arguments and provide Non-English help texts; but the help output then becomes a mixture of at least two languages, because terms like usage , positional arguments , optional arguments and show this help message and exit are automatically generated in English. How can I replace this English output with translations? Preferably, I would like to provide the translations within the script,

python argparse - add action to subparser with no arguments?

依然范特西╮ 提交于 2019-11-30 13:50:14
问题 I am adding subparsers to my parser to simulate subcommands functionality (for example code see: Simple command line application in python - parse user input?). Now I want to add a quit subparser/command that takes no arguments and has a "quit" action attached. Is it possible ? How can I go about it ? 回答1: The documentation for subcommands gives two examples of how to identify the subparser. https://docs.python.org/dev/library/argparse.html#sub-commands One is to give the add_subparsers a

argparse简要用法总结

拟墨画扇 提交于 2019-11-30 13:21:36
转: http://vra.github.io/2017/12/02/argparse-usage/ argparse 是python自带的命令行参数解析包,可以用来方便地读取命令行参数,当你的代码需要频繁地修改参数的时候,使用这个工具可以将参数和代码分离开来,让你的代码更简洁,适用范围更广。 argparse使用比较简单,常用的功能可能较快地实现出来,下面我分几个步骤, 以Python3为例 ,逐渐递增地讲述argparse的用法。 1. 基本框架 下面是使用argparser从命令行获取用户名,然后打印’Hello ‘+ 用户名,假设python文件名为 print_name.py : # file-name:print_name.pyimport argparsedef get_parser(): parser = argparse.ArgumentParser(description="Demo of argparse") parser.add_argument('--name', default='Great') return parserif __name__ == '__main__': parser = get_parser() args = parser.parse_args() name = args.name print('Hello {}'.format