Created
March 19, 2020 18:55
-
-
Save salamantos/d2b56a0b31b227d2d91e0d020c662625 to your computer and use it in GitHub Desktop.
Parse python libraries
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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