2014-10-17 31 views
0

匹配模式的我都行:使用正則表達式查找在Python

# runPath is the current path, commands is a list that's mostly irrelevant here 
def ParseShellScripts(runPath, commands): 
    for i in range(len(commands)): 
     if commands[i].startswith('{shell}'): 
      # todo: add validation/logging for directory `sh` and that scripts actually exist 
      with open(os.path.join(runPath, 'sh', commands[i][7:]),"r") as shellFile: 
       for matches in re.findall("/^source.*.sh", shellFile): 
        print matches 

不過,我得到這個錯誤:

Traceback (most recent call last): 
    File "veri.py", line 396, in <module> 
    main() 
    File "veri.py", line 351, in main 
    servList, labels, commands, expectedResponse = ParseConfig(relativeRunPath) 
    File "veri.py", line 279, in ParseConfig 
    commands = ParseShellScripts(runPath, commands) 
    File "veri.py", line 288, in ParseShellScripts 
    for matches in re.findall("/^source.*.sh", shellFile): 
    File "/usr/lib/python2.7/re.py", line 177, in findall 
    return _compile(pattern, flags).findall(string) 
TypeError: expected string or buffer 

編輯:添加一些文件作爲例子

#config.sh 
#!/bin/bash 

dbUser = 'user' 
dbPass = 'pass' 
dbSchema = '' 
dbMaxCons = '4000' 

#the shellFile I'm looking in 
#!/bin/bash 
source config.sh 

OUTPUT=$(su - mysql -c "mysqladmin variables" | grep max_connections | awk '{print $4}') 
if [[ ${OUTPUT} -ge ${dbMaxCons}]]; then 
    echo "Success" 
    echo ${OUTPUT} 
else 
    echo ${OUTPUT} 
fi 

基本上我想要一個ccomplish將搜索sh目錄中的所有已滿足的文件,並且如果它們中的任何一個包含source*.sh(例如,source config.sh),則打印該文件(最終,我將擴展它並將其附加到當前文件的頂部,以便我可以通過ssh傳遞單個命令字符串..但在這裏我不認爲這是不相關的。)

我在做什麼錯?

+0

shellfile是一個文件,你想傳遞一個字符串。你可能必須首先枚舉這些行。通常用於在shellfile中對於re.findall(「/^source。*。sh」,行)中的匹配:' – njzk2 2014-10-17 17:37:22

回答

1

您正在嘗試運行的文件句柄shellFile一個regex.findall。您需要從該文件讀取數據,然後對讀取的數據運行正則表達式。

也許,這樣的事情?

with open(os.path.join(runPath, 'sh', commands[i][7:]),"r") as shellFile: 
    data = shellFile.read() 
    for matches in re.findall("/^source.*.sh", data): 
     print matches 
+0

這是我寫的同一個解決方案,但需要更多的一串代碼。它也使用更多的內存。 – Zav 2014-10-17 17:41:02

+0

這並不總是關於行數,特別是當改變是微不足道的時候。你可以在一行中編寫大量的Python代碼,這對讀者來說是無法解讀的。關鍵是要說明OP的錯誤。另外,我不確定我是否明白如何在一行中調用讀取佔用更多內存,而不是在接下來調用它。 – 2014-10-17 17:44:01

+0

1)OFc,但是如果你將行限制在80-100個字符以內,這不是問題,2)將數據分配給變量,並且內存清理只會在「with」關閉後纔會提升,並且隨着我對變體內存的清理將會提高findall方法之後 - 循環之前。 – Zav 2014-10-17 18:13:50

1

你忘了打電話給.read()方法

for matches in re.findall("/^source.*.sh", shellFile.read())