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

2

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'
Clerc answered 9/5, 2020 at 13:31 Comment(2)
It is highly likely that, you forgot to export PORT. Hence there's no PORT in the env, hence it returns NoneDusen
Is there a reasonable default port for this app? Then os.getenv('PORT', default_port) would work.Kolb
R
9

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)
Rowboat answered 9/5, 2020 at 13:34 Comment(0)
C
0

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.

Clerc answered 9/5, 2020 at 17:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.