Python dynamic import module under a folder

Source: Internet
Author: User

Because there is "user upload script, dynamic Run" needs, so to dynamically import user uploaded modules


So I wrote a function to import dynamically.


#-*-coding:utf-8-*-import osimport sysimport os.pathimport queueimport commandsdef Test (ROOTDIR): #判断传入的路径下是否有 "__i nit__.py "This file is created if not, otherwise the import will not consider this moudle if Os.path.exists (rootdir): arr = Rootdir.spliplit ("/") path Dir = "" for path in Arr:pathdir = Pathdir +path+ "/" If not os.path.exists (pathdir+ "/__init_ _.py "): Commands.getoutput (" Touch "+pathdir+"/__init__.py ") #遍历文件夹找出app_开头的py文件, import, note globals, otherwise the scope is only in this            function under List_dirs = Os.walk (RootDir) for DirName, Subdirlist, fileList in List_dirs:for F in fileList: file_name = f if file_name[0:4] = = "App_" and file_name[-3:] = = ". Py": Imppat H = "" If dirname[-1:]! = "/": Imppath = Dirname.replace ("/", ".") [2:] Else:imppath = Dirname.replace ("/", ".")        [2:-1] Print dirName, "\ n", Imppath if Imppath! = "":            Exe_str = "from" + imppath+ "."                +file_name[0:-3]+ "Import *" Else:exe_str = "from" +file_name[0:-3]+ "Import *" EXEC (Exe_str,globals ()) test ("./app/inapp/") A = Printaa () A.printha ()



./app/inapp/
There's a app_xxx.py file.
Printaa This class, used to test the


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.