繁体   English   中英

如何将python屏幕输出保存到文本文件

[英]How to save python screen output to a text file

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

这是我所拥有的:

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 提供的用户文件 I/O 工具(这是f=open('file.txt', 'w')东西。

  • 如果不想修改您的程序,您可以使用流重定向(在Windows类 Unix 系统上)。 这是python myscript > output.txt东西。

  • 如果你想同时看到你的屏幕上,并在日志文件中的输出,如果你的系统是Unix,你不想修改你的程序,你可以使用tee命令Windows版本也存在,但我有没用过)

  • 将所需输出发送到屏幕、文件、电子邮件、推特的更好方法,无论使用日志记录模块 这里的学习曲线是所有选项中最陡峭的,但从长远来看,它会物有所值。

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

import sys 

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

然后在代码结束时恢复到输出到屏幕:

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

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

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

$ python myscript.py > myoutput.txt

这通常适用于将 cli 程序(python、perl、php、java、二进制或其他)的所有输出放入一个文件中,有关更多信息,请参阅如何将 bash 脚本的整个输出保存到文件中。

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

$ python myscript.py | tee myoutput.txt

有关 tee 的更多信息,请参阅: 如何将输出重定向到文件和标准输出

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

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

像这样:

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

只需将>>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)

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

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

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

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

首先创建文件。

通过打开文件

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

或者

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

如果您想附加到文件

现在,通过写入同一个文件

f.write(<text to be written>)

使用完毕后关闭文件

#good pracitice
f.close()

这个很简单,就用这个例子

import sys
with open("test.txt", 'w') as sys.stdout:
    print("hello")
f = open('file.txt', 'w') #open the file(this will not only open the file also 
#if you had one will create a new one on top or it would create one if you 
#didn't have one

f.write(info_to_write_into_the_file) #this will put the info in the file

f.close() #this will close the file handler. AKA free the used memory

我希望这有帮助

python script_name.py > saveit.txt

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

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

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

def oprint(message):
    print(message)
    global log
    log.write(message)
    return()

code ...

log.close()

每当您想打印某些内容时,只需使用 oprint 而不是打印。

注意1:如果您想将函数 oprint 放在模块中然后导入它,请使用:

import builtins

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

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

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

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

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

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

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
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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM