-->

Lauch default editor (like 'webbrowser' mo

2020-08-11 00:00发布

问题:

Is there a simple way to lauch the systems default editor from a Python command-line tool, like the webbrowser module?

回答1:

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))



回答2:

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).



回答3:

If you need to open a file for editing, you could be interested in this question.



回答4:

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.