需要重复一定次数的函数,并且每次都返回一个新的变量名

时间:2014-06-03 19:21:46

标签: python python-2.7

作为更大的应用程序的一部分,我正在努力解决这个问题。基本上,我会问用户总共有多少台服务器,然后请求每台服务器的名称,并获取服务器IP。根据用户输入的服务器总数,我希望能够多次重复这个过程。

认为这样的事情会起作用,但我非常确定关于将元组解包为变量的部分不会。

def add_servers():
    Server_name = raw_input("Please enter the server name for the next server: ")
    server_IP = socket.gethostbyname(Server_name)
    return (Server_name,server_IP)

def primary_server():
    PServerName = raw_input("Please enter the name for the primary server: ")
    PS_IP = socket.gethostbyname(PServerName)
    return (PServerName,PS_IP)

#Grab the total number of servers.
total_servers = int(raw_input("Please enter the total number of servers: "))
if total_servers > 1:
    add_servs = int(total_servers - 1)
    primary_server()
    for server in range(add_servs):
        add_servers()
        Server_name, server_IP = add_servers()
else:
    primary_server() #If there is only 1 server, don't subtract, and run the function for the primary server only.
    PServer, PS_IP = primary_server()

2 个答案:

答案 0 :(得分:2)

为什么不使用字典来尝试这样的事情?:

secondary_servers = {}
total_servers = int(raw_input("Please enter the total number of servers: "))
if total_servers > 1:
    add_servs = int(total_servers - 1)
    primary_server()
    for server in range(add_servs):
        Server_name, server_IP = add_servers()
        if Server_name not in secondary_servers.keys():
            secondary_servers[Server_name] = server_IP

这样所有的辅助服务器都在字典中。如果需要维护订单,可以将其更改为OrderedDict()。否则只需使用一个列表并继续将元组附加到列表中。

根据评论,这是在另一个答案中考虑的修订建议:

server_count = None

while server_count is None:
    total_servers = input('Please enter total number of servers: ')
    try:
        server_count = int(total_servers)
    except ValueError:
        total_servers = input('That is not a valid number, try again: ')

servers = {}  # This is an empty dict
for i in range(1, server_count+1):
    if i == 1:
        servers["Primary Server"] = primary_server()
    else:
        servers["Secondary Server " + str(i)] = add_servers()

答案 1 :(得分:0)

使用列表收集服务器,并循环直到列表的长度与输入的数字相同:

server_count = None

while server_count is None:
    total_servers = input('Please enter total number of servers: ')
    try:
        server_count = int(total_servers)
    except ValueError:
        total_servers = input('That is not a valid number, try again: ')

servers = []  # This is an empty list
while len(servers) != server_count:
    if len(servers) < 1:
        servers.append(primary_server())
    else:
        servers.append(add_servers())