【问题标题】:How to save python screen output to a text file如何将python屏幕输出保存到文本文件
【发布时间】:2014-09-21 07:01:36
【问题描述】:

我想从字典中查询项目并将打印输出保存到文本文件中。

这是我所拥有的:

import json
import exec.fullog as e

inp = e.getdata() #inp now is a dict() which has items, keys and values.

#Query

print('Data collected on:', inp['header']['timestamp'].date())
print('\n CLASS 1 INFO\n')

for item in inp['Demographics']:
    if item['name'] in ['Carly', 'Jane']:
        print(item['name'], 'Height:', item['ht'], 'Age:', item['years'])

for item in inp['Activity']:
    if item['name'] in ['Cycle', 'Run', 'Swim']:
        print(item['name'], 'Athlete:', item['athl_name'], 'Age:', item['years'])

【问题讨论】:

  • 简单地说,继续打印任何你想要的东西,到控制台,就像你在 Python 文件中使用 printlog 一样;这里没有具体的变化。现在,在执行python文件python3 yo.py时,只需将命令替换为python3 yo.py > logs.txt

标签: python python-2.7


【解决方案1】:
class Logger:
    def __init__(self, application_log_file, init_text="Program started", print_with_time=True):
        import sys
        self.__output_num = 0
        self.origin = sys.stdout
        self.init_text = init_text
        self.__init = False
        self.print_with_time = print_with_time
        self.log_file = application_log_file
        self.data = ""
        self.last_time = 0
        sys.stdout = self
        sys.stderr = self

    def flush(self):
        if self.data == "\n":
            return
        sys.stdout = self.origin
        print(self.__create_log_text(self.data) if self.print_with_time else self.data)
        with open(self.log_file, "a", encoding="utf-8") as log:
            log.write(self.__create_log_text(self.data))
        self.data = ""
        sys.stdout = self

    def __create_log_text(self, string: str):
        if self.last_time == str(datetime.datetime.today())[:-7]:
            return string
        self.last_time = str(datetime.datetime.today())[:-7]
        if not self.__init:
            self.__init = True
            return str(datetime.datetime.today())[:-7] + " | " + f"{self.init_text}\n"
        return str(datetime.datetime.today())[:-7] + " | " + string

    def write(self, data):
        self.data += data

【讨论】:

    【解决方案2】:
    idx = 0
    for wall in walls:
        np.savetxt("C:/Users/vimal/OneDrive/Desktop/documents-export-2021-06-11/wall/wall_"+str(idx)+".csv",
                   wall, delimiter=",")
        idx += 1
    

    【讨论】:

      【解决方案3】:

      abarnert 的回答非常好,而且是pythonic。另一个完全不同的路线(不是在 python 中)是让 bash 为你做这件事:

      $ python myscript.py > myoutput.txt
      

      这通常用于将 cli 程序(python、perl、php、java、二进制或其他)的所有输出放入文件中,请参阅How to save entire output of bash script to file 了解更多信息。

      如果你希望输出到标准输出到文件,你可以使用tee:

      $ python myscript.py | tee myoutput.txt
      

      有关 tee 的更多信息,请参阅:How to redirect output to a file and stdout

      【讨论】:

      • 实际上,这更通用:简单的> 重定向适用于 Windows,并且适用于几乎所有 *nix shell,而不仅仅是 bash。
      • 感谢@abarnert,我很高兴不知道 Windows cmd,但我距离 tcsh 的创建者之一约 100 英尺,所以我绝对应该知道得更好。我已更新以反映您的信息。
      • 嗯,cmd.exe 是 DOS command.com 的超集,它是 CP/M CCP 的克隆,有一些细微的变化,我敢打赌你办公室里的某个人至少对此有模糊的回忆。 :)
      • @jachilles 添加了!
      • @hafiz031 在第一个示例中使用>>(sh 附加运算符)而不是>
      【解决方案4】:

      我们可以在使用 append 选项打开文件后,仅使用两行代码,简单地将 python 内置打印函数的输出传递给文件:

      with open('filename.txt', 'a') as file:
          print('\nThis printed data will store in a file', file=file)
      

      希望这可以解决问题...

      注意:此代码适用于 python3,但目前不支持 python2。

      【讨论】:

        【解决方案5】:

        这个很简单,利用这个例子就行了

        import sys
        with open("test.txt", 'w') as sys.stdout:
            print("hello")
        

        【讨论】:

          【解决方案6】:

          我找到了一个快速的方法:

          log = open("log.txt", 'a')
          
          def oprint(message):
              print(message)
              global log
              log.write(message)
              return()
          
          code ...
          
          log.close()
          

          当您想打印某些东西时,只需使用 oprint 而不是 print。

          注意1:如果你想把函数oprint放在一个模块中然后导入它,使用:

          import builtins
          
          builtins.log = open("log.txt", 'a')
          

          注意2:你传递给oprint的应该是一个字符串(所以如果你在打印中使用逗号分隔多个字符串,你可以用+替换它)

          【讨论】:

            【解决方案7】:
            python script_name.py > saveit.txt
            

            因为这个方案使用 shell 命令行来启动 Python 程序,所以所有常用的 shell 语法都适用。例如,通过这种方式,我们可以将 Python 脚本的打印输出路由到文件中进行保存。

            【讨论】:

              【解决方案8】:

              这是python 3+中一个非常简单的方法:

              f = open('filename.txt', 'w')
              print('something', file = f)
              

              ^ 从这个答案中发现:https://stackoverflow.com/a/4110906/6794367

              【讨论】:

                【解决方案9】:

                在脚本中执行此操作的一个快速而肮脏的技巧是将屏幕输出定向到文件:

                import sys 
                
                stdoutOrigin=sys.stdout 
                sys.stdout = open("log.txt", "w")
                

                然后在代码末尾恢复到输出到屏幕:

                sys.stdout.close()
                sys.stdout=stdoutOrigin
                

                这应该适用于简单的代码,但对于复杂的代码,还有其他更正式的方法,例如使用Python logging

                【讨论】:

                  【解决方案10】:

                  让我总结一下所有的答案并补充一些。

                  • 要从脚本中写入文件,用户 file I/O tools 由 Python 提供(这是 f=open('file.txt', 'w') 的东西。

                  • 如果不想修改程序,可以使用流重定向(windowsUnix-like systems)。这是python myscript > output.txt 的东西。

                  • 如果您想在屏幕上和日志文件中看到输出,并且如果您使用的是 Unix,并且不想修改程序,您可以用tee commandwindows version also exists,不过我没用过)

                  • 使用logging module 将所需输出发送到屏幕、文件、电子邮件、twitter 的更好方法。这里的学习曲线是所有选项中最陡峭的,但从长远来看,它会收回成本。

                  【讨论】:

                    【解决方案11】:

                    你可能会想要这个。最简单的解决方案是

                    先创建文件。

                    打开文件

                    f = open('<filename>', 'w')
                    

                    f = open('<filename>', 'a')
                    

                    如果你想追加到文件

                    现在,通过

                    写入同一个文件
                    f.write(<text to be written>)
                    

                    使用完后关闭文件

                    #good pracitice
                    f.close()
                    

                    【讨论】:

                      【解决方案12】:

                      您要求的并非不可能,但可能不是您真正想要的。

                      不要尝试将屏幕输出保存到文件,只需将输出写入文件而不是屏幕。

                      像这样:

                      with open('outfile.txt', 'w') as outfile:
                          print >>outfile, 'Data collected on:', input['header']['timestamp'].date()
                      

                      只需将 &gt;&gt;outfile 添加到所有打印语句中,并确保所有内容都缩进到该 with 语句下。


                      更一般地说,最好使用字符串格式而不是魔术print 逗号,这意味着您可以改用write 函数。例如:

                      outfile.write('Data collected on: {}'.format(input['header']['timestamp'].date()))
                      

                      但如果print 已经在做你想做的格式化,你现在可以坚持下去。


                      如果您有一些其他人编写的 Python 脚本(或者更糟糕的是,您没有源代码的已编译 C 程序)并且无法进行此更改,该怎么办?然后答案是将其包装在另一个脚本中,该脚本使用subprocess 模块捕获其输出。同样,您可能不希望这样,但如果您这样做:

                      output = subprocess.check_output([sys.executable, './otherscript.py'])
                      with open('outfile.txt', 'wb') as outfile:
                          outfile.write(output)
                      

                      【讨论】:

                        猜你喜欢
                        • 1970-01-01
                        • 2015-03-29
                        • 2012-12-21
                        • 1970-01-01
                        • 1970-01-01
                        • 1970-01-01
                        • 1970-01-01
                        • 1970-01-01
                        相关资源
                        最近更新 更多