Regex To Parse Import Statements In Python
can someone help me writing single regex to get module(s) from python source line? from abc.lmn import pqr from abc.lmn import pqr as xyz import abc import abc as xyz it has 3 sub
Solution 1:
Instead of using a regex, using the built in python library ast might be a better approach. https://docs.python.org/2/library/ast.html You can use it to parse python syntax.
import ast
import_string = """from abc.lmn import pqr
from abc.lmn import pqr as xyz
import abc
import abc as xyz"""
modules = []
for node in ast.iter_child_nodes(ast.parse(import_string)):
if isinstance(node, ast.ImportFrom):
if not node.names[0].asname: # excluding the 'as' part of import
modules.append(node.module)
elif isinstance(node, ast.Import): # excluding the 'as' part of import
if not node.names[0].asname:
modules.append(node.names[0].name)
that will give you ['abc.lmn', 'abc'] and it is fairly easy to tweak if you want to pull other information.
Post a Comment for "Regex To Parse Import Statements In Python"