3
votes

I created a Django project to launch a htmlpage which has a button with name run test. I would like to run a python script file hello.py(located outside the django project) when the button is clicked. I am quite new to this scripting.

Can anyone help me with this question as soon as possible? Your help would be appreciated.

My django project consists of following files:

TestProject(project folder)

myapp(folder)

  • int.py
  • admin.py
  • models.py
  • tests.py
  • urls.py
  • views.py

Templates(folder)

  • index.html

Testproject(folder)

  • int.py
  • urls.py
  • settings.py
  • views.py
  • wsgi.py
  • admin.py
  • manage.py

The python script file-helllo.py is located C:/hello.py

1

1 Answers

1
votes

There are two basic approaches you could take to do this:

(1) Run the script as a subprocess (i.e. execute a separate program outside of your django application) - this is documented in the Python docs on subprocesses. Below is a brief example, you will need to go through the docs to understand exactly how you want to call your script (i.e. to handle return codes, output to stdout and stderr, etc)

import subprocess
subprocess.call(["python", "C:/hello.py"])

(2) If there is a specific function in this script that you could call, then you could add the directory containing the python script to sys.path, and then import the script and call the relevant function. This is detailed in this stack overflow question, and would be arguably the cleaner approach (As a sidenote, would advise moving hello.py to a more suitable location, the root of your C: drive probably isn't the right place to store scripts).

import sys
sys.path.append("C:/")

from hello import function_to_call
function_to_call()

If you are struggling to put together the web page that allows you to display the button and react to the button press by calling the script, it would be advisable to work through the excellent Django tutorial writing your first Django application.