Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import a python module without .py extension, [duplicate]

Tags:

python

import

I agree that there are similar questions,but none serve my purpose.

  • I have a python script,without a .py extension.
  • I can neither change the file name nor add a symlink. The file name is significant.

  • I need to import the above mentioned file to another python script
  • I have tried the following

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

    and

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

    Where the module test is just

    print 'hello world'
    

  • My requirement is that the import statement works just like it imports if the file was test.py,that is,prints hello world upon import.
  • Is there any way to "run" the module imported by using imp or imortlib?

    I would like to add that I am talking about a control file in the autotest project,if it matters.

    like image 599
    rjv Avatar asked May 31 '13 05:05

    rjv


    1 Answers

    You can use imp.load_source

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

    abc:

    print "hello world"
    a = 1 
    
    like image 133
    Ashwini Chaudhary Avatar answered Sep 24 '22 19:09

    Ashwini Chaudhary