【问题标题】:IOError: [Errno 2] No such file or directory occasionallyIOError: [Errno 2] 偶尔没有这样的文件或目录
【发布时间】:2014-05-10 23:36:17
【问题描述】:

我有一个网络应用程序和一个移动应用程序连接到我的服务器。在我的服务器中,我有一个模块 (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')

我能做些什么来解决这个问题?

【问题讨论】:

  • 尝试让 config.py 文件运行 ls 命令,我认为工作目录可能与它实际所在的目录不同。
  • 有没有办法动态获取正确的路径?

标签: python nosuchfileexception


【解决方案1】:

首先从config.py中的os.path模块导入dirnamejoin

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

【讨论】:

  • 我试图做类似的事情但没有成功,缺少dirname(__file__)。感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-26
相关资源
最近更新 更多