2016-12-06 98 views
0

我有一个参数是变量为搜索功能的问题。如何将字符串变量传递给搜索功能?

这是我想要实现的:
我有一个文件充满了值,我想检查文件以确保在我继续之前存在特定的匹配行。我要确保,如果一个有效<begSW=UNIQUE-DNS-NAME-HERE<>存在并且可达行<endSW=UNIQUE-DNS-NAME-HERE<>存在。直到我打电话if searchForString(searchString,fileLoc):它总是返回false

,一切工作正常。如果我给你变“搜索字符串”的直接价值,并将它传递它的作品,所以我知道它一定有什么用,我结合串的方式,但我似乎无法找出什么我做错了。

如果我检查的数据“searchForString”使用我看到了似乎是有效值:

values in fileLines list: 

['<begSW=UNIQUE-DNS-NAME-HERE<>', ' <begPortType=UNIQUE-PORT-HERE<>', '  <portNumbers=80,443,22<>', ' <endPortType=UNIQUE-PORT-HERE<>', '<endSW=UNIQUE-DNS-NAME-HERE<>'] 

value of searchVar: 

<endSW=UNIQUE-DNS-NAME-HERE<> 

文件中的条目的例子是:

<begSW=UNIQUE-DNS-NAME-HERE<> 
    <begPortType=UNIQUE-PORT-HERE<> 
     <portNumbers=80,443,22<> 
    <endPortType=UNIQUE-PORT-HERE<> 
<endSW=UNIQUE-DNS-NAME-HERE<> 

这里是代码有问题:

def searchForString(searchVar,readFile): 
    with open(readFile) as findMe: 
     fileLines = findMe.read().splitlines() 
     print fileLines 
     print searchVar 
     if searchVar in fileLines: 
      return True 
     return False 
    findMe.close() 

fileLoc = '/dir/folder/file' 
fileLoc.lstrip() 
fileLoc.rstrip() 
with open(fileLoc,'r') as switchFile: 
    for line in switchFile: 
     #declare all the vars we need 
     lineDelimiter = '#' 
     endLine = '<>\n' 
     begSWLine= '<begSW=' 
     endSWLine = '<endSW=' 
     begPortType = '<begPortType=' 
     endPortType = '<endPortType=' 
     portNumList = '<portNumbers=' 
     #skip over commented lines -(REMOVE THIS) 
     if line.startswith(lineDelimiter): 
      pass 
     #checks the file for a valid switch name 
     #checks to see if the host is up and reachable 
     #checks to see if there is a file input is valid 
     if line.startswith(begSWLine): 
      #extract switch name from file 
      switchName = line[7:-3] 
      #check to make sure switch is up 
      if pingCheck(switchName): 
       print 'Ping success. Host is reachable.' 
       searchString = endSWLine+switchName+'<>' 
       **#THIS PART IS SUCKING, WORKS WITH DIRECT STRING PASS 
       #WONT WORK WITH A VARIABLE** 
       if searchForString(searchString,fileLoc): 
        print 'found!' 
       else: 
        print 'not found' 

任何建议或指导将是非常有益的。

+0

做一些更多的阅读之后,我已经决定要输入的文本文件更改为XML并使用内置在库中。 –

回答

0

很难说没有文件的内容,但我会尝试

switchName = line[7:-2] 

所以这看起来像

>>> '<begSW=UNIQUE-DNS-NAME-HERE<>'[7:-2] 
'UNIQUE-DNS-NAME-HERE' 

此外,你可以看看正则表达式搜索,使您的清理更加灵活。

import re 
# re.findall(search_expression, string_to_search) 

>>> re.findall('\=(.+)(?:\<)', '<begSW=UNIQUE-DNS-NAME-HERE<>')[0] 
'UNIQUE-DNS-NAME-HERE' 

>>> e.findall('\=(.+)(?:\<)', '  <portNumbers=80,443,22<>')[0] 
'80,443,22' 
+0

下面是该文件的内容的一个例子:

+0

确保您得到一个数组一样 <'begSW = US-CA-SD-190IN4-BA01 <>', '', ', '', ''] 没有这个, “在switchFile中的行”将不起作用 – Neil

相关问题