使用shell=True和参数运行python子流程

使用shell=True和参数运行python子流程,python,linux,shell,Python,Linux,Shell,我正在尝试移植以下工作正常的linux shell命令: docker run --name mycontainer myimage --detach -p 389:389 -p 689:689 要使用python,请执行以下操作: container_name="mycontainer" image_name="myimage" subprocess.check_call('docker run --name $container_name $image_name --detach -p 3

我正在尝试移植以下工作正常的linux shell命令:

docker run --name mycontainer myimage --detach -p 389:389 -p 689:689
要使用python,请执行以下操作:

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)
但我得到了一个错误:

"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
因此,参数没有得到解析。当shell=True时,这样的参数是不能使用的吗?如果是,我能从python运行纯shell命令的最接近的方法是什么?

在python中不能使用$variable来计算变量,这只在shell中有效。改为这样做:

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

您正在设置名为container_name和image_name的Python变量。这些不是shell变量,shell对它们一无所知。考虑Python字符串格式化“-No.{}”。FraveCuultAlgNo.No.1在您的问题中有另一个误解:没有Linux shell命令这样的东西。Shell具有内置命令,但用于启动其他程序。这些都与Linux无关,顺便说一句,在其他系统上也是如此。在本例中,要调用的程序是docker。顺便说一下:考虑使用Python 3。