Python 如何在django应用程序的views.py中执行外部脚本?
下面是我的django文件结构Python 如何在django应用程序的views.py中执行外部脚本?,python,django,python-2.7,Python,Django,Python 2.7,下面是我的django文件结构 我的项目 myapp 迁移 静止的 模板 myapp demo.html url.py views.py models.py 管理员 apps.py tests.py 剧本 demo_script.py manage.py 我想知道的是如何从views.py执行脚本Scripts/demo_script.py(在应用程序“myapp”之外),如果执行成功,则在myapp/templates/myapp/demo.html上显示“Success”
- 我的项目
- myapp
- 迁移
- 静止的
- 模板
- myapp
- demo.html
- myapp
- url.py
- views.py
- models.py
- 管理员
- apps.py
- tests.py
- 剧本
- demo_script.py
- manage.py
relative_path = "scripts/demo_script.py"
# or
absolute_path = os.path.join(settings.BASE_DIR, "scripts", "demo_script.py")
exec(open(relative_path or absolute_path).read()) # execute the py file
Django中引用的所有路径都是相对于BASE\u DIR
的BASE\u DIR
是您的manage.py
所在位置。只需使用:
relative_path = "scripts/demo_script.py"
# or
absolute_path = os.path.join(settings.BASE_DIR, "scripts", "demo_script.py")
exec(open(relative_path or absolute_path).read()) # execute the py file
Django中引用的所有路径都是相对于BASE\u DIR
的BASE\u DIR
是您的manage.py
所在