【问题标题】:Passing arguments in Jupyter Notebook在 Jupyter Notebook 中传递参数
【发布时间】:2018-01-30 12:53:14
【问题描述】:

我正在关注“Learn Python The Hard Way”一书,我在 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 笔记本来做到这一点。

【问题讨论】:

    标签: python parameter-passing jupyter-notebook


    【解决方案1】:

    在 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
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多