首页 > 解决方案 > 为什么我无法在我的工作目录中导入模块?

问题描述

所以我有一堆我正在尝试运行的代码。

一方面,我设置了我的工作目录并执行了存储在那里的代码。

cd /Users/abrahammathew/Desktop/object_detection_cats/object_detection/

python3 export_inference_graph.py \
    --input_type image_tensor \
    --pipeline_config_path data/ssd_mobilenet_v1_pets.config \
    --trained_checkpoint_prefix data/model.ckpt-997 \
    --output_directory object_detection_graph

但是,这会产生此错误。

from object_detection import exporter
Traceback (most recent call last):

  File "<ipython-input-20-0bc5d13491d6>", line 1, in <module>
    from object_detection import exporter

ImportError: cannot import name 'exporter'

这没有任何意义,因为导出器文件位于工作目录中。

我的目录中的内容

为什么导入命令不起作用?

我去尝试通过设置 os.chdir 然后导入将其导入 Spyder,但这也会导致错误。

os.chdir('/Users/abrahammathew/Desktop/object_detection_cats/object_detection')

import exporter  ### THIS WORKS!!!!!

from object_detection import exporter
Traceback (most recent call last):

  File "<ipython-input-23-0bc5d13491d6>", line 1, in <module>
    from object_detection import exporter

ImportError: cannot import name 'exporter'

标签: python

解决方案


工作目录在object_detection目录内。为了import object_detection工作,你需要在目录中,/Users/abrahammathew/Desktop/object_detection_cats. 所以要么:

  1. 在父目录中工作(对于旧版本的 Python,您可能需要在 中设置一个空__init__.pyobject_detection但现代版本使用隐式命名空间包,因此__init__.py不需要),或者
  2. 将导入更改为just import exporter(它本身就是工作目录中的一个模块)。

推荐阅读