Search code examples
pythonlinuxfastapi

how to run fastapi with a specific python interpreter on linux


I'm (trying to) run FastAPI on a linux container that has multiple versions of python. When I do fastapi run, I want fastapi to run using a particular python interpreter. (e.g. I want it to use the python at /usr/bin/python3.12 instead of at /usr/bin/python3.9.

How do I do that?


Solution

  • The fastapi 'binary' is only present in the python environment in which it is installed. You decide which python you are using by determining which fastapi 'binary' you are calling. You should be able to determine the one you are actually using with which fastapi in most cases. If you want to know where the fastapi of your preferred environment is, one way to do it is to run that particular python, and check sys.path(). That should tell you where your site packages folder is, and you can look there for the fastapi executable. While I haven't checked, it'll probably be in the bin directory close to the site packages folder, probably one or two levels up.

    If you have fastapi in multiple environments, you can call fastapi with the full path to the fastapi binary of the particular environment you want to use, or adjust your $PATH of that terminal to ensure the correct one is selected.

    If you're planning on maintaining multiple python versions and environments, though, I strongly suggest you look into using pyenv + virtualenv, which will help manage these things for you.

    When you're operating in a container, however, there is something to be said about NOT having multiple python versions living side by side, so consider if you really need those. The whole point is to have a well specified environment with exactly the things you need at exactly the right versions and not much more.