【问题标题】:Python 3: Clean exit through input-command with asyncioPython 3:使用 asyncio 通过输入命令清除退出
【发布时间】:2017-09-21 07:58:30
【问题描述】:

在执行使用 asyncio 的 Python 脚本时,我无法通过输入命令将干净退出返回到终端。

脚本做了很多事情,但也提供了一个 CLI 用于输入。 键入“完成”并按 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()

输入“完成”时在 cm_cli 中执行的代码:

def run(self):
    print("[CM_CLI] Type 'help' for available commands, 'test' to run test.")
    while True:
        print('\033[0m', end=' ')     # stop printing yellow
        params = (input('>> '))
        print('\033[1;33m', end=' ')  # start printing yellow

        params = params.split()
        if len(params) < 1:
            continue

        if  params[0] == "help":
            print("[CM_CLI] Available commands are:")
        elif  params[0] == "":
            continue
        elif  params[0] == "done":
            print("[CM_CLI] Exiting.")
            raise KeyboardInterrupt
        else:
            print("[CM_CLI] Unknown command.")

当我简单地启动脚本(称为 cerberos_manager.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 中关闭循环,但没有更接近。有什么干净的出口返回航站楼的建议吗?

【问题讨论】:

    标签: python exit


    【解决方案1】:

    看看这个例子:

    import asyncio
    
    def hello_world(loop):
        print('Hello World')
        loop.stop()
    
    loop = asyncio.get_event_loop()
    
    # Schedule a call to hello_world()
    loop.call_soon(hello_world, loop)
    
    # Blocking call interrupted by loop.stop()
    loop.run_forever()
    loop.close()
    

    您应该在回调函数 (run()) 中捕获异常并在其中触发 loop.stop()。之后在主模块中使用loop.close()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-28
      • 1970-01-01
      • 1970-01-01
      • 2015-01-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多