简体   繁体   English

在 Jupyter Notebook 中运行 Python 脚本,并传递参数

[英]Running a Python script in Jupyter Notebook, with arguments passing

I have this simple Python script which I run from my Jupyter Notebook.我有一个从 Jupyter Notebook 运行的简单 Python 脚本。 However the arguments I pass to it seemingly are ignored and this results in an exception:然而,我传递给它的参数似乎被忽略了,这导致了一个异常:

two_digits.py两位数.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

You need to use sys.argv instead of sys.stdin.read() :您需要使用sys.argv而不是sys.stdin.read()

two_digits.py两位数.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)

command line / jupyter magic line:命令行 / jupyter 魔术线:

%run two_digits 3 5

or, with a slightly different output:或者,输出略有不同:
Note: this uses a !注意:这使用了一个! prefix to indicate command line to jupyter前缀以指示 jupyter 的命令行

!ipython two_digits.py 2 3

output: (using magic line %run)输出:(使用魔术线 %run)

running two_digits.py ['two_digits.py', '2', '3']
2 3 5
%%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')

We have several options:我们有几个选择:

%%!
python calc.py 7 3 +

or或者

%run calc.py 7 3 +

or或者

!python calc.py 7 3 +

or with the path in output或输出中的路径

!ipython calc.py 7 3 +

To access the output use the first way with %%!要访问输出,请使用%%! . . Output is a list (IPython.utils.text.SList)输出是一个列表 (IPython.utils.text.SList)

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

[Out 1]
['10']

Now you can use underscore '_'现在您可以使用下划线“_”

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

[Out 2]
5.0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM