forked from boxlite-ai/boxlite
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrun_commands.py
More file actions
98 lines (78 loc) · 2.63 KB
/
Copy pathrun_commands.py
File metadata and controls
98 lines (78 loc) · 2.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#!/usr/bin/env python3
"""
Execute commands and stream output via the REST API.
Demonstrates:
- box.exec() to run commands in a remote box
- Streaming stdout and stderr
- Exit codes and error handling
- Environment variables per command
- Using async context manager for auto start/stop
Prerequisites:
make dev:python
boxlite serve --port 8100
"""
import asyncio
from boxlite import ApiKeyCredential, Boxlite, BoxOptions, BoxliteRestOptions
SERVER_URL = "http://localhost:8100"
def connect() -> Boxlite:
return Boxlite.rest(BoxliteRestOptions(
url=SERVER_URL, credential=ApiKeyCredential("local-dev-key"),
))
async def main():
print("=" * 50)
print("REST API: Command Execution")
print("=" * 50)
rt = connect()
# Create and start a box
opts = BoxOptions(image="alpine:latest", auto_remove=False)
box = await rt.create(opts, name="exec-demo")
await box.start()
print(f" Box {box.id} started")
# --- Simple command ---
print("\n=== Simple Command ===")
execution = await box.exec("echo", args=["hello from REST API"])
stdout = execution.stdout()
async for line in stdout:
print(f" stdout: {line}")
result = await execution.wait()
print(f" exit_code: {result.exit_code}")
# --- Command with arguments ---
print("\n=== Command with Arguments ===")
execution = await box.exec("ls", args=["-la", "/"])
stdout = execution.stdout()
async for line in stdout:
print(f" {line}")
await execution.wait()
# --- Multi-line output (streaming) ---
print("\n=== Streaming Output ===")
execution = await box.exec(
"sh", args=["-c", "for i in 1 2 3; do echo \"line $i\"; done"],
)
stdout = execution.stdout()
count = 0
async for line in stdout:
count += 1
print(f" [{count}] {line}")
await execution.wait()
# --- Failed command (non-zero exit) ---
print("\n=== Failed Command ===")
execution = await box.exec("sh", args=["-c", "exit 42"])
result = await execution.wait()
print(f" exit_code: {result.exit_code}")
print(f" error_message: {result.error_message}")
# --- Environment variables ---
print("\n=== Per-Command Environment ===")
execution = await box.exec(
"sh", args=["-c", "echo GREETING=$GREETING"],
env=[("GREETING", "hello-from-rest")],
)
stdout = execution.stdout()
async for line in stdout:
print(f" {line}")
await execution.wait()
# --- Cleanup ---
await rt.remove(box.id, force=True)
print(f"\n Cleaned up box {box.id}")
print("\n Done")
if __name__ == "__main__":
asyncio.run(main())