如何从兄弟目录导入Python脚本?
导入Python脚本的方法有很多种,这里列举了一些常见的方法:
import
语句:import my_module
from
关键字:from my_module import my_function
as
关键字:from my_module import my_function as my_func
*
:from my_module import *
import my_module.my_function
from .my_module import my_function
!
:from !my_module import my_function
!:
:from !my_module import my_function as my_func
::
:from my_module import my_function
importlib
:import importlib.util
import os
file_path = os.path.join(os.path.dirname(__file__), "my_module.py")
spec = importlib.util.spec_from_file_location(file_path, file_path)
my_module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(my_module)
__import__
:import __import__
__import__(module_name, fromlist=[submodule_name])
open()
:with open("my_module.py", "r") as f:
code = f.read()
pickle
:import pickle
with open("my_module.pkl", "rb") as f:
my_module = pickle.load(f)
unpickle
:import pickle
with open("my_module.pkl", "rb") as f:
my_module = pickle.load(f)
os
:import os
module_path = os.path.join(os.path.dirname(__file__), "my_module.py")
my_module = __import__(module_path, fromlist=[""])
sys
:import sys
module_path = os.path.join(os.path.dirname(__file__), "my_module.py")
my_module = __import__(module_path, fromlist=[""])
sys.modules[__name__]=my_module
import_module
:from importlib import import_module
module_path = os.path.join(os.path.dirname(__file__), "my_module.py")
my_module = import_module(module_path)
open_module
:from importlib import open_module
module_path = os.path.join(os.path.dirname(__file__), "my_module.py")
my_module = open_module(module_path)
find_module
:from importlib.find_module import find_module
module_path = os.path.join(os.path.dirname(__file__), "my_module.py")
my_module = find_module(module_path)
load_module
:from importlib.load_module import load_module
module_path = os.path.join(os.path.dirname(__file__), "my_module.py")
my_module = load_module(module_path)
ModuleSpec
:
from importlib.machinery import ModuleSpec
module_path = os.path.join(os.path.dirname(file), "my_module
领取专属 10元无门槛券
手把手带您无忧上云