如何在bash脚本中调用Jupyter Notebook函数?

huangapple go评论75阅读模式
英文:

How do I call a Jupyter Notebook function within a bash script?

问题

如果我有一个包含函数的Jupyter Notebook文件,如何从bash脚本或Linux命令提示符中调用该函数?
我可以成功地使用
ipython -c "%run test.ipynb"
来运行test.ipynb中的Python代码,这对于我不需要发送任何参数的情况非常有用。

但是,如果我有一个名为another_test.ipnyb的文件,其中包含一个名为find_error(n)的函数,并且我想从bash脚本(或Linux命令提示符)中调用find_error并发送适当的输入参数值,我该如何操作?

我知道可以使用
python -c "import another_test; another_test.find_error(${n})"
来调用another_test.py中的find_error(n)函数。
但在这种情况下,我更喜欢使用ipynb文件。

英文:

If I have a Jupyter Notebook file that contains a function, how do I call that function from a bash script or Linux command prompt?
I can successfully use
ipython -c "%run test.ipynb"
to run the python code in test.ipynb, which I can use for cases where I don't need to send any arguments in.

But if I have a file named another_test.ipnyb with function called find_error(n) and I want to call find_error from a bash script (or Linux command prompt), sending the appropriate value for the input argument, how do I do that?

I know I can use
python -c "import another_test; another_test.find_error(${n})"
to call function find_error(n) in another_test.py.
But I prefer to use ipynb files in this case.

答案1

得分: 1

我不认为你实际上可以做到这一点。我相当肯定那些笔记本文件只是JSON。也许你可以在你的脚本中将这个笔记本转换成Python,然后用你的输入调用生成的Python脚本。

类似这样的方式:

#!/bin/bash

# 将Jupyter笔记本转换为Python脚本
jupyter nbconvert --to script another_test.ipynb

# 重命名Python脚本
mv another_test.py another_test_script.py

# 用输入参数调用Python函数
python -c "from another_test_script import find_error; print(find_error($1))"

然后使用./myscript.sh "my error input"进行调用。

英文:

I don't think you can actually do this. I'm pretty sure those notebook files are just JSON. Maybe you can convert this notebook to python in your script, then call the resulting python script with your input.

Something like this

#!/bin/bash

# Convert the Jupyter notebook to a Python script
jupyter nbconvert --to script another_test.ipynb

# Rename the Python script
mv another_test.py another_test_script.py

# Call the Python function with the input argument
python -c "from another_test_script import find_error; print(find_error($1))"

Then call with ./myscript.sh "my error input".

huangapple
  • 本文由 发表于 2023年7月28日 03:31:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/76782878.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定