main.py 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123
  1. """
  2. An example demonstrating a stand-alone "console".
  3. Copyright (c) Jupyter Development Team.
  4. Distributed under the terms of the Modified BSD License.
  5. Example
  6. -------
  7. To run the example, make sure the Jupyter notebook server version 4.2+ is
  8. installed.
  9. - To build the JavaScript bundle: ``npm install && npm run build``.
  10. - To run the Python code: ``python main.py``.
  11. - Navigate to ``localhost:8765`` in your browser.
  12. Note
  13. ----
  14. This file provides the Python code for interacting with the Jupyter notebook
  15. server using ``ZMQ`` and the ``tornado`` web server.
  16. """
  17. import re
  18. import subprocess
  19. import sys
  20. import threading
  21. import tornado.web
  22. # Install the pyzmq ioloop. Must be done after importing tornado.web and
  23. # before importing any additional tornado modules
  24. from zmq.eventloop import ioloop
  25. ioloop.install()
  26. PORT = 8765
  27. """int: Port number of web application"""
  28. class MainPageHandler(tornado.web.RequestHandler):
  29. """Handle requests between the main app page and notebook server."""
  30. def initialize(self, base_url):
  31. """Intitialize the base URL of the handler."""
  32. self.base_url = base_url
  33. def get(self):
  34. """Get the main page for the application's interface."""
  35. return self.render("index.html", static=self.static_url,
  36. base_url=self.base_url)
  37. def main(argv):
  38. """Start the 'console' example.
  39. - Start the Tornado main event loop for the Jupyter notebook server
  40. - Set up the main page event handler for the 'console' example
  41. """
  42. url = "http://localhost:%s" % PORT
  43. nb_command = [sys.executable, '-m', 'notebook', '--no-browser', '--debug',
  44. '--NotebookApp.allow_origin="%s"' % url]
  45. nb_server = subprocess.Popen(nb_command, stderr=subprocess.STDOUT,
  46. stdout=subprocess.PIPE)
  47. # Wait for Jupyter notebook server to complete start up
  48. while 1:
  49. line = nb_server.stdout.readline().decode('utf-8').strip()
  50. if not line:
  51. continue
  52. print(line)
  53. if 'Jupyter Notebook is running at:' in line:
  54. base_url = re.search('(http.*?)$', line).groups()[0]
  55. break
  56. while 1:
  57. line = nb_server.stdout.readline().decode('utf-8').strip()
  58. if not line:
  59. continue
  60. print(line)
  61. if 'Control-C' in line:
  62. break
  63. def print_thread():
  64. while 1:
  65. line = nb_server.stdout.readline().decode('utf-8').strip()
  66. if not line:
  67. continue
  68. print(line)
  69. thread = threading.Thread(target=print_thread)
  70. thread.setDaemon(True)
  71. thread.start()
  72. handlers = [
  73. (r"/", MainPageHandler, {'base_url': base_url}),
  74. (r'/(.*)', tornado.web.StaticFileHandler, {'path': '.'}),
  75. ]
  76. app = tornado.web.Application(handlers, static_path='build',
  77. template_path='.',
  78. compiled_template_cache=False)
  79. app.listen(PORT, 'localhost')
  80. # For Windows, add no-op to wake every 5 seconds (5000 ms) to handle
  81. # signals that may be ignored by the Tornado main event loop
  82. if sys.platform.startswith('win'):
  83. pc = ioloop.PeriodicCallback(lambda: None, 5000)
  84. pc.start()
  85. loop = ioloop.IOLoop.current()
  86. print('Browse to http://localhost:%s' % PORT)
  87. try:
  88. # Start the Tornado main event loop
  89. loop.start()
  90. except KeyboardInterrupt:
  91. print(" Shutting down on SIGINT")
  92. finally:
  93. nb_server.kill()
  94. loop.close()
  95. if __name__ == '__main__':
  96. main(sys.argv)