标签: argparse

如何停止argparse.FileType创建指定为默认的文件

我喜欢这个argparse模块.argparse.FileType也是有帮助的,除非您希望默认值不是sys.std*因为即使您提供值也会创建默认输出文件.

例如:

parser.add_argument('--outfile', type=FileType('w'), default="out.txt")
Run Code Online (Sandbox Code Playgroud)

即使您使用--outfile指定文件,也会创建out.txt.

我能想到的最好的是:

class MagicFileType(object):

    def __init__(self, *args, **kwargs):

        # save args/kwargs and set filetype to None
        self.filetype = None
        self.args = args
        self.kwargs = kwargs

    def __getattr__(self, attr):
        """ Delegate everything to the filetype """

        # If we haven't created it, now is the time to do so
        if self.filetype is None:
            self.filetype = FileType(*self.args, **self.kwargs)
            self.filetype = self.filetype(self.filename)

        return getattr(self.filetype, attr)

    def __call__(self, filename):
        """ Just cache the …
Run Code Online (Sandbox Code Playgroud)

python argparse

8
推荐指数
1
解决办法
1241
查看次数

argparse参数的可选值

我想区分这三种情况:

  • 国旗根本不存在python example.py;
  • 标志存在但没有值python example.py -t; 和
  • 该标志存在并具有值python example.py -t ~/some/path.

我怎么能用Python做到这一点argparse?前两个案件将被覆盖,action='store_true'但第三个案件将失效.

python command-line-interface argparse python-3.x

8
推荐指数
1
解决办法
837
查看次数

Python:如何在从命令行调用时启用kwargs?(也许与argparse)

假设我有模块myscript.py; 该模块是生产代码,通常称为%dir%>python myscript.py foo bar.

我想扩展它以获取关键字参数.我知道我可以使用下面的脚本来获取这些参数,但不幸的是,我们必须使用它来调用它

%dir%>python myscript.py main(foo, bar).

我知道我可以使用该argparse模块,但我不知道该怎么做.

import sys

def main(foo,bar,**kwargs):
    print 'Called myscript with:'
        print 'foo = %s' % foo
        print 'bar = %s' % bar
        if kwargs:
            for k in kwargs.keys():
                print 'keyword argument : %s' % k + ' = ' + '%s' % kwargs[k]   

if __name__=="__main__":
    exec(''.join(sys.argv[1:]))
Run Code Online (Sandbox Code Playgroud)

python command-line kwargs python-2.7 argparse

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

如何切换布尔 argparse 选项?

我试图将 configparser 和 argparse 结合起来用于脚本,以便 argparse 定义的各种参数的默认值存储在通过 configparser 操作的配置文件中。我遇到的问题是布尔选项。argparse 具有这些选项的store_true和store_false操作,它们会自动创建默认值并指定给定选项时要更改的内容。但是,由于默认值是从配置文件中读取的,因此我不知道要提前做什么才能使用这些操作。这会建议类似:

import argparse,configparser

config = configparser.ConfigParser()
config['DEFAULT']['test'] = 'False'
config.read('testing.cfg')

parser = argparse.ArgumentParser()

if config.getboolean('DEFAULT','test'):
    parser.add_argument('-t',action='store_false', dest='test')
else:
    parser.add_argument('-t',action='store_true', dest='test')

args = parser.parse_args()

print(args.test)
Run Code Online (Sandbox Code Playgroud)

parser.addargument但是,我不喜欢在条件中包含语句的想法(尤其是我拥有的这些选项越多,就越麻烦)。我更喜欢的是这样的:

parser.add_argument('-t',action='toggle_boolean',dest='test',default=config.getboolean('DEFAULT','test'))
Run Code Online (Sandbox Code Playgroud)

在这种情况下,toggle_boolean当给出参数时,该操作将切换布尔值的状态,无论它是什么。问题是所述操作 ( toggle_boolean) 不存在。我将如何定义这样的操作,或者是否有更好的方法来做到这一点?

python configparser argparse python-3.x

8
推荐指数
1
解决办法
7737
查看次数

python argparse 自动完成文件路径

所以我有一个 python 程序,它读取这样的配置文件:

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('-c', '--config',  type=str, help='config file', required=True)

args = parser.parse_args()
cfg_filename = args.config
Run Code Online (Sandbox Code Playgroud)

我希望能够在 bash 中自动完成路径。例如,假设调用了上面的程序,main.py并且有一个名为 的配置文件config_1.txt,其结构如下:

folder/
  main.py
  configs/
    config_1.txt
Run Code Online (Sandbox Code Playgroud)

假设在我的终端中它看起来像

folder/
  main.py
  configs/
    config_1.txt
Run Code Online (Sandbox Code Playgroud)

我希望按一个选项卡会给出:

user@host:~/folder$ python main.py -c con
Run Code Online (Sandbox Code Playgroud)

然后另一个选项卡给出

user@host:~/folder$ python main.py -c config/
Run Code Online (Sandbox Code Playgroud)

我尝试过添加

import argcomplete
argcomplete.autocomplete(parser)
Run Code Online (Sandbox Code Playgroud)

但没有用。

python bash argparse

8
推荐指数
1
解决办法
1576
查看次数

在 parser.add_argument 中同时设置 action='store_true' 和 default=False 有什么意义?

我一直读这样的代码,

parser.add_argument('--name', action='store_true', default=False, help='XXX')

例如,此代码man-sf-emnlp/train.py - midas-research

default=False但既然已经设置了,设置还有什么意义呢action='store_true'?

python command-line command-line-interface command-line-arguments argparse

8
推荐指数
1
解决办法
6097
查看次数

call_command参数是必需的

我试图以call_command一种非常类似于这个问题的方式使用Django 而没有答案.

我称之为的方式是:

    args = []
    kwargs = {
        'solr_url': 'http://127.0.0.1:8983/solr/collection1',
        'type': 'opinions',
        'update': True,
        'everything': True,
        'do_commit': True,
        'traceback': True,
    }
    call_command('cl_update_index', **kwargs)
Run Code Online (Sandbox Code Playgroud)

理论上,根据文档,这应该有效.但它不起作用,它只是不起作用.

这是add_arguments我的Command类的方法:

def add_arguments(self, parser):
    parser.add_argument(
        '--type',
        type=valid_obj_type,
        required=True,
        help='Because the Solr indexes are loosely bound to the database, '
             'commands require that the correct model is provided in this '
             'argument. Current choices are "audio" or "opinions".'
    )
    parser.add_argument(
        '--solr-url',
        required=True,
        type=str,
        help='When swapping cores, it …
Run Code Online (Sandbox Code Playgroud)

python django argparse django-commands

7
推荐指数
1
解决办法
3777
查看次数

访问传递给argparser参数的选项?

是否有可能访问传递给参数的选择元组?如果是这样,我该怎么做呢

例如,如果我有

parser = argparse.ArgumentParser(description='choose location')
parser.add_argument(
    "--location",
    choices=('here', 'there', 'anywhere')
)
args = parser.parse_args()
Run Code Online (Sandbox Code Playgroud)

我可以访问元组('here', 'there', 'anywhere')吗?

python argparse

7
推荐指数
1
解决办法
394
查看次数

如何使用 argparse 指定最小或最大浮点值

如何使用 指定最小或最大浮点参数argprase?我希望能够在最小和最大浮点值之间提供命令行参数。

我能找到的最接近的是 中的choices选项add_argument(),但它只指定了参数的允许值。

parser.add_argument("L", type=float, choices=range(2))
Run Code Online (Sandbox Code Playgroud)

0.5L的命令行参数失败:

invalid choice: 0.5 (choose from 0, 1)
Run Code Online (Sandbox Code Playgroud)

python argparse

7
推荐指数
2
解决办法
2810
查看次数

Custom conflict handling for ArgumentParser

What I need

I need an ArgumentParser, with a conflict handling scheme, that resolves some registered set of duplicate arguments, but raises on all other arguments.

What I tried

My initial approach (see also the code example at the bottom) was to subclass ArgumentParser, add a _handle_conflict_custom method, and then instantiate the subclass with ArgumentParser(conflict_handler='custom'), thinking that the _get_handler method would pick it up.

The Problem

This raises an error, because the ArgumentParser inherits from _ActionsContainer, …

python subclass argparse

7
推荐指数
1
解决办法
766
查看次数