File: creosote.py

package info (click to toggle)
python-pcgi 1.999a4-2
  • links: PTS
  • area: main
  • in suites: slink
  • size: 380 kB
  • ctags: 194
  • sloc: ansic: 1,508; python: 776; makefile: 137; sh: 71
file content (66 lines) | stat: -rwxr-xr-x 2,102 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#!/usr/bin/env python
# creosote.py - lightweight message passing with datagrams
# JeffBauer@bigfoot.com

import sys, socket

BUFSIZE = 1024
PORT = 7739

def spew(msg, host='localhost', port=PORT):
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.bind('', 0)
    s.sendto(msg, (host, port))

def bucket(port=PORT, logfile=None):
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.bind('', port)
    print 'creosote bucket waiting on port: %s' % port
    if logfile:
        f = open(logfile, 'a+')
    while 1:
        data, addr = s.recvfrom(BUFSIZE)
        print `data`[1:-1]
        if logfile:
            f.write(`data`[1:-1]+'\n')
            f.flush()

class MrCreosote:
    """lightweight message passing with datagrams"""
    def __init__(self, host='localhost', port=PORT):
        self.host = host
        self.port = port
        self.client = None
        self.disabled = 0
        self.redirect_server = None
        self.redirect_client = None
    def bucket(self, logfile=None):
        bucket(self.port, logfile)
    def redirector(self, host, port=PORT):
        if self.disabled:
            return
        if self.redirect_server == None:
            self.redirect_server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            self.redirect_server.bind('', self.port)
        if self.redirect_client == None:
            self.redirect_client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            self.redirect_client.bind('', 0)
        while 1:
            data, addr = self.redirect_server.recvfrom(BUFSIZE)
            self.redirect_client.sendto(data, (host, port))
    def spew(self, msg):
        if self.disabled:
            return
        if self.client == None:
            self.client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            self.client.bind('', 0)
        self.client.sendto(msg, (self.host, self.port))

if __name__ == '__main__':
    """usage: creosote [message]"""
    if len(sys.argv) < 2:
        bucket()
    else:
        from string import joinfields
        spew(joinfields(sys.argv[1:],' '))