从 Twisted 调用 Python 代码

Calling Python code from Twisted

首先,我应该说这可能更多是一个设计问题,而不是代码本身。

我有一个包含一个服务器和多个客户端的网络(用 Twisted 编写,因为我需要这些异步非阻塞特性),这样的服务器-客户端组合只是接收-发送消息。

但是,在某些时候,我希望一个客户端在收到特定消息时 运行 一个 python 文件。该客户端应该继续监听并与服务器通信,而且,如果需要,我应该能够停止该文件,所以我的第一个想法是为该 python 文件启动一个线程并忘记它。

最后它应该是这样的:服务器向 ClientA 发送消息,ClientA 及其 dataReceived 函数解释消息并决定 运行 那个 python 文件(我不知道需要多长时间,可能包含阻塞调用),当 python 文件完成时 运行ning 应该将结果发送给 ClientB。

所以,问题是:

无论如何,我非常感谢任何类型的建议,因为 python 和 twisted 都不是我的专长,所有这些想法可能都不是最好的。

谢谢!

初读时,我以为你是在暗示 twisted 不是 python。如果您有这种想法,请记住以下几点:

Twisted is a python framework, I.E. it is python. Specifically it's about getting the most out of a single process/thread/core by allowing the programmer to hand-tune the scheduling/order-of-ops in their own code (which is nearly the opposite of the typical use of threads).

While you can interact with threads in twisted, its quite tricky to do without ruining the efficiency of twisted. (for longer description of threads vs events see SO: )

如果你真的想从扭曲的 python 中生成新的 python(即在不同的核心上完成这项工作 运行),那么我会考虑生成它作为一个过程关闭,请参阅此 SO 中 Glyph 的回答: 好的图书馆可以完成这项工作。

进程提供适当的分离,让您扭曲的应用程序 运行 不会明显变慢,您应该会发现您的所有 starting/stoping/pausing/killing 需求都会得到满足。

具体回答您的问题:

Would it be starting a thread a good idea for that python file in ClientA?

我会说“不”,这通常不是一个好主意,在您的具体情况下,您应该考虑使用流程。

Can I have another reactor loop inside that python file?

严格来说“不,你不能拥有多个反应器”——但 twisted 可以同时管理成百上千个单独的任务,所有任务都在同一个反应器中,将满足你的需要。 IE。 运行 所有不同的异步任务都在一个反应​​器中,这就是 twisted 的目的。

顺便说一句,我总是推荐以下关于 twisted 的教程:krondo Twisted 简介http://krondo.com/?page_id=1327它很长,但是如果你通过它,这种工作就会变得非常清楚。

祝一切顺利!