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, 2014 at 20:51

1 Answer 1


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

# Listen for incoming connections

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

        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>
                print >>sys.stderr, 'no more data from', client_address

        # Clean up the connection

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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