在 python 3 中,您可以重新分配print
:
#!/usr/bin/python3
def other_fn():
#This will use the print function that's active when the function is called
print("Printing from function")
file_name = "test.txt"
with open(file_name, "w+") as f_out:
py_print = print #Need to use this to restore builtin print later, and to not induce recursion
print = lambda out_str : py_print(out_str, file=f_out)
#If you'd like, for completeness, you can include args+kwargs
print = lambda *args, **kwargs : py_print(*args, file=f_out, **kwargs)
print("Writing to %s" %(file_name))
other_fn() #Writes to file
#Must restore builtin print, or you'll get 'I/O operation on closed file'
#If you attempt to print after this block
print = py_print
print("Printing to stdout")
other_fn() #Writes to console/stdout
请注意,print fromother_fn
仅切换输出,因为print正在全局范围内重新分配。如果我们在函数中分配print ,通常不会影响print in 。如果我们想影响所有的打印调用,other_fn
我们可以使用global关键字:
import builtins
def other_fn():
#This will use the print function that's active when the function is called
print("Printing from function")
def main():
global print #Without this, other_fn will use builtins.print
file_name = "test.txt"
with open(file_name, "w+") as f_out:
print = lambda *args, **kwargs : builtins.print(*args, file=f_out, **kwargs)
print("Writing to %s" %(file_name))
other_fn() #Writes to file
#Must restore builtin print, or you'll get 'I/O operation on closed file'
#If you attempt to print after this block
print = builtins.print
print("Printing to stdout")
other_fn() #Writes to console/stdout
就个人而言,我更喜欢print
通过将输出文件描述符烘焙到一个新函数中来回避使用该函数的要求:
file_name = "myoutput.txt"
with open(file_name, "w+") as outfile:
fprint = lambda pstring : print(pstring, file=outfile)
print("Writing to stdout")
fprint("Writing to %s" % (file_name))