pythonrunpy

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


I'm attempting to start a discord.py bot that is in a different py file and can successfully get the bot to start, however I'm not sure how to exit/stop the script once i've started it. ctrl+c works if I'm in in the shell however I have a pyqt script running the module and i'd like to keep the launcher up without closing it out as well.

@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

Solution

  • It would be better to refactor your hangoutcore to only do important things when you invoke something in it, e.g.

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

    and then you can just

    import hangoutcore
    

    whenever, and then call

    hangoutcore.run()
    

    when you want to do the main thing.