Python - how to fix the parse from ini file the correct values, but not parse values from values field

StackOverflow https://stackoverflow.com/questions/19284766

  •  30-06-2022
  •  | 
  •  

Question

Parsing wrong value from ini file, how can i parse the username from username= field not from the value?

1) Ini file stored with predefined presets, which i need to read in 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) Code: i was trying seems wrong for username/password field

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) outputs (wrong):

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

4) expected output was:

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

Solution

The problem is that your condition if findme in line does not work with your file. In your file, the string "username" is in the line defining the url -- which is why you're seeing the output that you're seeing.

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

A better approach would be:

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()

Using the optional int arg to split guarantees that the list returned has length two and that it will actually be the key,val pair defined by that line.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top