Enrico Franchi Homepage

Questo sito è obsoleto. La nuova versione di questa pagina è disponibile presso akropolix

This site is old. The new version of this page is available on akropolix

Python Threaded Shell

pythreadshell.py (download)
#!/usr/bin/python
# -*- Coding: utf-8 -*-

import os
import sys
import threading, Queue

def run(q, args):
    ret = os.spawnvp(os.P_WAIT, args[0], args)
    q.put(ret)

while True:
    cmd = raw_input('$ ')
    if cmd.strip() == "exit": sys.exit(0)
    if cmd.strip() == "": continue
    argv = cmd.split()
    q = Queue.Queue()
    t = threading.Thread(
                         name='subprocess', 
                         target=run, 
                         args=(q, argv)
                        )
    t.start()
    print "Wait for thread running (%s)" % argv[0]
    t.join()
    ret = q.get()
    print "Thread finished."
    print "Prosess returned with (%d)" % ret

This is just an example. In Python threads are usually not the best way to code. You can also see os.spanwvp() in action. More details here.
To let threads comunicate we use a Queue. That is to say the thread responsible for spawning children writes the return value in the queue. The main thread waits for the secondary thread (t.join()) and then reads the return value from the Queue. Queues are among the safest ways to code with threads. Unfortunately not always can they be used.

back

xhtml 1.1 CSS 2.1 RSS 2.0
Made with a Mac Made with BBEdit Made with Brain

All documentation is under FDL and all source code is under BSD, unless differently stated.

24-mar-06