Skip to content

Commit

Permalink
Change behavior of ipython notebook --port=...
Browse files Browse the repository at this point in the history
Previously ipython notebook took the port parameter as a suggested place to
start looking for open ports.  With this commit:
* `ipython notebook` : start at port 8888 and try random ports until success
* `ipython notebook --port=1234` : use port 1234, failing if it is not available

Closes ipythongh-1750
  • Loading branch information
bfroehle committed May 31, 2012
1 parent e605f72 commit 6092194
Showing 1 changed file with 23 additions and 16 deletions.
39 changes: 23 additions & 16 deletions IPython/frontend/html/notebook/notebookapp.py
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -269,8 +269,9 @@ class NotebookApp(BaseIPythonApplication):
def _ip_changed(self, name, old, new): def _ip_changed(self, name, old, new):
if new == u'*': self.ip = u'' if new == u'*': self.ip = u''


port = Integer(8888, config=True, port = Integer(0, config=True,
help="The port the notebook server will listen on." help=("The port the notebook server will listen on. Use 0 to try several random "
"ports beginning at 8888.")
) )


certfile = Unicode(u'', config=True, certfile = Unicode(u'', config=True,
Expand Down Expand Up @@ -422,20 +423,26 @@ def init_webapp(self):
'but not using any encryption or authentication. This is highly ' 'but not using any encryption or authentication. This is highly '
'insecure and not recommended.') 'insecure and not recommended.')


# Try random ports centered around the default. if self.port:
from random import randint self.http_server.listen(self.port, self.ip)
n = 50 # Max number of attempts, keep reasonably large. else:
for port in range(self.port, self.port+5) + [self.port + randint(-2*n, 2*n) for i in range(n-5)]: # Try random ports centered around the default.
try: from random import randint
self.http_server.listen(port, self.ip) default_port = 8888
except socket.error, e: n = 50 # Max number of attempts, keep reasonably large.
if e.errno != errno.EADDRINUSE: available_ports = range(default_port, default_port+5) \
raise + [default_port + randint(-2*n, 2*n) for i in range(n-5)]
self.log.info('The port %i is already in use, trying another random port.' % port) for port in available_ports:
else: try:
self.port = port self.http_server.listen(port, self.ip)
break except socket.error, e:

if e.errno != errno.EADDRINUSE:
raise
self.log.info('The port %i is already in use, trying another random port.' % port)
else:
self.port = port
break

def init_signal(self): def init_signal(self):
# FIXME: remove this check when pyzmq dependency is >= 2.1.11 # FIXME: remove this check when pyzmq dependency is >= 2.1.11
# safely extract zmq version info: # safely extract zmq version info:
Expand Down

0 comments on commit 6092194

Please sign in to comment.