You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django中使用subprocess执行上传Python文件报错如何解决?

报错原因

你直接将Django接收的InMemoryUploadedFile内存文件对象传入了subprocess.run方法,该方法的执行路径参数仅支持字符串、字节类数据或者路径对象,无法直接识别内存文件类型,因此触发类型错误。

修复步骤
  • 先将内存中存储的上传脚本写入本地磁盘文件,拿到对应的本地存储路径
  • 将本地路径传入subprocess.run执行Python脚本
  • 执行完成后清理临时文件,避免磁盘冗余占用
修复后代码示例
import os
import tempfile
import subprocess
from django.http import HttpResponse

def execute(request):
    if request.method == 'POST':
        file = request.FILES.get('document')
        if not file:
            return HttpResponse("未检测到上传的有效文件")
        # 基础文件格式校验
        if not file.name.endswith('.py'):
            return HttpResponse("仅允许上传后缀为.py的Python脚本文件")

        # 创建临时磁盘文件存储上传内容
        with tempfile.NamedTemporaryFile(mode='wb', suffix='.py', delete=False) as tmp_file:
            for chunk in file.chunks():
                tmp_file.write(chunk)
            tmp_file_path = tmp_file.name

        try:
            # 执行脚本,添加超时避免脚本无限运行占用资源
            exec_result = subprocess.run(
                ['python', tmp_file_path],
                capture_output=True,
                text=True,
                timeout=30
            )
            return HttpResponse(f"脚本执行完成\n标准输出:{exec_result.stdout}\n错误输出:{exec_result.stderr}")
        finally:
            # 无论执行是否成功,都删除临时文件
            os.unlink(tmp_file_path)
安全提示

允许用户上传并执行脚本属于极高风险操作,生产环境部署时必须做好权限校验、沙箱隔离、资源使用限制,避免恶意脚本窃取服务器数据、破坏系统环境。

内容的提问来源于stack exchange,提问作者new

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 11:48:01