运行SimpleHTTPServer时设置当前目录
有没有办法设置你想要启动SimpleHTTPServer或BaseHTTPServer的目录?
4 个回答
1
在Linux上做到这一点而不改变目录:
bash -c "cd /your/path; python -m SimpleHTTPServer"
3
如果你想从代码里运行,而不是通过命令行来运行,SimpleHTTPRequestHandler
这个类可以接收一个 directory
参数,默认值是当前目录:
def __init__(self, *args, directory=None, **kwargs):
if directory is None:
directory = os.getcwd()
你可以这样使用它:
import http.server
class Handler(http.server.SimpleHTTPRequestHandler):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs, directory='/path/to/your/dir')
def main():
http.server.test(Handler) # test(Handler, port=8080)
if __name__ == '__main__':
main()
71
如果你直接在命令行中使用 SimpleHTTPServer
,你可以简单地利用一些命令行的功能:
pushd /path/you/want/to/serve; python -m SimpleHTTPServer; popd
在Python 3中,你需要使用:
pushd /path/you/want/to/serve; python -m http.server; popd
在Python 3.0中,SimpleHTTPServer模块已经合并到http.server中了。