Invalid Syntax on "def sleeper" - python

I am working on a small project involving servos on the Raspberry Pi.
I wanted the servos to run for x amount of time then stop. Was trying out my code and am currently getting Invalid syntax on "def sleeper" and have no idea why.
Also being new to Stackoverflow, I had some issues indenting the code, my apologies!
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BOARD)
GPIO.setup(7,GPIO.OUT)
try:
while True:
GPIO.output(7,1)
time.sleep(0.0015)
GPIO.output(7,0)
def sleeper():
while True:
num = input('How long to wait: ')
try:
num = float(num)
except ValueError:
print('Please enter in a number.\n')
continue
print('Before: %s' % time.ctime())
time.sleep(num)
print('After: %s\n' % time.ctime())
try:
sleeper()
except KeyboardInterrupt:
print('\n\nKeyboard exception received. Exiting.')
exit()

That's because you didn't wrote any except block for the first try ... except pair:
This may work as you want:
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BOARD)
GPIO.setup(7,GPIO.OUT)
try:
while True:
GPIO.output(7,1)
time.sleep(0.0015)
GPIO.output(7,0)
except:
pass
def sleeper():
while True:
num = input('How long to wait: ')
try:
num = float(num)
except ValueError:
print('Please enter in a number.\n')
continue
print('Before: %s' % time.ctime())
time.sleep(num)
print('After: %s\n' % time.ctime())
try:
sleeper()
except KeyboardInterrupt:
print('\n\nKeyboard exception received. Exiting.')
exit()
Check indentations please.

Related

problem printing a string within except? Program just ends instead of printing statement

The program isn't printing what I want ("too slow") after the except with the KeyboardInterrupt, which should end the program and print the string, instead the program just ends. I tried messing around with it a bit but can't seem to figure it out. What should I do?
import os
import signal
import threading
from random import randint
def timed_input(interval, *args):
t = threading.Timer(interval, os.kill, args=(os.getpid(), signal.SIGINT))
t.start()
try:
return int(input(*args))
except:
pass
finally:
t.cancel()
while True:
want = randint(1,9)
try:
got = timed_input(5, f'type "{want}": ')
except KeyboardInterrupt:
print('too slow')
else:
if got != want:
print('You Lose.')
break
This is because your first function is removing the KeyboardInterrupt thus making the second try block useless.
To fix this add another except block for the first function so it is properly raised:
import os
import signal
import threading
from random import randint
def timed_input(interval, *args):
t = threading.Timer(interval, os.kill, args=(os.getpid(), signal.SIGINT))
t.start()
try:
return int(input(*args))
except KeyboardInterrupt:
raise
except ValueError:
pass
finally:
t.cancel()
while True:
want = randint(1,9)
try:
got = timed_input(5, f'type "{want}": ')
except KeyboardInterrupt:
print('too slow')
else:
if got != want:
print('You Lose.')
break

KeyboardInterrupt exeption handling with time.sleep

I am going to display current time every 2 seconds and exception handling.
If there is KeyboardInterrupt, message should display like print('Program is stopped').
But in my code, try/except isn`t working.So how can I print message like 'Stopped'?
from datetime import datetime
import time
def display_time():
time.sleep(2)
current_time = datetime.now()
print('Time: ', current_time.strftime("%X"))
try:
while True:
display_time()
except KeyboardInterrupt:
print('Stopped')
print('Program ends')
You should check if Ctrl-C is pressed inside the while loop and, if so break outside the loop:
while True:
try:
display_time()
except KeyboardInterrupt:
print("Stopped")
break
print('Program ends')

Python password alarm for five minutes

I have written this python program for a game:
print("CC ACTIVATED")
import lcddriver
import time
import subprocess
display = lcddriver.lcd()
try:
display.lcd_display_string("CC... ", 1)
time.sleep(2)
display.lcd_display_string("ONLINE", 2)
time.sleep(2)
display.lcd_clear()
except Exception:
print("SCREEN ERROR")
try:
display.lcd_display_string("SETUP A", 1)
display.lcd_display_string("PASSWORD? Y/N", 2)
except Exception:
print("SCREEN ERROR")
activate = input("")
if activate == 'y':
print("ACTIVATED")
try:
display.lcd_clear()
display.lcd_display_string("", 1)
time.sleep(2)
display.lcd_display_string("LOADING", 2)
time.sleep(2)
display.lcd_clear()
except Exception:
print("SCREEN ERROR")
else:
print("ABORT")
try:
display.lcd_clear()
display.lcd_display_string("", 1)
time.sleep(2)
display.lcd_display_string("ABORT", 2)
time.sleep(2)
display.lcd_clear()
subprocess.call(["sudo","halt"])
except Exception:
print("SCREEN ERROR")
subprocess.call(["sudo","halt"])
k = True
while k:
try:
display.lcd_clear()
display.lcd_display_string("ENTER PASWORD", 1)
display.lcd_display_string("----------------", 2)
except Exception:
print("SCREEN ERROR")
pasword = input("")
display.lcd_clear()
try:
display.lcd_clear()
display.lcd_display_string("YOU TYPED:", 1)
display.lcd_display_string(pasword, 2)
time.sleep(2)
display.lcd_display_string("CONFIRM? Y/N", 1)
except Exception:
print("SCREEN ERROR")
ok = input("")
if ok == 'y':
k = False
else:
display.lcd_clear()
try:
display.lcd_clear()
display.lcd_display_string("PASSWORD", 1)
display.lcd_display_string("SET", 2)
except Exception:
print("SCREEN ERROR")
time.sleep(2)
run = True
try:
display.lcd_clear()
display.lcd_display_string("STARTING ", 1)
display.lcd_display_string("GAME...", 2)
except Exception:
print("SCREEN ERROR")
time.sleep(2)
while run:
try:
display.lcd_clear()
display.lcd_display_string("ENTER PASSWORD ", 1)
display.lcd_display_string("TO DEACTIVATE", 2)
except Exception:
print("SCREEN ERROR")
pasword1 = input("")
if pasword1 == pasword:
try:
display.lcd_clear()
display.lcd_display_string("PASSWORD....", 1)
time.sleep(2)
display.lcd_display_string("ACCEPTED", 2)
time.sleep(2)
display.lcd_clear()
display.lcd_display_string("DEACTIVATED", 2)
subprocess.call(["sudo","halt"])
time.sleep(10)
except Exception:
print("SCREEN ERROR")
subprocess.call(["sudo","halt"])
else:
try:
display.lcd_clear()
display.lcd_display_string("PASSWORD....", 1)
time.sleep(2)
display.lcd_display_string("UNACCEPTED", 2)
time.sleep(2)
except Exception:
print("SCREEN ERROR")
It runs on a raspberry pi and works absolutely fine, but there is one thing I want to do that is a bit above my skill level. I need this program to give you three attempts to guess the password,then at the fourth attempt play an audio recording. Afterward it needs to respond to failed attempts with the audio recording for five minutes and then go back to the silent three chances. I know how to get it to do the audio recording, but I need help with the five minute part. Does anyone here know how to do this? Thanks.
To permit three password attempts, you will need a counter variable which will count up to three with each failed attempt.
Rather than just running while k == True, you want to check against both k == True and attempts <= 3. As far as waiting five minutes, you will want to create a timestamp of when the user last guessed.
from datetime import datetime
...
k = True
password_attempts = 0
while k and password_attempts < 4:
try:
display.lcd_clear()
display.lcd_display_string("ENTER PASWORD", 1)
display.lcd_display_string("----------------", 2)
except Exception:
print("SCREEN ERROR")
pasword = input("")
display.lcd_clear()
try:
display.lcd_clear()
display.lcd_display_string("YOU TYPED:", 1)
display.lcd_display_string(pasword, 2)
time.sleep(2)
display.lcd_display_string("CONFIRM? Y/N", 1)
except Exception:
print("SCREEN ERROR")
ok = input("")
if ok == "y":
k = False
else:
display.lcd_clear()
password_attempts += 1
if password_attempts == 4:
#Create a timestamp of last attempt
last_request = datetime.now()
current_request = datetime.now()
while((last_request - current_request).total_seconds() < 5 * 60):
#Code to play music
current_request = datetime.now()
Then it's up to you to re-route the player back to the point in the program where they try entering the passwords again.
But, the design choices you've made at the beginning of this project will really start to get in the way of what you want to do.
I suggest you consider a redesign of your program, in order to make working on it much easier and more pleasant.
One of the best parts of programming is code re-use; this is most easily understood with functions. In Python, you create a function with the syntax def function_name():
Then, when you want to run the code within that function, you simply call it by name: function_name().
What does this mean for your app?
You could wrap writing to the LCD in a method, so that you can avoid repeatedly typing out the same try:... except: block (by the way... when you write except Exception, you are catching ALL exceptions your program might throw. This is considered bad practice, because you may not want to do the same thing irrespective of what the exception was in the first place. Rather, try to find a specific exception you're trying to catch, and catch that one by name, specifically).
An example of rewriting the LCD printing:
def print_to_lcd(statements_to_print: [str]):
line_number = 1
try:
for statement in statements_to_print:
display.lcd_display_string(statement, line_number)
line_number += 1
except Exception:
print("SCREEN ERROR")
Then, you just produce a list of things for the LCD to print, and call the LCD function with them:
things_to_write = ["PASSWORD...", "UNACCEPTED"]
print_to_lcd(things_to_write)
The same can be said about how you check your password value, when you play the music, etc.
Any time you find yourself repeatedly re-writing the same information, take a moment and think if there's a way you can write it once, and just re-use it. It'll make your programs much easier to write, and much easier to use.
Particularly in this case, since you want to re-do the same thing after waiting for a period of time. Imagine, rather than having to write tons of if-statements, when the user enters the password wrong for the fourth time, you just write something like:
play_music_for_five_minutes()
prompt_for_password()
Let me know if there are any further questions I can answer!

Why is this usage of "except" a syntax error in Python 3?

I am trying to write a simple program which will turn lights on and off based on the time of day, in Python 3.
I keep on getting a syntax error when try and use except KeyboardInterrupt: in a while loop. This is the error:
except KeyboardInterrupt:
^
SyntaxError: invalid syntax
As I have doubled checked the syntax with online documentation I am at a loss as to what I am doing wrong and I guess I am missing some piece of understanding here.
Here is the full code for reference:
#!/usr/bin/python
import time
import datetime
TimeStart = datetime.time(17, 0, 0)
TimeEnd = datetime.time(18, 30, 0)
def onoff():
while True:
if TimeEnd > datetime.datetime.now().time() and TimeStart < datetime.datetime.now().time():
print("Pin 18 High")
else:
print("Pin 18 Low")
except KeyboardInterrupt:
pass
print("Error..... Quiting.....")
raise
sys.exit()
time.sleep(30)
onoff()
You cannot use the except statement outside of a try: ... except: ... code block.
https://docs.python.org/3/tutorial/errors.html#handling-exceptions
So you would rephrase your code as
while True:
try:
if TimeEnd > datetime.datetime.now().time() and TimeStart < datetime.datetime.now().time() :
print ("Pin 18 High")
else:
print ("Pin 18 Low")
except KeyboardInterrupt:
pass
print("Error..... Quiting.....")
raise
sys.exit()
which I haven't tried but essentially
wraps the if statement with a try clause, and
any KeyboardInterrupt would be captured by the except statement.

Time limit on input in Python [duplicate]

This question already has answers here:
Keyboard input with timeout?
(28 answers)
Closed 3 years ago.
What I would like to be able to do is ask a user a question using input. For example:
print('some scenario')
prompt = input("You have 10 seconds to choose the correct answer...\n")
and then if the time elapses print something like
print('Sorry, times up.')
Any help pointing me in the right direction would be greatly appreciated.
If it is acceptable to block the main thread when user haven't provided an answer:
from threading import Timer
timeout = 10
t = Timer(timeout, print, ['Sorry, times up'])
t.start()
prompt = "You have %d seconds to choose the correct answer...\n" % timeout
answer = input(prompt)
t.cancel()
Otherwise, you could use #Alex Martelli's answer (modified for Python 3) on Windows (not tested):
import msvcrt
import time
class TimeoutExpired(Exception):
pass
def input_with_timeout(prompt, timeout, timer=time.monotonic):
sys.stdout.write(prompt)
sys.stdout.flush()
endtime = timer() + timeout
result = []
while timer() < endtime:
if msvcrt.kbhit():
result.append(msvcrt.getwche()) #XXX can it block on multibyte characters?
if result[-1] == '\r':
return ''.join(result[:-1])
time.sleep(0.04) # just to yield to other processes/threads
raise TimeoutExpired
Usage:
try:
answer = input_with_timeout(prompt, 10)
except TimeoutExpired:
print('Sorry, times up')
else:
print('Got %r' % answer)
On Unix you could try:
import select
import sys
def input_with_timeout(prompt, timeout):
sys.stdout.write(prompt)
sys.stdout.flush()
ready, _, _ = select.select([sys.stdin], [],[], timeout)
if ready:
return sys.stdin.readline().rstrip('\n') # expect stdin to be line-buffered
raise TimeoutExpired
Or:
import signal
def alarm_handler(signum, frame):
raise TimeoutExpired
def input_with_timeout(prompt, timeout):
# set signal handler
signal.signal(signal.SIGALRM, alarm_handler)
signal.alarm(timeout) # produce SIGALRM in `timeout` seconds
try:
return input(prompt)
finally:
signal.alarm(0) # cancel alarm
Interesting problem, this seems to work:
import time
from threading import Thread
answer = None
def check():
time.sleep(2)
if answer != None:
return
print("Too Slow")
Thread(target = check).start()
answer = input("Input something: ")

Categories