Is there a way to programmatically clear the terminal across platforms in Python 3? - python-3.x

Long-time lurker, first time asker.
Is there a way to automatically clear the terminal in Python 3 regardless of what platform the app is being used in?
I've come across the following (from this answer) which utilises ANSI escape codes:
import sys
sys.stderr.write("\x1b[2J\x1b[H")
But for it to work cross-platform it requires the colorama module which appears to only work on python 2.7.
For context I'm learning Python by building a game of battleships, but after each guess I want to be able to clear the screen and re-print the board.
Any help is appreciated!
Cheers

I use a single snippet for all the platforms:
import subprocess
clear = lambda: subprocess.call('cls' if os.name=='nt' else 'clear')
clear()
Same idea but with a spoon of syntactic sugar:
import subprocess
clear = lambda: subprocess.call('cls||clear', shell=True)
clear()

I know of this method
import os
clear = lambda: os.system('cls')
clear()
I'm not sure if it works with other platforms, but it's working in windows python 3.x
import os
clear = lambda: os.system('clear')
clear()
That might work for linux and OS X, but I can't test.

Related

I want to embed python console in my tkinter window.. How can i do it?

I am making a text editor and want to add a feature of IDLE in my app. So i want an frame with python IDLE embedded in it with all menus and features which original python IDLE gives.
I looked in source of idle lib but cannot find a solution.
try:
import idlelib.pyshell
except ImportError:
# IDLE is not installed, but maybe pyshell is on sys.path:
from . import pyshell
import os
idledir = os.path.dirname(os.path.abspath(pyshell.__file__))
if idledir != os.getcwd():
# We're not in the IDLE directory, help the subprocess find run.py
pypath = os.environ.get('PYTHONPATH', '')
if pypath:
os.environ['PYTHONPATH'] = pypath + ':' + idledir
else:
os.environ['PYTHONPATH'] = idledir
pyshell.main()
else:
idlelib.pyshell.main()
This code is of pyshell.pyw found under idlelib folder in all python install
I searched the idle.pyw and found that it uses a program pyshell which is real shell. So how can i embed it.
I want a Tkinter frame with python IDLE shell embedded in it.Please give the code. Thanks in advance.
idlelib implements IDLE. While you are free to use it otherwise, it is private in the sense that code and interfaces can change in any release without the usual back-compatibility constraints. Import and use idlelib modules at your own rish.
Currently, a Shell window is a Toplevel with a Menu and a Frame. The latter has a Text and vertical Scrollbar. It is not possible to visually embed a Toplevel within a frame (or within another Toplevel or root = Tk()). top = Toplevel(myframe) works, but top cannot be placed, packed, or gridded within myframe.
I hope in the future to refactor editor.py and pyshell.py so as to separate the window with menu from the frame with scrollable text. The result should include embeddable EditorFrame and ShellFrame classes that have parent as an arguments. But that is in the future.
Currently, one can run IDLE from within python with import idlelib.idle. However, because this runs mainloop() (on its own root), it blocks and does not finish until all IDLE windows are closed. This may not be what one wants.
If having Shell run in a separate window is acceptable, one could extract from python.main the 10-20 lines needed to just run Shell. Some experimentation would be needed. If the main app uses tkinter, this function should take the app's root as an argument and not call mainloop().
Tcl having Tkcon.tcl . when each thread source (means run/exec) the Tkcon.tcl
each thread will pop up a Tk shell/Tk console/tkcon.tcl very good idea for debug. and print message individually by thread.
Python having idle.py ... and how to use it ? still finding out the example .
The are same Tk base . why can't find an suitable example? so far ... keep finding...

How to run PyQt5 GUIs in non-blocking threads?

I have a PyQt5 GUI class that I want to be able to create multiple instances of either from an interactive console or normal run. I need these GUIs to be non-blocking so that they can be used while subsequent code runs.
I've tried calling app.exec__() in separate threads for each GUI like this answer, but the program sometimes crashes as the comment on the answer warned it would:
Run pyQT GUI main app in seperate Thread
And now I'm trying to get the code below working which I made based on this answer:
Run Pyqt GUI main app as a separate, non-blocking process
But when I run it the windows pop and and immediately disappear
import sys
from PyQt5 import QtWidgets, QtGui, QtCore
import time
class MainWindow(QtWidgets.QWidget):
def __init__(self):
# call super class constructor
super(MainWindow, self).__init__()
# build the objects one by one
layout = QtWidgets.QVBoxLayout(self)
self.pb_load = QtWidgets.QPushButton('Load')
self.pb_clear= QtWidgets.QPushButton('Clear')
self.edit = QtWidgets.QTextEdit()
layout.addWidget(self.edit)
layout.addWidget(self.pb_load)
layout.addWidget(self.pb_clear)
# connect the callbacks to the push-buttons
self.pb_load.clicked.connect(self.callback_pb_load)
self.pb_clear.clicked.connect(self.callback_pb_clear)
def callback_pb_load(self):
self.edit.append('hello world')
def callback_pb_clear(self):
self.edit.clear()
def show():
app = QtWidgets.QApplication.instance()
if not app:
app = QtWidgets.QApplication(sys.argv)
win = MainWindow()
win.show()
if __name__ == '__main__':
show()
show()
EDIT - I don't see how this question is a duplicate. The 'duplicate' questions are only slightly related and don't provide solutions to my problem at all.
I want to be able to create multiple instances of a GUI (MainWindow in my example) by calling the show() function from either an interactive session or script, and I want those windows to stay on my screen while subsequent code is running.
EDIT2 - When I run the code as a script I can do what I want by using multiprocessing, see this demo:
https://www.screencast.com/t/5WvJNVSLm9OR
However I still need help because I want it to also work in interactive Python console sessions, and multiprocessing does not work in that case.
It isn't necessary to use separate threads or processes for this. You just need a way to maintain a reference to each new window when importing the script in a python interactive session. A simple list can be used for this. It is only necessary to explictly start an event-loop when running the script from the command-line; in an interactive session, it will be handled automatically by PyQt.
Here is an implementation of this approach:
...
_cache = []
def show(title=''):
if QtWidgets.QApplication.instance() is None:
_cache.append(QtWidgets.QApplication(sys.argv))
win = MainWindow()
win.setWindowTitle(title)
win.setAttribute(QtCore.Qt.WA_DeleteOnClose)
win.destroyed.connect(lambda: _cache.remove(win))
_cache.append(win)
win.show()
if __name__ == '__main__':
show('Foo')
show('Bar')
sys.exit(QtWidgets.QApplication.instance().exec_())
This is a minor addendum to #ekhumoro's answer. I don't have enough reputation to only add a comment so I had to write this as an answer.
#ekhumoro's answer almost fully answers #Esostack's question, but doesn't work in the Ipython console. After many hours of searching for the answer to this question myself, I came across a comment from #titusjan in a three year old thread (here) also responding to a good answer from #ekhumoro.
The missing part to #ekhumoro's answer which results in the gui windows freezing for Ipython specifically is that Ipython should be set to use the qt gui at launch or once running.
To make this work with Ipython:
Launch Ipython with ipython --gui=qt5
In a running Ipython console run the magic command %gui qt5
To fix it from a Python script you can run this function
def fix_ipython():
from IPython import get_ipython
ipython = get_ipython()
if ipython is not None:
ipython.magic("gui qt5")

Cross-Platform Console Clearing? [duplicate]

This question already has answers here:
How to clear the interpreter console?
(31 answers)
Closed 4 years ago.
What do I need to do if I want to clear the console without OS-Limitations?
I know that on Linux and Mac the command "clear" exists, whereas Windows has "cls".
I want to clear the console every now and then on the three major systems without personally choosing "clear" or "cls".
My idea so far was
import platform
os = platform.system()
if os == "Windows":
clear = 'cls'
else:
clear = 'clear'
and then just use clear as variable for both, depending on the OS, but it doesn't work. Is something like this actually possible?
For accuracy use sys and as a good practice use subprocess
#usr/bin/env python
from sys import platform
from subprocess import run
command = {'win32': 'cls', 'linux': 'clear'}
if __name__ == '__main__':
run(command[platform], shell=True)
As BartoszKP said there are many ways of doing this, I find this a very clean way of doing it.

Python command to stop and start windows services ?

what is the python command to stop and start windows services.I can't use win32serviceutil because am using latest python version 3.6.
You could use the sc command line interface provided by Windows:
import subprocess
# start the service
args = ['sc', 'start', 'Service Name']
result = subprocess.run(args)
# stop the service
args[1] = 'stop'
result = subprocess.run(args)
The existing answer is very unpythonic and not simple enough.
I was searching for a Pythonic solution and stumbled upon this question.
I have a much simpler solution that isn't Pythonic.
Just use net start servicename with os.system.
For example, if we want to start MySQL80:
import os
os.system('net start MySQL80')
Now using it as a function:
import os
def start_service(svc):
os.system(f'net start {svc}')
And to stop the service, use net stop servicename:
import os
def stop_service(svc):
os.system(f'net stop {svc}')
I know my solution isn't Pythonic but the existing answer also isn't Pythonic and so far in my Google searching I haven't found anything both relevant and Pythonic.
Install pywin32 from GitHub, there's no limitation regarding Python 3.6 in there(2017, I know) + it works directly with the Win32 API, so no os.system() or similar command calling. Also, no need for compiling, the author supplies the binaries in an installer. And there doesn't seem to be any issue with PyPI as well - the versions are matching.
Use the StartService(serviceName, args = None, machine = None) function.

Cross-platform screenshot in Python 3

There are quite a few questions like this one, but none of them seem to be both cross-platform and specifically for Python 3, and I'm struggling to find a reliable solution.
How can I take a cross-platform screenshot in Python 3?
My current solution has been to use the ImageGrab function from the PIL library, like so:
from PIL import ImageGrab
image = ImageGrab.grab()
You can use platform.system() to find the current OS, and then use a different solution depending on the operating system:
import platform
if platform.system()=="Windows":
...
elif platform.system()=="Darwin": #Mac
...
elif plarform.system()=="Linux":
...
You can use PrtSc Library.
Command : pip3 install PrtSc
Code :
import PrtSc.PrtSc as Screen
screen=Screen.PrtSc(True,"file.png")

Resources