Difference between revisions of "Python-examples"

From Bashlinux
Jump to: navigation, search
 
Line 1: Line 1:
 
__NOTOC__
 
__NOTOC__
 
= Python: Examples =
 
= Python: Examples =
== Client/Server ==
+
== Server/Client ==
  +
Simple Server/Client communication, communication data is text.
  +
 
==== Server ====
 
==== Server ====
 
 
Line 38: Line 40:
 
print sock.recv(1024)
 
print sock.recv(1024)
 
sock.send('bye')
 
sock.send('bye')
  +
</nowiki></pre>
  +
  +
  +
== Subprocess in a Thread ==
  +
How to handle `Popen`, a subprocess, in a thread in Python.
  +
  +
<pre><nowiki>
  +
import threading
  +
import subprocess
  +
  +
class MyClass(threading.Thread):
  +
def __init__(self):
  +
self.stdout = None
  +
self.stderr = None
  +
threading.Thread.__init__(self)
  +
  +
def run(self):
  +
p = subprocess.Popen('rsync -av /etc/passwd /tmp'.split(),
  +
shell=False,
  +
stdout=subprocess.PIPE,
  +
stderr=subprocess.PIPE)
  +
  +
self.stdout, self.stderr = p.communicate()
  +
  +
myclass = MyClass()
  +
myclass.start()
  +
myclass.join()
  +
print myclass.stdout
 
</nowiki></pre>
 
</nowiki></pre>

Revision as of 00:47, 5 March 2010

Python: Examples

Server/Client

Simple Server/Client communication, communication data is text.

Server

import SocketServer

class EchoRequestHandler(SocketServer.BaseRequestHandler):
    def setup(self):
        print self.client_address, 'connected!'
        self.request.send('hi ' + str(self.client_address) + '\n')

    def handle(self):
        while 1:
            data = self.request.recv(1024)
            self.request.send(data)
            if data.strip() == 'bye':
                return

    def finish(self):
        print self.client_address, 'disconnected!'
        self.request.send('bye ' + str(self.client_address) + '\n')

#server host is a tuple ('host', port)
server = SocketServer.ThreadingTCPServer(('localhost', 5000), EchoRequestHandler)
server.serve_forever()
 


Client

 
import socket

sock = socket.socket(socket.AF_INET, sock.SOCK_STREAM)
sock.connect(('localhost', 5000))
print sock.recv(1024)
sock.send('bye')
 


Subprocess in a Thread

How to handle `Popen`, a subprocess, in a thread in Python.

import threading
import subprocess

class MyClass(threading.Thread):
    def __init__(self):
        self.stdout = None
        self.stderr = None
        threading.Thread.__init__(self)

    def run(self):
        p = subprocess.Popen('rsync -av /etc/passwd /tmp'.split(),
                             shell=False,
                             stdout=subprocess.PIPE,
                             stderr=subprocess.PIPE)

        self.stdout, self.stderr = p.communicate()

myclass = MyClass()
myclass.start()
myclass.join()
print myclass.stdout