[Tutor] opening a file directly from memory

Alan Gauld alan.gauld at btinternet.com
Tue Nov 17 22:33:46 CET 2009

<mjekl at iol.pt> wrote 

>>> If you do you can call it explicitly, but if you do not then you  
>>> need to find a way of getting the OS to tell you, or to leave it to  
>>> the OS.

> I'm interested in nthis for the sake of generalizing (which is  
> better). How can I get the OS to tell me which program to use. 
> alternatively, how to tell the OS to open it - assuming that since the  
> os knows which program to use it will just use it 

This is where it gets messy.

The solution depends on the OS. If its Windows you can use Startfile.
If its MacOS you can interrogate the package manifest.
If its another Unix you can use any of several options depending on the 
flavour. The simplest is, I think, the file command, then if its a 
text file you can check the shebang line at the top of the file. But 
modern Unices, like Linux have file association tables - but these 
are often associated with the desktop environment - KDE, Gnome etc.
Finally for text files you should check the EDITOR and VISUAL 
environment variables - although these are increasingly not 
used or respected nowadays.

So you could write a program that checked the OS and then tried 
all of these options to identify the host application. But even then 
you are not guaranteed to succeed!

Finally you can try just running the file via os.system or the 
subprocess module and see what happens!

But there is no foolproof way of doing it on all OS. That's why 
its easier if you either know what app to use or create a 
config file such that the user can specify the app at install time.
On unix that would traditionally be called .myapprc aand be 
stored in each users home directory.

On Windows it would either be a registry entry or a myapp.ini file,
usually stored in the Windows directory or (better IMHO but against 
MS guidelines) in the app directory.


Alan Gauld
Author of the Learn to Program web site

More information about the Tutor mailing list