使用动态路径从另一个文件运行python文件

时间:2014-09-23 06:24:40

标签: python

我尝试在我的python文件中运行命令,该文件位于动态文件中。我尝试使用import语句,据我所知,这是本案的更好解决方案。

以下是代码:

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()

问题是路径是一个字符串,它给我以下错误:

    import path as runcommand
ImportError: No module named path

如何导入我不知道其名称的文件,并从中运行主命令?

2 个答案:

答案 0 :(得分:0)

您必须使用importlib.import_module

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

注意:请确保您的模块的父目录位于PYTHONPATH中或添加到sys.path中。

答案 1 :(得分:0)

使用

runcommand = __import__(path)

代替