python import 模块导入路径

当前程序目录结构是这样的
1.png
main.py的代码:

#! /usr/bin/env python
# encoding:utf-8

from A import call_a
def main():
    call_a()
if __name__ == '__main__':
    main()

A.py文件的代码:

#! /usr/bin/env python
# encoding:utf-8
from B import call_b

def call_a():
	print "call_a"
	call_b()

B.py文件代码:

#! /usr/bin/env python
# encoding:utf-8
def call_b():
    print "Call_b"

当我通过bash命令运行脚本:

bogon:tests nooper$ python innermodules/main.py 
Traceback (most recent call last):
  File "innermodules/main.py", line 4, in <module>
    from A import call_a
ImportError: No module named A
bogon:tests nooper$ 

是不能识别模块的加载路径,但是能通过IDE-pycharm运行。如何通过shell来执行脚本main.py,还是需要对__init__.py文件进行加载包。

阅读 63.9k
3 个回答
import sys
sys.path.append('..')

将父目录加入import路径

A.py 和 main.py 没有在同一个文件夹下
可以把A.py和main.py 放到同一个文件夹下 或者把A.py 加入import 路径
或者 from ..A import call_a

新手上路,请多包涵

可以直接通过pycharm来修改import的路径,具体pycharm版本不一样,对应按钮位置不一样,因此仅以文字说明。

file->Settings(Ctrl+Shift+s)->Project Setting->Project Interpreter->选择你的python版本->Interpreter Path->添加

你这里的话添加如下目录即可
**\tests
即project的根目录。

如果你在tests下有文件夹test2,其下有文件c.py。要引用c文件的c2
在你的main.py里面加入:
from test2.c import c2
路径是以你添加的路径的相对路径。。。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题