CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-pyarmor

A command-line tool for obfuscating Python scripts, binding obfuscated scripts to specific machines, and setting expiration dates

Pending
Overview
Eval results
Files

project-management.mddocs/

Project Management

PyArmor provides comprehensive project management capabilities for organizing and maintaining obfuscation workflows. Projects store configuration settings, manage source files, and provide batch processing for complex applications with multiple scripts and dependencies.

Capabilities

Legacy Project Class (v7)

Classic project management with dictionary-based configuration and file-based persistence.

class Project(dict):
    """
    PyArmor project management class inheriting from dict.
    Stores all project configuration as key-value pairs.
    """
    
    def open(self, path: str) -> None:
        """
        Open existing project from configuration file.
        
        Args:
            path (str): Path to project configuration file (.json)
            
        Raises:
            FileNotFoundError: If project file doesn't exist
            ValueError: If project file format is invalid
        """
    
    def save(self, path: str) -> None:
        """
        Save project configuration to file.
        
        Args:
            path (str): Output path for project file (.json)
            
        Raises:
            PermissionError: If unable to write to path
            OSError: If disk space insufficient
        """
    
    def check(self) -> bool:
        """
        Validate project configuration and file consistency.
        
        Returns:
            bool: True if project is valid and consistent
            
        Raises:
            ProjectError: If validation fails with details
        """
    
    def get_build_files(self, force: bool = False, excludes: list = []) -> list:
        """
        Get list of files to be obfuscated based on project settings.
        
        Args:
            force (bool): Force inclusion of all files ignoring timestamps
            excludes (list): Additional patterns to exclude from build
            
        Returns:
            list: List of file paths to obfuscate
        """
    
    def info(self) -> str:
        """
        Generate formatted project information string.
        
        Returns:
            str: Multi-line formatted project summary
        """
    
    def _update(self, **kwargs) -> None:
        """
        Update project settings with keyword arguments.
        
        Args:
            **kwargs: Configuration options to update
        """
    
    @classmethod
    def build_manifest(cls, manifest: str, path: str = None) -> list:
        """
        Build file list from manifest template using distutils.
        
        Args:
            manifest (str): Manifest template content
            path (str, optional): Base path for file resolution
            
        Returns:
            list: List of file paths matching manifest patterns
        """
    
    @classmethod 
    def build_globfiles(cls, patterns: list, path: str = '') -> list:
        """
        Build file list from glob patterns.
        
        Args:
            patterns (list): List of glob patterns to match
            path (str): Base path for pattern matching (default: '')
            
        Returns:
            list: List of file paths matching glob patterns
        """

Modern Project Management (v8+)

Enhanced project management with improved configuration handling and context integration.

class Project:
    """
    Modern PyArmor project management with enhanced features.
    """
    
    def __init__(self, ctx=None):
        """
        Initialize project with optional context.
        
        Args:
            ctx (Context, optional): PyArmor context instance
        """
    
    def create(self, path: str, **kwargs) -> None:
        """
        Create new project at specified path.
        
        Args:
            path (str): Project directory path
            **kwargs: Initial project configuration
        """
    
    def load(self, path: str) -> None:
        """
        Load existing project from directory.
        
        Args:
            path (str): Project directory path
        """
    
    def configure(self, **options) -> None:
        """
        Update project configuration options.
        
        Args:
            **options: Configuration key-value pairs
        """
    
    def build(self, **kwargs) -> None:
        """
        Build project with current configuration.
        
        Args:
            **kwargs: Build-specific options
        """

Project Configuration Attributes

# Core Settings
class ProjectSettings:
    name: str          # Project name identifier
    title: str         # Human-readable project title
    src: str           # Source directory path (default: "src")
    output: str        # Output directory path (default: "dist")
    entry: str         # Main entry script name
    
    # File Management
    includes: list     # File patterns to include
    excludes: list     # File patterns to exclude
    manifest: str      # Manifest template for file discovery
    
    # Obfuscation Settings
    obf_code: int      # Code obfuscation level (0=off, 1=on, 2=advanced)
    obf_mod: int       # Module obfuscation (0=off, 1=on)
    wrap_mode: int     # Wrap mode (0=off, 1=on)
    advanced_mode: int # Advanced protection level (0-5)
    
    # Runtime Settings  
    runtime_path: str      # Runtime package path
    package_runtime: int   # Package runtime with scripts (0=off, 1=on)
    bootstrap_code: int    # Bootstrap code generation (0=off, 1=on)
    
    # Security Settings
    restrict_mode: int     # Restriction level (0=none, 1=import, 2=private, 3=restrict)
    cross_protection: int  # Cross-script protection (0=off, 1=on)
    license_file: str      # License file path
    
    # Platform Settings
    platform: str          # Target platform specification
    mixins: list          # Platform-specific mixins
    
    # Plugin Settings  
    plugins: list         # Enabled plugins list
    plugin_options: dict  # Plugin configuration options

Project Operations

Creating Projects

from pyarmor.project import Project

# Create new project
proj = Project()
proj.name = "MyApplication"
proj.title = "My Python Application"
proj.src = "src"
proj.output = "dist"
proj.entry = "main.py"

# Configure obfuscation
proj.obf_code = 1          # Enable code obfuscation
proj.obf_mod = 1           # Enable module obfuscation
proj.wrap_mode = 1         # Enable wrap mode
proj.advanced_mode = 2     # Super mode protection
proj.restrict_mode = 2     # Private mode

# Configure runtime
proj.package_runtime = 1   # Package runtime files
proj.bootstrap_code = 1    # Generate bootstrap

# Save project
proj.save("myapp.json")

Loading and Building Projects

# Load existing project
proj = Project()
proj.open("myapp.json")

# Validate project
if proj.check():
    print("Project is valid")
    
# Get files to build
files = proj.get_build_files()
print(f"Building {len(files)} files")

# Show project information
print(proj.info())

# Update configuration
proj._update(
    obf_code=2,           # Advanced code obfuscation
    mix_str=1,            # Enable string mixing
    expired="2024-12-31"  # Set expiration
)

# Save updated configuration
proj.save("myapp.json")

Project Directory Structure

myproject/
├── myapp.json          # Project configuration file
├── src/                # Source directory
│   ├── main.py        # Entry script
│   ├── module1.py     # Application modules
│   └── package/       # Sub-packages
├── dist/              # Output directory (generated)
│   ├── main.py        # Obfuscated entry script
│   ├── module1.py     # Obfuscated modules
│   ├── package/       # Obfuscated packages
│   └── pyarmor_runtime_000000/  # Runtime files
└── .pyarmor_config    # Local configuration (optional)

File Discovery and Management

Include/Exclude Patterns

# Configure file patterns
proj.includes = [
    "src/**/*.py",        # All Python files in src
    "lib/*.py",           # Python files in lib
    "!src/test_*.py"      # Exclude test files
]

proj.excludes = [
    "__pycache__",        # Python cache directories
    "*.pyc",              # Compiled Python files
    "test/",              # Test directory
    "docs/",              # Documentation
    ".git"                # Version control
]

# Custom manifest template
proj.manifest = """
global-include *.py
recursive-exclude test *
recursive-exclude docs *
prune __pycache__
"""

Build File Resolution

# Get all files to build
all_files = proj.get_build_files()

# Force rebuild (ignore timestamps)
force_files = proj.get_build_files(force=True)

# Exclude additional patterns
filtered_files = proj.get_build_files(excludes=["vendor/", "*.bak"])

# Process build files
for filepath in all_files:
    print(f"Processing: {filepath}")
    # Obfuscation logic here

Advanced Project Features

Cross-Platform Projects

# Configure for multiple platforms
proj.platform = "linux.x86_64,windows.x86_64,darwin.x86_64"

# Platform-specific settings
proj.mixins = [
    "windows:--advanced 2",
    "linux:--restrict 1", 
    "darwin:--package-runtime 0"
]

Plugin Integration

# Enable plugins
proj.plugins = ["check_ntp_time", "assert_armored"]

# Plugin configuration
proj.plugin_options = {
    "check_ntp_time": {
        "server": "pool.ntp.org",
        "timeout": 10
    },
    "assert_armored": {
        "threshold": 0.8
    }
}

License Integration

# Configure project license
proj.license_file = "licenses/app.lic"

# License-specific obfuscation
proj.cross_protection = 1    # Enable cross protection
proj.restrict_mode = 3       # Restrict mode for license validation

Error Handling

from pyarmor.project import Project, ProjectError

try:
    proj = Project()
    proj.open("nonexistent.json")
except FileNotFoundError:
    print("Project file not found")
except ProjectError as e:
    print(f"Project error: {e}")

try:
    proj.check()
except ProjectError as e:
    print(f"Project validation failed: {e}")
    # Handle validation errors
    
# Graceful handling of build issues
files = proj.get_build_files()
if not files:
    print("No files to build - check project configuration")

Install with Tessl CLI

npx tessl i tessl/pypi-pyarmor

docs

cli.md

configuration.md

index.md

licensing.md

obfuscation.md

platform-support.md

project-management.md

tile.json