通过阅读 python 中的 属性 文件获得价值的关键基础?

get key basis on value by reading property file in python?

我有一个像这样的 属性 文件 "holder.txt",格式是 key=value。这里的键是 clientId,值是 hostname.

p10=machineA.abc.host.com
p11=machineB.pqr.host.com
p12=machineC.abc.host.com
p13=machineD.abc.host.com

现在我想在 python 中读取此文件并获取相应的 clientId,其中此 python 脚本是 运行。例如:如果 python 脚本在 machineA.abc.host.com 上是 运行 那么它应该给我 p10 作为 clientId。其他人也一样。

import socket, ConfigParser

hostname=socket.getfqdn()
print(hostname)

# now basis on "hostname" figure out whats the clientId 
# by reading "holder.txt" file

现在我已经使用 ConfigParser 但我的困惑是如何根据主机名获取 clientId 的键值?我们可以在 python 内完成吗?

您需要读取 holder 文件并将其作为字典存储在内存中:

mappings = {}
with open('holder.txt', 'r') as f:
    for line in f:
        mapping = line.split('=')
        mappings[mapping[1].rstrip()] = mapping[0]

然后每次要从主机名获取clientId时执行映射:

import socket, ConfigParser

hostname=socket.getfqdn()
clientId = mappings[hostname]

希望对您有所帮助。