#!/usr/bin/python3.2
import sys
def match_text(pattern):
line = (yield)
if pattern in line:
print(line)
x = match_text('apple')
x.next()
for line in input('>>>> '):
if x.send(line):
print(line)
x.close()
Run Code Online (Sandbox Code Playgroud)
这是一个协程,但Python3.2将其视为生成器 - 为什么?这里发生了什么?我指的是David Beazeley编写的Python Essential Reference:20.
引用相关部分:
Normally, functions operate on a single set of input arguments. However, a function can
also be written to operate as a task that processes a sequence of inputs sent to
it.This type of function is known as a coroutine and is created by using the yield
statement …Run Code Online (Sandbox Code Playgroud) 我正在尝试分析一个实例方法,所以我做了类似的事情:
import cProfile
class Test():
def __init__(self):
pass
def method(self):
cProfile.runctx("self.method_actual()", globals(), locals())
def method_actual(self):
print "Run"
if __name__ == "__main__":
Test().method()
Run Code Online (Sandbox Code Playgroud)
但是现在当我希望"method"返回由"method_actual"计算的值时出现问题.我真的不想两次调用"method_actual".
还有其他方法,可以线程安全吗?(在我的应用程序中,cProfile数据被保存到由其中一个args命名的数据文件中,因此它们不会被破坏,我可以在以后组合它们.)