从另一个具有动态路径的文件运行python文件

从另一个具有动态路径的文件运行python文件,python,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

我尝试在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
如何导入不知道名称的文件并从中运行主命令?

您必须使用

导入导入库
importlib.import_模块()
注意:请确保模块的父目录位于PYTHONPATH中或添加在
sys.path中

使用

runcommand = __import__(path)
反而

runcommand = __import__(path)