简体   繁体   中英

Trouble printing variables from other files

Description

I have a script → report_creator.py which will need some variables from another python script → extracted_data.py . The number of variables from extracted_data.py will always be based on the system it extracts data from (if the system has 1 server, we will have 1 variable, if the system has 2 servers, we will have 2 variables and so on). You can never know the exact number of variables the extracted_data.py will have.

Let's say we have extracted data from a system with 2 servers and the extracted_data.py file looks something like:

parameterx_server1 = "value"
parameterx_server2 = "another value"

What I have:report_creator.py :

import os
import extracted_data

#Extract all variables names starting with parameterx from extracted_data.py and store them into a list

variables = os.popen("""cat extracted_data.py | grep '^parameterx_*' | awk '{print $1}'""").read().strip()
variables = variables.split("\n")

#After the execution of the command, the list looks like this:
# variables = ['parameterx_server1', 'parameterx_server2']

Problem

The script now has a list containing all the parameterx variables from extracted_data.py :

variables = ['parameterx_server1', 'parameterx_server2']

The only thing remaining is to get the corresponding value of each variable from the variables list from the extracted_data.py , something like:

print extracted_data.parameterx_server1

I tried something like:

for variable in variables:
    print extracted_data.variable

But for some reason I get an AttributeError: 'module' object has no attribute 'variable' .

You can extract the variables and their value defined in the extracted_data.py file like this:

import extracted_data

extract_vars = {name: getattr(extracted_data, name)
                    for name in dir(extracted_data) if not name.startswith('_')}
print(extract_vars)  # -> {'parameterx_server2': 'another value', 'parameterx_server1': 'value'}

As shown, afterwards extract_vars is a dictionary containing both the variable names and associated values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM