2017-04-20 155 views
0

我想创建一个启动python脚本时的按钮。这个脚本打开一个data.txt文件并将其转换为json,以便将来可以将它集成到我的数据库中。点击按钮提交时,在Django网站运行python脚本

我今天想要做的只是创建一个按钮,当点击开始脚本时(如果文件json result.txt已经创建,可以检查函数是否工作,我会检查我的文档)。 这里是我做了什么:

在urls.py

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

在views.py

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

模板accueil.html

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

的错误消息如下:

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

enter image description here

我认为错误主要是在视图中,也许一个语法错误?


我改变了我的模板和我的看法。它重定向良好,但剧本没有启动:

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

'Python newscript.py''看起来不对 - 不应该是'python newscript.py'吗? – Alasdair

回答

3

用与网址模板标签字符串时,应使用引号:

{% url "recup_wos" %} 

目前尚不清楚为什么你想运行一个python脚本使用system。既然是一个Python脚本,它可能会更好

from newscript import do_stuff 

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

如果这是不可能的,那么你可以使用的subprocess代替os.system运行命令。如果失败,那么你应该得到一个回溯,这可能有助于确定问题。

import subprocess 

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