main.py 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. """
  2. Copyright (c) Jupyter Development Team.
  3. Distributed under the terms of the Modified BSD License.
  4. """
  5. import re
  6. import subprocess
  7. import sys
  8. import threading
  9. import tornado.web
  10. # Install the pyzmq ioloop. This has to be done before anything else from
  11. # tornado is imported.
  12. from zmq.eventloop import ioloop
  13. ioloop.install()
  14. PORT = 8765
  15. class MainPageHandler(tornado.web.RequestHandler):
  16. def initialize(self, base_url, ws_url):
  17. self.base_url = base_url
  18. self.ws_url = ws_url
  19. def get(self):
  20. return self.render("index.html", static=self.static_url,
  21. base_url=self.base_url, ws_url=self.ws_url)
  22. def main(argv):
  23. url = "http://localhost:%s" % PORT
  24. nb_command = [sys.executable, '-m', 'notebook', '--no-browser', '--debug',
  25. '--NotebookApp.allow_origin="%s"' % url]
  26. nb_server = subprocess.Popen(nb_command, stderr=subprocess.STDOUT,
  27. stdout=subprocess.PIPE)
  28. # wait for notebook server to start up
  29. while 1:
  30. line = nb_server.stdout.readline().decode('utf-8').strip()
  31. if not line:
  32. continue
  33. print(line)
  34. if 'Jupyter Notebook is running at:' in line:
  35. base_url = re.search('(http.*?)$', line).groups()[0]
  36. ws_url = base_url.replace('http', 'ws')
  37. break
  38. while 1:
  39. line = nb_server.stdout.readline().decode('utf-8').strip()
  40. if not line:
  41. continue
  42. print(line)
  43. if 'Control-C' in line:
  44. break
  45. def print_thread():
  46. while 1:
  47. line = nb_server.stdout.readline().decode('utf-8').strip()
  48. if not line:
  49. continue
  50. print(line)
  51. thread = threading.Thread(target=print_thread)
  52. thread.setDaemon(True)
  53. thread.start()
  54. handlers = [
  55. (r"/", MainPageHandler, {'base_url': base_url, 'ws_url': ws_url}),
  56. (r'/(.*)', tornado.web.StaticFileHandler, {'path': '.'}),
  57. ]
  58. app = tornado.web.Application(handlers, static_path='build',
  59. template_path='.',
  60. compiled_template_cache=False)
  61. app.listen(PORT, 'localhost')
  62. if sys.platform.startswith('win'):
  63. # add no-op to wake every 5s
  64. # to handle signals that may be ignored by the inner loop
  65. pc = ioloop.PeriodicCallback(lambda: None, 5000)
  66. pc.start()
  67. loop = ioloop.IOLoop.current()
  68. print('Browse to http://localhost:%s' % PORT)
  69. try:
  70. loop.start()
  71. except KeyboardInterrupt:
  72. print(" Shutting down on SIGINT")
  73. finally:
  74. nb_server.kill()
  75. loop.close()
  76. if __name__ == '__main__':
  77. main(sys.argv)