Python clear terminal without using system calls - python

I would like to write a python script for use on Windows and Linux that clears the screen.
Most of the examples for this are something like:
import os
os.system('cls')
which works, but is a bit dicey given all of the issues with making system calls (security issues). Is there a better way of clearing the terminal in python without needing to use system?
The best alternative I have found so far was this:
print("\033c");
but it has the slight annoyance of removing everything from the terminal
(ie I would like it to clear the terminal, but the user should be able to scroll up and see previous output in the terminal).

The following ANSI escape code should help on linux (and most *nix unless you find a really weird terminal):
print("\x1b[2J\x1b[H",end="")
It'll clear the screen and put your cursor at the top left. You can still scroll up to find your old stuff but you may have to go up a decent distance to find it.
I have absolutely no idea what it'll do on windows. You may find you need to detect the os and use a different method there.
For python 2.x you'll need to use sys.stdout.write instead of the print statement as you can't suppress the \n on print in 2.x as far as I know.

If you have special knowledge of the screen size you can use a modified version of your original print-based answer.
def cls(x):
"""Clears the screen after printing x newlines."""
print "\n" * x
print "\033c"
In Python 3.3 and later you can divine the size of the Terminal window with shutil, but I don't think there's a great way to do it in 2.7 without actually importing os, which you said should be avoided.

This piece of code doesn't call os directly from the code.
Try this:
from subprocess import call
def clear(int=None):
call('clear')
if int == 0:
exit()
clear()
It worked for me, I work on linux but I think it will work on windows to.

Related

ubuntu python script use PyAutoGui to press some buttons not run when make the focus on the sublime text editor

I wrote this script in python
import pyautogui
import time
time.sleep(.1)
pyautogui.keyDown("ctrl")
pyautogui.press("a")
pyautogui.keyUp("ctrl")
pyautogui.press("c")
pyautogui.press("p")
pyautogui.press("p")
pyautogui.press("t")
pyautogui.press("enter")
pyautogui.keyDown("ctrl")
pyautogui.keyDown("shift")
pyautogui.press(",")
pyautogui.keyUp("ctrl")
pyautogui.keyUp("shift")
pyautogui.press("tab")
And I created a shortcut in ubuntu to run it. python3 Scripts/cpp.py
The script works correctly when I make focus on any text element (on the browser for example). But when I make focus on the sublime text or any other text editor It does not work.
What is the reason for this issue?
(This script makes sense and do something useful for me)
If you’re running your program as administrator, pyautogui won’t be able to interact with it. This can catch people out pretty easily because you can set certain programs to always run as administrator, so it won’t be the first thing you think of. This is the case for Windows anyway.
On Ubuntu, from your experience, it seems like it is actually important to run it as an admin. So I guess in general keep the privileges in mind when you have programs interacting with other programs.
Also, your script can be cleaned up a bit.
# Probably a good idea to have a bit of a slightly longer sleep.
time.sleep(0.3)
#pyautogui.keyDown("ctrl")
#pyautogui.press("a")
#pyautogui.keyUp("ctrl")
# Is equivalent to
pyautogui.hotkey("ctrl", "a")
# The next block looks like you're writing text. So write some text.
#pyautogui.press("c")
#pyautogui.press("p")
#pyautogui.press("p")
#pyautogui.press("t")
pyautogui.write("cppt")
pyautogui.press("enter")
#pyautogui.keyDown("ctrl")
#pyautogui.keyDown("shift")
#pyautogui.press(",")
#pyautogui.keyUp("ctrl")
#pyautogui.keyUp("shift")
# Again, use a hotkey here.
pyautogui.hotkey("ctrl", "shift", ",")
pyautogui.press("tab")

Is there still a way to clear the screen in python?

So I just want to know because it is not working with the other commands, for instance, the ANSI way to clear and the os module way or the function. Nothing is working. Does this still exist?
You can use:
os.system('clear') # linux/osx
os.system('cls') # windows

Python hide already printed text

I'm creating a simple two-player board game where each player must place pieces on their own boards. What I would like to do is by either:
opening a new terminal window (regardless which OS the program is run on) for both players so that the board is saved within a variable but the other player cannot scroll up to see where they placed their pieces.
clearing the current terminal completely so that neither player could scroll and see the other player's board. I am aware of the unix 'clear' command but it doesn't achieve the effect I'm after and doesn't work with all OS's (though this might be something that I'll have to sacrifice to get a working solution)
I have tried clearing the screen but haven't been able to completely remove all the text. I don't have a preference; whichever method is easier. Also, if it would be easier to use a different method that I haven't thought of, all other suggestions are welcome. Thanks in advance!
EDIT: Other solutions give the appearance that text has been cleared but a user could still scroll up and see the text that was cleared. I'd like a way to remove any way that a user could see this text.
EDIT 2: Please read the other answers and the comments as they provide a lot of information about the topic as a whole. In particular, thanks to #zondo.
Consider using a portable terminal handling library. They abstract away the system specifica of common tasks like erasing the "screen" (i.e. terminal), or placing output at a specific position on the "screen" (again, meaning the text terminal). However, to use such a library effectively, you often have to switch to its style of generating output on the screen instead of naively printing strings.
curses is one such library (based on the C library ncurses) and included in the Python standard library. To get started, be sure to have a look at the curses tutorial in the official Python documentation.
I'd personally just use this.
import os
os.system("cls" if os.name == "nt" else "clear") #"cls" for Windows, otherwise "clear"
I would recomend a simple ANSI escape code to move the cursor position, Cursor Escape Codes, to the start of the board everytime. There is also an ANSI escape code that completly clears the console though, so you can choose.
If you are on windows you must first import colorama a module that makes windows prompt be able to use the ANSI codes as such:
import colorama # OR: from colorama import init
colorama.init() # AND THEN: init()
So if your board has n rows, after the user input for their turn, you move the cursor UP n rows + however many were required for user input, so if you wrote Input row, col: ... then you would go UP n+1, etc...
A simple example:
numLines = 1
print("Hello world!")
print("\033[<{0}>A".format(numLines), "This came AFTER hello world line")
You may not like this, it's a bit higher level than a basic two player board game, but there is always using some sort of GUI.
I personally like tkinter myself.
You don't want the option of people scrolling up to see printed text, but you can't remove what has been printed, that's like asking a printer to remove ink off a page. It's going to stay there.
Research a GUI interface, and try and make the game in that. Otherwise, you could let me take a stab at creating a explanatory piece of code that shows you how to use tkinter. If you do, link me the game you have so I can understand what you want.

IPython - cycle through blocks in input history?

Say I input the following:
def foo():
print(2)
Then later, when I want to edit my function, I press the Up arrow key to rewrite it, and that cycles through my inputs one line at a time (i.e. first it shows print(2), then def foo():). Is there any way to make it cycle through blocks of code the way IDLE does it?
I have this problem with an earlier version of iPython on Linux (11 I think). New versions do not do this.
I currently still use 11, and my solution was to just use the iPython qtconsole instead which does what you want. I would assume it would do the same on Windows.
Since IPython has stopped using readline, this issue has come back, the "solution" is to use PageUp and PageDown instead C-up and C-down.

keyboard short cut for accessing previous statements in python IDLE using a Mac

Is there a keyboard short cut for accessing previous statements in python IDLE? I am using a Mac
Thanks
On Windows this hotkey is alt-p.
However, assuming IDLE has options in Mac ;) you should be able to find out by going to Options->Configure IDLE. Then look in the Keys tab and under Custom Key Bindings, look for "history-previous".
That should tell you what you need to know.
Using IDLE on the MAC you would need Ctrl+P (not command) for Previous statement (instruction) and Ctrl+N for Next statement.
I was struggling with this same question as I am always using the Up arrow on most of the "shell" style programs.
Also, you can scroll back up to any previous line and hit 'return', which will place that statement in the current working line.

Categories