Search code examples
pythonpython-2.7simplehttpserver

Python SimpleHTTPServer Change Service Directory


I wrote the following piece of code to start an HTTP server, with a future option of being able to start a TCP/IP server instead:

import SimpleHTTPServer
import SocketServer
import time
import socket

def choose():
if raw_input("Would you like to start an HTTP or TCP/IP Server?: ") == "HTTP":
    print "You have selected HTTP server."
    if raw_input("Is this correct? Use Y/N to answer. ") == "Y":
        print ""
        start_HTTP()
    else:
        choose()
else:
    print "Goodbye! "

def start_HTTP():
    PORT = int(raw_input("Which port do you want to send out of? "))
    Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
    httpd = SocketServer.TCPServer(("", PORT), Handler)
    print "Please wait one moment..."
    time.sleep(2)
    run_HTTP(PORT, httpd)

def run_HTTP(PORT, httpd):
    print "Use the following IP address to connect to this server (LAN only): " + [(s.connect(('8.8.8.8', 80)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1] #prints local IP address
    print "Now serving from port: ", PORT
    print "To shutdown the server, use the PiServer_Off software."
    time.sleep(2)
    print ""
    print "Any traffic through the server will be recorded and displayed below: "
    httpd.serve_forever()

choose()

I want to change the directory so that at a future point, no one but the host machine can terminate the server (since the PiServer Off software will be installed in the same directory).

I found this solution, but it looks to be for a shell, and I do not know how to modify it for my code (using Pycharm): http://www.tecmint.com/python-simplehttpserver-to-create-webserver-or-serve-files-instantly/

# pushd /x01/tecmint/; python –m SimpleHTTPServer 9999; popd;

I also found this but it does not seem to answer my question: Change directory Python SimpleHTTPServer uses

I was wondering if anyone could share and explain their way of changing the directory without moving the server file, as I want to use this to build an in-home file-sharing system.

Thanks!


Solution

  • Use os.chdir to change the current directory then follow as you normally would to start the server.