main.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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. PORT = 8765
  11. class MainPageHandler(tornado.web.RequestHandler):
  12. def initialize(self, base_url, ws_url):
  13. self.base_url = base_url
  14. self.ws_url = ws_url
  15. def get(self):
  16. return self.render("index.html", static=self.static_url,
  17. base_url=self.base_url, ws_url=self.ws_url)
  18. def main(argv):
  19. url = "http://localhost:%s" % PORT
  20. nb_command = [sys.executable, '-m', 'notebook', '--no-browser', '--debug',
  21. '--NotebookApp.allow_origin="%s"' % url]
  22. nb_server = subprocess.Popen(nb_command, stderr=subprocess.STDOUT,
  23. stdout=subprocess.PIPE)
  24. # wait for notebook server to start up
  25. while 1:
  26. line = nb_server.stdout.readline().decode('utf-8').strip()
  27. if not line:
  28. continue
  29. print(line)
  30. if 'Jupyter Notebook is running at:' in line:
  31. base_url = re.search('(http.*?)$', line).groups()[0]
  32. ws_url = base_url.replace('http', 'ws')
  33. break
  34. while 1:
  35. line = nb_server.stdout.readline().decode('utf-8').strip()
  36. if not line:
  37. continue
  38. print(line)
  39. if 'Control-C' in line:
  40. break
  41. def print_thread():
  42. while 1:
  43. line = nb_server.stdout.readline().decode('utf-8').strip()
  44. if not line:
  45. continue
  46. print(line)
  47. thread = threading.Thread(target=print_thread, daemon=True)
  48. thread.start()
  49. handlers = [
  50. (r"/", MainPageHandler, {'base_url': base_url, 'ws_url': ws_url }),
  51. (r'/(.*)', tornado.web.StaticFileHandler, {'path': '.'}),
  52. ]
  53. app = tornado.web.Application(handlers, static_path='build',
  54. template_path='.')
  55. app.listen(PORT, 'localhost')
  56. loop = tornado.ioloop.IOLoop.instance()
  57. print('Browse to http://localhost:%s' % PORT)
  58. try:
  59. loop.start()
  60. except KeyboardInterrupt:
  61. print(" Shutting down on SIGINT")
  62. finally:
  63. nb_server.kill()
  64. loop.close()
  65. if __name__ == '__main__':
  66. main(sys.argv)