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

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

我正在尝试 运行 下面的简单代码段

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

我可以理解 PORT 是 s 字符串,但我需要转换为 int。为什么我收到错误

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

您没有名为 PORT 的环境变量。

os.getenv('PORT') -> returns None -> 当您尝试将其转换为 int

时抛出异常

在 运行 您的脚本之前,通过以下方式在您的终端中创建环境变量:

export PORT=1234

或者,您可以提供一个默认端口,以防它未定义为您机器上的环境变量:

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

感谢您发表评论并提供解决方案。实际上,我的本地系统中没有分配端口,这就是原因。苏都说得对。