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

2 投票
2 回答
12053 浏览
提问于 2025-04-28 04:12

我有:

# 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目录下所有指定的文件,如果其中任何一个文件包含source*.sh(比如说source config.sh),就打印出那个文件(最终我会把它扩展并添加到当前文件的顶部,这样我就可以通过ssh传递这个单一的命令字符串……不过我觉得这在这里不是重点)。

我哪里做错了?

暂无标签

2 个回答

2

你忘了调用 .read() 方法了

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

你想在文件句柄 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

撰写回答