在 python 中启动 SimpleHTTPServer

Start SimpleHTTPServer in python

是否有比 copy/past 更好的 elegant/systematic/future 证明方法来调用 if __name__ == '__main__' 中的所有代码?

我正在将 bash 脚本转换为 python。我们经常使用的两个命令是 python -m SimpleHTTPServer YOUR_PORTpython -m http.server YOUR_PORT.

在 2.x 中翻译这个相当干净。

SimpleHTTPServer main:

if __name__ == '__main__':
    test()

我的模拟主要代码:

import SimpleHTTPServer
SimpleHTTPServer.test()

翻译成 3.x 不干净。

http.server main:

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--cgi', action='store_true',
                       help='Run as CGI Server')
    parser.add_argument('--bind', '-b', default='', metavar='ADDRESS',
                        help='Specify alternate bind address '
                             '[default: all interfaces]')
    parser.add_argument('port', action='store',
                        default=8000, type=int,
                        nargs='?',
                        help='Specify alternate port [default: 8000]')
    args = parser.parse_args()
    if args.cgi:
        handler_class = CGIHTTPRequestHandler
    else:
        handler_class = SimpleHTTPRequestHandler
    test(HandlerClass=handler_class, port=args.port, bind=args.bind)

我的模拟主要代码:

import argparse
import http.server
from http.server import CGIHTTPRequestHandler, SimpleHTTPRequestHandler
parser = argparse.ArgumentParser()
parser.add_argument('--cgi', action='store_true',
                   help='Run as CGI Server')
parser.add_argument('--bind', '-b', default='', metavar='ADDRESS',
                    help='Specify alternate bind address '
                         '[default: all interfaces]')
parser.add_argument('port', action='store',
                    default=8000, type=int,
                    nargs='?',
                    help='Specify alternate port [default: 8000]')
args = parser.parse_args()
if args.cgi:
    handler_class = CGIHTTPRequestHandler
else:
    handler_class = SimpleHTTPRequestHandler
http.server.test(HandlerClass=handler_class, port=args.port, bind=args.bind)

这看起来很糟糕,我不确定这是否是最好的方法,但是下面的代码似乎可以轻松启动服务器:

import importlib
exec(compile(importlib.util.find_spec('http.server').loader.get_source(
    'http.server'), 'server.py', 'exec'), dict(__name__='__main__'))

更新 1: 启动 http.server 模块的下一个想法可能不会好多少,但它直接利用 http.server 模块而不是处理 importlib 模块。

import http.server
exec(compile(http.server.__loader__.get_source(http.server.__name__),
             http.server.__file__, 'exec'), dict(__name__='__main__'))

当然,这可能只是意味着最好创建一个实用程序函数来处理在我们想要 运行 它们进入的任何上下文中执行模块。

import sys

nvl = lambda value, other: other if value is None else value

def exec_module(module, globals=None, locals=None):
    frame = sys._getframe(1)
    globals = nvl(globals, {})
    globals.update(frame.f_globals)
    locals = nvl(locals, {})
    locals.update(frame.f_locals)
    exec(compile(module.__loader__.get_source(module.__name__),
                 module.__file__, 'exec'), globals, locals)

# this is how you would use the code up above

import http.server

exec_module(http.server, dict(__name__='__main__'))

更新 2: exec_module 函数可能更像下面这样,但由于某种原因没有引起我的注意,它似乎没有按预期工作:

def exec_module(module, globals=None, locals=None):
    frame = sys._getframe(1)

    exec_globals = nvl(globals, {})
    copy_globals = exec_globals.copy()
    exec_globals.update(frame.f_globals)
    exec_globals.update(copy_globals)

    exec_locals = nvl(locals, {})
    copy_locals = exec_locals.copy()
    exec_locals.update(frame.f_locals)
    exec_locals.update(copy_locals)

    exec(compile(module.__loader__.get_source(module.__name__),
                 module.__file__, 'exec'), exec_globals, exec_locals)

这些变化考虑到了两件事。首先,保留对传入的全局变量和局部变量的引用,以防调用者想在函数 运行s 之后检查它们的状态。其次,来自调用者的全局变量和局部变量不能覆盖传入的全局变量和局部变量中已经设置的任何值。