简体   繁体   中英

Import local module in jupyter notebook

A very basic questions on importing modules created locally.

I am unable to import a locally created module. The module exists in the current working directory

在此处输入图片说明

在此处输入图片说明

Am i missing something?

%%capture
%run myModule.ipynb

You will get all functions/variables defined in myModule file. This will also overwrite variables of your current notebook but

from Mymodule import person

has also that effect.

import os 
#if you want to know current working dir
os.getcwd()
#if you want to change
os.chdir('G:/a-2017-master')
# if you want to list dir
os.listdir()

['.DS_Store', '.gitignore', 'cs109a_hw0.ipynb', 'hwassets', 'Labs', 'Lectures', 'Midterms', 'Module.py', 'Projects', 'README.md', 'Sections', ' pycache ']

import os
import Module as m 
a = 10
b = 29
print(f"Addition of {a} and {b} : ",m.add(a,b))

I'm finding local library names must begin with a capital letter. If I keep all my local files in a folder called Code , I can import them; if it's called code , I cannot. (The names of subfolders and subfiles don't seem to suffer that restriction.)

This appears to be a Jupyter restriction, not a Python one -- from the command-line Python repl I can import whatever local .py file I want.

Here is an example from the W3schools Tutorial to create module locally:

  1. In a conda environmnet keras, 'cookie.py' module is created and jupyter notebook is initiated in the same path. Then create a file named 'Importing_module_locally'.

 (keras) ninjawarrior@ninjas-MBP cookiecutter % pwd /Users/ninjawarrior/miniconda3/environments_files/pythonbasics/Python_Tutorial_w3schools/mymodules/cookiecutter

  1. Confirming both module and jupyter notebook file is on the same path.

 (keras) ninjawarrior@ninjas-MBP cookiecutter % ls -lrt total 16 -rw-r--r-- 1 ninjawarrior staff 46 Oct 12 12:47 cookie.py drwxr-xr-x 3 ninjawarrior staff 96 Oct 12 12:50 __pycache__ -rw-r--r-- 1 ninjawarrior staff 751 Oct 12 12:56 Importing_module_locally.ipynb

  1. Enter the below in cookie.py

 def greeting(name): print("Hello, " + name)

`

  1. Enter the below in Import_module_locally

 import mymodule mymodule.greeting("Jonathan")

Result : Hello, Jonathan

Hope this helps !

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