简体   繁体   English

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

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

I'd like to query items from a dict and save the printed output to a text file.我想从字典中查询项目并将打印输出保存到文本文件中。

Here's what I have:这是我所拥有的:

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'])

Let me summarize all the answers and add some more.让我总结一下所有的答案并补充一些。

  • To write to a file from within your script, user file I/O tools that are provided by Python (this is the f=open('file.txt', 'w') stuff.要从脚本中写入文件,请使用 Python 提供的用户文件 I/O 工具(这是f=open('file.txt', 'w')东西。

  • If don't want to modify your program, you can use stream redirection (both on windows and on Unix-like systems ).如果不想修改您的程序,您可以使用流重定向(在Windows类 Unix 系统上)。 This is the python myscript > output.txt stuff.这是python myscript > output.txt东西。

  • If you want to see the output both on your screen and in a log file, and if you are on Unix, and you don't want to modify your program, you may use the tee command (windows version also exists , but I have never used it)如果你想同时看到你的屏幕上,并在日志文件中的输出,如果你的系统是Unix,你不想修改你的程序,你可以使用tee命令Windows版本也存在,但我有没用过)

  • Even better way to send the desired output to screen, file, e-mail, twitter, whatever is to use the logging module .将所需输出发送到屏幕、文件、电子邮件、推特的更好方法,无论使用日志记录模块 The learning curve here is the steepest among all the options, but in the long run it will pay for itself.这里的学习曲线是所有选项中最陡峭的,但从长远来看,它会物有所值。

A quick and dirty hack to do this within the script is to direct the screen output to a file:在脚本中执行此操作的一个快速而肮脏的技巧是将屏幕输出定向到一个文件:

import sys 

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

and then reverting back to outputting to screen at the end of your code:然后在代码结束时恢复到输出到屏幕:

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

This should work for a simple code, but for a complex code there are other more formal ways of doing it such as using Python logging .这应该适用于简单的代码,但对于复杂的代码,还有其他更正式的方法,例如使用Python logging

abarnert 's answer is very good and pythonic. abarnert的回答非常好,而且很有 Python 风格。 Another completely different route (not in python) is to let bash do this for you:另一个完全不同的路线(不在 python 中)是让 bash 为你做这件事:

$ python myscript.py > myoutput.txt

This works in general to put all the output of a cli program (python, perl, php, java, binary, or whatever) into a file, see How to save entire output of bash script to file for more.这通常适用于将 cli 程序(python、perl、php、java、二进制或其他)的所有输出放入一个文件中,有关更多信息,请参阅如何将 bash 脚本的整个输出保存到文件中。

If you want the output to go to stdout and to the file, you can use tee:如果您希望输出转到标准输出文件,您可以使用 tee:

$ python myscript.py | tee myoutput.txt

For more on tee, see: How to redirect output to a file and stdout有关 tee 的更多信息,请参阅: 如何将输出重定向到文件和标准输出

What you're asking for isn't impossible, but it's probably not what you actually want.您所要求的并非不可能,但可能不是您真正想要的。

Instead of trying to save the screen output to a file, just write the output to a file instead of to the screen.不要尝试将屏幕输出保存到文件,只需将输出写入文件而不是屏幕。

Like this:像这样:

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

Just add that >>outfile into all your print statements, and make sure everything is indented under that with statement.只需将>>outfile添加到所有打印语句中,并确保所有内容都缩进在with语句下。


More generally, it's better to use string formatting rather than magic print commas, which means you can use the write function instead.更一般地,最好使用字符串格式而不是魔术print逗号,这意味着您可以改用write函数。 For example:例如:

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

But if print is already doing what you want as far as formatting goes, you can stick with it for now.但是,如果就格式而言, print已经在做您想做的事情,那么您现在可以坚持使用它。


What if you've got some Python script someone else wrote (or, worse, a compiled C program that you don't have the source to) and can't make this change?如果您有一些其他人编写的 Python 脚本(或者更糟的是,您没有源代码的已编译 C 程序)并且无法进行此更改怎么办? Then the answer is to wrap it in another script that captures its output, with the subprocess module.然后答案是将它包装在另一个脚本中,该脚本使用subprocess模块捕获其输出。 Again, you probably don't want that, but if you do:同样,您可能不希望那样,但如果您这样做:

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

Here's a really simple way in python 3+:这是python 3+中一个非常简单的方法:

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

^ found that from this answer: https://stackoverflow.com/a/4110906/6794367 ^ 从这个答案中发现: https : //stackoverflow.com/a/4110906/6794367

You would probably want this.你可能想要这个。 Simplest solution would be最简单的解决方案是

Create file first.首先创建文件。

open file via通过打开文件

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

or或者

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

in case you want to append to file如果您想附加到文件

Now, write to the same file via现在,通过写入同一个文件

f.write(<text to be written>)

Close the file after you are done using it使用完毕后关闭文件

#good pracitice
f.close()

This is very simple, just make use of this example这个很简单,就用这个例子

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

I hope this helps 我希望这有帮助

python script_name.py > saveit.txt

Because this scheme uses shell command lines to start Python programs, all the usual shell syntax applies.因为这个方案使用 shell 命令行来启动 Python 程序,所以所有常用的 shell 语法都适用。 For instance, By this, we can route the printed output of a Python script to a file to save it.例如,通过这种方式,我们可以将 Python 脚本的打印输出路由到一个文件中进行保存。

I found a quick way for this:我找到了一个快速的方法:

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

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

code ...

log.close()

Whenever you want to print something just use oprint rather than print.每当您想打印某些内容时,只需使用 oprint 而不是打印。

Note1: In case you want to put the function oprint in a module then import it, use:注意1:如果您想将函数 oprint 放在模块中然后导入它,请使用:

import builtins

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

Note2: what you pass to oprint should be a one string (so if you were using a comma in your print to separate multiple strings, you may replace it with +)注意2:你传递给 oprint 的应该是一个字符串(所以如果你在打印中使用逗号来分隔多个字符串,你可以用 + 替换它)

We can simply pass the output of python inbuilt print function to a file after opening the file with the append option by using just two lines of code:在使用 append 选项打开文件后,只需使用两行代码,我们就可以简单地将 python 内置打印函数的输出传递给文件:

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

Hope this may resolve the issue...希望这可以解决问题......

Note: this code works with python3 however, python2 is not being supported currently.注意:此代码适用于 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