无法使用 subprocess.run 将容器日志重定向到文件

问题描述 投票:0回答:1

我有一个 python 脚本来启动一些容器,等待它们完成执行然后启动其他几个。我想获取容器日志,这个 bash 命令对我有用:

docker logs -f container-name &> tmp.log &

但是,当我尝试使用如下所示的 `subprocess.run 将它添加到我的 python 脚本时,它不会创建新文件。

subprocess.run(
     [
         "docker",
         "logs",
         "-f",
         "container-name",
         "&>",
         "tmp.log",
         "&"
     ],
     cwd=os.getcwd(),
     shell=False,
     stdout=subprocess.DEVNULL,
 )
python docker
1个回答
1
投票

您正在使用 shell 重定向(

&>
&
),由于设置
subprocess.run()
而无法被
shell=False
识别。

虽然设置

shell=True
可能是解决此问题的解决方案,但由于涉及潜在的安全风险,应谨慎使用(参见:子进程中“shell=True”的实际含义)。

更安全的方法是只创建和/或打开文件并将输出重定向到它:

import subprocess
import os

log_file = "tmp.log"
if not os.path.exists(log_file):
    open(log_file, "w").close()

with open(log_file, "a") as outfile:
    subprocess.run(
        ["docker", "logs", "-f", "container-name"],
        cwd=os.getcwd(),
        shell=False,
        stdout=outfile,
    )
© www.soinside.com 2019 - 2024. All rights reserved.