如何在程序完成(Python)后将控制台打印到文本文件? [英] How to print the console to a text file AFTER the program finishes (Python)?

查看:978
本文介绍了如何在程序完成(Python)后将控制台打印到文本文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个程序,通过print语句输出许多计算和结果到控制台。我想写一些代码导出(或保存)控制台的所有内容到一个简单的文本文件。

I have a program that outputs many calculations and results to the console through the print statement. I want to write some code to export (or save) all the contents of the console to a simple text file.

我搜索StackOverflow和其他网站,但我发现一些方法来重定向打印语句直接打印到文件,但我想让程序正常工作,显示输出到控制台,然后在程序的所有操作完成后保存它的内容。

I searched StackOverflow and other sites but I found some methods to redirect the print statement to print to a file directly, but I want the program to work normally, to display outputs to the console, then to save its contents AFTER all operations of the program done.

我使用PyCharm与Python2.7如果重要

I am using PyCharm with Python2.7 if it matters

推荐答案

确定,所以通常要完成它,你必须重写python print 。但是...有一个ipython,它提供了一些钩子。

Ok, so normally to get it done, you have to rewrite python print built-in function. But... There is ipython, which provides some hooks.

首先你需要安装 ipython / p>

First you need to have ipython installed:

#bash
sudo pip install ipython

(我使用sudo来简单找到那个文件夹,我需要到达,进一步阅读)

(I'm using sudo to simple locate then folder I need to reach, read further)

有ipython扩展文件夹可用,所以得到它:

After ipython installation you'll have ipython extensions folder available, so get to it:

#bash
cd ~/.ipython/extensions/

并在那里创建一个名为 print_to_file.py ,这里是它的内容:

and create there let's say a file called print_to_file.py, here is its content:

#python
class PrintWatcher(object):
    def __init__(self, ip):
        self.shell = ip

    def post_execute(self):
        with open('/home/turkus/shell.txt', 'a+') as f:
            in_len = len(self.shell.user_ns['In'])
            i = in_len - 1

            in_ = self.shell.user_ns['In'][i]
            out = self.shell.user_ns['Out'].get(i, '')
            # you can edit this line if you want different input in shell.txt
            f.write('{}\n{}\n'.format(in_, out))


def load_ipython_extension(ip):
    pw = PrintWatcher(ip)
    ip.events.register('post_run_cell', pw.post_execute)

保存文件后只需运行:

#bash
ipython profile create 

# you will get something like that:
[ProfileCreate] Generating default config file: u'/home/turkus/.ipython/profile_default/ipython_config.py'

现在回到设置我们的钩子。我们必须打开在上面路径下创建的 ipython_config.py ,并放置一些魔术(有很多东西在那里,所以去文件的末尾):

Now get back to setting up our hook. We must open ipython_config.py created under path above and put there some magic (there is a lot of stuff there, so go to the end of file):

# some commented lines here
c = get_config()
c.InteractiveShellApp.extensions = [
    'print_to_file'
]



保存后,可以运行 ipython 并编写您的代码。每一个你的输入都将写入你在上面提供的路径下的一个文件中,在我的例子中:

After saving it, you can run ipython and write your code. Every your input will be written in a file under path you provided above, in my case it was:

/home/turkus/shell.txt

注释

您可以避免每次 ipython 加载您的扩展程序,只需删除'print_to_file' ipython_config.py 中的 c.InteractiveShellApp.extensions 列表。但请记住,您可以随时加载它,只需输入 ipython 控制台:

You can avoid loading your extension every time ipython fires up, by just delete 'print_to_file' from c.InteractiveShellApp.extensions list in ipython_config.py. But remember that you can load it anytime you need, just by typing in ipython console:

➜  ~ ipython
Python 2.7.12 (default, Jul  1 2016, 15:12:24) 
Type "copyright", "credits" or "license" for more information.

IPython 4.0.0 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

In [1]: %load_ext print_to_file

c $ c> print_to_file.py 在使用%reload_ext print_to_file 命令后会反映在打开的ipython shell中,因此您不必退出并再次启动它。

Any change in print_to_file.py is being reflected in open ipython shell after using %reload_ext print_to_file command, so you don't have to exit from and fire up it again.

这篇关于如何在程序完成(Python)后将控制台打印到文本文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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