Python Threaded Shell
#!/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.