Search code examples
pythonbashhttpstdinibeacon

Python send bash command output by query string


I am a beginner to Python so please bear with me. I need my python program to accept incoming data (stdin) from a command (ibeacon scan -b) and send that data by query string to my server. I using Raspbian on a raspberry pi. The ibeacon_scan command output looks like this.

iBeacon Scan ...
3F234454-CFD-4A0FF-ADF2-F4911BA9FFA6 1 4 -71 -69
3F234454-CFD-4A0FF-ADF2-F4911BA9FFA6 6 2 -71 -63
3F234454-CFD-4A0FF-ADF2-F4911BA9FFA6 1 4 -71 -69
3F234454-CFD-4A0FF-ADF2-F4911BA9FFA6 5 7 -71 -64
...keeps updating

I'm pipping the command to the python script.

ibeacon scan -b > python.py &

Here is the outline of what I think could work. I need help organizing the code correctly.

import httplib, urllib, fileinput

for line in fileinput():
   params = urllib.urlencode({'@UUID': 12524, '@Major': 1, '@Minor': 2, '@Power': -71, '@RSSI': -66})
   headers = {"Content-type": "application/x-www-form-urlencoded","Accept": "text/plain"}
   conn = httplib.HTTPConnection("www.example.com")
   conn.request("POST", "", params, headers)
   response = conn.getresponse()
   print response.status, response.reason
   data = response.read()
   data
   conn.close()

I know there are a lot of problems with this and I could really use any advice on any of this. Thank you for your time!


Solution

  • There are several problems in your code.

    1. Wrong bash command: At the moment you are extending the output to your python.py file, which is completely wrong. You should use a pipe and execute the python.py script. Your command should look like this:

    ibeacon scan -b | ./python.py &
    

    Make shure your python.py script is executable (chown). As an alternative you could also try this:

    ibeacon scan -b | python python.py &
    

    2. Wrong use of fileintput: Your for loop should look like this:

    for line in fileinput.input():
        ...