我有几个配置文件。一个有一些球队名字,另一个有位置。我的每个用户都会上传一个包含团队和职位的文件。团队和职位必须与配置文件中的内容匹配,否则将打印错误。我可以让脚本只读取每个配置文件中的一个值。它没有读取其余的值。如何让它读取配置文件中的所有值?
以下是两个配置文件: 对于团队: [队] 球队=巴塞罗那,拜仁,国际米兰,切尔西
职位:
[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)
答案 0 :(得分: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
答案 1 :(得分:0)
那怎么样?
for open in line('team.cfg','r'): list_fu = [line.split()中列的列] 打印(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.现在你用if条件抓住团队和用户:
for list_fu [1]中的行: if line =='守门员': print(line)#do你想做什么