[Tutor] Allocation of serial ports

2013-11-29 Thread Phil

Thank you for reading this.

This question is not specifically related to Python, however, someone 
may be able to point me in the right direction. The operating system in 
use is Linux.


I have a twin USB to serial adaptor that gives me ttyUSB0 and ttyUSB1 
and my programme uses both of those ports. The problem is the random 
allocation of the ports. Port A, for example, could be either ttyUSB0 or 
ttyUSB1.


So, how can I ensure that port A is always ttyUSB0 or how can I adapt my 
programme so that the address of the port is known to the programme?



--
Regards,
Phil
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Allocation of serial ports

2013-11-29 Thread Dominik George
Hi,

>So, how can I ensure that port A is always ttyUSB0

http://hintshop.ludvig.co.nz/show/persistent-names-usb-serial-devices/

-nik 
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python scope and variable binding

2013-11-29 Thread spir

On 11/29/2013 06:20 AM, eryksun wrote:

On Wed, Nov 27, 2013 at 10:04 AM, Arnaud Legout  wrote:
[...]


For what it's worth, a personal point of view on Python class defs. I ended up 
undertanding class definitions as code blocks the following way:


Imagine Python has kinds of free sections of code (like Lua or C, and many other 
languages), but using "section" as keyword like so, which permits to name such 
sections:


section Def_Write_i:
i = 1
print(i)

Def_Write_i is a block of code, like a func, or a branch of an 'if' statement, 
or a loop body. Unlike a func, it cannot be called, it is just executed on the 
way. I could serve to struture code (I actually would enjoy that).


Now, add to this that such as section's scope (namespace) is permanent like an 
object (like an object's __dict__), instead of transient like function scopes: 
and you get classes as code blocks and namespaces. [C's function-local static 
vars are somewhat similar: they remain; but unlike Python's class vars they are 
not accessible from outside the func.]


In Lua, definition of an "object-like" table is similar, but unlike for Python 
classes it cannot refer to itself or its own local vars, because at definition 
time the object (the table) does not yet exists as such:


t = {
i = 1,
j = i+1,-- error
k = t.i+1,  -- error as well
}

To reproduce the functionality of Python classes, it should be (but is not) that 
the above code is equivalent to:


t = {}
t.i = 1
t.j = t.i+1
t.k = t.i+1

Also, there cannot be any other statement there but assignments.

I used to use this weird feature of Python classes to make free, permanent, and 
even computable scopes. For instance, to define parsers: sets of named patterns, 
with higher-level ones building on lowel-level ones:


  class ArithParser(Parser):
  digit   = Range("0-9")
  natural = String(digit)
  natural.test("123") ### debug ###
  integer = Comp(Option('-'), natural)
 ...

In addition, one can have such free namespaces initialised and given other 
attributes:

  arith_parser = ArithParser()  # init & get instance attributes defined in 
Parser

Denis
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] pygame error

2013-11-29 Thread Steven D'Aprano
On Thu, Nov 28, 2013 at 12:43:17AM +0530, Vipul Sharma wrote:
> Hello ! I am a beginner in pygame, i was just trying a simple pygame
> program where I wanted to load an image (.png) from the same directory
> where my actual source code was.
> I wrote this line in my source code to load the image :
> 
> Img = pygame.image.load('cat.png')
> 
> But I got a traceback :
> 
> pygame.error: File is not a Windows BMP file
> 
> Can anyone pls tell what is the problem with the code, why this error
> arises ?

Is the error message not clear enough? The file is a PNG file, not a
Windows BMP file.

By default, pygame only supports BMP images. If you want to use a more
useful range of image types, like PNG, JPG, and so forth, you need to
build pygame with image support.

See here for more information:

http://www.pygame.org/docs/ref/image.html



-- 
Steven
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Allocation of serial ports

2013-11-29 Thread Phil

On 11/29/2013 06:17 PM, Dominik George wrote:

Hi,


So, how can I ensure that port A is always ttyUSB0


http://hintshop.ludvig.co.nz/show/persistent-names-usb-serial-devices/



Thank you Dominik, the link answers my question exactly.

--
Regards,
Phil
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] TypeError: range() integer end argument expected, got float.

2013-11-29 Thread spinefxr
Hi


Newbie at this.  I am getting this error:   
TypeError: range() integer end argument expected, got float.



Using python 7.3


here is my code



def PaymentTable(balance, annualInterestRate, payment):
month = 0
while month < 12:
balance = balance - payment
interest = balance * (annualInterestRate/12)
balance = balance + interest
month += 1

if balance <= 0:
return True

balance = 4773
annualInterestRate = .2
monthlyinterest = balance * (annualInterestRate/12)
lowerbound = round(balance / 12, 0)
upperbound = round((balance + (monthlyinterest * 12)) / 12, 0)


for payment in range(lowerbound, upperbound, 10):
if PaymentTable(balance, annualInterestRate, payment) == True:  Error 
occurs at this line
print 'Lowest Payment: ', payment
break



Richard Roth
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] empty delimiters, and None

2013-11-29 Thread ugajin
I run Inkscape (an Open Source vector drawing application) on OSX (Snow 
leopard)  installed via .dmg pkg. The application ships with a collection of 
Python extensions, one of which Measure Path, failed to execute. 

I could not find a reference for this issue in the Inkscape archives, and I 
tried and worked with other workarounds including a javascript (outside 
Inkscape) to find the length of Bézier paths, but eventually I raised the issue 
and contacted launchpad/inkscape (question #239599) but to limited avail. After 
much continued searching I then found this Bug #803791 report which describes 
(as an aside) the exact same issue together with a solution. 

I know next to nothing about Python and I shall be glad if any Python guru can 
make clear (in layman's terms where possible) what the problem is/was and how 
the fix works. 

I remembered an alternative posting that I had read, which reported that Python 
dislikes empty delimiters. So I took a slightly different approach to the one 
mentioned in the above bug report. Instead of removing line 35 from the Measure 
Path script I replaced the empty delimiters with the Python constant None. To 
my great delight as well as my own amazement the 'fix' worked. 

The problem may or may not be limited to OSX. 

On trying to run the script (before the fix) I had the following traceback 
message: 
File "measure.py", line 35, in 
locale.setlocale(locale.LC_ALL, '')
File 
"/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/locale.py",
 line 494, in setlocale
return _setlocale(category, locale)
locale.Error: unsupported locale setting

If I booted from the Unix file I received the following feedback:
Setting Language: .UTF-8
(process:82224): Gtk-WARNING **: Locale not supported by C library.
Using the 
fallback 'C' locale.

Line 35 (above) shows the empty delimiter. The fix that I applied was to 
replace line 35 in the Measure.py script with:
locale.setlocale(locale.LC_ALL, None). The Measure Path script then executes 
correctly. No other action is/was required.

I note also the Python 2 library entry for Built-in Constants as:
None
The sole value of types.NoneType. None is frequently used to represent the 
absence of a value, as when default arguments are not passed to a function.
Changed in version 2.4: Assignments to None are illegal and raise a SyntaxError.

And under standard type hierarchy as:
None
This type has a single value. There is a single object with this value. This 
object is accessed through the built-in name None. It is used to signify the 
absence of a value in many situations, e.g., it is returned from functions that 
don’t explicitly return anything. Its truth value is false.
I have run the various scripts in a Python Validator, and line 35 (both 
versions) pass unremarked, although there are a few other code errors and 
warnings and many pep8 warnings. 

I have also looked at locale.py Line 494 of which is the last line of a def 
(def function?) I include this below, hopefully this may save you searching for 
locale.py (Pyhon 2.6) should you need it and wish to answer the above 
questions, it may help.

def setlocale(category, locale=None):

""" Set the locale for the given category.  The locale can be
a string, a locale tuple (language code, encoding), or None.

Locale tuples are converted to strings the locale aliasing
engine.  Locale strings are passed directly to the C lib.

category may be given as one of the LC_* values.

"""
if locale and type(locale) is not type(""):
# convert to string
locale = normalize(_build_localename(locale))
return _setlocale(category, locale)


Many, many thanks for your interest and considering matters.

-A
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Pretty printing XML using LXML on Python3

2013-11-29 Thread SM
Thank you, eryksun. using tounicode seems to work on this small piece of
code. It still has issues with my code which is generating a big XML code.
I will figure out why.
-SM


On Thu, Nov 28, 2013 at 2:45 PM, eryksun  wrote:

> On Thu, Nov 28, 2013 at 2:12 PM, SM  wrote:
> > Run with Python3:
> >
> > $ python3 testx.py
> > b'\n  \n  some text\n\n'
>
> print() first gets the object as a string. tostring() returns bytes,
> and bytes.__str__ returns the same as bytes.__repr__. You can decode
> the bytes before printing, or instead use tounicode():
>
> >>> s = etree.tounicode(root, pretty_print=True)
> >>> print(s)
> 
>   
>   some text
> 
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] TypeError: range() integer end argument expected, got float.

2013-11-29 Thread Dominik George
Hi,

> Using python 7.3

I think we must update 'import antigravity' to say something about
python-driven flux capacitors :þ ...

> def PaymentTable(balance, annualInterestRate, payment):

You should not CamelCase function names.

> upperbound = round((balance + (monthlyinterest * 12)) / 12, 0)

Your error is because round() does not cast to int. It produces an
integer number in a strict mathematical sense, but not as a data type.

Use int() for that.

> for payment in range(lowerbound, upperbound, 10):
> if PaymentTable(balance, annualInterestRate, payment) == True:  Error 
> occurs at this line
> print 'Lowest Payment: ', payment
> break

A few notes about that.

1. You mentioned above that you use Python 7.3. As already said, I do
not know what that is, because right now there is Python 2.x and 3.x. I
assumed you meant 3.3, because that is widely used, but in that case,
your print statement would not work. print() is a function, please get
used to that.

2. Do not compare with True. Either the expression is True, or it is
False. No need to be redundantly explicit ;).

3. There might be a more pythonic way to find the lowest payment. List
comprehensions and min() come to mind; however, due to your naming
conventions I do not fully understand what the code is supposed to find.
Something called PaymentTable is supposed to return a table-like thing,
not a boolean. Maybe you should get a bit more into detail about that
(comment your code, for example ;)) and help us give you more hints on
it.

Cheers,
Nik

-- 
* mirabilos is handling my post-1990 smartphone *
 Aaah, it vibrates! Wherefore art thou, demonic device??

PGP-Fingerprint: 3C9D 54A4 7575 C026 FB17  FD26 B79A 3C16 A0C4 F296


signature.asc
Description: Digital signature
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] TypeError: range() integer end argument expected, got float.

2013-11-29 Thread Steven D'Aprano
On Fri, Nov 29, 2013 at 02:24:49PM -0500, spine...@aol.com wrote:
> Hi
> 
> 
> Newbie at this.  I am getting this error:   
> TypeError: range() integer end argument expected, got float.

Note carefully that the error here is with the range() function. In your 
code, you have:

> for payment in range(lowerbound, upperbound, 10):
> if PaymentTable(balance, annualInterestRate, payment) == True:  Error 
> occurs at this line

You are mistaken about where the error occurs. It occurs on the 
*previous* line, the one that says "for payment in range...".

You have three arguments for range. All three need to be integers (whole 
numbers, like 0, 1, 2, ...) not floats (numbers with decimal points like 
2.5, 5.25, or even 7.0). Even if the fraction part is "point zero", 
Python will insist it is a float.

You have two solutions here: the best one is to go back to where you 
define lowerbound and upperbound and make sure they are whole numbers 
with no decimal point.

The less-good solution is to change the line to this:

for payment in range(int(lowerbound), int(upperbound), 10):



-- 
Steven
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] empty delimiters, and None

2013-11-29 Thread eryksun
On Fri, Nov 29, 2013 at 8:19 AM,   wrote:
>
> On trying to run the script (before the fix) I had the following traceback
> message:
> File "measure.py", line 35, in 
> locale.setlocale(locale.LC_ALL, '')
> File
> "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/locale.py",
> line 494, in setlocale
> return _setlocale(category, locale)
> locale.Error: unsupported locale setting
>
> If I booted from the Unix file I received the following feedback:
> Setting Language: .UTF-8
> (process:82224): Gtk-WARNING **: Locale not supported by C library.
Using
> the fallback 'C' locale.

It looks like you have a misconfigured environment. ".UTF-8" is
missing the language, such as "en_GB.UTF-8".

locale.setlocale calls the C runtime setlocale. Passing an empty
string as the 2nd argument instructs setlocale to use the environment
variables LC_ALL, LC_COLLATE, LC_CTYPE, LC_MESSAGES, LC_MONETARY,
LC_NUMERIC, LC_TIME, and LANG. It uses the first one it finds. The
search order might vary depending on the implementation. Just check
them all: os.environ["LANG"], etc.

If you pass None (translated to NULL in the C call) as the 2nd
argument, then it only queries the current locale. This avoids the
immediate problem without really fixing it. The process will use the
default "C" locale.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] empty delimiters, and None

2013-11-29 Thread Steven D'Aprano
On Fri, Nov 29, 2013 at 08:19:37AM -0500, uga...@talktalk.net wrote:

[...]
> After much continued searching I then found this 
> Bug #803791 report which describes (as an aside) the exact same issue 
> together with a solution.

It might help if you provide a link to that bug report. Remember, you've 
read it, but we haven't.


> I know next to nothing about Python and I shall be glad if any Python 
> guru can make clear (in layman's terms where possible) what the 
> problem is/was and how the fix works.
> 
> I remembered an alternative posting that I had read, which reported 
> that Python dislikes empty delimiters. 

In general, that is certainly not true. Empty delimiters like [], '', {} 
and even () are legal and perfectly accepted in Python in many places. 
More context would be needed.


[...]
> On trying to run the script (before the fix) I had the following traceback 
> message: 
> File "measure.py", line 35, in 
> locale.setlocale(locale.LC_ALL, '')
> File 
> "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/locale.py",
>  line 494, in setlocale
> return _setlocale(category, locale)
> locale.Error: unsupported locale setting

Ah, now we're getting somewhere!

The locale settings control the internationalization of your operating 
system. For example, instead of everything being English all throughout 
the world, using locale, your computer can display buttons and menus in 
Greek when in Greece, in Japanese in Japan, and so on, provided the 
correct settings are available.

The locale.setlocale() function takes two arguments, the first 
locale.LC_ALL is okay, the problem is with the second one. Originally it 
was set to the empty string '' which tells Python to return the current 
locale. Python complains about that which means either:

- your system has no locale set at all;

- your system is set to use a locale which has been removed from 
  your computer.

To fix this, you can set an environment variable. I don't know how to do 
this in OS-X, but in Linux systems I would edit my .bashrc config file 
and add the line:

export LANG="blah blah blah"

where "blah blah blah" is the name of a locale. You can find out which 
locales are available by running the system command:

locale -a 

at the shell. If you need help doing this, you can try asking here, with 
luck somebody will know how to do this on a Mac.

For reference, here is the relevant part of the docs:

http://docs.python.org/2/library/locale.html#locale.setlocale


> If I booted from the Unix file I received the following feedback:
> Setting Language: .UTF-8
> (process:82224): Gtk-WARNING **: Locale not supported by C library.
Using the 
> fallback 'C' locale.

I have no idea what you mean by this, sorry. What does "booted from the 
Unix file" mean?


> Line 35 (above) shows the empty delimiter. The fix that I applied was 
> to replace line 35 in the Measure.py script with: 
> locale.setlocale(locale.LC_ALL, None). The Measure Path script then 
> executes correctly. No other action is/was required.

I'm glad that this fixes the problem for you, but I'd be wary about 
leaving None in place. Passing None rather than '' does subtly different 
things, and I'm not sure if the Measure Path script does what it is 
supposed to do with None in place.

Still, it appears to work, and I guess that provided there are no 
obvious problems with it, it seems harmless enough.

The best thing would be to report this problem, and the apparent fix, to 
the author of the Measure Path script, and see what he or she thinks 
about it.


> I note also the Python 2 library entry for Built-in Constants as:
> None
> The sole value of types.NoneType. 
[...]

Thanks for that, but we're very familiar with None, as Python 
programmers you can barely go five minutes without needing to use None 
or see None in a piece of code.


-- 
Steven
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] empty delimiters, and None

2013-11-29 Thread eryksun
On Fri, Nov 29, 2013 at 5:44 PM, Steven D'Aprano  wrote:
> Originally it was set to the empty string '' which tells Python to
> return the current locale.

Rather, an empty string instructs it to set the locale based on the
environment. The default value of None queries the category's locale.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] IndexError: list index out of range

2013-11-29 Thread richard kappler
I have a script that makes use of the Google speech recognition API as
follows:

import shlex

print " say something"
os.system('sox -r 16000 -t alsa default recording.flac silence 1 0.1 1% 1
1.5 1%')
cmd='wget -q -U "Mozilla/5.0" --post-file recording.flac
--header="Content-Type: audio/x-flac; rate=16000" -O - "
http://www.google.com/speech-api/v1/recognize?lang=en-us&client=chromium";'


args = shlex.split(cmd)
output,error = subprocess.Popen(args,stdout = subprocess.PIPE, stderr=
subprocess.PIPE).communicate()

if not error:
a = eval(output)

#a = eval(open("data.txt").read())
confidence= a['hypotheses'][0]['confidence']
speech=a['hypotheses'][0]['utterance']
 print "you said:   ", speech, "  with  ",confidence,"confidence"

When I run that script by itself, it works fine.

When I insert the script into a larger program, I get the following error:

ERROR:
Traceback (most recent call last):
  File "inga.py", line 146, in 
confidence= a['hypotheses'][0]['confidence']
IndexError: list index out of range

If I understand it correctly, the traceback is telling me that there is no
position [0] in my list, but I don't understand how that can be true. I'm
not using the variable "confidence" anywhere else in the program.

Here's the larger script/program into which the offending bits were
inserted, up to the point of the error:


#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
import aiml
import commands
import subprocess
import marshal
import datetime
import os
import os.path
from os.path import exists

###
 read sensors #
###

 environmental 

def environRead():
import serial
from time import sleep

sensors = dict.fromkeys('Sonar1 Sonar2 Sonar3 Sonar4 Dewpoint
Temperature Humidity Light'.split())

arduino = serial.Serial('/dev/ttyACM0', 9600)
sleep(1)
line = arduino.readline().strip()
line = line.lstrip('{').rstrip('}').strip()

envSense = {}
for item in line.split(','):
item = item.strip()
key, value = item.split(':')
key = key.strip()
value = value.strip()
envSense[key]=int(value)
return envSense

 end environmental ###

### somatic ##

def somaticRead():
import psutil as ps

cpu = ps.cpu_percent()
mem = ps.virtual_memory()
disk = ps.disk_usage('/')
# need code to strip % out of disk, leaving just hdd = and some number
# convert it all into a dictionary and return it

 end somatic ##

###
 end sensor read ##
###


###
## facerec 
###

from SimpleCV import Camera
import Image

# initialize camera
cam = Camera()

#snap a picture using the camera
img = cam.getImage()

# find the face
faces =
img.findHaarFeatures('/usr/local/share/OpenCV/haarcascades/haarcascade_frontalface_alt.xml')

if faces:
for face in faces:
face.draw()
# crop at box around detected face
cropped = face.crop()
# save to file for processing
im = cropped.copy()
im.save("temp.png")
#  process image - grayscale and size
im = Image.open("temp.png").convert("L")
im = im.resize((125, 150), Image.ANTIALIAS)
#delete the temp.png file
# filelist = [ f for f in os.listdir(".") if f.endswith(".png") ]
# for f in filelist:
#os.remove(f)
#save image for face recognizer
im.save("match.png")

subprocess.check_call(["python", "facerec", "match.png", "faceDbase", "18",
"3"])

filelist = [ f for f in os.listdir(".") if f.endswith(".png") ]
for f in filelist:
os.remove(f)

tmp = open("namefile.txt")
name = tmp.read()
#print("Hello " + name)
greet = ("Hello " + name)
print greet
festivalCmd = '(SayText "%s")' % greet
subprocess.Popen(['/usr/bin/festival', '-b', festivalCmd])
# need to add functions for not finding or not recognizing a face

# return from a function
#def get_face(arg):
#some_variable = 10 * arg
#return some_variable

#result = get_face(5)


## end facerec #



## sphinx speech rec will go here ##


##

Re: [Tutor] IndexError: list index out of range

2013-11-29 Thread Steven D'Aprano
On Fri, Nov 29, 2013 at 08:17:54PM -0500, richard kappler wrote:
> I have a script that makes use of the Google speech recognition API as
> follows:
[...]
> args = shlex.split(cmd)
> output,error = subprocess.Popen(args,stdout = subprocess.PIPE, stderr=
> subprocess.PIPE).communicate()
> 
> if not error:
> a = eval(output)

A trivial typo here: the line a = eval(output) needs to be indented.

More importantly though, this is quite risky. You're downloading data 
from the internet, then executing it as code. I really, really, really 
hope you trust the source of that data. By eval()ing their code, you 
give them complete and total control of your PC -- anything you can do, 
they can do.

It's not just *them* that you have to trust, but anyone in the world who 
manages to compromise their server or the communication channel between 
them and you.

How safe do you feel?


> ERROR:
> Traceback (most recent call last):
>   File "inga.py", line 146, in 
> confidence= a['hypotheses'][0]['confidence']
> IndexError: list index out of range
> 
> If I understand it correctly, the traceback is telling me that there is no
> position [0] in my list, but I don't understand how that can be true. I'm
> not using the variable "confidence" anywhere else in the program.

It's not "confidence" that has no position 0, but a['hypotheses'], 
whatever that is.

Start by printing a['hypotheses'] and seeing what it contains. My guess 
is that it probably contains an empty list, [].

Here's another reason for avoiding eval(). Presumably a['hypotheses'] is 
set by the code you download and then eval. That makes it completely 
opaque -- you can't easily see what it is doing, and if it plays up, you 
can't do anything about it. It's a complete black box that either works 
or doesn't work.

What can we do about this? Well, if using eval() really is the only way 
to do this, I'd say the risk is not worth it. That sort of gung-ho 
attitude to security suggests that it's only a matter of time before the 
source is hacked, and once they're hacked, anyone using it is vulnerable 
too.

[Aside: This sort of crap really makes me angry -- code injection 
vulnerabilities are one of the most common ways that viruses, spyware 
and other malware get into people's computers, and Google should know 
better than this. If Google actually recommend you use eval() to access 
their service, that just demonstrates that the Speech Recognition team 
don't give a monkey's toss for your security.]

In the meantime, you can start by printing the code before eval()'ing 
it. That way at least we can see what it's supposed to be getting. Go 
back to the lines:

if not error:
a = eval(output)

and change the block to:

print(output)
a = eval(output)  # WARNING WARNING DANGER DANGER
print(a)


and then we can see what the code was supposed to do and what it 
actually did. My guess is that it was working before, but you've 
exceeded some limit on the number of requests per day, or possibly the 
speech recognition can't make out any words so it just returns an empty 
list.


[soapbox] 
This is not aimed at you, you're a beginner and can be excused. But the 
Google techs have NO EXCUSE.  I am so effing sick of coders in the 21st 
century who have no effing clue about even the most common-sense basics 
of security. No wonder there are so many malware and viruses around. 
Using eval here is like posting the keys to your house to some arbitrary 
tradesperson you've never met with instructions "I'll be away all next 
week, come around whenever you like and do whatever jobs you think need 
doing." You damn well better trust them, AND the post office.



-- 
Steven
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] IndexError: list index out of range

2013-11-29 Thread Danny Yoo
>
>
> Here's another reason for avoiding eval(). Presumably a['hypotheses'] is
> set by the code you download and then eval. That makes it completely
> opaque -- you can't easily see what it is doing, and if it plays up, you
> can't do anything about it. It's a complete black box that either works
> or doesn't work.
>
>

The API is undocumented, as far as I can tell.  That being said, it appears
to be JSON-oriented.

http://mikepultz.com/2011/03/accessing-google-speech-api-chrome-11/

So the original questioner should use a JSON parser, rather than eval().
 For example:


http://www.athoughtabroad.com/2013/05/22/using-google-s-speech-recognition-web-service-with-python
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] IndexError: list index out of range

2013-11-29 Thread eryksun
On Fri, Nov 29, 2013 at 8:17 PM, richard kappler  wrote:
>
> args = shlex.split(cmd)
> output,error = subprocess.Popen(args,stdout = subprocess.PIPE, stderr=
> subprocess.PIPE).communicate()

Output to stderr doesn't necessarily mean a command failed. The
process returncode is what you need to inspect. Use
subprocess.check_output. It raises a subprocess.CalledProcessError for
a non-zero return code.

> if not error:
> a = eval(output)

Please post plain text to the list. Automatic conversion from rich to
plain text isn't Python friendly.

Don't use eval like this. Google isn't sending Python code in response
to a web query. They're sending JSON data:

import json

output = ('{"status":0,"id":"","hypotheses":'
  '[{"utterance":"Python","confidence":0.58060002}]}')

a = json.loads(output)

>>> a['hypotheses'][0]
{u'confidence': 0.58060002, u'utterance': u'Python'}

>>> a['hypotheses'][0]['utterance']
u'Python'

Remember to check the status code. I found a short list, but nothing official:

0 - correct
4 - missing audio file
5 - incorrect audio file

When the speech recognition fails to form a hypothesis, print "Ozzy,
is that you again?" ;)
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor