我编写了以下代码来启动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;
我也发现了这一点,但它似乎并不能回答我的问题:更改目录Python SimpleHTTPServer使用
我想知道是否有人可以分享并解释他们在不移动服务器文件的情况下更改目录的方法,因为我想用它来构建一个家庭文件共享系统。
谢谢!
问题如何运行为特定路径提供服务的http服务器?基本上是这个的复制品
然而,Andy Hayden在那里提出的解决方案似乎更合适
(它不那么"黑客"/依赖于副作用,而是使用类构造函数。(
如下所示:
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的基类没有上下文管理器协议,但这只是意味着您需要更改with
语句,并将其转换为一个简单的赋值:
httpd = socketserver.TCPServer(("", PORT), Handler)
最后一个细节要归功于Anthony Sottile。
使用os.chdir
更改当前目录,然后按照正常方式启动服务器。