2017-06-05 68 views
1

我是python的新手,我写了一个代码来为我的应用程序创建配置文件。我已经创建了适用于2个IP的代码,但可能会发生这样的情况:用户可能会输入更多的IP,并且对于Ip中的每次增加,配置文件将被更改。有验证服务器,它们只能是1或2。根据python中的用户输入创建多个文件

我传递输入到Python代码通过一个文件名“inputfile中”,下面是它的样子:

EnterIp_list: ip_1 ip_2 
authentication_server: as_1 as_2 

下面是如何最终配置文件被创建:

configfile1:     configfile2: 
App_ip: ip_1     App_ip: ip_2 
app_number: 1     app_number: 2 
authen_server: as_1   authen_server: as_2 

以下是python3代码的外观:

def createconfig(filename, app_ip, app_number, authen_server) 
    with open(filename, 'w') as inf: 
      inf.write("App_ip=" + app_ip + "\n") 
      inf.write("app_numbber=" + app_number) 
      inf.write("authen_server="+ authen_server) 


with open("inputfile") as f: 
    for line in f: 
     if EnterIP_list in line: 
      a= line.split("=") 
      b = a[1].split() 
     if authentiation_server in line: 
      c= line.split("=") 
      d=c[1].split() 

createconfig(configfile1, b[0], 1, d[0]) 
createconfig(configfile2, b[1], 2, d[1]) 

用户可以自由输入尽可能多的IP地址。有人可以请建议需要做什么使代码更通用和强大,以便它可以用于任何数量的输入IP?每增加一个新IP,app_number的值也会增加。

总会有两个身份验证服务器,他们会循环查看,例如第三个应用程序IP将再次与“as_1”关联。

回答

0

你只需要遍历b中的ip列表,注意你当前的代码只适用于你的“inputfile”的最后一行。只要只有一行,那就行了。

with open("inputfile") as f: 
    for line in f: 
     a= line.split("=") 
     b = a[1].split() 

app_count = 1 
for ip in b: 
    createconfig("configfile%s" % app_count , ip, app_count) 
    app_count += 1 

编辑:关于您的代码更改的解决方案更新。这样做无需修改了这么多你的代码的

with open("inputfile") as f: 
    for line in f: 
     if EnterIP_list in line: 
      ips = line.split("=")[1].split() 
     if authentiation_server in line: 
      auth_servers = line.split("=")[1].split() 

app_count = 1 
for ip, auth_server in zip(ips, auth_servers): 
    createconfig("configfile%s" % app_count , ip, app_count, auth_server) 
    app_count += 1 
+0

嗨,非常感谢您的回答,但是我的代码使用了更多的变量,这些变量在前面的描述中没有提及。我已经更新了我的描述,可以请检查吗? –

+0

解决方案已更新为包含authentication_server。 – olisch

0

一个不那么伟大的方式是删除最后两个createconfig()调用,而是做一个循环,一旦你有进行如下操作:

with open("inputfile") as f: 
for line in f: 
    a= line.split("=") 
    b = a[1].split() 

for app_number in b: 
    createconfig("configfile{}".format(app_number), b[app_number], app_number) 
+0

嗨,非常感谢您的回答,但我的代码使用了更多的变量,这在我之前的描述中没有提到。我已经更新了我的描述,可以请检查吗? –

相关问题