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

标签 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 目录中的所有指定文件,如果其中任何一个包含 source*.sh(例如,source config.sh), 打印那个文件(最终我会把它展开并将它附加到当前文件的顶部,这样我就可以通过 ssh 传递单个命令字符串..但这不相关在这里我不认为。)

我做错了什么?

最佳答案

您正在尝试在文件句柄 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

关于python - 使用正则表达式查找与 Python 中的模式匹配的所有行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26430429/

相关文章:

python - 在 Sublime 3 中运行自定义命令之前保存所有文件

javascript - 使用正则表达式以代码格式分离innerHTML元素

Python 正则表达式解析

c++ - 从文件对象到文件名

Java如何指定给定文件的扩展名

python - 如何一一读取RabbitMQ队列消息

python - SQLAlchemy 不包括 DELETE 中的 CTE

php - 我如何使用 php 检测字符串中的 iso8859-8 和 utf8 希伯来字符

java - 从 Uri 获取路径

python - 如何阻止 Scrapy CrawlSpider 跟踪超出所需的 URL?