如何在程序完成后将控制台打印到文本文件(Python)?

2023-12-15

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

我搜索了StackOverflow和其他网站,但我找到了一些方法来重定向打印语句以直接打印到文件,但我希望程序正常工作,将输出显示到控制台,然后在程序的所有操作之后保存其内容完毕。

如果重要的话,我将 PyCharm 与 Python2.7 一起使用


好吧,通常要完成它,你必须重写 pythonprint内置功能。但是...有ipython,它提供了一些钩子。

首先你需要有ipython安装:

#bash
sudo pip install ipython

(我使用 sudo 来简单地找到我需要访问的文件夹,进一步阅读)

安装 ipython 后,您将拥有可用的 ipython 扩展文件夹,因此请使用它:

#bash
cd ~/.ipython/extensions/

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

#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在上面的路径下创建并放一些魔法(那里有很多东西,所以转到文件末尾):

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

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

/home/turkus/shell.txt

Notes

您可以避免每次都加载扩展程序ipython只需删除即可启动'print_to_file' from c.InteractiveShellApp.extensions列出在ipython_config.py。但请记住,您可以随时加载它,只需输入ipython安慰:

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

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在程序完成后将控制台打印到文本文件(Python)? 的相关文章

随机推荐