Loading a Config File from Operation System Independent Place in Python

Loading a config file from operation system independent place in python

Try:

os.path.expanduser('~/.programname')

On linux this will return:

>>> import os
>>> os.path.expanduser('~/.programname')
'/home/user/.programname'

On windows this will return:

>>> import os
>>> os.path.expanduser('~/.programname')
'C:\\Documents and Settings\\user/.programname'

Which is a little ugly, so you'll probably want to do this:

>>> import os
>>> os.path.join(os.path.expanduser('~'), '.programname')
'C:\\Documents and Settings\\user\\.programname'

EDIT: For what it's worth, the following apps on my Windows machine create their config folders in my Documents and Settings\user folder:

  • Android
  • AgroUML
  • Gimp
  • IPython

EDIT 2: Oh wow, I just noticed I put /user/.programname instead of /home/user/.programname for the linux example. Fixed.

Is there a standard way to get the user config directory in python

You can take advantage of python third party library appdirs which does all the heavy lifting for you across multiple platforms ( Windows, Linux & Mac )

Platform-independent file paths?

You can use os.path and its functions, which take care of OS-specific paths:

>>> import os
>>> os.path.join('app', 'subdir', 'dir', 'filename.foo')
'app/subdir/dir/filename.foo'

On Windows, it should print out with backslashes.

OS independent path import in Python

i recommend using "os.path" like so:

import sys
from os import path

if __name__ == '__main__':
software_code_full_path = path.abspath(path.join(path.dirname(__file__), '../../source_code_folder'))

if software_code_full_path not in sys.path:
sys.path.append(software_code_full_path)

A system independent way using python to get the root directory/drive on which python is installed

You can get the path to the Python executable using sys.executable:

>>> import sys
>>> import os
>>> sys.executable
'/usr/bin/python'

Then, for Windows, the drive letter will be the first part of splitdrive:

>>> os.path.splitdrive(sys.executable)
('', '/usr/bin/python')

Open document with default OS application in Python, both in Windows and Mac OS

open and start are command-interpreter things for Mac OS/X and Windows respectively, to do this.

To call them from Python, you can either use subprocess module or os.system().

Here are considerations on which package to use:

  1. You can call them via os.system, which works, but...

    Escaping: os.system only works with filenames that don't have any spaces or other shell metacharacters in the pathname (e.g. A:\abc\def\a.txt), or else these need to be escaped. There is shlex.quote for Unix-like systems, but nothing really standard for Windows. Maybe see also python, windows : parsing command lines with shlex

    • MacOS/X: os.system("open " + shlex.quote(filename))
    • Windows: os.system("start " + filename) where properly speaking filename should be escaped, too.
  2. You can also call them via subprocess module, but...

    For Python 2.7 and newer, simply use

    subprocess.check_call(['open', filename])

    In Python 3.5+ you can equivalently use the slightly more complex but also somewhat more versatile

    subprocess.run(['open', filename], check=True)

    If you need to be compatible all the way back to Python 2.4, you can use subprocess.call() and implement your own error checking:

    try:
    retcode = subprocess.call("open " + filename, shell=True)
    if retcode < 0:
    print >>sys.stderr, "Child was terminated by signal", -retcode
    else:
    print >>sys.stderr, "Child returned", retcode
    except OSError, e:
    print >>sys.stderr, "Execution failed:", e

    Now, what are the advantages of using subprocess?

    • Security: In theory, this is more secure, but in fact we're needing to execute a command line one way or the other; in either environment, we need the environment and services to interpret, get paths, and so forth. In neither case are we executing arbitrary text, so it doesn't have an inherent "but you can type 'filename ; rm -rf /'" problem, and if the file name can be corrupted, using subprocess.call gives us little additional protection.
    • Error handling: It doesn't actually give us any more error detection, we're still depending on the retcode in either case; but the behavior to explicitly raise an exception in the case of an error will certainly help you notice if there is a failure (though in some scenarios, a traceback might not at all be more helpful than simply ignoring the error).
    • Spawns a (non-blocking) subprocess: We don't need to wait for the child process, since we're by problem statement starting a separate process.

    To the objection "But subprocess is preferred." However, os.system() is not deprecated, and it's in some sense the simplest tool for this particular job. Conclusion: using os.system() is therefore also a correct answer.

    A marked disadvantage is that the Windows start command requires you to pass in shell=True which negates most of the benefits of using subprocess.

What's the official way of storing settings for Python programs?

Depends on the predominant intended audience.

If it is programmers who change the file anyway, just use python files like settings.py

If it is end users then, think about ini files.



Related Topics



Leave a reply



Submit