简体   繁体   中英

How do I call python program (which has command line arguments) from PHP or Javascript?

My Python Program is,

from xbee import ZigBee
import serial
import sys

sPort = serial.Serial("/dev/ttyAMA0", 9600)
xbee = ZigBee(sPort)

targStr = sys.argv[1]
data = str(targStr)
print (data)
destAdd = "\x00\x13\xa2\x00\x40\xa9\xcc\xad"
xbee.send("tx",dest_addr_long=destAdd,dest_addr="\xff\fe",data=data)
print ("Sent!")

When I execute this python program on linux shell, it works all great! How do execute this program on certain event from HTML Page (Either using Javascript, AJAX or PHP) ?

You need to embed this code into some Python web server - for example Flask .

See example bellow - xbee_test.py (it is very raw, don't use that in production environment):

from flask import Flask
app = Flask(__name__)

from xbee import ZigBee
import serial

sPort = serial.Serial("/dev/ttyAMA0", 9600)
xbee = ZigBee(sPort)

@app.route("/<data>")
def index(data):
    destAdd = "\x00\x13\xa2\x00\x40\xa9\xcc\xad"
    xbee.send("tx",dest_addr_long=destAdd,dest_addr="\xff\fe",data=data)
    return "Sent!"

if __name__ == "__main__":
    app.run()

Now, when you run this in Python and hit http //localhost:5000/test_data you get your code executed.

Embedding this into HTML page as eg AJAX call is from this point on uncomplicated.

Here is how to obtain Flask installation and run that:

$ pip install Flask
$ python xbee_test.py
 * Running on http://localhost:5000/

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