简体   繁体   中英

How do I import python class from a module located within file directory named '@file_directory' or directory with special characters?

I'm trying to import a class from a module named my_classes.py . Problem is, it's located within a directory called @file_directory .

So the structure is, I have main.py at the top of the project directory, and also a directory called lib at the same level. Within 'lib' there is subdirectory named '@file_directory' and within it a module 'my_classes' as shown below.

-> main.py
-> /lib
   -> lib_other_files.py
   -> /@file_directory
      -> my_classes.py

What I can usually do is

from lib.@file_directory.myclasses import cust_class

But because the @ symbol is a wrapper symbol, it prevents me from importing files from '@file_directory'. The simple soultion is of course, just change the directory name but I want to keep the file name/don't have the rights to change it in the project. Is there a way to use like a escpae character to import module from a directory with special characters?

Another possibility: use the __import__() built-in function . This is essentially removing the overhead of the normal import command, but it allows you more flexibility in package-naming because it just takes a string as an argument - and that string can escape the otherwise-invalid characters.

So, this code should work:

_temp = __import__("lib.@file_directory.myclasses", globals(), locals(), ['cust_class'], 0)
cust_class = _temp.cust_class

Edit: The python standard library recommends using importlib instead. The same code would look like this in that:

import importlib
cust_class = importlib.import_module("lib.@file_directory.myclasses", "cust_class")

You can not import modules with characters like the '@' symbol... however, using execfile may be an appropriate workaround for you.

Tested with Python 2.7.5

my_classes.py example code:

def printMe():
    print "foo from my_classes"

main.py example code:

execfile("./lib/@file_directory/my_classes.py")
printMe()

Executing main.py prints out:

>>python main.py
foo from my_classes

Whats happening is main.py will run the my_classes.py file and now you can directly reference functions or any relevant code from my_classes.py.

Python 3.X Equivalent

I dont have python 3 installed but they did remove execfile.. the alternative for execfile would be:

exec(open("./lib/@file_directory/my_classes.py").read())

Hope this helps you accomplish your needs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM