I'm trying to log a command executed with subprocess.Popen() to a UDP socket via the stdout. I've seen attempts on the net but none of real success at least in my case.
Some people tried to subclass a socket and pass it to the "stdout" argument of Popen in order to override the default .write method to send over a socket, see, e.g. http://www.dreamincode.net/forums/topic/209734-using-a-socket-as-stdinstdout/
I also tried to subclass the "file" class and override the write method with my implementation but Popen does not seem to call any write method at all.
Indeed this idea of subclassing doesn't work for the simple reason that Popen(args,stdout=mysocket) does not call any mysocket.write (or whatever .write) method. To test this I called Popen in debug mode and tried to step from its init to the end without finding any .write or something resembling it. I'm working with python 2.7
Of course I know I can send stdout to PIPE and then read it, but this would require in my case creating (more than one) working thread to read PIPE and send, and if possible I'd like to avoid this solution if a simpler one is available with lower effort.
my file subclass
class Foo(file):
dbgIP = ""
dbgPORT = 0
sck = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
def __init__(self, dbgIP, dbgPORT):
file.__init__(self,"empty",'w')
self.sck.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
self.dbgIP = dbgIP
self.dbgPORT = dbgPORT
def write(self, text):
return self.sck.sendto(text, (self.dbgIP, self.dbgPORT))
An example call
foofile = Foo(MCAST_GROUP,MCAST_PORT)
subprocess.Popen("jackd -R -P62 -dalsa -dhw:0 -p256 -n2 -i2 -o2 -s -S -r22050",shell=True, stdout=foofile, stderr=subprocess.STDOUT)
Calling foofile.write("asd")
works fine