How to import python file via command line?

I am working on a project eiler and would like to type all my code. I have a file directory in the form of "problemxxx.py", where xxx is the problem number. Each of these files has a function main()that returns a response. So I created a file called run.py located in the same directory as the problem files. I can get the file name on the command line. But when I try to import the problem file, I keep getting ImportError: No module named problem. Below is the code for run.py so far along with the command line used.

# run.py
import sys
problem = sys.argv[1]
import problem         # I have also tired 'from problem import main' w/ same result

# will add timeit functions later, but trying to get this to run first
problem.main()

The command line queries I tried are the following: (both of them provide the ImportError value above)

python run.py problem001
python run.py problem001.py

How can I import a function main()from problem001.py file? Is an import imported with the file name stored in the variable? Is there a better solution than trying to get the file name through the command line? Let me know if I need to add more information, and thanks for any help!

+4
source share
3 answers

You can do this using __import__().

# run.py
import sys
problem = __import__(sys.argv[1], fromlist=["main"])         # I have also tired 'from problem import main' w/ same result
problem.main()

Then if you have problem001.py:

def main():
    print "In sub_main"

python run.py problem001Fingerprint call :

In sub_main

A cleaner way to do this (instead of a way __import__) is to use a module importlib. Your run.pymust be changed:

import importlib
problem = importlib.import_module(sys.argv[1])

question.

+2

! __ import_, __import__(problem). , . , , unittest, .

+1

You can use the exec () trick:

    import sys
    problem = sys.argv[1] 
    exec('import %s' % problem)
    exec('%s.main()' % problem)
0
source

All Articles