标签: argparse

Python的argparse permute参数顺序可以像gnu getopt一样吗?

GNU getopt和使用它的命令行工具允许交叉选项和参数,称为置换选项(参见http://www.gnu.org/software/libc/manual/html_node/Using-Getopt.html#Using -Getopt).Perl的Getopt :: Long模块也支持这个(使用qw(:config gnu_getopt)).argparse似乎不支持(甚至提及)置换选项.

有许多与arg/opt命令相关的SO问题,但似乎没有人回答这个问题:argparse可以像getopt那样置换参数顺序吗?

用例是一个典型的命令行签名,如GNU sort:

sort [opts] [files]
Run Code Online (Sandbox Code Playgroud)

其中1)选项和文件被置换,以及2)文件列表可以包含零个或多个参数.

例如:

import argparse
p = argparse.ArgumentParser();
p.add_argument('files',nargs='*',default=['-']);
p.add_argument('-z',action='store_true')

p.parse_args(['-z','bar','foo']) # ok
p.parse_args(['bar','foo','-z']) # ok
p.parse_args(['bar','-z','foo']) # not okay
usage: ipython [-h] [-z] [files [files ...]]
Run Code Online (Sandbox Code Playgroud)

我试过了:

  • p.parse_known_args - 没有抱怨,但实际上并没有置换,并且它不会忽略看起来像无效选项的参数(例如,--bogus或-b above).
  • p.add_argument('files',nargs = argparse.REMAINDER) - 选项-z包含在文件中,除非在位置args之前
  • p.add_argument( '文件',NARGS = '*',动作= '追加');

我想实现一些接近上面GNU排序原型的东西.我对可以为每个文件指定的标志不感兴趣(例如,-f file1 -f file2).

python command-line getopt command-line-arguments argparse

9
推荐指数
1
解决办法
1644
查看次数

argparse:获取未定义的参数数量

我正在构建一个脚本,它使用参数来配置行为,并应读取未定义数量的文件.使用以下代码可以读取一个文件.有没有办法实现这一点,而不必设置另一个参数,告诉脚本应该读取多少文件?

parser = argparse.ArgumentParser()
parser.add_argument("FILE", help="File to store as Gist")
parser.add_argument("-p", "--private", action="store_true", help="Make Gist private")
Run Code Online (Sandbox Code Playgroud)

python argparse

9
推荐指数
2
解决办法
8955
查看次数

在argparse中设置互斥集

我正在使用一个互斥的组,但我不止一个选项在一个独家集合中.我希望我的用法看起来像这样:

[--conf CONF | --hostname HOSTNAME --port PORT]
Run Code Online (Sandbox Code Playgroud)

知道如何实现这一点吗?我已经尝试将参数组添加到互斥组,但互斥部分不适用于子组,它允许--conf file --hostname host --port 22

python argparse

9
推荐指数
1
解决办法
453
查看次数

如何使用python argparse将add_argument_group添加到add_mutually_exclusive_group

我正在尝试实现以下内容:

$ prog.py -h
usage: prog.py [-h] [-s | -m] [[-y [year]] | [[-1 | -3] [month] [year]]]
Run Code Online (Sandbox Code Playgroud)

但是,无论我如何玩add_argument_group和add_mutually_exclusive_group,

#!/usr/bin/env python

import argparse

def main(opt):
    print(opt)

if __name__ == '__main__':

    parser = argparse.ArgumentParser()
    bar = parser.add_mutually_exclusive_group()
    bar.add_argument('-s', action='store_true', default=True)
    bar.add_argument('-m', action='store_true', default=False)

    #bar = parser.add_argument_group()
    bar = parser.add_mutually_exclusive_group()
    bar.add_argument('-y', metavar='year', type=int,
                     dest='iy', nargs='?', default=0)
    baz = bar.add_argument_group()
    g_13 = baz.add_mutually_exclusive_group()
    g_13.add_argument('-1', dest='i1',
                      help='Display single month output.',
                      action='store_true', default=True)
    g_13.add_argument('-3', dest='i3',
                      help='Display prev/current/next month output.',
                      action='store_true', default=False)
    #aaa = bar.add_argument_group()
    baz.add_argument(metavar='month', …
Run Code Online (Sandbox Code Playgroud)

python argparse

9
推荐指数
1
解决办法
1万
查看次数

从另一个脚本导入python脚本并使用参数运行它

我有一个python脚本,它已被打包为命令行脚本(因为你问的问题,pyrseas中的dbtoyaml.py).

我正在运行另一个python脚本,我想从中调用此脚本.有没有办法导入模块并从我的第二个脚本中人工填充所需的参数,以避免更改任何pyrseas代码?

from pyrseas import dbtoyaml -- My initial script, which also takes arguments dbtoyaml.main(['-m','-H MYHOSTNAME' .... other options])

还没有为我工作.

我收到一个奇怪的错误:

usage: checkSchemaChanges.py [-h] [-H HOST] [-p PORT] [-U USERNAME] [-W]
                         [-c CONFIG] [-r REPOSITORY] [-o OUTPUT]
                         [--version] [-m] [-O] [-x] [-n SCHEMA]
                         [-N SCHEMA] [-t TABLE] [-T TABLE]
                         dbname
checkSchemaChanges.py: error: unrecognized arguments: MYHOSTNAME mydatabaseuser
Run Code Online (Sandbox Code Playgroud)

这是我的新脚本(checkSchemaChanges.py,底部的MYHOSTNAME和mydatabaseuser)和dbtoyaml中的参数的混合,这些都是正确的.

这可能是令人困惑的argparse的双重参数吗?

python argparse

9
推荐指数
2
解决办法
5346
查看次数

Python argparse:在帮助条目之间插入空白行

使用argparse时,传递--help给程序会生成帮助文本.不幸的是,它很难阅读,因为选项之间没有空行.这是一个摘录来说明:

optional arguments:
  -h, --help            show this help message and exit
  -u FILENAME, --up-sound FILENAME
                        The sound to play when the network comes up. Default:
                        "/path/to/some/sound/file.wav"
  -d FILENAME, --down-sound FILENAME
                        The sound to play when the network goes down. Default:
                        "/path/to/some/other/sound/file.wav"
  -p EXECUTABLE, --player EXECUTABLE
                        The program to use to play sounds. Default: "play"
  -s, --silent          If specified, network_monitor.py will not play any
                        sounds.
  -c, --no-clear-screen
                        If specified, screen will not be cleared (nor extra
                        blank lines added) …
Run Code Online (Sandbox Code Playgroud)

python argparse

9
推荐指数
1
解决办法
810
查看次数

python argparse中的多行帮助显示

我在Python2.7中使用argparse,我想在参数的帮助文本中显示多行.

我的代码如下:

import argparse

parser = argparse.ArgumentParser(description='details',
        usage='use "%(prog)s --help" for more information')

parser.add_argument('--argument', default=None, type=sometype,
        help='''
             First line  \n
             Second line \n
             \n
             More lines  \n
             ''')
Run Code Online (Sandbox Code Playgroud)

我想在调用--help时多行打印出帮助信息.但是,输出如下所示.

First line Second line More lines
Run Code Online (Sandbox Code Playgroud)

我知道我可以通过将每行的字符串相加来解决问题.

parser.add_argument('--argument', default=None, type=sometype,
        help='First line  \n' +
             'Second line \n' +
             '\n'             + 
             'More lines')
Run Code Online (Sandbox Code Playgroud)

但是我想在帮助文本中添加几十行.我想知道有没有一种方便的方法将帮助文本分成多行?

而且,似乎帮助消息中的一行中可以显示的字符数有一个上限,在我的情况下为54.这种限制是否依赖于系统,是否有办法增加上限?

python argparse

9
推荐指数
2
解决办法
1万
查看次数

python argparse - 传递值WITHOUT命令行

我想我不理解python的argparse基本知识.

我正在尝试将Google YouTube API用于python脚本,但我不了解如何在不使用命令行的情况下将值传递给脚本.

例如,这里是对API的例子.github和其他地方的示例将此示例显示为从命令行调用,在调用脚本时从该命令行传递argparse值.

我不想使用命令行.我正在构建一个使用装饰器获取用户登录凭据的应用程序,当该用户想要上传到他们的YouTube帐户时,他们会提交一个表单,然后调用此脚本并将argparse值传递给它.

如何从另一个python脚本将值传递给argparser(请参阅下面的YouTube上传API脚本中的部分代码)?

if __name__ == '__main__':
    argparser.add_argument("--file", required=True, help="Video file to upload")
    argparser.add_argument("--title", help="Video title", default="Test Title")
    argparser.add_argument("--description", help="Video description",
        default="Test Description")
    argparser.add_argument("--category", default="22",
        help="Numeric video category. " +
            "See https://developers.google.com/youtube/v3/docs/videoCategories/list")
    argparser.add_argument("--keywords", help="Video keywords, comma separated",
        default="")
    argparser.add_argument("--privacyStatus", choices=VALID_PRIVACY_STATUSES,
        default=VALID_PRIVACY_STATUSES[0], help="Video privacy status.")
    args = argparser.parse_args()

    if not os.path.exists(args.file):
        exit("Please specify a valid file using the --file= parameter.")

    youtube = get_authenticated_service(args)
    try:
        initialize_upload(youtube, args)
    except HttpError, e:
        print "An HTTP error %d occurred:\n%s" …
Run Code Online (Sandbox Code Playgroud)

python google-api youtube-api argparse

9
推荐指数
2
解决办法
5251
查看次数

argparse中单个破折号和双破折号之间的区别

有谁知道用单个破折号-r和双破折号指定argparse文件之间的主要区别是什么--r?

我遇到了这个 Julia语言argparse,它将它们分为短和长,但没有说明为什么你会使用一个而不是另一个.

python argparse

9
推荐指数
2
解决办法
5190
查看次数

重新排序Python argparse参数组

我正在使用argparse,我有一个自定义参数组required arguments.有没有办法在帮助消息中更改参数组的顺序?我认为在可选参数之前获得所需的参数更合乎逻辑,但是没有找到任何帮助的文档或问题.

例如,更改此:

usage: foo.py [-h] -i INPUT [-o OUTPUT]

Foo

optional arguments:
  -h, --help            show this help message and exit
  -o OUTPUT, --output OUTPUT
                      Output file name

required arguments:
  -i INPUT, --input INPUT
                      Input file name
Run Code Online (Sandbox Code Playgroud)

对此:

usage: foo.py [-h] -i INPUT [-o OUTPUT]

Foo

required arguments:
  -i INPUT, --input INPUT
                      Input file name

optional arguments:
  -h, --help            show this help message and exit
  -o OUTPUT, --output OUTPUT
                      Output file name
Run Code Online (Sandbox Code Playgroud)

(例子来自这个问题)

python argparse

9
推荐指数
3
解决办法
4453
查看次数