Imp.load_source is a different file than .py, but .py also exists in this directory

I have this setting:

File: a.ext1 a.py

a.ext1 for some reason loads a.py, but as a mechanism I need to download a.ext1 file.

I can get it to work fine in py3, but I can't get it to work in py2.

Here is my python2 attempt: ** This is the main thread, of course, there is more code around it.

file = os.path.abspath(os.path.expanduser('a.ext1') directory = os.path.dirname(file) sys.path.append(directory) fullname = 'my.name.space.a' sys.modules['my.name.space'] = imp.new_module('my.name.space') x = imp.load_source(fullname,file) 

Now, if I do this; x, he will tell me:

 module 'my.name.space' from '<path>/a.ext1' 

but if I do dir (x), it gives me stuff from a.py. I want him to give me the material from the .ext1 file.

How can I make this work on py2?

Here's how it works on py3:

 file = os.path.abspath(os.path.expanduser('a.ext1')) directory = os.path.dirname(file) sys.path.append(directory) fullname = 'my.name.space.a' loader = importlib.machinery.SourceFileLoader(fullname = fullname, path = file) x = loader.load_module() 

Now x is exactly what I want, a.ext1 file, not .py

Any idea how I can get this to work for py2?

(Btw I read everything I could find on this topic in a stack overflow, but .py never existed)

+5
source share
1 answer

I don't know about mumbo jumbo with creating empty modules and extra paths, but the same thing works for me on 2.7. There should definitely not be a problem with a simple standalone example.

I would say that your a.py loaded in my.name.space.a , as well as in another place in the program, in which case this content conflicts with what you load under the same module name. There can only be one instance of a global module with a given name at a time, for example:

a.py:

 py_stuff = 1 

a.ext1

 ext1_stuff = 1 

test-ok.py:

 import imp x = imp.load_source('a', 'a.ext1') print(x) # <module 'a' from 'a.ext1'> print(dir(x)) # ['__builtins__', ..., 'ext1_stuff'] 

test-not-ok.py:

 import imp import a x = imp.load_source('a', 'a.ext1') print(x) # <module 'a' from 'a.ext1'> print(dir(x)) # ['__builtins__', ..., 'ext1_stuff', 'py_stuff'] 
0
source

Source: https://habr.com/ru/post/1215456/


All Articles