Open file in IDLE through python script - python

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').

Related

How does django's `python manage.py shell` keep the command prompt open?

When you run python manage.py shell, (or shell_plus if you have the extension), the script will import some stuff for you and then open a regular python shell for you to try commands out, as opposed to running the script and immediately closing.
I know that you can use the -i switch when calling a script to keep the command prompt open, for example python -i foo.py will run the contents of foo.py yet keep the shell open instead of immediately closing.
I would guess that when you call django's manage.py shell it somehow uses the same feature to get the command prompt to stay open and not immediately close out.
How does it work? Can I add something to any script file to make it behave the same way (without using the -i switch) ?
As of 2.2.3, the shell management command has three programs it can start -- ipython, bpython, and python. For the first two, you can start the shells using python:
def ipython(self, options):
from IPython import start_ipython
start_ipython(argv=[])
def bpython(self, options):
import bpython
bpython.embed()
For python, django sets up readline and then uses code.interact to start the python interpreter:
def python(self, options):
import code
# Set up a dictionary to serve as the environment for the shell, so
# that tab completion works on objects that are imported at runtime.
imported_objects = {}
try: # Try activating rlcompleter, because it's handy.
import readline
except ImportError:
pass
else:
# We don't have to wrap the following import in a 'try', because
# we already know 'readline' was imported successfully.
import rlcompleter
readline.set_completer(rlcompleter.Completer(imported_objects).complete)
# Enable tab completion on systems using libedit (e.g. macOS).
# These lines are copied from Python's Lib/site.py.
readline_doc = getattr(readline, '__doc__', '')
if readline_doc is not None and 'libedit' in readline_doc:
readline.parse_and_bind("bind ^I rl_complete")
else:
readline.parse_and_bind("tab:complete")
# We want to honor both $PYTHONSTARTUP and .pythonrc.py, so follow system
# conventions and get $PYTHONSTARTUP first then .pythonrc.py.
if not options['no_startup']:
for pythonrc in OrderedSet([os.environ.get("PYTHONSTARTUP"), os.path.expanduser('~/.pythonrc.py')]):
if not pythonrc:
continue
if not os.path.isfile(pythonrc):
continue
with open(pythonrc) as handle:
pythonrc_code = handle.read()
# Match the behavior of the cpython shell where an error in
# PYTHONSTARTUP prints an exception and continues.
try:
exec(compile(pythonrc_code, pythonrc, 'exec'), imported_objects)
except Exception:
traceback.print_exc()
code.interact(local=imported_objects)

Python RPi - File not found when running script from another script

I'm trying to run a python script from another python script on a Raspberry Pi 3 with Raspbian. I've been trying to find ways to do this for some hours and didn't find anything that worked. I've tried some ways but it either says that has not permission to execute the file or it can't find it. I don't know what I'm doing wrong. I need to run multiple instances of the other script through the main script in a new console (new processes) and keep them running (I don't expect them to return anything to the main script). Can anyone help me? Because with Windows it was really easy as the program was working fine until I tried to run it on Linux (with Windows, I used os.startfile).
In test.py:
print("test1")
input()
In main.py:
import os
import subprocess
print("main")
os.system("python test.py")
input()
In the console:
main
python: can't open file 'test.py': [Errno 2] No such file or directory
In main.py:
import os
import subprocess
print("main")
subprocess.Popen("python test.py",shell=True)
input()
In the console:
main
python: can't open file 'test.py': [Errno 2] No such file or directory
In main.py:
import os
import subprocess
print("main")
subprocess.call("python test.py",shell=True)
input()
In the console:
main
python: can't open file 'test.py': [Errno 2] No such file or directory
I tried more ways but I don't remember them. Maybe I'm doing something wrong?
EDIT: I can now run the scripts without any problems with os.chdir (thanks to J H). My problem now is that it prints test in the same console window as the main.py and I needed it to create another process for the test.py. Any solutions?
EDIT 2: Finally I could start a new processes of the test.py from the main.py! I used os.system('xdg-open "test.py"') to open test.py with the default application. Anyway thanks to J H, otherwise it would continue to say file not found.
Final main.py:
import os
print("main")
os.chdir('/home/pi/Desktop/')
os.system('xdg-open test.py')
input()
Thanks in advance!
Printing out os.getcwd() will help you to debug this.
Either supply a fully qualified pathname, /some/where/test.py, or use os.chdir('/some/where') before executing test.py.

How to launch a Window's shortcut using Python

I want to launch a shortcut named blender.ink located at "D://games//blender.ink". I have tryed using:-
os.startfile ("D://games//blender.ink")
But it failed, it only launches exe files.
The Python os.startfile function should work fine, but you need to specify a .lnk extension to be a valid Windows shortcut file:
import os
os.startfile (r"D:\games\blender.lnk")
If you need to wait for the application to complete before continuing, then a different approach would be needed as follows:
import win32com.shell.shell as shell
import win32event
se_ret = shell.ShellExecuteEx(fMask=0x140, lpFile=r"D:\games\blender.lnk", nShow=1)
win32event.WaitForSingleObject(se_ret['hProcess'], -1)

how to run python script from the console as if called from command prompt?

The python script I would use (source code here) would parse some arguments when called from the command line. However, I have no access to the Windows command prompt (cmd.exe) in my environment. Can I call the same script from within a Python console? I would rather not rewrite the script itself.
%run is a magic in IPython that runs a named file inside IPython as a program almost exactly like running that file from the shell. Quoting from %run? referring to %run file args:
This is similar to running at a system prompt python file args,
but with the advantage of giving you IPython's tracebacks, and of
loading all variables into your interactive namespace for further use
(unless -p is used, see below). (end quote)
The only downside is that the file to be run must be in the current working directory or somewhere along the PYTHONPATH. %run won't search $PATH.
%run takes several options which you can learn about from %run?. For instance: -p to run under the profiler.
If you can make system calls, you can use:
import os
os.system("importer.py arguments_go_here")
You want to spawn a new subprocess.
There's a module for that: subprocess
Examples:
Basic:
import sys
from subprocess import Popen
p = Popen(sys.executable, "C:\test.py")
Getting the subprocess's output:
import sys
from subprocess import Popen, PIPE
p = Popen(sys.executable, "C:\test.py", stdout=PIPE)
stdout = p.stdout
print stdout.read()
See the subprocess API Documentation for more details.

Running 3 python programs by a single program via subprocess.Popen method

I am trying to run 3 python programs simultaneously by running a single python program
I am using the following script in a separate python program sample.py
Sample.py:
import subprocess
subprocess.Popen(['AppFlatRent.py'])
subprocess.Popen(['AppForSale.py'])
subprocess.Popen(['LandForSale.py'])
All the three programs including python.py is in the same folder.
Error: OSError: [Errno 2] No such file or directory
Can someone guide me how can i do it using subprocess.Popen method?
The file cannot be found because the current working directory has not been set properly. Use the argument cwd="/path/to/script" in Popen
It's because your script are not in the current directory when you execute sample.py.
If you three script are in the same directory than sample.py, you could use :
import os
import subprocess
DIR = os.path.dirname(os.path.realpath(__file__))
def run(script):
url = os.path.join(DIR, script)
subprocess.Popen([url])
map(run, ['AppFlatRent.py','AppForSale.py', 'LandForSale.py'])
But honestly, if i was you i will do it using a bash script.
There might be shebang missing (#!..) in some of the scripts or executable permission is not set (chmod +x).
You could provide Python executable explicitly:
#!/usr/bin/env python
import inspect
import os
import sys
from subprocess import Popen
scripts = ['AppFlatRent.py', 'AppForSale.py', 'LandForSale.py']
def realpath(filename):
dir = os.path.realpath(os.path.dirname(inspect.getsourcefile(realpath)))
return os.path.join(dir, filename)
# start child processes
processes = [Popen([sys.executable or 'python', realpath(scriptname)])
for scriptname in scripts]
# wait for processes to complete
for p in processes:
p.wait()
The above assumes that script names are given relative to the module.
Consider importing the modules and running corresponding functions concurently using threading, multiprocessing modules instead of running them as scripts directly.

Categories