Python - HTTP post from stdin [closed]

2019-03-06 22:56发布

问题:

I am getting data in this format every second or so from a bash command 'ibeacon_scan"

ibeacon scan -b | stdin.py

Output:

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

I need to send that information by query string. Here is my code.

#!/usr/bin/python

import fileinput
import httplib
import urllib

for line in fileinput.input():
   string = line
   string2 = string.split(" ")
   parmas = string2
   parmas = urllib.urlencode({"UUID": "Major","Minor":"RSSI"})
   headers = {"Content-type": "application/x-www-form-urlencoded","Accept": "text/plain"}
   conn = httplib.HTTPConnection("67.205.14.22")
   conn.request("POST", "post.php", params, headers)
   response = conn.getresponse()
   print response.status, response.reason
   data = response.read()
   print data
   conn.close()

I'm getting this error:

Traceback (most recent call last):
  File "./stdin.py", line 14, in <module>
    conn.request("POST", "post.php", params, headers)
NameError: name 'params' is not defined

Something is wrong with params? How do I format this to correctly accept the 'ibeacon scan' command and send it by HTTP post?

回答1:

for line in fileinput.input():
   string = line
   string2 = string.split(" ")
   parmas = string2  # you call the variable parmas here
   parmas = urllib.urlencode({"UUID": "Major","Minor":"RSSI"})
   headers = {"Content-type": "application/x-www-form-urlencoded","Accept": "text/plain"}
   conn = httplib.HTTPConnection("67.205.14.22")
   conn.request("POST", "post.php", params, headers)  # and params here

You have made what looks to be a typo.