在Ipython中运行Python脚本时是否必须指定导入? [英] Do I have to specify import when Python script is being run in Ipython?

查看:162
本文介绍了在Ipython中运行Python脚本时是否必须指定导入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个脚本,我知道我将在Ipython中运行。

I am writing a script that I know I will run in Ipython.

我启动Ipython作为ipython --pylab。

I start Ipython as ipython --pylab.

这会导入numpy,matplotlib等。

This imports numpy, matplotlib, etc.

所以我必须在我的脚本中再次指定这些import语句吗?

So do I have to specify these import statements again in my script?

我没有,我的脚本没有运行。

I did not, and my script did not run.

感谢您的帮助。

推荐答案

- pylab numpy 导入为 * np 。我总是使用 np。来减少混淆。

--pylab imports numpy both as * and np. I always use np. to minimize confusion.

如果我需要 numpy 在我的脚本中,我将通常的 import numpy包含为np 行。这让我可以从shell运行脚本。我也可以在 IPython 中使用 run ... 运行它。我也可以在Ipython或其他一些脚本中执行 import

If I need numpy in my script, I include the usual import numpy as np line. This lets me run the script from the shell. I can also run it with run ... from within IPython. I could also do an import in Ipython or some other script.

我从未尝试省略 import numpy 行,我认为没有必要启动。它不会节省任何时间或空间。养成导入所需内容的习惯,不要认为环境会为你做。

I've never tried omitting the import numpy line, and I don't see any need to start. It doesn't save any time or space. Make a habit of importing what you need, and don't assume the environment will do it for you.

你在IPython中定义和编辑的函数不会需要他们自己的导入声明。

Functions that you define and edit from with in IPython don't need their own import statements.

刚试过这个剧本:

def foo1(x):
   return np.sum(x)

def foo2(x):
   return x.sum()

显然我可以用'run'加载它。并且 foo2(np.array([1,2,3]))有效,因为数组使用自己的方法。但 foo1 会产生 NameError:未定义全局名称'np'

Obviously I can load it with 'run'. And foo2(np.array([1,2,3])) works because the array uses its own method. But foo1 produces a NameError: global name 'np' is not defined.

这篇关于在Ipython中运行Python脚本时是否必须指定导入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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