有没有办法停止以 runpy.run_module('module') 启动的模块?

Is there a way to stop a module that was started with runpy.run_module('module')?

我正在尝试启动一个位于不同 py 文件中的 discord.py 机器人,并且可以成功启动该机器人,但是我不确定如何 exit/stop 脚本一次我已经开始了。 如果我在 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

最好将 hangoutcore 重构为仅在调用其中的某些内容时才做重要的事情,例如

import discordpy, eris, apple, fnord

# ... lots of bot logic

def run():
   ...

然后你就可以

import hangoutcore

任何时候,然后打电话

hangoutcore.run()

当你想做主要的事情时。