【问题标题】:Is there a way to stop a module that was started with runpy.run_module('module')?有没有办法停止以 runpy.run_module('module') 启动的模块?
【发布时间】:2021-10-25 22:20:00
【问题描述】:

我正在尝试启动一个位于不同 py 文件中的 discord.py 机器人,并且可以成功地启动该机器人,但是我不知道一旦我启动它后如何退出/停止脚本。 如果我在 shell 中,ctrl+c 可以工作,但是我有一个运行模块的 pyqt 脚本,我想在不关闭它的情况下保持启动器。

@click.group(invoke_without_command=True, options_metavar='[options]')
@click.pass_context
@click.option('-c', '--cli', help='launch hangoutcore without a gui.', is_flag=True)
def main(ctx, cli):
    """Launches the bot."""
    if ctx.invoked_subcommand is None:
        # since cli is a bool we can pass it as an environment variable so it can be accessed by any code running in this session.
        os.environ["bot_CLI"] = str(cli)
        print(os.environ["bot_CLI"])
        if not cli:
            try:
                qasync.run(botLauncher())
            except asyncio.exceptions.CancelledError as e:
                print(e)
        else:
            try:
                hangoutcore = runpy.run_module('hangoutcore')
                print(hangoutcore)

            except SystemExit as exception:
                exitcode = exception.code
            else:
                exitcode = 0

【问题讨论】:

    标签: python runpy


    【解决方案1】:

    最好重构你的hangoutcore,只在你调用其中的某些东西时才做重要的事情,例如

    import discordpy, eris, apple, fnord
    
    # ... lots of bot logic
    
    def run():
       ...
    
    

    然后你就可以了

    import hangoutcore
    

    无论何时,然后调用

    hangoutcore.run()
    

    当你想做主要的事情时。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-25
      • 2021-04-16
      • 1970-01-01
      • 1970-01-01
      • 2019-03-01
      • 1970-01-01
      相关资源
      最近更新 更多