Where to put a config file for a compiled Python s

2019-02-25 13:35发布

问题:

This is similar to Where to put a configuration file in Python?, but I'm asking about scripts compiled/frozen with py2exe or similar on Windows systems. (Namely, this one: What config file format to use for user-friendly strings of arbitrary bytes? https://gist.github.com/1119561)

My first thought was to put the config file in the same folder as the .exe, which makes it sort of self-contained. But if I associate files with the .exe, it will be called from their directory, not its own, so I'd need something like How do I get the path of the current executed file in Python? to find the config file.

Is this the best way? Or is there some standard config file locations to search in, like https://stackoverflow.com/a/7567946/125507 ?

回答1:

You can use the appdirs module to determine the appropriate folder for user data.



回答2:

If this is a config file that the user is supposed to edit, then put it somewhere obvious. I tend "compile" python apps in a directory structure like this:

C:/path/to/Application
| config.ini
| Run Application.bat  (runs code/application.exe)
| code/
  | application.exe
  | library.zip 
  | ... etc. 

This keeps the "start the app" shortcut and the config file in the same place, easy for the user to find.



回答3:

If you are using py2exe to package you script, following your links to the one that describes how to determine the path of the executable seems to be the proper way to go. Where you decide to store your config file relative to the exe is up to you. You can either place it in the root of the application directory (next to the exe) or create a config subdir. Its your choice.

On linux machines it can sometimes be common to make use of the etc/ locations for config files. OSX you would either use the users plist preferences location, or an etc. But again in any of these platforms you could also use a relative conf file in the apps directory.

If you were packaging some type of GUI framework, then you could make use of the registry and offer config options through your interface.



回答4:

I've created "compiled" executables in python on widnows that have files types associated with it, and I never had any issues opening my config file which was placed in the same location as the .exe. I used something like this to find it:

    conf = open(r"%s\settings.conf" % os.getcwd())

I stored my values separated by a newline character, so the file looked like this:

PNelson
21
6'

This stores a username, age, and height, to read the values I would use something like this:

settings = "\n".split(conf.read())

I'd then check the length of the array to make sure the config file wasn't corrupted or some way, if it was I'd write default values to the file and use those.