Ujjwal Chowdary
Ujjwal Chowdary

Reputation: 125

Save stdout into variables in Python

The properties file stores the information as Key and Values. Here Key is USER_NAME, PASSWORD, IP_ADD and Value is fenfnewl, fnaofna, ftp.internal.com

I wrote python script to extract info using a regex and printed the output. The output looks like

USER_NAME = fenfnewl
PASSWORD = fnaofna
IP_ADD = ftp.internal.com

I have variables V_USER_NAME, V_PASSWORD, V_IP_ADD. I want these variables to get the values as follows

V_USER_NAME = fenfnewl
V_PASSWORD = fnaofna
V_IP_ADD = ftp.internal.com

The code that i wrote to get the output from properties file is as follows and it works fine. I just want to change the Keys from USER_NAME to V_USER_NAME in the output.

 #!/usr/bin/env python

import re # import the regular expressions module
import sys
import mysql.connector


val = 'DEFAULT'
print val



REG_EXP={'DEFAULT':r"\bDEFAULT_(USER_NAME|PASSWORD|IP_ADD)\w*\b",
         'NOT_DEFAULT':r"\bNOT_DEFAULT_(USER_NAME|PASSWORD|IP_ADD)\w*\b"}
filename = "/Users/DOCUMENTS/some.properties"

if val != 'DEFAULT':
    pattern = re.compile(REG_EXP['NOT_DEFAULT'], re.IGNORECASE)
    with open(filename, "rt") as in_file:
        for line in in_file:
            if pattern.search(line) != None:
                print(line)


else:
    pattern = re.compile(REG_EXP['DEFAULT'], re.IGNORECASE)
    with open(filename, "rt") as in_file:
        for line in in_file:
            if pattern.search(line) != None:
                print(line)

I am a beginner to python. Any help is much appreciated. Thanks in advance

Upvotes: 0

Views: 662

Answers (1)

PaSTE
PaSTE

Reputation: 4548

If you know a priori what variables you want to pull from the file, you can always make a series of if/then statements that put the data into the variables you want. For example:

import re

REG_EXP = re.compile(r'\bDEFAULT_(USER_NAME|PASSWORD|IP_ADD)\w*\b\s*=\s*(.*)') # give me the value as well as the key
with open(filename, 'rt') as in_file:
    for line in in_file:
        match = REG_EXP.search(line)
        if match:
            key = match.group(1)
            value = match.group(2)
            if key == 'USER_NAME':
                V_USER_NAME = value
            elif key == 'PASSWORD':
                V_PASSWORD = value
            elif key == 'IP_ADD':
                V_IP_ADD = value

Of course, I use key and value here suggestively. Another way to handle this problem in python, where you want to create dynamic variable names that are determined by some user input, is to create a dict where the keys are the variable names. This is useful if you don't know what the variable names are going to be, or if you don't want to bother writing out all the if/then statements:

import re
result = {} # keys will be variable names

REG_EXP = re.compile(r'\bDEFAULT_(\w*)\b\s*=\s*(.*)') # don't know what the variable names are!
with open(filename, 'rt') as in_file:
    for line in in_file:
        match = REG_EXP.search(line)
        if match:
            key = 'V_' + match.group(1)
            value = match.group(2)
            result[key] = value

print(result) # gives something like {'V_USER_NAME': 'fenfnewl', 'V_PASSWORD': 'fnaofna', ...}

If you end up reading a lot of files like this and doing this kind of parsing, might I suggest looking into standardized input file formats like JSON or YAML? Python has some excellent packages for reading these types of files directly into dict-like structures, saving you the work of writing your own custom parser.

Finally, and I do not recommend this due to the potential for arbitrary code execution, if you really want to generate code that creates variables dynamically, you can always call exec:

import re

REG_EXP = re.compile(r'\bDEFAULT_(\w*)\b\s*=\s*(.*)') # don't know what the variable names are!
with open(filename, 'rt') as in_file:
    for line in in_file:
        match = REG_EXP.search(line)
        if match:
            key = 'V_' + match.group(1)
            value = match.group(2)
            exec(key + '=' value) # PLEASE RECONSIDER!

print(V_USER_NAME) # will hopefully print something like "fenfnewl", but might also give hackers root access to your machine.  Seriously.

If you are thinking about implementing this last solution, I urge you to reconsider! You have been warned.

Upvotes: 1

Related Questions