def start_server_background(port):
    """Start the newtab server as a background process."""

    if sys.version_info[0] == 2:
        lines = ('import pydoc\n'
                 'pydoc.serve({port})')
        cell = lines.format(port=port)
    else:
        # The location of newtabmagic (normally $IPYTHONDIR/extensions)
        # needs to be added to sys.path.
        path = repr(os.path.dirname(os.path.realpath(__file__)))
        lines = ('import sys\n'
                 'sys.path.append({path})\n'
                 'import newtabmagic\n'
                 'newtabmagic.pydoc_cli_monkey_patched({port})')
        cell = lines.format(path=path, port=port)

    # Use script cell magic so that shutting down IPython stops
    # the server process.
    line = "python --proc proc --bg --err error --out output"
    ip = get_ipython()
    ip.run_cell_magic("script", line, cell)

    return ip.user_ns['proc']
Start the newtab server as a background process.