簡體   English   中英

將$ PWD與subprocess.Popen()結合使用會導致Docker錯誤,可從shell運行

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

我想使用子進程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()

來自終端的命令完美運行時,將返回:

(b'',b'docker:來自守護程序的錯誤響應:創建$ PWD:“ $ PWD”包含本地卷名的無效字符,只有“ [a-zA-Z0-9] [a-zA-Z0-9_ .-]“。\\ n請參閱\\'docker run --help \\'。\\ n')

"$PWD"是shell擴展。 如果沒有外殼(如shell=False ),則不會擴展。

'%s:/data' % os.getcwd()是Python表達式,其結果與shell中的"$PWD:/data"相同。 從而:

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)

在這種情況下,請不要使用shlex.split() ,這一點很重要:如果這樣做了,並且位於名稱中帶有空格的目錄中,則該目錄的每個段都將成為一個單獨的參數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM