[英]How can I get my python script to read all values from a config file?
我有几个配置文件。 一个带有一些团队名称,另一个带有职位。 我的每个用户都将上传一个包含团队和职位的文件。 团队和职位必须与配置文件中的内容匹配,否则将显示错误。 我可以让脚本从每个配置文件中仅读取一个值。 它不会读取其余的值。 我如何获取它读取配置文件中的所有值?
以下是两个配置文件:对于团队:[团队]团队=巴塞罗那,拜仁,国际米兰,切尔西
职位:
[Positions]
positions = striker, midfielder, defender, goalkeeper
这是一个示例文本文件:
Teams Positions User ID
Barcelona goalkeeper BCTG-F
Barcelona striker BCTG-F
Bayern defender BCTG-F
Bayern striker BCTG-F
Inter striker BCTG-F
Inter midfielder BCTG-F
Chelsea midfielder BCTG-F
Chelsea goalkeeper BCTG-F
这是脚本:
#!usr/bin/python
from subprocess import *
import sys
import ConfigParser
import os
import csv
from sys import argv
script, user_id, team_file = argv
def main():
#get the actions
def teamCalls():
actions = ConfigParser.SafeConfigParser()
actions.read('/etc/nagios/ingestion/team.cfg')
for section_name in actions.sections():
for name, value in actions.items(section_name):
return '%s' %(value)
teamCalls()
#get the object types
def positionTypes():
objects = ConfigParser.SafeConfigParser()
objects.read('/etc/nagios/ingestion/position.cfg')
for section_name in objects.sections():
for name, value in objects.items(section_name):
return '%s' % (value)
positionTypes()
# checking path to file and user id
try:
f = csv.reader(open(team_file, "rb"), delimiter='\t')
except:
logging.error('No such file or directory. Please try again')
else:
for line in f:
for row in f:
if user_id != row[2]:
print ("User ID is incorrect")
elif teamCalls() != row[0]:
print ("Wrong team")
elif positionTypes() != row[1]:
print ("Position not valid")
else:
print row
finally:
print "all error checks done!"
main()
sys.exit(0)
您可以在循环的最内层语句中“返回”。 这将导致它立即返回,而不会循环遍历其余值。 如果您想要一个值列表,则可以执行以下操作:
calls = []
for section_name in actions.sections():
for name,value in actions.items(section_name):
calls.append(str(value)) # same as '%s' % (value)
return calls
那个怎么样?
对于open('team.cfg','r')中的行:list_fu = [line.split()中列的列] print(list_fu)
输出:
['Teams', 'Positions', 'User', 'ID']
['Barcelona', 'goalkeeper', 'BCTG-F']
['Barcelona', 'striker', 'BCTG-F']
['Bayern', 'defender', 'BCTG-F']
['Bayern', 'striker', 'BCTG-F']
['Inter', 'striker', 'BCTG-F']
['Inter', 'midfielder', 'BCTG-F']
['Chelsea', 'midfielder', 'BCTG-F']
['Chelsea', 'goalkeeper', 'BCTG-F']
如果您想阅读这些位置,现在应该在列表EG->位置列表中,因此该列为1。现在,如果条件满足,您将捕获“团队”和“用户”:
对于list_fu [1]中的行:如果line =='goalkeeper':print(line)#做您想做的事
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.