Please find below code as it is throwing the error - global name 'webserver' is not defined
.
import SimpleHTTPServer
import SocketServer
import os
from threading import Thread
import threading
class WebServer(Thread):
def __init__(self, stream_path):
"""
Class to create a Web server and add given folder to the web server which is passed as an argument.
In this case it creates the web server to the incoming streams pushed by VLC to temp folder
"""
Thread.__init__(self)
self.stream_path = stream_path
def run(self):
global WebServer
"""
This method is built in Thread object method invoked by start()
and the code which is under run() will be executed.
"""
os.chdir(self.stream_path)
PORT = 8000
Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
httpd = SocketServer.TCPServer(("", PORT), Handler)
print "serving at port", PORT
print "function thread", threading.currentThread()
httpd.serve_forever()
print "test1"
def create_web_server(self,stream_path):
global WebServer
"""
This method is to create the web server to a given path
"""
obj1 = WebServer(self,stream_path)
obj1.start()
print "server created"
def stop_web_server(self):
cmd='tskill python /A'
os.system(cmd)
if __name__ == '__main__':
create_web_server("","C:\\\\QED")
You don't need the two
global WebServer
lines in your code. Theglobal
keyword is used to grant write access to a global variable, and you don't have a global variable namedWebServer
.Your code should look like the following to resolve your error, though in its state, it will still throw errors because your code has multiple problems, including calling the
create_web_server
method by itself, as it's a method that needs to be run on aWebServer
object.I've included a working prototype example of your code at the bottom of my post.
Here is a simplified version of your code that should do the same thing (serve a directory with a basic
SimpleHTTPRequestHandler
).It runs the thread in
daemon
mode so that it can be interrupted with Ctrl-C. I removed several methods as they didn't seem to serve a purpose in your original code, and to show you a basic framework of what yourWebServer
class would probably look like.And to take it a step further, you don't need to create a
Thread
subclass. It's allowed because it feels more 'natural' to developers who are familiar with Java, where subclassingThread
or implementingRunnable
is standard practice.You can just do something like: