I'm in trouble about how to end a 'try' loop, which is occurred since I have the 'try', here is the code:
import time
class exe_loc:
mem = ''
lib = ''
main = ''
def wizard():
while True:
try:
temp_me = input('Please specify the full directory of the memory, usually it will be a folder called "mem"> ' )
if temp_me is True:
exe_loc.mem = temp_me
time.sleep(1)
else:
print('Error value! Please run this configurator again!')
sys.exit()
temp_lib = input('Please specify the full directory of the library, usually it will be a folder called "lib"> ')
if temp_lib is True:
exe_loc.lib = temp_lib
time.sleep(1)
else:
print('Invalid value! Please run this configurator again!')
sys.exit()
temp_main = input('Please specify the full main executable directory, usually it will be app main directory> ')
if temp_main is True:
exe_loc.main = temp_main
time.sleep(1)
I tried end it by using break, pass, and I even leaves it empty what I get is Unexpected EOF while parsing, I searched online and they said it is caused when the code blocks were not completed. Please show me if any of my code is wrong, thanks.
Btw, I'm using python 3 and I don't know how to be more specific for this question, kindly ask me if you did not understand. Sorry for my poor english.
EDIT: Solved by removing the try because I'm not using it, but I still wanna know how to end a try loop properly, thanks.
Your problem isn't the break, it's the overall, high-level shape of your try clause.
A try requires either an except or a finally block. You have neither, which means your try clause is never actually complete. So python keeps looking for the next bit until it reaches EOF (End Of File), at which point it complains.
The python docs explain in more detail, but basically you need either:
try:
do_stuff_here()
finally:
do_cleanup_here() # always runs, even if the above raises an exception
or
try:
do_stuff_here()
except SomeException:
handle_exception_here() # if do_stuff_here raised a SomeException
(You can also have both the except and finally.) If you don't need either the cleanup or the exception handling, that's even easier: just get rid of the try altogether, and have the block go directly under that while True.
Finally, as a terminology thing: try is not a loop. A loop is a bit of code that gets executed multiple times -- it loops. The try gets executed once. It's a "clause," not a "loop."
You have to also 'catch' the exception with the except statement, otherwise the try has no use.
So if you do something like:
try:
# some code here
except Exception:
# What to do if specified error is encountered
This way if anywhere in your try block an exception is raised it will not break your code, but it will be catched by your except.
Related
If I have a try except block in my python code, and the first line of my try statement raises an exception will it automatically move on to exception or will it finish the try block first?
try:
int(string)
string = "This was a mistake, can't int string"
except:
pass
Here is it checking if it can int(string), which it can't, and then it immediately moves onto except, or does it do the string assignment first?
When I run it, it seems like it stops right away, but I want to know if that's happening for sure or something else.
Thanks
Let's try it.
try:
1/0
print("what?")
except:
print("nope")
Output:
nope
>>>
When an exception is raised it moves on to the except.
From the python docs, I found this,
"The try statement works as follows.
First, the try clause (the statement(s) between the try and except keywords) is executed.
If no exception occurs, the except clause is skipped and execution of the try statement is finished.
If an exception occurs during execution of the try clause, the rest of the clause is skipped. Then if its type matches the exception named after the except keyword, the except clause is executed, and then execution continues after the try statement.
If an exception occurs which does not match the exception named in the except clause, it is passed on to outer try statements; if no handler is found, it is an unhandled exception and execution stops with a message as shown above."
Cheers!
Hope it helps!
#the try block is to run the process
try:
string = "This was a mistake, can't int string"
#you are parsing the string into an int
int(string)
#this block is to capture the exception when it is raised
except:
#here I am just printing the exception
print('Exception')
#the pass is to pass the execution and follow the remaining process.
pass
Output:
Exception
>>>
Well, that the whole point of an error handler. When an error occurs in out program, it crashes, it won't simply skip the error line.
try:
int(string)
string = "This was a mistake, can't int string"
except:
pass
So if the try block finishes even after an error occurred in the middle, then the error handler'd seem a bit pointless.
There seem to be some issue with your program and maybe your understanding of the try except block.
First of all, from the block of code you have provided, it seems to me like string isn't even defined yet when you try to pass int(string).
Secondly, the string variable which you seem to be defining under seems to me like is something you are trying to print to the console once the program spits out an error and passes to the except block. If this is what you are trying to do, then your code should look something like this:
try:
int(string)
except:
print("This was a mistake, can't int string")
If you were to run the code provided above, you would indeed confirm that the try except statement is working as it would print "This was a mistake, can't int string" into the console instead of giving an error. Hope this was somewhat helpful and understandable. You got this chief, keep grinding!
UPDATE: I think I may have just realized what I need to figure out re: the below, which is the correct error type to specify with the except clause (new to this, obviously)
Starting in a specified root directory, my program iterates through subdirectories, then files within those, identifying valid (.csv) data files and then aggregating and performing calculations on the data.
In cases where the root directory happens to be empty, can someone suggest a clean/graceful way to simply exit the program at the start without further processing?
I tried to adapt a suggestion I found here, but it didn't work as I expected:
Exit gracefully if file doesn't exist
That person's code was:
def main():
try:
file = open('file.txt', 'r')
except IOError:
print('There was an error opening the file!')
return
I gave the above a try, and it works for the particular case above. However, when I tried to adapt it as follows, it 'broke' and I got an "Index out of range error", instead dropping down to the except code.
dir = os.listdir(masterDirPath)
def main():
try:
item = dir[0]
except IOError:
print('The data area is empty.')
return
(Also/instead, I very much welcome suggestions for some completely other approach to the task overall)
To exit your program immediately you should use either exit() or quit(). Instead of throwing an error you could use the fact that many objects in Python are truthy; an empty list is False, and a list with one or more elements is True.
import os
dir_contents = os.listdir('.')
if dir_contents:
do_stuff
else:
print('Directory was empty. Exiting')
exit()
If you prefer explicitness to implicitness you could also check the length of your list using len(dir_contents) before indexing into it.
You might also want to avoid using dir in Python as a variable name as it will shadow the builtin function dir().
An empty list has no elements so you should catch IndexError instead of IOError.
def main():
try:
item = dir[0]
except IndexError:
print('The data area is empty.')
return
Why are you using an exception?
if not dir:
print('The data area is empty')
exit(0)
item = dir[0]
#!/usr/bin/env python
import os
path = 'path-to-your-dir'
if os.listdir(path) == []:
exit(0)
else:
print "Your other code goes here."
These are the exit commands and its definitions
exit(0) means a clean exit without any errors / problems
exit(1) means there was some issue / error / problem and that is why the program is exiting.
os._exit() for child processes
quit() the SystemExit exception behind the scenes.
sys.exit() kill the interpreter
import sys
def checkarg():
try:
filename=str(sys.argv[1])
if filename=="-mycommand":
print "SPECIFIC_TEXT"
sys.exit()
else:
return filename
except:
print "ERROR"
sys.exit()
Hello all...i have a problem with the code above. When i call the 'checkarg' function, if i did not pass any parameter on the command line i have the "ERROR" output and sys exit, just as expected.
But, if i provide a parameter on the command line (like "-mycommand") it prints the "SPECIFIC_TEXT" and then prints "ERROR" message from the EXCEPT block too.
The TRY block will only run when I provide a parameter, if I don't, then EXCEPT will get the turn. But, it is running the TRY and EXCEPT blocks together.
Does anybody knows the reason of this behavior?? Any mistake on my code? Tks for all !
I think I understand your question...
sys.exit() exits by raising a SystemExit exception, which your except statement is catching.
Answer found here: http://docs.python.org/library/sys.html
sys.exit([arg])
Exit from Python. This is implemented by raising the SystemExit exception, so cleanup actions specified by finally clauses of try statements are honored, and it is possible to intercept the exit attempt at an outer level.
sys.exit works by raising an exception. That's why your except block executes.
You really shouldn't be using try/except for situations where you can check the state using control flow logic.
Instead, in this case, check for if len(sys.argv) > 1.
Another reason never to use specifically a blank except: You will catch even system exceptions like SystemExit or KeyboardInterrupt, making it potentially impossible to terminate your program short of a messy kill.
I know you've already accepted an answer, but I think the root of the problem is that your try block contains code in which you do not necessarily wish to catch exceptions; rather, you merely wish these statements to be executed after the code in which you wish to catch exceptions if no exception occurs.
To address this, your try block should contain only filename=str(sys.argv[1]) and the rest of the code now in your try block should be moved to an else block, which will be executed only if no exception occurs. In other words:
try:
filename=str(sys.argv[1])
except:
print "ERROR"
sys.exit()
else:
if filename=="-mycommand":
print "SPECIFIC_TEXT"
sys.exit()
else:
return filename
Or in this case, since you exit the script entirely in the case of an exception, you don't actually need the else:
try:
filename=str(sys.argv[1])
except:
print "ERROR"
sys.exit()
if filename=="-mycommand":
print "SPECIFIC_TEXT"
sys.exit()
else:
return filename
The fact that you're catching every exception with your bare except is bad style and changing that would also avoid the problem, but to me, it's secondary. You do not wish to catch exceptions in your if/else code, so it should not be in the try block to begin with. IMHO, most admonitions against bare except would be moot if this guideline were followed more closely.
Okay, so I'm writing a very simplistic password cracker in python that brute forces a password with alphanumeric characters. Currently this code only supports 1 character passwords and a password file with a md5 hashed password inside. It will eventually include the option to specify your own character limits (how many characters the cracker tries until it fails). Right now I cannot kill this code when I want it to die. I have included a try and except snippit, however it's not working. What did I do wrong?
Code: http://pastebin.com/MkJGmmDU
import linecache, hashlib
alphaNumeric = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z",1,2,3,4,5,6,7,8,9,0]
class main:
def checker():
try:
while 1:
if hashlib.md5(alphaNumeric[num1]) == passwordHash:
print "Success! Your password is: " + str(alphaNumeric[num1])
break
except KeyboardInterrupt:
print "Keyboard Interrupt."
global num1, passwordHash, fileToCrack, numOfChars
print "What file do you want to crack?"
fileToCrack = raw_input("> ")
print "How many characters do you want to try?"
numOfChars = raw_input("> ")
print "Scanning file..."
passwordHash = linecache.getline(fileToCrack, 1)[0:32]
num1 = 0
checker()
main
The way to allow a KeyboardInterrupt to end your program is to do nothing. They work by depending on nothing catching them in an except block; when an exception bubbles all the way out of a program (or thread), it terminates.
What you have done is to trap the KeyboardInterrupts and handle them by printing a message and then continuing.
As for why the program gets stuck, there is nothing that ever causes num1 to change, so the md5 calculation is the same calculation every time. If you wanted to iterate over the symbols in alphaNumeric, then do that: for symbol in alphaNumeric: # do something with 'symbol'.
Of course, that will still only consider every possible one-character password. You're going to have to try harder than that... :)
I think you're also confused about the use of classes. Python does not require you to wrap everything inside a class. The main at the end of your program does nothing useful; your code runs because it is evaluated when the compiler tries to figure out what a main class is. This is an abuse of syntax. What you want to do is put this code in a main function, and call the function (the same way you call checker currently).
Besides printing, you need to actually exit your program when capturin KeyboardInterrupt, you're only printing a message.
This is what worked for me...
import sys
try:
....code that hangs....
except KeyboardInterrupt:
print "interupt"
sys.exit()
Well, when you use that try and except block, the error is raised when that error occurs. In your case, KeyboardInterrupt is your error here. But when KeyboardInterrupt is activated, nothing happens. This due to having nothing in the except part. You could do this after importing sys:
try:
#Your code#
except KeyboardInterrupt:
print 'Put Text Here'
sys.exit()
sys.exit() is an easy way to safely exit the program. This can be used for making programs with passwords to end the program if the password is wrong or something like that. That should fix the except part. Now to the try part:
If you have break as the end of the try part, nothing is going to happen. Why? Because break only works on loops, most people tend to do it for while loops. Let's make some examples. Here's one:
while 1:
print 'djfgerj'
break
The break statement will stop and end the loop immediately unlike its brother continue, which continues the loop. That's just extra information. Now if you have break in a something like this:
if liners == 0:
break
That's going to depend where that if statement is. If it is in a loop, it is going to stop the loop. If not, nothing is going to happen. I am assuming you made an attempt to exit the function which didn't work. It looks like the program should end, so use sys.exit() like I showed you above. Also, you should group that last piece of code (in the class) into a seperate function. I hope this helps you!
How could I go about doing something like this
Try to do something.
If it works, great, continue with normal flow.
If it fails run a function and try again.
If it once again fails throw an exception and stop code.
I believe I would have to make use of try but I haven't quite come around yet to how to use it in this particular example.
It doesn't sound like you want to do a nested try-catch at all. Exceptions as control flow are a gnarly anti-pattern, and where you can avoid it, you should.
In this scenario, avoidance is easy. In the method that you describe, you want to be sure that a file exists before you do some operations on it. You also have a method to "correct" the path should it not. If both attempts fail, then you want to bail out.
With that into account, we would want to use os.path.isfile for this.
from os.path import isfile
def something(filepath):
# Don't mutate the parameter if you can help it.
p = filepath
if not isfile(p):
p = correct_path(p)
if not isfile(p):
raise Error("Cannot find file {} after correction to {}, aborting.".format(filepath, p))
with open(p, 'r') as f:
# Rest of file operations here
Try a nested try catch:
try:
do_something() #if this works, will skip rest and continue
except:
do_fix_function() #on error, do extra function
try:
do_something() #try again
except:
throw error() #if it fails this time, stop and throw an error
Note that if your do_fix_function() can also fail, you might want to put it inside the second try statement instead
This works for an arbitrary number of tries; I set it to two since that's what you want.
tries = 2
while True:
try:
step1()
except CatchThisException:
tries -= 1
if tries: # if tries != 0
step3()
continue # not necessary, just for clarity
else:
raise # step 4
else:
break # step 2
You can use retrying package to solve your retry attempt. Just write a block of code that keeps repeating on failure, until max retries is hit
For example:
import random
from retrying import retry
#retry
def do_something_unreliable():
if random.randint(0, 10) > 1:
raise IOError("Broken sauce, everything is hosed!!!111one")
else:
return "Awesome sauce!"
print do_something_unreliable()