[英]Run multiple .py files in a jupyter notebook
Basically, I get some python files in a same directory of my main jupyter program, and inside this main program, I need a cell that will run all the other python files.基本上,我在主 jupyter 程序的同一目录中获得了一些 python 个文件,在这个主程序中,我需要一个单元格来运行所有其他 python 个文件。
*obs.: the py files are generated dynamically *obs.: py文件是动态生成的
I've tried to use something like我试过用类似的东西
%run *.py
or something like:或类似的东西:
while True: %run "script1.py"
but I need to set the name of the script dynamically但我需要动态设置脚本的名称
This will run every .py
script file in the current directory where the notebook is run, even those script files that the subsequent scripts make in the same directory:这将运行运行笔记本的当前目录中的每个.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)
I tried to make this universal by not relying on any special packages that allow handling shell wildcards.我试图通过不依赖任何允许处理 shell 通配符的特殊包来实现这一点。
You can see it demonstrated in action at the bottom of this notebook .您可以在本笔记本的底部看到它的实际演示。 The initial cells in that notebook set things up by making two scripts that each spawn three more scripts each.该笔记本中的初始单元格通过制作两个脚本来设置,每个脚本都会产生三个以上的脚本。 Each script is run once.每个脚本运行一次。
The header of the notebook contains instructions on how you can go here and press launch binder
to get a session served by MyBinder.org where that notebook will work.笔记本的 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 it actively. 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.