【问题标题】:Run bash script with Django使用 Django 运行 bash 脚本
【发布时间】:2018-12-13 03:37:03
【问题描述】:

我真的是 django 的新手。当我在 html 中按下一个按钮时,我需要运行一个 bash 脚本,并且我需要使用 Django 框架来执行它,因为我用它来构建我的网络。如果有人可以帮助我,我将不胜感激

编辑:我添加了我的模板和我的观点以便更有帮助。在“nuevaCancion”模板中,我使用了 2 个视图。

<body>
	
	{% block cabecera %}
	<br><br><br>
	<center>
	<h2> <kbd>Nueva Cancion</kbd> </h2>
	</center>
	{% endblock %}
	
	{% block contenido %}

		<br><br>
		<div class="container">
    		<form id='formulario' method='post' {% if formulario.is_multipart %} enctype="multipart/form-data" {% endif %} action=''>
				{% csrf_token %}
    			<center>
				<table>{{formulario}}</table>
        		<br><br>
        		<p><input type='submit' class="btn btn-success btn-lg" value='Añadir'/>
				 <a href="/ListadoCanciones/" type="input" class="btn btn-danger btn-lg">Cancelar</a></p>
				</center>
      	</form>
    	<br>
	</div>
	<center>
		<form action="" method="POST">
    		{% csrf_token %}
    		<button type="submit" class="btn btn-warning btn-lg">Call</button>
		</form>
	</center>
	{% endblock %}

</body>

Views.py

def index(request):
    if request.POST:
    subprocess.call('/home/josema/parser.sh')

    return render(request,'nuevaCancion.html',{})

解析器.sh

#! /bin/sh
python text4midiALLMilisecs.py tiger.mid

【问题讨论】:

标签: python html django bash shell


【解决方案1】:

你可以用空的form来做到这一点。

在您的模板中创建一个空的form

# index.html
<form action="{% url 'run_sh' %}" method="POST">
    {% csrf_token %}
    <button type="submit">Call</button>
</form>

为您的form添加url

from django.conf.urls import url

from . import views

urlpatterns = [
    url(r'^run-sh/$', views.index, name='run_sh')
]

现在在您的views.py 中,您需要从返回您的templateview 调用bash.sh 脚本

import subprocess

def index(request):
    if request.POST:
        # give the absolute path to your `text4midiAllMilisecs.py`
        # and for `tiger.mid`
        # subprocess.call(['python', '/path/to/text4midiALLMilisecs.py', '/path/to/tiger.mid'])

        subprocess.call('/home/user/test.sh')

    return render(request,'index.html',{})

我的test.sh 在主目录中。确保bash.sh 的第一行有sh executable 并且也有正确的权限。你可以给chmod u+rx bash.sh这样的权限。

我的test.sh 示例

#!/bin/sh
echo 'hello'

文件权限ls ~

-rwxrw-r--   1 test test    10 Jul  4 19:54  hello.sh*

【讨论】:

  • 我正在尝试您所说的,但我认为我的代码中缺少某些内容,因为它不起作用,我在哪里可以显示我的脚本以及我做了什么?另外,我必须添加一些网址还是不需要?
  • 我已经添加了它们:)
  • 你有两个表单,你说你对一个模板使用了两个views函数,尝试添加新的url并将这个url添加到form action
  • 我更新了我的答案,我添加了网址并将action添加到form
  • 您的bash.sh 文件只包含这行代码? python text4midiALLMilisecs.py tiger.mid ?
【解决方案2】:

用 Python 做:

带有子进程:

import subprocess
proc = subprocess.Popen("ls -l", stdout=subprocess.PIPE)
output, err = proc.communicate()
print output

或者用os模块:

import os
os.system('ls -l')

【讨论】:

    【解决方案3】:

    您可以在视图中使用 python 模块 subprocess

    import subprocess def your_view(request): subprocess.call('your_script.sh')

    【讨论】:

      【解决方案4】:

      详细解释可以参考我的博客>>

      http://www.easyaslinux.com/tutorials/devops/how-to-run-execute-any-script-python-perl-ruby-bash-etc-from-django-views/

      我建议你使用 Subprocess 模块的 Popen 方法。您的 shell 脚本可以通过 Subprocess 作为系统命令执行。

      这里有一点帮助。

      您的 views.py 应该如下所示。

      from subprocess import Popen, PIPE, STDOUT
      from django.http import HttpResponse
      
      def main_function(request):
          if request.method == 'POST':
                  command = ["bash","your_script_path.sh"]
                  try:
                          process = Popen(command, stdout=PIPE, stderr=STDOUT)
                          output = process.stdout.read()
                          exitstatus = process.poll()
                          if (exitstatus==0):
                                  result = {"status": "Success", "output":str(output)}
                          else:
                                  result = {"status": "Failed", "output":str(output)}
      
                  except Exception as e:
                          result =  {"status": "failed", "output":str(e)}
      
                  html = "<html><body>Script status: %s \n Output: %s</body></html>" %(result['status'],result['output'])
                  return HttpResponse(html)
      

      本例中,脚本的stderr和stdout保存在变量'output'中,脚本的退出码保存在变量'exitstatus'中。

      配置您的 urls.py 以调用视图函数“main_function”。

      url(r'^the_url_to_run_the_script$', main_function)
      

      现在您可以通过调用 http://server_url/the_url_to_run_the_script

      来运行脚本

      【讨论】:

        【解决方案5】:

        Python 3.5 开始subprocess.run() 是推荐的方法

        根据doc;

        调用子进程的推荐方法是使用 run() 它可以处理的所有用例的功能。对于更高级的用例, 可以直接使用底层的Popen接口。

        在 Python 3.5 中添加了 run() 函数;如果你需要保留 与旧版本的兼容性,请参阅旧的高级 API 部分。

        this 示例,

        import subprocess
        
        def index(request):
            if request.POST:
                subprocess.run(['/home/josema/parser.sh'])
        
            return render(request,'nuevaCancion.html',{})
        

        【讨论】:

          猜你喜欢
          • 2013-11-01
          • 2016-04-28
          • 2018-03-14
          • 1970-01-01
          • 2022-01-05
          • 1970-01-01
          • 2017-12-09
          • 1970-01-01
          • 2023-03-04
          相关资源
          最近更新 更多