2017-04-26 64 views
0

我想从模块abc.py 中导入函数foo()但是,abc.py包含其他函数,这些函数依赖于Python不可用的模块(即,我不能将它们导入到Python解释器,因为我用的ImageJ为Jython的运行abc.py)从没有模块依赖的模块中导入函数

一个解决方案,我发现是把有问题的进口名内 ==“主要”检查,如:

# abc.py 
def foo(): 
    print("Hello, World!") 

def run_main_function(): 
    foo() 
    ...other stuff using IJ... 

if __name__ == "__main__": 
    from ij import IJ 
    run_main_function() 

所以当我尝试t o将foo从另一个脚本def.py中导入,例如:

# def.py 
from abc import foo 

def other_func(): 
    foo() 

if __name__ == "__main__": 
    other_func() 

这是有效的。但是当我以正常的方式放置导入时,在脚本的顶部,出现错误:没有名为'ij'的模块。我想知道是否有解决这个问题的办法?特别是,我把进口放在脚本的顶部,然后在def.py中,我说只导入函数,而不依赖于abc.py?

回答

0

您不应在import声明中包含.py扩展名。它应该阅读:

from abc import foo 
+0

当然,写这个问题时这是一个类型/省略,谢谢指出。 – MMagician

0

I would like to know if there is a solution to this problem? Specifically, that I put the imports at the top of the script and then within def.py I say to import just the function, without dependencies of abc.py?

据我所知,那就是蟒蛇的工作方式。您应该将该导入放入使用它的函数中,否则始终无法使用。

def run_main_function(): 
    from ij import IJ 
    foo() 

另外,不要使用abc为模块名,这是一个标准库模块:Abstract Base Class 2.7Abstract Base Class 3.6

编辑:不要使用作为Kind Stranger导入时表示尾随.py