首页 > 解决方案 > TypeError: int() 参数必须是字符串、类似字节的对象或数字,而不是使用 Python 3.7 时的“NoneType”

问题描述

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

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

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

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

标签: pythonpython-3.xenvironment-variablesgetenv

解决方案


您没有名为PORT.

os.getenv('PORT')-> 返回None-> 当您尝试将其转换为 int 时抛出异常

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

export PORT=1234

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

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

推荐阅读