本文介绍了在Jupyter Notebook中运行Python脚本,并传递参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个从Jupyter Notebook运行的简单Python脚本.但是,我传递给它的参数似乎被忽略了,这导致了异常:
I have this simple Python script which I run from my Jupyter Notebook. However the arguments I pass to it seemingly are ignored and this results in an exception:
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
推荐答案
您需要使用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的命令行
or, with a slightly different output:
Note: this uses a !
prefix to indicate command line to jupyter
!ipython two_digits.py 2 3
输出:(使用魔术行%run)
output: (using magic line %run)
running two_digits.py ['two_digits.py', '2', '3']
2 3 5
这篇关于在Jupyter Notebook中运行Python脚本,并传递参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!