2

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:\Scripts\delete_records.py'

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

it opens file explorer at C:\Program Files\ibm\gsk8\lib64\C

Alex B
  • 2,165
  • 2
  • 27
  • 37
  • Are you asking about Windows? It thing [ShellExecute](https://msdn.microsoft.com/en-us/library/windows/desktop/bb762153%28v=vs.85%29.aspx) should do the trick. It is available from various Win32 API wrappers like pywin32 – myaut Mar 16 '15 at 20:18
  • Possible duplicate of http://stackoverflow.com/a/435669/1909577 – Vinod Sharma Mar 16 '15 at 20:26
  • @myaut Sorry, it's on Windows. – Alex B Mar 16 '15 at 20:36
  • @VinodSharma I do not see solution there – Alex B Mar 16 '15 at 20:39
  • 1
    > tried < you should write "edit" instead "open" as second parameter of ShellExecute (of course it works if appropriate operation is defined in registry in HKEY_CLASSES_ROOT) – myaut Mar 16 '15 at 20:43

3 Answers3

3
"""
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])
Jonathan Eunice
  • 21,653
  • 6
  • 75
  • 77
2

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()
myaut
  • 11,174
  • 2
  • 30
  • 62
0

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.