python - 从 ipython-notebook 转换为 .py

标签 python ipython jupyter-notebook

我正在尝试将 ipython 笔记本文件下载为 .py 文件。它工作得相当好,除了 .py 文件在单元格边界处散布有 "In: []" 。我可以忍受他们在那里,但我宁愿他们不在那里。
有什么简单的解决方法吗?

示例输出(我在 .py 文件中看到的内容):

# In[4]:

# Get names of all files
text_files = glob.glob('hw3data/*')
#print text_files


# In[5]:

def file_contents(file_name):
    with open(file_name) as f:
        return f.read()

编辑:本质上,我想知道是否可以使笔记本本身不输出#In[]。是否有命令行选项、实用程序或某种 %magic?

编辑:通过https://github.com/ipython/ipython/issues/5780 ,看来建议的解决方案只是使用自定义模板。来自水貂:

It's just a marker that indicates where the cells were. It is by design, but it has no effect on the Python, since it is a comment. If you want to remove them, you can use a custom exporter template that doesn't add these comments.

最佳答案

尝试

def rc(in_, out_):

    in_ = open(in_, 'r')
    out_ = open(out_,'w')
    out_.write(in_.readline())

    for line in in_:
        if not line.lstrip().startswith('# In['):
            out_.write(line)

    in_.close()
    out_.close()

rc('~/in_file.py', '~/out_file.py')

关于python - 从 ipython-notebook 转换为 .py,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23440300/

相关文章:

python - 激活虚拟环境并以批处理文件方式启动 jupyter notebook

python - 将 .py 文件作为模块导入时,文档字符串未显示?

python - 从 Python 插入 MySQL - 错误

python - 有没有办法使用 min 和 max 来编写这个 if-else?

ipython - 用代码配置Ipython后端使用Retina显示模式

ipython - 使用 Ipython ipywidget 创建变量?

python - 如何在两个连续的视频帧中跟踪轮辐?

python - Python中的错误处理可以检测程序状态

python - 如何使用奇点图像运行 jupyter 笔记本?

ubuntu - Docker/Jupyter notebook 设置 Base URL