简体   繁体   English

如何在Raspberry Pi上使用PHP运行python脚本?

[英]How do I run a python script using PHP on Raspberry Pi?

I want to run a python script on Raspberry Pi via web-app. 我想通过网络应用在Raspberry Pi上运行python脚本。 I have a PHP page for a button, and when the button is clicked it goes to another PHP page which is made up of the following code. 我有一个按钮的PHP页面,单击该按钮会转到另一个由以下代码组成的PHP页面。 If I type system("mkdir folder") it does work but it does not work for a python script. 如果我键入system("mkdir folder")它可以工作,但不适用于python脚本。 I have already changed the sudeors file using www-data ALL=NOPASSWD: ALL . 我已经使用www-data ALL=NOPASSWD: ALL更改了sudeors文件。

PHP file PHP文件

<?php
    system("sudo python3 x.py");
?>

Python Script Python脚本

#!/usr/bin/env python3
import os
os.system("gnome-terminal")

Try with 试试看

<?php echo shell_exec("python x.py");?>

This command should echo out the result of the executed command, useful for debugging since it will show errors that you might have either in the shell command or in the python script. 该命令应echo已执行命令的结果,对调试很有用,因为它将显示您可能在shell命令或python脚本中出现的错误。

or 要么

<?php echo exec("python x.py");?>

See this and this 看到这个这个

Also make sure and verify that your php engine has enough permissions to run shell commands. 还要确保并确认您的php引擎具有足够的权限来运行shell命令。 You could also try to disable safe-mode but it is deprecated and not recommended by any means. 您也可以尝试禁用安全模式,但是不建议使用它,并且不建议这样做。

Also from the comments in the references: 同样从参考文献中的评论中:

If you are running php as an Apache module in Unix then every system command you run is run as user apache. 如果您在Unix中将php作为Apache模块运行,则您运行的每个系统命令均以apache用户身份运行。 This just makes sense.. Unix won't allow privileges to be elevated in this manner. 这是有道理的。Unix不允许以这种方式提升特权。 If you need to run a system command with elevated privileges think through the problem carefully! 如果您需要以提升的权限运行系统命令,请仔细考虑问题!


As a side note, if you are trying to have an interactive webpage where you input stuff in it and it acts as a remote terminal shell that is defenitely not how to do it, it is a bit more complicated since it would require bidirectional connection in """" real time """". 附带说明一下,如果您尝试创建一个交互式网页,在其中输入内容,并且它充当远程终端外壳(绝对不是该操作的方式),则它会更加复杂,因为它将需要双向连接。 ““““ 即时的 ””””。 You would have to use some AJAX or a WebSocket connection with a WebSocket server on your raspi. 您必须将一些AJAXWebSocket连接与raspi上的WebSocket服务器一起使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM