简体   繁体   English

Python变量替换

[英]Python variable substitution

I have a script that calls a list of linux guests I am trying to tidy up. 我有一个脚本,它调用了我要整理的Linux来宾列表。 Here is the code: 这是代码:

#!/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)

The problem lies in this line: 问题出在这一行:

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

How do I use my list to populate the node variable while still being able to pass the info within the parentheses to the AdminControl function? 我如何使用列表填充节点变量,同时仍然能够将括号内的信息传递给AdminControl函数?

The argument string itself is the argument to the % operator, not the return value of the function call. 参数字符串本身是%运算符的参数,而不是函数调用的返回值。

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

Peeking into the crystal ball, Python 3.6 will allow you to write 窥探水晶球,Python 3.6将允许您编写

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

embedding the variable directly into a special format string literal. 将变量直接嵌入到特殊格式的字符串文字中。

你可以这样尝试吗

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

For more readability I would suggest this and also using the same way to format strings from variables (here I chose str.format ) 为了提高可读性,我建议这样做,并且也使用相同的方式来格式化变量的字符串(在这里我选择了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)

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

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