main.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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):
  17. self.base_url = base_url
  18. def get(self):
  19. return self.render("index.html", static=self.static_url,
  20. base_url=self.base_url)
  21. def main(argv):
  22. url = "http://localhost:%s" % PORT
  23. nb_command = [sys.executable, '-m', 'notebook', '--no-browser', '--debug',
  24. '--NotebookApp.allow_origin="%s"' % url]
  25. nb_server = subprocess.Popen(nb_command, stderr=subprocess.STDOUT,
  26. stdout=subprocess.PIPE)
  27. # wait for notebook server to start up
  28. while 1:
  29. line = nb_server.stdout.readline().decode('utf-8').strip()
  30. if not line:
  31. continue
  32. print(line)
  33. if 'Jupyter Notebook is running at:' in line:
  34. base_url = re.search('(http.*?)$', line).groups()[0]
  35. break
  36. while 1:
  37. line = nb_server.stdout.readline().decode('utf-8').strip()
  38. if not line:
  39. continue
  40. print(line)
  41. if 'Control-C' in line:
  42. break
  43. def print_thread():
  44. while 1:
  45. line = nb_server.stdout.readline().decode('utf-8').strip()
  46. if not line:
  47. continue
  48. print(line)
  49. thread = threading.Thread(target=print_thread)
  50. thread.setDaemon(True)
  51. thread.start()
  52. handlers = [
  53. (r"/", MainPageHandler, {'base_url': base_url}),
  54. (r'/(.*)', tornado.web.StaticFileHandler, {'path': '.'}),
  55. ]
  56. app = tornado.web.Application(handlers, static_path='build',
  57. template_path='.',
  58. compiled_template_cache=False)
  59. app.listen(PORT, 'localhost')
  60. if sys.platform.startswith('win'):
  61. # add no-op to wake every 5s
  62. # to handle signals that may be ignored by the inner loop
  63. pc = ioloop.PeriodicCallback(lambda: None, 5000)
  64. pc.start()
  65. loop = ioloop.IOLoop.current()
  66. print('Browse to http://localhost:%s' % PORT)
  67. try:
  68. loop.start()
  69. except KeyboardInterrupt:
  70. print(" Shutting down on SIGINT")
  71. finally:
  72. nb_server.kill()
  73. loop.close()
  74. if __name__ == '__main__':
  75. main(sys.argv)