pythonpython-3.xenvironment-variablesgetenv

TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType' while using Python 3.7


I am trying to run the simple below snippet

port = int(os.getenv('PORT'))
print("Starting app on port %d" % port)

I can understand the PORT is s string but I need to cast to a int. Why I am getting the error

TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType'

Solution

  • You don't have an environment variable called PORT.

    os.getenv('PORT') -> returns None -> throws exception when you try to convert it to int

    Before running your script, create in your terminal the environment variable by:

    export PORT=1234
    

    Or, you can provide a default port in case it's not defined as an environment variable on your machine:

    DEFAULT_PORT = 1234
    port = int(os.getenv('PORT',DEFAULT_PORT))
    print("Starting app on port %d" % port)