簡體   English   中英

我無法導入文件,但文件夾中的其他文件可以

[英]I can't import a file but the other file in the folder can

從昨天開始,我在導入方面遇到了問題。
我不了解我需要編輯的代碼導入方式。

config.py位於項目的根文件夾中,服務器在此處啟動。

server/src/session.py ,我們可以找到這個

#!/usr/bin/env python
# -*- Mode: Python; tab-width: 4; indent-tabs-mode: nil; coding: utf-8; -*-
# vim:set ft=python ts=4 sw=4 sts=4 autoindent:

'''docstring'''

from __future__ import with_statement

from Cookie import CookieError, SimpleCookie
from atexit import register as atexit_register
from datetime import datetime, timedelta
from hashlib import sha224
from os import makedirs, remove
from os.path import exists, dirname, join as path_join, isfile
from shutil import copy
from shutil import move
from tempfile import mkstemp

try:
    from cPickle import dump as pickle_dump, load as pickle_load
except ImportError:
    from pickle import dump as pickle_dump, load as pickle_load

from config import WORK_DIR

上一次導入很奇怪,因為沒有server/src/config.py ,config.py文件位於項目文件夾的根目錄中。
那么,為什么他可以在這里導入配置?

當我嘗試在文件server/src/save_in_database.py執行相同的server/src/save_in_database.py

import MySQLdb
import os
from config import DB_HOST, DB_USER, DB_PASS

我收到導入錯誤:

Traceback (most recent call last):
  File "server/src/save_in_database.py", line 4, in <module>
    from config import DB_HOST, DB_USER, DB_PASS
ImportError: No module named config

當我嘗試在我的文件server/src/save_in_database.py導入session文件時,出現了錯誤,但在其他文件中它可以正常工作。

Traceback (most recent call last):
  File "server/src/save_in_database.py", line 3, in <module>
    from session import get_session
  File "/home/etienne/ed-labelisator/back/server/src/session.py", line 32, in <module>
    from config import WORK_DIR
ImportError: No module named config

如果有人可以幫助我,我不明白原始程序員是如何導入的。
謝謝,抱歉英語不好

好的,經過幾次研究,我解決了我的問題。

當我啟動服務器時,程序將src / server添加到python路徑:

sys.path.append(os.path.join(os.path.dirname(__file__), 'server/src'))

因此, . AND ./src/server可以導入,這就是為什么它對他./src/server的原因。


而我,當我執行python2 server/src/save_in_database.py. 目錄未添加到python pah中,因此我無法導入config ,其他文件也無法執行該操作。

為了解決這個問題,我將以下代碼添加到server/src/save_in_database.py

if __name__ == '__main__':
    import sys
    sys.path.append(os.path.join(os.path.dirname(__file__), '../..'))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM