python 子进程正在覆盖用于标准输出的文件 - 我需要将它附加到文件(Windows) [英] python subprocess is overwriting file used for stdout - I need it to append to the file (windows)
问题描述
我想将 subprocess.call()
的 STDOUT
附加到现有文件中.我下面的代码覆盖了文件 -
I want to append the STDOUT
of subprocess.call()
to an existing file. My code below overwrites the file -
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()
中寻找与>>>
等效的内容.试图找到它让我发疯..
I'm looking for the equivalent of >>
in subprocess.call()
or subprocess.Popen()
. It's driving me crazy trying to find it..
更新:
按照到目前为止的答案,我已将代码更新为
Following the answers so far I've updated my code to
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 中从命令行运行此代码 -
I'm running this code from the command line in windows -
C:\users\aidan>test_subprocess.py
这会将文本添加到日志文件中.当我再次运行脚本时,没有添加任何新内容.它似乎仍在覆盖文件..
This adds the text to the log file. When I run the script again, nothing new is added. It still seems to be overwriting the file..
推荐答案
改用 'a' 追加模式:
Use the 'a' append mode instead:
log_file = open(log_file_path, 'a+')
如果你仍然看到以前的内容被覆盖了,也许 Windows 需要你明确地寻找到文件的末尾;以 'r+' 或 'w' 格式打开并查找到文件末尾:
If you still see previous content overwritten, perhaps Windows needs you to explicitly seek to the end of the file; open as 'r+' or 'w' and seek to the end of the file:
import os
log_file = open(log_file_path, 'r+')
log_file.seek(0, os.SEEK_END)
这篇关于python 子进程正在覆盖用于标准输出的文件 - 我需要将它附加到文件(Windows)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!