Where/How to save a preferences file in a *nix command line utility? - linux

I am writing a small command line utility. It should hopefully be able to run on OSX, UNIX and Linux.
It needs to save a few preferences somewhere, like in a small YAML config file.
Where would one save such a file?
Language: Python 2.7
OS: *nix

Commonly, these files go somewhere like ~/.rc (eg: ~/.hgrc). This could be the path to a file, or to a directory if you need lots of configuration settings.
For a nice description see http://www.linuxtopia.org/online_books/programming_books/art_of_unix_programming/ch10s03.html

I would avoid putting the file in the ~ directory only because it has gotten totally flooded with crap. The recent trend, at least on ubuntu, is to use ~/.config/<appname>/ for whatever dot files you need. I really like that convention.

If your application is named "someapp" you save the configuration in a file such as $HOME/.someapp. You can give the config file an extension if you like. If you think your app may have more than one config file you can use the directory $HOME/.someapp and create regular-named (not hidden) files in there.

Many cross-platform tools use the same path on OS X as on linux (and other POSIX/non-Windows platforms). The main advantage of using the POSIX locations isn't saving a few lines of code, but saving the need for Mac-specific instructions, and allowing Mac users to get help from the linux users in the community (without any need to translate their suggestions).
The other alternative is to put them in the "Mac-friendly" locations under ~/Library instead. The main advantage of using the Mac locations is basically "Apple says so"—unless you plan to sandbox your code, in which case the main advantage is that you can do so.
If you choose to use the Library locations, you should read About the OS X File System and OS X Library Directory Details in the File System Programming Guide, but here's the short version:
Almost everything: Create a subdirectory with your app's name or bundle ID (unless you're going out of your way to set a bundle ID, you'll get org.python.python, which you don't want…) under ~/Library/Application Support. Ideally you should use APIs like -[NSFileManager URLForDirectory:inDomain:appropriateForURL:create:error:] to get the path; if not, you have to deal with things like localization, sandbox containers, etc. manually.
Anything that can be easily re-created (so it doesn't need to be backed up, migrated, etc.): An identically-named subdirectory of ~/Library/Caches.
Preferences: Use the NSUserDefaults or CFPreferences APIs instead. If you use your own format, the "old" way of doing things is to create a subdirectory under ~/Library/Preferences named with your app's name or bundle ID, and put your files in that. Apple no longer recommends that, but doesn't really recommend an alternative (short of "use CFPreferences, damnit!"); many apps (e.g., Aquamacs) still do it the old way, but others instead pretend they're not preferences and store them under Application Support.
In Python, this works as follows (leaving out the error handling, and assuming you're going by name instead of setting a bundle ID for yourself):
from Foundation import *
fm = NSFileManager.defaultManager()
appsupport = (fm.URLForDirectory_inDomain_appropriateForURL_create_error_(
NSApplicationSupportDirectory, NSUserDomainMask, None, True, None)[0].
URLByAppendingPathComponent_isDirectory_(
appname, True))
caches = (fm.URLForDirectory_inDomain_appropriateForURL_create_error_(
NSCachesDirectory, NSUserDomainMask, None, True, None)[0].
URLByAppendingPathComponent_isDirectory_(
appname, True))
prefs = NSUserDefaults.persistentDomainForName_(appname)

Related

How to resolve system directories paths independently of system locale?

TLDR
I need to get paths to system directories like "Screenshots":
On an English system. I can just use this one:
C:/Users/User/Pictures/Screenshots
How do I get the path to "Screenshots" directory on a non-English system?
C:/Users/User/Pictures/[NAME]
Description
I have a file manager app, it displays system directories and loads them on click.
The app can run system commands via Powershell and use Node.js (preferred)
Problem
The problem is, it only works if the system has English system language.
Currently, to resolve the "Screenshots" directory path, the app simply joins the User directory with the word "Screenshots"
const pictures = electronRemote.app.getPath('pictures')
const screenshots = PATH.join(pictures, 'Screenshots')
link to the line in code
Expectedly, the C:/Users/User/Screenshots path only exists on English systems.
One way to solve this is to use short names, at least on Windows, I know that system directories have short names like SCREEN~1 and WALLPA~1 for Screenshots and Wallpapers directories, but if I use these names the paths will look like this:
C:/Users/User/SCREEN~1 instead of C:/Users/User/Screenshots throughout the app.
And even if I were to run these paths through a function to convert it to readable name, how would I know which word to replace it with? I need to get the name in the system's language.
Are these translations stored somewhere on the system? Can I just retrieve the translated directory name and use that in the code above?
Question
How do I make it to get / resolve the actual path of system directories like Screenshots and Wallpapers, independently of system locale?
If you know how to do it, could you please suggest the solution for all platforms (Win, Mac, Linux)?
Should I just use the short names like SCREEN~1 and then automatically replace all the occurrences in UI and also filter all paths through a function that replaces this short name with the actual path throughout the whole app? Seems like a lot of work, this approach

After adding libraries to dymola, i can't connect it to Python via buildingspy

After i have made some libraries load directly when i open Dymola by modifying the file : "c:/program files (x86)/dymola 2016 fd01/insert/dymola.mos" , and adding those lines :
Utilities.setenv("MODELICAPATH","C:/Users/hrameh/Desktop/EnergySystems_V2-73p/ModelicaLibraries/ExternalMedia-master/Modelica/ExternalMedia 3.2.1");
openModel("C:\Users\hrameh\Desktop\EnergySystems_V2-73p\ModelicaLibraries\ExternalMedia-master\Modelica\ExternalMedia 3.2.1\package.mo");
Utilities.setenv("MODELICAPATH","C:\Users\hrameh\Desktop\EnergySystems_V2-73p\ModelicaLibraries\EnergySystems");
openModel("C:\Users\hrameh\Desktop\EnergySystems_V2-73p\ModelicaLibraries\EnergySystems\package.mo");
Utilities.setenv("MODELICAPATH","\illuin\users$\hrameh\Mes documents\Dymola");
The model works completely fine in Dymola. But, when trying to simulate the model via Python using the buildingspy library, the simulation fails. Any suggestions to help me find a solution?
I guess your problem is, that buildingspy relies on the default working directory path Dymola gets when the dymola.exe is called by buildingspy - but the openModel-commands in your dymola.mos change the working directory.
Use
openModel("<path-to-package.mo>", changeDirectory=false);
to avoid this.
Additionally, with newer Dymola versions, you must ensure that no saved startup directory is used, by selecting: Edit -> Options -> Settings -> Do not save Startup directory.
As you currently use Dymola 2016 FD01 this is not a problem for you at the moment.
Such problems can be detected by showing the Dymola window when buildingspy simulates a model. You can do this with showGUI as shown in this minimum example:
import os
from buildingspy.simulate.Simulator import Simulator
os.environ["PATH"] += os.pathsep + "C:/Program Files (x86)/Dymola 2016 FD01/bin"
s = Simulator("Modelica.Blocks.Examples.PID_Controller", "dymola")
s.showGUI(show=True)
s.simulate()
Some further hints for your example:
You do not need the Utilities.setenv()-calls to open a library. openModel is sufficient
I would not use Utilities.setenv, as this is an undocumented and apparently a very old package (creation date is from 2004). Use Modelica.Utilities.System.setEnvironmentVariable instead. This way you also don't get an extra package loaded in the package browser
Using the file /insert/dymola.mos has some disadvantages:
it is used system wide by every user, so it should not contain paths to user directories
if you install a new dymola version, you must edit the insert/dymola.mos file of this installation again
Alternatives to dymola.mos
In Dymola 2016 FD01 use the file setup.mos instead to add the openModel commands (located in C:\Users\\AppData\Roaming\Dynasim)
Newer Dymola versions don't have setup.mos anymore, but setup.dymx for the settings and startup.mos for the user commands (to open libraries, etc.)

In Windows Node.js fs.readdirSync With Users Folders etc

I've been developing an nw.js project and use node.js file system functions in it as normal. In my application there is a file manager and I list folders and files according to user navigation. In Windows, for example, if I scan drive C: I get the Turkish named folder "Kullanıcılar" as "Users". I know it's real name in operating system is "Users" and just seen on the screen according to Languages. I can replace names of such folders when dispaying in my file manager but I'm searching for better solution if exists. Thanks in advance.
There's an SO answer here that reads the localized name of a folder in C# using the SHGetFileInfo function which might help you along.
Now I know you didn't ask, but in case you want to know where the information is stored... It's within the directory, in the Desktop.ini file.
For instance, my Windows 10 installation has this in it for "Users":
[.ShellClassInfo]
LocalizedResourceName=#%SystemRoot%\system32\shell32.dll,-21813
And this for the Images folder within my user folder (bringing this up to show you the additional keys):
[.ShellClassInfo]
LocalizedResourceName=#%SystemRoot%\system32\shell32.dll,-21779
InfoTip=#%SystemRoot%\system32\shell32.dll,-12688
IconResource=%SystemRoot%\system32\imageres.dll,-113
IconFile=%SystemRoot%\system32\shell32.dll
IconIndex=-236
The #%SystemRoot%\system32\shell32.dll,-21813 points to having to read the MUI (multilingual user interface) resources, key 21813 for the given file (presumably the # means that it's in this file, not this literal value, but don't quote me on that). %SystemRoot% is an environment variable that points to the Windows directory.
The actual MUI files and their locations are handled by Windows (see the MSDN link above), but we'll just happen to handily know that the MUI file for the US English localization of shell32.dll is system32\en-US\shell32.dll.mui.
Opening up that file with Resource Hacker, we can search for 21813 -- and voila! We can find STRINGTABLE resource #1364 that contains:
[...snip...]
21812, "Extras and Upgrades"
21813, "Users"
21814, "Saved Games"
[...snip...]
I unfortunately don't have tr-TR/shell32.dll.mui available, so you'll just have to trust me that you'd find the Kullanıcılar string there.

Change .eclipse folder in Linux

How can I change the .eclipse folder in Linux? I tried adding this line:
-Dosgi.configuration.area=/directory/directory1/eclipse/.eclipse
at the top of eclipse.ini but it doesn't work. I've also tried adding it to various other places in the eclipse.ini but still no luck.
Edit
I have added this line:
-Dosgi.configuration.area=file:/directory/directory1/eclipse/.eclipse
immediately below -vmargs. When Eclipse starts, it now reads from the correct .eclipse location and if .eclipse does not exist there, it creates it. Unfortunately, after Eclipse has loaded, another .eclipse folder is created in my home folder and Eclipse then continues to read from that folder. I suspect that my eclipse.ini file is now correct but there is another file I need to change.
The simplest thing to do is probably pass java a different user.home so that all the other myriad of places that derive a location base it off of user.home. So instead of what you have, use this in .ini file:
-Duser.home=/directory/other/here
In addition to .eclipse, you will probably find other directories created in your overridden user.home, such as .p2, .oracle_jre_usage, etc.
Other notes:
-Dosgi.configuration.area is the changes the configuration area for Eclipse, it does not effect user area. You also probably don't want to change that setting away from the default unless you really want multiple configurations (read more below).
Additionally, the normal thing to do would be to use -configuration as an argument to eclipse{.exe} and let eclipse convert it to the appropriate VM argument.
You probably want -user though to override the user area. Have a look at locations in the Eclipse help for more info (quoted below).
However, there are still things that have individual control over their location, such as secure storage, which is controlled by the -eclipse.keyring command line argument.
Locations
The Eclipse runtime defines a number of locations which give
plug-in developers context for reading/storing data and Eclipse users
a control over the scope of data sharing and visibility. Eclipse
defines the following notions of location:
User (-user) {osgi.user.area} [#none, #noDefault, #user.home,
#user.dir, filepath, url]
User locations are specific to, go figure,
users. Typically the user location is based on the value of the Java
user.home system property but this can be overridden. Information such
as user scoped preferences and login information may be found in the
user location.
Install (-install) {osgi.install.area} [#user.home,
#user.dir, filepath, url]
An install location is where Eclipse itself
is installed. In practice this location is the directory (typically
"eclipse") which is the parent of the eclipse.exe being run or the
plugins directory containing the org.eclipse.equinox.launcher bundle.
This location should be considered read-only to normal users as an
install may be shared by many users. It is possible to set the install
location and decouple eclipse.exe from the rest of Eclipse.
Configuration (-configuration) {osgi.configuration.area} [#none,
#noDefault, #user.home, #user.dir, filepath, url]
Configuration
locations contain files which identify and manage the (sub)set of an
install to run. As such, there may be many configurations per install.
Installs may come with a default configuration area but typical
startup scenarios involve the runtime attempting to find a more
writable configuration location.
Instance (-data) {osgi.instance.area}
[#none, #noDefault, #user.home, #user.dir, filepath, url]
Instance
locations contain user-defined data artifacts. For example, the
Resources plug-in uses the instance area as the workspace location and
thus the default home for projects. Other plugins are free to write
whatever files they like in this location.
While users can set any of
these locations, Eclipse will compute reasonable defaults if values
are not given. The most common usecase for setting location is the
instance area or, in the IDE context, the workspace. To run the
default Eclipse configuration on a specific data set you can specify:
eclipse -data c:\mydata
You must put property definitions like this at the end of the eclipse.ini after the -vmargs line. If there is no -vmargs line you must add one.
So:
.... other lines ....
-vmargs
... other arguments
-Dosgi.configuration.area=/directory/directory1/eclipse.eclipse

saving to /home/user/Documents in different locales / languages

In my linux python app for Fedora I want to save user's work to /home/user/Documents/MyCoolApp/TheirGreatWork.txt
But I am not sure how to find the "Documents" folder if the user is not using English as their default language.
What is the right way to determine the right path so that files go in their "Documents" folder.
EDIT
Here is a which comes up if you change locales... showing how paths can get easily changed.
I'd use the subprocess module to get the output of the command xdg-user-dir DOCUMENTS. For example:
import subprocess
documents_dir = subprocess.check_output(["xdg-user-dir", "DOCUMENTS"])
print documents_dir # This is what you're looking for.
There is no right way as the user may have changed their locale, which (fortunately) does not rename the directory. If you want a fixed place for files managed by your app, use ~user/.MyCoolApp or let the user specify the directory.

Resources