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

2024-06-26 17:50:11 发布

您现在位置: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()

问题是path是一个字符串,它给出了以下错误:

^{pr2}$

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


Tags: 文件path代码fromimport命令as动态
2条回答

您必须使用^{}。在

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

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

使用

runcommand = __import__(path)

取而代之的是

相关问题 更多 >