Prompt at the bottom of terminal and printout scrolls at the top in python - python-3.x

I am using Python 3.X and looking for a simplest way to have input at the lowest line and all print information scroll above it. For example if I have print("hello world"), it would print at the top and if I have name = input("What is your name"), it would be printed on the last line. It seems like there should be a super simple way to do it without using library like the rich.

So effectively you want the behavior that would occur when the terminal starts scrolling? Just dump a full screen of newlines when you start your program.
print('\n' * 200)

Related

How to Create a Cursor or Loading Indicator for an Infinite Loop

I am scraping current follow requests from Instagram. I have a main infinite loop that it making the requests and prints OK when it is done. I want to display an animated cursor or loading progress while it is downloading names.
while 1:
response = requests.get(IG_CFR_PAGE, headers=headers(""), params=params, cookies=cookies)
if response.status_code == 200:
cfr = response.json()
for entry in cfr["data"]["data"]:
#print(entry["text"])
usernames.append(entry["text"])
if cfr["data"]["cursor"]!= None:
params['cursor'] = cfr["data"]["cursor"]
time.sleep(1)
else:
break
else:
print(response.status_code)
print("Error in request .... aborting")
break
print("ok")
I looked for tqdm but it takes an iterable. In my case, I am just looping over JSON keys in line for entry in cfr["data"]["data"]: and so I guess can't use it. I just need suggestions as to know what should I use to indicate that this script is actually doing something. I just need suggestions or pseudocode is fine to send me in a right direction... the actual programming code is not needed as I will do that myself.
Thank you
As far as I'm aware, most functions that allow you to change the mouse cursor in Python are available only from various GUI modules - most of the popular ones, such as tkinter, PyQt5, pygame or others.
The problem is that most of these may only work when you've created a window of the GUI, which is probably unnecessary or not a nice idea if you're not using the same GUI, or any GUI for that matter. Even then, some may only take effect when the mouse pointer hovers over a certain widget in that GUI.
Note:
I've only (unsuccessfully) tried doing this with pygame.cursors before. It may be convenient because it even lets you create a custom shape with strings, or use a system cursor. But it displays a pygame.error: video system not initialized if you try doing this without having called pygame.display.init() first. I tried creating a window and setting a cursor, but it didn't seem to take effect.
After a quick google search for other ways to set an animated cursor, I came across this SO answer which might offer some insight if you're on windows.
Overall, using a terminal animation may probably be better and easier, so
this is an attempt at a basic answer for a loading animation in a terminal window :
(Of course, for an indefinite length of loop, it doesn't make sense to store a percentage completion etc, so this just animates at an arbitrary pace and repeats when it reaches the end)
i, w, d = 0, 20, 10000
while True:
# Do whatever
# No print statements except this last one
i = (i+1)%(w*d)
l = i//d
print("\r Processing... |" + " "*l+ "█" + " "*(w-l-1) +"|", end='')
i is used for iteration, w is the length of the bar, and d used to create some sort of 'delay', so that the bar doesn't change at every single iteration, but some slower (visible) speed
Edit: Important Note: The '\r' that resets the cursor position doesn't work in every terminal - it may still move to a new line for the next print() instead of the start of the same line - but this should most likely be fine in your system Terminal/cmd etc... May not be a good idea to run this in IDLE :P
Edit 2: Based on your comment, for a blinking indicator (using the same approach) -
i, d = 0, 300000
while True:
i = (i+1)%d
print("\r Working... " + ("█" if i < d/2 else " "), end='')

Python Inquirer Module: Remove Choices When Done (Using Curses)

NOTE: Although I give a lot of info on Inquirer, I'm pretty sure that most of it won't apply (just being safe). For my actual question about curses, its at the bottom.
I'm using the Inquirer module in Python 3 to allow the user to select a value from a list. I run this:
import inquirer
choice = inquirer.prompt([inquirer.List("size",message="Which size do you need?",choices=["Large", "Medium", "Small"])
And I'm given this:
[?] What size do you need?: Medium
Large
> Medium
Small
And using the up and down keys, I can change my selection, and hit enter to choose, after which the "choice" variable contains the value I selected. The issue is: Once the selection is done, the choices still show. I want to delete them when done. I'm currently using ANSI Escape Codes to delete the choices from onscreen when done, where x is the number of choices:
import sys
for i in range (x+1):
sys.stdout.write('\x1b[1A')
sys.stdout.write('\x1b[2K')
Which leaves the printed text as:
[?] What size do you need?: Medium
The issue is, ANSI escape codes aren't universal. I want to use a solution that works on all terminals, preferably curses, but curses isn't very friendly to new users, so I was wondering if anyone knew how to use curses to "delete x lines above current position". Thanks!
curses, as such, would erase the whole display (which is probably not what you want). A low-level terminfo/termcap approach might seem promising, but while ECMA-48 does define a sequence (ED, with parameter 1) which erases above the current position, there is no predefined terminfo/termcap capability which corresponds to this. All that you will find there is the capability for erasing to the end of the screen, or erasing the whole screen.
"ANSI sequences" is an obsolete term. Referring to ECMA-48, you could do
sys.stdout.write('\x1b[1J')
after moving the cursor to the last location you would like to erase.

How is the fancy command line implemented in Linux?

When installing things in Linux I often see stdout change after printing eg. there might be a counter showing installation progress that starts at 1% and goes up to 100%. How is this done? When I write C programs and I print something using printf, I can't change it afterwards - if I type 1%, it stays that way. How is it done? Is there a different function I have to use?
\r brings you back to the beginning of the line without issuing the \n to go to the next line. Use this to overwrite text on the screen to build progress bars, etc.
See:
How to add a progress bar to a shell script?

disable automatic line wrapping in Ubuntu terminal

I used some sql command to join two tables and the result was two terminal line long for each row of resulted table.
I dont want so ... i mean is there any way to get scroll bar at the bottom so that a row can be fit into a terminal line. and it will be a well structured and readable output
I hope you get my question.
There is no way on a standard terminal. You could use e.g. less as your pager for you sql-client.
I propose to pipe the output into the command less -S:
$ mysql-command-doing-the-SELECT | less -S
(To achieve this in the interactive mysql console, you can type pager less -S.)
Then all lines are displayed without being wrapped, and you can scroll sideways using the arrow keys. You can also use the command less (without the option -S) and then interactively type - S to achieve the non-wrapping. (Type again to toggle.)
If you need a real scroll bar, I propose to pipe the output into a real file and then use a more sophisticated program like gedit (which can be switched to a non-wrapping display) to display it with a decent scroll bar.
Another solution: copy the data from the terminal and paste it into your favorite editor. The copied text will not have any line breaks "\n".
(Offtopic: on a linux system you can just select the text with a mouse and mouse-middle-click in your editor. This will copy the text without filling out the main copy-paste buffer.)

QB64 Output issue

How do I scroll up and see previous displayed lines in the output?
I'm using QB64, and had to run a program 1000 times, but I cannot see the starting lines. Actually, I can't see the first 800 lines or so.
Is there a way to expand the window or scroll up to see everything? Because I do not have a scroll bar, and if I use any key to scroll up, it exits the console window.
Thanks in advance.
The new version of QB64 supports a console window, which should be able to do what you want. I'm not too used to console though, but if all else fails you could always save the text in a string array and examine that. There are some examples of creating lists in the community at qb64.net or you could make your own list with scrollbars, etc.
Input a line in the loop for data output:
if x > 24 then
if 24 MOD x then sleep
endif
MOD is the command for modulus where the modulus will return the remainder of 24 and x. in this case if it is zero then it will pause the console output until the user presses any key.
If you don't want to mess with custom buffers, just use the console:
$CONSOLE:ONLY
_DEST _CONSOLE
With that in the begining of your program, QB64 will create only a console window, which by default can be scrolled back so the past lines can be seen.

Resources