Tag: UNIX

Python UNIX Sockets

June 14, 2010 » Geek

I’ve been tinkering with using UNIX sockets for IPC from Python and I thought I would share my most basic experiment.

This is a super simple example of client/server usage of a socket. Essentially the server is a blocking command socket that echo’s whatever is passed through it.

Listing: server.py

# -*- coding: utf-8 -*-
import socket
import os, os.path
import time

if os.path.exists( "/tmp/python_unix_sockets_example" ):
  os.remove( "/tmp/python_unix_sockets_example" )

print "Opening socket..."
server = socket.socket( socket.AF_UNIX, socket.SOCK_DGRAM )
server.bind("/tmp/python_unix_sockets_example")

print "Listening..."
while True:
  datagram = server.recv( 1024 )
  if not datagram:
    break
  else:
    print "-" * 20
    print datagram
    if "DONE" == datagram:
      break
print "-" * 20
print "Shutting down..."
server.close()
os.remove( "/tmp/python_unix_sockets_example" )
print "Done"

Listing: client.py

# -*- coding: utf-8 -*-
import socket
import os, os.path

print "Connecting..."
if os.path.exists( "/tmp/python_unix_sockets_example" ):
  client = socket.socket( socket.AF_UNIX, socket.SOCK_DGRAM )
  client.connect( "/tmp/python_unix_sockets_example" )
  print "Ready."
  print "Ctrl-C to quit."
  print "Sending 'DONE' shuts down the server and quits."
  while True:
    try:
      x = raw_input( "> " )
      if "" != x:
        print "SEND:", x
        client.send( x )
        if "DONE" == x:
          print "Shutting down."
          break
    except KeyboardInterrupt, k:
      print "Shutting down."
  client.close()
else:
  print "Couldn't Connect!"
print "Done"

Here is the transcript of me running the client.

[email protected]:~/Desktop$ python client.py
Connecting...
Ready.
Ctrl-C to quit.
Sending 'DONE' shuts down the server and quits.
> Helo!
SEND: Helo!
> DONE
SEND: DONE
Shutting down.
Done
[email protected]:~/Desktop$

And here is the server transcript from that session.

[email protected]:~/Desktop$ python server.py
Opening socket...
Listening...
--------------------
Helo!
--------------------
DONE
--------------------
Shutting down...
Done
[email protected]:~/Desktop$

Now all you need is a protocol and you’ll be set for basic IPC.