# Managing configs to use scripts on different computers

I have some python scripts to run on different computers. To avoid struggles with different paths and filenames I made specific config-files (DConfig, AConfig and MConfig) and another script that decides which config to use. It works, but I guess, there are better ways to do this. Any ideas?

import os
import socket

hostname_K = 'DESKTOP-K'
hostname_A = 'A'
hostname_M = ''                    # hostname not known for sure

print("start config")
print("cwd: ", os.getcwd())
print("os: ", os.name)
# print(os.getlogin())                # Doesn't work on non-posix

hostname = socket.gethostname()
if hostname == hostname_K:
import DConfig as Conf
elif hostname == hostname_A:
import AConfig as Conf
else:
print("Hostname: {}, guess we are on M".format(hostname))
import MConfig as Conf

dirData = Conf.dirData
dirScript = Conf.dirScript
pathDB = Conf.pathDB

print("config done.")


How it is used by other scripts:

import config
XMLFILE = config.dirData + 'Tags.xml'
DATABASE = config.pathDB


Here is an example script for one of the config-files.

dirData = '/home/username/path/to/data/'


The other scripts are similar.

• dirData etc. are used by other scripts importing this config files. – klmr May 2 at 21:56
• It might be helpful if you include the 3 config files in the question as well. – pacmaninbw May 3 at 2:15

You have a value (hostname in this case) that you want to use to select among various data choices (config modules in this case). When you have situations like this, use a data structure. Sensible data is always simpler than logic. For example, see Rule 5 from Rob Pike.

An illustration based on your code:

import socket
import DConfig
import AConfig
import MConfig

configs = {
'host-D': DConfig,
'host-A': AConfig,
'host-M': MConfig,
}

hostname = socket.gethostname()
Conf = configs.get(hostname, MConfig)

• Thanks, that looks a lot better! – klmr May 2 at 22:07