从包外的脚本中导入Python

时间:2019-05-07 03:00:00

标签: python python-3.x python-import

Python无法导入程序包,但可以在程序包中正常运行。下面是一个功能完整的示例。在虚拟环境中,我使用3.6的所有答复,非常感谢!

parsers/
    __init__.py
    element.py
    parser1.py
    parser2.py
    parserresolver.py
outsidepkg.py

init .py为空

element.py:

def router():
    pass

parser1.py:

from element import *
def parse(data):
    return data

parser2.py:

from element import *
def parse(data):
    return data

parserresolver.py:

import sys
from parser1 import *
from parser2 import *

def resolve(data):
    parseddata = None
    parsers = ['parser1', 'parser2'] 
    funcname = 'parse'
    for parser in parsers:
        module = sys.modules[parser]
        if hasattr(module, funcname):
            func = getattr(module, funcname)
            parseddata = func(data)
            print(parseddata)
            return parseddata

if __name__ == "__main__":
    resolve('something')

outsidepkg.py:

import parsers.parserresolver
def getapi(data):
    parsers.parserresolver.resolve(data)
if __name__ == "__main__":
    print(getapi('in parse api main'))

因此,当我直接调用parserresolver.py时,效果很好,没有导入错误,并按预期打印出了“东西”。

但是当我致电outsidepkg.py时,出现此错误:

Traceback (most recent call last):
  File "C:\code\TestImport\TestImport\outsidepkg.py", line 1, in <module>
    import parsers.parserresolver
  File "C:\code\TestImport\TestImport\parsers\parserresolver.py", line 2, in <module>
    from parser1 import *
ModuleNotFoundError: No module named 'parser1'
Press any key to continue . . .

1 个答案:

答案 0 :(得分:2)

您需要更改以下商品的导入:

from file import whatever

收件人:

from .file import whatever

由于您要运行的代码位于文件夹外部,请使用.来获取目录,因为该文件不在软件包中。