0
votes

Following is my django file structure

  • myproject
  • myapp

    • migrations
    • static
    • templates

      • myapp
        • demo.html
    • urls.py

    • views.py
    • models.py
    • admin.py
    • apps.py
    • tests.py
  • Scripts
    • demo_script.py
  • manage.py

What I want to know is how to execute the script Scripts/demo_script.py (which is outside the application "myapp") from views.py and if it is executed successfully, show "Success" on myapp/templates/myapp/demo.html or else show "Failed to execute" on the same html page.

Thanks in advance!

1

1 Answers

2
votes

simply use:

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

All the paths referenced in Django are relative to the BASE_DIR. BASE_DIR is where your manage.py lies.