【问题标题】:Running Python file from Django views从 Django 视图运行 Python 文件
【发布时间】:2012-08-01 08:24:00
【问题描述】:

我知道以前有人问过这个问题,但建议的方法对我不起作用。 这就是我想要从我的 Django 视图中做的事情:

sudo python mypythonscript.py arg1 arg2 > mypythonscript.log

如果我从命令行执行它,它就像一个魅力,但不能让它通过 django 视图工作。 我曾尝试使用 os.system(command) 和 subprocess.call(command, shell=True) 但它们不起作用。 提前致谢。

编辑: 这是我的views.py:

from django.http import HttpResponse
import datetime
import subprocess

def li_view(request):
if request.is_ajax():
        if request.method == 'GET':
            message = "This is an XHR GET request"
        elif request.method == 'POST':
            message = "This is an XHR POST request"
            print request.POST
    else:
        message = "No XHR"
    num_instances = request.POST['num_instances']
    ami_id = "ami-ff02058b"
    command = "sudo python /home/bitnami/launch_instances.py 1 " + num_instances + " " + ami_id + " > /home/bitnami/launcinstances.log"
    subprocess.call(commad, shell=True)
    return HttpResponse("something creative will go here later")

整个故事是,我的网站上有一个表单,我想将该表单的内容作为参数传递给我的 launch_instances.py 脚本。 当我按下表单中的提交按钮时,它会发布到 /luanch_instances/ ,它会“重定向”到这个视图。 按原样执行代码不会做任何事情,它只会在新页面上向我显示“创建的东西稍后会在这里”。 如果我要怎么用

suprocess.check_call(command, shell=True)

这是我得到的:

Command 'sudo python /home/bitnami/launch_instances.py 1 ami-ff02058b > /home/bitnami/launchinstances.log' returned non-zero exit status 2

【问题讨论】:

  • 您需要告诉我们为什么它不起作用。显示您的代码和输出。
  • 另外,您想通过在 python 视图中执行此操作来完成什么?通常建议使用诸如 Celery 之类的任务队列来执行此类操作,因为它不会占用您的 Web 服务器。
  • @VladimirVolodin 我现在已经添加了输出和代码

标签: python django views


【解决方案1】:

当您尝试运行 python 脚本时,您可以简单地将代码从 launch_instances.py 导入您的视图,将输出重定向到 /home/bitnami/launcinstances.log(关于将 stdout 重定向到 python 中的文件:Redirect stdout to a file in Python?) .但是root权限仍然存在问题-一种选择是更改以下权限:从launch_instances.py调用代码所需的资源;您的日志文件;要让您的 django 进程执行该操作,第二个选项(不推荐)是以 root 身份运行 django 应用程序。

【讨论】:

  • 不知道为什么执行:sudo python mypythonscript.py arg1 arg2 > mypythonscript.log 需要root权限。假设 mypythonscript.py 不属于 django 进程的所有者,那么您可以简单地执行 chmod a+rx mypythonscript.pl
  • 但请记住,执行 chmod a+rx 可能会破坏安全性。
  • 没关系,我最后不需要使用 chmod a+rx。只需导入脚本即可完成工作:) 干杯
【解决方案2】:

很可能与权限有关。尝试检查命令执行的 stderr 和 stdout。我正在使用这段代码来调试我的 shell 命令:

process = subprocess.Popen(shlex.split(command), stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        output,error = process.communicate(input=pipe)

【讨论】:

  • 假设 input=pipe 你的意思是 input=subprocess.PIPE,我得到以下错误:'int' object has no attribute 'getitem'
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-23
  • 2017-06-20
  • 1970-01-01
  • 1970-01-01
  • 2013-09-24
  • 1970-01-01
相关资源
最近更新 更多