简体   繁体   中英

how to run Python script from php

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

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('\n')
    if data_end!=-1:
      rec=data[:data_end]
      print data
      data=data[data_end+1:]
    except KeyboardInterrupt:
      break

As pointed out by Jon Stirling, you are using "ls" to only listing the content of the folder or to check whether the file exist in that folder. To run the Python code, you need to change the PHP file into something like this:

<?PHP
$output=shell_exec('./hello.py');
echo "<pre>$output</pre>";
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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