0

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

4
  • I'm sorry- I'm not sure exactly what you're asking here. You have a Python script that reads information from a file and prints some output based on that information, right? And you're looking to print it in a different format? Perhaps you could post part of the script itself for us to examine? Commented Jun 13, 2017 at 20:06
  • Do you mean that you want to change the first bit of output into the second bit (with v_ added to each key name)? Or do you mean you want to create python variables with variable names and values defined by the first bit of output? That is, if the output were foo = bar, do you want to create a variable named v_foo with a string value of "bar"? Commented Jun 13, 2017 at 20:07
  • 4
    Any time you find yourself wanting to create dynamic variables, you almost always should be using a dictionary (or list/array if the variables are like foo1, foo2, foo3, ...). Commented Jun 13, 2017 at 20:12
  • Are you trying to pipe the original output to another Python script where you assign the given variables those values? If so, it might be better to import the function that you use to parse the file in the original script and use the output of that function to store the values you need. If you're really looking to pipe it through stdout, though, let us know. Commented Jun 13, 2017 at 20:19

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.