Created
May 13, 2021 14:40
-
-
Save nijkah/2098f0e074894bd0730ea3265444f4a2 to your computer and use it in GitHub Desktop.
This code converts code for import relative module to absolute path in all files.
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 os | |
import sys | |
from pathlib import Path | |
import fileinput | |
def get_all_files(parent_folder): | |
return list(Path(parent_folder).rglob("*")) | |
def main(target_path, root_level=1): | |
file_paths = get_all_files(target_path) | |
for file_path in file_paths: | |
if os.path.isdir(file_path) or str(file_path).split('.')[-1] == 'pyc': | |
continue | |
file_path = str(file_path) | |
filename = file_path.split("/")[-1] | |
dirname = os.path.dirname(file_path) | |
parent_path = str(Path(file_path).parent.parent) | |
if filename == "__init__.py": | |
continue | |
for line in fileinput.input([file_path], inplace=True): | |
flag = True | |
if "import" not in line: | |
flag = False | |
try: | |
target_module = line.split()[1] | |
function = line.split()[-1] | |
except: | |
target_module = line | |
function = line | |
flag = False | |
if not target_module.startswith(".."): | |
flag = False | |
if target_module == '..': | |
import_path = parent_path.replace("/", ".") | |
else: | |
import_path = os.path.join(parent_path, target_module[2:]).replace("/", ".") | |
if flag: | |
sys.stdout.write(line.replace(target_module, import_path)) | |
else: | |
sys.stdout.write(line) | |
if __name__ == "__main__": | |
target_path = "SIALibs" | |
main(target_path) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment