如何从 php 运行 Python 脚本
我想从 php 运行 python 脚本.这是我的python代码.保存在/home/pi,文件名为hello.py
#!/usr/bin/python进口蓝牙bd_addr="xx:xx:xx:xx:xx:xx"端口=1袜子=bluetooth.BluetoothSocket(bluetooth.RFCOMM)sock.connect((bd_addr.port))数据=""而 1:尝试:数据 +=sock.recv(1024)data_end=data.find('
')如果 data_end!=-1:rec=data[:data_end]打印数据数据=数据[数据结束+1:]除了键盘中断:休息
这是我的 php 代码.它保存在/var/www/html 中,文件名为 php.php
我在 chrome 中插入 localhost/php.php,它显示
-rw-r-r- 1 pi pi 378 Mar 8 12:07/home/pi/hello.py
有什么问题??
解决方案ls
命令用于列出目录中的文件或获取有关文件的信息.你在你的 python 文件上 ls
-ing 并且结果是正确的.它正在为您提供有关文件的信息.
只需将文件名放在shell_exec
中,即/home/pi/hello.py
.如果您不想依赖 shebang 并且命令 python
在您的 shell 环境中可用,那么您可以使用 python/home/pi/hello.py
而不是裸/home/pi/hello.py
.
同样,您将变量 datas
与 print
一起用于您打算使用 data
的地方 - 修复它.
php 代码:
<块引用>
或:
<块引用>
python 代码:
#!/usr/bin/python进口蓝牙bd_addr="xx:xx:xx:xx:xx:xx"端口=1袜子=bluetooth.BluetoothSocket(bluetooth.RFCOMM)sock.connect((bd_addr.port))数据=""而 1:尝试:数据 +=sock.recv(1024)data_end=data.find('
')如果 data_end!=-1:rec=data[:data_end]打印数据数据=数据[数据结束+1:]除了键盘中断:休息
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('
')
if data_end!=-1:
rec=data[:data_end]
print datas
data=data[data_end+1:]
except KeyboardInterrupt:
break
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>";
?>
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
what is the problem??
解决方案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.
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
.
Again, you used the variable datas
with print
where you intended to use data
- fix it.
php code:
<?php
$output=shell_exec('python /home/pi/hello.py');
echo "<pre>$output</pre>";
?>
or:
<?php
$output=shell_exec('/home/pi/hello.py');
echo "<pre>$output</pre>";
?>
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('
')
if data_end!=-1:
rec=data[:data_end]
print data
data=data[data_end+1:]
except KeyboardInterrupt:
break
相关文章