I just started using Python's keyboard module. I was exploring with the code below until there was a error occurring at the end on line 5. The goal of the code below is to detect if I pressed the "a" on my keyboard. I attempted to put a semicolon at the end of the print function, and I tried to replace the print("A") with pass and break but Python gave me the same error as before.
import keyboard
while True:
try:
if keyboard.is_pressed('a'):
print("A")
Output:
File "c:\users\emma\mu_code\keyboard.py", line 6
Syntax Error: unexpected EOF while parsing
Why do I have this syntax error and how can I get rid of it?
In your code add the except block, like so:
import keyboard
while True:
try:
if keyboard.is_pressed('a'):
print("A")
except:
#do something else, if there is an error, or any other key is pressed
If u dont know if u need try except, then just dont keep it in the try block:
import keyboard
while True:
if keyboard.is_pressed('a'):
print("A")
You didn't add except part.
If you are using try/except statement you need an except statement.
Make it.
import keyboard
while True:
try:
if keyboard.is_pressed('a'):
print("A")
else:
# Rest code . If you don't want to do anything then simply pass
pass
Related
How could I write a piece of code that recognizes if the any type of error has occurred and if it does the code just runs on a loop. What would be a function that I would place in <some error occurs> so it recognizes any error 0utput and re runs the code within 10 seconds.
while True:
<all your code>
if <some error occurs>:
time.sleep(10)
continue
Simply use try...except
while True:
try:
<all_your_code>
except:
time.sleep(10)
continue
Read this for better understanding: https://www.programiz.com/python-programming/exception-handling
Not sure what's wrong here, function's not printing anything (tried '1' as argument i). I've seen an answer suggesting adding flush=True to print, but that doesn't solve the issue. Any hints appreciated! More broadly - should I even be using the try/except framework if I want the function to be keyboard-controled, or is there a better way?
def i_printer(i):
while True:
try:
if keyboard.is_pressed('q'):
break
except:
print(i)
time.sleep(3)
EDIT: using Windows, apparently keyboard doens't work with it, looking for different solution.
Try and except blocks are used to handle exception. Since you are not going to face any error when clicking 'q', I don't think the usage of them is any good here. Just simple if statement would do the job.
def i_printer(i):
while True:
if keyboard.is_pressed('q'):
break
print(i)
time.sleep(3)
EDIT: In case you wanna record keyboard press try this out. The following code will record all the keys except 'q' and print recorded keys.
import keyboard
def i_printer():
rk = keyboard.record(until ='q')
return keyboard.play(rk, speed_factor = 1)
i_printer()
Got the ball rolling this way, with a generator function and an iterator (using windows, not linux):
import keyboard
import time
def printer():
while True:
yield '1'
time.sleep(1)
def iterator():
for i in aaa():
if keyboard.is_pressed('q'):
break
else:
print(i)
iterator()
I have a function that enables and disables services from the Netscaler. I pass in either enable or disable.
However, I want it to exit in the event someone passes a different value. I tried breaking out of it but it tells me my break is outside the loop. How can I resolve this?
def servicegroup_action(servicegroup_name,action):
if not action.upper() in ('ENABLE','DISABLE'):
break
try:
# do stuff
except NSNitroError, e:
print e.message
I think you are looking for return so as to terminate the function execution; a break is used to break out of a loop, and within your current code, there is no associated for/while loop.
The other option is to execute your code only if the correct values are passed, by indenting the try-except within the if block:
def servicegroup_action(servicegroup_name,action):
if action.upper() in ('ENABLE','DISABLE'):
try:
# do stuff
except NSNitroError, e:
print e.message
I am a novice at using exception handling. I am using the mechanize module to scrape several websites. My program fails frequently because the connection is slow and because the requests timeout. I would like to be able to retry the website (on a timeout, for instance) up to 5 times after 30 second delays between each try.
I looked at this stackoverflow answer and can see how I can handle various exceptions. I also see (although it looks very clumsy) how I can put the try/exception inside a while loop to control the 5 attempts ... but I do not understand how to break out of the loop, or "continue" when the connection is successful and no exception has been thrown.
from mechanize import Browser
import time
b = Browser()
tried=0
while tried < 5:
try:
r=b.open('http://www.google.com/foobar')
except (mechanize.HTTPError,mechanize.URLError) as e:
if isinstance(e,mechanize.HTTPError):
print e.code
tried += 1
sleep(30)
if tried > 4:
exit()
else:
print e.reason.args
tried += 1
sleep(30)
if tried > 4:
exit()
print "How can I get to here after the first successful b.open() attempt????"
I would appreciate advice about (1) how to break out of the loop on a successful open, and (2) how to make the whole block less clumsy/more elegant.
Your first question can be done with break:
while tried < 5:
try:
r=b.open('http://www.google.com/foobar')
break
except #etc...
The real question, however, is do you really want to: this is what is known as "Spaghetti code": if you try to graph execution through the program, it looks like a plate of spaghetti.
The real (imho) problem you are having, is that your logic for exiting the while loop is flawed. Rather than trying to stop after a number of attempts (a condition that never occurs because you're already exiting anyway), loop until you've got a connection:
#imports etc
tried=0
connected = False
while not Connected:
try:
r = b.open('http://www.google.com/foobar')
connected = true # if line above fails, this is never executed
except mechanize.HTTPError as e:
print e.code
tried += 1
if tried > 4:
exit()
sleep(30)
except mechanize.URLError as e:
print e.reason.args
tried += 1
if tried > 4:
exit()
sleep(30)
#Do stuff
You don't have to repeat things in the except block that you do in either case.
from mechanize import Browser
import time
b = Browser()
tried=0
while True:
try:
r=b.open('http://www.google.com/foobar')
except (mechanize.HTTPError,mechanize.URLError) as e:
tried += 1
if isinstance(e,mechanize.HTTPError):
print e.code
else:
print e.reason.args
if tried > 4:
exit()
sleep(30)
continue
break
Also, you may be able to use while not r: depending on what Browser.open returns.
Edit: roadierich showed a more elegant way with
try:
doSomething()
break
except:
...
Because an error skips to the except block.
For your first question, you simply want the "break" keyword, which breaks out of a loop.
For the second question, you can have several "except" clauses for one "try", for different kinds of exceptions. This replaces your isinstance() check and will make your code cleaner.
I made a program in Idle that says:
for trial in range(3):
if input('Password:') == 'password':
break
else:
# didn't find password after 3 attempts
**I need a stop program here**
print ("Welcome in")
Remember, this is in Idle, so I need program for Idle, not CMD. I also am using Python 3.2, if that helps.
A much nicer way to do this IMHO would be to put your program into a function and return when you want it to stop. Then just call the function to run your program.
def main():
for trial in range(3):
if input('Password:') == 'password':
break
else:
return
print ("Welcome in")
main()
use sys.exit() or raise SystemExit
import sys
for trial in range(3):
if input('Password:') == 'password':
break
else:
sys.exit()
print ("Welcome in"))
Edit:
To end it silently wrap it in a try-except block:
try:
import sys
for trial in range(1):
if raw_input('Password:') == 'password':
break
else:
raise SystemExit #or just sys.exit()
print ("Welcome in")
except SystemExit:
pass #when the program throws SysExit do nothing here,i.e end silently
I'm unsure what you mean by "in IDLE" vs "in CMD". A Python shell launched by IDLE should be able to be terminated the same way as a Python shell launched from the commandline.
Also, the tabs in your example appear to be wrong: everything below for... and above print... should be indented.
On to your question: are you asking for a command that terminates your script at that point? If so, adding the two lines from sys import exit and then calling exit() should do the trick, though it will raise a SystemExit exception. If you don't like that, you can add a pass handler for the SystemExit exception type at the outer layer of your program.
sys.exit can exit a program at any time.
I tried sys.exit() and it highlights 'sys' as INVALID SYNTAX.
It might be something to do with how I'm doing it, but if that's the case, then IDK then.