简体   繁体   English

将$ PWD与subprocess.Popen()结合使用会导致Docker错误,可从shell运行

[英]Using $PWD with subprocess.Popen() results in a Docker error, works from shell

I want to run a docker command from python using the subprocess Popen: 我想使用子进程Popen从python运行docker命令:

proc = subprocess.Popen(
    shlex.split(r'docker run -v $PWD:/data blang/latex pdflatex main.tex'),
    cwd=temp_dir, shell=False, stdout=subprocess.PIPE, 
stdin=subprocess.PIPE, stderr=subprocess.PIPE)
proc.communicate()

While the command from the terminal works perfect, this returns: 来自终端的命令完美运行时,将返回:

(b'', b'docker: Error response from daemon: create $PWD: "$PWD" includes invalid characters for a local volume name, only "[a-zA-Z0-9][a-zA-Z0-9_.-]" are allowed.\\nSee \\'docker run --help\\'.\\n') (b'',b'docker:来自守护程序的错误响应:创建$ PWD:“ $ PWD”包含本地卷名的无效字符,只有“ [a-zA-Z0-9] [a-zA-Z0-9_ .-]“。\\ n请参阅\\'docker run --help \\'。\\ n')

"$PWD" is a shell expansion. "$PWD"是shell扩展。 If you don't have a shell (as with shell=False ), it doesn't get expanded. 如果没有外壳(如shell=False ),则不会扩展。

'%s:/data' % os.getcwd() is a Python expression which will have the same result as "$PWD:/data" in shell. '%s:/data' % os.getcwd()是Python表达式,其结果与shell中的"$PWD:/data"相同。 Thus: 从而:

import os, subprocess
proc = subprocess.Popen(
    ['docker', 'run',
     '-v', '%s:/data' % os.getcwd(),
     'blang/latex', 'pdflatex', 'main.tex'],
    cwd=temp_dir, shell=False, stdout=subprocess.PIPE, 
    stdin=subprocess.PIPE, stderr=subprocess.PIPE)

It's important not to use shlex.split() in this case: If you did, and were in a directory with spaces in its name, each segment of that directory would become a separate argument. 在这种情况下,请不要使用shlex.split() ,这一点很重要:如果这样做了,并且位于名称中带有空格的目录中,则该目录的每个段都将成为一个单独的参数。

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

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