I am planning a Python script that'll use os.fork()
to create a bunch of child processes to perform some computations. The parent process will block until the children terminate.
The twist is that I need to be able to run the script both from the Unix shell using python
and from ipython
using %run
.
In what manner should the child processes terminate to avoid breaking back into the ipython
command prompt? In my experience, sys.exit()
won't do.
fork() method in Python is used to create a child process. This method work by calling the underlying OS function fork(). This method returns 0 in the child process and child's process id in the parent process. Note: os. fork() method is available only on UNIX platforms.
IPython (Interactive Python) is a command shell for interactive computing in multiple programming languages, originally developed for the Python programming language, that offers introspection, rich media, shell syntax, tab completion, and history.
IPython offers an enhanced read-eval-print loop (REPL) environment particularly well adapted to scientific computing. In other words, IPython is a powerful interface to the Python language. But it is certainly not the only one. Besides IPython, the most common way to use Python is to write scripts, files with the .
Compared to Python, IPython (created by Fernando Perez in 2001) can do every thing what python can do. Ipython provides even extra features like tab-completion, testing, debugging, system calls and many other features. You can think IPython as a powerful interface to the Python language.
The following seems to work:
import os, sys
child_pid = os.fork()
if child_pid == 0:
print 'in child'
os._exit(os.EX_OK)
print 'hm... wasn''t supposed to get here'
else:
print 'in parent'
The trick is to use os._exit()
instead of sys.exit()
. The documentation contains the following passage:
Note The standard way to exit is
sys.exit(n)
._exit()
should normally only be used in the child process after a fork().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With