python requests怎么设置重定向

Python015

python requests怎么设置重定向,第1张

class FakeOut:

def __init__(self):

self.str=''

self.n=0

def write(self,s):

self.str+="Out:[%s] %s\n"%(self.n,s)

self.n+=1

def show(self): #显示函数,非必须

print self.str

def clear(self): #清空函数,非必须

self.str=''

self.n=0

f=FakeOut()

import sys

old=sys.stdout

sys.stdout=f

print 'Hello weird.'

print 'Hello weird too.'

sys.stdout=old

f.show()

# 输出:

# Out:[0] Hello weird.

# Out:[1]

# Out:[2] Hello weird too.

# Out:[3]

Python编程中,往往需要将结果用print等输出,如果希望输出既可以显示到IDE的屏幕上,也能存到文件中(如txt)中,该怎么办呢?

方法1

可通过日志logging模块输出信息到文件或屏幕。但可能要设置log的level或输出端,对于同时需要记录debug error等信息的较为合适,官方教程推荐学习用更规范的logger来操作。

例如,可参考来自官网的这段代码。

import logging

logging.basicConfig(filename='log_examp.log',level=logging.DEBUG)

logging.debug('This message should go to the log file')

logging.info('So should this')

logging.warning('And this, too')

方法2

利用print输出两次

比如这里我想输出程序的path和程序的文件名

import os

# 第一句输出到consle:

print("filepath:",__file__,"\nfilename:",os.path.basename(__file__))

# 第二句输出到txt:

with open("outputlog.txt","a+") as f:

print("filepath:",__file__,

"\nfilename:",os.path.basename(__file__))

#当然 也可以用f.write("info")的方式写入文件

方法3

利用输出重定向输出两次

同样输出程序path和文件名

import os

import sys

temp=sys.stdout # 记录当前输出指向,默认是consle

with open("outputlog.txt","a+") as f:

sys.stdout=f # 输出指向txt文件

print("filepath:",__file__,

"\nfilename:",os.path.basename(__file__))

print("some other information")

print("some other")

print("information")

sys.stdout=temp # 输出重定向回consle

print(f.readlines()) # 将记录在文件中的结果输出到屏幕

R的重定向

这里多嘴补充一下,在windows下的R语言中,有个sink(‘文件名.后缀名’) 可以将输出重定向到文件中,然后用sink()重返控制台 很是方便