Question

I have a web app and a mobile app that connect to my server. In my server I have a module (md.py) that uses another module (config.py) which reads data from a local XML file.

When I send a request to config.py (indirectly) for data from my apps everything works fine. The problem occurs when I call config.py from md.py which are both on the same machine.

This is the hierarchy:

root/
  start.py

  md/
    __init__.py
    md.py

  server/ 
    __init__.py
    config.py
    server.py

    data/
        config.xml

This is md.py

from server import config

class Md:

    def get_data(self):        
        conf = config.Config() # Errno 2 here

This is 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()

And this is how I run these files in start.py

def start():
    global server_p

    server_p = subprocess.Popen('python ./server/server.py')
    md = subprocess.Popen('python ./md/md.py')

What can I do to fix this?

Was it helpful?

Solution

First import dirname and join from the os.path module in config.py:

from os.path import dirname, join

Then change CONF_FILE to:

CONF_FILE = join(dirname(__file__), 'data', 'config.xml')

Think of __file__ as the absolute path to the file some code is defined in, at the time it is loaded as a module. dirname takes that path and gives you a path to the directory that file lives in, and join strings together any number of arguments into a new path.

So first we would get {abs_path_to}root/server/config.py by reading __file__. Then dirname(__file__) gets us to {abs_path_to}root/server. Joining that with data and then config.xml finally gives us {abs_path_to}root/server/data/config.xml.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top