Efficient tool for running Python code in isolated subprocesses.
A simple and efficient way to execute arbitrary Python functions in subprocesses, while seamlessly relaying runtime information back to the main process. It is especially useful for diagnosing and resolving system issues that might otherwise crash the Python interpreter.
Designed with minimal dependencies and an intuitive interface, this tool makes it easy to execute any Python callable.
Install the library using pip:
pip install subprocess-executionClone the repository and install:
git clone https://github.com/joshwadd/subprocess-execution.git
cd subprocess-execution
pip install .First, import the run_in_subprocess decorator from the module:
from subprocess_execution import run_in_subprocessApply the @run_in_subprocess decorator to any function you want to execute in a subprocess:
@run_in_subprocess()
def my_function(arg1, arg2):
# Function logic here
return arg1 + arg2Call the function as usual:
result = my_function(5, 10)
print(result) # Output: 15You can specify a timeout (in seconds) after which the subprocess will be terminated if the function hasn't completed:
@run_in_subprocess(timeout_seconds=300) # Timeout after 5 minutes
def long_running_function():
# Potentially long-running operations
...If an exception occurs within the subprocess, it will be raised in the parent process:
@run_in_subprocess()
def faulty_function():
raise ValueError("An error occurred")
try:
faulty_function()
except Exception as e:
print(f"Caught an exception: {e}")from subprocess_execution import run_in_subprocess
@run_in_subprocess(timeout_seconds=10)
def compute_sum(numbers):
total = 0
for num in numbers:
total += num
return total
if __name__ == "__main__":
numbers = list(range(1000000))
try:
result = compute_sum(numbers)
print(f"The sum is: {result}")
except Exception as e:
print(f"An error occurred: {e}")This project is licensed under the MIT License.
For questions or feedback, feel free to reach out:
Email: josh.waddington1@gmail.com