简体   繁体   中英

Store user settings in Python script

I created a Python package that is actually a command line interface. Everything works fine, but I would like to be able to store simple user settings (a few values) in some file (json, yaml, or whatever). Handling such files itself is not a problem, but I don't know where I could store them. My program can be installed using pip install https://github.com/repo and works fully off-line.

It seems that Python does not allow me to store settings files in the same folder, where the compiled program itself is located (Programs\\Python\\Python38\\Scripts) which makes sense, but I don't know how to do it any other way.

Inspired by the comments under the question, I searched a little bit more and found the answer to my problem.

I store my settings file in C:\\users\\me\\appdata\\local\\programs\\python\\python38\\lib\\site-packages\\my_package\\config.json which can be accessed with

os.path.join(os.path.dirname(os.path.abspath(__file__)), 'config.json')

I haven't tested this on Linux or macOS yet, but I think it will work.

EDIT : Unfortunately it does not work on Linux without sudo. For this reason, I used the following:

os.path.join(os.path.expanduser("~"), '.my_package_name', 'config.json')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM