整体导入转换为局部导入
def import_from_whole_to_part(
src_python_path, dst_python_path, module_name='cv2'
):
with open(src_python_path, 'r', encoding='utf-8') as f:
dst_line_list = []
import_name_list = []
insert_import_name_index = -1
convert_flag = True
f_readlines = f.readlines()
for i, line in enumerate(f_readlines):
if module_name not in line :
dst_line_list.append(line)
else:
if line.startswith("from"):
convert_flag = False
break
else:
if line.startswith("import"):
dst_line_list.append(f'from {module_name} import (\n')
dst_line_list.append(')\n')
insert_import_name_index = i+1
elif line.strip()[0] == "#":
dst_line_list.append(line)
else:
dst_line_list.append(line.replace(f'{module_name}.', ''))
module_name_index_list = []
module_name_index = line.find(module_name)
while module_name_index != -1:
module_name_index_list.append(module_name_index)
module_name_index = line.find(module_name, module_name_index+1)
function_name_end_index = -1
line_len = len(line)
for module_name_index in module_name_index_list:
function_name_begin_index = module_name_index + 4
for j in range(function_name_begin_index+1, line_len):
line_str = line[j]
if (
line_str == '(' or line_str == ','
or line_str == '\n' or line_str == ')'
):
function_name_end_index = j
break
import_name_list.append(
line[function_name_begin_index:function_name_end_index]
)
if not import_name_list:
convert_flag = False
if convert_flag:
import_name_list = sorted(list(set(import_name_list)))
for import_name in import_name_list[::-1]:
dst_line_list.insert(
insert_import_name_index, f' {import_name},\n'
)
with open(dst_python_path, 'w', encoding='utf-8') as ff:
ff.writelines(dst_line_list)
if __name__ == '__main__':
src_python_path = "./test.py"
dst_python_path = "./test_part.py"
import_from_whole_to_part(src_python_path, dst_python_path)