【问题标题】:How to execute a python script from django management commands?如何从 django 管理命令执行 python 脚本?
【发布时间】:2016-05-25 03:42:32
【问题描述】:

我正在尝试执行不在我的 Django 项目目录中的 python 脚本...例如,这是我使用命令调用的管理类:

我需要以 ROOT 身​​份运行它,因为它需要访问我的树莓派上的 GPIO 引脚。 (我得到另一个错误)

(env) sudo python manage.py bubbles

调用这个脚本:execfile('/home/pi/rpi/bubbles.py')

# /home/pi/DjangoProjects/RaspberryPi/graphics/management/commands

from django.core.management.base import BaseCommand, CommandError
from django.core.management.base import BaseCommand
from graphics.models import Graphic


class Command(BaseCommand):

    help = "My test command"

    def handle(self, *args, **options):

        execfile('/home/pi/rpi/bubbles.py')

我收到这个错误

Traceback (most recent call last):
   File "manage.py", line 8, in <module>
 from django.core.management import execute_from_command_line
ImportError: No module named django.core.management

所以我猜这是我的虚拟环境的问题,有没有办法在虚拟环境范围之外执行脚本?有没有更好的方法来使用 django 命令或其他东西来执行这个脚本。我有什么意义吗?

我试图调用的python脚本:

#!/usr/bin/env python

import Image
import ImageDraw
import time
from rgbmatrix import Adafruit_RGBmatrix

# Rows and chain length are both required parameters:
matrix = Adafruit_RGBmatrix(16, 2)

# Bitmap example w/graphics prims
image = Image.new("1", (16, 64)) # Can be larger than matrix if wanted!!
draw  = ImageDraw.Draw(image)    # Declare Draw instance before prims


# 24-bit RGB scrolling example.
# The adafruit.png image has a couple columns of black pixels at
# the right edge, so erasing after the scrolled image isn't necessary.
while True:

    matrix.Clear()
    image = Image.open("bubbles.png")
    image.load()
    for n in range(64, -image.size[0], -1):
        matrix.SetImage(image.im.id, n, 1)
        time.sleep(0.025)

    matrix.Clear()

也许我做错了,我只是在学习将网络框架与我的树莓派结合起来。

【问题讨论】:

    标签: python django raspberry-pi execfile


    【解决方案1】:

    在你的 bubbles.py 中,而不是这样做

    def handle(self, *args, **options):
    
        execfile('/home/pi/rpi/bubbles.py')
    

    试试这个

    def handle(self, *args, **options):
    
        execfile('PATH_TO_YOUR_ENV/bin/python /home/pi/rpi/bubbles.py')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-27
      • 1970-01-01
      相关资源
      最近更新 更多