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()
I’m looking for the equivalent of >> in subprocess.call() or subprocess.Popen(). It’s driving me crazy trying to find it..
UPDATE:
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()
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..
Use the ‘a’ append mode instead:
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: