python中包引入遇到的問題

最近在用python的flask時候發現一點問題,代碼組織以下python

|-app
    |-__init__.py
    |-views.py
    |-operations.py
    |-xxx.py
|-run.py

按照python的約定,app做爲一個包(package),引入到run.py當中flask

from app import app

在app/__init__.py中加入須要引入的包session

from app import views,operations,xxx

按照這樣的結構運行整個項目是ok的app

operations.py 寫了一些後臺任務的邏輯,其中有一些對象是從__init__.py當中引入的命令行

from app import app, db_session, alarm_user, logger

單獨運行operations.py來調試一部分代碼時候發現了問題調試

if __name__ == "__main__":
    #print get_password()
    #print get_replication()
    print refresh_instance()

在PyCharm當中運行正常,但在命令行環境下沒法運行,會出現以下錯誤:code

#python operations.py
Traceback (most recent call last):
  File "operations.py", line 3, in <module>
    from app import app, db_session, alarm_user, logger
ImportError: No module named app

思索以後發現了玄機,PyCharm運行是以項目的根目錄做爲程序運行環境的。當進入命令行以後,咱們運行operations.py時的運行環境實際是在app/目錄下,所以解析app包就失敗了。
解決方法,擴展python運行環境,把根目錄引入運行環境對象

#!/bin/env python
# -*- coding: utf-8 -*-
import sys
sys.path.append("../")

from app import app, db_session, alarm_user, logger
相關文章
相關標籤/搜索