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

Viewed 4506

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'
2 Answers

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)

Thanks for commenting and giving the solutions. Actually there was no port assigned in my local system and thats the reason for it. Sou both are right.

Related