python - 外部 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 虚拟环境执行它,我该如何继续?
解决方案
你有两个选择,
选项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!")
推荐阅读
- google-maps - 使用集群标记离子 3 时 INFO_cLICK 事件未触发
- php - 是否存在安全漏洞,包括换个角度看
- jsp - 我如何使用一些jsp页面将数据插入数据库表?
- javascript - 仅创建 mp3 格式的 HTML/Javascript 音频播放器
- excel-formula - 需要 Excel 公式帮助 需要
- php - 如何在 Laravel 中打印数据以列格式显示的表格?
- javascript - JavaScript - 函数外的空数组
- php - Mysql Query 如果我们先调用两次获取计数然后列出,则需要更多时间
- java - 无法用 Java 实例化类型
- java - 停止、暂停和恢复由 Spring MVC 控制器中的队列运行的循环