我写了一些代码只是为了在 python 中练习冗长。详细程度是通过ArgumentParser
模块嵌入的。但是,我也想stdout
在详细程度被禁用时写入 to 文件:
#!/usr/bin/python
import sys
def printable1():
print "1"
def printable2():
print "2"
def printable3():
print "3"
def Main1():
printable1()
printable2()
def Main2():
printable2()
printable3()
class Logger(object):
def __init__(self):
self.terminal = sys.stdout
self.log = open("logfile2.log", "a")
def write(self, message):
self.terminal.write(message)
self.log.write(message)
if __name__ == "__main__":
from argparse import ArgumentParser
parser = ArgumentParser(description='PC Test',version="1.0")
parser.add_argument('--nopc',action='store_true', help='Do not perform test on the PC')
parser.add_argument('--pc', action='store_true', help='Do perform test on the PC')
# VERBOSITY
parser.add_argument('--vmode', dest='verbose', action='store_true',
help='Enable printing of status messages to stdout.')
args = parser.parse_args()
sys.stdout = Logger()
if args.verbose:
if args.pc:
Main1()
elif args.nopc:
Main2()
else:
Main1()
Main2()
--vmode
仅当使用参数启用详细程度时,此代码才会将标准输出写入文件。你能帮我找到解决办法吗?