pythonfastapiargparseuvicorn

Running Uvicorn on Mac command line results in error uvicorn: error: unrecognized arguments


When I run my FastAPI app with the Uvicorn command, the command line args are not recognized:

(env) mydir$ uvicorn main:app --port 8000 --host 0.0.0.0 --reload
...
uvicorn: error: unrecognized arguments: main:app --port 8000 --host 0.0.0.0 --reload
...

I'm making sure I'm using the uvicorn in my venv by confirming with which uvicorn.

Running uvicorn 0.34.2 with CPython 3.11.2 on Darwin.

What I tried, same result

Uninstalling and reinstalling the entire venv.

Uninstalling and reinstalling only uvicorn.

Using Uvicorn with command line args:

(env) mydir$ uvicorn main:app --port 8000 --host 0.0.0.0 --reload
INFO:     Will watch for changes in these directories: ['/Users/XXX/Documents/mydir']
INFO:     Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit)
INFO:     Started reloader process [7067] using StatReload
usage: uvicorn [-h] [--logs-dir LOGS_DIR]
uvicorn: error: unrecognized arguments: main:app --port 8000 --host 0.0.0.0 --reload

Using Python module:

(env) mydir$ python -m uvicorn main:app --port 8000 --host 0.0.0.0 --reload
INFO:     Will watch for changes in these directories: ['/Users/XXX/Documents/mydir']
INFO:     Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit)
INFO:     Started reloader process [6489] using StatReload
usage: __main__.py [-h] [--logs-dir LOGS_DIR]
__main__.py: error: unrecognized arguments: main:app --port 8000 --host 0.0.0.0 --reload

Using Uvicorn without args:

(env) mydir$ uvicorn main:app 
usage: uvicorn [-h] [--logs-dir LOGS_DIR]
uvicorn: error: unrecognized arguments: main:app
(env) mydir$ 

What I tried that works

Running Python main directly. But has no auto-reload option.

python3 -m main

Hardcoding in the main.py the args from command line. But I don't want to retain these settings for production.

if __name__ == "__main__":
    uvicorn.run(
        "main:app",
        host="0.0.0.0",
        port=8000,
        reload=True,
    )

Solution

  • Found the issue after scrolling to the top of my main.py....

    I'm using ArgParse which seems to be conflicting when passing in args on terminal.

    I'm going to just create my own argParse args and pass into the uvicorn code in main.py like so:

    parser: argparse.ArgumentParser = argparse.ArgumentParser()
    parser.add_argument(
        "--reload",
        type=bool,
        default=False,
        help="Reload the server on code changes.",
    )
    args: argparse.Namespace = parser.parse_args()
    
    if __name__ == "__main__":
        uvicorn.run(
            "main:app",
            host="0.0.0.0",
            port=8000,
            reload=args.reload,
        )