Python变量替换

2024-10-03 00:29:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个脚本,它调用我正在整理的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)

问题在于这一行:

^{pr2}$

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


Tags: 代码脚本列表客户serverlinuxusrstatus
3条回答

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

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

窥视水晶球,Python3.6将允许您编写

^{pr2}$

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

为了提高可读性,我建议使用同样的方法来格式化变量中的字符串(这里我选择了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)

你能这样试试吗

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

相关问题 更多 >