Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

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('
')
    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??

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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>";
?>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...