如何从php运行Python脚本
我想从php运行python脚本. 这是我的python代码.它保存在/home/pi中,文件名为hello.py
I want to run python script from php. this is my python code. It is saved in /home/pi and name of file is hello.py
#! /usr/bin/python
import bluetooth
bd_addr="xx:xx:xx:xx:xx:xx"
port=1
sock=bluetooth.BluetoothSocket(bluetooth.RFCOMM)
sock.connect((bd_addr.port))
data=""
while 1:
try:
data +=sock.recv(1024)
data_end=data.find('\n')
if data_end!=-1:
rec=data[:data_end]
print datas
data=data[data_end+1:]
except KeyboardInterrupt:
break
这是我的PHP代码.它保存在/var/www/html中,文件名为php.php
And here is my php code. It is saved in /var/www/html and name of file is php.php
<?php
$output=shell_exec('ls -l /home/pi/hello.py');
echo "<pre>$output</pre>";
?>
然后我在chrome中插入localhost/php.php,它会显示
And I insert localhost/php.php in chrome, it displays
-rw-r-r- 1 pi pi 378 Mar 8 12:07 /home/pi/hello.py
出什么问题了?
ls
命令用于列出目录中的文件或获取有关文件的信息.您正在python文件上ls
-ing,结果是正确的.它为您提供有关文件的信息.
ls
command is used to list files in a directory or to get information about a file. You are ls
-ing on your python file and the result is correct. It is providing you with information about the file.
只需将文件名放在shell_exec
内,即/home/pi/hello.py
.如果您不希望依赖shebang并且命令python
在您的shell环境中可用,那么您可以使用python /home/pi/hello.py
而不是裸露的/home/pi/hello.py
.
Just put the file name inside of shell_exec
that is /home/pi/hello.py
. If you do not want to depend on the shebang and the command python
is available in your shell environment then you can use python /home/pi/hello.py
instead of bare /home/pi/hello.py
.
同样,您将变量datas
与print
一起用于了打算使用data
的位置-对其进行修复.
Again, you used the variable datas
with print
where you intended to use data
- fix it.
php代码:
php code:
<?php
$output=shell_exec('python /home/pi/hello.py');
echo "<pre>$output</pre>";
?>
或:
<?php
$output=shell_exec('/home/pi/hello.py');
echo "<pre>$output</pre>";
?>
python代码:
python code:
#! /usr/bin/python
import bluetooth
bd_addr="xx:xx:xx:xx:xx:xx"
port=1
sock=bluetooth.BluetoothSocket(bluetooth.RFCOMM)
sock.connect((bd_addr.port))
data=""
while 1:
try:
data +=sock.recv(1024)
data_end=data.find('\n')
if data_end!=-1:
rec=data[:data_end]
print data
data=data[data_end+1:]
except KeyboardInterrupt:
break