簡體   English   中英

在 jupyter 筆記本中運行多個 .py 文件

[英]Run multiple .py files in a jupyter notebook

基本上,我在主 jupyter 程序的同一目錄中獲得了一些 python 個文件,在這個主程序中,我需要一個單元格來運行所有其他 python 個文件。

*obs.: py文件是動態生成的

我試過用類似的東西

%run *.py

或類似的東西:

while True: %run "script1.py"

但我需要動態設置腳本的名稱

這將運行運行筆記本的當前目錄中的每個.py腳本文件,甚至是后續腳本在同一目錄中創建的那些腳本文件:

import os
import fnmatch
import glob


executed_scripts = []
extension_to_match = ".py"

def execute_script(s):
    %run {s}

while set(executed_scripts) != set(glob.glob(f"*{extension_to_match}")):
    for file in os.listdir('.'):
        if fnmatch.fnmatch(file, '*'+extension_to_match):
            if file not in executed_scripts:
                execute_script(file)
                executed_scripts.append(file)

我試圖通過不依賴任何允許處理 shell 通配符的特殊包來實現這一點。

您可以在本筆記本的底部看到它的實際演示。 該筆記本中的初始單元格通過制作兩個腳本來設置,每個腳本都會產生三個以上的腳本。 每個腳本運行一次。

筆記本的 header 包含有關如何在此處使用 go 並按下launch binder以獲取由 MyBinder.org 提供的 session 的說明,該筆記本將在其中運行。 Once the session launches, you can type :curl -OL https.//gist.githubusercontent.com/fomightez/bcbeaa34f258e6ab959c842438077cb8/raw/4aa21f205c663688ef552acc38293d574c9667c4/for_so75075576.ipynb in a notebook cell to fetch the notebook in sessions there and then open it and run它積極地。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM