Search code examples
pythonpython-3.xpython-idle

Open file in IDLE through python script


How would I open a specific file in IDLE through a python script?

I understand that an app could be opened through subprocess:

import subprocess
subprocess.call('C:\\program.exe')

But I can't figure out how to make it open a file.

If it helps, this:

import os.path
import sys

# Enable running IDLE with idlelib in a non-standard location.
# This was once used to run development versions of IDLE.
# Because PEP 434 declared idle.py a public interface,
# removal should require deprecation.

idlelib_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
if idlelib_dir not in sys.path:
    sys.path.insert(0, idlelib_dir)

from idlelib.pyshell import main
main()

also opens IDLE. I checked, and main() does not take any parameters such as files to open.

I am using Windows 10 with Python 3.6.4.

Any help is greatly appreciated.


Solution

  • Here are 2 ways to open any python file through IDLE

    import subprocess
    
    p = subprocess.Popen(["idle.exe", path_to_file])
    # ... do other things while idle is running
    returncode = p.wait() # wait for notepad to exit
    

    OR:

    import subprocess
    import os
    
    subprocess.call([path_to_idle, path_to_file])
    

    You can also use these methods to open any file with any installed app (How can I open files in external programs in Python?)