-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathquick_start_example.py
More file actions
274 lines (215 loc) Β· 9 KB
/
quick_start_example.py
File metadata and controls
274 lines (215 loc) Β· 9 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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
#!/usr/bin/env python3
"""
Quick Start Example for Grainchain
This example demonstrates the core functionality of Grainchain in a simple,
easy-to-understand format. Perfect for getting started!
Run this example:
python examples/quick_start_example.py
"""
import asyncio
from grainchain import Sandbox
async def hello_world_example():
"""Basic 'Hello World' example."""
print("ποΈ Grainchain Quick Start Example")
print("=" * 40)
print("\n1. Creating a sandbox...")
async with Sandbox() as sandbox:
print(f" β
Sandbox created: {sandbox.sandbox_id}")
print(f" π Provider: {sandbox.provider_name}")
print("\n2. Executing a simple command...")
result = await sandbox.execute("echo 'Hello, Grainchain!'")
print(" π€ Command: echo 'Hello, Grainchain!'")
print(f" π₯ Output: {result.stdout.strip()}")
print("\n3. Running Python code...")
result = await sandbox.execute("python3 -c 'print(2 + 2)'")
print(" π€ Command: python3 -c 'print(2 + 2)'")
print(f" π₯ Output: {result.stdout.strip()}")
print("\n4. Creating and running a Python file...")
python_code = """
print("Hello from a Python file!")
print(f"The answer to everything is: {6 * 7}")
# Simple calculation
numbers = [1, 2, 3, 4, 5]
total = sum(numbers)
print(f"Sum of {numbers} = {total}")
"""
await sandbox.upload_file("hello.py", python_code)
print(" β
Uploaded hello.py")
result = await sandbox.execute("python3 hello.py")
print(" π€ Command: python3 hello.py")
print(" π₯ Output:")
for line in result.stdout.strip().split("\n"):
print(f" {line}")
print("\n5. Working with files...")
# List files in the sandbox
files = await sandbox.list_files(".")
print(
f" π Files in sandbox: {[f.name for f in files if not f.is_directory]}"
)
# Download the file we created
content = await sandbox.download_file("hello.py")
print(f" π₯ Downloaded hello.py ({len(content)} bytes)")
print("\nβ
Quick start example completed successfully!")
async def data_processing_example():
"""Simple data processing example."""
print("\n" + "=" * 40)
print("π Data Processing Example")
print("=" * 40)
# Create a simple data processing script
data_script = """
import json
import csv
from datetime import datetime
# Sample data
sales_data = [
{"date": "2024-01-01", "product": "Widget A", "sales": 100, "price": 10.99},
{"date": "2024-01-01", "product": "Widget B", "sales": 75, "price": 15.50},
{"date": "2024-01-02", "product": "Widget A", "sales": 120, "price": 10.99},
{"date": "2024-01-02", "product": "Widget B", "sales": 90, "price": 15.50},
{"date": "2024-01-03", "product": "Widget A", "sales": 80, "price": 10.99},
{"date": "2024-01-03", "product": "Widget B", "sales": 110, "price": 15.50},
]
print("Processing sales data...")
# Calculate totals
total_sales = sum(item["sales"] for item in sales_data)
total_revenue = sum(item["sales"] * item["price"] for item in sales_data)
print(f"Total units sold: {total_sales}")
print(f"Total revenue: ${total_revenue:.2f}")
# Group by product
product_totals = {}
for item in sales_data:
product = item["product"]
if product not in product_totals:
product_totals[product] = {"sales": 0, "revenue": 0}
product_totals[product]["sales"] += item["sales"]
product_totals[product]["revenue"] += item["sales"] * item["price"]
print("\\nSales by product:")
for product, totals in product_totals.items():
print(f" {product}: {totals['sales']} units, ${totals['revenue']:.2f}")
# Save results to JSON
results = {
"summary": {
"total_sales": total_sales,
"total_revenue": total_revenue,
"processed_at": datetime.now().isoformat()
},
"by_product": product_totals
}
with open("sales_results.json", "w") as f:
json.dump(results, f, indent=2)
print("\\nβ
Results saved to sales_results.json")
"""
async with Sandbox() as sandbox:
print("\n1. Uploading data processing script...")
await sandbox.upload_file("process_data.py", data_script)
print(" β
Script uploaded")
print("\n2. Running data processing...")
result = await sandbox.execute("python3 process_data.py")
if result.success:
print(" β
Processing completed successfully!")
print(" π₯ Output:")
for line in result.stdout.strip().split("\n"):
print(f" {line}")
print("\n3. Downloading results...")
try:
results_content = await sandbox.download_file("sales_results.json")
print(" β
Results downloaded:")
print(" π Content:")
# Pretty print the JSON
import json
results = json.loads(results_content.decode())
print(json.dumps(results, indent=4))
except Exception as e:
print(f" β Could not download results: {e}")
else:
print(f" β Processing failed: {result.stderr}")
async def benchmark_example():
"""Simple benchmark example."""
print("\n" + "=" * 40)
print("β‘ Performance Benchmark Example")
print("=" * 40)
import time
print("\n1. Testing basic command execution speed...")
start_time = time.time()
async with Sandbox() as sandbox:
# Test multiple commands
commands = [
"echo 'test'",
"python3 -c 'print(\"hello\")'",
"ls -la",
"pwd",
"date",
]
for i, command in enumerate(commands, 1):
cmd_start = time.time()
result = await sandbox.execute(command)
cmd_time = time.time() - cmd_start
status = "β
" if result.success else "β"
print(f" {status} Command {i}: {command} ({cmd_time:.3f}s)")
total_time = time.time() - start_time
print(f"\nπ Total benchmark time: {total_time:.3f}s")
print(f"π Average time per command: {total_time/len(commands):.3f}s")
async def error_handling_example():
"""Demonstrate error handling."""
print("\n" + "=" * 40)
print("π‘οΈ Error Handling Example")
print("=" * 40)
async with Sandbox() as sandbox:
print("\n1. Testing successful command...")
result = await sandbox.execute("echo 'This works!'")
if result.success:
print(f" β
Success: {result.stdout.strip()}")
print("\n2. Testing command that fails...")
result = await sandbox.execute("nonexistent_command")
if not result.success:
print(f" β Failed as expected (return code: {result.return_code})")
print(f" π Error message: {result.stderr.strip()}")
print("\n3. Testing file operations...")
try:
# Try to download a file that doesn't exist
await sandbox.download_file("nonexistent_file.txt")
print(" β This shouldn't happen!")
except Exception as e:
print(f" β
Caught expected error: {type(e).__name__}")
print(f" π Error message: {str(e)}")
print("\n4. Testing Python error handling...")
python_error_code = """
try:
result = 10 / 0 # This will cause a ZeroDivisionError
except ZeroDivisionError as e:
print(f"Caught error: {e}")
print("Handled gracefully!")
"""
await sandbox.upload_file("error_test.py", python_error_code)
result = await sandbox.execute("python3 error_test.py")
if result.success:
print(" β
Python error handling:")
for line in result.stdout.strip().split("\n"):
print(f" {line}")
async def main():
"""Run all quick start examples."""
try:
await hello_world_example()
await data_processing_example()
await benchmark_example()
await error_handling_example()
print("\n" + "π" * 20)
print("π All Quick Start Examples Completed Successfully! π")
print("π" * 20)
print("\nπ Next Steps:")
print(" β’ Explore more examples in the examples/ directory")
print(" β’ Try different providers (e2b, daytona, morph)")
print(" β’ Read the full documentation in README.md")
print(" β’ Run benchmarks: grainchain benchmark --provider local")
print(" β’ Check out the integration guide: INTEGRATION.md")
except Exception as e:
print(f"\nβ Example failed: {e}")
import traceback
traceback.print_exc()
print("\nπ§ Troubleshooting:")
print(" β’ Make sure grainchain is installed: pip install grainchain")
print(" β’ Check Python version: python --version (requires 3.12+)")
print(" β’ Try running: grainchain benchmark --provider local")
print(" β’ See TROUBLESHOOTING.md for more help")
if __name__ == "__main__":
asyncio.run(main())