在Jupyter Notebook中传递参数

Rub*_*iqs 4 python parameter-passing jupyter-notebook

我正在阅读“学习Python的艰难方法”这本书,我在exc13。练习如下:

from sys import argv
# read the WYSS section for how to run this
script, first, second, third = argv

print("The script is called:", script)
print("Your first variable is:", first)
print("Your second variable is:", second)
print("Your third variable is:", third)
Run Code Online (Sandbox Code Playgroud)

但是当我运行它时,出现以下错误

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-16-b23ff5448130> in <module>()
      1 from sys import argv
      2 # read the WYSS section for how to run this
----> 3 script, first, second, third = argv
      4 
      5 print("The script is called:", script)

ValueError: not enough values to unpack (expected 4, got 3)
Run Code Online (Sandbox Code Playgroud)

这是因为argv未填充。该书说使用终端,您可以在终端中输入以下内容来传递参数:

python ex13.py first 2nd 3rd
Run Code Online (Sandbox Code Playgroud)

在终端。但是我怎么只能使用Jupyter笔记本来做到这一点。

Jam*_*mes 5

在Jupyter Notebook中,您可以使用cell magic创建文件%%file。然后,您可以使用cell magic将命令发送到外壳以运行文件%%!

要写出文件:

%%file ex13.py
from sys import argv
# read the WYSS section for how to run this
script, first, second, third = argv

print("The script is called:", script)
print("Your first variable is:", first)
print("Your second variable is:", second)
print("Your third variable is:", third)
Run Code Online (Sandbox Code Playgroud)

要运行文件:

%%!
python ex13.py first 2nd 3rd
Run Code Online (Sandbox Code Playgroud)

您应该看到想要的结果。捕获打印输出,并以列表形式返回,每个打印行一个元素。