åå¿é²ï¼Pythonãã¡ã¤ã«ããã«ãã¹ã§importããæ¹æ³ï¼sys.path.append()ã使ããªãæ¹æ³ï¼
Pythonãã¡ã¤ã«å ã§å¥ã®Pythonãã¡ã¤ã«ãimportããéã åããã©ã«ãå ããµããã©ã«ãå ã«ããå ´åã¯ã以ä¸ã§importã§ãã¾ãã
# myscript.pyãimportãã import myscript # ãµããã©ã«ãã®å ´å import folder.myscript
ã¾ããä¸è¨ä»¥å¤ã®ãã©ã«ãã®Pythonãã¡ã¤ã«ãimportããå ´åãä¸è¬çã«ã¯sys.path.append()ã使ã£ã¦ãã¡ã¤ã«ã®ãã£ã¬ã¯ããªãpathã«è¿½å ããæ¹æ³ãç¨ãã¾ãã
import sys sys.path.append(folder_path) import myscript
ä¸æ¹ã§ãpathã追å ããããªãå ´é¢ãããã¨æãã¾ãã ãã®å ´åãimportlib.utilãç¨ãã以ä¸ã®æ¹æ³ãå¯è½ã§ãã
import importlib.util # Function to dynamically import a module given its full path def import_module_from_path(path): # Create a module spec from the given path spec = importlib.util.spec_from_file_location("module_name", path) # Load the module from the created spec module = importlib.util.module_from_spec(spec) # Execute the module to make its attributes accessible spec.loader.exec_module(module) # Return the imported module return module # Example usage module_path = '/path/to/your/module.py' module = import_module_from_path(module_path)
åèãµã¤ãï¼Dynamically Import a Module by Full Path in Python — Using importlib.util & sys | by Doug Creates | Medium