0

I try to run command in my python file, which located in dynamic file. I try to use the import statement, which as I understand is the better solution for this case.

Here is the code:

from subprocess import call
import tarfile
from contextlib import closing

def tarfile1(path):
    with closing(tarfile.open(path)) as tar:
      tar.extractall(path)
    import path as runcommand
    runcommand.main()

The problem is that path is a string, and it gives me the following error:

    import path as runcommand
ImportError: No module named path

How can I import the file, which I don't know its name, and run the main command from it?

Or Smith
  • 3,556
  • 13
  • 42
  • 69

2 Answers2

2

You have to use importlib.import_module.

import importlib
importlib.import_module(<<mymodule>>)

Note: Please make sure your module's parent directory is in PYTHONPATH or added in sys.path.

Nilesh
  • 20,521
  • 16
  • 92
  • 148
1

Use

runcommand = __import__(path)

instead