PyCharm 写好的项目在命令行部署时,出现找不到模块路径的问题

问题原因

在 PyCharm 中运行项目,项目会被默认添加包的 path
而当我们用命令行部署项目时,这些 path 需要我们手动添加

小实验

同样一个项目,我们分别在 PyCharm 和 shell 中运行,
在程序的执行入口,添上输出已有 path 的代码:

import sys

for p in sys.path:
    print(p)

PyCharm 输出

/home/disk1/xs_data/PycharmProjects/railway
/home/disk2/xs/home/PycharmProjects/railway
/home/disk2/xs/home/PycharmProjects/railway/Faster_RCNN_for_Rail/lib
/home/disk2/xs/home/PycharmProjects/railway/Faster_RCNN_for_Rail/faster_rcnn
/home/disk2/xs/home/PycharmProjects/railway/Faster_RCNN_for_Rail/vis
/home/disk2/xs/home/PycharmProjects/railway/Unet_segmentation
/home/disk2/xs/home/PycharmProjects/railway/Faster_RCNN_for_Rail
/home/disk2/xs/home/PycharmProjects/railway/app
/home/disk2/xs/home/PycharmProjects/railway/Faster_RCNN_for_Rail/lib/utils
/home/disk2/xs/home/PycharmProjects/railway/Faster_RCNN_for_Rail/lib/dataset
/home/disk2/xs/home/PycharmProjects/railway/Faster_RCNN_for_Rail/faster_rcnn/operator_py
/home/disk2/xs/home/PycharmProjects/railway/Faster_RCNN_for_Rail/faster_rcnn/symbols
/home/disk2/xs/home/PycharmProjects/railway/Faster_RCNN_for_Rail/lib/bbox
/home/disk2/xs/anaconda3/envs/flask/lib/python36.zip
/home/disk2/xs/anaconda3/envs/flask/lib/python3.6
/home/disk2/xs/anaconda3/envs/flask/lib/python3.6/lib-dynload
/home/disk2/xs/anaconda3/envs/flask/lib/python3.6/site-packages
/home/disk2/xs/apps/pycharm-2018.1.4/helpers/pycharm_matplotlib_backend

shell 输出

/home/disk1/xs_data/PycharmProjects/railway
/home/disk2/xs/anaconda3/lib/python36.zip
/home/disk2/xs/anaconda3/lib/python3.6
/home/disk2/xs/anaconda3/lib/python3.6/lib-dynload
/home/disk2/xs/anaconda3/lib/python3.6/site-packages

问题来了!少了好多 path!

  • 那么我们该怎么做呢?
  • 对了,直接在程序的入口把 PyCharm 生成的 path 加进去不就行了吗!
# add path for module import
paths = [
    '/home/disk2/xs/home/PycharmProjects/railway/app',
    '/home/disk2/xs/home/PycharmProjects/railway/Faster_RCNN_for_Rail',
    '/home/disk2/xs/home/PycharmProjects/railway/Faster_RCNN_for_Rail/lib',
    '/home/disk2/xs/home/PycharmProjects/railway/Faster_RCNN_for_Rail/lib/bbox',
    '/home/disk2/xs/home/PycharmProjects/railway/Faster_RCNN_for_Rail/lib/utils',
    '/home/disk2/xs/home/PycharmProjects/railway/Faster_RCNN_for_Rail/lib/dataset',
    '/home/disk2/xs/home/PycharmProjects/railway/Faster_RCNN_for_Rail/faster_rcnn',
    '/home/disk2/xs/home/PycharmProjects/railway/Faster_RCNN_for_Rail/faster_rcnn/operator_py',
    '/home/disk2/xs/home/PycharmProjects/railway/Faster_RCNN_for_Rail/faster_rcnn/symbols',
    '/home/disk2/xs/home/PycharmProjects/railway/Faster_RCNN_for_Rail/vis'
]

for p in paths:
    sys.path.append(p)

就是这样,部署成功了✌

对了,补充说明一句,如果大项目下有好几个小的运行环境,
比如 railway 这个项目,下面的环境有:

  • flask
  • rcnn
  • unet

我们添加的路径如果是 rcnn 子项目需要的,而大项目运行环境是 flask,此时这些 path 就不能添加在 flask 运行环境的程序入口,而要添加在 rcnn 环境程序的执行入口。

你可能感兴趣的:(PyCharm 写好的项目在命令行部署时,出现找不到模块路径的问题)