[英]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.您将获得 myModule 文件中定义的所有函数/变量。 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 '] ['.DS_Store', '.gitignore', 'cs109a_hw0.ipynb', 'hwassets', 'Labs', 'Lectures', 'Midterms', 'Module.py', 'Projects', 'README.md', '节',' 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;如果我将所有本地文件保存在一个名为
Code
的文件夹中,我就可以导入它们; if it's called code
, I cannot.如果它被称为
code
,我不能。 (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.这似乎是 Jupyter 限制,而不是 Python 限制——从命令行 Python repl 我可以导入我想要的任何本地
.py
文件。
Here is an example from the W3schools Tutorial to create module locally:以下是 W3schools 教程中用于在本地创建模块的示例:
(keras) ninjawarrior@ninjas-MBP cookiecutter % pwd /Users/ninjawarrior/miniconda3/environments_files/pythonbasics/Python_Tutorial_w3schools/mymodules/cookiecutter
(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
def greeting(name): print("Hello, " + name)
` `
import mymodule mymodule.greeting("Jonathan")
Result : Hello, Jonathan结果:你好,乔纳森
Hope this helps !希望这可以帮助 !
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.