- Katılım
- 6 Mayıs 2022
- Konular
- 48,270
- Mesajlar
- 48,580
- Tepkime puanı
- 74
- M2 Yaşı
- 3 yıl 11 ay 10 gün
- Trophy Puan
- 48
- M2 Yang
- 488,669
Gereksiz Import Tespit
Python projelerinde kullanılmayan importları tespit etmek için hazırladığım küçük bir analiz scriptini paylaşıyorum.
Python’un kendi kod analiz yapısını kullanarak dosyaları inceler. Kullanılmayan importları satır numarasıyla birlikte raporlar.
Python projelerinde kullanılmayan importları tespit etmek için hazırladığım küçük bir analiz scriptini paylaşıyorum.
Python’un kendi kod analiz yapısını kullanarak dosyaları inceler. Kullanılmayan importları satır numarasıyla birlikte raporlar.
Kod:
import os import ast class ImportAnalyzer(ast.NodeVisitor): def __init__(self): self.imports = {} self.used_names = set() def visit_Import(self, node): for alias in node.names: name = alias.asname or alias.name.split('.')[0] self.imports[name] = node.lineno self.generic_visit(node) def visit_ImportFrom(self, node): if node.names[0].name == "*": return for alias in node.names: name = alias.asname or alias.name self.imports[name] = node.lineno self.generic_visit(node) def visit_Name(self, node): self.used_names.add(node.id) self.generic_visit(node) def visit_Attribute(self, node): if isinstance(node.value, ast.Name): self.used_names.add(node.value.id) self.generic_visit(node) def safe_read(path): for enc in ("utf-8", "cp1254", "latin-1"): try: with open(path, "r", encoding=enc) as f: return f.read() except UnicodeDecodeError: continue # En son çare with open(path, "r", errors="ignore") as f: return f.read() def find_unused_imports(py_file): try: source = safe_read(py_file) tree = ast.parse(source, filename=py_file) except (SyntaxError, ValueError): return None analyzer = ImportAnalyzer() analyzer.visit(tree) return { name: line for name, line in analyzer.imports.items() if name not in analyzer.used_names } def scan_folder(root_folder): results = {} for root, _, files in os.walk(root_folder): for file in files: if file.endswith(".py"): path = os.path.join(root, file) unused = find_unused_imports(path) if unused: results[path] = unused return results if __name__ == "__main__": folder = input("Taranacak klasör yolu: ").strip() report = scan_folder(folder) if not report: print("🎉 Gereksiz import bulunamadı.") else: print("\n🚨 GEREKSİZ IMPORTLAR:\n") for file, imports in report.items(): print(f"📄 {file}") for name, line in imports.items(): print(f" - {name} (satır {line})") print()
Python – Gereksiz Import Tespit Scripti Nedir?
Python dili, özellikle büyük projelerde oldukça fazla modül ve kütüphane kullanımına olanak tanır. Ancak zamanla projenin büyümesiyle birlikte bazı import ifadeleri artık kullanılmaz hale gelebilir. Bu gereksiz importlar, hem performansı düşürebilir hem de kod okunabilirliğini bozabilir. Bu nedenle, gereksiz importları tespit eden bir script geliştirmek, projenin kalitesini artırmak açısından son derece faydalıdır.
Metin2 Geliştirme Sürecinde Neden Gereksiz Import Temizliği Yapmalıyız?
Metin2 özel sunucularında, genellikle Python ile yazılmış GUI sistemleri, oyun içi komutlar veya admin panelleri yer alır. Özellikle py root ve uiscript dosyalarında yapılan import işlemleri zamanla kontrol edilemeyebilir. Bu durumda, kullanılmayan importlar hafızayı gereksiz yere tüketebilir ve derleme süresini uzatabilir. Ayrıca, source edit yaparken bu tür temizlikler, kodun sürdürülebilirliğini artırır.
Python ile Gereksiz Importları Otomatik Tespit Eden Script
Aşağıda, Python ile yazılmış bir script örneği yer almaktadır. Bu script, belirtilen bir dizindeki tüm .py uzantılı dosyaları tarayarak, import edilen fakat kullanılmayan modülleri listeler.
Kod:
import ast[BR][/BR]import os[BR][/BR][BR][/BR]def find_unused_imports(file_path):[BR][/BR] with open(file_path, 'r', encoding='utf-8') as file:[BR][/BR] try:[BR][/BR] tree = ast.parse(file.read()) # Syntax tree'yi oluştur[BR][/BR] except SyntaxError:[BR][/BR] return [*] # Hatalı dosya varsa boş döner[BR][/BR][BR][/BR] imported_names = {}[BR][/BR] used_names = set()[BR][/BR][BR][/BR] for node in ast.walk(tree):[BR][/BR] if isinstance(node, ast.Import):[BR][/BR] for alias in node.names:[BR][/BR] imported_names[alias.asname or alias.name] = alias.name[BR][/BR] elif isinstance(node, ast.ImportFrom):[BR][/BR] for alias in node.names:[BR][/BR] imported_names[alias.asname or alias.name] = f'{node.module}.{alias.name}'[BR][/BR] elif isinstance(node, ast.Name): # Kullanılan isimleri tespit et[BR][/BR] used_names.add(node.id)[BR][/BR] elif isinstance(node, ast.Attribute): # foo.bar şeklindekiler için[BR][/BR] if isinstance(node.value, ast.Name):[BR][/BR] used_names.add(node.value.id)[BR][/BR][BR][/BR] unused = {k: v for k, v in imported_names.items() if k not in used_names}[BR][/BR] return unused[BR][/BR][BR][/BR]def scan_directory(directory):[BR][/BR] for root, _, files in os.walk(directory):[BR][/BR] for file in files:[BR][/BR] if file.endswith('.py'):[BR][/BR] file_path = os.path.join(root, file)[BR][/BR] unused = find_unused_imports(file_path)[BR][/BR] if unused:[BR][/BR] print(f'{file_path} dosyasında kullanılmayan importlar: {unused}')[BR][/BR]
Scriptin Kullanımı ve Uygulaması
Yukarıdaki scripti çalıştırmak için, scan_directory('proje_dizini') fonksiyonunu çağırmanız yeterlidir. Bu sayede, belirttiğiniz dizindeki tüm Python dosyaları taranacak ve kullanılmayan importlar ekrana yazdırılacaktır. Bu script, özellikle Metin2 py gui geliştirme süreçlerinde büyük kolaylık sağlar.
Sonuç
Metin2 development sürecinde, kod temizliği ve performans optimize etme çok önemlidir. Bu script sayesinde, gereksiz importları hızlıca tespit edip temizleyebilirsiniz. Böylece hem daha sade hem de daha hızlı çalışan bir sistem elde edersiniz.
What Is a Python Script to Detect Unused Imports?
Python allows extensive use of modules and libraries, especially in large projects. However, as projects grow over time, some import statements may become obsolete. These unnecessary imports can reduce performance and impair code readability. Therefore, developing a script to detect unused imports is highly beneficial for improving project quality.
Why Should We Clean Up Unused Imports During Metin2 Development?
In Metin2 private servers, Python-based GUI systems, in-game commands, or admin panels are commonly used. Especially within py root and uiscript files, import operations can gradually become unmanageable. In such cases, unused imports can unnecessarily consume memory and extend compilation time. Additionally, during source edits, such cleanups enhance code maintainability.
Python Script to Automatically Detect Unused Imports
Below is a Python script that scans all .py files in a given directory and lists modules that are imported but not used.
Kod:
import ast[BR][/BR]import os[BR][/BR][BR][/BR]def find_unused_imports(file_path):[BR][/BR] with open(file_path, 'r', encoding='utf-8') as file:[BR][/BR] try:[BR][/BR] tree = ast.parse(file.read()) # Create syntax tree[BR][/BR] except SyntaxError:[BR][/BR] return [*] # Return empty if there's an error[BR][/BR][BR][/BR] imported_names = {}[BR][/BR] used_names = set()[BR][/BR][BR][/BR] for node in ast.walk(tree):[BR][/BR] if isinstance(node, ast.Import):[BR][/BR] for alias in node.names:[BR][/BR] imported_names[alias.asname or alias.name] = alias.name[BR][/BR] elif isinstance(node, ast.ImportFrom):[BR][/BR] for alias in node.names:[BR][/BR] imported_names[alias.asname or alias.name] = f'{node.module}.{alias.name}'[BR][/BR] elif isinstance(node, ast.Name): # Identify used names[BR][/BR] used_names.add(node.id)[BR][/BR] elif isinstance(node, ast.Attribute): # For cases like foo.bar[BR][/BR] if isinstance(node.value, ast.Name):[BR][/BR] used_names.add(node.value.id)[BR][/BR][BR][/BR] unused = {k: v for k, v in imported_names.items() if k not in used_names}[BR][/BR] return unused[BR][/BR][BR][/BR]def scan_directory(directory):[BR][/BR] for root, _, files in os.walk(directory):[BR][/BR] for file in files:[BR][/BR] if file.endswith('.py'):[BR][/BR] file_path = os.path.join(root, file)[BR][/BR] unused = find_unused_imports(file_path)[BR][/BR] if unused:[BR][/BR] print(f'Unused imports in {file_path}: {unused}')[BR][/BR]
Usage and Application of the Script
To run this script, simply call the function scan_directory('project_directory'). This will scan all Python files in the specified directory and print out unused imports. This script greatly facilitates processes during Metin2 py gui development.
Conclusion
In the Metin2 development process, code cleanup and performance optimization are crucial. With this script, you can quickly detect and remove unused imports. This way, you obtain a cleaner and faster-running system.
