'How to write output of a subprocess.popen to a test file?

I want to store the output of a subprocess to a txt file in log format (date time output)

Below is my python code

proc = subprocess.Popen('sudo', '-S', 'sh', os.path.join(dpath, 'new_upgrade.sh'), 'rollback'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = proc.communicate(input=password_bytes)
print(out)
with open('output.txt','a') as out:
    out.write("{0} -- {1}\n".format(datetime.datetime.now().strftime("%Y-%m-%d %H:%M"),str(out)))
    out.write("{0} -- {1}\n".format(datetime.datetime.now().strftime("%Y-%m-%d %H:%M"), str(err)))

the output of the bash script gets printed in the terminal but not in output.txt file instead we get the following thing in toutput.txt

2022-02-28 12:16 -- <_io.TextIOWrapper name='output.txt' mode='a' encoding='UTF-8'>

the err gets appended in the output.text file

not sure whats... wrong Please help :)



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source