How can I create an asynchronous program with urwid and asyncio? - python

I want to build a chatroom with aiortc. Frist of all, I want to build a mockup with urwid as cli and asyncio.
The urwid part is already running fine, user input is possible. I know want to run a coroutine that generates random text and works as chat clients texting in that chatroom.
I have tried to run my urwid function with the mainloop as an asyncio coroutine but without success.
I don't know how to integrate an asynchronous function into my urwid mainloop.
def unhandled(key):
"""
functin to handle input
"""
global TEXT_INPUT
global lw_user_input
global lw_chatroom
global listbox_chatroom
if not isinstance(key, tuple):
if key == 'enter':
del lw_user_input[-1]
# create widegt and fill with user input
lw_chatroom.append(widget)
TEXT_INPUT = ""
listbox_chatroom.set_focus(len(lw_chatroom)-1, 'above')
elif key == 'esc':
raise urwid.ExitMainLoop()
elif key == 'backspace':
if len(lw_user_input) > 0:
user_input = lw_user_input[0].get_text()[0]
user_input = user_input[:-1]
del lw_user_input[-1]
TEXT_INPUT = user_input
lw_user_input.append(urwid.Text(TEXT_INPUT))
else:
TEXT_INPUT += key # repr(key)
if len(lw_user_input) > 0:
del lw_user_input[-1]
lw_user_input.append(urwid.Text(TEXT_INPUT))
else:
lw_user_input.append(urwid.Text(key))
def generate_output():
global lw_chatroom
global listbox_chatroom
while True:
# generate text and widgets and post with delay
lw_chatroom.append(chat_widget)
listbox_chatroom.set_focus(len(lw_chatroom)-1, 'above')
def create_cli():
# generate all widgets
uloop = urwid.MainLoop(frame, palette, screen,
unhandled_input=unhandled)
uloop.start()
if __name__ == '__main__':
create_cli()
I want to run generate_output() and unhandled(key) asynchronously. I have no idea how to.

Ok, I figured it out.
It is as simple as this:
aloop = asyncio.get_event_loop()
ev_loop = urwid.AsyncioEventLoop(loop=aloop)
loop = urwid.MainLoop(frame, palette, screen,
unhandled_input=unhandled, event_loop=ev_loop)
aloop.create_task(generate_output())
loop.run()

Related

Pyglet Audio Queue - Python

import pyglet, pafy
from pyglet.window import key
import urllib.request
from urllib.parse import *
from googleapiclient.discovery import build
api_key = ''
yt = build('youtube', 'v3', developerKey=api_key)
def download_file(search):
try:
os.remove("song.m4a")
except:
pass
request = yt.search().list(
part="snippet",
maxResults=1,
q=search
)
response = request.execute()
items = response['items']
item = items[0]
snippet = item['snippet']
title = snippet['title']
id_ = item["id"]
videoid = id_["videoId"]
url = "https://www.youtube.com/watch?v=" + videoid
info = pafy.new(url)
audio = info.getbestaudio(preftype="m4a")
audio.download('song.m4a', quiet=True)
file = 'song.m4a'
#if len(sys.argv)>1:
# file = sys.argv[1]
#
window = pyglet.window.Window()
#music = pyglet.resource.media(file)
player = pyglet.media.Player()
#player.queue(music)
#player.play()
paused = False
def help():
print("""\nCommands:
\tEsc or x \t Exit program
\tp \t Pause/unpause music
\th \t See this list again""")
print("""Welcome to this music player!
You can give a file as an argument or use the commands below.""")
help()
#window.event
def on_key_press(symbol, modifiers):
global paused
global player
global window
file = 'song.m4a'
if symbol == key.P:
if paused:
print("Resume")
player.play()
paused = False
else:
print("Pause")
player.pause()
paused = True
elif symbol == key.R:
pass
#Doesn't work :P
#player.seek(0)
elif symbol == key.H:
help()
elif symbol == key.ESCAPE:
try:
os.remove("song.m4a")
except:
pass
window.close()
elif symbol == key.Q:
srch = input("Queue Song: ")
download_file(srch)
music = pyglet.media.load(file)
player.queue(music)
#music.play()
player.next_source()
print(f'Added to queue.')
elif symbol == key.S:
srch = input("Play Song: ")
download_file(srch)
music = pyglet.media.load(file)
#music.play()
player.queue(music)
player.next_source()
pyglet.app.run()
pyglet.app.exit()
So I have been running into some issues with the Pyglet lib. I can't seem to get this part to work. Am I calling player.next_source() correctly? Because I just ran symbol == key.S put in a value for srch and nothing played. My goal is to make it so the input I enter when I press q will queue the song and automatically play after the current one, while pressing s and inputting a value there will overwrite the queue and prioritize that. Some help would be appreciated.
First, you are using player.next_source(). That forces the player to go to the next in queue. So your Q key function is incorrect, you aren't queuing it, you are queuing it and then forcing it to play. Which is what you should be doing with your S key. I think you have those confused or are mixed up on what the next_source actually does.
Secondly, when loading music, it's streamed from the file itself. It looks like you are overwriting the file each time you press a key (which isn't really ideal, and prone to errors doing it this way). So this will not work with streaming.
Your best bet is to load the file in it's entirety so that if the file gets overwritten, it's not going to cause weird issues with queued buffers. Try changing your
music = pyglet.media.load(file)
to
music = pyglet.media.load(file, streaming=False)
You also may have better luck downloading the file to a separate file or a temp file (see tempfile library) instead of trying to re-use the same filename.
Also you most likely have to store music into a global dictionary or global list to prevent it from being garbage collected. As music is a local variable to the function and will disappear as soon as the event is over. (This also means you will have to delete them from the list when you no longer need them to prevent a memory leak)

Threading with Python

complete python newbie...
I'm working with the Arduino pyfirmata package and Im trying to do something quite simple.
Depending on a user input to python, I want an LED to flash or not.
My problem is that the python program only asks for the user input once but I would like it to always ask for the input so the user can change function at any time.
I have tried using the threading package but no success... Perhaps there is a simpler way, but I am totally new to coding so I do not know of any other. Open to suggestions!!
Here is my code,
import pyfirmata
import threading
import time
board = pyfirmata.Arduino('/dev/cu.usbmodem14101')
def flash():
for i in range(1000):
board.digital[13].write(1)
time.sleep(1)
board.digital[13].write(0)
time.sleep(1)
def stop():
board.digital[13].write(0)
while True:
runMode = input("Run or Stop? ")
if runMode == "Run":
x = threading.Thread(target=flash(), args=(1,))
x.start()
# x.join()
elif runMode == "Stop":
x = threading.Thread(target=stop(), args=(1,))
x.start()
#x.join()
You can do it in an object-oriented way by creating your own Thread subclass something like the Flasher class below.
One of the advantages to this approach is that it would be relatively easy to extend the Flasher class and make it control LEDs connected to different outputs, or to allow the delay between flashes to be specified at creation time. Doing the former would allow multiple instances to be running at the same time.
import pyfirmata
import threading
import time
OFF, ON = False, True
class Flasher(threading.Thread):
DELAY = 1
def __init__(self):
super().__init__()
self.daemon = True
self.board = pyfirmata.Arduino('/dev/cu.usbmodem14101')
self.flashing = False
self.LED_state = OFF
def turn_LED_on(self):
self.board.digital[13].write(1)
self.LED_state = ON
def turn_LED_off(self):
self.board.digital[13].write(0)
self.LED_state = OFF
def run(self):
while True:
if self.flashing:
if self.LED_state == ON:
self.turn_LED_off()
else:
self.turn_LED_on()
time.sleep(self.DELAY)
def start_flashing(self):
if self.LED_state == OFF:
self.turn_LED_on()
self.flashing = True
def stop_flashing(self):
if self.LED_state == ON:
self.turn_LED_off()
self.flashing = False
flasher = Flasher()
flasher.start()
while True:
runMode = input("Run or Stop? ").strip().lower()
if runMode == "run":
flasher.start_flashing()
elif runMode == "stop":
flasher.stop_flashing()
else:
print('Unknown response ignored')
If your looking to just kill the thread you could use mulitiprocessing
which a multiprocessing.Process can p.terminate()
p = Process(target=flash, args=(,))
while True:
runMode = input("Run or Stop? ")
if runMode == "Run":
p.start()
elif runMode == "Stop":
p.terminate()
However this is not recommended to just kill threads as it can cause errors if the process is handling critical resources or dependant on other threads see here for a better explanation Is there any way to kill a Thread?
A better option as described here is to use flags to handle your flashing, they allow a simple communication between threads
from threading import Event
e = event()
def check_for_stop(e):
while not e.isSet():
flash()
print("Flashing Ended")
while True:
runMode = input("Run or Stop? ")
if runMode == "Run":
x = threading.Thread(target=check_for_stop, args=(e,))
x.start()
# x.join()
elif runMode == "Stop":
e.set() #set flag true
e.clear() #reset flag
here is the documentation for more info on event objects https://docs.python.org/2.0/lib/event-objects.html
I havent tested this code is just an example so apologies if it doesnt work straight away
Edit: Just looking at your function again you would want to check for the flag during the flashing thats my mistake aplogies so your flash function would look like
def flash():
while e.isSet():
board.digital[13].write(1)
time.sleep(1)
board.digital[13].write(0)
time.sleep(1)
and you would pass this into the thread as you have before
x = threading.Thread(target=flash(), args=(1,))
x.start()
You got an error in the code.
You should create the thread via:
x = threading.Thread(target=flash)
Note: You gave the entered 'flash()' therefore executing the method in the main thread. And also your method doesn't have any arguments therefore you can remove the args values

Cancelling input() when not done in allotted time: Python 3. Windows [duplicate]

in python, is there a way to, while waiting for a user input, count time so that after, say 30 seconds, the raw_input() function is automatically skipped?
The signal.alarm function, on which #jer's recommended solution is based, is unfortunately Unix-only. If you need a cross-platform or Windows-specific solution, you can base it on threading.Timer instead, using thread.interrupt_main to send a KeyboardInterrupt to the main thread from the timer thread. I.e.:
import thread
import threading
def raw_input_with_timeout(prompt, timeout=30.0):
print(prompt, end=' ')
timer = threading.Timer(timeout, thread.interrupt_main)
astring = None
try:
timer.start()
astring = input(prompt)
except KeyboardInterrupt:
pass
timer.cancel()
return astring
this will return None whether the 30 seconds time out or the user explicitly decides to hit control-C to give up on inputting anything, but it seems OK to treat the two cases in the same way (if you need to distinguish, you could use for the timer a function of your own that, before interrupting the main thread, records somewhere the fact that a timeout has happened, and in your handler for KeyboardInterrupt access that "somewhere" to discriminate which of the two cases occurred).
Edit: I could have sworn this was working but I must have been wrong -- the code above omits the obviously-needed timer.start(), and even with it I can't make it work any more. select.select would be the obvious other thing to try but it won't work on a "normal file" (including stdin) in Windows -- in Unix it works on all files, in Windows, only on sockets.
So I don't know how to do a cross-platform "raw input with timeout". A windows-specific one can be constructed with a tight loop polling msvcrt.kbhit, performing a msvcrt.getche (and checking if it's a return to indicate the output's done, in which case it breaks out of the loop, otherwise accumulates and keeps waiting) and checking the time to time out if needed. I cannot test because I have no Windows machine (they're all Macs and Linux ones), but here the untested code I would suggest:
import msvcrt
import time
def raw_input_with_timeout(prompt, timeout=30.0):
print(prompt, end=' ')
finishat = time.time() + timeout
result = []
while True:
if msvcrt.kbhit():
result.append(msvcrt.getche())
if result[-1] == '\r': # or \n, whatever Win returns;-)
return ''.join(result)
time.sleep(0.1) # just to yield to other processes/threads
else:
if time.time() > finishat:
return None
The OP in a comment says he does not want to return None upon timeout, but what's the alternative? Raising an exception? Returning a different default value? Whatever alternative he wants he can clearly put it in place of my return None;-).
If you don't want to time out just because the user is typing slowly (as opposed to, not typing at all!-), you could recompute finishat after every successful character input.
I found a solution to this problem in a blog post. Here's the code from that blog post:
import signal
class AlarmException(Exception):
pass
def alarmHandler(signum, frame):
raise AlarmException
def nonBlockingRawInput(prompt='', timeout=20):
signal.signal(signal.SIGALRM, alarmHandler)
signal.alarm(timeout)
try:
text = raw_input(prompt)
signal.alarm(0)
return text
except AlarmException:
print '\nPrompt timeout. Continuing...'
signal.signal(signal.SIGALRM, signal.SIG_IGN)
return ''
Please note: this code will only work on *nix OSs.
The input() function is designed to wait for the user to enter something (at least the [Enter] key).
If you are not dead set to use input(), below is a much lighter solution using tkinter. In tkinter, dialog boxes (and any widget) can be destroyed after a given time.
Here is an example :
import tkinter as tk
def W_Input (label='Input dialog box', timeout=5000):
w = tk.Tk()
w.title(label)
W_Input.data=''
wFrame = tk.Frame(w, background="light yellow", padx=20, pady=20)
wFrame.pack()
wEntryBox = tk.Entry(wFrame, background="white", width=100)
wEntryBox.focus_force()
wEntryBox.pack()
def fin():
W_Input.data = str(wEntryBox.get())
w.destroy()
wSubmitButton = tk.Button(w, text='OK', command=fin, default='active')
wSubmitButton.pack()
# --- optionnal extra code in order to have a stroke on "Return" equivalent to a mouse click on the OK button
def fin_R(event): fin()
w.bind("<Return>", fin_R)
# --- END extra code ---
w.after(timeout, w.destroy) # This is the KEY INSTRUCTION that destroys the dialog box after the given timeout in millisecondsd
w.mainloop()
W_Input() # can be called with 2 parameter, the window title (string), and the timeout duration in miliseconds
if W_Input.data : print('\nYou entered this : ', W_Input.data, end=2*'\n')
else : print('\nNothing was entered \n')
from threading import Timer
def input_with_timeout(x):
def time_up():
answer= None
print('time up...')
t = Timer(x,time_up) # x is amount of time in seconds
t.start()
try:
answer = input("enter answer : ")
except Exception:
print('pass\n')
answer = None
if answer != True: # it means if variable have somthing
t.cancel() # time_up will not execute(so, no skip)
input_with_timeout(5) # try this for five seconds
As it is self defined... run it in command line prompt , I hope you will get the answer
read this python doc you will be crystal clear what just happened in this code!!
A curses example which takes for a timed math test
#!/usr/bin/env python3
import curses
import curses.ascii
import time
#stdscr = curses.initscr() - Using curses.wrapper instead
def main(stdscr):
hd = 100 #Timeout in tenths of a second
answer = ''
stdscr.addstr('5+3=') #Your prompt text
s = time.time() #Timing function to show that solution is working properly
while True:
#curses.echo(False)
curses.halfdelay(hd)
start = time.time()
c = stdscr.getch()
if c == curses.ascii.NL: #Enter Press
break
elif c == -1: #Return on timer complete
break
elif c == curses.ascii.DEL: #Backspace key for corrections. Could add additional hooks for cursor movement
answer = answer[:-1]
y, x = curses.getsyx()
stdscr.delch(y, x-1)
elif curses.ascii.isdigit(c): #Filter because I only wanted digits accepted
answer += chr(c)
stdscr.addstr(chr(c))
hd -= int((time.time() - start) * 10) #Sets the new time on getch based on the time already used
stdscr.addstr('\n')
stdscr.addstr('Elapsed Time: %i\n'%(time.time() - s))
stdscr.addstr('This is the answer: %s\n'%answer)
#stdscr.refresh() ##implied with the call to getch
stdscr.addstr('Press any key to exit...')
curses.wrapper(main)
under linux one could use curses and getch function, its non blocking.
see getch()
https://docs.python.org/2/library/curses.html
function that waits for keyboard input for x seconds (you have to initialize a curses window (win1) first!
import time
def tastaturabfrage():
inittime = int(time.time()) # time now
waitingtime = 2.00 # time to wait in seconds
while inittime+waitingtime>int(time.time()):
key = win1.getch() #check if keyboard entry or screen resize
if key == curses.KEY_RESIZE:
empty()
resize()
key=0
if key == 118:
p(4,'KEY V Pressed')
yourfunction();
if key == 107:
p(4,'KEY K Pressed')
yourfunction();
if key == 99:
p(4,'KEY c Pressed')
yourfunction();
if key == 120:
p(4,'KEY x Pressed')
yourfunction();
else:
yourfunction
key=0
This is for newer python versions, but I believe it will still answer the question. What this does is it creates a message to the user that the time is up, then ends the code. I'm sure there's a way to make it skip the input rather than completely end the code, but either way, this should at least help...
import sys
import time
from threading import Thread
import pyautogui as pag
#imports the needed modules
xyz = 1 #for a reference call
choice1 = None #sets the starting status
def check():
time.sleep(15)#the time limit set on the message
global xyz
if choice1 != None: # if choice1 has input in it, than the time will not expire
return
if xyz == 1: # if no input has been made within the time limit, then this message
# will display
pag.confirm(text = 'Time is up!', title = 'Time is up!!!!!!!!!')
sys.exit()
Thread(target = check).start()#starts the timer
choice1 = input("Please Enter your choice: ")

time out and proceed if no input() provided [duplicate]

in python, is there a way to, while waiting for a user input, count time so that after, say 30 seconds, the raw_input() function is automatically skipped?
The signal.alarm function, on which #jer's recommended solution is based, is unfortunately Unix-only. If you need a cross-platform or Windows-specific solution, you can base it on threading.Timer instead, using thread.interrupt_main to send a KeyboardInterrupt to the main thread from the timer thread. I.e.:
import thread
import threading
def raw_input_with_timeout(prompt, timeout=30.0):
print(prompt, end=' ')
timer = threading.Timer(timeout, thread.interrupt_main)
astring = None
try:
timer.start()
astring = input(prompt)
except KeyboardInterrupt:
pass
timer.cancel()
return astring
this will return None whether the 30 seconds time out or the user explicitly decides to hit control-C to give up on inputting anything, but it seems OK to treat the two cases in the same way (if you need to distinguish, you could use for the timer a function of your own that, before interrupting the main thread, records somewhere the fact that a timeout has happened, and in your handler for KeyboardInterrupt access that "somewhere" to discriminate which of the two cases occurred).
Edit: I could have sworn this was working but I must have been wrong -- the code above omits the obviously-needed timer.start(), and even with it I can't make it work any more. select.select would be the obvious other thing to try but it won't work on a "normal file" (including stdin) in Windows -- in Unix it works on all files, in Windows, only on sockets.
So I don't know how to do a cross-platform "raw input with timeout". A windows-specific one can be constructed with a tight loop polling msvcrt.kbhit, performing a msvcrt.getche (and checking if it's a return to indicate the output's done, in which case it breaks out of the loop, otherwise accumulates and keeps waiting) and checking the time to time out if needed. I cannot test because I have no Windows machine (they're all Macs and Linux ones), but here the untested code I would suggest:
import msvcrt
import time
def raw_input_with_timeout(prompt, timeout=30.0):
print(prompt, end=' ')
finishat = time.time() + timeout
result = []
while True:
if msvcrt.kbhit():
result.append(msvcrt.getche())
if result[-1] == '\r': # or \n, whatever Win returns;-)
return ''.join(result)
time.sleep(0.1) # just to yield to other processes/threads
else:
if time.time() > finishat:
return None
The OP in a comment says he does not want to return None upon timeout, but what's the alternative? Raising an exception? Returning a different default value? Whatever alternative he wants he can clearly put it in place of my return None;-).
If you don't want to time out just because the user is typing slowly (as opposed to, not typing at all!-), you could recompute finishat after every successful character input.
I found a solution to this problem in a blog post. Here's the code from that blog post:
import signal
class AlarmException(Exception):
pass
def alarmHandler(signum, frame):
raise AlarmException
def nonBlockingRawInput(prompt='', timeout=20):
signal.signal(signal.SIGALRM, alarmHandler)
signal.alarm(timeout)
try:
text = raw_input(prompt)
signal.alarm(0)
return text
except AlarmException:
print '\nPrompt timeout. Continuing...'
signal.signal(signal.SIGALRM, signal.SIG_IGN)
return ''
Please note: this code will only work on *nix OSs.
The input() function is designed to wait for the user to enter something (at least the [Enter] key).
If you are not dead set to use input(), below is a much lighter solution using tkinter. In tkinter, dialog boxes (and any widget) can be destroyed after a given time.
Here is an example :
import tkinter as tk
def W_Input (label='Input dialog box', timeout=5000):
w = tk.Tk()
w.title(label)
W_Input.data=''
wFrame = tk.Frame(w, background="light yellow", padx=20, pady=20)
wFrame.pack()
wEntryBox = tk.Entry(wFrame, background="white", width=100)
wEntryBox.focus_force()
wEntryBox.pack()
def fin():
W_Input.data = str(wEntryBox.get())
w.destroy()
wSubmitButton = tk.Button(w, text='OK', command=fin, default='active')
wSubmitButton.pack()
# --- optionnal extra code in order to have a stroke on "Return" equivalent to a mouse click on the OK button
def fin_R(event): fin()
w.bind("<Return>", fin_R)
# --- END extra code ---
w.after(timeout, w.destroy) # This is the KEY INSTRUCTION that destroys the dialog box after the given timeout in millisecondsd
w.mainloop()
W_Input() # can be called with 2 parameter, the window title (string), and the timeout duration in miliseconds
if W_Input.data : print('\nYou entered this : ', W_Input.data, end=2*'\n')
else : print('\nNothing was entered \n')
from threading import Timer
def input_with_timeout(x):
def time_up():
answer= None
print('time up...')
t = Timer(x,time_up) # x is amount of time in seconds
t.start()
try:
answer = input("enter answer : ")
except Exception:
print('pass\n')
answer = None
if answer != True: # it means if variable have somthing
t.cancel() # time_up will not execute(so, no skip)
input_with_timeout(5) # try this for five seconds
As it is self defined... run it in command line prompt , I hope you will get the answer
read this python doc you will be crystal clear what just happened in this code!!
A curses example which takes for a timed math test
#!/usr/bin/env python3
import curses
import curses.ascii
import time
#stdscr = curses.initscr() - Using curses.wrapper instead
def main(stdscr):
hd = 100 #Timeout in tenths of a second
answer = ''
stdscr.addstr('5+3=') #Your prompt text
s = time.time() #Timing function to show that solution is working properly
while True:
#curses.echo(False)
curses.halfdelay(hd)
start = time.time()
c = stdscr.getch()
if c == curses.ascii.NL: #Enter Press
break
elif c == -1: #Return on timer complete
break
elif c == curses.ascii.DEL: #Backspace key for corrections. Could add additional hooks for cursor movement
answer = answer[:-1]
y, x = curses.getsyx()
stdscr.delch(y, x-1)
elif curses.ascii.isdigit(c): #Filter because I only wanted digits accepted
answer += chr(c)
stdscr.addstr(chr(c))
hd -= int((time.time() - start) * 10) #Sets the new time on getch based on the time already used
stdscr.addstr('\n')
stdscr.addstr('Elapsed Time: %i\n'%(time.time() - s))
stdscr.addstr('This is the answer: %s\n'%answer)
#stdscr.refresh() ##implied with the call to getch
stdscr.addstr('Press any key to exit...')
curses.wrapper(main)
under linux one could use curses and getch function, its non blocking.
see getch()
https://docs.python.org/2/library/curses.html
function that waits for keyboard input for x seconds (you have to initialize a curses window (win1) first!
import time
def tastaturabfrage():
inittime = int(time.time()) # time now
waitingtime = 2.00 # time to wait in seconds
while inittime+waitingtime>int(time.time()):
key = win1.getch() #check if keyboard entry or screen resize
if key == curses.KEY_RESIZE:
empty()
resize()
key=0
if key == 118:
p(4,'KEY V Pressed')
yourfunction();
if key == 107:
p(4,'KEY K Pressed')
yourfunction();
if key == 99:
p(4,'KEY c Pressed')
yourfunction();
if key == 120:
p(4,'KEY x Pressed')
yourfunction();
else:
yourfunction
key=0
This is for newer python versions, but I believe it will still answer the question. What this does is it creates a message to the user that the time is up, then ends the code. I'm sure there's a way to make it skip the input rather than completely end the code, but either way, this should at least help...
import sys
import time
from threading import Thread
import pyautogui as pag
#imports the needed modules
xyz = 1 #for a reference call
choice1 = None #sets the starting status
def check():
time.sleep(15)#the time limit set on the message
global xyz
if choice1 != None: # if choice1 has input in it, than the time will not expire
return
if xyz == 1: # if no input has been made within the time limit, then this message
# will display
pag.confirm(text = 'Time is up!', title = 'Time is up!!!!!!!!!')
sys.exit()
Thread(target = check).start()#starts the timer
choice1 = input("Please Enter your choice: ")

Interrupting a timer

I'm creating part of a program right now for a personal project and I need some help on one aspect of it.
Here is how the program works:
User enters the amount of time to run
User enters the text - Files are modified
Timer is started
optional User can enter "password" to interrupt the timer
Actions are reversed
I have all of the steps coded except the Timer because I'm trying to figure out the best way to do this. Ideally, I'd like the timer to be displaying a countdown, and if the user enters a certain "password" the timer is interrupted and it skips to step number 5.
Would the best way to do this be with a thread? I haven't worked much with threads in the past. I just need someway for the timer to be displayed while also giving control back to the user in case they want to enter that password.
Thanks for any help you provide.
Here's the code:
import time
import urllib
import sys
def restore():
backup = open(r'...backupfile.txt','r')
text = open(r'...file.txt', 'w+')
text.seek(0)
for line in backup:
text.write(line)
backup.close()
text.close()
text = open(r'...file.txt', 'a+')
backup = open(r'...backupfile.txt','w+')
text.seek(0)
for line in text:
backup.write(line)
backup.close()
while True:
url = raw_input('Please enter a URL: ')
try:
if url[:7] != 'http://':
urllib.urlopen('http://' + url)
else:
urllib.urlopen(url)
except IOError:
print "Not a real URL"
continue
text.write(url)
while True:
choice = raw_input('Would you like to enter another url? (y/n): ')
try:
if choice == 'y' or choice == 'n':
break
except:
continue
if choice == 'y':
text.seek(2)
continue
elif choice == 'n':
while True:
choice = raw_input('Would you to restore your file to the original backup (y/n): ')
try:
if choice == 'y' or choice == 'n':
break
except:
continue
if choice == 'y':
text.close()
restore()
sys.exit('Your file has been restored')
else:
text.close()
sys.exit('Your file has been modified')
As you can see, I haven't added the timing part yet. It's pretty straight forward, just adding urls to a text file and then closing them. If the user wants the original file, reverse() is called.
Under Windows you can use msvcrt to ask for a key. Asking for a password is actually more complex, because you have to track several keys. This program stops with F1.
import time
import msvcrt
from threading import Thread
import threading
class worker(Thread):
def __init__(self,maxsec):
self._maxsec = maxsec
Thread.__init__(self)
self._stop = threading.Event()
def run(self):
i = 1
start = time.time()
while not self.stopped():
t = time.time()
dif = t-start
time.sleep(1) # you want to take this out later (implement progressbar)
# print something once in a while
if i%2==0: print '.',
#check key pressed
if msvcrt.kbhit():
if ord(msvcrt.getch()) == 59:
self.stop()
#do stuff
# timeout
if dif > self._maxsec:
break
i+=1
def stop(self):
print 'thread stopped'
self._stop.set()
def stopped(self):
return self._stop.isSet()
print 'number of seconds to run '
timeToRun = raw_input()
#input files
#not implemented
#run
w = worker(timeToRun)
w.run()
#reverse actions

Categories

Resources