Python 2.7.11 (v2.7.11:6d1b6a68f775, Dec 5 2015, 20:32:19) [MSC v.1500 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> import sys >>> for fd in (sys.stdin, sys.stdout, sys.stderr): print fd <idlelib.PyShell.PseudoInputFile object at 0x0177C910> <idlelib.PyShell.PseudoOutputFile object at 0x0177C970> <idlelib.PyShell.PseudoOutputFile object at 0x017852B0> >>> for fd in (sys.__stdin__, sys.__stdout__, sys.__stderr__): print fd <open file '<stdin>', mode 'r' at 0x00FED020> <open file '<stdout>', mode 'w' at 0x00FED078> <open file '<stderr>', mode 'w' at 0x00FED0D0> >>>
>>> import sys
>>> print 'Hello World'
Hello World
>>> sys.stdout.write('Hello World')
Hello World
E:\>echo print 'hello' > test.py E:\>test.py > out.txt E:\>type out.txt hello E:\>test.py >> out.txt E:\>type out.txt hello hello E:\>test.py > nul
[wangxiaoyuan_@localhost ~]$ echo $SHELL /bin/bash [wangxiaoyuan_@localhost ~]$ python -c "print 'hello'" hello [wangxiaoyuan_@localhost ~]$ python -c "print 'hello'" > out.txt [wangxiaoyuan_@localhost ~]$ cat out.txt hello [wangxiaoyuan_@localhost ~]$ python -c "print 'world'" >> out.txt [wangxiaoyuan_@localhost ~]$ cat out.txt hello world [wangxiaoyuan_@localhost ~]$ python -c "print 'I am'" | tee out.txt I am [wangxiaoyuan_@localhost ~]$ python -c "print 'xywang'" | tee -a out.txt xywang [wangxiaoyuan_@localhost ~]$ cat out.txt I am xywang [wangxiaoyuan_@localhost ~]$ python -c "print 'hello'" > /dev/null [wangxiaoyuan_@localhost ~]$
memo = cStringIO.StringIO(); serr = sys.stderr; file = open('out.txt', 'w+')
print >>memo, 'StringIO'; print >>serr, 'stderr'; print >>file, 'file'
print >>None, memo.getvalue()
import sys
savedStdout = sys.stdout #保存标准输出流
with open('out.txt', 'w+') as file:
sys.stdout = file #标准输出重定向至文件
print 'This message is for file!'
sys.stdout = savedStdout #恢复标准输出流
print 'This message is for screen!'
class RedirectStdout: #import os, sys, cStringIO
def __init__(self):
self.content = ''
self.savedStdout = sys.stdout
self.memObj, self.fileObj, self.nulObj = None, None, None
#外部的print语句将执行本write()方法,并由当前sys.stdout输出
def write(self, outStr):
#self.content.append(outStr)
self.content += outStr
def toCons(self): #标准输出重定向至控制台
sys.stdout = self.savedStdout #sys.__stdout__
def toMemo(self): #标准输出重定向至内存
self.memObj = cStringIO.StringIO()
sys.stdout = self.memObj
def toFile(self, file='out.txt'): #标准输出重定向至文件
self.fileObj = open(file, 'a+', 1) #改为行缓冲
sys.stdout = self.fileObj
def toMute(self): #抑制输出
self.nulObj = open(os.devnull, 'w')
sys.stdout = self.nulObj
def restore(self):
self.content = ''
if self.memObj.closed != True:
self.memObj.close()
if self.fileObj.closed != True:
self.fileObj.close()
if self.nulObj.closed != True:
self.nulObj.close()
sys.stdout = self.savedStdout #sys.__stdout__
redirObj = RedirectStdout()
sys.stdout = redirObj #本句会抑制"Let's begin!"输出
print "Let's begin!"
#屏显'Hello World!'和'I am xywang.'(两行)
redirObj.toCons(); print 'Hello World!'; print 'I am xywang.'
#写入'How are you?'和"Can't complain."(两行)
redirObj.toFile(); print 'How are you?'; print "Can't complain."
redirObj.toCons(); print "What'up?" #屏显
redirObj.toMute(); print '<Silence>' #无屏显或写入
os.system('echo Never redirect me!') #控制台屏显'Never redirect me!'
redirObj.toMemo(); print 'What a pity!' #无屏显或写入
redirObj.toCons(); print 'Hello?' #屏显
redirObj.toFile(); print "Oh, xywang can't hear me" #该串写入文件
redirObj.restore()
print 'Pop up' #屏显
import sys, cStringIO, contextlib
class DummyFile:
def write(self, outStr): pass
@contextlib.contextmanager
def MuteStdout():
savedStdout = sys.stdout
sys.stdout = cStringIO.StringIO() #DummyFile()
try:
yield
except Exception: #捕获到错误时,屏显被抑制的输出(该处理并非必需)
content, sys.stdout = sys.stdout, savedStdout
print content.getvalue()#; raise
#finally:
sys.stdout = savedStdout
with MuteStdout(): print "I'll show up when <raise> is executed!" #不屏显不写入 raise #屏显上句 print "I'm hiding myself somewhere:)" #不屏显
import os, sys
from contextlib import contextmanager
@contextmanager
def RedirectStdout(newStdout):
savedStdout, sys.stdout = sys.stdout, newStdout
try:
yield
finally:
sys.stdout = savedStdout
def Greeting(): print 'Hello, boss!'
with open('out.txt', "w+") as file:
print "I'm writing to you..." #屏显
with RedirectStdout(file):
print 'I hope this letter finds you well!' #写入文件
print 'Check your mailbox.' #屏显
with open(os.devnull, "w+") as file, RedirectStdout(file):
Greeting() #不屏显不写入
print 'I deserve a pay raise:)' #不屏显不写入
print 'Did you hear what I said?' #屏显
import sys, cStringIO, functools
def MuteStdout(retCache=False):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
savedStdout = sys.stdout
sys.stdout = cStringIO.StringIO()
try:
ret = func(*args, **kwargs)
if retCache == True:
ret = sys.stdout.getvalue().strip()
finally:
sys.stdout = savedStdout
return ret
return wrapper
return decorator
@MuteStdout(True) def Exclaim(): print 'I am proud of myself!' @MuteStdout() def Mumble(): print 'I lack confidence...'; return 'sad' print Exclaim(), Exclaim.__name__ #屏显'I am proud of myself! Exclaim' print Mumble(), Mumble.__name__ #屏显'sad Mumble'
def RedirectStdout(newStdout=sys.stdout):
def decorator(func):
def wrapper(*args,**kwargs):
savedStdout, sys.stdout = sys.stdout, newStdout
try:
return func(*args, **kwargs)
finally:
sys.stdout = savedStdout
return wrapper
return decorator
file = open('out.txt', "w+")
@RedirectStdout(file)
def FunNoArg(): print 'No argument.'
@RedirectStdout(file)
def FunOneArg(a): print 'One argument:', a
def FunTwoArg(a, b): print 'Two arguments: %s, %s' %(a,b)
FunNoArg() #写文件'No argument.'
FunOneArg(1984) #写文件'One argument: 1984'
RedirectStdout()(FunTwoArg)(10,29) #屏显'Two arguments: 10, 29'
print FunNoArg.__name__ #屏显'wrapper'(应显示'FunNoArg')
file.close()
import logging
logging.basicConfig(level = logging.DEBUG,
format = '%(asctime)s [%(levelname)s] at %(filename)s,%(lineno)d: %(message)s',
datefmt = '%Y-%m-%d(%a)%H:%M:%S',
filename = 'out.txt',
filemode = 'w')
#将大于或等于INFO级别的日志信息输出到StreamHandler(默认为标准错误)
console = logging.StreamHandler()
console.setLevel(logging.INFO)
formatter = logging.Formatter('[%(levelname)-8s] %(message)s') #屏显实时查看,无需时间
console.setFormatter(formatter)
logging.getLogger().addHandler(console)
logging.debug('gubed'); logging.info('ofni'); logging.critical('lacitirc')
[INFO ] ofni [CRITICAL] lacitirc
2016-05-13(Fri)17:10:53 [DEBUG] at test.py,25: gubed 2016-05-13(Fri)17:10:53 [INFO] at test.py,25: ofni 2016-05-13(Fri)17:10:53 [CRITICAL] at test.py,25: lacitirc
#logger.conf
###############Logger###############
[loggers]
keys=root,Logger2F,Logger2CF
[logger_root]
level=DEBUG
handlers=hWholeConsole
[logger_Logger2F]
handlers=hWholeFile
qualname=Logger2F
propagate=0
[logger_Logger2CF]
handlers=hPartialConsole,hPartialFile
qualname=Logger2CF
propagate=0
###############Handler###############
[handlers]
keys=hWholeConsole,hPartialConsole,hWholeFile,hPartialFile
[handler_hWholeConsole]
class=StreamHandler
level=DEBUG
formatter=simpFormatter
args=(sys.stdout,)
[handler_hPartialConsole]
class=StreamHandler
level=INFO
formatter=simpFormatter
args=(sys.stderr,)
[handler_hWholeFile]
class=FileHandler
level=DEBUG
formatter=timeFormatter
args=('out.txt', 'a')
[handler_hPartialFile]
class=FileHandler
level=WARNING
formatter=timeFormatter
args=('out.txt', 'w')
###############Formatter###############
[formatters]
keys=simpFormatter,timeFormatter
[formatter_simpFormatter]
format=[%(levelname)s] at %(filename)s,%(lineno)d: %(message)s
[formatter_timeFormatter]
format=%(asctime)s [%(levelname)s] at %(filename)s,%(lineno)d: %(message)s
datefmt=%Y-%m-%d(%a)%H:%M:%S
import logging, logging.config
logging.config.fileConfig("logger.conf")
logger = logging.getLogger("Logger2CF")
logger.debug('gubed'); logger.info('ofni'); logger.warn('nraw')
logger.error('rorre'); logger.critical('lacitirc')
logger1 = logging.getLogger("Logger2F")
logger1.debug('GUBED'); logger1.critical('LACITIRC')
logger2 = logging.getLogger()
logger2.debug('gUbEd'); logger2.critical('lAcItIrC')
[INFO] at test.py,7: ofni [WARNING] at test.py,7: nraw [ERROR] at test.py,8: rorre [CRITICAL] at test.py,8: lacitirc [DEBUG] at test.py,14: gUbEd [CRITICAL] at test.py,14: lAcItIrC
2016-05-13(Fri)20:31:21 [WARNING] at test.py,7: nraw 2016-05-13(Fri)20:31:21 [ERROR] at test.py,8: rorre 2016-05-13(Fri)20:31:21 [CRITICAL] at test.py,8: lacitirc 2016-05-13(Fri)20:31:21 [DEBUG] at test.py,11: GUBED 2016-05-13(Fri)20:31:21 [CRITICAL] at test.py,11: LACITIRC
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有