python import的路径问题
作者:互联网
一、问题概述
我想在measure.py中import utils.py中的函数。
在measure.py中添加如下代码:
from utils import *
在Pycharm中运行是可以的,但是在服务器上运行是报错的。
二、解决方法
在measure.py中添加如下代码:
import sys
print(sys.path)
然后分别在Pycharm和服务器上运行。
Pycharm输出:
['/home/ruipeng/Desktop/zrp_project/GCPR/new_measure',
'/home/ruipeng/Desktop/zrp_project/GCPR',
'/home/ruipeng/pycharm-2021.1.1/plugins/python/helpers/pycharm_display', '/home/ruipeng/anaconda3/envs/activity2vec/lib/python37.zip',
'/home/ruipeng/anaconda3/envs/activity2vec/lib/python3.7',
'/home/ruipeng/anaconda3/envs/activity2vec/lib/python3.7/lib-dynload', '/home/ruipeng/anaconda3/envs/activity2vec/lib/python3.7/site-packages',
'/media/ruipeng/1.42.6-24922/HAKE-Action-Torch/AlphaPose',
'/media/ruipeng/1.42.6-24922/HAKE-Action-Torch',
'/home/ruipeng/anaconda3/envs/activity2vec/lib/python3.7/site-packages/pycocotools-2.0-py3.7-linux-x86_64.egg', '/home/ruipeng/anaconda3/envs/activity2vec/lib/python3.7/site-packages/torchlight-1.0-py3.7.egg',
'/home/ruipeng/pycharm-2021.1.1/plugins/python/helpers/pycharm_matplotlib_backend']
服务器上输出:
['/home/ruipeng/Project/GCPR/new_measure',
'/home/ruipeng/anaconda3/envs/human/lib/python37.zip',
'/home/ruipeng/anaconda3/envs/human/lib/python3.7',
'/home/ruipeng/anaconda3/envs/human/lib/python3.7/lib-dynload',
'/home/ruipeng/anaconda3/envs/human/lib/python3.7/site-packages']
可见,出现上述差异的原因是,Pycharm会默认将项目的根目录添加到sys.path!
所以往往在pycharm下运行没有问题,但部署项目时,用命令行运行文件却报错。
可以print(sys.path)分别看一下pycharm下和命令行运行。
因此,解决方法是:
在measure.py中的import前添加以下代码:
sys.path.append("/home/ruipeng/Project/GCPR") # 服务器上的路径
print(sys.path)
运行后,服务器上的输出变为:
['/home/ruipeng/Project/GCPR/new_measure',
'/home/ruipeng/Project/GCPR',
'/home/ruipeng/anaconda3/envs/human/lib/python37.zip',
'/home/ruipeng/anaconda3/envs/human/lib/python3.7',
'/home/ruipeng/anaconda3/envs/human/lib/python3.7/lib-dynload',
'/home/ruipeng/anaconda3/envs/human/lib/python3.7/site-packages']
这样的话,在服务器上用命令行运行便不会报错了。
标签:lib,anaconda3,python,路径,python3.7,envs,ruipeng,home,import 来源: https://www.cnblogs.com/wonderlust/p/16348209.html