外部Python脚本和Django虚拟环境

2024-09-30 05:19:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用子流程从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虚拟环境执行它,如何继续


Tags: pathdjangoself脚本程序运行viewexecuteget
1条回答
网友
1楼 · 发布于 2024-09-30 05:19:36

你有两个选择

选项1:

  • 将脚本升级为管理命令
  • 使用django.core.management.call_命令运行脚本
  • 通过这种方式,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!")

相关问题 更多 >

    热门问题