匹配模式的我都行:使用正則表達式查找在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傳遞單個命令字符串..但在這裏我不認爲這是不相關的。)
我在做什麼錯?
shellfile是一個文件,你想傳遞一個字符串。你可能必須首先枚舉這些行。通常用於在shellfile中對於re.findall(「/^source。*。sh」,行)中的匹配:' – njzk2 2014-10-17 17:37:22