main.py 3.6 KB

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