简体   繁体   中英

Python variable substitution

I have a script that calls a list of linux guests I am trying to tidy up. 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?

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

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 )

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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