Warm tip: This article is reproduced from serverfault.com, please click

python-如何使用属性文件或xml文件根据提供的参数显示数据

(python - How to use the property file or xml file to display data based on the parameter supplied)

发布于 2020-11-29 17:24:33

我有具有以下结构的属性文件或xml文件:

#conf.properties
DEV="jdbc:oracle:thin:@devHost:1521:ORCL"
QA="jdbc:oracle:thin:@qaHost:1521:ORCL"


#db_conf.xml
<?xml version="1.0"?>
<environments>
    <env name="Dev">
        <username>oracle</username>
        <password>welcome</password>
        <url>devHost:1521</url>
    </env>
    <env name="QA">
        <username>oracle</username>
        <password>welcome</password>
        <url>qaHost:1525</url>
    </env>
</environments>

我想编写一个python / shell脚本,该脚本从命令行获取单个参数并处理结果。我可以使用任何属性文件选项或基于XML的文件来获取详细信息。例如。如果我将参数作为dev传递给脚本,则应返回dev的连接字符串值(如果使用属性文件),或者如果我使用xml文件并传递参数,则应返回dev特定的用户名,密码,URL详细信息和存储在3个新变量中。

我怎样才能做到这一点?最简单的方法是什么?我在python代码中使用了变量。但我想知道如何使用基于属性文件或基于xml文件的方法。

Questioner
Subbu
Viewed
0
Jack Fleeting 2020-11-30 22:16:34

我不了解属性文件,但是就xml而言,你可以尝试以下操作:

from lxml import etree

conf = """[your xml above]"""
input = "Dev"

doc = etree.XML(conf)
# to load from a file, try: etree.parse(r'path_to_file\file_name.xml')
spath = f"//env[@name='{input}']"
#the above uses f-strings to create the xpath search expression: see https://realpython.com/python-f-strings/
for dev in doc.xpath(spath):
    u_name = dev.xpath('./username/text()')[0]
    pw = dev.xpath('./password/text()')[0]
    url= dev.xpath('./url/text()')[0]
u_name,pw,url

输出:

('oracle', 'welcome', 'devHost:1521')