Reputation: 291
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)
Upvotes: 0
Views: 982
Reputation: 179
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!
Upvotes: 0
Reputation: 45089
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?
Upvotes: 2