python 子进程正在覆盖用于 stdout 的文件 - 我需要它附加到文件 (windows)

标签 python windows file subprocess stdout

我想将 subprocess.call()STDOUT 附加到现有文件。我下面的代码覆盖了文件 -

log_file = open(log_file_path, 'r+')
cmd = r'echo "some info for the log file"'
subprocess.call(cmd, shell=True, stdout=log_file, stderr=STDOUT)
log_file.close()

我在 subprocess.call()subprocess.Popen() 中寻找 >>> 的等价物。试图找到它让我发疯..

更新:

根据到目前为止的答案,我已将代码更新为

import subprocess

log_file = open('test_log_file.log', 'a+')
cmd = r'echo "some info for the log file\n"'
subprocess.call(cmd, shell=True, stdout=log_file, stderr=subprocess.STDOUT)
log_file.close()

我在 Windows 的命令行中运行这段代码 -

C:\users\aidan>test_subprocess.py

这会将文本添加到日志文件中。当我再次运行脚本时,没有添加任何新内容。它似乎仍在覆盖文件..

最佳答案

改为使用 'a' 附加模式:

log_file = open(log_file_path, 'a+')

如果您仍然看到以前的内容被覆盖,可能是 Windows 需要您明确地查找到文件末尾;以 'r+' 或 'w' 打开并查找文件末尾:

import os

log_file = open(log_file_path, 'r+')
log_file.seek(0, os.SEEK_END)

关于python 子进程正在覆盖用于 stdout 的文件 - 我需要它附加到文件 (windows),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10722752/

相关文章:

c++ - 服务和用户模式进程之间的共享全局事件不起作用

java - Java中如何删除Vector中的多个元素?

java - 使用默认程序运行文件并等待编辑结束

python - 在 pandas 和 numpy 中聚合 lambda 函数

python - BeautifulSoup:findAll 找不到标签

windows - 构建 Sqlite 模块时出现 cl.exe 错误 D8003(缺少源文件名)

python - 将 Python 编译为 native 代码?

c++ - FSCTL_GET_RETRIEVAL_POINTERS 对小文件失败

python - 如何在python中将字符串转换为日期时间

Python-3 : Why this following code returns none in print statement?