I'm getting an "Unexpected unindent error" - python

I'm creating a program and I recently started exception handling. The program worked fine a couple times but now I'm getting an IndentationError every time it starts, which is bizarre because it worked fine before. It is large, so I'm only including a snippet of the program. Let me know if you need the whole thing.
The only way I can get it to work is if I delete the command
I've included some lines in-between the commands so you can more clearly identify them. The problem command is the one in the middle.
elif 'python' in cmd:
pythonProgram = cmd.split(' ')[1]
execfile(pythonProgram)
elif 'cd' in cmd:
desired_directory = cmd.split(' ')[1]
if desired_directory == "..":
os.chdir('..')
else:
try:
os.chdir(desired_directory)
print "'%s' Is not a valid directory!" % desired_directory
elif 'ver' in cmd:
print"JDOS_2", currentVersion
I've also attempted to hash out the lower elif and gotten the same error with the next elif statement in the program.
This seems like a simple problem, and I'm most likely overseeing something, but the indentations of elif commands are the same. This is the error output.
File "/Users/#######/PycharmProjects/untitled/JDOS/SYS64/jdosos.py", line 64
elif cmd == "ver":
^
IndentationError: unexpected unindent
Process finished with exit code 0
And I haven't had any problems mixing spaces and indents as its littered all over my program.

A bit late, but I needed a matching except block to go with the try argument.
This is the fixed code and works perfectly.
elif 'cd' in cmd:
desired_directory = cmd.split('cd ')[1]
if desired_directory == "..":
os.chdir('..')
else:
try:
os.chdir(desired_directory)
except OSError as e:
print("'%s' Is not a valid directory!" % desired_directory)

Related

How can I avoid this error "SyntaxError: unexpected EOF while parsing"

while True:
try:
result = login(browser, url)
if not result != 0:
login(browser, url)
while True:
try:
time.sleep(1)
browser.find_element_by_class_name("submit").click()
except:
browser.find_element_by_xpath("//a[contains(.,'Restart Battle')]").click()
It shows error on this line:
browser.find_element_by_xpath("//a[contains(.,'Restart Battle')]").click()
I tried removing parentheses and spaces and other stuff, but it isn't going off.
Any idea what I should do?
When using try, you need an except. For example, the following code prints error:
try:
x=1/0
except:
print("error")
But this throws an SyntaxError: unexpected EOF while parsing:
try:
x=1/0
# except:
# print("error")
So, you need an exception at the end of the try statement here:
while True:
try:
result = login(browser, url)
if not result != 0:
...
except:
...
This error means that in your script something begins, but the EOF (End of File — the file is your script) occurred before it ends.
(Similar as the unexpected “The End” in a watched crime thriller without revealing a perpetrator.)
It means that you started something (e.g. writing " as a start of the string literal), but you never ended it (no closing ").
The typical cases are unbalanced quotes, apostrophes, parentheses, and so on.
In your case it is the first try: without the expected except: just in the 2nd line of your script.

Can not get keyboardInterrupt to catch ctrl c in python program running in linux

I want my program to stop executing when a ctrl-c is entered in the terminal window (that has focus) where the program is executing. Every google hit tells me this should work but it doesn't.
First I tried putting the try block in a class method my main invoked:
try:
for row in csvInput:
<process the current row...>
except KeyboardInterrupt:
print '\nTerminating program!\n'
exit()
and then I tried putting the try block in my main program and that didn't work:
if __name__ == '__main__':
try:
programArg = ProgramArgs(argparse.ArgumentParser)
args = programArg.processArgs()
currentDir = os.getcwd()
product = Product(currentDir, args.directory[0], programArg.outputDir)
product.verify()
except KeyboardInterrupt:
print '\nTerminating program!\n'
exit()
I recently (May 2, 2020) hit this same issue in Windows-10 using Anaconda2-Spyder(Python2.7). I am new to using Spyder. I tried multiple ways to get [break] or [ctrl-c] to work as expected by trying several suggestions listed in stackoverflow. Nothing seemed to work. However, what I eventually noticed is that the program stops on the line found after the "KeyboardInterrupt" catch.
[Solution]: select [Run current line] or [continue execution] from the debugger tools (either menu item or icon functions) and the rest of the program executes and the program properly exits. I built the following to experiment with keyboard input.
def Test(a=0,b=0):
#Simple program to test Try/Catch or in Python try/except.
#[break] using [Ctrl-C] seemed to hang the machine.
#Yes, upon [Ctrl-C] the program stopped accepting User #
Inputs but execution was still "hung".
def Add(x,y):
result = x+y
return result
def getValue(x,label="first"):
while not x:
try:
x=input("Enter {} value:".format(label))
x = float(x)
continue
except KeyboardInterrupt:
print("\n\nUser initiated [Break] detected." +
"Stopping Program now....")
#use the following without <import sys>
raise SystemExit
#otherwise, the following requires <import sys>
#sys.exit("User Initiated [Break]!")
except Exception:
x=""
print("Invalid entry, please retry using a " +
"numeric entry value (real or integer #)")
continue
return x
print ("I am an adding machine program.\n" +
"Just feed me two numbers using "Test(x,y) format\n" +
"to add x and y. Invalid entries will cause a \n" +
"prompt for User entries from the keyboard.")
if not a:
a = getValue(a,"first")
if not b:
b = getValue(b,"second")
return Add(a,b)

sys.exit in python console

Hi I have troubles using sys.exit in a python console. It works really nice with ipython. My code looks roughly like this:
if name == "lin":
do stuff
elif name == "static":
do other stuff
else:
sys.exit("error in input argument name, Unknown name")
If know the program know jumps in the else loop it breaks down and gives me the error message. If I use IPython everything is nice but if I use a Python console the console freezes and I have to restart it which is kind of inconvenient.
I use Python 2.7 with Spyder on MAC.
Is there a workaround such that I the code works in Python and IPython in the same way? Is this a spyder problem?
Thanks for help
Not sure this is what you should be using sys.exit for. This function basically just throws a special exception (SystemExit) that is not caught by the python REPL. Basically it exits python, and you go back to the terminal shell. ipython's REPL does catch SystemExit. It displays the message and then goes back to the REPL.
Rather than using sys.exit you should do something like:
def do_something(name):
if name == "lin":
print("do stuff")
elif name == "static":
print("do other stuff")
else:
raise ValueError("Unknown name: {}".format(name))
while True:
name = raw_input("enter a name: ")
try:
do_something(name)
except ValueError as e:
print("There was a problem with your input.")
print(e)
else:
print("success")
break # exit loop
You need to import sys. The following works for me:
import sys
name="dave"
if name == "lin":
print "do stuff"
elif name == "static":
print "do other stuff"
else:
sys.exit("error in input argument name, Unknown name")

Need to rerun script after error or exception is risen

Need to rerun my selenium python script after either a 'list index is out of range' error or the page does not load and throughs some error or exception that has to due with it timing out. And no, upping the time for the page to load does not help, since it will continuously try to load. So is there a way to make the script stop and restart on its own if it encounters a problem?
Like this?
while True:
try:
<your script>
except <error>:
pass
else:
break
#kevin You are right. But this question needs little more.
def initiate_test_condition():
"""
This should have the initial setup (Environment where your testcase to be tested)
Example:
* reopening your browser and
* kill all already opened browsers
"""
pass
def test_case_flow():
"""
write your selenium testing code
"""
initiate_test_condition()
try:
"""
your testing code
"""
# if all code runs successfully
return 1
except Exception as error:
print str(error)
return 0
if __name__ == '__main__':
total_rerun = 0
while True:
if total_rerun != 5 and total_rerun < 5:
if test_case_flow():
print "Looks like the code is passed :)"
return or break
else:
total_rerun += 1
print "Rerunning the code"
else:
print "Code Failed after rerunning %d times " % total_rerun
break

do not understand this use of sys module

Here is code from a tutorial in A Byte of Python:
import sys
filename = 'poem.txt'
def readfile(filename):
#Print a file to standard output
f = file(filename)
while True:
line = f.readline()
if len(line) == 0:
break
print line,
f.close()
if len(sys.argv) < 2:
print 'No action specified'
sys.exit() //<--This is where the error is occurring
if sys.argv[1].startswith('--'):
option = sys.argv[1][2:] #fetches sys.argv[1] without first 2 char
if option == 'version':
print 'Version 1.2'
elif option == 'help':
print '''\
This program prints files to the standard output.
Any number of files can be specified.
Options include:
--version: Prints the version number
--help: Displays this help'''
else:
print 'Unknown option'
sys.exit()
else:
for filename in sys.argv[1:]:
readfile(filename)
When I run this code, this is the error that appears:
Traceback (most recent call last):
File "C:/Python/sysmodulepr.py", line 17, in <module>
sys.exit()
SystemExit
I don't understand why. Please help.
It's telling you that sys.exit() has executed on line 17 of your program.
The entry for for sys.exit in the Python documentation tells you that this exits your program.
There's no way this line can execute without producing other output, so I think there's something missing in the question.
If you're using IDLE, it will print the stack anyway. Try running your script from the command line, it won't print that error message when executed outside the IDE.
It's not an error. sys.exit() raises SystemExit exception to allow try:... finally block to cleanup used resources
Try in Idle:
import sys
sys.exit()
From documentation for sys.exit():
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.
edit
The error shouldn't be normally printed unless you're trying to run the script in some interactive interpreters (for example Idle).
It's nothing to worry about, but the script looks like it's standalone, so you should use it as such.

Categories

Resources