简体   繁体   English

python argparse:如何在类型关键字中调用函数时使用其他已解析的参数作为参数?

[英]python argparse: how to use other parsed argument as parameter at calling function in type keyword?

I am trying to create an user interface using argparse module. 我正在尝试使用argparse模块创建用户界面。

One of the argument need to be converted, so I use the type keyword: 其中一个参数需要转换,因此我使用type关键字:

add_argument('positional', ..., type=myfunction)

and there is another optional argument: 还有另一个可选参数:

add_argument('-s', dest='switch', ...) 

in addition, I have 另外,我有

parsed_argument=parse_args()

However, in myfunction , I hope I can use an additional parameter to control the behavior, which is the optional argument above, ie 但是,在myfunction ,希望我可以使用一个附加参数来控制行为,这是上面的可选参数,即

def myfunction(positional, switch=parsed_argument.switch): 
     ...

How can I achieve that? 我该如何实现?

Simple answer: You can't. 简单答案:不能。 The arguments are parsed separately, and there is no real guarantee that some order is maintained. 参数是单独解析的,并不能真正保证维持某些顺序。 Instead of putting your logic into the argument type, just store it as a string and do your stuff after parsing the command line: 无需将逻辑放入参数类型,只需将其存储为字符串,然后在解析命令行后执行操作即可:

parser.add_argument('positional')
parser.add_argument('-s', '--switch')

args = parser.parse_args()

myfunction(args.positional, switch=args.switch)

I'm not sure I did understand correctly what you want to achieve, but if what you want to do is something that looks like: 我不确定我是否正确理解您要实现的目标,但是如果您要完成的目标是:

myprog.py cmd1 --switcha
myprog.py cmd2 --switchb

yes you can, you need to use subparsers. 是的,您可以,您需要使用子解析器。 I wrote a good example of it for a little PoC I wrote to access stackoverflow's API from CLI . 我为通过POI访问stackoverflow的API编写的一些PoC编写了一个很好的示例。 The whole logic is a bit long to put thoroughly here, but mainly the idea is: 整个逻辑在这里要花很长时间,但是主要的想法是:

  1. create your parser using parser = argparse.ArgumentParser(...) 使用parser = argparse.ArgumentParser(...)创建解析器
  2. create the subparsers using subparsers = parser.add_subparsers(...) 使用subparsers = parser.add_subparsers(...)创建子subparsers = parser.add_subparsers(...)
  3. add the commands with things like `subparser.add_parser('mycommand', help='Its only a command').set_defaults(func=mycmd_fn) where 添加带有诸如subparser.add_parser('mycommand',help ='Its only a command')之类的命令。set_defaults(func = mycmd_fn)其中
  4. mycmd_fn takes args as parameters where you have all the switches you issued to the command! mycmd_fnargs作为参数,在该参数中,您可以对命令发出所有开关!

the difference from what you ask, is that you'll need one function per command, and not one function with the positional argument as first argument. 与您要求的不同之处在于,每个命令将需要一个函数,而不是将positional参数作为第一个参数的一个函数。 But you can leverage that easily by having mycmd_fn being like: mycmd_fn = lambda *args: myfunction('mycmd', *args) 但是您可以通过使mycmd_fn像这样轻松地利用它: mycmd_fn = lambda *args: myfunction('mycmd', *args)

HTH HTH

From the documentation: 从文档中:

type= can take any callable that takes a single string argument and returns the converted value: type =可以接受带有单个字符串参数并返回转换后值的任何可调用项:

Python functions like int and float are good examples of a type function should be like. intfloat这样的Python函数就是类型函数的一个很好的例子。 int takes a string and returns a number. int接受一个字符串并返回一个数字。 If it can't convert the string it raises a ValueError . 如果无法转换字符串,则会引发ValueError Your function could do the same. 您的功能可以执行相同的操作。 argparse.ArgumentTypeError is another option. argparse.ArgumentTypeError是另一个选项。 argparse isn't going to pass any optional arguments to it. argparse不会将任何可选参数传递给它。 Look at the code for argparse.FileType to see a more elaborate example of a custom type . 查看argparse.FileType的代码,以查看自定义type详细示例。

action is another place where you can customize behavior. action是您可以自定义行为的另一个地方。 The documentation has an example of a custom Action. 该文档提供了一个自定义操作的示例。 Its arguments include the namespace , the object where the parser is collecting the values it will return to you. 它的参数包括namespace ,解析器将在其中收集它将返回给您的值的对象。 This object contains any arguments have already been set. 该对象包含任何已设置的参数。 In theory your switch value will be available there - if it occurs first. 理论上,您的switch值将在那里可用-如果它首先出现。

There are many SO answers that give custom Actions . 有许多SO答案可提供自定义Actions

Subparsers are another good way of customizing the handling of arguments. 子解析器是自定义参数处理的另一种好方法。

Often it is better to check for the interaction of arguments after parse_args . 通常,最好检查parse_args之后参数的交互。 In your case 'switch' could occur after the positional and still have effect. 在您的情况下,“切换”可能会在位置之后发生,并且仍然有效。 And argparse.Error lets you use the argparse error mechanism (eg displaying the usage) argparse.Error允许您使用argparse错误机制(例如,显示用法)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM