MCPcopy Create free account
hub / github.com/HKUDS/AutoAgent / run_python

Function run_python

autoagent/tools/terminal_tools.py:355–419  ·  view source on GitHub ↗

Run a python script. Args: code_path: The absolute or relative path (the relative path is from the root of the workplace `/workplace`) to the python script file. cwd: The working directory of the python script. If not provided, will regard the directory of the script as the

(
    context_variables,
    code_path: str,
    cwd: str = None,
    env_vars: Optional[Dict[str, str]] = None,
)

Source from the content-addressed store, hash-verified

353@register_tool("run_python")
354@process_terminal_response
355def run_python(
356 context_variables,
357 code_path: str,
358 cwd: str = None,
359 env_vars: Optional[Dict[str, str]] = None,
360) -> str:
361 """
362 Run a python script.
363 Args:
364 code_path: The absolute or relative path (the relative path is from the root of the workplace `/workplace`) to the python script file.
365 cwd: The working directory of the python script. If not provided, will regard the directory of the script as the working directory. If there is a command `cd ...` in the instruction for running the script, you should provide the cwd and not use the default value. (Optional)
366 env_vars: The environment variables to be set before running the python script. (Optional)
367 Returns:
368 A string representation of the exit code and output of the python script.
369 """
370 env: Union[DockerEnv, LocalEnv] = context_variables.get("code_env", LocalEnv())
371 try:
372 # 转换为绝对路径
373 # abs_path = str(Path(code_path).resolve())
374 if Path(code_path).is_absolute():
375 if env.run_command(f"ls {code_path}")['status'] != 0: return f"[ERROR] File {code_path} does not exist"
376 code_abs_path = code_path
377 else:
378 code_abs_path = f"{env.docker_workplace}/{code_path}"
379 if env.run_command(f"ls {code_abs_path}")['status'] != 0: return f'[ERROR] You use a relative path, so we regard the `{env.docker_workplace}` as the root of the workplace, but `{code_abs_path}` does not exist'
380
381
382 if cwd:
383 # 使用指定的项目根目录
384 if Path(cwd).is_absolute():
385 if env.run_command(f"ls {cwd}")['status'] != 0: return f"[ERROR] Working directory {cwd} does not exist"
386 else:
387 cwd = f"{env.docker_workplace}/{cwd}"
388 if env.run_command(f"ls {cwd}")['status'] != 0: return f"[ERROR] You use a relative path for `cwd`, so we regard the `{env.docker_workplace}` as the working directory, but `{cwd}` does not exist"
389 else:
390 cwd = str(Path(code_abs_path).parent)
391
392
393 # 设置PYTHONPATH
394 pythonpath = str(cwd)
395
396 # 获取Python解释器路径
397 env_str = f"PYTHONPATH={pythonpath}"
398
399 if env_vars:
400 env_str += " " + " ".join([f"{k}={v}" for k, v in env_vars.items()])
401 # print(env_str)
402
403 # 构建相对模块路径
404 try:
405 rel_path = Path(code_abs_path).relative_to(cwd)
406 module_path = str(rel_path.with_suffix('')).replace(os.sep, '.')
407
408 command = f"cd {cwd} && {env_str} python -m {module_path}"
409 except ValueError:
410 # 如果无法构建相对路径,使用完整路径
411 command = f"cd {cwd} && {env_str} python {code_path}"
412

Callers

nothing calls this directly

Calls 3

LocalEnvClass · 0.90
getMethod · 0.80
run_commandMethod · 0.45

Tested by

no test coverage detected