Utilities for task management by creation and execution OS-specific scripts.
Project description
CommandScript
CommandScript is a Python library that provides utilities for task management through the creation and execution of OS-specific scripts. It simplifies cross-platform command execution by generating shell scripts (.sh for Unix-like systems, .bat for Windows) and handling logging, timing, and error checking automatically.
Based on the invoke library, it allows you to create collections of tasks running along the following pipeline:
Features
- Cross-platform script execution: Automatically generates and executes OS-specific scripts (Bash for Linux/macOS, Batch for Windows)
- ⚠️ MacOS (NOT TESTED)
- ✅ Linux (POSIX)
- Generates
.shBash scripts - Uses
bashfor execution - Measures execution time with nanosecond precision
- Generates
- ✅ Windows (NT)
- Generates
.batBatch scripts - Uses
cmd.exefor execution - Handles Windows path separators and quoting
- Supports delayed variable expansion
- Generates
- Task management: Built-in support for Invoke tasks with decorators
- each task you launch:
- will collect its log twice: in console and special file (defined for the task unique)
- if managed via
ScriptExecutorwill has two files for yourself:- script file:
path/to/.generated/your-script-task.(sh|bat) - script logs:
path/to/.generated/your-script-task.log
- script file:
- when task is finished:
- its script is saved and could be launch via terminal directly
- its execution log is saved and could be open in IDE for analytics
- each task you launch:
- Environment context: Global environment variable management for script execution
- Integrated logging: Colored console output and file logging with timestamps
- Error handling: Automatic return code checking and error logging on failures
- Timing: Execution duration measurement for performance monitoring
Installation
Install CommandScript using pip:
pip install commandcript
Dependencies
CommandScript requires the following dependencies (automatically installed):
invoke>=2.2.0- Task execution frameworkcolorama>=0.4.6- Cross-platform colored terminal text
Quick Start
✅ Good practice example you can see the tasks.py in this repository.
Basic Usage
import os
import commandcript
# Set up environment context
commandcript.ENV_CONTEXT \
.add_env_var('PROJECT_GIT_DIR', '/path/to/project') \
.add_env_var('COMMANDSCRIPT_SCRIPT_DIR', '${PROJECT_GIT_DIR}/scripts')
# Create and execute a simple command
executor = commandcript.ScriptExecutor(
log_dir=commandcript.ENV_CONTEXT.COMMANDSCRIPT_SCRIPT_DIR,
execute_created_script=True
)
executor.add_cwd('/path/to/working/directory') \
.add_command(['echo', 'Hello, World!']) \
.execute(log='hello_world')
Using with Invoke Tasks
import invoke
import commandcript
commandcript.ENV_CONTEXT.add_env_var('COMMANDSCRIPT_SCRIPT_DIR', '/path/to/folder/with/generated/scripts/.generated')
# Define a task
@commandcript.script_task()
def build(ctx):
"""Build the project"""
commandcript.ScriptExecutor(ctx.script_dir, ctx.launch) \
.add_cwd(commandcript.ENV_CONTEXT.PROJECT_GIT_DIR.hld) \
.add_command(['python', 'setup.py', 'build']) \
.execute(log='build')
# Create namespace and run
namespace = invoke.Collection()
namespace.add_task(build)
Environment Setup
commandcript.ENV_CONTEXT is a global instance of the EnvContext class, which is a specialized dictionary for storing environment variables as EnvVariable objects used across @commandcript.script_task() instances.
The EnvContext class provides additional functionality for managing environment variables, including the add_env_var method for retrieving OS environment variables with defaults and automatic variable substitution.
Variable substitution: You can use ${VAR} syntax in default values. The value will be stored in two forms:
.hld— hold value with OS-specific substitution placeholders (e.g.,$VARon POSIX,%VAR%on Windows).exp— fully expanded value with all substitutions resolved
Before using CommandScript, set up the environment context:
from src.commandcript import ENV_CONTEXT
ENV_CONTEXT\
.add_env_var('PROJECT_GIT_DIR', f'{__file__}/../')\
.add_env_var('COMMANDSCRIPT_SCRIPT_DIR', '${PROJECT_GIT_DIR}/.generated')\
.add_env_var('PROJECT_DIST_DIR', '${PROJECT_GIT_DIR}/dist')
# Access values
print(ENV_CONTEXT.PROJECT_DIST_DIR.hld) # ${PROJECT_GIT_DIR}/dist (or %PROJECT_GIT_DIR%/dist on Windows)
print(ENV_CONTEXT.PROJECT_DIST_DIR.exp) # /path/to/project/dist
Multi-command execution
import commandcript
commandcript.ENV_CONTEXT.add_env_var('LOG_DIR', '/path/to/logs')
executor = commandcript.ScriptExecutor(commandcript.ENV_CONTEXT.LOG_DIR, True)
executor.add_cwd('/tmp') \
.add_env({'MY_VAR': 'value'}) \
.add_command(['export', 'MY_VAR=override']) \
.add_command(['echo', '$MY_VAR']) \
.add_command(['ls', '-la']) \
.execute(log='multi_command')
Task with Parameters
@commandcript.script_task(
help={
'target': 'Build target (default: all)',
'clean': 'Clean before build'
}
)
def build(ctx, target='all', clean=False):
executor = commandcript.ScriptExecutor(ctx.script_dir, ctx.launch)
if clean:
executor.add_command(['make', 'clean'])
executor.add_command(['make', target]) \
.execute(log=f'build_{target}')
API Reference
ScriptExecutor
The main class for executing commands via OS-specific scripts.
- Constructor:
ScriptExecutor(log_dir: EnvVariable, execute_created_script: bool)
log_dir:EnvVariableobject pointing to the directory where log files and scripts will be stored (uses.expinternally)execute_created_script: If True, executes the generated script; if False, only generates it
- Methods
add_cwd(cwd: str): Set working directory for script executionadd_env(env: dict): Add environment variablesadd_command(command: list, enter=True, offset=True): Add a single commandadd_commands(commands: List[list], enter=True, offset=True): Add multiple commandsexecute(log: str = None): Execute the script and log output. On failure, logs the error without raising an exception.
EnvVariable
Represents a single environment variable with support for cross-platform substitution syntax.
- Properties
name: The variable namehld: Hold value with OS-specific substitution placeholders ($VARon POSIX,%VAR%on Windows)exp: Fully expanded value with all${VAR}substitutions resolved__str__(): Returns the hold value (.hld)
EnvContext
Specialized dictionary (Dict[str, EnvVariable]) for managing environment variables.
- Methods
add_env_var(env_var_name: str, default_value: str = None) -> EnvContext: Add an environment variable from OS environment with fallback to default value. Supports${VAR}substitution in default values.
@script_task()
Decorator for defining Invoke tasks with CommandScript integration.
@commandcript.script_task(
help={'param': 'Description'},
iterable=['param']
)
def my_task(ctx, param=None):
# Task implementation
pass
Logging
CommandScript provides colored logging utilities:
INFO: General information (blue)SUCCESS: Success messages (green)STATUS: Status updates (cyan)ERROR: Error messages (red)
import commandcript
commandcript.INFO.log_line("This is an info message")
commandcript.SUCCESS.log_line("Operation completed successfully")
commandcript.ERROR.log_line("An error occurred")
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file commandscript-1.2.1.tar.gz.
File metadata
- Download URL: commandscript-1.2.1.tar.gz
- Upload date:
- Size: 14.2 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.12.3
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
317cd55476840bb8ff9d5610128a11432ad7dc38becd7349d5d40f684e3bc7a6
|
|
| MD5 |
2485844bd50e20495d00c30026abf099
|
|
| BLAKE2b-256 |
d0469cb232318333106e231102532b4a822f921b910f3946ce5839396caf905a
|
File details
Details for the file commandscript-1.2.1-py3-none-any.whl.
File metadata
- Download URL: commandscript-1.2.1-py3-none-any.whl
- Upload date:
- Size: 13.3 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.12.3
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
b7d0e85717d1cbf6fb4be6a049eeaf1c626d121cb8659754fea6312df0ab46fe
|
|
| MD5 |
c0fad85040f5e8fd808d399c9e3bd24e
|
|
| BLAKE2b-256 |
af852d37d792faecba6f088c6c2192505dfdef81356a6d60ad269f7001228af4
|