【问题标题】:run python file from another file with dynamic path [duplicate]从另一个具有动态路径的文件运行python文件[重复]
【发布时间】:2014-11-17 06:06:31
【问题描述】:

我尝试在位于动态文件中的 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

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

【问题讨论】:

    标签: python


    【解决方案1】:

    你必须使用importlib.import_module

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

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

    【讨论】:

      【解决方案2】:

      使用

      runcommand = __import__(path)
      

      改为

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-06-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多