如何从php运行Python脚本 [英] how to run Python script from php

查看:92
本文介绍了如何从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.

同样,您将变量datasprint一起用于了打算使用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

这篇关于如何从php运行Python脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆