On Linux you can clone the current process with os.fork(). The child returns 0, the parent receives the child PID. Use os.getpid() to inspect the current PID and os.getppid() to check the parent.
1 2 3 4 5 6 7 8
import os
print'Process (%s) start...' % os.getpid() pid = os.fork() if pid == 0: print'I am child process (%s) and my parent is %s.' % (os.getpid(), os.getppid()) else: print'I (%s) just created a child process (%s).' % (os.getpid(), pid)
multiprocessing
Windows lacks fork(), so we use the cross-platform multiprocessing module:
if __name__ == '__main__': print'Parent process %s.' % os.getpid() p = Process(target=run_proc, args=('test',)) print'Process will start.' p.start() p.join() print'Process end.'
Process pools
Pool keeps a fixed number of worker processes:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
from multiprocessing import Pool import os, time, random
if __name__ == '__main__': print'Parent process %s.' % os.getpid() p = Pool() # defaults to CPU count for i inrange(5): p.apply_async(long_time_task, args=(i,)) print'Waiting for all subprocesses done...' p.close() p.join() print'All subprocesses done.'
if __name__ == '__main__': with Manager() as manager: d = manager.dict() l = manager.list() p = Process(target=f, args=(d, l)) p.start() p.join() print d print l
subprocess
Use subprocess to spawn non-Python programs. subprocess.call() runs a command and waits; Popen gives more control over stdin/stdout/stderr.
1 2 3 4 5
import subprocess subprocess.call(['ls', '-l'])
p = subprocess.Popen(['grep', 'python'], stdin=subprocess.PIPE) p.communicate('python subprocess module\n')
Multithreading
Creating threads
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
import time, threading
defloop(): print'thread %s is running...' % threading.current_thread().name for n inrange(5): print'thread %s >>> %s' % (threading.current_thread().name, n) time.sleep(1) print'thread %s ended.' % threading.current_thread().name
print'thread %s is running...' % threading.current_thread().name