首页 > 解决方案 > 外部 Python 脚本和 Django 虚拟环境

问题描述

我以这种方式使用子进程从我的 Django 应用程序运行外部脚本:

class ExecutePythonFileView(View):
    def get(self, request):
        # Execute script
        script_path = os.path.join(settings.BASE_DIR, '/Code/zenet/zenet/workers/stats_scraper.py')
        subprocess.call(['python', script_path])
        # Return response
        return HttpResponse("Executed!")

我需要通过 Django 虚拟环境执行它,我该如何继续?

标签: pythondjangodjango-rest-frameworkdjango-viewsvirtualenv

解决方案


你有两个选择,

选项1:

  • 将脚本升级为管理命令
  • 使用 django.core.management.call_command 运行脚本
  • 这样 Django 会在需要时负责生成子进程和相关的东西

选项#2:

  • 继续使用相同的方法
  • 更新视图如下
import sys

class ExecutePythonFileView(View):
    def get(self, request):
        # Execute script
        script_path = os.path.join(settings.BASE_DIR, '/Code/zenet/zenet/workers/stats_scraper.py')
        subprocess.call([sys.executable, script_path])
        # Return response
        return HttpResponse("Executed!")

推荐阅读