确定从 ipython notebook 读取和写入的所有文件

Determine all files read into and written from an ipython notebook

这是对这个问题的概括:Way to extract pickles coming in and out of ipython / jupyter notebook

在最高级别,我正在寻找一种方法来自动总结 ipython 笔记本中发生的事情。我看到的一种简化问题的方法是将笔记本内部的所有数据操作视为一个黑盒子,并且只关注它的输入和输出是什么。那么,有没有一种方法可以给定 ipython 笔记本的文件路径,您如何轻松确定它读入内存的所有不同 files/websites 以及后来 writes/dumps 的所有文件?我在想也许有一个函数可以扫描文件,解析输入和输出,并将其保存到字典中以便于访问:

summary_dict = summerize_file_io(ipynb_filepath)

print summary_dict["inputs"] 
> ["../Resources/Data/company_orders.csv", "http://special_company.com/company_financials.csv" ]

print summary_dict["outputs"]
> ["orders_histogram.jpg","data_consolidated.pickle"]

我想知道如何轻松地做到这一点,除了 pickle 对象之外,还包括不同的格式,例如:txt、csv、jpg、png 等...而且还可能涉及直接从 Web 将数据读取到笔记本中本身。

您可以通过将内置 open 修补为 JRG 来检查您打开或修改了哪些文件,如果需要,您应该扩展此功能以修补您用于连接到网站的任何功能也要跟踪它。

import builtins


modified = {}
old_open = builtins.open


def new_open(name, mode='r', *args, **kwargs):
    modified[name] = mode
    return old_open(name, mode=mode, *args, **kwargs)


# patch builtin open
builtins.open = new_open


# check modified
def whats_modified():
    print('Session has opened/modified the following files:')
    for name in sorted(modified):
        mode = modified[name]
        print(mode.ljust(8) + name)

如果我们在解释器中执行它(或将其用作模块),我们可以看到我们修改了什么以及我们如何打开它。

In [4]: with open('ex.txt') as file:
   ...:     print('ex.txt:', file.read())
   ...:     
ex.txt: some text.



In [5]: with open('other.txt', 'w') as file:
   ...:     file.write('Other text.\n')
   ...:     

In [6]: whats_modified()
Session has opened/modified the following files:
r       ex.txt
w       other.txt

虽然这有点受限,因为当文件重新打开时模式将被覆盖,但这可以通过在 new_open.

中执行一些额外检查来修复