在 Unix 中,我们有一个 SOURCE 命令,它可以在 shell 脚本中加载文本文件,并且文本文件中的所有这些参数都可以作为脚本中的变量使用。我们有与 python 相同的东西吗?我需要将属性文件从边缘节点加载到 .py 脚本,并根据值在 .py 脚本内做出决定。
Sample job.properties file in edge node is below.
databaseName=employee
hdfspath=/tenancy/ida/data
....
我需要在 .py 脚本中加载这个 job.properties 文件,这样我就不需要将它们作为命令行参数传递。请指教
最佳答案
事实上,您可以自定义 import用于此类目的的机制。不过,让我提供一个快速技巧:
def source(filename):
variables = {}
with open(filename) as f:
for line in f:
try:
name, value = line.strip().split('=')
except:
continue
variables[name] = value
return variables
variables = source('job.properties')
print(variables)
函数source
迭代所提供文件中的行并将赋值存储在dict
ionic 变量
中。如果行不包含赋值,try
/ except
将简单地跳过它。
要进一步模拟 shell 采购的行为,您可以添加
globals().update(variables)
如果在模块(非函数)级别工作,这将使 databaseName
和 hdfspath
可用作 Python 变量。
请注意,所有“源”变量都将为 str
,即使对于源文件中的 my_int=42
行也是如此。
关于python - Python 中等效的 Unix Source 命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58729547/