0

I need to catch incoming data from tcp socket at any time and then execute a python script on my Raspberry Pi. How do I do that? I hope that you understand what i need to do.

  • 1
    There are plenty of tutorials on the www to do what you want. Perhaps try one and let us know if you have a problem. – joan Dec 20 '14 at 20:51
2

Have you considered putting the TCP socket receive code inside your Python script?

Or you can just write another Python script that does a socket create, socket listen, and socket receive before calling your other Python script.

Here is some of the code to do this from http://pymotw.com/2/socket/tcp.html:

import socket
import sys

# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Connect the socket to the port where the server is listening
# substitute the TCP port you want to listen on for 10000 below
server_address = ('', 10000)

print >>sys.stderr, 'connecting to %s port %s' % server_address
sock.connect(server_address)

# Listen for incoming connections
sock.listen(1)

while True:
    # Wait for a connection
    print >>sys.stderr, 'waiting for a connection'
    connection, client_address = sock.accept()

    try:
        print >>sys.stderr, 'connection from', client_address

        # Receive the data in small chunks and retransmit it
        while True:
            data = connection.recv(16)
            print >>sys.stderr, 'received "%s"' % data
            if data:
                print >>sys.stderr, 'Data received - starting other Python script'
                <insert Python code to start other Python script>
            else:
                print >>sys.stderr, 'no more data from', client_address
                break

    finally:
        # Clean up the connection
        connection.close()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.