外部 Python 脚本和 Django 虚拟环境

External Python Scripts and Django Virtual Env

我 运行 我的 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 虚拟环境执行它,我该如何继续?

你有两个选择,

选项#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!")