【问题标题】:Running a Python script in Jupyter Notebook, with arguments passing在 Jupyter Notebook 中运行 Python 脚本,并传递参数
【发布时间】:2018-07-27 05:02:15
【问题描述】:

我有一个从 Jupyter Notebook 运行的简单 Python 脚本。但是,我传递给它的参数似乎被忽略了,这会导致异常:

two_digits.py

import sys
input = sys.stdin.read()
tokens = input.split()
a = int(tokens[0])
b = int(tokens[1])
print(a + b)

%run two_digits 3 5

ndexError                                Traceback (most recent call last)
D:\Mint_ns\two_digits.py in <module>()
      5 tokens = input.split()
      6 
----> 7 a = int(tokens[0])
      8 
      9 b = int(tokens[1])

IndexError: list index out of range

【问题讨论】:

    标签: python python-3.x jupyter-notebook jupyter


    【解决方案1】:

    您需要使用sys.argv 而不是sys.stdin.read()

    two_digits.py

    import sys
    args = sys.argv  # a list of the arguments provided (str)
    print("running two_digits.py", args)
    a, b = int(args[1]), int(args[2])
    print(a, b, a + b)
    

    命令行/jupyter魔法线:

    %run two_digits 3 5
    

    或者,输出略有不同:
    注意:这使用 ! 前缀来指示 jupyter 的命令行

    !ipython two_digits.py 2 3
    

    输出:(使用魔法线 %run)

    running two_digits.py ['two_digits.py', '2', '3']
    2 3 5
    

    【讨论】:

    • 很高兴知道,如果您的 .py 在不同的文件夹中:更改工作目录,然后运行:%pwd #查看当前工作目录 %cd #更改为您想要的目录
    【解决方案2】:
    %%file calc.py
    
    from sys import argv
    
    script, a, b, sign = argv
    
    if sign == '+': 
        print(int(a) + int(b))
    elif sign == '-':
        print(int(a) - int(b))
    else:
        print('I can only add and subtract')
    

    我们有几种选择:

    %%!
    python calc.py 7 3 +
    

    %run calc.py 7 3 +
    

    !python calc.py 7 3 +
    

    或输出路径

    !ipython calc.py 7 3 +
    

    要访问输出,请使用%%! 的第一种方式。输出是一个列表(IPython.utils.text.SList)

    [In 1]
    %%!
    python calc.py 7 3 +
    
    [Out 1]
    ['10']
    

    现在你可以使用下划线'_'

    [In 2]
    int(_[0])/2  # 10 / 2
    
    [Out 2]
    5.0
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-19
      • 1970-01-01
      • 1970-01-01
      • 2020-04-08
      • 1970-01-01
      相关资源
      最近更新 更多