ฉันกำลังดูการใช้ไฟล์* .ipynbเป็นแหล่งของความจริงและเขียนโปรแกรม 'รวบรวม' ไฟล์เหล่านี้เป็นไฟล์. py สำหรับงาน / งานที่กำหนดเวลาไว้
วิธีเดียวที่ฉันเข้าใจในการทำเช่นนี้คือผ่าน GUI มีวิธีทำผ่าน command line หรือไม่
ฉันกำลังดูการใช้ไฟล์* .ipynbเป็นแหล่งของความจริงและเขียนโปรแกรม 'รวบรวม' ไฟล์เหล่านี้เป็นไฟล์. py สำหรับงาน / งานที่กำหนดเวลาไว้
วิธีเดียวที่ฉันเข้าใจในการทำเช่นนี้คือผ่าน GUI มีวิธีทำผ่าน command line หรือไม่
คำตอบ:
หากคุณไม่ต้องการส่งออกสคริปต์ Python ทุกครั้งที่คุณบันทึกหรือคุณไม่ต้องการรีสตาร์ทเคอร์เนล IPython:
บนบรรทัดคำสั่งคุณสามารถใช้nbconvert:
$ jupyter nbconvert --to script [YOUR_NOTEBOOK].ipynb
ในฐานะที่เป็นการแฮ็กคุณสามารถเรียกใช้คำสั่งด้านบนในสมุดบันทึก IPythonโดยรอการอนุมัติล่วงหน้า!(ใช้สำหรับอาร์กิวเมนต์บรรทัดคำสั่งใด ๆ ) ภายในสมุดบันทึก:
!jupyter nbconvert --to script config_template.ipynb
ก่อนที่จะ--to scriptถูกเพิ่มตัวเลือกคือ--to pythonหรือ--to=pythonแต่มันถูกเปลี่ยนชื่อในการย้ายไปสู่ระบบโน๊ตบุ๊คผู้ไม่เชื่อเรื่องภาษา
jupyterคุณสามารถเรียกnbconvertผ่านตะขอก่อนหรือหลังบันทึก: อับดุลContentsManager.pre_save_hook FileContentsManager.post_save_hookคุณจะเพิ่มตะขอหลังการบันทึกjupyter nbconvert --to script [notebook]
                    jupyter nbconvert --to script /path/to/notebooks/*.ipynb
                    # In[ ]:ประเภทของเนื้อหาในสคริปต์ฉันต้องการให้มันสะอาด มีวิธีใดที่จะทำเช่นนั้น?
                    หากคุณต้องการแปลง*.ipynbไฟล์ทั้งหมดจากไดเรกทอรีปัจจุบันเป็นสคริปต์ไพ ธ อนคุณสามารถเรียกใช้คำสั่งดังนี้:
jupyter nbconvert --to script *.ipynb
นี่เป็นวิธีที่รวดเร็วและสกปรกในการดึงรหัสจาก V3 หรือ V4 ipynb โดยไม่ต้องใช้ ipython มันไม่ได้ตรวจสอบประเภทของเซลล์ ฯลฯ
import sys,json
f = open(sys.argv[1], 'r') #input.ipynb
j = json.load(f)
of = open(sys.argv[2], 'w') #output.py
if j["nbformat"] >=4:
        for i,cell in enumerate(j["cells"]):
                of.write("#cell "+str(i)+"\n")
                for line in cell["source"]:
                        of.write(line)
                of.write('\n\n')
else:
        for i,cell in enumerate(j["worksheets"][0]["cells"]):
                of.write("#cell "+str(i)+"\n")
                for line in cell["input"]:
                        of.write(line)
                of.write('\n\n')
of.close()
newlines='\n'อาร์กิวเมนต์ตัวที่สามในการเรียกไฟล์เอาต์พุตแบบเปิด (Python 3.x)
                    ติดตามตัวอย่างก่อนหน้านี้ แต่ใช้เวอร์ชัน libformat lib ใหม่ :
import nbformat
from nbconvert import PythonExporter
def convertNotebook(notebookPath, modulePath):
  with open(notebookPath) as fh:
    nb = nbformat.reads(fh.read(), nbformat.NO_CONVERT)
  exporter = PythonExporter()
  source, meta = exporter.from_notebook_node(nb)
  with open(modulePath, 'w+') as fh:
    fh.writelines(source.encode('utf-8'))
คุณสามารถทำได้จาก IPython API
from IPython.nbformat import current as nbformat
from IPython.nbconvert import PythonExporter
filepath = 'path/to/my_notebook.ipynb'
export_path = 'path/to/my_notebook.py'
with open(filepath) as fh:
    nb = nbformat.reads_json(fh.read())
exporter = PythonExporter()
# source is a tuple of python source code
# meta contains metadata
source, meta = exporter.from_notebook_node(nb)
with open(export_path, 'w+') as fh:
    fh.writelines(source)
Jupytextยินดีที่มีใน toolchain ของคุณสำหรับการแปลงดังกล่าว มันช่วยให้ไม่เพียง แต่แปลงจากสมุดบันทึกเป็นสคริปต์ แต่คุณสามารถย้อนกลับจากสคริปต์เป็นสมุดบันทึกได้อีกด้วย และยังมีสมุดบันทึกที่ผลิตในรูปแบบที่ดำเนินการ
jupytext --to py notebook.ipynb                 # convert notebook.ipynb to a .py file
jupytext --to notebook notebook.py              # convert notebook.py to an .ipynb file with no outputs
jupytext --to notebook --execute notebook.py    # convert notebook.py to an .ipynb file and run it 
สำหรับการแปลงไฟล์รูปแบบ * .ipynb ทั้งหมดในไดเรกทอรีปัจจุบันเป็นสคริปต์ python แบบวนซ้ำ:
for i in *.ipynb **/*.ipynb; do 
    echo "$i"
    jupyter nbconvert  "$i" "$i"
done
--to scriptอาร์กิวเมนต์เพื่อหลีกเลี่ยงเอาต์พุต HTML เริ่มต้นใน Jupiter 4.4.0
                    ฉันมีปัญหานี้และพยายามหาวิธีแก้ปัญหาออนไลน์ แม้ว่าฉันจะพบวิธีแก้ปัญหาบางอย่าง แต่ก็ยังมีปัญหาเช่นปัญหาที่น่ารำคาญUntitled.txtสร้างอัตโนมัติที่เมื่อคุณเริ่มสมุดบันทึกใหม่จากแผงควบคุม
ดังนั้นในที่สุดฉันก็เขียนทางออกของตัวเอง :
import io
import os
import re
from nbconvert.exporters.script import ScriptExporter
from notebook.utils import to_api_path
def script_post_save(model, os_path, contents_manager, **kwargs):
    """Save a copy of notebook to the corresponding language source script.
    For example, when you save a `foo.ipynb` file, a corresponding `foo.py`
    python script will also be saved in the same directory.
    However, existing config files I found online (including the one written in
    the official documentation), will also create an `Untitile.txt` file when
    you create a new notebook, even if you have not pressed the "save" button.
    This is annoying because we usually will rename the notebook with a more
    meaningful name later, and now we have to rename the generated script file,
    too!
    Therefore we make a change here to filter out the newly created notebooks
    by checking their names. For a notebook which has not been given a name,
    i.e., its name is `Untitled.*`, the corresponding source script will not be
    saved. Note that the behavior also applies even if you manually save an
    "Untitled" notebook. The rationale is that we usually do not want to save
    scripts with the useless "Untitled" names.
    """
    # only process for notebooks
    if model["type"] != "notebook":
        return
    script_exporter = ScriptExporter(parent=contents_manager)
    base, __ = os.path.splitext(os_path)
    # do nothing if the notebook name ends with `Untitled[0-9]*`
    regex = re.compile(r"Untitled[0-9]*$")
    if regex.search(base):
        return
    script, resources = script_exporter.from_filename(os_path)
    script_fname = base + resources.get('output_extension', '.txt')
    log = contents_manager.log
    log.info("Saving script at /%s",
             to_api_path(script_fname, contents_manager.root_dir))
    with io.open(script_fname, "w", encoding="utf-8") as f:
        f.write(script)
c.FileContentsManager.post_save_hook = script_post_save
หากต้องการใช้สคริปต์นี้คุณสามารถเพิ่มเข้าไปได้ ~/.jupyter/jupyter_notebook_config.py :)
โปรดทราบว่าคุณอาจต้องรีสตาร์ท notebook / lab ของ jupyter เพื่อให้สามารถใช้งานได้
มีแพ็คเกจที่ดีมากที่ชื่อว่าnb_devซึ่งออกแบบมาสำหรับการเขียนแพ็คเกจ Python ใน Jupyter Notebooks ชอบnbconvert,มันสามารถเปลี่ยนสมุดบันทึกเป็นไฟล์. py แต่มีความยืดหยุ่นและมีประสิทธิภาพมากขึ้นเนื่องจากมีคุณสมบัติการเขียนเพิ่มเติมที่ดีมากมายที่จะช่วยคุณพัฒนาการทดสอบเอกสารและลงทะเบียนแพ็คเกจบน PyPI มันได้รับการพัฒนาโดยคน fast.ai  
มีเส้นโค้งการเรียนรู้เล็กน้อย แต่เอกสารประกอบนั้นดีและไม่ยากโดยรวม
inputคีย์โดยที่cell_typeเท่ากับ 'code' ลองดูที่รูปแบบ