How to open a Python Script in IDLE from a Python script

Viewed 193

So I've been finding a few answers but none of them do the trick. I'd like to open a file (script.py) in IDLE using a python script (openscript.py). It seems os.system or subprocess.Popen should do the trick but I can't seem to find the correct link to open in IDLE.

import os
def openFile():
    filename = "script.py"
    os.system("C:\\Program Files\\Python38\\Lib\\idlelib\\idle.pyw " + filename)

openFile()
1 Answers

Since .pyw is Windows-only, you must be running on Windows. When asking a question, always give the error message, as it likely has the answer. On Win10, your code results in a Windows error box saying that there is no app associated with that file and a suggestion to install one if needed. Replacing os.system with subprocess.run gives the error OSError: [WinError 193] %1 is not a valid Win32 application. So replace idle.pyw with the application that will run IDLE. The following (saved as tem3.py) works for me when run either from an IDLE editor or Command Prompt.

import subprocess as sub
def openFile():
    filename = "f:/Python/a/tem3.py"
    sub.run(r"C:\Programs\Python39\pythonw.exe -m idlelib " + filename)

openFile()
Related