argparse

Python argparse: Make at least one argument required

半世苍凉 提交于 2019-11-28 17:21:28
I've been using argparse for a Python program that can -process , -upload or both: parser = argparse.ArgumentParser(description='Log archiver arguments.') parser.add_argument('-process', action='store_true') parser.add_argument('-upload', action='store_true') args = parser.parse_args() The program is meaningless without at least one parameter. How can I configure argparse to force at least one parameter to be chosen? UPDATE: Following the comments: What's the Pythonic way to parametrize a program with at least one option? if not (args.process or args.upload): parser.error('No action requested,

Python argparse and controlling/overriding the exit status code

梦想与她 提交于 2019-11-28 17:12:52
Apart from tinkering with the argparse source, is there any way to control the exit status code should there be a problem when parse_args() is called, for example, a missing required switch? Rob Cowie I'm not aware of any mechanism to specify an exit code on a per-argument basis. You can catch the SystemExit exception raised on .parse_args() but I'm not sure how you would then ascertain what specifically caused the error. EDIT: For anyone coming to this looking for a practical solution, the following is the situation: ArgumentError() is raised appropriately when arg parsing fails. It is passed

Custom tab completion in python argparse

徘徊边缘 提交于 2019-11-28 17:05:52
问题 How to get shell tab completion cooperating with argparse in a Python script? #!/usr/bin/env python import argparse def main(**args): pass if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('positional', choices=['spam', 'eggs']) parser.add_argument('--optional', choices=['foo1', 'foo2', 'bar']) args = parser.parse_args() main(**vars(args)) With an executable flag set on the .py file, the expected results should be something like: $ ./example.py sp<tab> ->

python argh/argparse: How can I pass a list as a command-line argument?

大城市里の小女人 提交于 2019-11-28 16:34:36
问题 I'm trying to pass a list of arguments to a python script using the argh library. Something that can take inputs like these: ./my_script.py my-func --argA blah --argB 1 2 3 4 ./my_script.py my-func --argA blah --argB 1 ./my_script.py my-func --argA blah --argB My internal code looks like this: import argh @argh.arg('--argA', default="bleh", help='My first arg') @argh.arg('--argB', default=[], help='A list-type arg--except it\'s not!') def my_func(args): "A function that does something" print

Python argparse command line flags without arguments

谁说胖子不能爱 提交于 2019-11-28 15:19:50
How do I add an optional flag to my command line args? eg. so I can write python myprog.py or python myprog.py -w I tried parser.add_argument('-w') But I just get an error message saying Usage [-w W] error: argument -w: expected one argument which I take it means that it wants an argument value for the -w option. What's the way of just accepting a flag? I'm finding http://docs.python.org/library/argparse.html rather opaque on this question. Jdog As you have it, the argument w is expecting a value after -w on the command line. If you are just looking to flip a switch by setting a variable True

Argparse: Required arguments listed under “optional arguments”?

青春壹個敷衍的年華 提交于 2019-11-28 15:06:19
I use the following simple code to parse some arguments; note that one of them is required. Unfortunately, when the user runs the script without providing the argument, the displayed usage/help text does not indicate that there is a non-optional argument, which I find very confusing. How can I get python to indicate that an argument is not optional? Here is the code: import argparse if __name__ == '__main__': parser = argparse.ArgumentParser( description='Foo') parser.add_argument('-i','--input', help='Input file name', required=True) parser.add_argument('-o','--output', help='Output file name

Allow positional command-line arguments with nargs to be seperated by a flag

穿精又带淫゛_ 提交于 2019-11-28 13:34:50
I have a program using argparse. It takes 1 required positional argument, 1 optional positional argument, and 1 flag argument. Something like: usage: test.py [-h] [-a A] b [c] So, I tried using this: parser = argparse.ArgumentParser() parser.add_argument('-a') parser.add_argument('b') parser.add_argument('c', nargs='?', default=None) print(parser.parse_args()) Which works fine for test.py B C -a A and test.py -a A B C . But when I do test.py B -a A C , it throws an error: $ python3 test.py B -a A C usage: test.py [-h] [-a A] b [c] test.py: error: unrecognized arguments: C So, how can I get it

python——高级模块话题

 ̄綄美尐妖づ 提交于 2019-11-28 13:06:18
1.1 最小化from *的破坏 from *会把所有变量名复制出去,导入者可能得到超出它需要的分布(包括会覆盖导入者内的变量名的变量名)。 在__init__.py中使用 __all__ 则可以保证from *语句只会把__all__列表中的这些变量名复制出来。另外对于模块中以 _x 形式的变量是指出不被复制的变量名。 1.2混合用法模型:__name__和__main__ 每个模块都有一个名为__main__的内置属性,python会自动设置该属性: 如果文件是以顶层程序文件执行,在启动时,__name__就会设备为字符串"__main__"。 如果文件被导入,__name__就会改成客户端所了解的模块名。 结果就是模块可以检测自己的__name__,来确定他是执行还是在导入。 1.3 以__name__进行单元测试 这就是在pycharm中常用的方法: if __name__ == '__main__': #这种语法来进行单元测试 import sys if len(sys.argv) ==1: # sys.argv列表包含了命令行参数,是一个字符串列表,其中你第一个总是将要运行的脚本名 print('without argv') else: print(sys.argv[1]) 其实,更多的在平时看到的可能是使用argparse模块。argparse是一个命令行工具

How to handle CLI subcommands with argparse

╄→гoц情女王★ 提交于 2019-11-28 11:33:00
I need to implement a command line interface in which the program accepts subcommands. For example, if the program is called “foo”, the CLI would look like foo cmd1 <cmd1-options> foo cmd2 foo cmd3 <cmd3-options> cmd1 and cmd3 must be used with at least one of their options and the three cmd* arguments are always exclusive. I am trying to use subparsers in argparse, but with no success for the moment. The problem is with cmd2 , that has no arguments: if I try to add the subparser entry with no arguments, the namespace returned by parse_args will not contain any information telling me that this

How can I get argparse in Python 2.6?

送分小仙女□ 提交于 2019-11-28 10:39:54
I have some Python 2.7 code written that uses the argparse module. Now I need to run it on a Python 2.6 machine and it won't work since argparse was added in 2.7. Is there anyway I can get argparse in 2.6? I would like to avoid rewriting the code, since I will be transferring this kind of code between the machines often. Upgrading python is not an option. I should have clarified that the ideal solution would be something that does not require module installation. You can install it via pip or easy_install: https://pypi.python.org/pypi/argparse user3517231 On Centos, Scientific, or Redhat, you