简体   繁体   English

将stdout保存到Python中的变量中

[英]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 此处的密钥是USER_NAME,PASSWORD,IP_ADD,值是fenfnewl,fnaofna,ftp.internal.com

I wrote python script to extract info using a regex and printed the output. 我编写了python脚本以使用正则表达式提取信息并打印输出。 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. 我有变量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. 我只想在输出中将密钥从USER_NAME更改为V_USER_NAME。

 #!/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. 我是python的初学者。 Any help is much appreciated. 任何帮助深表感谢。 Thanks in advance 提前致谢

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. 如果您先验地知道要从文件中提取什么变量,则始终可以执行一系列的if / then语句,将数据放入所需的变量中。 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. 当然,我在这里建议使用keyvalue 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. 在python中,要创建由某些用户输入确定的动态变量名的另一种方法是在dict中创建键为变量名的dict 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: 如果您不知道变量名将是什么,或者不想麻烦写出所有if / then语句,这将非常有用:

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 ? 如果您最终阅读了很多像这样的文件并进行了这种解析,那么我是否建议您研究JSONYAML等标准化的输入文件格式? 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. Python有一些出色的软件包,可以将这些类型的文件直接读入类似dict的结构中,从而省去了编写自己的自定义解析器的工作。

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 : 最后, 由于可能执行任意代码因此我不建议这样做 ,如果您真的想生成动态创建变量的代码,则可以随时调用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. 你被警告了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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