5

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.

    2
    • i don't think so,I already tried that.I said that the imported module must be executed.That did not happen with imp Commented May 31, 2013 at 5:26
    • Modules are executed when they are imported. Commented May 31, 2013 at 5:37

    1 Answer 1

    5

    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 
    
    Sign up to request clarification or add additional context in comments.

    6 Comments

    It works, BTW, Why 'foo' is required?I don't see any use of it.
    well,the output does not match mine,I see no hello world in my output.
    @RajeevS it works for me, in shell as well as IDLE.
    @RajeevS: You are doing imp.load_source("test", "."), but if you read the documentation, it should be imp.load_source(name, path). You should do imp.load_source('test', 'test').
    Yeah,that was the issue.:)
    |

    Start asking to get answers

    Find the answer to your question by asking.

    Ask question

    Explore related questions

    See similar questions with these tags.