【问题标题】:Asynchronous Python CGI call halts browser until complete异步 Python CGI 调用暂停浏览器直到完成
【发布时间】:2017-05-26 15:13:24
【问题描述】:

我正在尝试异步执行一个长时间运行的 python 2.7 cgi 脚本并向浏览器返回一个完整的 html,因此它不会超时(并且无需等待脚本完成)...我在 Windows XAMPP 上运行缩写代码如下

我的问题是浏览器仍在等待整个脚本完成...我做错了什么吗?我已经阅读了其他类似的问题,他们评论说添加 stdout 和 stderr 参数可能会解决问题,但它对我来说没有...我还尝试设置 close_fds=True 并消除 stdout/sterr 参数,但这也不起作用... script.py 独立工作正常,没有任何输出...

或者您有其他推荐的方法吗?感谢您提供的任何帮助!

#!c:\program files\anaconda2\python.exe
import cgi
import subprocess
import sys

subprocess.Popen([sys.executable, 'c:/path/script.py'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

print 'Content-type:text/html\r\n\r\n'
print '<html>'
print '<head></head>'
print '<body></body>'

【问题讨论】:

  • 大声笑,我不是建议你使用 asyncio。请花点时间阅读答案
  • 谢谢!我希望有比 celery 更轻量级的东西,因为它运行的频率非常低,而且设置所有基础设施似乎有点多。您可能会推荐其他解决方案吗?
  • 在这种情况下,只需将您的数据放入缓存或 redis 甚至数据库(数据库非常不适合频繁的任务)并让 cron 作业处理它
  • Celery 也不再支持 Windows:docs.celeryproject.org/en/latest/faq.html。除了 Celery 还有其他选择吗?还是我只使用 schtasks?

标签: python asynchronous cgi


【解决方案1】:

Popen 有一些标志可以将进程与父进程分离...这允许 cgi “完成”,即使子进程仍在运行。

kwargs = {}
CREATE_NEW_PROCESS_GROUP = 0x00000200  # note: could get it from subprocess
DETACHED_PROCESS = 0x00000008          # 0x8 | 0x200 == 0x208
kwargs.update(creationflags=DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP)  
subprocess.Popen([sys.executable, 'c:/path/script.py'], close_fds=True, **kwargs)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-31
    • 1970-01-01
    • 1970-01-01
    • 2010-10-10
    • 1970-01-01
    • 1970-01-01
    • 2014-09-02
    • 1970-01-01
    相关资源
    最近更新 更多