在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笔记本来做到这一点。

詹姆士

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

要运行文件:

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

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章