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

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..

Related

f.write() function is not working in python since this morning

I am using Python 2.7 and the function, f.write() is not working. A part of my code is given below.
Please suggest if any packages need to be installed.
for item in data1['OperationalTimes']['airportResources']:
with open("airportResources_details.txt",'a') as f: -- code works fine till here when i try to "print data1"
f.write(item['arrivalTerminal']+'\n') -- this line is not getting through
For a start, you can avoid the performance drain of opening and closing the file for every single item, by simply changing the order of things:
with open("airportResources_details.txt",'a') as f:
for item in data1['OperationalTimes']['airportResources']:
f.write(item['arrivalTerminal']+'\n')
Beyond that, you may want to check the usual suspects, like ensuring you're running in the correct directory. For example, use os.system("pwd") for getting the current working directory (on a UNIX-like platform).
Or temporarily changing the file specifier to something like /tmp/xyzzy.txt and seeing if that gets created in the right place.
Or temporarily changing it to use print rather than f.write to see if it comes out on standard output.

Blocking until a file is closed in python

I have Python set up to create and open a txt file [see Open document with default application in Python ], which I then manually make some changes to and close. Immidiately after this is complete I want Python to open up next txt file. I currently have this set up so that python waits for a key command that I type after I have closed the file, and on that key, it opens the next one for me to edit.
Is there a way of getting Python to open the next document as soon as the prior one is closed (i.e to skip out having python wait for a key to be clicked). ... I will be repeating this task approximately 100,000 times, and thus every fraction of a second of clicking mounts up very quickly. I basically want to get rid of having to interface with python, and simply to have the next txt file automatically appear as soon as prior one is closed.
I couldn't work out how to do it, but was thinking along the lines of a wait until the prior file is closed (wasn't sure if there was a way for python to be able to tell if a file is open/closed).
For reference, I am using python2.7 and Windows.
Use the subprocess module's Popen Constructor to open the file. It will return an object with a wait() method which will block until the file is closed.
How about something like:
for fname in list_of_files:
with open(fname, mode) as f:
# do stuff
In case of interest, the following code using the modified time method worked:
os.startfile(text_file_name)
modified = time.ctime(os.path.getmtime(text_file_name))
created = time.ctime(os.path.getctime(text_file_name))
while modified == created:
sleep(0.5)
modified = time.ctime(os.path.getmtime(text_file_name))
print modified
print "moving on to next item"
sleep(0.5)
sys.stdout.flush()
Athough I think I will use the Popen constructor in the future since that seems a much more elegant way of doing (and also allows for situations where the file is closed without an edit been needed).

python not writing to file for initial run

I have a super simple code and when run the first time it does not write to the file. But when run a second/multiple times later it writes to the file. The same thing happens when using "w" instead of "a" as well.
It also seems that the file is not closed after fh.close is run because I am unable to delete it - and a message appears saying that python is using the file. Any suggestions? Thanks!
fh = open("hello.txt","a")
fh.write("hello world again")
fh.close
fh.close doesn't call close, it just refers to the function. You need to do fh.close() to call the function.
you need to put the brackets after fh.close else you aren't actually calling the function, and if you are running interactively (i.e. with IDLE) then the interpreter keeps the file open.
so change your last line to:
fh.close()
James
The other posters are correct.
Also, I would suggest using the "with" statement when working with files, because then they will be automatically closed when your code goes out of scope.
with open("hello.txt","a") as fh:
fh.write("hello world again")
# Code that doesnt use the file continues here
If you use this, you never have to worry about closing your file. Even if runtime errors occur, the file will still always be closed.

How to not lose Intermediate Data in File

While Learning Python, we do Print to screen but eventually graduate to printing to output files... However most times all errors are not resolved in the code... In such cases the code aborts after running some 10 20 loops or say 80% of the code and then aborts.. However during this time the data that is printed to the file is lost as the file.close() is not executed.
In Python is there a way in which we can save the WIP file. I want to do this without closing and reopening the file once again multiple times in append modes. This will help in Debugging and also not losing the data that has been accumulated before the error was occurred.
After searching i did not find something like this .... if someone has or can give any ideas how to make a module for this that will be great... What we need is a generic catchall... in case of any error.. execute the catchall code to close the file and then exit from Python.
You can flush the internal file buffer by calling f.flush() on the file object in question.
Even better is to wrap the file access in a with block. If an exception is raised, the file is closed.
with open('tmp.txt', 'r') as f:
do_stuff_with(f)
On the documentation of File objects : https://docs.python.org/2/library/stdtypes.html?highlight=flush#file.flush
Use the flush function. There is also a note on the doc with os.fsync function to be sure the data are written on the disc.

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!

Categories