使用Jupyter笔记本中的输入运行python脚本
我已经创建了以下名为使用Jupyter笔记本中的输入运行python脚本,python,input,jupyter-notebook,Python,Input,Jupyter Notebook,我已经创建了以下名为week1_1.py的Python脚本: import sys input = sys.stdin.read() tokens = input.split() a = int(tokens[0]) b = int(tokens[1]) print(a + b) 然而,当我在Jupyter笔记本中调用它时,我得到以下例外: %run -i week1_1 2 3 --------------------------------------------------------
week1_1.py
的Python脚本:
import sys
input = sys.stdin.read()
tokens = input.split()
a = int(tokens[0])
b = int(tokens[1])
print(a + b)
然而,当我在Jupyter笔记本中调用它时,我得到以下例外:
%run -i week1_1 2 3
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
D:\Mint_ns\week1_1.py in <module>()
8 input = sys.stdin.read()
9 tokens = input.split()
---> 10 a = int(tokens[0])
11 b = int(tokens[1])
12 print(a + b)
IndexError: list index out of range
%run-i周1_12 3
---------------------------------------------------------------------------
索引器回溯(最后一次最近调用)
D:\Mint\u ns\week1\u 1.py in()
8输入=sys.stdin.read()
9令牌=input.split()
--->10 a=int(令牌[0])
11 b=int(令牌[1])
12打印(a+b)
索引器:列表索引超出范围
导致此异常的原因可能是什么?一种更简单的方法是使用
原始输入,而不是stdin.read
:
tokens = raw_input().split()
a = int(tokens[0])
b = int(tokens[1])
print(a + b)
更简单的方法是使用原始输入
而不是标准输入。读取
:
tokens = raw_input().split()
a = int(tokens[0])
b = int(tokens[1])
print(a + b)
您可以使用input()
替换sys.stdin.read()
为什么不能使用sys.stdin.read()
?sys.stdin.read()。所以我猜当你在jupyter笔记本中运行它时,当你运行单元格时,它会读到EOF。(我不确定。)
但是input()
将在jupyter笔记本中正常运行。我建议您在获取键盘输入时使用input()
而不是sys.stdin.read()
您可以使用input()
替换sys.stdin.read()
为什么不能使用sys.stdin.read()
?sys.stdin.read()。所以我猜当你在jupyter笔记本中运行它时,当你运行单元格时,它会读到EOF。(我不确定。)
但是input()
将在jupyter笔记本中正常运行。在获取键盘输入时,我建议您使用input()
而不是sys.stdin.read()
。要在Jupyter笔记本中获取用户输入,请使用input()
(或者对于Python 2使用raw\u input()
):
希望这有帮助 若要在Jupyter笔记本中获取用户输入,请使用input()
(或Python 2的raw\u input()
):
希望这有帮助 或:
print(sum(int(i) for i in input().split()))
示例输出:
1 1
2
或:
示例输出:
1 1
2
print(tokens)
或print(len(tokens))
显示什么<代码>令牌
可能是一个空列表。打印(令牌)
或打印(len(令牌))
显示什么<代码>令牌
可能是一个空列表。