首页 > 解决方案 > 从 Django 远程运行 pygame 脚本

问题描述

在我运行 Raspian、Apache 服务器的 Pi3 上,我有一个 Django 应用程序。

我正在尝试从 Django 运行一个 python 文件。
如果我通过 SSH 连接到我的 Pi 并输入“python test_data.py”,它运行良好。我以用户“pi”的身份登录

test_data.py 就是这个。

output = "success!"
print(output)

网址.py

url(r'^mygame/$', views.my_game),

views.py文件我有以下内容

from subprocess import PIPE, run

def my_game(request):
    command = ['sudo', 'python test_data.py']
    result = run(command, stdout=PIPE, stderr=PIPE, shell=True, universal_newlines=True)
    return render(request, 'rungame.html',{'data1':result})

当通过网络浏览器调用 /mygame 时,这是我在 rungame.html 中打印的结果,所以我知道它调用了 test_data.py。好像是权限问题?我不明白下面的意思。有人可以建议这是否是权限问题,我该如何解决?

CompletedProcess(args=['sudo', 'python mygame.py'], returncode=1, stdout='', stderr='usage: sudo -h | -K | -k | -V\
nusage: sudo -v [-AknS] [-g group] [-h host] [-p prompt] [-u user]\
nusage: sudo -l [-AknS] [-g group] [-h host] [-p prompt] [-U user] [-u user]\n [command]\
nusage: sudo [-AbEHknPS] [-r role] [-t type] [-C num] [-g group] [-h host] [-p\n prompt] [-u user] [VAR=value] [-i|-s] [<command>]\
nusage: sudo -e [-AknS] [-r role] [-t type] [-C num] [-g group] [-h host] [-p\n prompt] [-u user] file ...\n')

谢谢

添加信息:创建 mygame.py 以测试概念

import pygame
import sys

pygame.init()

WIDTH = 800
HEIGHT = 600

screen = pygame.display.set_mode((WIDTH, HEIGHT))
background = pygame.image.load('background1.png')


print("test")
game_over = False

while not game_over:
    screen.blit(background, (0, 0))
    pygame.display.update()
    for event in pygame.event.get():
        print(event)
        if event.type == pygame.QUIT:
            sys.exit()

这是我的 Apache 配置文件

<VirtualHost *:80>
    ServerName www.example.com

    ServerAdmin webmaster@localhost

    Alias /static /home/pi/Dev/ehome/src/static
        <Directory /home/pi/Dev/ehome/src/static>
           Require all granted
         </Directory>

    <Directory /home/pi/Dev/ehome/src/ehome>
        <Files wsgi.py>
            Require all granted
        </Files>
    </Directory>

    WSGIDaemonProcess ehome python-path=/home/pi/Dev/ehome/src:/home/pi/Dev/ehome/lib/python3.5/site-packages
    WSGIProcessGroup ehome
    WSGIScriptAlias / /home/pi/Dev/ehome/src/ehome/wsgi.py


    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined

</VirtualHost>

# vim: syntax=apache ts=4 sw=4 sts=4 sr noet

标签: pythondjango

解决方案


不要使用子进程调用脚本。您有一个 python 脚本,将其设为函数并将其导入 Django。然后在您的views.py 中调用该函数。

测试数据.py

def my_function():
    output = "success!"
    return output

视图.py

from test_data import my_function

def my_game(request):
    result = my_function()
    return render(request, 'rungame.html',{'data1':result})

test_data.py脚本与views.py放在同一目录中。


推荐阅读