简体   繁体   中英

How to pass a variable inside quotes on Python?

I'm using the docker-py SDK and I need to pass some variables inside the containers.run .

What I need:

MYDIR = '/variable/dir'
MYURL = 'https://example.com'
client = docker.from_env()
container = client.containers.run(image="alpine:latest", name="container", user="1000", volumes=['MYDIR:/tmp'], command=["/bin/sh", "echo MYURL"])

What I get: One error after other.

As you can see I need to put the variables inside the quotes of volumes and command .

I tried various combinations without any luck: with quotes, without them, using str concatenation, etc...

Any idea how to solve this?

Thanks in advance.

You want to combine a string from a variable with another string. There are many ways to do this in Python. The latest way is called f-strings, which are very close to your "pass a variable inside quotes" in terms of syntax (although that's an oversimplification of what's actually happening).

For example:

container = client.containers.run(image="alpine:latest", 
                name="container", user="1000", volumes=[f'{MYDIR}/tmp'],
                command=["/bin/sh", f"echo {MYURL}"])

Note that each string into which we have inserted a variable 1) begins with an f before the opening quote marks (hence "f-strings"—the f is for formatted) and 2) places the variable in {...} brackets. You can actually use any expression inside the brackets, not just a single variable name.

The key to solving your problem is understanding why this error occurred:

Bad Request ("create MYDIR/resources: "MYDIR/resources" includes invalid characters for a local volume name, only "[a-zA-Z0-9][a-zA-Z0-9_.-]" are allowed. If you intended to pass a host directory, use absolute path")

No where in this error actually requires you to "put the variables inside the quotes of volumes and command". What you actually need to do is to fix the path string (which you call 'quotes') to contain a valid volume name as specified by the regular expression in your error message.

Because you censored MYDIR, I cannot provide you further assistance as to why you might be getting the invalid volume name error. Perhaps you might have a path with unescaped spaces , etc...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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