当前位置: 首页 > news >正文

Python执行脚本并捕获输出

这里写目录标题

  • Piston API在线执行Pure Python
    • Piston API示例
    • Piston API的局限性
    • 解决方案
  • 使用subprocess执行本地脚本并捕获输出

Piston API在线执行Pure Python

Piston API示例

import requests

response = requests.post(
    "https://emkc.org/api/v2/piston/execute",
    json={
        "language": "python",
        "version": "3.10.0",
        "files": [  # 必须用 files 数组包裹代码
            {"content": "print(1+1)"}  # 代码放在 content 字段中
        ],
    },
)
print(response.json())

输出

{'stdout': '2\n', 'stderr': '', 'code': 0, ...}

Piston API的局限性

  • emkc.org提供的Piston API是一个在线执行代码的服务,默认只预装少量基础库(如requestsnumpy等常见库)。根据官方文档,它不支持动态安装第三方库,因此直接调用ortools会报错ModuleNotFoundError
  • 验证方法:尝试在代码中添加print(requests.__version__),若返回版本号则说明requests已预装;而ortools会报错。

解决方案

(1) 本地运行或使用支持自定义环境

  • 本地安装Python和ortools:确保Python版本(如3.5.2)和ortools版本(如7.1.6722)兼容:
    pip install ortools==7.1.6722
    
  • 使用Google Colab:Colab默认预装ortools,且支持动态安装其他库:
    !pip install ortools  # 若未预装则运行
    from ortools.linear_solver import pywraplp  # 直接调用
    

(2) 寻找支持自定义依赖的在线服务

  • Replit:在Replit的Python模板中,可通过poetry add ortools安装依赖。
  • GitHub Codespaces:支持自定义Dockerfile或requirements.txt配置环境。

(3) 调整代码兼容性(如必须使用Piston API)

  • 若无法更换环境,可尝试将ortools相关的代码逻辑改写为纯Python实现,但仅适用于简单问题,复杂优化问题无法绕过库依赖。

使用subprocess执行本地脚本并捕获输出

示例:

import subprocess

def run_py_file(file_path):
    result = subprocess.run(
        ["python", file_path], 
        capture_output=True, 
        text=True, 
        encoding="utf-8"
    )
    return {
        "exit_code": result.returncode,
        "stdout": result.stdout,
        "stderr": result.stderr
    }

# 调用示例
output = run_py_file("your_script.py")
print(output["stdout"])

your_script.py为:

print("")

若your_script.py文件中有多个函数,需要传参,需要选择执行的函数,并正确传参:
your_script.py为:

# your_script.py 内容示例
import argparse
import sys
import json

def func1(a, b):
    print(f"func1 收到参数:{a}{b}")

def func2(text):
    print(f"func2 收到消息:{text}")

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--func", help="要调用的函数名")
    parser.add_argument("--args", help="JSON格式的参数列表")
    args = parser.parse_args()

    # 解析参数
    if args.args:
        func_args = json.loads(args.args)
    else:
        func_args = []

    # 动态获取函数并调用
    func = getattr(sys.modules[__name__], args.func, None)
    if func:
        try:
            func(*func_args)
        except TypeError as e:
            print(f"参数错误:{e}", file=sys.stderr)
            sys.exit(1)
    else:
        print(f"错误:未找到函数 {args.func}", file=sys.stderr)
        sys.exit(1)

使用subprocess:

import subprocess
import json

def run_py_file(file_path, func_name=None, args=None):
    cmd = ["python", file_path]
    if func_name:
        cmd.extend(["--func", func_name])
    if args is not None:
        cmd.extend(["--args", json.dumps(args)])
    
    result = subprocess.run(
        cmd,
        capture_output=True,
        text=True,
        encoding="gbk"  # 修改编码为系统默认
    )
    return {
        "exit_code": result.returncode,
        "stdout": result.stdout,
        "stderr": result.stderr
    }


# 调用 func1 并传递两个参数
output = run_py_file("./src/test/your_script.py", "func1", ["Hello", 123])
print(output["stdout"])  # 输出:func1 收到参数:Hello 和 123

# # 调用 func2 并传递一个参数
# output = run_py_file("your_script.py", "func2", ["测试消息"])
# print(output["stdout"])  # 输出:func2 收到消息:测试消息

输出结果为:

PS C:\Users\pengkangzhen\PycharmProjects\llm-ecr> & C:/Users/pengkangzhen/anaconda3/python.exe c:/Users/pengkangzhen/PycharmProjects/llm-ecr/src/test/test.py
func1 收到参数:Hello 和 123

相关文章:

  • linux下手动升级ollama
  • Windows逆向工程入门之MASM过程调用机制深度解析
  • 【前端css】position定位
  • 虚拟机IP的配置,让它上网
  • [BUUCTF]web--wp(持续更新中)
  • 嵌入式C语言学习记录之-14~17day
  • 2024第十六届蓝桥杯模拟赛(第二期)-Python
  • RT-DETR融合YOLOv12中的R-ELAN结构
  • NModbus 连接到Modbus服务器(Modbus TCP)
  • 详解DeepSeek模型底层原理及和ChatGPT区别点
  • 【通俗讲解电子电路】——从零开始理解生活中的电路(三)
  • 什么是 Prompt?——一篇详细的介绍
  • 一周学会Flask3 Python Web开发-Flask3之表单处理WTForms安装与定义WTForms表单类
  • 【向量数据库Weaviate】 和Elasticsearch的区别
  • 0012SSM+VUE学生考勤管理系统的设计与实现程序+文档
  • PGlite:浏览器中运行的PostgreSQL
  • ‌Vetur‌ 与 Vue-Official 的区别
  • Leetcode 316 去除重复字母
  • 第10篇:文件IO与数据持久化(下)(JSON、二进制文件)
  • 塔能物联运维:城市照明运维成本的破局之道
  • 包装纸箱怎么做网站/seo培训机构
  • 怎么提高网站建设水平/网站优化公司推荐
  • wordpress xueqiu/而的跟地seo排名点击软件
  • 公司网站建设的建议/广告主资源哪里找
  • 网站建设维护费摊销/抖来查关键词搜索排名
  • 网站设计理念/西安关键词排名首页