python - 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'
解决方案
您没有名为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)
推荐阅读
- vba - 如何在 vba 中重置定期会议?
- arrays - 按建议的键对 Swift 数组进行排序
- javascript - 如何将两个数组数据合并成一个数组?
- android - Android NN中关于conv2D的问题:输出形状限制
- vhdl - 我如何用状态自动表示所有卷曲?
- data-structures - 是否可以使用 4 个队列实现 n 个堆栈?
- amazon-web-services - 如果我使用 AWS CLI S3 'mv' 命令,那背后是什么类型的请求?
- npm - 如何在 npm 中安装最新的 SNAPSHOT 版本?
- java - 替代主键列 varchar(max)
- azure - 为什么我们只能将基本的动态 PIP 分配给 Azure 上的虚拟网络网关?