简体   繁体   English

进入python或ipython解释器时自动导入模块

[英]Automatically import modules when entering the python or ipython interpreter

I find myself typing import numpy as np almost every single time I fire up the python interpreter.我发现自己几乎每次启动 python 解释器时都输入import numpy as np How do I set up the python or ipython interpreter so that numpy is automatically imported?如何设置 python 或 ipython 解释器以便自动导入 numpy?

For ipython, there are two ways to achieve this. 对于ipython,有两种方法可以实现此目的。 Both involve ipython's configuration directory which is located in ~/.ipython . 两者都涉及ipython的配置目录,该目录位于~/.ipython

  1. Create a custom ipython profile. 创建一个自定义的ipython配置文件。
  2. Or you can add a startup file to ~/.ipython/profile_default/startup/ 或者您可以将启动文件添加到~/.ipython/profile_default/startup/

For simplicity, I'd use option 2. All you have to do is place a .py or .ipy file in the ~/.ipython/profile_default/startup directory and it will automatically be executed. 为简单起见,我将使用选项2。所有您需要做的是将.py.ipy文件放在~/.ipython/profile_default/startup目录中,它将自动执行。 So you could simple place import numpy as np in a simple file and you'll have np in the namespace of your ipython prompt. 因此,您可以import numpy as np到一个简单文件中,然后在ipython提示符的命名空间中包含np。

Option 2 will actually work with a custom profile, but using a custom profile will allow you to change the startup requirements and other configuration based on a particular case. 选项2实际上将与自定义配置文件一起使用,但是使用自定义配置文件将使您可以根据特定情况更改启动要求和其他配置。 However, if you'd always like np to be available to you then by all means put it in the startup directory. 但是,如果您始终希望np可供您使用,则一定要将其放在启动目录中。

For more information on ipython configuration. 有关ipython配置的更多信息。 The docs have a much more complete explanation. 文档有一个更完整的解释。

Use the environment variable PYTHONSTARTUP . 使用环境变量PYTHONSTARTUP From the official documentation: 从官方文档中:

If this is the name of a readable file, the Python commands in that file are executed before the first prompt is displayed in interactive mode. 如果这是可读文件的名称,则在以交互方式显示第一个提示之前,将执行该文件中的Python命令。 The file is executed in the same namespace where interactive commands are executed so that objects defined or imported in it can be used without qualification in the interactive session. 在与执行交互式命令相同的名称空间中执行文件,以便在其中定义或导入的对象可以在交互式会话中使用而无需限定。

So, just create a python script with the import statement and point the environment variable to it. 因此,只需使用import语句创建一个python脚本,然后将环境变量指向该脚本即可。 Having said that, remember that 'Explicit is always better than implicit', so don't rely on this behavior for production scripts. 话虽如此,请记住,“显式总是比隐式更好”,因此不要在生产脚本中依赖此行为。

For Ipython, see this tutorial on how to make a ipython_config file 对于Ipython,请参阅教程,了解如何制作ipython_config文件

I use a ~/.startup.py file like this: 我使用〜/ .startup.py文件,如下所示:

# Ned's .startup.py file
print("(.startup.py)")
import datetime, os, pprint, re, sys, time
print("(imported datetime, os, pprint, re, sys, time)")

pp = pprint.pprint

Then define PYTHONSTARTUP=~/.startup.py, and Python will use it when starting a shell. 然后定义PYTHONSTARTUP =〜/ .startup.py,Python将在启动shell时使用它。

The print statements are there so when I start the shell, I get a reminder that it's in effect, and what has been imported already. 打印语句在那里,因此当我启动外壳程序时,会提醒我它已经生效,并且已经导入了什么内容。 The pp shortcut is really handy too... pp快捷键也非常方便...

While creating a custom startup script like ravenac95 suggests is the best general answer for most cases, it won't work in circumstances where you want to use a from __future__ import X . 尽管在大多数情况下,创建诸如ravenac95 建议之类的自定义启动脚本是最佳的通用答案,但在要使用from __future__ import X情况下,它将无法正常工作。 If you sometimes work in Python 2.x but want to use modern division, there is only one way to do this. 如果您有时在Python 2.x中工作,但想使用现代除法,则只有一种方法可以做到这一点。 Once you create a profile, edit the profile_default (For Ubuntu this is located in ~/.ipython/profile_default ) and add something like the following to the bottom: 创建配置文件后,编辑profile_default (对于Ubuntu,它位于~/.ipython/profile_default ),并在底部添加类似以下内容:

c.InteractiveShellApp.exec_lines = [
    'from __future__ import division, print_function',
    'import numpy as np',
    'import matplotlib.pyplot as plt',
    ]

As a simpler alternative to the accepted answer, on linux: 在Linux上,作为可接受答案的一种更简单的选择:

just define an alias, eg put alias pynp='python -i -c"import numpy as np"' in your ~/.bash_aliases file. 只需定义一个别名即可,例如,将〜/ .bash_aliases文件中的alias pynp='python -i -c"import numpy as np"' You can then invoke python+numpy with pynp , and you can still use just python with python . 然后,您可以使用pynp调用python + numpy,并且仍然可以仅将python与python Python scripts' behaviour is left untouched. Python脚本的行为保持不变。

You can create a normal python script as import_numpy.py or anything you like 您可以将普通的python脚本创建为import_numpy.py或任何您喜欢的东西

#!/bin/env python3
import numpy as np

then launch it with -i flag. 然后使用-i标志启动它。

python -i import_numpy.py

Way like this will give you flexibility to choose only modules you want for different projects. 这样,您便可以灵活地只为不同的项目选择所需的模块。

As ravenac95 mentioned in his answer , you can either create a custom profile or modify the default profile. 正如ravenac95在他的回答中提到的那样,您可以创建自定义配置文件或修改默认配置文件。 This answer is quick view of Linux commands needed to import numpy as np automatically. 该答案是快速查看import numpy as np自动import numpy as np所需的Linux命令的视图。

If you want to use a custom profile called numpy , run: 如果要使用名为numpy的定制概要文件,请运行:

ipython profile create numpy
echo 'import numpy as np' >> $(ipython locate profile numpy)/startup/00_imports.py
ipython --profile=numpy

Or if you want to modify the default profile to always import numpy: 或者,如果您想修改默认配置文件以始终导入numpy:

echo 'import numpy as np' >> $(ipython locate profile default)/startup/00_imports.py
ipython

Check out the IPython config tutorial to read more in depth about configuring profiles. 查看IPython配置教程 ,以深入了解有关配置配置文件的内容。 See .ipython/profile_default/startup/README to understand how the startup directory works. 请参阅.ipython/profile_default/startup/README以了解启动目录的工作方式。

My default ipython invocation is 我的默认ipython调用是

ipython --pylab --nosep --InteractiveShellApp.pylab_import_all=False

--pylab has been a ipython option for some time. --pylab一直是ipython选项。 It imports numpy and (parts of) matplotlib . 它导入numpymatplotlib (的一部分)。 I've added the --Inter... option so it does not use the * import, since I prefer to use the explicit np.... . 我添加了--Inter...选项,因此它不使用*导入,因为我更喜欢使用显式的np....

This can be a shortcut, alias or script. 这可以是快捷方式,别名或脚本。

I created a little script to get ipython initialized with the code you want.我创建了一个小脚本来用你想要的代码初始化 ipython。

  • Create a start.ipy file at your project root folder.在您的项目根文件夹中创建一个start.ipy文件。
  • Edit the created file with all the things you need to get into ipython.使用进入 ipython 所需的所有内容编辑创建的文件。
  • ipython profile create <your_profile_name> . ipython profile create <your_profile_name> Tip, do not add the word "profile" to the name because ipython already includes it.提示,不要在名称中添加“profile”一词,因为 ipython 已经包含它。
  • cp start.ipy ~/.ipython/profile_<your_profile_name>/startup/start.ipy
  • Run ipython --profile=<your_profile_name> everytime you need everything loaded in ipython.每次需要在 ipython 中加载所有内容时运行ipython --profile=<your_profile_name>

With this solution, you don't need to set any env variable up.使用此解决方案,您无需设置任何环境变量。 You will need to copy the start.ipy file to the ipython folder every time you modify it, though.不过,每次修改ipython文件时都需要将它复制到start.ipy文件夹中。

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

相关问题 模块在python解释器中工作,但在iPython中不工作 - Modules work in python interpreter but not in iPython 自动将当前目录中的所有模块导入python交互式解释器 - Automatically import all modules in the current directory into python interactive interpreter 输入python口译员时打印问候语 - print greeting message when entering python interpreter ipython notebook可以导入pyd模块,但是python解释器不能 - ipython notebook can import a pyd module but the python interpreter can't 修改 Python/PIP 导入失败时自动安装模块 - Modify Python/PIP to automatically install modules when failed to import 使用-c选项时如何自动告诉python导入模块? - How to tell python import modules automatically when use the -c option? 使用iPython时如何为python解释器提供选项 - How to supply options to the python interpreter when using iPython 尽管安装在使用过的 python 解释器中,但无法在 pycharm 中导入模块 - Unable to import modules in pycharm in spite being installed in the used python interpreter python作为脚本运行时导入失败,但在iPython中却没有? - import fails when running python as script, but not in iPython? 为什么不能引用看似由解释器自动加载的模块而没有额外的`import`语句? - Why can't you reference modules that appear to be automatically loaded by the interpreter without an additional `import` statement?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM