Python - 如何从ini文件中修复解析正确的值,但不解析值字段中的值

时间:2013-10-09 23:52:21

标签: python parsing ini

从ini文件中解析错误的值,如何解析username = field中的用户名而不是值?

1)使用预定义预设存储的Ini文件,我需要在python中读取

$ cat /var/tmp/file.ini
banner=QUESTIONS sentence
network=lan
programming=pytohn
url=http\://pbx/register?username=E300B1&password=1234&option=localip&localip=
username=E300B1
password=1234
server=pbx

2)代码:我正在尝试用户名/密码字段

import re,os, time, socket, datetime, threading, subprocess, logging, gtk, gobject
logging.basicConfig(filename='/var/tmp/log.log',level=logging.DEBUG)

def readini(findme):
  f = open('/var/tmp/file.ini', "r")
  for line in f:
    if line:
      if findme in line:
        r= line.split("=")
        return r[1].replace("\\n", "").rstrip()

host = readini("server")
username = preadini("username")
password = readini("password")

command = """curl 'http://%s/a/b?username=%s&password=%s&language=EN'""" % (host, username, password)
logging.debug( command )
os.system( command )

3)输出(错误):

DEBUG:root:curl 'http://192.168.1.10/a/b?username=http\://pbx/register?username&password=http\://pbx/register?username&language=EN'

4)预期输出为:

DEBUG:root:curl 'http://192.168.1.10/a/b?username=E300B1&password=1234&language=EN'

1 个答案:

答案 0 :(得分:1)

问题在于您的条件if findme in line不适用于您的文件。在您的文件中,字符串“username”位于定义网址的行中 - 这就是您看到输出的原因。

 url=http\://pbx/register?username=E300B1&password=1234&option=localip&localip=

更好的方法是:

def readini(findme):
  f = open('/var/tmp/file.ini', "r")
  for line in f:
    if "=" in line:
        key,val = line.split("=",1)
        if findme in key:
            return val.replace("\\n", "").rstrip()

使用可选的int arg进行拆分可以保证返回的列表长度为2,并且它实际上是该行定义的key,val对。