Skip to content

Instantly share code, notes, and snippets.

@salamantos
Created March 19, 2020 18:55
Show Gist options
  • Save salamantos/d2b56a0b31b227d2d91e0d020c662625 to your computer and use it in GitHub Desktop.
Save salamantos/d2b56a0b31b227d2d91e0d020c662625 to your computer and use it in GitHub Desktop.
Parse python libraries
import re
from typing import List
def parse_dependencies(file_path: str) -> List[str]:
"""
:param file_path - path of file to be parsed
:return list of strings
Example file.py:
import numpy
from pandas import ndarray,\
kekule
import matplotlib as plt
def f():
from re import findall
import ku_le42
Returns:
['numpy', 'pandas', 'matplotlib', 're', 'ku_le42']
"""
libraries = []
with open(file_path, 'r') as file:
for line in file:
library = re.match(r'^\s*import\s([\w\d_]+)\s', line)
if library and library.group(1):
libraries.append(library.group(1))
else:
library = re.match(r'^\s*from\s([\w\d_]+)\simport', line)
if library and library.group(1):
libraries.append(library.group(1))
return libraries
if __name__ == '__main__':
print(parse_dependencies('file.py'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment