When precise calculation, data processing, or algorithm validation is needed, execute Python code via the exec tool.
When to use
- Mathematical calculations (especially complex calculations where estimation is not accurate enough)
- Data processing and statistical analysis
- Algorithm validation and prototype development
- Text/data format conversion
- Generate structured output
Examples
Simple calculation:
exec(command="python3 -c \"print(2 ** 100)\"")
Multi-line code (write to a temporary file and then execute):
exec(command="python3 << 'EOF'\ndata = [85, 92, 78, 96, 88, 73, 91]\navg = sum(data) / len(data)\nprint(f'均值: {avg:.1f}, 最高: {max(data)}, 最低: {min(data)}')\nEOF")
Fibonacci sequence:
exec(command="python3 -c \"\ndef fib(n):\n a, b = 0, 1\n for _ in range(n):\n a, b = b, a + b\n return a\nprint(fib(50))\n\"")
Execute an existing Python script:
exec(command="python3 scripts/analysis.py")
Install dependencies and then execute:
exec(command="pip install pandas && python3 -c \"import pandas; print(pandas.__version__)\"")
Tips
- Be sure to use
print()to output results — only stdout is captured. - For complex code, it is recommended to write it to a file first, then use
exec(command="python3 script.py")to execute it, avoiding escaping issues. - You can use heredoc syntax(
python3 << 'EOF' ... EOF) to execute multi-line code. - Split complex tasks into multiple calls, validating each step progressively.
- When third-party libraries are needed, first use
exec(command="pip install xxx")to install them.