Skip to main content
 首页 » 编程设计

python之如果 __name__ == "__main__":,则托管在 Apache 上的 web.py 不会在旁边运行代码

2024年08月21日32daizhj

我有我在 question 中提到的相同代码我的。现在我在 Apache 上托管了相同的 web.py 应用程序。但是当我启动 Apache 时,if __name__ == "__main__": 中的代码没有被执行。

在 Apache 中托管时是否可以运行后台进程(查看代码的其他问题)?

为什么if __name__ == "__main__":里面的代码没有执行?

当 web.py 在没有 Apache 的情况下运行时,它运行良好。

请您参考如下方法:

if __name__ == '__main__': 中的代码不会运行,因为那不是 Apache 运行 python 代码的方式。

更有可能的是,您在 mod_wsgi 或 uwsgi 下运行 python,这是让 Apache 与 python 对话的一种方式。

保留 if __name__ == '__main__': 内容:这对简单测试很有用,但添加类似的 block :

if __name__ == '__main__': 
    app = web.application(urls, globals()) 
    app.run() 
elif under_mod_wsgi or under_uwsgi: 
    app = web.application(urls, globals()) 
    application = app.wsgifunc()  # !!rather than app.run() 

你的 Process 东西应该仍然运行(引用你的其他问题)。

要检测 under_mod_wsgi 您是否可以:

try: 
    from mod_wsgi import version 
    if version: 
        pass 
    under_mod_wsgi = True 
except ImportError: 
    under_mod_wsgi = False 
 
try: 
    import uwsgi 
    under_uwsgi = True 
except ImportError: 
    under_uwsgi = False