Kapil
Kapil

Reputation: 134

How to quickly kill and repoen a uvicorn porcess in same port from another process?

I have a script that runs a uvicorn process in seperate thread (and does other things as well) based on the config file. I wanted it to reload if config file is modified so I make a new script that starts the main script in the seperate process, watches for the file change and if change occurs kill the previous process and starts the new one. But I found that, after I change the config file, everything else works fine excpet the uvicorn. I also found that, if I don't use script runner script and close (with Ctrl+C) and repoen the main script manually, it works just file. Here's the structure of my program,

main.py (main scritp):

def run_uvicorn():
    uvicorn.run(...)

def main():
    # Does something
    starts_in_new_thread(run_uvicorn)
    # Does other things

script_runner.py:

from main import main
process = multiprocessing.Process(target = main)
process.start()

def file_modified_handler():
    process.kill()
    process = multiprocessing.Process(target =  main)
    process.start()

observe_file_change(handler=file_modified_handler)

Manual restart of the script works file.

Upvotes: 1

Views: 631

Answers (1)

this scheme should only be used when developing and debugging code. Uvicorn has the --reload flag for this. Try to write uvicorn.run(reload=True) and not use this Observer.

Upvotes: 1

Related Questions