Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reading from sys.stdin without newline or EOF

I want to recieve data from my gps-tracker. It sends data by tcp, so I use xinetd to listen some tcp port and python script to handle data. This is xinetd config:

service gps-gprs
{
    disable     = no
    flags       = REUSE
    socket_type = stream
    protocol    = tcp
    port    = 57003
    user        = root
    wait        = no
    server      = /path/to/gps.py
    server_args     = 3
} 

Config in /etc/services

gps-gprs        57003/tcp           # Tracking system

And Python script gps.py

#!/usr/bin/python
import sys

def main():
    data = sys.stdin.readline().strip() 
    #do something with data
    print 'ok'

if __name__ =='__main__':
    main()

The tracker sends data strings in raw text like

$GPRMC,132017.000,A,8251.5039,N,01040.0065,E,0.00,,010111,0,,A*75+79161234567#

The problem is that sys.stdin in python script doesn't recieve end of line or end of file character and sys.stdin.readline() goes forever. I tried to send data from another pc with a python script

import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('', 57003))
s.sendall( u'hello'  )
data = s.recv(4024)
s.close()
print 'Received', data

and if the message is 'hello', it fails, but if the message is 'hello\n', it's ok and everything is fine. But I don't know ho to tell tracker or xinetd to add this '\n' at the end of messages. How can I read the data from sys.stdin without EOF or EOL in it?

like image 576
Павел Тявин Avatar asked Sep 06 '12 20:09

Павел Тявин


People also ask

Is SYS stdin readline faster than input?

stdin. readline() is the fastest one when reading strings and input() when reading integers.

Does readline read newline?

The readline method reads one line from the file and returns it as a string. The string returned by readline will contain the newline character at the end. This method returns the empty string when it reaches the end of the file.


1 Answers

Simple:

data=sys.stdin.read().splitlines()

for i in data:
        print i

No newlines

like image 71
aDoN Avatar answered Sep 21 '22 05:09

aDoN