Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ipython and fork()

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.

like image 951
NPE Avatar asked May 18 '11 19:05

NPE


People also ask

What is a fork in Python?

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.

What is IPython used for?

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.

Is IPython better than Python?

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 .

What is the difference between Python and IPython?

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.


1 Answers

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().

like image 159
NPE Avatar answered Sep 19 '22 05:09

NPE