程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python dynamically imports self written modules or classes

編輯:Python

background : stay python If you want to write your own py The file is reused as a module , Import other files , You may need to create a specific directory as package, And then all of the py All files are placed in this directory , And add the directory in the environment variable configuration , For details, please refer to my other blog :python: Write your own module import_Wsyoneself The blog of -CSDN Blog _python how import My own module

But this is too rigid , Not flexible enough , Files to be moved , And the portability is not good , The following is a method to import files in the directory where the code is located

from os import sys, path
PARENT_DIR = path.dirname(path.dirname(path.abspath(__file__)))
sys.path.append(path.join(PARENT_DIR,"mycode"))
from vanilla_encoder import my_vanilla_autoencoder,draw_result

  The above code is just an example , You can step through the test , see PARENT_DIR, And then use path.join Splice into what you want to be package The catalog of , The last sentence is from the vanilla_encoder.py Import two functions into the file

The measured available ( Especially for pycharm That kind of software that is very troublesome to import directories is very practical )


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved