1

This is what a.py looks

import sys


def test_import(another_python_file):
    import another_python_file as b
    b.run_me()

if __name__ == '__main__':
    print sys.argv
    test_import(sys.argv[1].strip())

this is what b.py looks

def run_me():
    print 'I am script b'

When I run, I get

$ python a.py b.py
['a.py', 'b.py']
Traceback (most recent call last):
  File "a.py", line 10, in <module>
    test_import(sys.argv[1].strip())
  File "a.py", line 5, in test_import
    import another_python_file as b
ImportError: No module named another_python_file

What I need? I would expect it to import b.py and print I am script b

What am I missing?

1

2 Answers 2

1
a.py:

import os
import sys


def test_import(another_python_file):
    b = __import__(another_python_file)
    b.run_me()

if __name__ == '__main__':
    print sys.argv
    test_import(sys.argv[1].strip('.py'))

b.py
def run_me():
    print 'I am script b'

$ python a.py b.py
['a.py', 'b.py']
I am script b

I was able to do that referring to http://www.diveintopython.net/functional_programming/dynamic_import.html

Sign up to request clarification or add additional context in comments.

Comments

0

If you don't need flexibility, you can simply use __import__('module_name'). If you need advanced features like cache control, module searching or reloading, use the imp module.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.