Search code examples
pythonpython-3.xpython-idle

How can I open the currently running script's .py file using IDLE in Python?


In a GUI app written in Python and Tkinter, I want to add a menu command which will open the source code of the *.py file in IDLE. I also want it to be platform independent.

I've tried using os.system to open IDLE from Scripts folder of Python, but that would be platform dependent. I couldn't find a way to get the Scripts folder of Python to make it independent. How can I achieve this?


Solution

  • To open a file in an IDLE editor, the command line is

    <python> -m idlelib <path>
    

    where <python> is the full path to a python executable or a name that resolves to such. If you want to open IDLE with the same python that is running you python app, which is likely what you want, use the platform-independent sys.executable. The path to the source code for the running app is __file__. This is one of the semi-hidden global variables when python runs a file. Or give the path to any other file.

    Whether you use os.system or subprocess is a different issue. The latter is more flexible. subprocess.run replaces os.system. subprocess.Popen should not block. IDLE uses the latter to run user code.