3
\$\begingroup\$

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/'
dirScript = '/home/username/path/to/scripts/'
pathDB = '/home/username/path/to/database.db'

The other scripts are similar.

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

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)
\$\endgroup\$
1
  • \$\begingroup\$ Thanks, that looks a lot better! \$\endgroup\$ – klmr May 2 at 22:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.