Python - How to check for usb keyboard? - python-2.7

Is there any way to have a check that a usb keyboard is attached?
I'm new to both programming and python so I apologize if this is a dumb question.
Here's what I would like to happen:
if(usb_keyboard_attached == true):
string1 = raw_input("Enter Text ")
maincode
I am using Python 2.7 and intend to run the script on a Raspberry Pi.

I'm not sure about detecting that it is a USB keyboard (or any type of keyboard for that matter), but it seems like you're just looking to make sure that this is interactive. If that's the case, you can use:
import sys
if sys.stdin.isatty():
string1 = raw_input("Enter text ")

Related

Receiving back string of lenght 0 from os.popen('cmd').read()

I am working with a command line tool called 'ideviceinfo' (see https://github.com/libimobiledevice) to help me to quickly get back serial, IMEI and battery health information from the iOS device I work with daily. It executes much quicker than Apple's own 'cfgutil' tools.
Up to know I have been able to develop a more complicated script than the one shown below in PyCharm (my main IDE) to assign specific values etc to individual variables and then to use something like to pyclip and pyautogui to help automatically paste these into the fields of the database app we work with. I have also been able to use the simplified version of the script both in Mac OS X terminal and in the python shell without any hiccups.
I am looking to use AppleScript to help make running the script as easy as possible.
When I try to use Applescript's "do shell script 'python script.py'" I just get back a string of lenght zero when I call 'ideviceinfo'. The exact same thing happens when I try to build an Automator app with a 'Run Shell Script' component for "python script.py".
I have tried my best to isolate the problem down. When other more basic commands such as 'date' are called within the script they return valid strings.
#!/usr/bin/python
import os
ideviceinfoOutput = os.popen('ideviceinfo').read()
print ideviceinfoOutput
print len (ideviceinfoOutput)
boringExample = os.popen('date').read()
print boringExample
print len (boringExample)
I am running Mac OS X 10.11 and am on Python 2.7
Thanks.
I think I've managed to fix it on my own. I just need to be far more explicit about where the 'ideviceinfo' binary (I hope that's the correct term) was stored on the computer.
Changed one line of code to
ideviceinfoOutput = os.popen('/usr/local/bin/ideviceinfo').read()
and all seems to be OK again.

dragonfly+dragon naturally speaking not working

I've got Dragon Naturally Speaking 14, dragonfly, the latest natlink (4.1 or something), pywin32, python 2.7, and wxpython installed
I've got a python file with this in it in my "user configuration directory" set up by natlink
I get the natlink popup message when Dragon Naturally Speaking starts, telling me that it's working. I reset DNS 14 to ensure my "macro" (dosomething.py) is loaded.
this is the code in my dosomething.py
from dragonfly import Grammar, CompoundRule
# Voice command rule combining spoken form and recognition processing.
class ExampleRule(CompoundRule):
spec = "do something computer" # Spoken form of command.
def _process_recognition(self, node, extras): # Callback when command is spoken.
print "Voice command spoken."
# Create a grammar which contains and loads the command rule.
grammar = Grammar("example grammar") # Create a grammar to contain the command rule.
grammar.add_rule(ExampleRule()) # Add the command rule to the grammar.
grammar.load() # Load the grammar.
while True:
pythoncom.PumpWaitingMessages()
sleep(.1)
however, when I start up & activate DNS and say "do something computer" with dictation & command mode, or just command mode, the transcription box pops up, how can I tell if it's working or not? I don't think it is. What is supposed to happen? I'm new to python, I fired up the interpreter in the cmd window and no prompt like "Voice command spoken." is ever generated when I say the voice command. Is that what's supposed to happen?
There are two ways to load up Dragonfly grammars: through Natlink, and through Windows Speech Recognition. WSR requires you to put in that while loop with pythoncom.PumpWaitingMessages(), but that won't work with Natlink. You should comment it out.
If you set this up correctly, you won't see "Voice command spoken." in any cmd prompt -- you will see it in the Natlink window.

Python speech recognition for Raspberry Pi 2

I am trying to find a Speech recognition library similar to PySpeech that will work on a Raspberry Pi 2. I am new to this and have tried researching but there are so many applications I just need help choosing the correct one.
All I am trying to do is, when a user says something the program will recognize keywords and open up the correct part of my code which will just display information about that keyword.
Right now I am using Python 2.7 and PyQt4 to display what I want but am willing to change if there is something easier such as KivyPi, PyGame, etc.
I am up for any ideas or any help to push me into the right direction.
Thank You!
I created a library called SpeakPython that helps Python developers do exactly this, and just released it under GPL3. The library is built upon pocketsphinx (sphinxbase) and gstreamer (for streaming recognition, which leads to fast results). It will allow you to attach python code to speech commands.
It's very accurate and dynamic for command parsing such as this, and I've tested it on the Pi already. Let me know if you have any issues.
To recognize few words on Raspberry Pi 2 with Python you can use Python bindings to Pocketsphinx
You can find pocketsphinx tutorial to get started here.
You can find some installation details for RPi here.
You can find code example here.
You can find already functioning example using pocketsphinx and python here.
Here is what I have up and running on my pi, it uses python speech recognition, pyaudio and pythons espeak for voice response (if you want that, if not just take it out) this will listen for voice input, print it to text and speak it back to you.. You can manipulate this to do whatever you want basically -
import pyaudio
from subprocess import call
import speech_recognition
r = sr.Recognizer()
r.energy_threshold=4000
with sr.Microphone(device_index = 2, sample_rate = 44100, chunk_size = 512) as source:
print 'listening..'
audio = r.listen(source)
print 'processing'
try:
message = (r.recognize_google(audio, language = 'en-us', show_all=False))
call(["espeak", message])
except:
call(['espeak', 'Could not understand you'])

How to read text from an application window using pywinauto

I have a python code which opens a SSH session using Putty and passes a command to reboot a remote machine using pywinauto.
I want to read the text from the putty terminal after typing the password and compare it
Is there a way I can do it?
Below is the piece of code for the same
app_Putty = application.Application()
app_Putty.start_("C:\Users\debajyoti.bose\Downloads\putty.exe")
app_Putty.top_window_().TypeKeys(IP)
app_Putty.top_window_().TypeKeys("{TAB}"+"22")
app_Putty.top_window_().RadioButton4.Click()
app_Putty.top_window_().OpenButton.Click()
time.sleep(10)
app_Putty.top_window_().NoButton.Click()
time.sleep(2)
app_Putty.top_window_().TypeKeys(user+"{ENTER}")
time.sleep(3)
app_Putty.top_window_().TypeKeys(password+"{ENTER}")
time.sleep(3)
app_Putty.top_window_().TypeKeys("/bin/reboot"+"{ENTER}")
time.sleep(5)
app_Putty.kill_()
time.sleep(120)
I am using pywinauto v0.4.0
Thanks in advance.
OK, let's try app_Putty.top_window_().WindowText(). If it fails your mission looks impossible.
You can't capture directly like this from what I can tell, but I had to find a workaround, and the one I found was this
#clear the buffer with alt space menu
app.window(title='PuTTY - Title').type_keys('% l',with_spaces=True)
#copy the buffer to clipboard
app.window(title='PuTTY - Title').type_keys('% o',with_spaces=True)
I was having to do this because the putty.log file was missing the selection indicator icon (asterisk) on the screen when it was logging output and I needed a way to know which item was selected to move up or down.

Python terminal application with interface like nano

This may be a stupid question but I'm not sure how to phrase it in a google-friendly way...
In a terminal if you type something like:
nano some_file
then nano opens up an edit window inside the terminal. A text based application. Ctrl+X closes it again and you see the terminal as it was.
Here's another example:
man ls
How can I make a text based terminal application in python?
I hope this question makes sense, let me know if you need more clarification...
You probably need to use alternative screen buffer. To enable it just print '\0033[?1049h' and for disabling '\0033[?1049l' (Terminal Control Escape Sequences).
http://invisible-island.net/xterm/ctlseqs/ctlseqs.html#The%20Alternate%20Screen%20Buffer
Example:
print('\033[?1049h', end='')
print('Alternative screen buffer')
s = input()
print('\033[?1049l', end='')
print('Normal mode')
print(s) `
This does the trick:
http://docs.python.org/2/howto/curses.html
Example:
import curses
oScreen = curses.initscr()
curses.noecho()
curses.curs_set(0)
oScreen.keypad(1)
oScreen.addstr("Woooooooooooooo\n\n",curses.A_BOLD)
while True:
oEvent = oScreen.getch()
if oEvent == ord("q"):
break
curses.endwin()