Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
控制台和文件上的Python输出_Python_File_Console_Output - Fatal编程技术网

控制台和文件上的Python输出

控制台和文件上的Python输出,python,file,console,output,Python,File,Console,Output,我正在写一个代码来分析PDF文件。我想在控制台上显示输出,并将输出的副本保存在文件中,我使用以下代码将输出保存在文件中: import sys sys.stdout = open('C:\\users\\Suleiman JK\\Desktop\\file.txt',"w") print "test" 但是,我是否也可以将输出显示到控制台中,但不使用类,因为我不擅长使用它们?(这个答案使用Python 3,如果您喜欢Python 2,则必须对其进行调整。) 首先导入Python包(和用于访问标

我正在写一个代码来分析PDF文件。我想在控制台上显示输出,并将输出的副本保存在文件中,我使用以下代码将输出保存在文件中:

import sys
sys.stdout = open('C:\\users\\Suleiman JK\\Desktop\\file.txt',"w")
print "test"
但是,我是否也可以将输出显示到控制台中,但不使用类,因为我不擅长使用它们?

(这个答案使用Python 3,如果您喜欢Python 2,则必须对其进行调整。)

首先导入Python包(和用于访问标准输出流的sys):

在入口点中,对于标准输出流和输出文件:

targets = logging.StreamHandler(sys.stdout), logging.FileHandler('test.log')
并仅输出不带日志级别的消息:

logging.basicConfig(format='%(message)s', level=logging.INFO, handlers=targets)
现在您可以使用它:

>>> logging.info('testing the logging system')
testing the logging system
>>> logging.info('second message')
second message
>>> print(*open('test.log'), sep='')
testing the logging system
second message

sys.stdout
可以指向任何具有写入方法的对象,因此您可以创建一个同时写入文件和控制台的类

import sys

class LoggingPrinter:
    def __init__(self, filename):
        self.out_file = open(filename, "w")
        self.old_stdout = sys.stdout
        #this object will take over `stdout`'s job
        sys.stdout = self
    #executed when the user does a `print`
    def write(self, text): 
        self.old_stdout.write(text)
        self.out_file.write(text)
    #executed when `with` block begins
    def __enter__(self): 
        return self
    #executed when `with` block ends
    def __exit__(self, type, value, traceback): 
        #we don't want to log anymore. Restore the original stdout object.
        sys.stdout = self.old_stdout

print "Entering section of program that will be logged."
with LoggingPrinter("result.txt"):
    print "I've got a lovely bunch of coconuts."
print "Exiting logged section of program."
结果:

控制台:

Entering section of program that will be logged.
I've got a lovely bunch of coconuts.
Exiting logged section of program.
result.txt:

I've got a lovely bunch of coconuts.

在某些情况下,此方法可能比codesparkle更可取,因为您不必将所有现有的
print
s替换为
logging.info
。只需将您想要登录的所有内容放入一个带有块的

您可以创建一个函数,该函数既可以打印到控制台,也可以打印到文件。您可以通过切换stdout来执行此操作,例如:

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
print_both(open_file_variable, 'pass arguments as if it is', 'print!', 1, '!')
 print_both(open_file_variable, 'you should concatenate'+str(4334654)+'arguments together')
或者使用文件写入方法(我建议使用此方法,除非您必须使用标准输出)

请注意:

  • 传递给函数的文件参数必须在函数外部打开(例如在程序开始时),并在函数外部关闭(例如在程序结束时)。您应该在附加模式下打开它
  • 将*args传递给函数允许您以与传递给print函数相同的方式传递参数。所以你把参数传递给print
  • …就像这样:

    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
    
    print_both(open_file_variable, 'pass arguments as if it is', 'print!', 1, '!')
    
     print_both(open_file_variable, 'you should concatenate'+str(4334654)+'arguments together')
    
    否则,您必须将所有内容转换为单个参数,即单个字符串。它看起来是这样的:

    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
    
    print_both(open_file_variable, 'pass arguments as if it is', 'print!', 1, '!')
    
     print_both(open_file_variable, 'you should concatenate'+str(4334654)+'arguments together')
    

    我仍然建议你学会正确使用课堂,你会从中受益匪浅。希望这能有所帮助。

    我懒得写函数,所以当我需要打印到控制台和文件时,我写了这个快速且(不太)脏的代码:

    import sys
    ...
    with open('myreport.txt', 'w') as f:
        for out in [sys.stdout, f]:
            print('some data', file=out)
            print('some mre data', file=out)
    

    您可以使用
    f.write(data)
    将输出存储在文件中,然后使用
    print(data)
    将输出打印到控制台。我不理解问题中的类引用。Python模块来解救我@我的意思是我知道如何在课堂上工作。如果我想在上面的示例中使用它,我如何使用writeWith类的方法来实现这一点
    X.write():……
    where。。。。是您发布的代码或其任何变体。虽然我不知道您为什么要这样做,但日志记录包也可以解决您的问题。如果我的代码中有许多“print”命令,我该如何处理?使用print_both代替print_,例如,
    print_both(文件,'print stuff');同时打印(文件“打印其他内容”)