从运行“deferToThread”的函数获取结果
我最近开始研究twisted,不太熟悉它的功能。我有一个与“deferToThread”方法相关的问题...我的代码在这里使用这个方法
from twisted.internet.threads import deferToThread
from twisted.internet import reactor
results=[]
class Tool(object):
def exectool(self,tool):
# print "Test Class Exec tool running..........."
exec tool
return
def getResult(self,tool):
return results.append(deferToThread(self.exectool, tool))
to=Tool()
to.getResult(tools)
f=open(temp).read()
obj_tool=compile(f, 'a_filename', 'exec')
[ at 0x8ce7020, file "a_filename", line 1>, at 0x8cd4e30 ,文件“a_filename”,第 2 行>]
我在 getResults() 方法中一一传递工具,它成功执行了 &打印文件对象中编写的脚本的结果。 我必须将工具执行的结果存储在某个变量中,以便我可以将其保存在数据库中。当我调用 re=to.getResult(tools) 并打印“re”时,如何实现此原因,它不会打印任何内容。 我必须将其结果存储在数据库中吗?我能做点什么吗?
提前致谢
I have recently started working on twisted not much familiar with its functions.I have a problem related to "deferToThread" method...my code is here to use this method
from twisted.internet.threads import deferToThread
from twisted.internet import reactor
results=[]
class Tool(object):
def exectool(self,tool):
# print "Test Class Exec tool running..........."
exec tool
return
def getResult(self,tool):
return results.append(deferToThread(self.exectool, tool))
to=Tool()
to.getResult(tools)
f=open(temp).read()
obj_tool=compile(f, 'a_filename', 'exec')
[ at 0x8ce7020, file "a_filename", line 1>, at 0x8cd4e30, file "a_filename", line 2>]
I am passing tools one by one in getResults() method it executs successfully & prints the results what script written in the file objects.
I have to store the result of tools executing in some variable so that I can save it in database.How to achieve this cause when i call re=to.getResult(tools) and print "re" it prints none.
I HAVE TO STORE ITS RESULTS IN DATABASE? IS THERE SOMETHING I CAN DO?
thanx in advance
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这里有两个问题。
首先,如果您从未启动反应器,则 deferToThread 将无法工作。希望这个代码片段实际上是从运行 Reactor 的更大的 Twisted 应用程序中提取的,这样这对您来说就不会成为实际问题。但除非您添加一个
reactor.run()
调用,否则您不应期望此代码片段能够正常工作。其次,deferToThread 返回一个 Deferred。
Deferred
会根据您传入的可调用结果触发。这在 API 文档。 Twisted 中的许多 API 都会返回Deferred
,因此您可能需要阅读 涵盖它们的文档。一旦您了解了它们的工作原理以及如何使用它们,很多事情都会变得容易一些。There are two problems here.
First,
deferToThread
will not work if you never start the reactor. Hopefully this code snippet was actually extracted from a larger Twisted-using application where the reactor is running, so that won't be an actual problem for you. But you shouldn't expect this snippet to work unless you add areactor.run()
call to it.Second,
deferToThread
returns aDeferred
. TheDeferred
fires with the result of the callable you passed in. This is covered in the API documentation. Many APIs in Twisted return aDeferred
, so you might want to read the documentation covering them. Once you understand how they work and how to use them, lots of things should be quite a bit easier.