简体   繁体   中英

How does jupyter notebook import modules which are not in the current working directory?

I am trying to understand how import works in jupyter notebook. My present working directory is "home/username". I have three python modules.

The path names of these modules are as given below.

  1. "/home/username/module1.py"
  2. "/home/username/folder/module2.py"
  3. "/home/username/anaconda3/lib/python3.7/os.py" (which is an inbuilt python module)

Jupyter Notebook:

cell 1: import module1 Works just fine

cell 2: import module2 gives ModuleNotFoundError: No module named 'module2'

cell 3: import os Works just fine

It seems like modules in the working directory can be imported without any problem. So, module1.py can be imported. Modules in other directories that are not packages cannot be imported directly. So, module2.py throws an error. But if this is the case how can os.py , which is not the working directory or in another package in the same directory, be imported directly?

This is really more about how python itself works.

You should be able to import module2 with from folder import module2 . You should declare /home/username/folder as a package by create a blank init file /home/username/folder/__init__py . I recommend naming the package something more unique, like potrus_folder , that way you don't get naming conflicts down the line.

To explain: Python keeps track of what modules it has available through it's path, it is usually set in your environment variables. To see what folders it looks in for modules you can do import sys then print(sys.path) . By default your working directory ( /home/username/ ) will be included, with highest priority (it should thus be either first or last in sys.path , I don't remember). You can add your own folder with sys.path.append('/some/folder') , although it is frowned upon, and you should really add it to your system path, or just keep it as a package in your working directory.

Packages are really just subfolders of paths which have already been added. You access them, as I explained earlier, by using the from X import Y syntax, or if you want to go deeper from XZ import Y . Remember the __init__.py file.

The path of os library is set in environment* Whenever you give import it would search all the directories which are added in your environment + the pwd , so you could just add the directory in environment and that would work

By default /home/username/anaconda3/lib/python3.7/ is added by default at the time of installation since there is where most of the module lies, but you can add urs too

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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