将变量从Jupyter笔记本传递到python脚本 [英] Pass variable from Jupyter notebook to python script

查看:182
本文介绍了将变量从Jupyter笔记本传递到python脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Jupyter笔记本中定义一个变量,然后将其传递给python脚本.

I would like to define a variable in a Jupyter notebook and then pass it to a python script.

例如,在笔记本电脑上:

For example, in the notebook:

a = [1, 2, 3, 4]

%run example.py
print foo

在example.py

And in example.py

b = [5, 8, 9, 10]
foo = a + b

当然,这会返回错误,因为在example.py中尚未定义a.但是,如果exam​​ple.py代替了

Of course, this returns an error because a has not been defined in example.py. However, if example.py has instead

a = [1, 2, 3, 4]
b = [5, 8, 9, 10]
foo = a + b

然后,即使在Jupyter笔记本本身中未定义foo,Jupyter笔记本也可以在脚本运行后查看" foo并将其打印出来.

Then the Jupyter notebook can "see" foo after the script is run and print it, even though foo was not defined in the Jupyter notebook itself.

为什么python脚本在Jupyter笔记本环境中看不到变量?以及如何将变量从笔记本环境传递到脚本?

Why can't the python script see variables in the Jupyter notebook environment? And how can I pass a variable from the notebook environment to the script?

推荐答案

python脚本无法在jupyter笔记本环境中查看变量,因为它们是不同的程序.当您使用魔术命令时,它将作为单独的程序运行.如果要将变量传递给方法,则可以选择将其转换为函数.说添加

The python script cannot see the variables in jupyter notebook environment because they are different programs. When you use magic commands it runs as a separate program. If you want to pass the variable to the method then you have the option to convert that into a function. Say add

def add(a):
  b = [5, 8, 9, 10]
  foo = a + b

然后在Jupyter中您可以执行此操作

Then in Jupyter you can do this

from example import add
add(a)

您必须将它们带入同一程序.否则,您可以传递参数并使用argv在脚本中解析它们.但是我不希望您那样做,因为他们希望他们彼此见面.

You have to bring them in the same program. Otherwise you can pass the arguments and parse them in the script using argv. But I don't think you want to do that as you want them to see each other.

这篇关于将变量从Jupyter笔记本传递到python脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆