简体   繁体   English

sys.argv CLI参数的python-helper列表

[英]python- helper list for sys.argv CLI argument

I have to read a CLI argument for my python script and then pass that input argument by the user to a method. 我必须为我的python脚本读取CLI参数,然后由用户将该输入参数传递给方法。 I want to provide user with a list of valid arguments that she can enter, sort of when you run the script with an invalid argument or with no argument passed- it shows you that you can only enter these arguments. 我想为用户提供一个她可以输入的有效参数列表,类似于在运行脚本时使用无效参数或不传递任何参数的脚本-它向您显示只能输入这些参数。

I know we can achieve this with argparse module, but argparse in my case will be an overkill- since I just want to pass whatever (valid)argument the user gave to a method. 我知道我们可以使用argparse模块来实现这一点,但是在我的情况下,argparse会显得过分杀人,因为我只想将用户给出的任何(有效)参数传递给方法。 How should I achieve this? 我应该如何实现?

parser.add_argument('--system-status', '-st', metavar='<host>', type=str)
if args.system-status:
    method(args.system-status)

And the same stuff repeated for 5 other variables? 对其他5个变量重复相同的内容吗?

The argparse lib is the way to go, if you dont want to check for each parameter you could use something like this: argparse库是一种解决方法,如果您不想检查每个参数,则可以使用如下代码:

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('--foo')
parser.add_argument('--bar')
parser.add_argument('--baz')
args = parser.parse_args()

def f(foo=None, bar=None, baz=None, **kwargs):
    print(foo)
    print(bar)
    print(baz)

f(**args.__dict__)

**args.__dict__ will turn args in a dictionary turn it into kwargs. **args.__dict__会将字典中的args转换为kwargs。

If you really absolutly don't want to use argparse then sys.argv will give you the list of parameters passed to the function. 如果您绝对不想使用argparse,则sys.argv将为您提供传递给该函数的参数列表。

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

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