# Title: Python Requirements File Generator # Author: K0NxT3D # Description: Generate requirements.txt file script for Python. # Original File: genreq.py import ast import sys import argparse import pkg_resources import importlib.util def get_installed_packages(): # Get a list of installed packages and their versions installed_packages = {pkg.key: pkg.version for pkg in pkg_resources.working_set} return installed_packages def is_standard_lib(module_name): """Check if the module is part of the standard library.""" # Check if the module can be found in the standard library spec = importlib.util.find_spec(module_name) return spec is not None and 'site-packages' not in spec.origin def generate_requirements(file_path): # Open and read the Python file with open(file_path, 'r') as file: tree = ast.parse(file.read()) # Extract all the import statements imports = set() for node in ast.walk(tree): if isinstance(node, ast.Import): for alias in node.names: imports.add(alias.name) elif isinstance(node, ast.ImportFrom): imports.add(node.module) # Get installed packages installed_packages = get_installed_packages() # Filter out standard library modules and keep only third-party libraries third_party = [] for module in imports: if not is_standard_lib(module): # Only third-party modules if module in installed_packages: third_party.append(f"{module}=={installed_packages[module]}") # Write to requirements.txt with open('requirements.txt', 'w') as req_file: for package in third_party: req_file.write(package + '\n') print("requirements.txt file generated successfully.") def main(): # Set up command-line argument parsing parser = argparse.ArgumentParser(description="Generate a requirements.txt file from a Python script.") parser.add_argument('file', help="Path to the Python file to analyze.") args = parser.parse_args() # Ensure the file exists try: generate_requirements(args.file) except FileNotFoundError: print(f"Error: The file '{args.file}' does not exist.") sys.exit(1) if __name__ == "__main__": main()