William Welch William Welch - 1 year ago 50
Linux Question

Code to open a file like double clicking on it

When a file is double clicked in a file manager it is automatically opened using the application associated with the type of the file.

How can I do the same from code. I am open to any programming language. I have a little experience with Python and C.

My target operating systems are Ubuntu Linux and OSX. However, ideally I would like to find a solution that works with Windows, OSX, and Ubuntu linux.

Answer Source

For MAC os x

In your terminal in os x you can use the command open to open files with the default application. In python you can use the os module to immitate shell commands. So you should try this code:

os.system("open foo.doc")

Or if you want to force a window to open when there already is an instance of that window:

os.system("open -n foo.doc")

os.system("command") just executes a command from the command line. And open opens a file with its default application.

For linux

use xdg-open. For examples refer to this article.