Я читал о перенаправлении распечаток в файл журнала , однако я не понял, почему принятый ответ не сработал, как ожидалось.
Оригинальный код был на Python2, я немного его изменил, так как работаю над Python3.
Принятый ответ :
https://stackoverflow.com/a/2513511/9013730
import os
def test():
cmd = 'ver'
print("1. Running command:",cmd) # message.log only, NOT in console
os.system(cmd) # This appear in console only, but not in message.log
print('3. Done') # message.log only, NOT in console
import sys
old_stdout = sys.stdout
log_file = open("message.log","w")
sys.stdout = log_file
print("This will be written to message.log") # message.log only, NOT in console
test()
sys.stdout = old_stdout
log_file.close()
Консольный вывод
Как видите, только os.system(cmd)
распечатано в консоли, а я не увидел его в сообщении message.log.
Microsoft Windows
message.log Вывод
Когда я проверял вывод message.log, os.system(cmd)
там не было.
This will be written to message.log
1. Running command: ver
3. Done
Можно ли создать одинаковый (точный) вывод как в консоли, так и в файле message.log?
Требуемый вывод как в консоли, так и в message.log
This will be written to message.log
1. Running command: ver
Microsoft Windows
3. Done