在Jupyter Notebook中传递参数

时间:2018-01-30 12:53:15

标签: 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)

但是当我运行这个时,我收到了以下错误

---------------------------------------------------------------------------
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)

这是因为argv没有填写。书中说使用终端,在终端中你可以输入以下参数传递:

python ex13.py first 2nd 3rd

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

1 个答案:

答案 0 :(得分:5)

在Jupyter Notebook中,您可以使用单元格魔术%%file创建文件。然后,您可以使用单元格魔术%%!向shell发送命令以运行该文件。

写出文件:

%%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)

运行文件:

%%!
python ex13.py first 2nd 3rd

您应该会看到您要查找的结果。打印输出被捕获并作为列表返回,每个打印行一个元素。