控制台和文件上的Python输出 [英] Python output on both console and file

查看:101
本文介绍了控制台和文件上的Python输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写代码以分析PDF文件.我想在控制台上显示输出以及在文件中复制输出,我使用以下代码将输出保存在文件中:

I'm writing a code to analyze PDF file. I want to display the output on the console as well as to have a copy of the output in a file, I used this code save the output in a file:

import sys
sys.stdout = open('C:\\users\\Suleiman JK\\Desktop\\file.txt',"w")
print "test"

但是我是否也可以将输出显示到控制台中但不使用类,因为我对它们不满意?

but could I display the output into console as well but without using classes because I'm not good with them?

推荐答案

您可以创建一个可以同时打印到控制台和文件的函数.您可以通过切换标准输出来执行此操作,例如像这样:

You could make a function which prints both to console and to file. You can either do it by switching stdout, e.g. like this:

def print_both(file, *args):
    temp = sys.stdout #assign console output to a variable
    print ' '.join([str(arg) for arg in args]) 
    sys.stdout = file 
    print ' '.join([str(arg) for arg in args])
    sys.stdout = temp #set stdout back to console output

或使用文件写入方法(除非您必须使用stdout,否则我建议使用此方法)

or by using file write method (I suggest using this unless you have to use stdout)

def print_both(file, *args):
    toprint = ' '.join([str(arg) for arg in args])
    print toprint
    file.write(toprint)

请注意:

  1. 传递给函数的文件参数必须在函数外部(例如,在程序的开头)打开,并在函数外部(例如,在程序的结尾)关闭.您应该以附加模式打开它.
  2. 将* args传递给函数使您可以像对打印函数一样传递参数.因此,您传递参数进行打印...

...像这样:

print_both(open_file_variable, 'pass arguments as if it is', 'print!', 1, '!')

否则,您必须将所有内容都转换为单个参数,即单个字符串.看起来像这样:

Otherwise, you'd have to turn everything into a single argument i.e. a single string. It would look like this:

 print_both(open_file_variable, 'you should concatenate'+str(4334654)+'arguments together')

我仍然建议您学习正确使用类,您将从中受益匪浅.希望这会有所帮助.

I still suggest you learn to use classes properly, you'd benefit from that very much. Hope this helps.

这篇关于控制台和文件上的Python输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆