![](/img/trans.png)
[英]How to get 'print()', 'os.system()' and 'subprocess.run()' output to be displayed in both console and log file?
[英]How to get both stdin and stdout output to be displayed in both console and log file?
以下代碼將輸出輸出到控制台以及log.txt
文件。
碼
import sys
class multifile(object):
def __init__(self, files):
self._files = files
def __getattr__(self, attr, *args):
return self._wrap(attr, *args)
def _wrap(self, attr, *args):
def g(*a, **kw):
for f in self._files:
res = getattr(f, attr, *args)(*a, **kw)
return res
return g
sys.stdout = multifile([ sys.stdout, open('log.txt', 'w') ])
name = input('What is your name: ')
print('Your name is',name)
控制台輸出
C:\>python script.py
What is your name: ABC
Your name is ABC
log.txt
文件
What is your name: Your name is ABC
不幸的是,輸入的ABC\\n
僅顯示在控制台上,而不顯示在log.txt
文件中。
是否可以將所有內容同時log.txt
控制台和log.txt
文件?
控制台和log.txt
文件中都需要輸出
What is your name: ABC
Your name is ABC
我想在控制台和log.txt
文件中都獲得類似(精確)的輸出嗎?
如果有更簡便的方法,也請告知我。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.