简体   繁体   English

如何使用 dockerfile 在 python 脚本中设置环境变量?

[英]How do I set environment variables in a python script using a dockerfile?

I'm trying to run a simple hello world program from a docker container.我正在尝试从 docker 容器运行一个简单的 hello world 程序。 What I want to do is display a custom message that I pass to the environment variable.我想要做的是显示我传递给环境变量的自定义消息。 If nothing is passed to the environment variable than the program should just display a default message of "Hello World.".如果没有将任何内容传递给环境变量,那么程序应该只显示一条默认消息“Hello World.”。 I've already created an environment variable in my dockerfile and I'm trying to override that variable in my environment variable file using the --env-file flag, However.我已经在我的 dockerfile 中创建了一个环境变量,我正在尝试使用 --env-file 标志在我的环境变量文件中覆盖该变量,但是。 I'm not sure what the correct syntax would be for setting the environment variable since I'm getting "invalid syntax".我不确定设置环境变量的正确语法是什么,因为我得到“无效的语法”。

Below are my files:以下是我的文件:

Dockerfile Dockerfile

FROM python:3
ADD main.py /
ENV MESSAGE "Hello World!"
CMD ["python3", "./main.py"]

env_file env_file

MESSAGE="Goodbye World!"

main.py主文件

# simple hello world program
print($MESSAGE)

This is how I'm building and running my container这就是我构建和运行容器的方式

docker build -t example -f Dockerfile .
docker run --env-file=env_file --rm --name example example

Change your main.py to:将您的main.py更改为:

import os

print(os.environ['MESSAGE'])

Accessing environment variables using $ in Python is not supported and is not valid Python syntax.不支持在 Python 中使用$访问环境变量,这也是无效的 Python 语法。

Note that this will raise an exception if there's no such environment variable, so you may want to use os.environ.get('MESSAGE') and check for None or do some error handling in that case.请注意,如果没有这样的环境变量,这将引发异常,因此您可能需要使用os.environ.get('MESSAGE')并检查None或在这种情况下进行一些错误处理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM