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?

0

2 Answers 2

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.

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

Comments

1

Use

runcommand = __import__(path)

instead

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.