简体   繁体   中英

Running python subprocess with shell=True with parameters

I am trying to "port" the following linux shell command (that works fine):

docker run --name mycontainer myimage --detach -p 389:389 -p 689:689

to python with:

container_name="mycontainer"
image_name="myimage"
subprocess.check_call('docker run --name $container_name $image_name --detach -p 389:389 -p 689:689', shell=True)

But I get the error:

"docker run" requires at least 1 argument.
See 'docker run --help'.

Usage:  docker run [OPTIONS] IMAGE [COMMAND] [ARG...]

Run a command in a new container
Traceback (most recent call last):
  File "myscript.py", line 110, in <module>
    subprocess.check_call('docker run --name $container_name $image_name --detach -p 389:389 -p 689:689', shell=True)
  File "/usr/lib/python2.7/subprocess.py", line 186, in check_call
    raise CalledProcessError(retcode, cmd)
subprocess.CalledProcessError: Command 'docker run --name $container_name --detach $image_name -p 389:389 -p 689:689' returned non-zero exit status 1

So the parameters are not resolved. Is it a no-go to use parameters like this when shell=True and if so what is the closest I can get to running "pure" shell commands from python?

You cannot use $variable to evaluate variable in Python, this only works in shells. Do this instead:

subprocess.check_call('docker run --name ' + container_name + ' ' + image_name + ' --detach -p 389:389 -p 689:689', shell=True)

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