Use Linux env variables in python program

376 views Asked by At

I'm trying OS env variables to be used in python code. Below is example.

Env Variable


    export DOCKER_HOST=10.0.0.5
    export PORT=1002

Python code


    import os 
    import docker 
    host = os.environ['DOCKER_HOST']
    port = os.environ['PORT']
    client = docker.APIClient(base_url='tcp://host:port')

It is supposed to inject the variables of host and port but its not working. I tried to add .format which is helpless

Error

raceback (most recent call last):
  File "./update.py", line 24, in 
    client = docker.APIClient(base_url="tcp://docker_host:docker_port")
  File "/usr/local/lib/python2.7/dist-packages/docker/api/client.py", line 109, in __init__
    base_url, IS_WINDOWS_PLATFORM, tls=bool(tls)
  File "/usr/local/lib/python2.7/dist-packages/docker/utils/utils.py", line 363, in parse_host
    "Invalid port: {0}".format(addr)
docker.errors.DockerException: Invalid port: docker_host:docker_port
1

There are 1 answers

1
Tarun Lalwani On BEST ANSWER

Your issue is below

client = docker.APIClient(base_url='tcp://host:port')

You are using host:port as literal strings. Python doesn't have string interpolation until Python 3.6. You can use one of below ways

client = docker.APIClient(base_url='tcp://' + host + ':' + port)
client = docker.APIClient(base_url='tcp://{}:{}'.format(host,port))
client = docker.APIClient(base_url='tcp://{0}:{1}'.format(host,port))
client = docker.APIClient(base_url='tcp://{host}:{port}'.format(host=host,port=port))
client = docker.APIClient(base_url='tcp://%s:%s' % (host,port))

Edit-1

Thanks to @code_onkel for pointing out the string interpolation in Python 3.6 (had not used it earlier). You can also use below if you are using Python 3.6.X

client = docker.APIClient(base_url=f'tcp://{host}:{port}')

The f before the string is important. Please refer to PEP 498 for more details