使用正则表达式查找与Python中的模式匹配的所有行

时间:2014-10-17 17:34:53

标签: python regex file

我有:

# 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   

基本上我想要完成的是搜索sh目录中的所有specefied文件,如果其中任何文件包含source*.sh(例如source config.sh),则打印该文件(最终我将它扩展出来并将其附加到当前文件的顶部,以便我可以通过ssh传递单个命令字符串..但这不相关,我不认为。)

我做错了什么?

2 个答案:

答案 0 :(得分:2)

你忘了打电话给.read()方法

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

答案 1 :(得分:2)

您正尝试在文件句柄regex.findall上运行shellFile。您需要从该文件中读取,并对您读取的数据运行正则表达式。

也许,这样的事情?

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