Ncurses, python, and OSX Lion - python

I'm new to nurses, and trying it out on my OSX Lion with some python code. I've ran across a weird bug, and I don't know what I'm doing wrong. I've Googled extensively, and can't find a similar issue, even in linux. I've selectively removed lines to see if one of them is an issue, also. When I run the code below, I get nothing. No menu, and my terminal is messed up, if I hit enter, you see what I get in the picture below. I have to type a reset to make it work well again. Can anyone give me suggestions, or point me in the direction where to look? I would really appreciate it. Thanks.
Script:
import curses
screen = curses.initscr() # Init curses
curses.noecho() # Suppress key output to screen
curses.curs_set(0) # remove cursor from screen
screen.keypad(1) # set mode when capturing keypresses
top_pos = 12
left_pos = 12
screen.addstr(top_pos, left_pos, "This is a String")
Result:
BTW, I'm using the default python and libs in Lion, no macports. I'd like to use the native libraries, if possible.

You have 2 problems.
After adding the string to the screen with addstr you don't tell it to refresh the screen. Add this after the call to addstr:
screen.refresh()
You need to call endwin() at the end of you program to reset the terminal. Add this to the end of your program:
curses.endwin()
That said, after making those 2 changes when you run your program it will appear to do nothing because after displaying the string on the screen curses exits and returns the screen to the state before you ran the program.
Add this before the call to endwin():
screen.getch()
Then it will wait for you press a key before exiting.

Related

how to update stdscr size with python curses after resizing the terminal

I tried searching everywhere on the internet, but nowhere did I find an answer that worked for me, so I'm asking a new question.
In my code, I'm telling curses to get the terminal size and update some variables according to it. On my first try, I did something like this (this is the function that gets called after the window has been resized manually):
def resize():
rows, cols = stdscr.getmaxyx()
#some more code irrelevant to the question
When I found out that doesn't work, I realised that the stdscr is probably not getting resized, even though the terminal is. So I tried closing the stdscr and initialising it again:
def resize():
curses.endwin()
curses.wrapper(initialise)
#some more code that's irrelevant to the question
#showing the initialise function just in case:
def initialise(stdscrarg):
global stdscr
stdscr = stdscrarg
That, however, also didn't work. In other words, the stdscr initialised in the size that the terminal had before resizing. i.e. if I had a terminal over a quarter of my screen and then resized it to full screen, the function would correctly deal with the warping of the text, but it would redraw the content adjusted to just the original quarter of the screen, and would leave the junk characters in the rest of the screen, like this:
Before resizing
After resizing, before refreshing
After refreshing.
As you can see, the stdscr has initialised to its original size instead of taking on the size of the terminal. And I have tested it and confirmed that it really is the size of the stdscr, and not just the text printed on it (as when I gradually add strings to it, it throws an error when it reaches the end of the original size screen, instead of continuing to the end of the terminal screen and only then throwing an error.)
My question is: How can I get the new size of the terminal and make stdscr initialise with this new size?
Working on Windows 11, Python 3.10, module curses (though when installing it through pip, its name is windows-curses)

How to clear pycharm output terminal with code? [duplicate]

Is there a way to clear the "Run" console in PyCharm?
I want a code that delete/hide all the print() made previously.
Like the "clear_all" button, but without having to press it manually.
I have read that there is a way to do it in a terminal with os.system("cls"), but in PyCharm, it only adds a small square without clearing anything.
Also, I don't want to use print("\n" *100) since I don't want to be able to scroll back and see the previous prints.
In Pycharm:
CMD + , (or Pycharm preferences);
Search: "clear all";
Double click -> Add keyboard shortcut (set it to CTRL + L or anything)
Enjoy this new hot key in your Pycharm console!
Pycharm Community Edition 2020.1.3
You can right click anywhere above the current line on the console, and choose the "Clear All" option. It'll clear the console
How to
Download this package https://github.com/asweigart/pyautogui. It allows python to send key strokes.
You may have to install some other packages first
If you are installing PyAutoGUI from PyPI using pip:
Windows has no dependencies. The Win32 extensions do not need to be
installed.
OS X needs the pyobjc-core and pyobjc module installed (in that
order).
Linux needs the python3-xlib (or python-xlib for Python 2) module
installed.
Pillow needs to be installed, and on Linux you may need to install additional libraries to make sure Pillow's PNG/JPEG works correctly. See:
Set a keyboard shortcut for clearing the run window in pycharm as explained by Taylan Aydinli
CMD + , (or Pycharm preferences);
Search: "clear all"; Double click ->
Add keyboard shortcut (set it to CTRL + L or anything)
Enjoy this new hot key in your Pycharm console!
Then if you set the keyboard shortcut for 'clear all' to Command + L use this in your python script
import pyautogui
pyautogui.hotkey('command', 'l')
Example program
This will clear the screen after the user types an input.
If you aren't focused on the tool window then your clear hot-key won't work, you can see this for yourself if you try pressing your hot-key while focused on, say, the editor, you won't clear the embedded terminals contents.
PyAutoGUI has no way of focusing on windows directly, to solve this you can try to find the coordinate where the run terminal is located and then send a left click to focus, if you don't already know the coordinates where you can click your mouse you can find it out with the following code:
import pyautogui
from time import sleep
sleep(2)
print(pyautogui.position())
An example of output:
(2799, 575)
and now the actual code:
import pyautogui
while True:
input_1 = input("?")
print(input_1)
pyautogui.click(x=2799, y=575)
pyautogui.hotkey('command', 'l')
Easy Method:
Shortcut: Control K,
Right click on terminal and clear Buffer
There's also another way of doing it using the system class from os. All you need to do is have this code:
from os import system, name
# define our clear function
def clear():
# for windows the name is 'nt'
if name == 'nt':
_ = system('cls')
# and for mac and linux, the os.name is 'posix'
else:
_ = system('clear')
# Then, whenever you want to clear the screen, just use this clear function as:
clear()
However, in order for this functionality to work in pycharm, you need to enable "Emulate terminal in output console". You can find this under edit configuration of the file where you want to use the clear function, then it's under Execution option. Here's a screenshot: pycharm screensho
You could just do a ("\n" * 100000000), so it'll be impossible to scroll back.
In PyCharm terminal you can type 'cls' just like in linux terminal.
For Python Console (where you see the output) assign a shortkey for "clear all" in File -> Settings -> Keymap -> Other -> "Clear all"
You can also click somewhere on the PythonConsole -> Right button -> clear.
Hope it helps
I just relised that instead of going to the trouble of setting up a shortcut, you could just set up a command using PyAutoGUI to click on the trash bin on the side of the window e.g
note, to install pyautogui click on the end of the import pyautogui line, then press alt+enter and click install pyautogui.
import pyautogui
# to find the coordinates of the bin...
from time import sleep
sleep(2) # hover your mouse over bin in this time
mousepos = pyautogui.position() gets current pos of mouse
x,y = mousepos # storing mouse position
print(mousepos) # prints current pos of mouse
# then to clear it;
pyautogui.click(x, y) # and just put this line of code wherever you want to clear it
(this isn't perfect thanks to the time it takes to run the code and using the mouse, but it is reasonable solution depending on what you are using it for.)
I hope this answer is helpful even though this is an old question.
Just click the trash can icon to the left of the command window and it clears the command history!
In PyCharm 2019.3.3 you can right click and select "Clear All" button.This is deleting all written data inside of the console and unfortunately this is manual.
Sorry to say this, here the main question is how to do it programmatically means while my code is running I want my code to clear previous data and at some stage and then continue running the code. It should work like reset button.
After spending some time on research I solved my problem using Mahak Khurmi's solution https://stackoverflow.com/a/67543234/16878188.
If you edit the run configuration you can enable "emulate terminal in output console" and you can use the os.system("cls") line and it will work normally.
Iconman had the easiest answer.
But simply printing "\n" * 20 (or whatever your terminal height is) will clear the screen, and the only difference is that the cursor is at the bottom.
I came here because I wanted to visually see how long each step of a complex process was taking (I'm implementing a progress bar), and the terminal is already full of scrolling logging information.
I ended up printing ("A" * 40) * 20, and then "B" and "C" etc., and then filming it. Reviewing the video made it easy to see how many seconds each step took. Yes I know I could use time-stamps, but this was fun!

Blessings: how to move cursor to bottom of screen on exit?

I'm trying out some cursor-graphical output of a Python script, to give my app a nice progress bar.
I use the following to ensure my screen is blank before displaying output.
print term.clear
But when my Python script finishes, my shell prompt is output at the top of the screen, overwriting part of the progress bar.
How can I move the cursor to below my graphical output as the Python script exits? I have tried this right before exiting the script:
print term.move(0, term.height-1)
But this seems to be ignored. My shell begins output at the top of the screen.
I don't want to enter fullscreen mode, I'd like to leave the final output of the progress bar on the screen after the script finishes.
My environment is:
OS X 10.10 Terminal in xterm-256 mode.
Python 2.7.10
Blessings 1.6
I think you have the arguments to term.move() backwards (based on the "Moving Permanently" section here).
move() Parameters are y coordinate, then x coordinate.
Try this:
print term.move(term.height - 1, 0)

python curses tty screen blink

I'm writing a python curses game (https://github.com/pankshok/xoinvader).
I found a problem: in terminal emulator it works fine, but in tty screen blinks.
I tried to use curses.flash(), but it got even worse.
for example, screen field:
self.screen = curses.newwin(80, 24, 0, 0)
Main loop:
def loop(self):
while True:
self.events()
self.update()
self.render()
render: (https://github.com/pankshok/xoinvader/blob/master/xoi.py#L175)
self.screen.clear()
#draw some characters
self.screen.refresh()
time.sleep(0.03)
Constant time in sleep function is temporary, until I write 60 render calls controller.
How to implement render method correctly?
Thanks in advance,
Paul.
Don't call clear to clear the screen, use erase instead. Using clear sets a flag so that when you call refresh the first thing it does is clear the screen of the terminal. This is what is causing the terminal's screen to appear to blink. The user sees the old screen, then a completely blank screen, then your new screen. If you use erase then it will instead modify the old screen to look like the new one.
You may still see some odd flashing or other artifacts on slow terminals. Try calling screen.idcok(False) and screen.idlok(False) to stop curses from using insert and deletion operations to update the screen.

Pressing keys with python win32api

I am trying to achieve the following behavior in a PYTHON 2.4 script, here are the steps, and after them, the question:
Python script starts
The script gives a 3 seconds delay to change to 'Z' program's window
The script does some clicks on the 'Z' program's window.
The script stops making clicks
/* ¿? */
Ask to continue with the program's excecution
/* ¿? */
Go to step 2
So, in steps 5 and 7 what I want to do is simulate the pressing of keys Alt+Tab in order to go back to the script window (in step 5), and go back again to the 'Z' program's window (in step 7).
And the problem is that I have no idea how to achieve this (the simulation to press keys alt+tab), and didn't find answers to my doubts.
I am using the python win32api modules to positionate mouse in a certain point and make the clicks, but I don't find the way to simulate the key pressing.
Try This :
1) Use : https://gist.github.com/chriskiehl/2906125
2)
import win32api
import win32com.client
shell = win32com.client.Dispatch("WScript.Shell")
shell.Run("app")
win32api.Sleep(100)
shell.AppActivate("myApp")
win32api.Sleep(100)
shell.SendKeys("name")
win32api.Sleep(500)
shell.SendKeys("{ENTER}")
win32api.Sleep(2500)
shell.SendKeys("^a") # CTRL+A may "select all" depending on which window's focused
shell.SendKeys("{DELETE}") # Delete selected text? Depends on context. :P
shell.SendKeys("{TAB}") #Press tab... to change focus or whatever
You need the WinApi function SendInput.
See the description in the MSDN:
http://msdn.microsoft.com/en-us/library/windows/desktop/ms646310(v=vs.85).aspx
An Easier Way
Use this Library W32S
My Library.
And If u want , just copy the source instead

Categories

Resources