简体   繁体   中英

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.

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? )

One can run IDLE from a command line on any platform with <python> -m idlelib <IDLE args> , where <python> could be 'python', 'python3', or something line 'py -3.8', depending on the platform. <IDLE args> are defined in the "Command line usage" subsection of the IDLE doc , also available within IDLE as Help => IDLE Help.

A possible 'IDLE arg' is the path of a file to be opened in an editor window. Relative paths are relative to the current working directory, which can be changed with the 'cd' command. A working command line can used quoted or turned into a list for a subprocess.run or subprocess.Popen call. In Python code, the working directory is changed with os.chdir('newdir') .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM