Python:将列表分配给函数

时间:2019-02-21 20:19:33

标签: python

有没有一种方法可以基于变量env分配列表并将结果传递给函数?我传递了一个名为env的变量,例如,可以是UPE,DEV,PRD。根据结果​​,我想将列表分别分配给以下功能。最好的方法是什么?

UPE=['SERVER1','SERVER2','SERVER3','SERVER4']
DEV=['ServerA','ServerB']
PRD=['SERVER1','SERVER2','SERVER3','SERVER4']

if os.path.isfile('/myfile/' + configFile):

  config_parser = ConfigParser()
  config_parser.read('/myfile/' + configFile)

if actions == "start":
    startOVD('start',UPE[3]) //I want pass the result of env setup variable
    #ans = raw_input("Would you like to start OVD, MSAS,OAG : y | n : ")
    if env == 'UPE':
        startMSAS('start',UPE[0])
        startOAG('start',UPE[1])
    startOHS('start',UPE[2])
    for section_name in sorted(config_parser.sections(), reverse=True):
        adminURL = config_parser.get(section_name, 'ADMIN_URL')
        adminUsername = config_parser.get(section_name, 'ADMIN_USER')
        adminPassword = config_parser.get(section_name, 'ADMIN_PASS')
        adminHost = config_parser.get(section_name, 'NM_HOST')
        domainName = config_parser.get(section_name, 'DOMAIN_NAME')
        domainDir = config_parser.get(section_name, 'DOMAIN_DIR')
        admPort = adminURL[-4:]

        printHeader('Initiating Starting Sequence')
        startAdmin('start', adminHost, domainDir, domainName, admPort)
        showServerStatus('start', adminUsername, adminPassword, adminURL)


if actions == "stop":
    for section_name in (config_parser.sections()):
        adminURL = config_parser.get(section_name, 'ADMIN_URL')
        adminUsername = config_parser.get(section_name, 'ADMIN_USER')
        adminPassword = config_parser.get(section_name, 'ADMIN_PASS')
        adminHost = config_parser.get(section_name, 'NM_HOST')
        domainName = config_parser.get(section_name, 'DOMAIN_NAME')
        domainDir = config_parser.get(section_name, 'DOMAIN_DIR')
        admPort = adminURL[-4:]

        printHeader('Initiating Stopping Sequence')
        showServerStatus('stop', adminUsername, adminPassword, adminURL)
        stopAdmin(adminHost, domainDir, domainName, admPort)

    if env == 'UPE':
        stopMSAS('stop',UPE[0])
        stopOAG('stop',UPE[1])
    stopOHS('stop',UPE[2])
    stopOVD('stop',UPE[3])

1 个答案:

答案 0 :(得分:0)

我将通过设置回调列表来进行组织。

from functools import partial

start_funcs = [partial(startOVD 'start',UPE[3])
if env == 'UPE':
    start_funcs.extend([partial(startMSAS, 'start', UPE[0]),
                       partial(startOAG, 'start', UPE[1])])
start_funcs.append(partial(startOHS, 'start', UPE[2]))

env具有不同值的情况添加类似的逻辑。最后,您将遍历start_funcs并按顺序调用每个函数。

if actions == "start":
    for f in start_funcs:
        f()

    # ...