Is there a simple way to lauch the systems default editor from a Python command-line tool, like the webbrowser module?
-
Which filetype? For .txt and .py, opening with default application is good enough. For other filetypes, you might not get an editor. – u0b34a0f6ae Sep 18 '09 at 11:34
-
In my case I need to edit .xml and normal text (like commit messag in svn). – pkit Sep 18 '09 at 15:43
4 Answers
Under windows you can simply "execute" the file and the default action will be taken:
os.system('c:/tmp/sample.txt')
For this example a default editor will spawn. Under UNIX there is an environment variable called EDITOR, so you need to use something like:
os.system('%s %s' % (os.getenv('EDITOR'), filename))
- 971
- 1
- 9
- 20
- 194
- 2
-
1
-
-
1@exhuma if $EDITOR isn't set then you don't have *user-set* default to work with. On OS X you can `subprocess.call(["open, "
"])` to use the default application, just like if you used the GUI. On linux you can `subprocess.call(["xdg-open", " – conner.xyz Aug 27 '15 at 22:27"])` like @u0b34a0f6ae suggested. `suprocess` is used here instead of `system` since `subprocess` is intended to replace `system`. It's more secure and provides methods like `Popen` that provide greater flexibility. -
What if it's not a .txt file? What if you want to edit a .html file using default editor? – niCk cAMel May 05 '17 at 11:56
The modern Linux way to open a file is using xdg-open; however it does not guarantee that a text editor will open the file. Using $EDITOR is appropriate if your program is command-line oriented (and your users).
- 45,417
- 14
- 88
- 100
If you need to open a file for editing, you could be interested in this question.
-
(This caveat also applies to my answer) If viewer and editor are separate, this opens the viewer in 9/10 cases. Call it on a HTML file and the web browser will open it for *viewing*. – u0b34a0f6ae Sep 18 '09 at 11:32
-
You're right, of course :) Maybe the OP will clarify which filetype she needs to handle.. – Joril Sep 18 '09 at 13:04
You can actually use the webbrowser module to do this. All the answers given so far for both this and the linked question are just the same things the webbrowser module does behind the hood.
The ONLY difference is if they have $EDITOR set, which is rare. So perhaps a better flow would be:
editor = os.getenv('EDITOR')
if editor:
os.system(editor + ' ' + filename)
else:
webbrowser.open(filename)
OK, now that I’ve told you that, I should let you know that the webbrowser module does state that it does not support this case.
Note that on some platforms, trying to open a filename using this function, may work and start the operating system's associated program. However, this is neither supported nor portable.
So if it doesn't work, don’t submit a bug report. But for most uses, it should work.
- 612
- 8
- 25
- 13,936
- 8
- 61
- 82