使用sed解释多行条件

2024-04-20 06:19:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直致力于构造一个sed表达式来解析python文件的导入并提取模块的名称。你知道吗

这是一个简单的例子,我解决使用(我需要的输出是模块名称没有'作为'或任何空格..):

from testfunctions import mod1, mod2 as blala, mod3, mod4

到目前为止我所拥有的:

grep -ir "from testfunctions import" */*.py | sed -E s/'\s+as\s+\w+'//g | sed -E s/'from testfunctions import\s+'//g

在上述情况下,这确实可以得到所需的结果。你知道吗

问题: 在导入类似的文件中:

from testfunctions import mod1, mod2 as blala, mod3, mod4 \
     mod5, mod6 as bla, mod7 \
   mod8, mod9 ...

有什么办法可以改进我的管道表达式来处理多行吗?


Tags: 模块文件fromimport名称表达式assed
2条回答

试试这个

   sed -n -r '/from/,/^\s*$/p;' *.py | sed ':x; /\\$/ { N; s/\\\n//; tx }'  | sed 's/^.*.import//g;s/  */ /g'

谢谢大家的帮助。我不知道像ast这样的模块存在。。它真的帮助我实现了我的目标。你知道吗

我把我需要的解决方案的一个简单版本放在一起,如果其他人也遇到这个问题,我只是作为参考:

import glob
import ast

moduleList = []
# get all .py file names
testFiles = glob.glob('*/*.py')
for testFile in testFiles:
    with open(testFile) as code:
        # ast.parse creates the tree off of plain code
        tree = ast.parse(code.read())
        # there are better ways to traverse the tree, in this sample there
        # is no guarantee to the traversal order
        for node in ast.walk(tree):
            if isinstance(node, ast.ImportFrom) and node.module == 'testfunctions':
                # each node will contain an ast.ImportFrom instance which
                # data members are: module, names(list of ast.alias) and level
                moduleList.extend([alias.name for alias in node.names])

你可以在这里阅读更多关于它的信息:https://greentreesnakes.readthedocs.io/en/latest/manipulating.html#inspecting-nodes

相关问题 更多 >