Python SimpleHTTPServer更改服务目录

时间:2015-07-06 16:57:18

标签: python python-2.7 simplehttpserver

我编写了以下代码来启动HTTP服务器,以后可以选择启动TCP / IP服务器:

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()

我想更改目录,以便在将来,除了主机之外没有人可以终止服务器(因为PiServer Off软件将安装在同一目录中)。

我找到了这个解决方案,但它看起来是一个shell,我不知道如何为我的代码修改它(使用Pycharm):http://www.tecmint.com/python-simplehttpserver-to-create-webserver-or-serve-files-instantly/

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

我也发现了这个但似乎没有回答我的问题:Change directory Python SimpleHTTPServer uses

我想知道是否有人可以在不移动服务器文件的情况下分享和解释他们改变目录的方式,因为我想用它来构建一个家庭文件共享系统。

谢谢!

2 个答案:

答案 0 :(得分:2)

问题How to run a http server which serves a specific path?基本上是这个问题的重复。
但是,Andy Hayden提出的解决方案似乎更合适。
(它不太“ hacky” /取决于副作用,而是使用类构造函数。)

是这样的:

import http.server
import socketserver

PORT = 8000
DIRECTORY = "web"


class Handler(http.server.SimpleHTTPRequestHandler):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, directory=DIRECTORY, **kwargs)


with socketserver.TCPServer(("", PORT), Handler) as httpd:
    print("serving at port", PORT)
    httpd.serve_forever()

上面的代码适用于Python> = 3.6
对于3.5以下的Python,TCPServer的基类没有可用的contextmanager协议,但这仅意味着您需要更改with语句并将其转换为简单的赋值:

httpd = socketserver.TCPServer(("", PORT), Handler)

为此Anthony Sottile获得last detail的积分。

答案 1 :(得分:0)

使用os.chdir更改当前目录,然后按照通常的方式启动服务器。