server.py 982 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. #!/usr/bin/python
  2. # -*- coding: utf-8 -*-
  3. import sys, os
  4. from socket import socket
  5. import socketserver
  6. import http.server
  7. import threading
  8. class Server():
  9. def __init__(self, parent):
  10. self.parent = parent
  11. # find free port
  12. sock = socket()
  13. sock.bind(('', 0))
  14. self._port = sock.getsockname()[1]
  15. sock.close()
  16. # self.initial_cwd = os.getcwd()
  17. self.thread = threading.Thread(target=self.webserver)
  18. self.thread.daemon = True
  19. self.thread.start()
  20. # os.chdir(self.initial_cwd)
  21. def webserver(self):
  22. os.chdir(self.parent.cwd)
  23. self.httpd = http.server.HTTPServer(('', self.port), http.server.SimpleHTTPRequestHandler)
  24. self.httpd.serve_forever()
  25. print("serving at port", self._port)
  26. @property
  27. def port(self):
  28. return self._port
  29. def reload(self):
  30. # self.thread.shutdown()
  31. os.chdir(self.parent.cwd)
  32. # self.thread.start()
  33. # os.chdir(self.initial_cwd)