How to open python file in default editor from Python script

Question:

When I try on Windows
webbrowser.open(fname) or os.startfile(fname) or os.system ('cmd /c "start %s"' % fname)
my python script is getting executed.

How to open it for edit in default editor (like SQL script)

Edit:

import ctypes

shell32 = ctypes.windll.shell32
fname = r'C:Scriptsdelete_records.py'

shell32.ShellExecuteA(0,"open",fname,0,0,5)

it opens file explorer at C:Program Filesibmgsk8lib64C

Asked By: Alex B

||

Answers:

"""
Open the current file in the default editor
"""

import os
import subprocess

DEFAULT_EDITOR = '/usr/bin/vi' # backup, if not defined in environment vars

path = os.path.abspath(os.path.expanduser(__file__))
editor = os.environ.get('EDITOR', DEFAULT_EDITOR)
subprocess.call([editor, path])
Answered By: Jonathan Eunice

Default open and edit actions are handled by ShellExecute WinAPI function (actions are defined in registry in HKEY_CLASSES_ROOT subtree).

There are couple of way to access WinAPI from Python script.

  1. Using nicer wrapper like pywin32. It is safer than ctypes, but it is non-standard Python module. I.e:

    import win32api
    win32api.ShellExecute(None, "edit", "C:\Public\calc.bat", None, "C:\Public\", 1)
    
  2. Using ctypes. It is trickier and doesn’t control arguments, so may cause fault (unless you provide result type and arguments type manually).

    import ctypes
    ShellExecuteA = ctypes.windll.shell32.ShellExecuteA
    ShellExecuteA(None, "edit", "C:\Public\calc.bat", None, "C:\Public\", 1)
    

To check which actions are supported for desired filetype, do the following:

  1. Run regedit.exe
  2. Go to HKEY_CLASSES_ROOT and pick desired extension, i.e. .py. Read (Default) value on left pane – it would be class name, i.e. Python.File.
  3. Open that class name subtree in HKEY_CLASSES_ROOT. It should contain shell subtree, under which you will find available shell actions. For me and Python scripts they are Edit with IDLE and Edit with Pythonwin.
  4. Pass these values as second parameter of ShellExecute()
Answered By: myaut

As per the documentation of os.startfile, you can define an operation to execute. So os.startfile(fname,operation='edit') shoudl work for what you want. See also this answer.

Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.