Popular Python recipes tagged "meta:requires=select"http://code.activestate.com/recipes/langs/python/tags/meta:requires=select/2013-07-07T02:09:57-07:00ActiveState Code RecipesPrimitive Peer to Peer Chat (Python) 2013-07-07T02:09:57-07:00teddy_khttp://code.activestate.com/recipes/users/4187115/http://code.activestate.com/recipes/578591-primitive-peer-to-peer-chat/ <p style="color: grey"> Python recipe 578591 by <a href="/recipes/users/4187115/">teddy_k</a> (<a href="/recipes/tags/chat/">chat</a>, <a href="/recipes/tags/peer/">peer</a>, <a href="/recipes/tags/select/">select</a>, <a href="/recipes/tags/socket/">socket</a>, <a href="/recipes/tags/threading/">threading</a>). </p> <p>This took me longer than it should have. I am putting it here in the hopes that this post will spare others from having to Google things for extended periods of time.</p> <p>In short, you either listen for a connection (Chat_Server), or connect to a remote IP address (Chat_Client). From there, you can send text strings back and forth. </p> <p>This is a bit rough-hewn, obviously; I apologize in advance.</p> Distributed lock manager for Python (Python) 2012-07-04T21:03:32-07:00pavelhttp://code.activestate.com/recipes/users/4171837/http://code.activestate.com/recipes/578194-distributed-lock-manager-for-python/ <p style="color: grey"> Python recipe 578194 by <a href="/recipes/users/4171837/">pavel</a> (<a href="/recipes/tags/distributed/">distributed</a>, <a href="/recipes/tags/lock/">lock</a>, <a href="/recipes/tags/locking/">locking</a>, <a href="/recipes/tags/locks/">locks</a>, <a href="/recipes/tags/manager/">manager</a>, <a href="/recipes/tags/socket/">socket</a>, <a href="/recipes/tags/thread/">thread</a>, <a href="/recipes/tags/threading/">threading</a>, <a href="/recipes/tags/wsgi/">wsgi</a>). Revision 2. </p> <p>Distributed lock manager provides mutex(es) over network. It is used to synchronize processes running on different machines, e.g. WSGI processes in case of web applications. Lock object is compatible with threading.Lock and can be used as a context manager ("with statement"). It can be easily modified to use UNIX sockets instead of TCP/IP. Communication protocol is text based.</p> <p>First start server process:</p> <pre class="prettyprint"><code>$ chmod +x dlm.py $ ./dlm.py </code></pre> <p>Usage:</p> <pre class="prettyprint"><code>from dlm import LockClient client = LockClient('localhost', 27272, 'client_name') lock = client.mkLock('lock_name') lock.acquire() # critical section here... lock.release() # using context manager with lock: # critical section here... </code></pre> Multi threaded SMTP proxy (Python) 2010-06-12T22:27:00-07:00Lobsanghttp://code.activestate.com/recipes/users/4174176/http://code.activestate.com/recipes/577260-multi-threaded-smtp-proxy/ <p style="color: grey"> Python recipe 577260 by <a href="/recipes/users/4174176/">Lobsang</a> (<a href="/recipes/tags/mail/">mail</a>, <a href="/recipes/tags/proxy/">proxy</a>, <a href="/recipes/tags/smtp/">smtp</a>). Revision 2. </p> <p>This smtp proxy can be used to process any part of the message (header and body). It is also possible to process all the body part just before it is send to the MTA.</p> <p>The aim of this proxy is to allow a modification of the message on the fly. It had been tested with the postfix <a href="http://www.postfix.org/SMTPD_PROXY_README.html">before queue content filter</a></p> POSIX context manager to temporarily silence, or filter lines from stdout (Python) 2010-03-03T06:17:23-08:00pwallerhttp://code.activestate.com/recipes/users/4173218/http://code.activestate.com/recipes/577083-posix-context-manager-to-temporarily-silence-or-fi/ <p style="color: grey"> Python recipe 577083 by <a href="/recipes/users/4173218/">pwaller</a> (<a href="/recipes/tags/contextmanager/">contextmanager</a>, <a href="/recipes/tags/freopen/">freopen</a>, <a href="/recipes/tags/silence/">silence</a>, <a href="/recipes/tags/stdout/">stdout</a>, <a href="/recipes/tags/with/">with</a>). Revision 2. </p> <p>Fed up with libraries you don't have control over emitting text into your precious stdout?</p> <p>If they use stdout through python, then you can just change sys.stdout to be something else. If they are printing directly to stdout through a C module, or some other means, then you are stuck.</p> <p>.. at least until you discover the <code>with silence():</code> block!</p> <p>Caveats: Non-portable, tested only on 2.6 under Linux, uses threading.</p> <p>Example output:</p> <pre class="prettyprint"><code>$ python silence_file.py Before with block.. Sensible stuff! After the silence block </code></pre> Subprocess with async I/O pipes class (Python) 2009-05-17T02:02:04-07:00Mike Kazantsevhttp://code.activestate.com/recipes/users/4170279/http://code.activestate.com/recipes/576759-subprocess-with-async-io-pipes-class/ <p style="color: grey"> Python recipe 576759 by <a href="/recipes/users/4170279/">Mike Kazantsev</a> (<a href="/recipes/tags/asynchronous/">asynchronous</a>, <a href="/recipes/tags/ipc/">ipc</a>, <a href="/recipes/tags/non_blocking_i_o/">non_blocking_i_o</a>, <a href="/recipes/tags/pipe/">pipe</a>, <a href="/recipes/tags/subprocess/">subprocess</a>). Revision 2. </p> <p>Just stumbled upon the need to move data chunks between subprocesses in a non-linear way with some logic in-between, so tee(1) and fifo(7)'s weren't too good option. Inspired by 440554, but rewritten from scratch to remove unnecessary delays due to sleep(3) calls and suboptimal try/sleep-based polling.</p> Chat server & client using select.select (Python) 2007-09-28T08:57:53-07:00Anandhttp://code.activestate.com/recipes/users/760763/http://code.activestate.com/recipes/531824-chat-server-client-using-selectselect/ <p style="color: grey"> Python recipe 531824 by <a href="/recipes/users/760763/">Anand</a> (<a href="/recipes/tags/network/">network</a>). Revision 3. </p> <p>This recipe demos how to write a simple command line chat server &amp; client using multiplexing using select.select. The server uses select call to multiplex multiple clients and the client uses it to multiplex command line &amp; socket I/O.</p> how to implement kbhit() on Linux (Python) 2008-05-03T05:13:00-07:00Nelson Rushhttp://code.activestate.com/recipes/users/144881/http://code.activestate.com/recipes/572182-how-to-implement-kbhit-on-linux/ <p style="color: grey"> Python recipe 572182 by <a href="/recipes/users/144881/">Nelson Rush</a> . Revision 2. </p> <p>kbhit on linux, the sample just prints dots until you press any key. I updated the sample to show how to implement unbuffered getch and getche safely.</p> Multithreaded Multiplexer/Demultiplexer to allow multiple transactions to be performed in parallel on a single channel (Python) 2008-10-04T00:12:00-07:00david decotignyhttp://code.activestate.com/recipes/users/4129454/http://code.activestate.com/recipes/576520-multithreaded-multiplexerdemultiplexer-to-allow-mu/ <p style="color: grey"> Python recipe 576520 by <a href="/recipes/users/4129454/">david decotigny</a> (<a href="/recipes/tags/demultiplexer/">demultiplexer</a>, <a href="/recipes/tags/multiplexer/">multiplexer</a>, <a href="/recipes/tags/thread/">thread</a>, <a href="/recipes/tags/transaction/">transaction</a>). Revision 8. </p> <p>Imagine you have one wire and you want to send a message from a machine A to another machine B, and wait for an answer from B (a "request/response transaction" in the following). Now imagine you have many threads on A which can make this kind of transaction "simultaneously", then you have to be cautious, otherwise you might get the wrong responses for your transactions. One solution is to serialize the transactions: the threads on A will have to wait for their turn to make their request/response transaction.</p> <p>Another solution is to map a thread requesting a transaction on A, to a thread handling it on B. This allows for several transactions to be in flight at the same time on the same wire. This is what this module does: on A lives a multiplexer and threads call its transaction() method to initiate the request/response. On B, process_transaction() of a demultiplexer will get called by worker threads. All this in a multi-threaded way on a single wire. The module takes care of managing the interleaving requests/responses.</p> CallPipe: Call the methods of an object in a remote process (Python) 2008-09-17T17:33:36-07:00david decotignyhttp://code.activestate.com/recipes/users/4129454/http://code.activestate.com/recipes/576509-callpipe-call-the-methods-of-an-object-in-a-remote/ <p style="color: grey"> Python recipe 576509 by <a href="/recipes/users/4129454/">david decotigny</a> (<a href="/recipes/tags/call/">call</a>, <a href="/recipes/tags/multiprocessing/">multiprocessing</a>, <a href="/recipes/tags/pipe/">pipe</a>, <a href="/recipes/tags/processing/">processing</a>, <a href="/recipes/tags/remote/">remote</a>). Revision 6. </p> <p>I am process A and I own object Obj. Now I decide to fork(): process B is born.</p> <p>How do I do to make process B call the methods of A's object Obj (and not the methods of its own copy of Obj...) ?</p> <p>This is what this module does: you create the "CallPipe" for Obj prior to fork()ing, and then process B can call any method of A's object Obj through it.</p> unix subprocess wrapper (Python) 2008-07-29T07:11:17-07:00Pádraig Bradyhttp://code.activestate.com/recipes/users/1890175/http://code.activestate.com/recipes/576387-unix-subprocess-wrapper/ <p style="color: grey"> Python recipe 576387 by <a href="/recipes/users/1890175/">Pádraig Brady</a> (<a href="/recipes/tags/group/">group</a>, <a href="/recipes/tags/popen/">popen</a>, <a href="/recipes/tags/subprocess/">subprocess</a>, <a href="/recipes/tags/unix/">unix</a>). Revision 2. </p> <p>I have used this for ages to control child processes (and all their children). Some of the existing subprocess module was based on this, but I find this simpler for my uses at least.</p> <h4>Example:</h4> <pre class="prettyprint"><code>import subProcess process = subProcess.subProcess("your shell command") process.read() #timeout is optional handle(process.outdata, process.errdata) del(process) </code></pre> Access mplayer (slave mode) from python (Python) 2008-01-14T16:09:13-08:00Fabien Devauxhttp://code.activestate.com/recipes/users/2639370/http://code.activestate.com/recipes/542195-access-mplayer-slave-mode-from-python/ <p style="color: grey"> Python recipe 542195 by <a href="/recipes/users/2639370/">Fabien Devaux</a> . </p> <p>Light but somehow easy to use interface to access mplayer process. It works with introspection, I hope the class is self-explanatory. I tested it under Linux only.</p> Asyncore/asynchat in GTK (Python) 2008-03-17T13:51:05-07:00Niklas Janlerthttp://code.activestate.com/recipes/users/4132331/http://code.activestate.com/recipes/551774-asyncoreasynchat-in-gtk/ <p style="color: grey"> Python recipe 551774 by <a href="/recipes/users/4132331/">Niklas Janlert</a> (<a href="/recipes/tags/ui/">ui</a>). </p> <p>This recipe makes it possible to run asyncore/asynchat dispatchers in the GTK main thread.</p> A stoppable XMLRPCServer (Python) 2007-05-17T02:04:48-07:00Eli Golovinskyhttp://code.activestate.com/recipes/users/2770692/http://code.activestate.com/recipes/520583-a-stoppable-xmlrpcserver/ <p style="color: grey"> Python recipe 520583 by <a href="/recipes/users/2770692/">Eli Golovinsky</a> (<a href="/recipes/tags/network/">network</a>). </p> <p>SimpleXMLRPCServer is too simple. It's serve_forever function doesn't allow it to be incorporated into anything that needs to be gracefully stopped at some point. This code extends SimpleXMLRPCServer with the server_until_stopped and stop_serving functions.</p> A generic, multi protocol asynchronous server (Python) 2007-04-05T05:35:23-07:00Pierre Quentelhttp://code.activestate.com/recipes/users/1552957/http://code.activestate.com/recipes/511453-a-generic-multi-protocol-asynchronous-server/ <p style="color: grey"> Python recipe 511453 by <a href="/recipes/users/1552957/">Pierre Quentel</a> (<a href="/recipes/tags/web/">web</a>). </p> <p>This recipe implements the concept of asynchronous socket programming in a more straighforward way than in the modules asyncore and asynchat of the standard distribution, which I find difficult to understand</p> Module For Running Simple Proxies (Python) 2007-02-01T21:51:53-08:00Stephen Chappellhttp://code.activestate.com/recipes/users/2608421/http://code.activestate.com/recipes/502204-module-for-running-simple-proxies/ <p style="color: grey"> Python recipe 502204 by <a href="/recipes/users/2608421/">Stephen Chappell</a> (<a href="/recipes/tags/network/">network</a>). </p> <p>Proxies can be useful at times but may not be simple to create and run. This recipe provides a single class that can build proxy objects capable of being both started and stopped.</p> Module to allow Asynchronous subprocess use on Windows and Posix platforms (Python) 2006-12-01T17:30:02-08:00Josiah Carlsonhttp://code.activestate.com/recipes/users/1241800/http://code.activestate.com/recipes/440554-module-to-allow-asynchronous-subprocess-use-on-win/ <p style="color: grey"> Python recipe 440554 by <a href="/recipes/users/1241800/">Josiah Carlson</a> (<a href="/recipes/tags/sysadmin/">sysadmin</a>). Revision 10. </p> <p>The 'subprocess' module in Python 2.4 has made creating and accessing subprocess streams in Python relatively convenient for all supported platforms, but what if you want to interact with the started subprocess? That is, what if you want to send a command, read the response, and send a new command based on that response?</p> <p>Now there is a solution. The included subprocess.Popen subclass adds three new commonly used methods: recv(maxsize=None), recv_err(maxsize=None), and send(input), along with a utility method: send_recv(input='', maxsize=None).</p> <p>recv() and recv_err() both read at most maxsize bytes from the started subprocess. send() sends strings to the started subprocess. send_recv() will send the provided input, and read up to maxsize bytes from both stdout and stderr.</p> <p>If any of the pipes are closed, the attributes for those pipes will be set to None, and the methods will return None.</p> <p>v. 1.3 fixed a few bugs relating to *nix support v. 1.4,5 fixed initialization on all platforms, a few bugs relating to Windows support, added two utility functions, and added an example of how to use this module. v. 1.6 fixed linux _recv() and test initialization thanks to Yuri Takhteyev at Stanford. v. 1.7 removed _setup() and __init__() and fixed subprocess unittests thanks to Antonio Valentino. Added 4th argument 'tr' to recv_some(), which is, approximately, the number of times it will attempt to recieve data. Added 5th argument 'stderr' to recv_some(), where when true, will recieve from stderr. Cleaned up some pipe closing. v. 1.8 Fixed missing self. parameter in non-windows _recv method thanks to comment. v. 1.9 Fixed fcntl calls for closed handles.</p> Waitable, cross-process threading.Event class. (Python) 2006-10-10T11:18:34-07:00David Wilsonhttp://code.activestate.com/recipes/users/1822824/http://code.activestate.com/recipes/498191-waitable-cross-process-threadingevent-class/ <p style="color: grey"> Python recipe 498191 by <a href="/recipes/users/1822824/">David Wilson</a> (<a href="/recipes/tags/threads/">threads</a>). </p> <p>This class implements an interface similar to threading.Event using os.pipe() as the mechanism for signalling. This allows the class to be used to wake up select.select() and select.poll() loops without having to peridiodically resume execution to check the status of an event.</p> IPv6 Multicast (Python) 2005-10-28T11:43:52-07:00Shane Hollowayhttp://code.activestate.com/recipes/users/861616/http://code.activestate.com/recipes/442490-ipv6-multicast/ <p style="color: grey"> Python recipe 442490 by <a href="/recipes/users/861616/">Shane Holloway</a> (<a href="/recipes/tags/network/">network</a>). </p> <p>IPv6 can be tricky in many ways, and multicast makes it even more fun. This recipe is intended to give you a working implementation to start from.</p> My first application server (Python) 2009-02-23T11:53:57-08:00Pierre Quentelhttp://code.activestate.com/recipes/users/1552957/http://code.activestate.com/recipes/392879-my-first-application-server/ <p style="color: grey"> Python recipe 392879 by <a href="/recipes/users/1552957/">Pierre Quentel</a> (<a href="/recipes/tags/web/">web</a>). Revision 8. </p> <p>For those who want to start dynamic web programming, but don't know what to choose among the many Python web frameworks, this program might be a good starting point</p> <p>ScriptServer is a minimalist application server, handling both GET and POST requests, including multipart/form-data for file uploads, HTTP redirections, and with an in-memory session management. It can run Python scripts and template files using the standard string substitution format</p> <p>The scripts are run in the same process as the server, avoiding the CGI overhead. The environment variables are provided in the namespace where the script runs</p> <p>To start the server, run </p> <pre class="prettyprint"><code>python ScriptServer.py </code></pre> <p>In your web browser, enter <a href="http://localhost" rel="nofollow">http://localhost</a>, this will show you a listing of the directory. Add the scripts in the same directory as ScriptServer</p> Simple HTTP server based on asyncore/asynchat (Python) 2005-10-16T08:26:59-07:00Pierre Quentelhttp://code.activestate.com/recipes/users/1552957/http://code.activestate.com/recipes/259148-simple-http-server-based-on-asyncoreasynchat/ <p style="color: grey"> Python recipe 259148 by <a href="/recipes/users/1552957/">Pierre Quentel</a> (<a href="/recipes/tags/web/">web</a>). Revision 8. </p> <p>A simple HTTP Server, intended to be as simple as the standard module SimpleHTTPServer, built upon the asyncore/asynchat modules (uses non-blocking sockets). Provides a Server (copied from medusa http_server) and a RequestHandler class. RequestHandler handles both GET and POST methods and inherits SimpleHTTPServer.SimpleHTTPRequestHandler</p> <p>It can be easily extended by overriding the handle_data() method in the RequestHandler class</p>