Python - TQDM Clearing the line above it before printing - python

So, I've ran into a bit of a problem because my vocabulary isn't big enough to define it. TQDM in python has a specific function that, when printed, deletes the line above it and only the singular line above it. I've tried looking through the documentation to see if there's a simple way to do it outside of the TQDM module, but I can't seem to find anything. For reference, here is the image of my console after fully printing, and the code along with it. Screenshot of my console
while xLoad == False:
string1 = ''' Loading Prerequisites. . . " '''
sleep(1)
for letter in string1:
sleep(0.01)
sys.stdout.write(letter)
sys.stdout.flush()
for i in tqdm(range(_RAND_(800, 1999))):
sleep(.0001)
xLoad = True
# Responsible for making a fake loading bar to simulate loading files before startup
sleep(3)
# End of File
The code above is specifically for the last lines where the actual loading bar is displayed, not the top or the rest of the file. I can send the rest if needed, but what i'm referring to in this specific post is the ability to clear a line before printing a new one without clearing console entirely. I want to keep the "Modeni" and "Thank You" Message on the screen at all times while the rest of the text is displayed below. I hope I made sense in this post, and I appreciate any and all the help.

If I'm understanding your situation correctly, I was wanting to do the same thing and found a solution from this entry: TQDM Printing to Newline: Solution
Add ", position=0, leave=False" inside your tqdm call. For example:
for item in tqdm(list_of_items, desc='Item Description', position=0, leave=False):
Once the loop has finished, it will clear the line making it usable for the next thing, be that another tqdm or whatever.
Hope this helps, and thanks for articulating the question better than I could ever have hoped to have done.

Related

How to edit console output

I have the following very simple code
stdout.write("Hello World")
stdout.write("\rBye world")
stdout.write("\rActually hello back")
Which prints as expected 'Actually hello back' however if i were to add a newline
stdout.write("\n")
How can I go back a newline and then to the beginning of the line so I can actually just output "Hi" instead of
Actually hello back
Hi
I tried
stdout.write("\r")
stdout.write("\b")
However none of them seem to do the trick. The end goal is to display a big chunk of text and then update the output in real time without having to write again. How can I achieve this in python?
EDIT
My question is different than the one suggested as I don't want to modify a single line. I want to be able to print 4-5 lines of text and then replace them in real time instead of just one line that is modified.
Well, if You want to gain full control over the terminal, I would suggest to use the curses library.
The curses module provides an interface to the curses library, the
de-facto standard for portable advanced terminal handling.
Using it, You can edit multiple lines in terminal like this:
import curses
import time
stdscr = curses.initscr()
stdscr.addstr("line 1\n")
stdscr.addstr("line 2\n")
stdscr.refresh()
time.sleep(3)
stdscr.erase()
stdscr.addstr("edited line 1\n")
stdscr.addstr("edited line 2\n")
stdscr.refresh()
time.sleep(3)
curses.endwin()
The capabilities of this library are much greater though. Full tutorial here.

How do I print the output onto a txt file: Mac

This is my first time asking a question. I am just starting to get into programming, so i am beginning with Python. So I've basically got a random number generator inside of a while loop, thats inside of my "r()' function. What I want to do is take all of the numbers (basically like an infinite amount until i shut down idle) and put them into a text file. Now i have looked for this on the world wide web and have found solutions for this, but on a windows computer. I have a mac with python 2.7. ANY HELP IS VERY MUCH APPRECIATED! My current code is below
from random import randrange
def r():
while True:
print randrange(1,10)
The general idea is to open the file, write to it (as many times as you need to), and close it. This is explained in the tutorial under Reading and Writing Files.
The with statement (described toward the end of that section) is a great way to make sure the file always gets closed. (Otherwise, when you stopped your script with ^C, the file might end up missing the last few hundred bytes, and you'd have to use try/finally to handle that properly.)
The write method on files isn't quite as "friendly" as the print statement—it doesn't automatically convert things to strings, add a newline at the end, accept multiple comma-separated values, etc. So usually, you'll want to use string formatting to do that stuff for you.
For example:
def r():
with open('textfile.txt', 'w') as f:
while True:
f.write('{}\n'.format(randrange(1, 10)))
You'll need to call the function and then redirect the output to a file or use the python API to write to a file. Your whole script could be:
from random import randrange
def r():
while True:
print randrange(1,10)
r()
Then you can run python script_name.py > output.txt
If you'd like to use the python API to write to a file, your script should be modified to something like the following:
from random import randrange
def r():
with open('somefile.txt', 'w') as f:
while True:
f.write('{}\n'.format(randrange(1,10)))
r()
The with statement will take care of closing the file instance appropriately.

Deleting temporary files in python

I really would like to learn how submit questions using the cool formatting that seems to be available but it is not obvious to me just how to do that....
My question: My plan was to print "birdlist" (output from a listbox) to the file "Plain.txt" and then
delete the file so as to make it unavailable after the program exits. The problem with this is that for some reason "Plain.txt" gets deleted before the printing even starts...
The code below works quite well so long as I don't un-comment the last two lines in order to delete "Plain.txt... I have also tried to use the "tempfile" function that exists....it does not like me to send formatted string data to the temporary file. Is there a way to do this that is simple enough for my bird-brain to understand???
text_file = open("Plain.txt","w")
for name,place,time in birdlist:
text_file.write('{0:30}\t {1:>5}\t {2:10}\n'.format(name, place, time))
win32api.ShellExecute (0,"print",'Plain.txt','/d:"%s"' % win32print.GetDefaultPrinter (),".",0)
text_file.close()
#os.unlink(text_file.name)
#os.path.exists(text_file.name)
The problem is that Windows ShellExecute will just start the process and then return to you. It won't wait until the print process has finished with it.
If using the windows API directly, you can wait using the ShellExecuteEx function, but it doesn't appear to be in win32api.
If the user is going to be using your application for a while, you can keep a record of the file and delete it later.
Or you can write your own printing code so you don't have to hand it off to somebody else. See Print to standard printer from Python?
I had a similar issue with a program i'm writing. I was calling win32api.ShellExecute() under a for loop, to print a list of files and delete them afterwards. I started getting Notepad.exe popup messages on my screen telling me the file doesn't exist. After inserting some raw_input("press enter") statements to debug, i discovered that I needed a delay to avoid deleting the file too fast, so adding a time.sleep(.25) line after my ShellExecute("print",...) seemed to do the trick and fix it.
Might not be the cleanest approach, but I couldn't find anything more elegant for printing in Python that handles it better.
One thing i've been thinking about is using the 'Instance Handle ID' that is returned on successful ShellExecute() calls.. if its > 32 and >= 0 the call was successful. Maybe only run the delete if ShellExecute returns in that range, rather than trying to use an arbitrary time.sleep value. The only problem with this is it returns an exception if it's not successful and breaks out of the program.
Hope this helps!

Problem with exiting a Word doc using Python

This is my first time using this so be kind :) basically my question is I am making a program that opens many Microsoft Word 2007 docs and reads from a certain table in that document and writes that info to an excel file there is well in excess of 1000 word docs. I have all of this working but the only problem when I run my code it does not close MSword after opening each doc I have to manually do this at the end of the program run by opening word and selecting exit word option from the Home menu. Another problem is also if a run this program consecutively on the second run everything goes to hell it prints the same thing repeatedly no matter which doc is selected I think this may have to do with how MSword is deciding which doc is active e.g. is it still opening the last active document that was not closed from the last run. Anyways here is my code for the opening and closing part I wont bore you guys with the rest::
MSWord = win32com.client.Dispatch("Word.Application")
MSWord.Visible = 0
# Open a specific file
#myWordDoc = tkFileDialog.askopenfilename()
MSWord.Documents.Open("C:\\Documents and Settings\\fdosier" + chosen_doc)
#Get the textual content
docText = MSWord.Documents[0].Content
charText = MSWord.Documents[0].Characters
# Get a list of tables
ListTables = MSWord.Documents[0].Tables
------Main Code---------
MSWord.Documents.Close
MSWord.Documents.Quit
del MSWord
Basically, Python is not VBA, so this:
MSWord.Documents.Close
is equivalent to:
getattr(MSWord.Documents, "Close")
i.e. you just get some method object and do nothing with it. You need to call the method with the call operator (the parentheses :) :
MSWord.Documents.Close()
Accordingly for .Quit.
Before your MSWord.Quit did you try using:
MSWord.ActiveWindow.Close
Or even more simpley just doing
MSWord.Quit
I dont really understand if you are trying to close a document or the application.
I think you need a MSWord.Quit at the end (before and/or instead of the the del)

Python: How to ensure the last line of code has completed?

I'm doing some kind of complex operation, it needs the last line(s) of code has completed, then proceed to the next step, for example. I need to ensure a file has written on the disk then read it. Always, the next line of code fires while the file haven't written on disk , and thus error came up. How resolve this?
Okay..
picture.save(path, format='png')
time.sleep(1) #How to ensure the last step has finished
im = Image.open(path)
You do not need to do anything unless the previous operation is asynchronous. In your case, you should check picture.save's documentation to see if it specifically define as asynchronous. By default everything is synchronize. Each line will complete before it continues to next operation.
Seems like you just want to check is that there's a file at path before trying to open it.
You could check for the path's existence before trying to open it and sleep for a bit if it doesn't exist, but that sleep might not be long enough, and you still might have a problem opening the file.
You really should just enclose the open operation in a try-except block:
try:
im = Image.open(path)
except [whatever exception you are getting]:
# Handle the fact that you couldn't open the file
im = None # Maybe like this..

Categories