在执行使用asyncio的Python脚本时,我很难通过输入命令将干净的出口返回到终端。在
这个脚本做了很多事情,但也提供了一个CLI作为输入。 键入“done”并按enter应该会关闭整个脚本。 我试着用下面的代码来做,但似乎不起作用。在
脚本代码:
try:
cm_cli = CmCli(iot_net, loop, logger)
cm_cli.start()
loop.run_forever()
except KeyboardInterrupt:
print("[CerberOS_Manager] Shutting everything down.")
for task in asyncio.Task.all_tasks():
task.close()
loop.stop()
sys.exit()
键入“done”时在cm_cli中执行的代码:
^{pr2}$当我启动脚本(称为cerberos)时会发生什么_经理.py)然后键入done:
pi@raspberrypi:~/git/yggdrasil_managers/cerberos_mgmt $ sudo python3 cerberos_manager.py
[CM_CLI] Type 'help' for available commands, 'test' to run test.
>> done
[CM_CLI] Exiting.
Exception in thread Thread-11:
Traceback (most recent call last):
File "/usr/local/lib/python3.6/threading.py", line 916, in _bootstrap_inner
self.run()
File "/home/pi/git/yggdrasil_managers/cerberos_mgmt/cm_cli.py", line 57, in run
raise KeyboardInterrupt
KeyboardInterrupt
因此,它引发中断,但无法到达另一部分的打印输出。我尝试过在cm峎cli中关闭循环,但没有更进一步。有没有什么建议可以让你干净地回到候机楼?在
看看这个例子:
您应该在回调函数(
run()
)中捕获异常并在其中触发loop.stop()
。然后在主模块中使用loop.close()
。在相关问题 更多 >
编程相关推荐