A simple Python library for creating and interacting with virtual terminals
VirtualTerm is a Python library designed for creating and managing virtual terminal sessions programmatically. It allows users to run interactive shell commands, handle command timeouts, and monitor output streams within isolated terminal environments. This library is particularly useful for developers building automation tools, testing environments, or managing interactive shell-based workflows.
import asyncio
from virtual_term import VirtualTerm
async def main():
with await VirtualTerm.spawn() as term:
term.write(b"sudo apt-get upgrade\n")
await asyncio.sleep(1)
print((await term.read_new_output()).decode())
term.write(b"y\n") # Respond with 'y' to confirm upgrade
result = await term.wait_for_last_command()
print(result.output.decode())
assert result.return_code == 0
asyncio.run(main())Install with pip:
pip install virtual-termYou can also use update_timeout and global_timeout to handle commands that hang / run indefinitely:
import asyncio
from pathlib import Path
from virtual_term import VirtualTerm, CommandTimeoutError
async def start_npm_server(project_dir: Path) -> VirtualTerm:
term = await VirtualTerm.spawn(cwd=project_dir)
try:
result = await term.run_command(
b"npm run dev",
update_timeout=2.0, # Max seconds to wait while output is "frozen" (no new output)
global_timeout=10.0 # Max total seconds to wait for the command
)
raise RuntimeError(result.output.decode().strip())
except CommandTimeoutError:
output = await term.read_new_output()
print("Server started in background! Server output:", output.decode().strip())
return term
asyncio.run(start_npm_server(Path("/path/to/your/project")))VirtualTerm uses Rye for dependency management and development workflows. To get started with development, ensure you have Rye installed, then clone the repository and set up the environment:
git clone https://github.com/MatthewScholefield/virtual-term.git
cd virtual-term
rye sync
rye run pre-commit install
# Run tests
rye test