是否可以通过 python 脚本中的 cli 动态调用函数

是否可以通过 python 脚本中的 cli 动态调用函数

我在调用此 python 脚本时尝试调用特定函数,即此脚本中有多个函数。我尝试使用全局变量,但没有使用 dough。

#!/usr/bin/python3

"""
This module is used to access the service account key stored in the secret manager secret
"""


import sys
import argparse

import json
import datetime
import argparse

def parse_arguments():

    parser = argparse.ArgumentParser(description='Service account key credential', formatter_class=argparse.RawDescriptionHelpFormatter)

    parser.add_argument('-p', '--project_name',
                        metavar='<project_name>',
                        help='GCP project name to retrieve the service account key credential stored in secret manager secret',
                        required=True)

    parser.add_argument('-n', '--secret_name',
                        metavar='<secret_name>',
                        help='name of the secret where service account credential is stored',
                        required=True)

    parser.add_argument('-e', '--email_id',
                        metavar='<email_id>',
                        help='name of the secret where service account credential is stored',
                        required=False)

    parsers = parser.parse_args()
    return parsers


def sa_credentials():
    """
    This is the main method to retrieve the secret manager secret which consists of the service account credential
    """
    options = parse_arguments()
    print(options)

    project_name = options.project_name
    secret_name  = options.secret_name

    print("It worked")

if __name__ == "__main__":
    globals()[sys.argv[1]]

这就是我运行它的方式,但什么也没发生

# ./test.py sa_credentials -p the-webbing-330212 -n my-secret

答案1

通过参数调用方法不是一个好习惯,它可能是一个安全漏洞

你应该使用类似python test.py 'call_function_one' [...]

然后在您的脚本中,您必须获取参数并执行:

if (arg[0] == 'call_function_one'):
  function_one(parameters)

另外,您可以直接在您的参数中解析参数main,这是使用argument_parser的常用方法,然后调用您的函数:)

相关内容