|
| 1 | +from codeboxapi import CodeBox |
| 2 | + |
| 3 | +# Initialize CodeBox |
| 4 | +codebox = CodeBox(api_key="local") # or get your API key at https://codeboxapi.com |
| 5 | + |
| 6 | +# Basic Examples |
| 7 | +# ------------- |
| 8 | + |
| 9 | +# 1. Simple Code Execution |
| 10 | +result = codebox.exec("print('Hello World!')") |
| 11 | +print(result.text) # Output: Hello World! |
| 12 | + |
| 13 | +# 2. File Operations |
| 14 | +# Upload a file |
| 15 | +codebox.upload("example.txt", b"Hello from CodeBox!") |
| 16 | + |
| 17 | +# Download a file |
| 18 | +downloaded = codebox.download("example.txt") |
| 19 | +content = downloaded.get_content() # Returns b"Hello from CodeBox!" |
| 20 | + |
| 21 | +# List files |
| 22 | +files = codebox.list_files() # Returns list[RemoteFile] |
| 23 | + |
| 24 | +# 3. Package Management |
| 25 | +# Install packages |
| 26 | +codebox.install("pandas") |
| 27 | + |
| 28 | +# List installed packages |
| 29 | +packages = codebox.list_packages() |
| 30 | + |
| 31 | +# 4. Variable Management |
| 32 | +# Execute code that creates variables |
| 33 | +codebox.exec(""" |
| 34 | +x = 42 |
| 35 | +data = [1, 2, 3] |
| 36 | +name = "Alice" |
| 37 | +""") |
| 38 | + |
| 39 | +# Show all variables |
| 40 | +variables = codebox.show_variables() |
| 41 | +print(variables) # Shows dict with all variables and their values |
| 42 | + |
| 43 | +# 5. Plotting with Matplotlib |
| 44 | +plot_code = """ |
| 45 | +import matplotlib.pyplot as plt |
| 46 | +plt.figure(figsize=(10, 5)) |
| 47 | +plt.plot([1, 2, 3, 4], [1, 4, 2, 3]) |
| 48 | +plt.title('My Plot') |
| 49 | +plt.show() |
| 50 | +""" |
| 51 | +result = codebox.exec(plot_code) |
| 52 | +# result.images will contain the plot as bytes |
| 53 | + |
| 54 | +# 6. Streaming Output |
| 55 | +# Useful for long-running operations |
| 56 | +for chunk in codebox.stream_exec(""" |
| 57 | +for i in range(5): |
| 58 | + print(f"Processing item {i}") |
| 59 | + import time |
| 60 | + time.sleep(1) |
| 61 | +"""): |
| 62 | + print(chunk.content, end="") |
| 63 | + |
| 64 | +# 7. Bash Commands |
| 65 | +# Execute bash commands |
| 66 | +codebox.exec("ls -la", kernel="bash") |
| 67 | +codebox.exec("pwd", kernel="bash") |
| 68 | + |
| 69 | +# Create and run Python scripts via bash |
| 70 | +codebox.exec("echo \"print('Running from file')\" > script.py", kernel="bash") |
| 71 | +codebox.exec("python script.py", kernel="bash") |
| 72 | + |
| 73 | +# 8. Error Handling |
| 74 | +result = codebox.exec("1/0") |
| 75 | +if result.errors: |
| 76 | + print("Error occurred:", result.errors[0]) |
0 commit comments