首先,我想提到我对Python并不特别熟悉。最近我被迫熟悉一段代码样本,让我大吃一惊,但我无法“翻译”它。我查看了各种文档和文章,也没有帮助:
- “yield”关键字是什么? - 解释Python yield关键字 - yield语句 - yield表达式 这是涉及的函数的缩短版本:
- “yield”关键字是什么? - 解释Python yield关键字 - yield语句 - yield表达式 这是涉及的函数的缩短版本:
@coroutine
def processMessage(receiver):
global userID
#...
while True:
msg = (yield)
try:
#...
except Exception as err:
#...
我无法理解它的作用,因此无法“步入”代码。我的问题是,“这个函数是做什么的?”和“这个函数要遵循哪些步骤?”
让我摸不着头脑的是msg = (yield)
这一行。我不知道它想要实现什么。直觉告诉我它只是在接收新消息,但我不明白为什么。如果有人知道,并且如果我提供了足够的信息,我会非常感激他们能够给出一个解释。
try
语句块:
if msg['event'] == 'message' and 'text' in msg and msg['peer'] is not None:
if msg['sender']['username'] == username:
userID = msg['receiver']['peer_id']
config.read(fullpath + '/cfg/' + str(userID) + '.cfg')
if config.has_section(str(userID)):
log('Config found')
readConfig()
log('Config loaded')
else:
log('Config not found')
writeConfig()
log('New config created')
if 'username' in msg['sender']:
parse_text(msg['text'], msg['sender']['username'], msg['id'])
附言:receiver
是一个套接字接收器。
yield
的地方。这是一个与telegram-cli交互的脚本。 - Pyromonkyield
就是这样工作的。这是一个协程,在旧的、非异步的意义上。不过问题要问什么还不清楚。 - user2357112