argparse

argparse - Combining parent parser, subparsers and default values

笑着哭i 提交于 2019-11-29 06:12:39
I wanted to define different subparsers in a script, with both inheriting options from a common parent, but with different defaults. It doesn't work as expected, though. Here's what I did: import argparse # this is the top level parser parser = argparse.ArgumentParser(description='bla bla') # this serves as a parent parser base_parser = argparse.ArgumentParser(add_help=False) base_parser.add_argument('-n', help='number', type=int) # subparsers subparsers = parser.add_subparsers() subparser1= subparsers.add_parser('a', help='subparser 1', parents=[base_parser]) subparser1.set_defaults(n=50)

Don't parse options after the last positional argument

允我心安 提交于 2019-11-29 05:45:44
I'm writing a wrapper around the ssh command line client. After the first positional argument that's part of command , all further options should also be treated as positional arguments. Under optparse , I believe this would be done with disable_interspersed_args . Presently I have something like this: parser = argparse.ArgumentParser() parser.add_argument('--parallel', default=False, action='store_true') # maybe allow no command? this would ssh interactively into each machine... parser.add_argument('command', nargs='+') args = parser.parse_args() But if options are passed as part of the

Python 命令行之旅:使用 argparse 实现 git 命令

梦想的初衷 提交于 2019-11-29 05:42:40
作者:HelloGitHub- Prodesire HelloGitHub 的《讲解开源项目》系列,项目地址: https://github.com/HelloGitHub-Team/Article 前言 在前面三篇介绍 argparse 的文章中,我们全面了解了 argparse 的能力,相信不少小伙伴们都已经摩拳擦掌,想要打造一个属于自己的命令行工具。 本文将以我们日常工作中最常见的 git 命令为例,讲解如何使用 argparse 库来实现一个真正可用的命令行程序。 本系列文章默认使用 Python 3 作为解释器进行讲解。 若你仍在使用 Python 2,请注意两者之间语法和库的使用差异哦~ git 常用命令 大家不妨回忆一下,平时最常使用 git 子命令都有哪些? 当你写好一段代码或增删一些文件后,会用如下命令查看文件状态: git status 确认文件状态后,会用如下命令将的一个或多个文件(夹)添加到暂存区: git add [pathspec [pathspec ...]] 然后使用如下命令提交信息: git commit -m "your commit message" 最后使用如下命令将提交推送到远程仓库: git push 我们将使用 argparse 和 gitpython 库来实现这 4 个子命令。 关于 gitpython gitpython 是一个和

Python: Typehints for argparse.Namespace objects

瘦欲@ 提交于 2019-11-29 05:13:29
问题 Is there a way to have Python static analyzers (e.g. in PyCharm, other IDEs) pick up on Typehints on argparse.Namespace objects? Example: parser = argparse.ArgumentParser() parser.add_argument('--somearg') parsed = parser.parse_args(['--somearg','someval']) # type: argparse.Namespace the_arg = parsed.somearg # <- Pycharm complains that parsed object has no attribute 'somearg' If I remove the type declaration in the inline comment, PyCharm doesn't complain, but it also doesn't pick up on

argparse: flatten the result of action='append'

橙三吉。 提交于 2019-11-29 04:04:53
I'd like to make a script that supports an argument list of the form ./myscript --env ONE=1,TWO=2 --env THREE=3 Here's my attempt: import argparse parser = argparse.ArgumentParser() parser.add_argument( '--env', type=lambda s: s.split(','), action='append', ) options = parser.parse_args() print options.env $ ./myscript --env ONE=1,TWO=2 --env THREE=3 [['ONE=1', 'TWO=2'], ['THREE=3']] Sure I can fix this in postprocessing: options.env = [x for y in options.env for x in y] but I'm wondering if there's some way to get the flattened list directly from argparse, so that I don't have to maintain a

Case insensitive argparse choices

此生再无相见时 提交于 2019-11-29 02:47:53
Is it possible to check argparse choices in case-insensitive manner? import argparse choices = ["win64", "win32"] parser = argparse.ArgumentParser() parser.add_argument("-p", choices=choices) print(parser.parse_args(["-p", "Win32"])) results in: usage: choices.py [-h] [-p {win64,win32}] choices.py: error: argument -p: invalid choice: 'Win32' (choose from 'win64','win32') Transform the argument into lowercase by using type = lambda s : s.lower() for the -p switch. As pointed out by chepner in the comments, since str.lower is already an appropriate function, the lambda wrapper is not necessarily

How do I avoid the capital placeholders in python's argparse module?

我的梦境 提交于 2019-11-29 02:31:14
There was a question that asked where they come from, and the accepted answer was a bunch of links to tutorials and source code. Explanation for argparse python modul behaviour: Where do the capital placeholders come from? None of it was helpful to me, I want to either get rid of them, or know their purpose. For example, a line like this: parser.add_argument('-c', '--chunksize', type=int, help='chunk size in bits') produces garbage like this: optional arguments: -h, --help show this help message and exit -c CHUNKSIZE, --chunksize CHUNKSIZE chunk size in bits and if I try with an empty metavar

python argparse - either both optional arguments or else neither one

痴心易碎 提交于 2019-11-29 02:26:47
问题 I have a program that uses a default name and password. I'm using argparse to allow the user to specify command line options, and I would like to enable the user to provide the program with a different name and password to use. So I have the following: parser.add_argument( '-n', '--name', help='the login name that you wish the program to use' ) parser.add_argument( '-p', '--password', help='the password to log in with.' ) But it doesn't make any sense to specify only the name or only the

Python argparse required=True but --version functionality?

痞子三分冷 提交于 2019-11-28 23:04:22
In all my scripts I use the standard flags --help and --version , however I cannot seem to figure out how to make a --version with parser.add_argument(..., required=True) . import sys, os, argparse parser = argparse.ArgumentParser(description='How to get --version to work?') parser.add_argument('--version', action='store_true', help='print version information') parser.add_argument('-H', '--hostname', dest='hostname', required=True, help='Host name, IP Address') parser.add_argument('-d', '--database', dest='database', required=True, help='Check database with indicated name') parser.add_argument

directory path types with argparse

﹥>﹥吖頭↗ 提交于 2019-11-28 22:37:53
问题 My python script needs to read files from a directory passed on the command line. I have defined a readable_dir type as below to be used with argparse for validating that the directory passed on the command line is existent and readable. Additionally, a default value (/tmp/non_existent_dir in the example below) has also been specified for the directory argument. The problem here is that argparse invokes readable_dir() on the default value even in a situation where a directory argument is