Run Python

Execute Python code from an agent with argv-list execution — no shell, no re-tokenisation

run_python runs a Python snippet for an agent and returns its output. Code is passed to subprocess.run as an argv list ([sys.executable, "-c", code]), so the source is preserved verbatim — no shell, no re-tokenisation — identically on POSIX and Windows.

python
from praisonaiagents import Agent
from praisonai.code.tools import run_python

agent = Agent(
    name="Python Runner",
    instructions="Run short Python snippets and report the output.",
    tools=[run_python],
)
agent.start("Print the sum of the first 10 squares")

The user asks the agent to compute something; the agent runs the snippet as an argv list and returns the captured output.

Diagram

📋 Code snippet

🐍 run_python

🔧 argv: sys.executable -c code

✅ stdout / exit code

Quick Start

  1. Give an agent the tool
    python
    from praisonaiagents import Agent
    from praisonai.code.tools import run_python
    
    agent = Agent(
        name="Python Runner",
        instructions="Run Python snippets and report the output.",
        tools=[run_python],
    )
    agent.start("Compute 2 ** 20 and print it")
  2. Call it directly
    python
    from praisonai.code.tools import run_python
    
    result = run_python("print('hello from python')")
    print(result["stdout"])   # hello from python
    print(result["exit_code"])  # 0
  3. Verify verbatim source is preserved

    Snippets with newlines, backslashes, and mixed quotes that used to break under shell quoting now run intact:

    python
    from praisonai.code.tools import run_python
    
    result = run_python(r'''
    import json
    data = {"path": "C:\\Users\\alice", "note": "she said \"hi\""}
    print(json.dumps(data))
    ''')
    # → prints the intact JSON without shell mangling on either OS

How It Works

Diagram
run_pythonAgentUserrun_pythonAgentUserRun this Pythoncode snippetsubprocess.run([sys.executable, “-c”, code]){stdout, stderr, exit_code, success}Result

Passing an argv list means the operating system hands your exact code string to Python as a single argument. There is no intermediate shell to expand $VAR, collapse quotes, or re-split on whitespace — so the caller’s source arrives byte-for-byte.

Before / after

Snippet featureOld shell-string pathargv-list path
NewlinesRe-tokenised, often mangledPreserved verbatim
Backslashes (C:\Users\...)Escaped/expanded by the shellPreserved verbatim
Mixed single/double quotesBroke quoting, could errorPreserved verbatim
POSIX vs WindowsDivergedIdentical behaviour

Return Shape

run_python returns the same dictionary shape as execute_command:

KeyTypeDescription
successboolTrue when the exit code is 0
exit_codeintProcess exit code
stdoutstrCaptured standard output
stderrstrCaptured standard error
python
from praisonai.code.tools import run_python

result = run_python("import sys; sys.stderr.write('warn\\n'); print('ok')")
result["success"]    # True
result["stdout"]     # "ok\n"
result["stderr"]     # "warn\n"

Best Practices

Use raw strings for backslash-heavy code

Wrap Windows paths or regex-heavy snippets in r'''...''' so your own Python source doesn’t consume the backslashes before run_python ever sees them.

Gate it behind approval for untrusted agents

run_python executes arbitrary code. Pair it with Approval so a human confirms each snippet on untrusted routes.

Set a timeout for long snippets

Pass timeout=<seconds> to bound execution; the default is 60 seconds.

Prefer run_python over hand-building a shell command

Building python -c "..." strings yourself re-introduces the quoting bugs this tool fixes. Pass the code to run_python and let the argv list carry it.


Related