G+_abby Sand Posted May 20, 2014 Share Posted May 20, 2014 I want to write a python code that uses the built-in with function to open a file, but I want a specific command to be executed each time an exception is raised. The problem I am having is that the command I want to raise is skipped each time an exception is raised try: with open(some file) as f s = f.read except IOError: this part of the code is never executed how do write the with statement so it executes. thanks Link to comment Share on other sites More sharing options...
G+_Dan Sarauer (N3m1sys) Posted May 20, 2014 Share Posted May 20, 2014 I tried what you wrote here almost verbatim and I can get the error block to execute. If there is no file named 'somefile' then you will throw that IOError and your code will execute. Link to comment Share on other sites More sharing options...
G+_abby Sand Posted May 20, 2014 Author Share Posted May 20, 2014 Thanks for answering All things you mention above is true but I wanted some command to execute when IOError is thrown. I do not know where to put the command so that it executes instead of IOError. Link to comment Share on other sites More sharing options...
G+_Dan Sarauer (N3m1sys) Posted May 20, 2014 Share Posted May 20, 2014 I was able to run a print command when the error was thrown. What platform are you running this from? If you are trying to run code that doesn't stay in the program, then the program will execute that code and exit the program. Link to comment Share on other sites More sharing options...
G+_abby Sand Posted May 20, 2014 Author Share Posted May 20, 2014 I am using ubuntu 12.04 How did you manage to execute the print statement thanks Link to comment Share on other sites More sharing options...
G+_Dan Sarauer (N3m1sys) Posted May 20, 2014 Share Posted May 20, 2014 Regardless of environment, the last part of my statement holds true. If you are executing code that runs and then ends without calling another part of your program to execute, your code will execute and end. If you were to say prompt a menu and wait for input, or call another program to handle the instance you caught (by say creating the missing file and then calling this function again) you would make the program continue to run and shouldn't see it exit as you have described. Link to comment Share on other sites More sharing options...
G+_abby Sand Posted May 20, 2014 Author Share Posted May 20, 2014 I get it now thanks you Daniel Sarauer you been a great help. It good to know that there are help ful good programmers out there. I love this community Link to comment Share on other sites More sharing options...
G+_L I Posted May 23, 2014 Share Posted May 23, 2014 This is what I got when I tried to run: >>> try: ... with open("somefile") as f: ... s=f.read() ... except IOError: ... print "caught" ... caught >>> Link to comment Share on other sites More sharing options...
Recommended Posts