python - TypeError : int() argument must be a string, 类似字节的对象或数字,而不是使用 Python 3.7 时的 'NoneType'

标签 python python-3.x environment-variables getenv

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

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)

关于python - TypeError : int() argument must be a string, 类似字节的对象或数字,而不是使用 Python 3.7 时的 'NoneType',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61697523/

相关文章:

scope - Gitlab CI $CI_ENVIRONMENT_SLUG 为空

ruby-on-rails - .env 没有被加载到 Rails 的测试环境中,使用 rspec

python - getthreshold() 除了垃圾回收之外的用途

python - 自定义夹层(使用不同的主题)

python - 从嵌套列表的字典理解返回字典

python - 通过 lambda 定义的函数列表的意外行为

python-3.x - python 3.5+ 中 pycurl 的异步替代方案

qt - Qt Creator的工程文件(.pro)中如何修改PATH变量

python - 如何使用 Python 将使用 Google App Engine Launcher 在本地主机上制作的记录导入到在线 App Engine 数据存储区?

python - 你能简化 Python 中不等于或等于的链式比较吗?