英文:
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,
)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论