1

I would like to create a button that when launching a python script. This script opens a data.txt file and transforms it into json so that I can integrate it into my database in the future.

What I want to do today is just to create a button that when clicking starts the script (I would check in my documents if the file json result.txt has been created which allows me to check if the function works). Here is what I have done:

In urls.py

url(r'whatever^$', views.recup_wos, name='recup_wos'),

In views.py

def recup_wos(request):
    if request.method == 'POST':
        import newscript.py
        os.system('python newscript.py')
    return redirect('accueil')

Template accueil.html

<form action='{% url recup_wos %}' method="POST">
  <input value="Executer" type="submit">
</form>

The error message is the following:

Reverse for '' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []

enter image description here

I think the error is mainly in the view, maybe a syntax error?


I changed my template and my view. It does the redirection well but the script does not launch :

def recup_wos(request):
if request.method == 'POST':
   os.system('Python newscript.py')
return redirect('../page/accueil')

1 Answers1

5

You should use quotes when using strings with the url template tag:

{% url "recup_wos" %}

It's not clear why you are trying to run a python script using system. Since it is a Python script it might be better to

from newscript import do_stuff

def recup_wos(request):
    if request.method == 'POST':
        do_stuff()
    return redirect('../page/accueil')

If that is not possible, then you could use subprocess instead of os.system to run the command. If it fails, then you should get a traceback which might help identify the problem.

import subprocess

def recup_wos(request):
    if request.method == 'POST':
        subprocess.check_call(['python', 'newscript.py'])  # nb lowercase 'python'
    return redirect('../page/accueil')
Alasdair
  • 298,606
  • 55
  • 578
  • 516