initialization problem in Python - python

The error is given at the end:
from brisa.core.reactors import install_default_reactor
reactor = install_default_reactor()
print reactor
from brisa.upnp.control_point.control_point import ControlPoint
def on_new_device(dev):
print 'Got new device:', dev.udn
print "Type 'list' to see the whole list"
if not dev:
return
def create_control_point():
c = ControlPoint()
print "hello"
c.subscribe('new_device_event', on_new_device)
print "c"
return c
def main():
print "Inside main"
c = create_control_point()
print "Inside create control point"
c.start()
reactor.add_after_stop_func(c.stop)
reactor.main()
def _search(c):
""" Start searching for devices of type upnp:rootdevice and repeat
search every 600 seconds (UPnP default)
"""
c.start_search(600, 'upnp:rootdevice')
def _stop(c):
""" Stop searching
"""
c.stop_search()
def _list_devices(c):
""" Lists the devices that are in network.
"""
k = 0
for d in c.get_devices().values():
print 'Device no.:', k
print 'UDN:', d.udn
print 'Name:', d.friendly_name
print 'Device type:', d.device_type
print 'Services:', d.services.keys() # Only print services name
print
k += 1
# Control the loop at _handle_cmds function
running_handle_cmds = True
commands = {
'search': _search,
'stop': _stop,
'list': _list_devices,
}
def _handle_cmds(c):
while running_handle_cmds:
try:
input = raw_input('>>> ').strip()
if len(input.split(" ")) > 0:
try:
if len(input.split(" ")) > 1:
commands[input.split(" ")[0]](c, input.split(" ")[1])
else:
commands[input.split(" ")[0]](c)
except KeyError, IndexError:
print 'Invalid command, try help'
except TypeError:
print 'Wrong usage, try help to see'
except KeyboardInterrupt, EOFError:
c.stop()
break
# Stops the main loop
reactor.main_quit()
if __name__ == '__main__':
print "hello"
main()
Error:
ankit#ubuntu:~/Desktop$ python controlpt.py
<brisa.core.reactors.glib2.GLib2Reactor object at 0x965bdcc>
hello
Inside main
After that I know understand, it is not initialising the control point. The Information about the libraries(Control point) is available at http://brisa.garage.maemo.org/apidoc/index.html

If this is anything like some other event-based libraries such as Twisted, you want to get the reactor's main running before you do much of anything else.
Drop the call to reactor.main in your main function. Then, instead of just calling main in your if at the bottom, do this:
if __name__ == "__main__":
run_async_function(main)
reactor.main()
See if things behave more like what you expect then.
(run_async_function is in the threaded_call module.)

Related

Thread SpeechRecognition and get return value while doing other stuff at the same time

My question is how to thread a function that needs time to execute , then return a value , whilst I can do other stuff at the same time.
I saw others similar questions and solutions but I don't get how to apply them here.
import speech_recognition as sr
r = sr.Recognizer()
import threading
from queue import Queue
queue = Queue()
def mySpeechRecognizer():
print("START SPEECH INPUT\n") #
with sr.Microphone() as source:
r.adjust_for_ambient_noise(source)
try:
audio = r.listen(source)#, timeout = 5) #####
userInput = r.recognize_google(audio)
if any(userInput) == True:
print("Text Input :", userInput) #
# do sth here
print("END SPEECH INPUT NORMAL") #
return userInput #
except Exception as e:
print("Exception In Function mySpeechRecognizer() :", e)
print("END SPEECH INPUT EXCEPTION") #
return #
recognize = threading.Thread(target = lambda q: q.put(mySpeechRecognizer()), args = (queue, ))
recognize.start()
print('do sth')
recognize.join()
print('do sth')
print(queue.get())
print('do sth')
My expectation is that it will print 3 times "do sth" while recognizing. Once it finishes , it will print the return value without blocking the print , i.e. getting queue.get() while print
How can I accomplish this , and what's wrong with my attempt ?
I think I have finally came up with a solution . . .
We can use queue.empty() to check whether the func has a return value or not ( True --> is empty i.e. no return val ; False --> not empty i.e. has return val ) so when queue.empty() remains True , I can do other stuff like print. With the while loop , it will be something like this :
...
while queue.empty(): # don't have return val
print("do sth") # do stuff
else: # --> have return val
print(queue.get()) # print the return val of the func
recognize.join() # join the thread
Correct me if I am wrong ?

Run a command inside a running python script

I think it's a very easy thing to do but im still searching for an answer.
I have a Python script running which looks like this:
Waiting for argument:_________
Is there an easy way how i can start the script and automatically put some arguments in it?
I really don't understand u but i think u want something like
import os, sys
#def some_other_functions
def cmd():
try:
com = raw_input('Waiting for argument:_________ ')
#Or u can pass values as sys.args
#like com = sys.argv[1]
while len(com) == 0:
com = raw_input('Waiting for argument:_________ ')
if len(com) != 0:
print os.system(com)
if str(com) == 'exit':
sys.exit()
print '\nContinuer executing other commands or write --exit to quite the program\n'
while True:
com = raw_input('Waiting for argument:_________ ')
if len(com) == 0:
print 'Entered nothing'
if str(com) == 'exit':
sys.exit()
else:
print os.system(com)
except Exception, e:
print str(e)
cmd()

specific thread exit in python

I am using a thread to create an interruptible, which sends the KeyboardInterrupt command when a specific key is pressed. After this process I again use the msvcrt.getch() function. the problem is that the thread won't exit until I have pressed the key once. Ie the countdown function finishes but the the thread is still waiting for the input for the msvcrt.getch() function.
I tried putting exit.thread() at the end of the countdown function, but that exited the main thread. Do I need to use threading instead of thread?
import time, thread, msvcrt
print "enter time for timer"
n=raw_input()
def input_thread():
z=msvcrt.getch()
if z == "a" :
thread.interrupt_main()
if z != "a" :
thread.start_new_thread(input_thread, ())
print "nope"
thread.exit()
def countdown(n):
try:
thread.start_new_thread(input_thread, ())
for i in range(int(n)):
c = int(n) - int(i)
print c ,'seconds left','\r',
time.sleep(1)
except KeyboardInterrupt:
print "I was rudly interrupted"
countdown(n)
print """
"""
k=msvcrt.getch()
if k == "k" :
print "you typed k"
else :
print "you did not type K"
It is not the most beautiful way, but it works.
from concurrent.futures import thread
import threading
import time, msvcrt
print("enter time for timer")
n=input()
def input_thread():
z=msvcrt.getch()
if z == "a" :
thread.interrupt_main()
if z != "a" :
thread.start_new_thread(input_thread, ())
print ("nope")
thread.exit()
def countdown(n):
try:
threading.Thread(target=input_thread)
for i in range(int(n)):
c = int(n) - int(i)
print (c ,'seconds left','\r')
time.sleep(1)
except KeyboardInterrupt:
print("I was rudly interrupted")
countdown(n)
print ("")
k=msvcrt.getch()
if k == "k" :
print("you typed k")
else :
print ("you did not type K")

Program not executing full, stops in the middle

from brisa.core.reactors import install_default_reactor
reactor = install_default_reactor()
print reactor
from brisa.core.threaded_call import run_async_function
from brisa.upnp.control_point.control_point import ControlPoint
from datetime import datetime
service = ('u', 'urn:schemas-upnp-org:service:SwitchPower:1')
binary_light_type = 'urn:schemas-upnp-org:device:BinaryLight:1'
def on_new_device(dev):
print 'Got new device:', dev.udn
print "Type 'list' to see the whole list"
if not dev:
return
def get_switch_service(device):
return device.services[service[1]]
def create_control_point():
c = ControlPoint()
print "hello"
c.subscribe('new_device_event', on_new_device)
print "c"
return c
def main():
""" Main loop iteration receiving input commands.
"""
print "hell"
c = create_control_point()
print "helllo"
c.start()
run_async_function(_handle_cmds, (c, ))
reactor.add_after_stop_func(c.stop)
reactor.main()
def _exit(c):
""" Stops the _handle_cmds loop
"""
global running_handle_cmds
running_handle_cmds = False
def _search(c):
""" Start searching for devices of type upnp:rootdevice and repeat
search every 600 seconds (UPnP default)
"""
c.start_search(600, 'upnp:rootdevice')
def _get_status(c):
""" Gets the binary light status and print if it's on or off.
"""
try:
service = get_switch_service(c.current_server)
status_response = service.GetStatus()
if status_response['ResultStatus'] == '1':
print 'Binary light status is on'
else:
print 'Binary light status is off'
except Exception, e:
if not hasattr(c, 'current_server') or not c.current_server:
print 'BinaryLight device not set.Please use set_light <n>'
else:
print 'Error in get_status():', e
def _get_target(c):
""" Gets the binary light target and print if it's on or off.
"""
try:
service = get_switch_service(c.current_server)
status_response = service.GetTarget()
if status_response['RetTargetValue'] == '1':
print 'Binary light target is on'
else:
print 'Binary light target is off'
except Exception, e:
if not hasattr(c, 'current_server') or not c.current_server:
print 'BinaryLight device not set.Please use set_light <n>'
else:
print 'Error in get_target():', e
def _stop(c):
""" Stop searching
"""
c.stop_search()
def _list_devices(c):
""" Lists the devices that are in network.
"""
k = 0
for d in c.get_devices().values():
print 'Device no.:', k
print 'UDN:', d.udn
print 'Name:', d.friendly_name
print 'Device type:', d.device_type
print 'Services:', d.services.keys() # Only print services name
print
k += 1
if __name__ == '__main__':
print "hello"
main()
I am getting the output:
ankit#ubuntu:~/Desktop$ python controlpt.py
<brisa.core.reactors.glib2.GLib2Reactor object at 0x88c3e0c>
hello
hell
It is not going to the line c = create_control_point. why is that? please guide me in removing this error.
I am not familiar with this 'brisa' library. I would gather that, for some reason, the ControlPoint constructor is exiting the entire program using sys.exit() (or is calling some equivalent C code).
Run the program on the command-line, like this:
$ python
>>> import controlpt
>>> controlpt.main()
Then you should be able to see if it is actually quitting the whole process. If it dumps you back to the >>> prompt, then I don't know what's going on. But if it quits Python entirely, it means that that ControlPoint constructor is quitting.

Python quits after a constructor is called

My code seems to be failing after the constructor is called.
Here is my code - it is failing on the c = create_control_point() line in main():
from brisa.core.reactors import install_default_reactor
reactor = install_default_reactor()
print reactor
from brisa.core.threaded_call import run_async_function
from brisa.upnp.control_point.control_point import ControlPoint
from datetime import datetime
service = ('u', 'urn:schemas-upnp-org:service:SwitchPower:1')
binary_light_type = 'urn:schemas-upnp-org:device:BinaryLight:1'
def on_new_device(dev):
print 'Got new device:', dev.udn
print "Type 'list' to see the whole list"
if not dev:
return
def get_switch_service(device):
return device.services[service[1]]
def create_control_point():
c = ControlPoint()
print "hello"
c.subscribe('new_device_event', on_new_device)
print "c"
return c
def main():
""" Main loop iteration receiving input commands.
"""
print "hell"
c = create_control_point()
print "helllo"
c.start()
run_async_function(_handle_cmds, (c, ))
reactor.add_after_stop_func(c.stop)
reactor.main()
def _exit(c):
""" Stops the _handle_cmds loop
"""
global running_handle_cmds
running_handle_cmds = False
def _search(c):
""" Start searching for devices of type upnp:rootdevice and repeat
search every 600 seconds (UPnP default)
"""
c.start_search(600, 'upnp:rootdevice')
def _get_status(c):
""" Gets the binary light status and print if it's on or off.
"""
try:
service = get_switch_service(c.current_server)
status_response = service.GetStatus()
if status_response['ResultStatus'] == '1':
print 'Binary light status is on'
else:
print 'Binary light status is off'
except Exception, e:
if not hasattr(c, 'current_server') or not c.current_server:
print 'BinaryLight device not set.Please use set_light <n>'
else:
print 'Error in get_status():', e
def _get_target(c):
""" Gets the binary light target and print if it's on or off.
"""
try:
service = get_switch_service(c.current_server)
status_response = service.GetTarget()
if status_response['RetTargetValue'] == '1':
print 'Binary light target is on'
else:
print 'Binary light target is off'
except Exception, e:
if not hasattr(c, 'current_server') or not c.current_server:
print 'BinaryLight device not set.Please use set_light <n>'
else:
print 'Error in get_target():', e
def _stop(c):
""" Stop searching
"""
c.stop_search()
def _list_devices(c):
""" Lists the devices that are in network.
"""
k = 0
for d in c.get_devices().values():
print 'Device no.:', k
print 'UDN:', d.udn
print 'Name:', d.friendly_name
print 'Device type:', d.device_type
print 'Services:', d.services.keys() # Only print services name
print
k += 1
if __name__ == '__main__':
print "hello"
main()
I am getting the output:
ankit#ubuntu:~/Desktop$ python controlpt.py
<brisa.core.reactors.glib2.GLib2Reactor object at 0x88c3e0c>
hello
hell
Why isn't it getting to the c = create_control_point() line? Also, the controlpoint constructor is quitting the whole program.
When I tried
$ python
>>> import controlpt
>>> controlpt.main()
I got the output:
>>> controlpt.main()
hell
ankit#ubuntu:~/Desktop$
Help?
Since it's dying on the ControlPoint initialization, have you tried the following in the interpreter?
from brisa.upnp.control_point.control_point import ControlPoint
c = ControlPoint()
If that works, then there's something else at play.

Categories