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

huangapple go评论67阅读模式
英文:

Not able to redirect container logs to file using subprocess.run

问题

我有一个Python脚本来启动一些容器,等待它们执行完成,然后启动另外一些容器。我想获取容器的日志,这个Bash命令适用于我:

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

然而,当我尝试将它添加到我的Python脚本中使用subprocess.run时,它不会创建一个新文件。

subprocess.run(
     [
         "docker",
         "logs",
         "-f",
         "container-name",
         "&>>",
         "tmp.log",
         "&"
     ],
     cwd=os.getcwd(),
     shell=False,
     stdout=subprocess.DEVNULL,
 )
英文:

I have a python script to start some containers, wait for them to finish execution and then start a few others. I wanted to get the container logs and this bash command worked for me:

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

However when I try to add it to my python script using `subprocess.run like below, it doesn't create a new file.

subprocess.run(
     [
         "docker",
         "logs",
         "-f",
         "container-name",
         "&>",
         "tmp.log",
         "&"
     ],
     cwd=os.getcwd(),
     shell=False,
     stdout=subprocess.DEVNULL,
 )

答案1

得分: 1

你正在使用shell重定向 (&>&),这些在subprocess.run()中因为shell=False而无法识别。

虽然将shell=True可能是解决此问题的方法,但由于涉及潜在的安全风险,应谨慎使用(参见:subprocess中'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,
    )
英文:

You are using shell redirection (&> and &) which are not recognized by subprocess.run() due to setting shell=False.

Although setting shell=True could be a solution to resolve this issue, it should be used with caution due to the potential security risks involved (See: Actual meaning of 'shell=True' in subprocess).

A safer approach would be to just create and/or open the file and redirect the output to it:

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,
    )

huangapple
  • 本文由 发表于 2023年3月3日 17:45:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/75625466.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定