Import python module without .py extension,

I agree that there are similar questions, but no one serves my purpose.

I have a python script, without the .py extension.

I can neither change the file name nor add a symlink. The file name is significant.

I need to import the above file into another python script

I tried the following

>>> imp.load_source('test','.') <module 'test' from '.'> 

and

 >>> importlib.import_module('test','.') <module 'test' from '.'> 

If the test module is just

 print 'hello world' 

My requirement is that the import statement works the same as it imports if the file was test.py , i.e. prints hello world upon import.

Is there a way to “run” an imported module using imp or imortlib?

I would like to add that I'm talking about a control file in an autotest project , if that matters.

+4
source share
1 answer

You can use imp.load_source

 >>> import imp >>> mod = imp.load_source("test", "test") hello world >>> mod.a 1 

a:

 print "hello world" a = 1 
+5
source

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


All Articles