IOError: [Errno 2] 找不到文件或目录偶尔出现
我有一个网页应用和一个手机应用,它们都连接到我的服务器。在我的服务器上,有一个模块叫做 md.py
,它使用另一个模块 config.py
,这个模块会从本地的 XML 文件中读取数据。
当我从我的应用间接发送请求到 config.py
获取数据时,一切都运行得很好。但当我从 md.py
直接调用 config.py
时,问题就出现了,虽然它们都在同一台机器上。
这是它们的层级结构:
root/
start.py
md/
__init__.py
md.py
server/
__init__.py
config.py
server.py
data/
config.xml
这是 md.py
from server import config
class Md:
def get_data(self):
conf = config.Config() # Errno 2 here
这是 config.py
import xml.etree.ElementTree as ET
CONF_FILE = "data/config.xml"
class Config:
def __init__(self):
self.file = ET.parse(CONF_FILE)
self.root = self.file.getroot()
这是我在 start.py
中运行这些文件的方式
def start():
global server_p
server_p = subprocess.Popen('python ./server/server.py')
md = subprocess.Popen('python ./md/md.py')
我该怎么做才能解决这个问题呢?
1 个回答
2
首先,在 config.py
文件中导入 dirname
和 join
这两个函数,它们来自 os.path
模块:
from os.path import dirname, join
然后把 CONF_FILE
改成:
CONF_FILE = join(dirname(__file__), 'data', 'config.xml')
可以把 __file__
想象成一个文件的绝对路径,这个文件是某段代码定义的,当它作为模块加载时就会用到这个路径。dirname
函数会从这个路径中提取出文件所在的目录,而 join
函数则可以把多个字符串拼接成一个新的路径。
所以,首先我们通过读取 __file__
得到 {abs_path_to}root/server/config.py
的绝对路径。接着,使用 dirname(__file__)
就能得到 {abs_path_to}root/server
的路径。然后把这个路径和 data
以及 config.xml
拼接在一起,最后得到的就是 {abs_path_to}root/server/data/config.xml
。