How to import/open numpy module to IDLE

╄→гoц情女王★ 提交于 2019-12-02 21:14:05

The title is misleading in the following sense. You do not want to import a module to IDLE. You want to import it to the python that is running your code. When running IDLE, this currently is the same python running IDLE. To find which python is running, the following should work anywhere on any recent python, either directly or in an IDE:

import sys; print(sys.executable)

Running this in IDLE on my Windows machine, I get

C:\Programs\Python36\pythonw.exe

(The w suffix is a Windows-specific variant binary for running GUI programs without an empty console window popping up. It should be omitted in what follows.)

To import a module to a particular python, it must be installed for that particular python. The easiest way to do that is to run pip with that particular python in a console. For instance, given the executable above:

C:\Programs\Python36> python -m pip install numpy

On *nix, one may have to first run, I believe, python -m ensurepip to install pip itself for that python.

About import pip; pip.main: pip is designed as a command line utility that initializes, performs one function, and exits. main() is an intentionally undocumented internal implementation detail. The author of pip discourages its use as it is designed for one call followed by program exit. Multiple calls will not work right when internal data get out of sync with installed files.

Tadhg McDonald-Jensen

To install packages without affecting anaconda's configuration you can use pip from within IDLE:

import pip
pip.main(["install","numpy"])

Although because IDLE can be a little slow with refresh rate (at least it is on my mac) it can be a great speed boost to hide the output until the end:

import sys
import pip
import io

stdout_real = sys.stdout
sys.stdout = io.StringIO()
try:
    pip.main(["install","kfksnaf"])
finally:
    stdout_real.write(sys.stdout.getvalue())
    sys.stdout = stdout_real

note that this means that all standard output will be displayed after the error text which might be confusing if something goes wrong so do try it normally first and only do this if it lags badly.

On the other hand, it seems like anaconda has commandeered a lot of the functionalities of the python installed from python.org, to reduce it's impact on your machine you should take a look at Use Default Python Rather than Anaconda Installation When Called from the Terminal although this might then break functionalities of anaconda which may then in turn make it difficult to switch back if you want to do so.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!