Python变量替换

时间:2016-03-17 20:42:22

标签: python list variables

我有一个脚本调用我想要整理的linux客户列表。这是代码:

#!/usr/bin/python


guests = ['guest1','guest2','guest3','guest*']
def serverCheck(guestList)
    for g in guestList:
        server = AdminControl.completeObjectName('cell=tstenvironment,node=guest1,name=uatenvironment,type=Server,*')
        try:
            status = AdminControl.getAttribute(server, 'state')
            print g + status
        except:
            print "Error %s is down." % g
serverCheck(guests)

问题出在这一行:

server = AdminControl.completeObjectName('cell=Afcutst,node=%s,name=afcuuat1,type=Server,*') % g

如何使用我的列表填充节点变量,同时仍然能够将括号内的信息传递给AdminControl函数?

3 个答案:

答案 0 :(得分:1)

参数字符串本身是%运算符的参数,而不是函数调用的返回值。

server = AdminControl.completeObjectName(
    'cell=Afcutst,node=%s,name=afcuuat1,type=Server,*' % (g,)
)

窥视水晶球,Python 3.6将允许你写

server = AdminControl.completeObjectName(
    f'cell=Afcutst,node={g},name=afcuuat1,type=Server,*'
)

将变量直接嵌入到特殊的格式字符串文字中。

答案 1 :(得分:0)

你能尝试这样吗

AdminControl.completeObjectName('cell=tstenvironment,node=%s,name=uatenvironment,type=Server,*'%g)

答案 2 :(得分:0)

为了更具可读性,我建议使用相同的方法来设置变量的字符串格式(这里我选择了str.format

guests = ['guest1','guest2','guest3','guest*']

def serverCheck(guestList)
    name_tpl = 'cell=tstenvironment,node={},name=uatenvironment,type=Server,*'

    for g in guestList:
        obj_name = name_tpl.format(g)
        server = AdminControl.completeObjectName(obj_name)
        try:
            status = AdminControl.getAttribute(server, 'state')
            print '{}: {}'.format(g, status)
        except:
            print 'Error {} is down'.format(g)

serverCheck(guests)
相关问题