trouble with pyplot in os x

2012-08-03 Thread Eric
I'm just starting to futz around with matplotlib and I tried to run this
example from the matplotlib doc page (it's the imshow() example):

import numpy as np
import matplotlib.cm as cm
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt

delta = 0.025
x = y = np.arange(-3.0, 3.0, delta)
X, Y = np.meshgrid(x, y)
Z1 = mlab.bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0)
Z2 = mlab.bivariate_normal(X, Y, 1.5, 0.5, 1, 1)
Z = Z2-Z1  # difference of Gaussians

im = plt.imshow(Z, interpolation='bilinear', cmap=cm.gray,
origin='lower', extent=[-3,3,-3,3])

plt.show()



I get the following error: 

Exception in Tkinter callback
Traceback (most recent call last):
  File 
"/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk/Tkinter.py",
 line 1410, in __call__
return self.func(*args)
  File 
"/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/backends/backend_tkagg.py",
 line 248, in resize
self.show()
  File 
"/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/backends/backend_tkagg.py",
 line 252, in draw
tkagg.blit(self._tkphoto, self.renderer._renderer, colormode=2)
  File 
"/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/backends/tkagg.py",
 line 19, in blit
tk.call("PyAggImagePhoto", photoimage, id(aggimage), colormode, 
id(bbox_array))
TclError



I'm using Python 2.7.3 on OS X 10.6.8 and I'm invoking python by doing
"arch -i386 python" because matplotlib doesn't do 64-bit.  Has anyone
else seen this?  Does anyone know why this is happening?  It looks
like a problem with tkinter but beyond that I haven't a clue.  And,
finally, any ideas as to how to make it behave?

TIA,
eric
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: trouble with pyplot in os x

2012-08-04 Thread Eric
On Saturday, August 4, 2012 8:11:44 AM UTC-5, William R. Wing (Bill Wing) wrote:
> On Aug 3, 2012, at 11:12 PM, Eric  wrote:
> 
> 
> 
> > I'm just starting to futz around with matplotlib and I tried to run this
> 
> > example from the matplotlib doc page (it's the imshow() example):
> 
> > 
> 
> > import numpy as np
> 
> > import matplotlib.cm as cm
> 
> > import matplotlib.mlab as mlab
> 
> > import matplotlib.pyplot as plt
> 
> > 
> 
> > delta = 0.025
> 
> > x = y = np.arange(-3.0, 3.0, delta)
> 
> > X, Y = np.meshgrid(x, y)
> 
> > Z1 = mlab.bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0)
> 
> > Z2 = mlab.bivariate_normal(X, Y, 1.5, 0.5, 1, 1)
> 
> > Z = Z2-Z1  # difference of Gaussians
> 
> > 
> 
> > im = plt.imshow(Z, interpolation='bilinear', cmap=cm.gray,
> 
> >origin='lower', extent=[-3,3,-3,3])
> 
> > 
> 
> > plt.show()
> 
> > 
> 
> > 
> 
> 
> 
> OK
> 
> 
> 
> > 
> 
> > I get the following error: 
> 
> > 
> 
> > Exception in Tkinter callback
> 
> > Traceback (most recent call last):
> 
> >  File 
> > "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk/Tkinter.py",
> >  line 1410, in __call__
> 
> >return self.func(*args)
> 
> >  File 
> > "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/backends/backend_tkagg.py",
> >  line 248, in resize
> 
> >self.show()
> 
> >  File 
> > "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/backends/backend_tkagg.py",
> >  line 252, in draw
> 
> >tkagg.blit(self._tkphoto, self.renderer._renderer, colormode=2)
> 
> >  File 
> > "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/backends/tkagg.py",
> >  line 19, in blit
> 
> >tk.call("PyAggImagePhoto", photoimage, id(aggimage), colormode, 
> > id(bbox_array))
> 
> > TclError
> 
> > 
> 
> > 
> 
> 
> 
> This looks as though you are running the latest python from python.org, not 
> the pre-installed python from Apple (that's good).
> 
> 
> 
> > 
> 
> > I'm using Python 2.7.3 on OS X 10.6.8 and I'm invoking python by doing
> 
> > "arch -i386 python" because matplotlib doesn't do 64-bit.  Has anyone
> 
> > else seen this?  Does anyone know why this is happening?  It looks
> 
> > like a problem with tkinter but beyond that I haven't a clue.  And,
> 
> > finally, any ideas as to how to make it behave?
> 
> > 
> 
> 
> 
> I DON'T know how tk is getting mixed into this, it shouldn't be.  But I think 
> I can tell you how to get matplotlib working...
> 
> 
> 
> Matplotlib DOES do 64-bit, the problem is numpy, which as you download in 
> binary form does not.  But, if you copy the bash script here:
> 
> 
> 
>   
> https://raw.github.com/fonnesbeck/ScipySuperpack/master/install_superpack.sh
> 
> 
> 
> it will download the sources and build a 64-bit numpy, which will then give 
> you a default 64-bit full package of python, numpy, and matplotlib.
> 
> 
> 
> That's what I've done, and my system runs the demo you listed in your post 
> with no problems.
> 
> 
> 
> > TIA,
> 
> > eric
> 
> > -- 
> 
> > http://mail.python.org/mailman/listinfo/python-list
> 
> 
> 
> Good luck,
> 
> -Bill

Yes, I got the Python 2.7 (and 3.2) distributions from python.org and I also 
got Tcl/Tk per their directions.  I still have all the old Apple installed 
stuff too plus some older Tcl/Tk.

Doesn't matplotlib use Tk (Tkinter) to do its graphs and what-not?  I also have 
at least two different versions of Tcl/Tk (8.5.7 and 8.5.12) and I'm wondering 
if that may not be causing problems.

I'll give that bash script a try.

Thanks,
eric


-- 
http://mail.python.org/mailman/listinfo/python-list


Validating string for FDQN

2011-06-06 Thread Eric
Hello,

Is there a library or regex that can determine if a string is a fqdn
(fully qualified domain name)? I'm writing a script that needs to add
a defined domain to the end of a hostname if it isn't already a fqdn
and doesn't contain the defined domain.

Thanks.
-- 
http://mail.python.org/mailman/listinfo/python-list


A beginning programmer

2011-07-10 Thread Eric
Greetings everyone;

Fresh High School graduate here with a passion for problem solving. My
last 2 years of HS I took programming courses (actually fairly good
ones; yay for good tech departments) that showed me

QuickBasic
VisualBasic
C++
Java

(in that order)

A friend of mine often talked about how nice Python was and being an
xkcd fan, i saw Python come up alot in the jokes. Python's awesome; I
see limitless possibilities in a very easy to understand and use
language that as xkcd put it "Programmings fun again!"

My problem is this though... I don't know what to do with this new
found knowledge of these languages. I'm a linux user so availability
of development tools is haaardly a problem. But I just don't know
what to do with it, I don't have any problems that need to be solved
and unfortunately I'm not familar enough with the languages (except
maybe c++) to help out the big projects like KDE / Gnome.

I realize this is the python mailing list and that I brought up some
non-python languages but I'm sure my situation is hardly new for those
looking to get into programming but having no idea of where to begin.

Any feedback is much appreciated!

-Eric-
-- 
http://mail.python.org/mailman/listinfo/python-list


retrieving https pages

2005-07-18 Thread Eric
I'm using Linux - Manriva LE2005, python 2.3 (or i can also use python 2.4
on my other system just as well).
Anyways...
I want to get a web page containing my stock grants.
The initial page is an https and there is a form on it to
fill in your username and password and then click "login"
I played with python's urlopen and basically it complains "your browser
doesnt support frames" meaning the urlopen call makes it unhappy somehow.
Is it reasonable to think i can build a script to login to this secure
website, move to a different page (on that site) and download it to disk?
Or am i just looking at a ling complicated task.
I'd really like to get the page because then i can analyze it from a cron
job and email myself my current options value each week or each month. 
Thanks
Eric

-- 
http://mail.python.org/mailman/listinfo/python-list


Newbie Program

2005-08-04 Thread Eric
I am reading a book on Python and ran across and exercise that I just
can't seem to figure out.  Its pretty simple, but I just can't get
past a certain point.

The task is to create a program that flips a coin 100 times and keeps
track of the total of heads and tails which is printed to the screen.

My plan was to use import random with a range of 2 and use a
conditional statement to count to 100. The problem I am encountering
is how do I keep track of the totals for heads and tails?

Any suggestions would be appreciated. Keep in mind I am very new to
Python so there may be a more sophisticated way, but I am just trying
to use what the book has taught so far.

Thanks,
Eric
-- 
http://mail.python.org/mailman/listinfo/python-list


Ftplib.FTP_TLS Ports

2014-12-09 Thread Eric
We are trying to open our firewall but it keeps failing.  The docs state
that the default port is 21 and we've opened port 21.  I've ran tcpdump on
the box while running the script.  I see a destination port of 21, but
there seems to be random destination ports such as 2320 which follow.  If
we open the firewall to allow all traffic, the script works.  Here is a
snip of what I have for the ftp portion.  Any ideas would be helpful.

import ftplib

session = ftplib.FTP_TLS('xxx.ftp.com','user','password')
file = open('Bkup.tar.gz','rb')
session.storbinary('STOR Bkup.tar.gz', file)
file.close()
session.quit()

Thanks!
Eric
-- 
https://mail.python.org/mailman/listinfo/python-list


Built-in Python3 web server functionality - wsgiref & http.server

2015-06-07 Thread Eric
I am trying to better understand the built-in python3 web server functionality 
and have just started reading the documentation.

There seem to be two options provided by Python 3.

1. 
wsgiref
https://docs.python.org/3/library/wsgiref.html

2.
http.server
https://docs.python.org/3/library/http.server.html


Both options appear to offer a simple way to get a simple web server up and 
running. It does appear that wsgiref is built on top of http.server. Is this 
correct? 

Would it be correct to say that wsgiref is a high(er?)-level framework for 
designing web-based applications where as http.server is operating at a lower 
level? While one could do everything with just http.server, if wsgiref was 
appropriate for a particular use case, it would be the path to follow.

Any insights into this topic would be appreciated.

Are there any good python 3 books covering this functionality?




-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Why Python is not both an interpreter and a compiler?

2015-09-01 Thread eric



On Tue, Sep 1, 2015 at 12:20 PM, Marko Rauhamaa  
wrote:

Steven D'Aprano :

 I believe that Marko is wrong. It is not so easy to compile Python 
to
 machine language for real machines. That's why the compiler targets 
a

 virtual machine instead.


Somehow Guile manages it even though Scheme is at least as dynamic a
language as Python.


I'm wondering if any of the VM lessons learned with forth environments 
would help?


https://en.wikipedia.org/wiki/Threaded_code




-- 
https://mail.python.org/mailman/listinfo/python-list


Python horks on WinXP path names

2011-12-08 Thread Eric
I'm running Python 2.7 on WinXP (ActiveState community version) and
when I try to do this:

if __name__ == '__main__':
root = Tkinter.Tk()
root.withdraw()
fileNames = tkFileDialog.askopenfilenames()
root.destroy()
print fileNames
# windows filename gets
for fileName in fileNames:
print fileName
file = open(fileName, 'r')
for line in file.readlines():
print line.strip()


I get this:

C:\Documents and Settings\eric\Desktop\PythonShop>python picker.py
{C:/Documents and Settings/eric/Desktop/PythonShop/cereal.py}
{
Traceback (most recent call last):
  File "picker.py", line 31, in 
file = open(fileName, 'r')
IOError: [Errno 2] No such file or directory: u'{'

That is, fileName is in a form that open() doesn't recognize.  On a
BSD box the code works fine.  What's going on with the file name and
how do I fix it?


TIA,
eric
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python horks on WinXP path names

2011-12-08 Thread Eric
On Dec 8, 2:43 pm, Ian Kelly  wrote:
> On Thu, Dec 8, 2011 at 1:16 PM, Eric  wrote:
> > I'm running Python 2.7 on WinXP (ActiveState community version) and
> > when I try to do this:
>
> > if __name__ == '__main__':
> >    root = Tkinter.Tk()
> >    root.withdraw()
> >    fileNames = tkFileDialog.askopenfilenames()
> >    root.destroy()
> >    print fileNames
> > # windows filename gets
> > for fileName in fileNames:
> >    print fileName
> >    file = open(fileName, 'r')
> >    for line in file.readlines():
> >            print line.strip()
>
> > I get this:
>
> > C:\Documents and Settings\eric\Desktop\PythonShop>python picker.py
> > {C:/Documents and Settings/eric/Desktop/PythonShop/cereal.py}
> > {
> > Traceback (most recent call last):
> >  File "picker.py", line 31, in 
> >    file = open(fileName, 'r')
> > IOError: [Errno 2] No such file or directory: u'{'
>
> > That is, fileName is in a form that open() doesn't recognize.  On a
> > BSD box the code works fine.  What's going on with the file name and
> > how do I fix it?
>
> http://bugs.python.org/issue5712


Thanks!

eric
-- 
http://mail.python.org/mailman/listinfo/python-list


curses (or something) for windows

2011-12-12 Thread Eric
Is there something similar to curses available for the Windows version
of Python (2.7, community edition)?  Preferably something built-in.
In general, I'm looking to do gui-ish things from within the command
window.

Also, in particular, is there a way to get the console size (rows,
cols).  I've seen how to do it in unix land but not for windows.

TIA,
eric
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: curses (or something) for windows

2011-12-12 Thread Eric
On Dec 12, 5:47 pm, alex23  wrote:
> On Dec 13, 7:15 am, Eric  wrote:
>
> > Is there something similar to curses available for the Windows version
> > of Python (2.7, community edition)?  Preferably something built-in.
> > In general, I'm looking to do gui-ish things from within the command
> > window.
>
> > Also, in particular, is there a way to get the console size (rows,
> > cols).  I've seen how to do it in unix land but not for windows.
>
> > TIA,
> > eric
>
> Check outhttp://www.lfd.uci.edu/~gohlke/pythonlibs/
>
> It's a fantastic resource, Win32 & 64 versions of a lot of packages.

Wowee that's a lot of stuff.  Thanks for the tip.

eric
-- 
http://mail.python.org/mailman/listinfo/python-list


file data => array(s)

2011-12-14 Thread Eric
I'm trying to read some file data into a set of arrays.  The file data
is just four columns of numbers, like so:

   1.22.2   3.3  0.5
   0.1   0.21.0  10.1
   ... and so on

I'd like to read this into four arrays, one array for each column.
Alternatively, I guess something like this is okay too:

   [[1.2, 2.2, 3.3, 0.5], [0.1, 0.2, 1.0, 10.1], ... and so on]

I came up with the following for the four array option:

   file = open(fileName, 'r')
   for line in file.readlines():
  d1, e1, d2, e2 = map(float, line.split())
  data1.append(d1)  # where data1, err1, data2, err2 are init-ed
as empty lists
  err1.append(e1)
  data2.append(d2)
  err2.append(e2)
   file.close()

But somehow it doesn't seem very python-esque (I'm thinking there's a
more elegant and succinct way to do it in python).  I've also tried
replacing the above "map" line with:

  d = d + map(float, line.split())  # where d is initialized as d
= []

But all I get is one long flat list, not what I want.

So is the map and append method the best I can do or is there a
slicker way?

One more thing, no numpy.  Nothing against numpy but I'm curious to
see what can be done with just the box stock python install.

TIA,
eric
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: file data => array(s)

2011-12-14 Thread Eric
On Dec 14, 4:59 pm, Dave Angel  wrote:

> Note that your code won't work (and mine probably won't either) if one
> of the lines has 3 or 5 items.  Or if one of the numbers isn't legal
> format for a float.  So you need to think about error checking, or
> decide whether a partial result is important.
>
> --
>
> DaveA


Haven't tried your suggestion yet, I just wanted to comment on this
last part real quick.  I have the same concern, my plan is to wrap all
that stuff up in a "try:" construct.  In such cases the program only
has to kick out a simple, sensible (for non-programmers) error message
and quit.

BTW, I didn't say it originally, but this is for 2.7 and hopefully
it'll be easy to carry over to 3.2.

Thanks,
eric
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: file data => array(s)

2011-12-15 Thread Eric
On Dec 14, 5:27 pm, Steven D'Aprano  wrote:
> On Wed, 14 Dec 2011 14:20:40 -0800, Eric wrote:
> > I'm trying to read some file data into a set of arrays.  The file data
> > is just four columns of numbers, like so:
>
> >    1.2    2.2   3.3  0.5
> >    0.1   0.2    1.0  10.1
> >    ... and so on
>
> > I'd like to read this into four arrays, one array for each column.
> > Alternatively, I guess something like this is okay too:
>
> >    [[1.2, 2.2, 3.3, 0.5], [0.1, 0.2, 1.0, 10.1], ... and so on]
>
> First thing: due to the fundamental nature of binary floating point
> numbers, if you convert text like "0.1" to a float, you don't get 0.1,
> you get 0.10001. That is because 0.1000...01 is the closest
> possible combination of fractions of 1/2, 1/4, 1/8, ... that adds up to
> 1/10.
>
> If this fact disturbs you, you can import the decimal module and use
> decimal.Decimal instead; otherwise forget I said anything and continue
> using float. I will assume you're happy with floats.
>

Yeah, I don't think it'll be a problem.  As I understand it a float in
python is a double in C and all our old C programs used doubles.  From
PDP-11 to MIPS3k to P2 I've seen what I think may have been rounding
or precision errors but I haven't heard any complaints because of
them.

Thanks,
eric
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: file data => array(s)

2011-12-15 Thread Eric
On Dec 14, 4:59 pm, Dave Angel  wrote:
> On 12/14/2011 05:20 PM, Eric wrote:
>
>
>
>
>
>
>
> > I'm trying to read some file data into a set of arrays.  The file data
> > is just four columns of numbers, like so:
>
> >     1.2    2.2   3.3  0.5
> >     0.1   0.2    1.0  10.1
> >     ... and so on
>
> > I'd like to read this into four arrays, one array for each column.
> > Alternatively, I guess something like this is okay too:
>
> >     [[1.2, 2.2, 3.3, 0.5], [0.1, 0.2, 1.0, 10.1], ... and so on]
>
> > I came up with the following for the four array option:
>
> >     file = open(fileName, 'r')
> >     for line in file.readlines():
>
> The readlines() call is a waste of time/space.  file is already an
> iterator that'll return lines for you.
>
>
>
>
>
>
>
> >        d1, e1, d2, e2 = map(float, line.split())
> >        data1.append(d1)  # where data1, err1, data2, err2 are init-ed
> > as empty lists
> >        err1.append(e1)
> >        data2.append(d2)
> >        err2.append(e2)
> >     file.close()
>
> > But somehow it doesn't seem very python-esque (I'm thinking there's a
> > more elegant and succinct way to do it in python).  I've also tried
> > replacing the above "map" line with:
>
> >        d = d + map(float, line.split())  # where d is initialized as d
> > = []
>
> > But all I get is one long flat list, not what I want.
>
> > So is the map and append method the best I can do or is there a
> > slicker way?
>
> > One more thing, no numpy.  Nothing against numpy but I'm curious to
> > see what can be done with just the box stock python install.
>
> > TIA,
> > eric
>
> When I see a problem like this, I turn to zip().  It's got some powerful
> uses when rows and columns need inverting.
>
> I didn't try it on an actual file, but the following works:
> linedata =    [[1.2, 2.2, 3.3, 0.5], [0.1, 0.2, 1.0, 10.1] ]
>
> data, err1, data2, err2 = zip(*linedata)
>
> print data
> print err1
> print data2
> print err2
>
> So you could try (untested)
>
> file = open(filename, "r")
> linedata = [ map(float, line) for line in file]
> data, err1, data2, err2 = zip(*linedata)
> file.close()
>
> DaveA

Neat.  This is what I had in mind for a python-esque solution.  Only
thing is "map(float,line)" should be "map(float,line.split()).  Looks
like it should be easy enough to weed out any funky data sets because
between map() and zip() it's fairly picky about the amount and type of
data.

Finally, the input files I'll be using for real aren't just four
columns of data.  The beginning of the file may have comments
(optional) and will have two lines of text to identify the data.
Maybe I can still do it w/o readlines.

Thanks,
eric

-- 
http://mail.python.org/mailman/listinfo/python-list


what does 'a=b=c=[]' do

2011-12-21 Thread Eric
Is it true that if I want to create an array or arbitrary size such
as:
   for a in range(n):
  x.append()

I must do this instead?
   x=[]
   for a in range(n):
  x.append()

Now to my actual question.  I need to do the above for multiple arrays
(all the same, arbitrary size).  So I do this:
   x=y=z=[]
   for a in range(n):
  x.append()
  y.append()
  z.append()

Except it seems that I didn't create three different arrays, I created
one array that goes by three different names (i.e. x[], y[] and z[]
all reference the same pile of numbers, no idea which pile).

This surprises me, can someone tell me why it shouldn't?  I figure if
I want to create and initialize three scalars the just do "a=b=c=7",
for example, so why not extend it to arrays.  Also, is there a more
pythonic way to do "x=[], y=[], z=[]"?

It's a slick language but I still have trouble wrapping my brain
around some of the concepts.

TIA,
eric
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: what does 'a=b=c=[]' do

2011-12-22 Thread Eric
On Dec 21, 6:50 pm, alex23  wrote:
> On Dec 22, 8:25 am, Eric  wrote:
>
> > This surprises me, can someone tell me why it shouldn't?  I figure if
> > I want to create and initialize three scalars the just do "a=b=c=7",
> > for example, so why not extend it to arrays.
>
> The thing to remember is that everything is an object, and that it's
> better to think of variables as labels on an object.
>
> So: a=b=c=7 means that _one_ integer object with the value of 7 can be
> referenced using any of the labels a, b or c. x=y=z=[] means that
> _one_ empty list can be referenced using x, y or z.
>
> The difference is that the value of a number object _cannot be
> changed_ ('immutable') while a list can be modified to add or remove
> items ('mutable'). a=10 just reassigns the label a to an integer
> object of value 10. x.append("foo") _modifies_ the list referred to by
> x, which is the same list known as y & z.
>


> > Also, is there a more pythonic way to do "x=[], y=[], z=[]"?
>
> I'd say that _is_ the most pythonic way, it's very obvious in its
> intent (or would be with appropriate names). If it bothers you that
> much:
>

Thanks for the explanation.  I guess from what I've seen of Python
so far I was expecting something more, I don't know, compact.
Anyway, it doesn't bother me, at least not enough to go and do
something like this:

>     def listgen(count, default=[]):
>         for _ in xrange(count):
>             yield default[:]
>
>     x, y, z = listgen(3)

Thanks,
eric


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: what does 'a=b=c=[]' do

2011-12-22 Thread Eric
On Dec 21, 5:44 pm, Steven D'Aprano  wrote:

> Yes, you should create your lists before trying to append to them.
>
> But you aren't forced to use a for-loop. You can use a list comprehension:
>
> x = [some_function(a) for a in range(n)]
>
> Notice that here you don't need x to pre-exist, because the list comp
> creates a brand new list, which then gets assigned directly to x.
>
> > Now to my actual question.  I need to do the above for multiple arrays
> > (all the same, arbitrary size).  So I do this:
> >    x=y=z=[]
>
> This creates one empty list object, and gives it three names, x, y and z.
> Every time you append to the list, all three names see the same change,
> because they refer to a single list.
>
> [...]
>
> > Except it seems that I didn't create three different arrays, I created
> > one array that goes by three different names (i.e. x[], y[] and z[] all
> > reference the same pile of numbers, no idea which pile).
>
> Exactly.
>
> > This surprises me, can someone tell me why it shouldn't?
>
> Because that's the way Python works. Python is an object-oriented, name
> binding language. This is how OO name binding works: you have a single
> object, with three names bound to it. The above line is short-cut for:
>
> a = []
> b = a
> c = a
>
> Python does not make a copy of the list unless you specifically instruct
> it to.
>
> > I figure if I
> > want to create and initialize three scalars the just do "a=b=c=7",
>
> That creates a single integer object with value 7, and binds three names
> to it, *exactly* the same as the above.
>
> If you could modify int objects in place, like you can modify lists in
> place, you would see precisely the same effect. But ints are immutable:
> all operations on ints create new ints. Lists are mutable, and can be
> changed in place.
>
> > for
> > example, so why not extend it to arrays.  Also, is there a more pythonic
> > way to do "x=[], y=[], z=[]"?
>
> Well that literally won't work, you can't separate them by commas.
> Newlines or semicolons will work.
>
> Or: x, y, z = [], [], []
>
> Either is pretty Pythonic.
>
> --
> Steven

Thanks to you and Dennis for the quick lesson and tips.  Very helpful
and illuminating.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ANNOUNCE; Try python beta

2005-12-21 Thread Eric
On 20 December 2005, Mike Meyer wrote:
> Ok, I've given it the interface I want, and made it less of an
> attractive nuisance.
>
> http://www.mired.org/home/mwm/try_python/ is now ready for people to
> play with. There's no tutorial information on it yet, that's the next
> thing to do. However, I won't be able to work on it for a while, so if
> you want to make suggestions about what that should look like, all
> such suggestions will be given proper consideration.

I'm not sure about everyone else, but I find the big warnings about
CSS and JavaScript almost as annoying as the fact that it doesn't do
anything.  At all, even with JavaScript enabled.  Then again, my main
browser is elinks, so my opinion is somewhat biased.  

If you get it working in Lynx, supporting other browsers should be
easier than the other posts make this solution sound.

- Eric
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Failing unittest Test cases

2006-01-09 Thread Eric
On  9 January 2006, Scott David Daniels wrote:
> There has been a bit of discussion about a way of providing test cases
> in a test suite that _should_ work but don't.  One of the rules has been
> the test suite should be runnable and silent at every checkin.  Recently
> there was a checkin of a test that _should_ work but doesn't.  The
> discussion got around to means of indicating such tests (because the
> effort of creating a test should be captured) without disturbing the
> development flow.
>
> The following code demonstrates a decorator that might be used to
> aid this process.  Any comments, additions, deletions?

Interesting idea.  I have been prepending 'f' to my test functions that
don't yet work, so they simply don't run at all.  Then when I have time
to add new functionality, I grep for 'ftest' in the test suite.

- Eric
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Suppressing banner on interactive startup?

2006-08-05 Thread Eric
On 27 July 2006, Tim Chase wrote:
> A couple of hopefully short (interrelated) questions:
>
> 1) is there a way to suppress the banner when starting Python 
> interactively?  [...]
>
> 2) is there a way to change the two prompts from ">>>" and "..." 
> to other options?  [...]

I noticed that the first part of your query was never answered.
To combine both of these, try the following (modified to taste):

python -ic 'import sys; sys.ps1="$ "; sys.ps2="> "'

- Eric
-- 
http://mail.python.org/mailman/listinfo/python-list


pyPgSQL / trac issues

2006-09-04 Thread Eric
Hey guys,

Has anyone seen this error when installing trac?  The problem seems
related to pyPgSQL, which is installed.  (Although I had to go in and
add some headers to make it work)

Templates directory [/usr/local/share/trac/templates]>

Creating and Initializing Project
Failed to create environment.
/usr/local/lib/python2.4/site-packages/pyPgSQL/libpq/libpqmodule.so:
undefined symbol: lo_export
Traceback (most recent call last):
  File "/usr/local/lib/python2.4/site-packages/trac/scripts/admin.py",
line 139, in env_create
self.__env = Environment(self.envname, create=True, db_str=db_str)
  File "/usr/local/lib/python2.4/site-packages/trac/env.py", line 79,
in __init__
self.create(db_str)
  File "/usr/local/lib/python2.4/site-packages/trac/env.py", line 197,
in create
db.init_db(self.path, db_str)
  File "/usr/local/lib/python2.4/site-packages/trac/db.py", line 442,
in init_db
cls.init_db(**args)
  File "/usr/local/lib/python2.4/site-packages/trac/db.py", line 408,
in init_db
self = cls(**args)
  File "/usr/local/lib/python2.4/site-packages/trac/db.py", line 376,
in __init__
from pyPgSQL import PgSQL
  File "/usr/local/lib/python2.4/site-packages/pyPgSQL/PgSQL.py", line
449, in ?
from libpq import *
  File
"/usr/local/lib/python2.4/site-packages/pyPgSQL/libpq/__init__.py",
line 23, in ?
from libpq import *
ImportError:
/usr/local/lib/python2.4/site-packages/pyPgSQL/libpq/libpqmodule.so:
undefined symbol: lo_export
Failed to initialize environment. 1
Traceback (most recent call last):
  File "/usr/local/lib/python2.4/site-packages/trac/scripts/admin.py",
line 594, in do_initenv
self.env_create(db_str)
  File "/usr/local/lib/python2.4/site-packages/trac/scripts/admin.py",
line 144, in env_create
sys.exit(1)
SystemExit: 1

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: newbe's re question

2006-09-20 Thread Eric
[EMAIL PROTECTED] wrote:
> All I am after realy is to change this
>
>  reline = re.line.split('instr', '/d$')
>
> into something that grabs any line with instr in it take all the
> numbers and then grab any comment that may or may not be at the end of
> the line starting with ; until the end of the line including white
> spaces.
>
> [code]
> def extractCsdInstrument (input_File_Name, output_File_Name,
> instr_number):
> "takes an .csd input file and grabs instr_number instrument and
> creates output_File_Name"
> f = open (input_File_Name , 'r')
> f2 = open (output_File_Name, 'w')
> instr_yes = 'false' # Python has built-in booleans
># Also, use sane naming: isInstr or hasInstr
>
> for line in f:
>   if "instr" in line:
>if instr_yes == 'true': # Use the bool -- `if hasInstr:`
>break
>
>reline = re.line.split('instr', '/d$') # ???
>number = int(reline[1])
> if number == instr_number:  # Doesn't need to be 2 lines
> instr_yes = "true": # the `:` is a syntax 
> error
>   if instr_yes = "true":
>f2.write(f.line) # odd way of doing it...
>
> f.close()
> f2.close()
>
> [/code]

Did you read the HOWTO on regular expressions yet? It's included with
the standard documentation, but here's a link:

http://www.amk.ca/python/howto/regex/

Now, onto the issues:
1) The escape character is \, not /. Use "\d" to match a number.

2) I'm not sure I understand what you're trying to extract with your
regex. As it is, the expression will return a list containing one item,
a string identical to the line being matched up to, but not including,
the first number. The rest of the line will be discarded. Try Kiki, a
tool for testing regular expressions, before burying the expression in
your code.

3) Python has built-in booleans: True and False, no quotes. Use them so
that you don't get flamed on forums.

4) I don't claim to be a Python guru, but here's a massaged version of
the function you gave:

[code]

def extractCsdInstrument (inputPath, outputPath, instrId):
""" Takes a .csd file, grabs info for instrument ID and writes to
file. """
src = open(inputPath, 'r')
dst = open(outputPath, 'w')
for line in src:
if "instr" in line:
info_comment = line.split(";", 1) # [info, comment]
# Extract integers
instrInfo = re.split(r"[^0-9]*", info_comment[0])
# Check the second number in the line
if instrInfo[1] == str(instrId):
dst.write(instrInfo.append(info_comment[1]))
src.close()
dst.close()

[/code]

I didn't check if this actually works, since I don't know what a .csd
file looks like. There are of course other, better ways to do it, but
hopefully this leads you in the right direction.

5) Please, read the documentation that came with your Python
installation. Reading up on string methods etc. ahead of time will save
you much more time than trying to slug through it. Also consider using
a text editor with syntax highlighting; that will help catch most
obvious syntax errors during coding.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Input from keyboard

2006-09-22 Thread Eric
utab wrote:
> hi,
> I could not understand why python stdin and stdout are not explained in
> any of the tutorials on the net,
>
> I want to read some input continuously from keyboard and then I would
> like to process these input.
>
> I have a code like this but getting errors, I would like to terminate
> when there is an empty string in the input, why is not this easy as the
> "cin" or "scanf". I had to search for even this easy operation. Is
> there a way to send EOF signal to terminate input(ctrl+??)
>
> #!/usr/bin/env python
> import sys, math   # load system and math module
> x=[]
> y=[]
> IN=True
> print 'input x and y values :   '
> while IN:
> xt,yt=input()
>
> if (xt==' ' or yt==' '):
> print 'you have not entered x or y, quiting'
> break
> else:
> xt= float(xt);yt=float(yt)
> x.append(xt);y.append(yt)
>
> for i in range(x):
> print x[i]


Summary:

std::cout << "Statement\n";
is
print "Statement"

std::cin << value;
is
value = raw_input()


std::cout << "Prompt:"
std::cin << value;
is
value = raw_input("Prompt:")


It's a little assymetrical, but useful. Lower-level functions also
exist in the sys module as stdin, stdout and stderr.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Input from keyboard

2006-09-22 Thread Eric
> std::cin << value;


Oops, that should be >>.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Replacing line in a text file

2006-09-22 Thread Eric

Tim Chase wrote:
> > That is, until such time as Guido finalizes PyESP.
> >
> > import PyESP
> > e = ESP.mindread(CSUIDL, "r")
>
> Sounds like an extension to the __future__ module.
>
>  >>> from __future__ import answers
>  >>> answers.answer(op.question)
>
> How many other languages have a time-machine built-in, that will
> take the programmer into the future?
>
> No apache mod_precognition.
> Perl offers no "use Eventual::Solution".
> C/C++ offers no "#include ".
> Same goes for Java's lack of "import java.ball.crystal"
>
> Yet another reason to be a python programmer. :)
>
> -tkc

Oh, that time machine of his...

The only thing I know of that compares is Vim 7.0's :later command.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Replacing line in a text file

2006-09-22 Thread Eric

CSUIDL PROGRAMMEr wrote:
> Folks
> I am trying to read a file
> This file has a line containing string  'disable = yes'
>
> I want to change this line to 'disable = no'
>
> The concern here is that , i plan to take into account the white spaces
> also.
>
> I tried copying all file int list and then tried to manipulate that
> list
>
> But the search is not working
>
> Any answer
>
> thanks

Is this a configuration file? Depending on what exactly is in the file,
you may want to either import it directly or parse it -- especially if
"disable = yes" appears more than once in the file.

Could you post an example of the file for us?

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Fatal error after RE-installing Python 2.3.4

2006-09-22 Thread Eric

Cappy2112 wrote:
> I've just started a job which has a massive python2.3.4-centric tools
> installation and configuration.
>
> I know what you're going to say, but I can't upgrade and be the only
> one with a newer version. There are close to 30 engineers using this
> same tools configuration, and it has been working fine for a long time.
> For now, we all have to live with the limitations and or bugs in 2.3.4.
>
> I'm running Windows XP, SP2, on a AMD 1.79Ghz MP 2200+.
>
> After editing/testing one of the python test scripts, I was about to
> check a small script change into cvs, when my mentor suggested running
> pychecker. When I did this, I saw a several pages full of warnings.
>
> For me not knowing the code base well enough to know what to expect, He
> thought this was odd, took the file, ran pychecker on his system, with
> the file I've edited, and only sees 4-5 warnings.
>
> We have the same version of Python, that being 2.3.4, the same version
> of pychecker which is 0.8.14.
>
> I had deleted and re-installed pychecker, and still saw the same
> warnings.
> I have compared this to another machine, and again, I am the odd man
> out.
>
> I've deleted all the Python packages, pythonwin, and The core 2.3.4
> distribution, and re-installed everything from scratch.
>
> Now, When I launch Python from a cmd console, the following is reported
>
> C:\Windows\system32\cmd.exe- python
> The NTVDM CPU has encountered an illegal instruction.
> Chose close to terminate the application.
>
>
> Oddly enough, when I run Python.exe from the Program Files menu, it
> launches just fine.
>
>
> The virus scanner doesn't find any known viruses, and I've also
> disabled the virus checker after un-installing-reinstalling Python the
> last time.
> I've also tried downloading another copy of the installer.
>
> Does anyone have any ideas what is causing this and how to fix it? My
> job depends on me getting Python2.3.4 back to working order.
>
>
>
> thanks

What happens when you run "C:\Python2.3\python.exe" from the command
line (or the equivalent path)? How about pythonw.exe (or the windowed
equivalent, not sure about the naming)? Are .py and .pyw files
displayed with the correct icons? When installing Python packages, is
Python 2.3 detected as the default installation?

Since there was a lot of uninstalling and reinstalling, I'm suspicious
that the Windows registry was messed up somewhere along the line. If
you're suave with regedit, you could try poking around in there.

Finally, does your $PATH include the Python directory? That could also
cause problems if it doesn't.

And, what sorts of warnings did PyChecker display? Missing
files/modules?

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: which "GUI module" you suggest me to use?

2007-06-05 Thread Eric
On Jun 5, 4:17 pm, ZioMiP <[EMAIL PROTECTED]> wrote:
> Cameron Laird ha scritto:
>
>
>
> > In article <[EMAIL PROTECTED]>,
> > ZioMiP  <[EMAIL PROTECTED]> wrote:
> >> Hi to all...
>
> >> I'm actually using Tkinter for my GUI... but I need to "put a piece of a
> >> web-page in a widget" how can I do?
>
> >> which GUI module do you suggest me to use for do that?
>
> >> or which GUI module do you suggest me to use at all?
>
> >> I'm acutally using Windows Xp but I also use Linux...
>
> >> I know that WxPython work only under Windows and PyGTK work only under
> >> Linux... there's some other modules?
>
> > ?  wxPython is available for Linux and Mac OS X.  PyGTK is
> > available for Windows.
>
> > Apparently you want to embed Web content in a Tkinter widget.
> > There are several ways to do this.  Do you need a live browser,
> > or is it enough to render HTML?
>
> I think is like a "live browser"... not only render HTML because the
> webpage got a bit of javascript inside...

Is this webpage untouchable, or is HTML rendering just a shortcut to
avoid redesigning part of the app? If you need faithful rendering of
an arbitrary webpage along with a Javascript runtime, that's a bigger
issue, and you might want to look at some of the Mozilla tools,
particularly XULRunner:

http://developer.mozilla.org/en/docs/Building_XULRunner_with_Python

Otherwise, wxPython's HTML widget or TkHtml should be fine -- your
code will probably be easier to maintain and debug if you translate
that bit of Javascript to Python (language constructs are similar,
especially with xml.dom.minidom).

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Want to learn Python

2007-06-15 Thread Eric
On Jun 15, 7:41 am, Amol <[EMAIL PROTECTED]> wrote:
> Hi, I want to learn Python in less than a month which resources should
> I use. I prefer to read books . Please give me a list of *recognized*
> resources. Thank You all

I started here: http://docs.python.org/tut/tut.html

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: newbie question: parsing street name from address

2007-06-21 Thread Eric
On Jun 21, 9:47 am, cjl <[EMAIL PROTECTED]> wrote:
> P:
>
> I am working on a project that requires geocoding, and have written a
> very simple geocoder that uses the Google service.
>
> I would like to be able to extract the name of the street from the
> addresses in my data, however they vary significantly. Here a some
> examples:
>
> 25 Main St
> 2500 14th St
> 12 Bennet Pkwy
> Pearl St
> Bennet Rd and Main st
> 19th St
>
> As you can see, sometimes I have the house number, and sometimes I do
> not. Sometimes the street name is a number. Sometimes I simply have
> the names of intersecting streets.
>
> I would like to be able to parse the above into the following:
>
> Main St
> 14th St
> Bennet Pkwy
> Pearl St
> Bennet Rd
> Main St
> 19th St
>
> How might I approach this complex parsing problem?
>
> -CJL

You might be able to use consistencies in your data to make this
simpler.  If the examples you have there are representative, it looks
like what you should do is look for a word like 'St' or 'Rd' and then
return that word and the previous word.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: newbie question: parsing street name from address

2007-06-22 Thread Eric
On Jun 21, 6:03 pm, John Machin <[EMAIL PROTECTED]> wrote:
> On Jun 22, 4:43 am, Eric <[EMAIL PROTECTED]> wrote:
>
>
>
> > On Jun 21, 9:47 am, cjl <[EMAIL PROTECTED]> wrote:
>
> > > P:
>
> > > I am working on a project that requires geocoding, and have written a
> > > very simple geocoder that uses the Google service.
>
> > > I would like to be able to extract the name of the street from the
> > > addresses in my data, however they vary significantly. Here a some
> > > examples:
>
> > > 25 Main St
> > > 2500 14th St
> > > 12 Bennet Pkwy
> > > Pearl St
> > > Bennet Rd and Main st
> > > 19th St
>
> > > As you can see, sometimes I have the house number, and sometimes I do
> > > not. Sometimes the street name is a number. Sometimes I simply have
> > > the names of intersecting streets.
>
> > > I would like to be able to parse the above into the following:
>
> > > Main St
> > > 14th St
> > > Bennet Pkwy
> > > Pearl St
> > > Bennet Rd
> > > Main St
> > > 19th St
>
> > > How might I approach this complex parsing problem?
>
> > > -CJL
>
> > You might be able to use consistencies in your data to make this
> > simpler.  If the examples you have there are representative, it looks
> > like what you should do is look for a word like 'St' or 'Rd' and then
> > return that word and the previous word.
>
> The OP's data already contains
> [corner|cnr [of]] Foo Rd and|& Bar St
> and real world data will contain things like
> 1234 John F Kennedy Memorial Drive
> 456 Broadway
>
> As Paul wrote, "Parsing street addresses is a very complex parsing
> problem", even when you restrict yourself to one mostly-English-
> speaking country. Software written under such restrictions rapidly
> breaks down elsewhere (Rue de la Paix, Wilhelmstrasse, Avenida 9 de
> Julio, etc) and blows up altogether when street names aren't used in
> postal addresses (e.g. Japan).

No doubt that address parsing is, in general, a very difficult
problem.  However, it may not be necessary for him to solve the
general problem.  If his dataset is more limited in formats then his
problem is much simpler.

-- 
http://mail.python.org/mailman/listinfo/python-list


Newbie question - better way to do this?

2007-05-27 Thread Eric
I have some working code, but I realized it is just the way I would
write it in C, which means there is probably a better (more pythonic)
way of doing it.

Here's the section of code:

accumulate = firstIsCaps = False
accumStart = i = 0
while i < len(words):
firstIsCaps = firstIsCapitalized(words[i])
if firstIsCaps and not accumulate:
accumStart, accumulate = i, True
elif accumulate and not firstIsCaps:
doSomething(words[accumStart : i])
accumulate = False
i += 1

words is a big long array of strings.  What I want to do is find
consecutive sequences of words that have the first letter capitalized,
and then call doSomething on them.  (And you can ignore the fact that
it won't find a sequence at the very end of words, that is fine for my
purposes).

Thanks,
Eric

-- 
http://mail.python.org/mailman/listinfo/python-list


with ctypes, how to parse a multi-string

2007-05-30 Thread Eric

Hi,

I am currently dealing with ctypes, interfacing with winscard libbrary
(for smart card access).

Several APIs (e.g. SCardListReaderGroupsW ) take a pointer to an
unicode string as a parameter , which points at function return to a
"sequence" of unicode strings, NULL terminated. The last string is
double NULL terminated. (of course buffer length is also returned as
another parameter).

e.g. it could return something like
'group1\x00group2\x00group3\x00\x00'

What should I use as argtypes to my function prototype in order to
gain access to the full list? using c_wchar_p works, but it resolves
the string until it reaches the first \x00, resulting in having access
to the first entry of the list only.

as reference, my current ctypes mapping for this API is:

# extern WINSCARDAPI LONG WINAPI
# SCardListReaderGroupsW(
# IN  SCARDCONTEXT hContext,
# OUT LPWSTR mszGroups,
# IN OUT  LPDWORD pcchGroups);

_ListReaderGroups = scardlib.SCardListReaderGroupsW
_ListReaderGroups.argtypes = [ c_ulong, c_void_p, c_void_p ]
_ListReaderGroups.restype  = c_ulong

Calling the API looks like:

pcchreadergrp = c_long(SCARD_AUTOALLOCATE)
groups   = c_wchar_p()

_ListReaderGroups( ctx, byref(groups), byref(pcchreadergrp))


Should I be using some array/ctypes.cast() combination to gain access
to all returned characters?

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: with ctypes, how to parse a multi-string

2007-05-31 Thread Eric
On May 31, 2:52 pm, Thomas Heller <[EMAIL PROTECTED]> wrote:
> Eric schrieb:
>
>
>
> > Hi,
>
> > I am currently dealing with ctypes, interfacing with winscard libbrary
> > (for smart card access).
>
> > Several APIs (e.g. SCardListReaderGroupsW ) take a pointer to an
> > unicode string as a parameter , which points at function return to a
> > "sequence" of unicode strings, NULL terminated. The last string is
> > double NULL terminated. (of course buffer length is also returned as
> > another parameter).
>
> > e.g. it could return something like
> > 'group1\x00group2\x00group3\x00\x00'
>
> > What should I use as argtypes to my function prototype in order to
> > gain access to the full list? using c_wchar_p works, but it resolves
> > the string until it reaches the first \x00, resulting in having access
> > to the first entry of the list only.
>
> A c_wchar_p instance represent a (one!) zero-terminated string, as you
> already know.  A POINTER(c_wchar) instance is more flexible, you should
> use that instead.  It can be indexed/sliced with arbitrary indexes.
>
> Here is a simple script to get you started:
>
> """
> from ctypes import *
>
> # Normally, the function call will fill the buffer:
> buf = create_unicode_buffer("first\0second\0third\0")
>
> # The pointer you will pass to the function call
> ptr = cast(buf, POINTER(c_wchar))
>
> # function call omitted
>
> # Print the raw result
> print ptr[:len(buf)]
>
> # Print a list of strings
> print ptr[:len(buf)].split("\0")
> """
>
> Thomas

Thanks Thomas, it works as expected!

Regards,

Eric

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Free Air Conditioners!!!!!!

2007-08-22 Thread Eric
And $15 shipping to get the "free" paper sent to you!  ;^)


"Zentrader" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED]
> On Aug 21, 10:13 pm, "Scott M." <[EMAIL PROTECTED]> wrote:
>> Oh my God!  How did you know?!!  You were so smart to post that here!
>>
>> <[EMAIL PROTECTED]> wrote in message
>>
>> news:[EMAIL PROTECTED]
>>
>> >http://freeairconditioners.blogspot.com/
>
> It's probably a handheld fan made out of a piece of paper
> 


-- 
http://mail.python.org/mailman/listinfo/python-list


Getting started with python

2007-04-14 Thread Eric
Hello, after reading some of the book Programming Python it seems that
python is something I would like to delve deeper into. The only thing
is, I have no idea what I should try and write. So I was hoping that
someone here could help point me to a group/project that would be a
good starting place for a person with limited python knowledge, but
that is willing to learn whatever is necessary. I'm hoping that with a
goal I can start to learn python instead of just playing around with
it. Thanks.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Replace

2006-05-06 Thread Eric
On 2006-05-06, Tim Williams wrote:
> On 06/05/06, Eric <[EMAIL PROTECTED]> wrote:
>> I have a string...
>>
>> str = "tyrtrbd =ffgtyuf == =tyryr =u=p ff"
>>
>> I want to replace the characters after each '=', what I ended up doing is
>> somthing like this...
>>
>> buf = list(str)
>> newchr = '#'
>>
>> count = 0
>> for i in range(len(buf)):
>>   if buf[count] == '=':
>> buf[count + 1] = newchr
>> count = count + 1
>>   else:
>> count = count + 1
>>
>> newstr = ''.join(buf)
>>
>> Is there a better, faster way of doing it? Using somthing like
>> str.index() dosn't work because...
>>
>
> After you find an '=' you are updating the next chr in the list to '#'
>  then testing the '#' to see if it is an '=' .
>
> This would be quicker as it bypasses testing your self-added '#' , and
> also removes a " count +1"
>
> #Untested
> buf = list(str)
> newchr = '#'
> count = 0
> for i in range(len(buf)):
>   if buf[count] == '=':
>count = count + 1
>buf[count] = newchr
> count = count + 1
>
>
> I might have done something like this (using s instead of str)
>
> #untested
>>>> buf = list(s)
>>>> newstr = ''
>>>> while buf:
> ...   newstr +=  buf.pop(0)  # get the first item in buf and append it to 
> newstr
> ...   if new[-1]  == '=':
> ...   newstr += '#'
> ...   buf.pop(0)  # discard the next item in buf
>
>
> HTH :)

Thanks, I should have included more info about what I was trying to do, just
trying to keep my post short. I was messing around trying to write a simple 
script to decode yenc encoded usenet posts. Yenc uses the '=' before special
chars like '\n', '\r', those chars need to handled differently. Iterating over
each char in a file dosn't sound like the best idea.

import sys
import string

crap = sys.stdin

d42 = string.join([chr((x - 42) % 256) for x in range(256)], '')
d64 = string.join([chr((x - 64) % 256) for x in range(256)], '')

def proccess(crapstring):
  buffer = list(crapstring)

  count = 0
  for count in range(len(buffer)):
if buffer[count] != '=':
  buffer[count] = buffer[count].translate(d42)
  count = count + 1
else:
  buffer[count + 1] = buffer[count + 1].translate(d64)
  buffer[count] = ''
  count = count + 1

  newstring = ''.join(buffer)
  return newstring

while 1:
  line = crap.readline()
  if not line:
break
  if line[:7] != '=ybegin':
continue
  header = line.split()
  """Do somthing with header sometime"""
  break

linebuf = []
while 1:
  line = crap.readline()
  if line[:5] != '=yend':
if line[-2:] == "\r\n":
  line = line[:-2]
pline = proccess(line)
linebuf.append(pline)
  else:
break

deccrap = ''.join(linebuf)
sys.stdout.write(deccrap)


This script isn't working for some reason. I'll figure that out someday.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Replace

2006-05-06 Thread Eric
On 2006-05-06, Dennis Lee Bieber wrote:
> On Sat, 06 May 2006 19:55:35 GMT, Dennis Lee Bieber
><[EMAIL PROTECTED]> declaimed the following in comp.lang.python:
>
>
>> splits = encData.split("#", 1)
>
>   Whoops # => =
>
>   Since there are only what, five, escaped characters, the use of a
> translate table seems somewhat overkill... A simple dictionary can be
> used...
>
> #   pseudo-yENC decoder
> #   ignores all of the protocol except for the
> #   data portion decode
>
> d42 = "".join([chr((x - 42) % 256) for x in range(256)])
> d64 = { "@" : "\0",
> "I" : "\t",
> "J" : "\n",
> "M" : "\r",
> "}" : "="   }
> e42 = "".join([chr((x + 42) % 256) for x in range(256)])
> e64 = { "\0" : "=@",
> "\t" : "=I",
> "\n" : "=J",
> "\r" : "=M",
> "=" : "=}"  }
>
> def decode(encData):
> segments = []
> while True:
> splits = encData.split("=", 1)
> segments.append(splits[0])
> if len(splits) == 1:break
> segments.append(d64[splits[1][0]])
> encData = splits[1][1:]
>
> decData = "".join(segments).translate(d42)
> return decData
>
> def encode(decData):
> segments = []
> encData = decData.translate(e42)
> while encData:
> pos = len(encData)
>
> nl = encData.find("\0")
> tb = encData.find("\t")
> lf = encData.find("\n")
> cr = encData.find("\r")
> eq = encData.find("=")
>
> if nl != -1:
> pos = min(pos, nl)
> if tb != -1:
> pos = min(pos, tb)
> if lf != -1:
> pos = min(pos, lf)
> if cr != -1:
> pos = min(pos, cr)
> if eq != -1:
> pos = min(pos, eq)
>
> segments.append(encData[:pos])
>
> if pos < len(encData):
> segments.append(e64[encData[pos]])
> encData = encData[pos+1:]
>
> return "".join(segments)
>
>
> if __name__ == "__main__":
> junk = """This is not
> the end of the silliness
> being inflicted upon the world of 183743ljf8734jflu807ur32"""
>
> morejunk = encode(junk)
> print morejunk
> 
> print decode(morejunk)
> print
>
> tbl = "".join([chr(x) for x in range(256)])
> 
> print repr(tbl)
> print
> yetmore = encode(tbl)
> print repr(yetmore)
> print
> print repr(decode(yetmore))

I think you right about the d64 translation thing, it does seem like overkill.
I've been playin with sting.split(), came up with...

def decode(encData):
  segments = []
  splits = encData.split("=")
  for i in range(len(splits)):
if i == 0:
  segments.append(splits[0].translate(d42))
else:
  segments.append(splits[i][0].translate(d64) + splits[i][1:].translate(d42
))

  decoded = ''.join(segments)
  return decoded

string.split might be the way to go, this function almost decodes the test file
from the ydec site correctly.
-- 
http://mail.python.org/mailman/listinfo/python-list


standalone python web server

2007-12-26 Thread eric
Hi all,

I want to setup simple python web server and I want it to just unzip
and run, without any installation steps (have no right to do it).

I've tried to write by myself, however, I find I am getting into more
details like processing image file, different file type(like FLV) ..
etc. Any recommendation or tools suggested for me?

Thanks,
Eric
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: standalone python web server

2007-12-27 Thread eric
On Dec 27, 6:22 pm, Bjoern Schliessmann  wrote:
> eric wrote:
> > I want to setup simple python web server and I want it to just
> > unzip and run, without any installation steps (have no right to do
> > it).
>
> Which OS? You might run into authorisation problems if you want it
> to listen on port 80 TCP.
>
> Regards,
>
> Björn
>
> --
> BOFH excuse #303:
>
> fractal radiation jamming the backbone

I'm not planned to use port 80, cause this simple web server is
designed to monitor my set of backend server.

in googling, I find a simple python web server "SNAKELETS", it can
just unzip to run. However, this project seems stale for sometime.

Anyone know anything about it?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: standalone python web server

2007-12-27 Thread eric
On Dec 27, 4:52 pm, Panos Laganakos <[EMAIL PROTECTED]> wrote:
> On Dec 27, 7:41 am, eric <[EMAIL PROTECTED]> wrote:
>
> > Hi all,
>
> > I want to setup simple python web server and I want it to just unzip
> > and run, without any installation steps (have no right to do it).
>
> > I've tried to write by myself, however, I find I am getting into more
> > details like processing image file, different file type(like FLV) ..
> > etc. Any recommendation or tools suggested for me?
>
> > Thanks,
> > Eric
>
> Django[1], has an internal webserver, you might wanna take a look into
> it, as to how it's done. Other than that, Twisted[2], makes it pretty
> easy to write one.
>
> [1]http://www.djangoproject.com
> [2]http://twistedmatrix.com

thanks.
Actually, I've considered to use django, however it required to run
command (which I don't have right to do it)
python setup.py install

Btw, is it possible to use without running setup.py ?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Client side GUI-like web framework ?

2008-02-04 Thread Eric
On Feb 4, 9:45 am, USCode <[EMAIL PROTECTED]> wrote:
> Wouldn't it be handy if there was a web framework that allowed you to
> create pages and control the interface like you would using a
> client-side GUI framework such as Tkinter?
>
> The framework would need a small, fast web server that would
> automatically fire up when you ran your application and you then control
> the interface just like you would with client-side GUI widgets (within
> the limitations of browsers of course).  It would handle all the
> complexities of HTTP, HTML, Javascript, etc. letting you focus on adding
> functionality to your application.
>
> Essentially you would be using the browser as your cross-platform
> client-side interface.  You would just interact with all the widgets
> like trees, grids, paned windows, checkboxes, buttons, etc.
>
> There wouldn't happen to be anything like that available, would there?
> I've seen CherryPy but that doesn't quite seem to be what I described.
>
> Thanks!

The most all-encompassing Python web framework I know of is
Turbogears. It handles Javascript, your database, and everything in
between; CherryPy is its built-in server. The setup script for it is
kind of horrifying, on account of the huge number of separate packages
it grabs from around the Internet, but it's still a popular framework.
I think that's one thing you could use for an easy-peasy, highly
interactive web application.

There is actually no shortage of existing Python web frameworks.
-- 
http://mail.python.org/mailman/listinfo/python-list


[Q] SOAP Server in Python

2008-03-19 Thread Eric
What is the best, well supported, way to write a SOAP Server in
Python? Where can a good example be found?
I do have a WSDL file.

In PHP5, it is rather trivial to write a SOAP server once one has a
WSDL file. For example, a simple SOAP Server written using PHP5 might
look like:

setClass( "MySoapServer" );
$server->handle();
?>

I am basically looking to do the same thing in Python as easily.

Any help or pointers would be appreciated.

thank you.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: SOAP Server in Python

2008-03-19 Thread Eric
On Mar 19, 10:59 am, [EMAIL PROTECTED] wrote:
> On Mar 19, 9:19 am, Eric <[EMAIL PROTECTED]> wrote:
>
> > I am basically looking to do the same thing in Python as easily.
>
> > Any help or pointers would be appreciated.
>
> Googling for "python soap" turned up a few hits that may help you.

Yes, but I don't have the knowledge to accurately or effectively
evaluate the information. I was hoping someone here had some
experience writing a SOAP Server using Python and would be willing to
share what they know.


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: SOAP Server in Python

2008-03-19 Thread Eric
On Mar 19, 10:59 am, [EMAIL PROTECTED] wrote:
> On Mar 19, 9:19 am, Eric <[EMAIL PROTECTED]> wrote:
>
> > I am basically looking to do the same thing in Python as easily.
>
> > Any help or pointers would be appreciated.
>
> Googling for "python soap" turned up a few hits that may help you.

Yes, but I don't have the knowledge to accurately or effectively
evaluate the information. I was hoping someone here had some
experience writing a SOAP Server using Python and would be willing to
share what they know.


-- 
http://mail.python.org/mailman/listinfo/python-list


calling an external program and capturing the output

2009-01-18 Thread Eric

Coming from a perl background I'm new to the Python world.  I need to
read a list of values, send each value to an external program and
capture and act on the output of that program. Reading and parsing the
initial values is not a problem but I can't seem to find anything on
the sending to and capturing from an external program.

Any suggestions would be greatly appreciated.

-Eric
--
http://mail.python.org/mailman/listinfo/python-list


Re: calling an external program and capturing the output

2009-01-18 Thread Eric

Thanks guys. That helped point me int he right direction.

with your advice on the subprocess module I stumbled upon this
posting:
http://www.velocityreviews.com/forums/t359866-subprocess-module.html

for anyone else that might be interested here is the solution. It
simply calls a perl script called add.pl that reads 2 numbers from
stdin and adds them together.

Thanks again for the help.

-Eric


#!/usr/bin/env python

import subprocess

prog = "./add.pl"
args = "3 4"

app = subprocess.Popen
(prog ,stdout=subprocess.PIPE,stdin=subprocess.PIPE,stderr=subprocess.PIPE)

print "opened " + prog
#print app.stdout.read()

print "writing \'" + args + "\' to " + prog + " subprocess"
app.stdin.write(args)
app.stdin.write("\n")

print "wrote \'" + args + "\' to " + prog + " subprocess"
result = app.stdout.read()
result = result.rstrip('\n')

print "received: " + result



and here is the output:

./call_add.py
opened ./add.pl
writing '3 4' to ./add.pl subprocess
wrote '3 4' to ./add.pl subprocess
received: 7



--
http://mail.python.org/mailman/listinfo/python-list


Combining several text files

2009-02-02 Thread Eric
This is my first post, so please advise if I'm not using proper
etiquette. I've actually searched around a bit and while I think I can
do this, I can't think of a clean elegant way. I'm pretty new to
Python, but from what I've learned so far is that there is almost
always an easier way.

I have to parse several log files. I've already written a working
parser. The log files are simple text files that when they get to a
certain size are renamed to append a number. So, you might end up
with:

filename.log.2
filename.log.1
filename.log

The higher the number, the older the file. I want to search for all
the files in a directory with "filename.log" as part of their name.
Then I can do one of two things. First I could combine them so that
the resulting file ends up with the oldest on top and newest on the
bottom. Otherwise, I could just iterate over the multiple files within
my parser.

I don't need working code (that makes things too easy), just clear
suggestions to a Python newcomer to speed me on my way.

Thanks
--
http://mail.python.org/mailman/listinfo/python-list


Re: Combining several text files

2009-02-02 Thread Eric
On Feb 2, 12:17 pm, Chris Rebert  wrote:
> On Mon, Feb 2, 2009 at 9:48 AM, Eric  wrote:
> > This is my first post, so please advise if I'm not using proper
> > etiquette. I've actually searched around a bit and while I think I can
> > do this, I can't think of a clean elegant way. I'm pretty new to
> > Python, but from what I've learned so far is that there is almost
> > always an easier way.
>
> > I have to parse several log files. I've already written a working
> > parser. The log files are simple text files that when they get to a
> > certain size are renamed to append a number. So, you might end up
> > with:
>
> > filename.log.2
> > filename.log.1
> > filename.log
>
> > The higher the number, the older the file. I want to search for all
> > the files in a directory with "filename.log" as part of their name.
> > Then I can do one of two things. First I could combine them so that
> > the resulting file ends up with the oldest on top and newest on the
> > bottom. Otherwise, I could just iterate over the multiple files within
> > my parser.
>
> > I don't need working code (that makes things too easy), just clear
> > suggestions to a Python newcomer to speed me on my way.
>
> For listing the filenames, you'll want to use 
> os.listdir:http://docs.python.org/library/os.html#os.listdir
>
> or possibly the `glob` module depending on your 
> needs:http://docs.python.org/library/glob.html
>
> Cheers,
> Chris
>
> --
> Follow the path of the Iguana...http://rebertia.com

That wasn't too hard at all. I even found the construct:

logfile = [elem for elem in files if elem.find(ln) >= 0]

For my own interest, is there an easy way once I have the file names
to create a single concatenated file?

Thanks,

Eric
--
http://mail.python.org/mailman/listinfo/python-list


Re: python an sqlite objects

2008-12-03 Thread eric
On Dec 3, 10:21 pm, Gerhard Häring <[EMAIL PROTECTED]> wrote:
> azrael wrote:
> > It logical that it would be more efficient and logical to use a object
> > oriented database, but in this case I ask because of the portable
> > nature of sqlite.
>
> > so, if I get it right, this should be possible [...]
>
> Did you try it? Did it work? If so,it was pure luck. Attached is a
> script that shows how to do it right.
>
> -- Gerhard
>
>  sqlite_serialize.py
> 1KViewDownload

Hi,

it is also possible to use Google Protobuf ( http://code.google.com/p/protobuf/
)  instead of pickle or json
 - it's portable to other languages too
 - you define what's the data you really wan't
 - it's fast, and compact


I've done it on one of my projects ( see the code here
http://code.google.com/p/pyshow/source/browse/trunk/src/pyshow/data/msgdb.py
), and using BerkeleyDB instead of sqlite( but that's not the point
here)

What I like with protobuf is that writing the proto file defines the
real data structure, and that's a guaranty over time/processes/coders.
I don't recommand using pickle to serialise object in a database.
Because, it's easy at the beginning, but later, when you are going to
'upgrade' your objects (adding some new fields for instance, or
splitting a field into a new object), you'll get a lot of troubles
( keeping the legacy object to live with the new one, implies renaming
all objects ? etc.). That's what protobuf is for.

BTW, I'm seeking help to start a new project that would connect
protobuf to Database, like the piece of code I've done with
berkeleyDB, but at a bigger scale. If anyone is interested.



--
http://mail.python.org/mailman/listinfo/python-list


Re: simplest way to strip a comment from the end of a line?

2008-12-04 Thread eric
On Dec 4, 4:50 pm, Joe Strout <[EMAIL PROTECTED]> wrote:
> I have lines in a config file which can end with a comment (delimited  
> by # as in Python), but which may also contain string literals  
> (delimited by double quotes).  A comment delimiter within a string  
> literal doesn't count.  Is there any easy way to strip off such a  
> comment, or do I need to use a loop to find each # and then count the  
> quotation marks to its left?
>
> Thanks,
> - Joe

Hi,

if the string literal you wan't to escape, is not escaped (i.e
contains \" ) then a regexp like

.*?(?:".*?".*?)*#(?P .*?)$

(not tested)
.*?  everything but keep it greedy
".*?" the string literal not escaped



--
http://mail.python.org/mailman/listinfo/python-list


Re: simplest way to strip a comment from the end of a line?

2008-12-04 Thread eric
On Dec 4, 5:15 pm, eric <[EMAIL PROTECTED]> wrote:
> On Dec 4, 4:50 pm, Joe Strout <[EMAIL PROTECTED]> wrote:
>
> > I have lines in a config file which can end with a comment (delimited  
> > by # as in Python), but which may also contain string literals  
> > (delimited by double quotes).  A comment delimiter within a string  
> > literal doesn't count.  Is there any easy way to strip off such a  
> > comment, or do I need to use a loop to find each # and then count the  
> > quotation marks to its left?
>
> > Thanks,
> > - Joe
>
> Hi,
>
> if the string literal you wan't to escape, is not escaped (i.e
> contains \" ) then a regexp like
>
> .*?(?:".*?".*?)*#(?P .*?)$
>
> (not tested)
> .*?  everything but keep it greedy
> ".*?" the string literal not escaped


well it works too

import re

test ='''this is a test 1
this is a test 2 #with a comment
this is a '#gnarlier' test #with a comment
this is a "#gnarlier" test #with a comment
'''

splitter = re.compile(r'(?m)^(?P.*?(".*?".*?)*)(?:#.*?)?$')

def com_strip(text):
return [x[0] for x in splitter.findall(test) ]

# raw implementation
for line in test.split('\n'):
print line, '->', re.match(r'(?P.*?(".*?".*?)*)(?:#.*?)?$',
line).group("data")

# with a function
for line in com_strip(test):
print line

and here is the console output

this is a test 1 -> this is a test 1
this is a test 2 #with a comment -> this is a test 2
this is a '#gnarlier' test #with a comment  -> this is a '
this is a "#gnarlier" test #with a comment  -> this is a "#gnarlier"
test
 ->
this is a test 1
this is a test 2
this is a '
this is a "#gnarlier" test


--
http://mail.python.org/mailman/listinfo/python-list


Re: simplest way to strip a comment from the end of a line?

2008-12-05 Thread eric
On Dec 4, 11:35 pm, Paul McGuire <[EMAIL PROTECTED]> wrote:
> Yowza!  My eyes glaze over when I see re's like "r'(?m)^(?P.*?
> (".*?".*?)*)(?:#.*?)?$"!
>

yeah, I know ... :( ( I love complicated regexp ... it's like a puzzle
game for me)


> from pyparsing import quotedString, Suppress, restOfLine
>
> comment = Suppress('#' + restOfLine)
> recognizer = quotedString | comment
>
> for t in tests:
>     print t
>     print recognizer.transformString(t)
>     print
>
> Prints:
>
> this is a test 1
> this is a test 1
>
> this is a test 2 #with a comment
> this is a test 2
>
> this is a '#gnarlier' test #with a comment
> this is a '#gnarlier' test
>
> this is a "#gnarlier" test #with a comment
> this is a "#gnarlier" test
>
> For some added fun, add a parse action to quoted strings, to know when
> we've really done something interesting:
>
> def detectGnarliness(tokens):
>     if '#' in tokens[0]:
>         print "Ooooh, how gnarly! ->", tokens[0]
> quotedString.setParseAction(detectGnarliness)
>
> Now our output becomes:
>
> this is a test 1
> this is a test 1
>
> this is a test 2 #with a comment
> this is a test 2
>
> this is a '#gnarlier' test #with a comment
> Ooooh, how gnarly! -> '#gnarlier'
> this is a '#gnarlier' test
>
> this is a "#gnarlier" test #with a comment
> Ooooh, how gnarly! -> "#gnarlier"
> this is a "#gnarlier" test
>
> -- Paul


I didn't knew pyparsing. It's amazing ! thanks
--
http://mail.python.org/mailman/listinfo/python-list


A more pythonic way of writting

2008-12-05 Thread eric
Hi,

I've got this two pieces of code that works together, and fine

def testit():
for vals in [[i&mask==mask for mask in [1<',  flag(*vals)

def flag(IGNORECASE=False, LOCALE=False, MULTILINE=False,
DOTALL=False, UNICODE=False, VERBOSE=False):
vals = [IGNORECASE, LOCALE, MULTILINE, DOTALL, UNICODE, VERBOSE]
filtered = map( lambda m:m[1],filter( lambda m: m[0], zip(vals,
'iLmsux')))
return '?'+''.join( filtered  )

testit()

but I'm not proud of the way it is written. I dont find it very
pythonic.
I have to multiplex (using zip) bool and value, filter using only the
bool, and demultiplex later using map

the first simply parses all the possible combination of 6 boolean
(can't hardly be made simpler)

the second function, should simply return a string based on the
boolean value
i,   L,   m,  s,  u, x,
True, False, False, True, True, False
=  ?isu

that's should take only one line, shouldn't it?

any idea ?

--
http://mail.python.org/mailman/listinfo/python-list


Re: A more pythonic way of writting

2008-12-05 Thread eric
On Dec 5, 3:44 pm, "Mark Tolonen" <[EMAIL PROTECTED]> wrote:
> "eric" <[EMAIL PROTECTED]> wrote in message
>
> news:[EMAIL PROTECTED]
>
> > def flag(IGNORECASE=False, LOCALE=False, MULTILINE=False,
> > DOTALL=False, UNICODE=False, VERBOSE=False):
> >    vals = [IGNORECASE, LOCALE, MULTILINE, DOTALL, UNICODE, VERBOSE]
> >    filtered = map( lambda m:m[1],filter( lambda m: m[0],
> > zip(vals,'iLmsux')))
> >    return '?'+''.join( filtered  )
>
>     filtered = [c for c,v in zip('iLmsux',vals) if v]
>
> -Mark

thank you very much ! great !

I can't get used to this late 'if' syntax !

@Gerard
nice hypercube function. But I'll keep with my implementation :
I like to believe that the less the 'debug pointer' stands in the
python code, the fastest the code is (or is potentially)

I keep thinking that
def hypercube(ndims) :
for i in range(1<http://mail.python.org/mailman/listinfo/python-list


Re: simplest way to strip a comment from the end of a line?

2008-12-05 Thread eric
On Dec 5, 11:56 am, eric <[EMAIL PROTECTED]> wrote:
> On Dec 4, 11:35 pm, Paul McGuire <[EMAIL PROTECTED]> wrote:
>
> > Yowza!  My eyes glaze over when I see re's like "r'(?m)^(?P.*?
> > (".*?".*?)*)(?:#.*?)?$"!
>
> yeah, I know ... :( ( I love complicated regexp ... it's like a puzzle
> game for me)
>
>
>
> > from pyparsing import quotedString, Suppress, restOfLine
>
> > comment = Suppress('#' + restOfLine)
> > recognizer = quotedString | comment
>
> > for t in tests:
> >     print t
> >     print recognizer.transformString(t)
> >     print
>
> > Prints:
>
> > this is a test 1
> > this is a test 1
>
> > this is a test 2 #with a comment
> > this is a test 2
>
> > this is a '#gnarlier' test #with a comment
> > this is a '#gnarlier' test
>
> > this is a "#gnarlier" test #with a comment
> > this is a "#gnarlier" test
>
> > For some added fun, add a parse action to quoted strings, to know when
> > we've really done something interesting:
>
> > def detectGnarliness(tokens):
> >     if '#' in tokens[0]:
> >         print "Ooooh, how gnarly! ->", tokens[0]
> > quotedString.setParseAction(detectGnarliness)
>
> > Now our output becomes:
>
> > this is a test 1
> > this is a test 1
>
> > this is a test 2 #with a comment
> > this is a test 2
>
> > this is a '#gnarlier' test #with a comment
> > Ooooh, how gnarly! -> '#gnarlier'
> > this is a '#gnarlier' test
>
> > this is a "#gnarlier" test #with a comment
> > Ooooh, how gnarly! -> "#gnarlier"
> > this is a "#gnarlier" test
>
> > -- Paul
>
> I didn't knew pyparsing. It's amazing ! thanks


maybe you'd rather replace:
splitter = re.compile(r'(?m)^(?P.*?(".*?".*?)*)(?:#.*?)?$')

by

from reO import *
quote = characters('"') # defining the characters used as string sep
sharp= string('#') # defining the sharp symbol
data = ALL + repeat( group( quote + ALL + quote + ALL ) )# ALL
( "ALL" ALL)*
comment = group(sharp+ALL+END_LINE) # the comment itself

xp = flag(MULTILINE=True) + START_LINE + group( data, name="data") +
if_exists(comment)

splitter = xp.compile()



--
http://mail.python.org/mailman/listinfo/python-list


Re: A more pythonic way of writting

2008-12-05 Thread eric
On Dec 6, 12:19 am, Steven D'Aprano <[EMAIL PROTECTED]
cybersource.com.au> wrote:
> On Fri, 05 Dec 2008 07:44:21 -0800, eric wrote:
> > I like to believe that the less the 'debug pointer' stands in the python
> > code, the fastest the code is (or is potentially)
>
> What's a debug pointer?
>
> Pre-mature optimization is the root of evil in programming. Unless you
> have actually *measured* the speed of the code, how do you know you
> aren't making it slower instead of faster?
>
> Experience with other languages often is misleading when programming with
> Python. If you are used to programming in C, for example, then you will
> tend to program one way because comparisons are fast and moving records
> is slow. But in Python, comparisons can be slow and moving records is
> fast, so the C programmer's intuitions about "fast code" are often
> pessimations instead of optimizations.
>
> --
> Steven

you are right about premature optimization. I cannot disagree.

My 'rule of thumb' was more about that:
1/ keep the code the more descriptive and the less procedural as
possible.
2/ the less instructions you write, the more optimization you'll get
from the others

the hypercube function is cool, and I would use it, if I weren't in
charge of maintaining the code.


I've done some 'timeit'

import timeit

t1 = timeit.Timer(
"""
h1 = hypercube(6)
""",
"""def hypercube(ndims):
return [[i&mask==mask for mask in [1<http://mail.python.org/mailman/listinfo/python-list


Re: Determining whether a variable is less/greater than a range.

2008-12-08 Thread eric
On Dec 8, 11:44 am, "[EMAIL PROTECTED]"
<[EMAIL PROTECTED]> wrote:
> Hi. I'm having another go at learning Python so I'll probably be
> asking a few basic questions. Here is the first one.
>
> a = list(range(10, 21)
>
> b = 9
>
> c = 21
>
> How can I find out if b and c have values less or more than the values
> in list a?
>
> Thanks.


what about:
a = list(range(10, 21))


def compare(value, list):
m,M = min(list), max(list)
return value>=m, value<=M

b = 9
c = 21

print compare(b,a)
print compare(c,a)

for i in range (8, 25):
print i, compare(i, a)


"""
(False, True)
(True, False)
8 (False, True)
9 (False, True)
10 (True, True)
11 (True, True)
12 (True, True)
13 (True, True)
14 (True, True)
15 (True, True)
16 (True, True)
17 (True, True)
18 (True, True)
19 (True, True)
20 (True, True)
21 (True, False)
22 (True, False)
23 (True, False)
24 (True, False)
"""

it helps?
--
http://mail.python.org/mailman/listinfo/python-list


Google Summer of Code 2009

2008-12-08 Thread Eric
Hello,
I am interested in participating in Google Summer of Code 2009,
hopefully for something in Python.  I realize that this is way before
it begins, but I would like to start to get to know the community
better and find something that I could work on during the summer of
code.  I know a decent amount of Python, and I am a Sophomore Computer
Science major.  My school teaches Java, but on the side I taught
myself Python.  If anyone knows of any projects that could use another
hand, I would appreciate it.

Thanks,
Eric
--
http://mail.python.org/mailman/listinfo/python-list


Re: 'pretty print' for built in types

2008-12-09 Thread eric
On Dec 9, 4:31 pm, Robert Dailey <[EMAIL PROTECTED]> wrote:
> Hi,
>
> Is there a built in way to 'pretty print' a dict, list, and tuple
> (Amongst other types)? Dicts probably print the ugliest of them all,
> and it would be nice to see a way to print them in a readable way. I
> can come up with my own function to do this, but I don't want to do
> this if I don't have to.


you can have a look at [http://code.google.com/p/prynt/ prynt], it
provides some simple functions, to pretty print into RestructuredText,
and then, when the process is finished (it's an option) show the
'console' converted into html.
dict are transformed into definition:
 key: value
 key: value


it helps ?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Google Summer of Code 2009

2008-12-09 Thread Eric
On Dec 9, 6:26 am, André <[EMAIL PROTECTED]> wrote:
> On Dec 8, 10:34 pm, Eric <[EMAIL PROTECTED]> wrote:
>
> You should have a look athttp://wiki.python.org/moin/SummerOfCode
>
> It's still early, so there's nothing yet for 2009, but I am sure that
> some ongoing projects mentioned in previous years [like Crunchy ;-)]
> will be looking for volunteers.
>
> André

Thanks for the link.  For some reason I hadn't seen Crunchy there
before.  I would be interested in doing something for Crunchy.  The
class room server seems like a good project if it hasn't been tackled
yet.  I also wouldn't mind trying to get the history menu going as a
start.

-Eric
--
http://mail.python.org/mailman/listinfo/python-list


Re: Best way to report progress at fixed intervals

2008-12-10 Thread eric
Don't mind if I give my shot ?

def work(i):
"""
Dummy process function, which takes a random time in the interval
0.0-0.5 secs to execute
"""
print "Work step %d" % i
time.sleep(0.5 * random.random())

def workAll(work, verbose=True, max_iter=20, progress_interval=1.0):
'''
pass the real job as a callable
'''
progress = time.time()
for i in range(max_iter): # do the requested loop
work(i)
if verbose:
print "Work through all %d steps reporting progress every
%3.1f secs..." %(max_iter, progress_interval)
interval = time.time()-progress
if interval>progress_interval:
print "Processed %d of %d at pace %s" % (i, max_iter,
interval)
progress +=interval


if __name__=="__main__":
workAll(work, False)


It's works fine, and the "pace" is 'almost' the required one. You earn
a no-thread-mess, and cleaner alg.

But the loop is controlled by the caller (the WorkAll function) this
is also called ass-backward algorithm, and you cannot expect
algorithms to be assbackward (even if it's the best way to implement
them).

You can use the yield statement, to turn  easilly your alg into a
nice, stopable assbackward algo:

def work():
"""
Dummy process function, which takes a random time in the interval
0.0-0.5 secs to execute
"""
for i in range(50):
print "Work step %d" % i
time.sleep(0.5 * random.random())
yield i # kind-of "publish it and let the caller do whatever
it want s (good practice anyway)


def workAll(work, verbose=True, max_iter=20, progress_interval=1.0):
'''
pass the real job as a generator
'''
progress = time.time()
i = 0
for w in work: # do the requested loop
if verbose:
print "Work through all %d steps reporting progress every
%3.1f secs..." %(max_iter, progress_interval)
interval = time.time()-progress
if interval>progress_interval:
print "Processed %d at pace %s" % (w, interval)
progress +=interval
if i>=max_iter:
work.close()
i+=1


if __name__=="__main__":
workAll(work(), False) # note the calling difference


hope it helps.

--
http://mail.python.org/mailman/listinfo/python-list


Re: How to pass out the result from iterated function

2008-12-10 Thread eric
On Dec 10, 9:16 pm, JD <[EMAIL PROTECTED]> wrote:
> I got a iterated function like this:
>
> def iterSomething(list):
>     has_something = False
>     for cell in list:
>         if something in cell:
>             has_something = True
>             output = something
>    if has_something:
>        iterSomething(output)
>    else:
>        final_out = outupt
>
> The problem is how can I read this final_out outside of the function.
> I tried the global statement, it seems not work. Any idea?
>
> JD

why don't you just return it ?


def iterSomething(list):
has_something = False
for cell in list:
if something in cell:
has_something = True
output = something
   if has_something:
   return iterSomething(output)
   else:
   return output

?
--
http://mail.python.org/mailman/listinfo/python-list


Best Practice using Glade/Python

2008-12-18 Thread eric
Hi,

I was wondering which is the "best practice" using glade/python, and,
of course, especially the connect (both side).

I didn't found that much documentation on the net ( too noisy), and
the best "thing" I've found was http://www.linuxjournal.com/article/7558
which is a bit old now (2004). The article is very interesting BTW,
but I was concerned by the fact it might be a little outdated.

It smells like I'm missing something here, and that there have been a
clean way to connect both (the autoconnect stuff does not seem that
clean to me) for a long time now.

So here is the question, do you practive galde/python, which is your
practice ?

Thanks


Eric
http://codeslash.blogspot.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: Factoring Polynomials

2008-12-18 Thread eric
On Dec 18, 8:37 pm, [email protected] wrote:
> I am trying to write a simple application to factor polynomials. I
> wrote (simple) raw_input lines to collect the a, b, and c values from
> the user, but I dont know how to implement the quadratic equation
>
> x = (-b +or- (b^2 - 4ac)^1/2) / 2a
>
> into python. Any ideas?

with numpy:
from numpy import *

s=[1,-1]
x = -b+s*sqrt( b**2-4*a*c )/(2*a)

Eric
http://codeslash.blogspot.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: Factoring Polynomials

2008-12-18 Thread eric
On Dec 18, 9:40 pm, "J. Cliff Dyer"  wrote:
> On Thu, 2008-12-18 at 11:52 -0800, eric wrote:
> > On Dec 18, 8:37 pm, [email protected] wrote:
> > > I am trying to write a simple application to factor polynomials. I
> > > wrote (simple) raw_input lines to collect the a, b, and c values from
> > > the user, but I dont know how to implement the quadratic equation
>
> > > x = (-b +or- (b^2 - 4ac)^1/2) / 2a
>
> > > into python. Any ideas?
>
> > with numpy:
> > from numpy import *
>
> > s=[1,-1]
> > x = -b+s*sqrt( b**2-4*a*c )/(2*a)
>
> > Eric
>
> Without the Nump.
>
> def polynomial(a, b, c):
>     N = ((b**2 - 4*a*c)**.5) / 2*a
>     return (-b + N, -b - N)

there is a little mistake in your formula :

def roots_of(a, b, c):
N = ((b**2 - 4*a*c)**.5)
return ((-b + N)/(2*a), (-b - N)/(2*a))

but I stick with numpy, numpy is heavy, but not as much as using a
computer to solve this problem ! And numpy should be standard module
for computer science student !

Eric
http://codeslash.blogspot.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: Which sparse matrix package?

2008-12-18 Thread eric
On Dec 18, 11:52 pm, MRAB  wrote:
> James Mills wrote:
> > On Fri, Dec 19, 2008 at 8:18 AM, Martin Manns  wrote:
> >> Hi:
>
> > Hi,
>
> >> I am writing a spreadsheet application in Python
>
> > What's wrong with pyspread ?
>
> > [ ... snip ... ]
>
> >> The dict that I tried out is of the type:
>
> >> {(1,2,3): "2323", (1,2,545): "2324234", ... }
>
> >> It is too slow for my application when it grows. One slicing operation
> >> with list comprehensions takes about 1/2 s on my computer for 1E6
> >> elements.
>
> > Let me get this straight.
> > It's taking 0.5s to slice your matrix
> > of 1E7 (1000.0 rows/columns)
>
> > Are you mad ? This is TEN Millions and you
> > required it faster than 0.5s ?
>
> No, 1E6, or ONLY 1 million. :-)

what does Internet explorer 6 & 7 have to do with that ? ;-)

>
> > Am I missing something here ?
>
> Would a matrix of matrices work better, ie a supermatrix where each
> element is either a submatrix of cells or None if the submatrix is
> empty? How much memory it would save would depend on how sparse the
> matrix is.

sparse matrix efficiency is all about guessing the probability for a
cell to be empty. My guess is that the probability for a cell (i,j) to
be empty grows with norm(i,j)

then, you should store your data in a list, and the indexes in another
"list", then use a BTree like algorithm, or keep you data ordered by
norm(i,j) growing.

something like:

data = [] #
kernel =[] # full of couples (i,j)

def add(i,j,value):
data.append(value) # or put in the "right place" to keep it sorted
kernel.append(i,j) # same comment

def get(i,j):
k = kernel_of(i,j)
return data[k]
def set(i,j,value):
   if is_probably_empty():
  k = kernel_of(i,j)
  if k:
data[k]= value
  else: add(i,j,value)

   else:
  add(i,j,value)

where the 'kernel_of method" can take advantage of the sorted order
(i*j or max(i,j) should be as good) to make a fast dichotomy.

The set method is about finding if the cell is 'empty or not' and then
either perform an indexof, or a add.
to efficiently know if a cell is empty (the is_probably_empty method)
or not, try to use the bloom filter using
i*j%m as hash function (for instance)

here arrays have the size of your actual data (maybe thousands of cell
for a huge spreadsheet), that's MUCH better than the size of the
maxN*maxM

if my memory is correct, there is room in numpy for your own sparse
matrix implementation. You should try it with your own sparse matrix
implementation.





--
Eric
http://codeslash.blogspot.com
--
http://mail.python.org/mailman/listinfo/python-list


best way to code

2008-12-19 Thread eric
hi,

I need to find a "good" design pattern to instanciate, and add
specific code all in one. Let me explain it :

I need to define "some" code, better be in a class, something like

class LinkA(object):
def mystuff(self):
 

class LinkB(object):
def mystuff(self):
 


AND I need an instance of this class
{ "stuff A": LinkA()
  "stuff B": LinkB()
}

This kind of code "would" be fine, I mean, the result effect in memory
is fine for me.
But I don't like the way I have to
1/ give a useless name to LinkA, linkB (there can be hundreds of names
like that)
2/ I have to write it down two times (and that's one time too much)

any ideas ?

something like
[
new object():
def mystuff(self):
   
,
new object():
def mystuff(self):
   
]

would be really perfect (but I know it does not work, or at least, I
don't know how to make it work)

In fact, I would like to define a class, and an instance in a single
statement


thanks

--
Eric
http://codeslash.blogspot.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: best way to code

2008-12-19 Thread eric
On Dec 19, 5:35 pm, Peter Otten <[email protected]> wrote:
> eric wrote:
> > hi,
>
> > I need to find a "good" design pattern to instanciate, and add
> > specific code all in one. Let me explain it :
>
> > I need to define "some" code, better be in a class, something like
>
> > class LinkA(object):
> >     def mystuff(self):
> >          
>
> > class LinkB(object):
> >     def mystuff(self):
> >          
>
> > AND I need an instance of this class
> > { "stuff A": LinkA()
> >   "stuff B": LinkB()
> > }
>
> > This kind of code "would" be fine, I mean, the result effect in memory
> > is fine for me.
> > But I don't like the way I have to
> > 1/ give a useless name to LinkA, linkB (there can be hundreds of names
> > like that)
> > 2/ I have to write it down two times (and that's one time too much)
>
> > any ideas ?
>
> > something like
> > [
> > new object():
> >     def mystuff(self):
> >        
> > ,
> > new object():
> >     def mystuff(self):
> >        
> > ]
>
> > would be really perfect (but I know it does not work, or at least, I
> > don't know how to make it work)
>
> > In fact, I would like to define a class, and an instance in a single
> > statement
> >>> class Register:
>
> ...     def __init__(self):
> ...             self.items = []
> ...     def __call__(self, method):
> ...             class Link(object):
> ...                     mystuff = method
> ...             self.items.append(Link())
> ...>>> register = Register()
> >>> @register
>
> ... def mystuff(self): print "first"
> ...>>> @register
>
> ... def mystuff(self): print "second"
> ...>>> for item in register.items:
>
> ...     item.mystuff()
> ...
> first
> second
>
> Peter


hi,

I've tried something like this :

import inspect

class Test(object):
class Inner(object):
def mystuff(self):
print "hello stuff"

class InnerB(object):
def mystuff(self):
print "hello B"


def filter(member):
return inspect.isclass(member) and not member==Test.__class__
d = dict( (name, c()) for name, c in inspect.getmembers(Test,
filter ) )
print d


it works too, but I prefer your method

thanks

--
Eric
http://codeslash.blogspot.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: best way to code

2008-12-19 Thread eric
On Dec 19, 6:36 pm, eric  wrote:
> On Dec 19, 5:35 pm, Peter Otten <[email protected]> wrote:
>
>
>
> > eric wrote:
> > > hi,
>
> > > I need to find a "good" design pattern to instanciate, and add
> > > specific code all in one. Let me explain it :
>
> > > I need to define "some" code, better be in a class, something like
>
> > > class LinkA(object):
> > >     def mystuff(self):
> > >          
>
> > > class LinkB(object):
> > >     def mystuff(self):
> > >          
>
> > > AND I need an instance of this class
> > > { "stuff A": LinkA()
> > >   "stuff B": LinkB()
> > > }
>
> > > This kind of code "would" be fine, I mean, the result effect in memory
> > > is fine for me.
> > > But I don't like the way I have to
> > > 1/ give a useless name to LinkA, linkB (there can be hundreds of names
> > > like that)
> > > 2/ I have to write it down two times (and that's one time too much)
>
> > > any ideas ?
>
> > > something like
> > > [
> > > new object():
> > >     def mystuff(self):
> > >        
> > > ,
> > > new object():
> > >     def mystuff(self):
> > >        
> > > ]
>
> > > would be really perfect (but I know it does not work, or at least, I
> > > don't know how to make it work)
>
> > > In fact, I would like to define a class, and an instance in a single
> > > statement
> > >>> class Register:
>
> > ...     def __init__(self):
> > ...             self.items = []
> > ...     def __call__(self, method):
> > ...             class Link(object):
> > ...                     mystuff = method
> > ...             self.items.append(Link())
> > ...>>> register = Register()
> > >>> @register
>
> > ... def mystuff(self): print "first"
> > ...>>> @register
>
> > ... def mystuff(self): print "second"
> > ...>>> for item in register.items:
>
> > ...     item.mystuff()
> > ...
> > first
> > second
>
> > Peter
>
> hi,
>
> I've tried something like this :
>
> import inspect
>
> class Test(object):
>     class Inner(object):
>         def mystuff(self):
>             print "hello stuff"
>
>     class InnerB(object):
>         def mystuff(self):
>             print "hello B"
>
> def filter(member):
>     return inspect.isclass(member) and not member==Test.__class__
> d = dict( (name, c()) for name, c in inspect.getmembers(Test,
> filter ) )
> print d
>
> it works too, but I prefer your method
>
> thanks
>
> --
> Erichttp://codeslash.blogspot.com

Finally here is my 'final' shot:

context: when building a glade GUI I wanted to connect 'nicely'
signals (I hate coding the same info in several places)

here is my main :

if __name__=="__main__":
pathname = os.path.dirname(sys.argv[0])
startup = os.path.join(pathname, 'pyshow/pyshow.glade')
xml = gtk.glade.XML(startup) #'filename.glade')

#the stuff starts here
m = MainApp()
for widget_name, codget in m.items():
codget.set_widget( xml.get_widget(widget_name) )

gtk.main()


and here is the 'MainApp' code, based on the question, and finally I
get stuck to my second solution


import inspect
class Controller(dict):
def __init__(self):
dict.__init__(self)
self.update(
(name, c()) for name, c in inspect.getmembers
(self.__class__, lambda member: inspect.isclass(member) and not
member==self.__class__.__class__  )
   )



class MainApp(Controller):
def __init__(self):
Controller.__init__(self)

class main_window(codget):
def on_destroy(self, widget, modget):
print "bye bye"

class play(codget):
def on_clicked(self, widget, modget):
print "you have clicked"



the business is hidden in codget ( as COntroller gaDGET), and what's
interesting for me, is that every signal handler has a 'modget' ( as
in model gadget) that it can use to do the job (part of the MVC
pattern)

thanks Peter anyway, I didn't use your solution in this specific case,
but I loved the solution anyway, and I'm sure that I'll use it one
day.







--
http://mail.python.org/mailman/listinfo/python-list


Simple question about Python lists

2008-11-11 Thread Eric
I'm learning Python (while coming from MATLAB). One question I have is
that if I have a list with say 8 elements, and I want just a few of
them how do I select them out. In MATLAB, if I just want the first,
fifth and eighth element I might do something like this:

b = a([1 5 8]);

I can't seem to figure out a similar Python construct for selecting
specific indices. Any suggestions?

Thanks,

Eric
--
http://mail.python.org/mailman/listinfo/python-list


Re: Simple question about Python lists

2008-11-11 Thread Eric
On Nov 11, 1:51 pm, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote:
> On Tue, 11 Nov 2008 11:47:53 -0800, Eric wrote:
> > I'm learning Python (while coming from MATLAB). One question I have is
> > that if I have a list with say 8 elements, and I want just a few of them
> > how do I select them out. In MATLAB, if I just want the first, fifth and
> > eighth element I might do something like this:
>
> > b = a([1 5 8]);
>
> > I can't seem to figure out a similar Python construct for selecting
> > specific indices. Any suggestions?
>
> b = [a[i] for i in [1, 5, 8]]
>
> Ciao,
>         Marc 'BlackJack' Rintsch

Thanks! It makes sense, but in this case MATLAB seems easier and no
less readable. That said, I know better than for a newbie like me to
question syntax issues.

Regards,

Eric
--
http://mail.python.org/mailman/listinfo/python-list


Suggestions for an education programming project

2008-11-17 Thread Eric
Hi,

I've been trying to get my son interested in learning some simple
programming for a while. While I understand that a structured tutorial
is best, I think if we can write something cool at least once, it will
encourage him to learn more. While I have a lot of experience with
MATLAB, I've just started playing with Python. It seems to me to be a
great language to learn with. My son has an idea for a program to
write. Basically he would like to present a window with a small circle
on it. The window title would have the instruction to click on the
circle. As the mouse approaches the circle, it moves away from the
spot. Being a kid, the visual and interactive aspect appeals. I think
this will be nice as he can add complexity incrementally such as what
direction to move, how to handle running into the edge of the window,
etc.

What I'd like is a suggestion as to what GUI framework to use (Tk, wx
or something else). I can add modules if necessary. I'd just as soon
use something clean, understandable and not too complex. Certainly,
what ever we use needs to have good documentation. No code please,
that's for us to figure out. In case it matters, we are using are
programming in OS X.

Thanks in advance,

Eric
--
http://mail.python.org/mailman/listinfo/python-list


Re: Suggestions for an education programming project

2008-11-17 Thread Eric
On Nov 17, 1:06 pm, Arnaud Delobelle <[EMAIL PROTECTED]> wrote:
> Eric <[EMAIL PROTECTED]> writes:
> > Hi,
>
> > I've been trying to get my son interested in learning some simple
> > programming for a while. While I understand that a structured tutorial
> > is best, I think if we can write something cool at least once, it will
> > encourage him to learn more.
>
> I know it's not based on Python but...
>
> Do you know about scratch (http://scratch.mit.edu/)? I think it's a
> fantastic tool for kids to learn to program.  Unfortunately mine is
> still too young but I am trying to introduce it in my school (I work as
> a teacher).
>
> --
> Arnaud

Actually, my son is 15, so Scratch might be too simplistic. PyGame
looks interesting. I'll play around with it tonight.

Eric
--
http://mail.python.org/mailman/listinfo/python-list


Re: Simple question about Python lists

2008-11-17 Thread Eric
On Nov 11, 7:31 pm, Ben Finney <[EMAIL PROTECTED]>
wrote:
> Steven D'Aprano <[EMAIL PROTECTED]> writes:
> > On Wed, 12 Nov 2008 10:08:45 +1100, Ben Finney wrote:
>
> > >Eric<[EMAIL PROTECTED]> writes:
> > >> In MATLAB, if  I just want the first, fifth  and eighth element I
> > >> might do something like this:
>
> > >> b = a([1 5 8]);
>
> > > Yes: the above code uses magic numbers which convey no semantic
> > > meaning, and should instead use *named* elemets of a container. In
> > > Python, that's done with a mapping type, which has the built-in
> > > type of ‘dict’.
>
> > > In other words: a list is best for sequences where any item is
> > > semantically identical to any other, and you can (for example)
> > > re-order all the elements in the list without changing their
> > > semantic meaning. If, instead, you want semantic meaning, that's
> > > best done via *names*, not magic numbers.
>
> > What the OP is asking for is a generalization of slicing.
>
> I don't think so. (The OP is, of course, welcome to respond to
> this or existing requests for clarification of their intent.)
>
> > Given a slice alist[start:end:stride] the indices are given by the
> > sequence start+i*stride, bounded by end. It seems to me that the OP
> > has asked how to take a slice where the indices are from an
> > arbitrary set, possibly given by an equation, but not necessarily.
>
> I think that's exactly what is *not* being asked for, based on the
> specific example given. The example was “I just want the first,
> fifth, and eighth element”, and the example implementation showed
> them with those numeric literals in the code. On that basis I
> interpreted the need for *those elements specifically*, for some
> semantic reason not yet disclosed.
>
> If, instead, the OP wanted to retrieve “indices … from an arbitrary
> set, possibly given by an equation”, I would recommend that *that
> equation* be abstracted behind an expression, or even a well-named
> function, that would make explicit what the *meaning* of the set was.
>
> I maintain that anything which expresses “retrieve the indices at
> these numbers” without saying *in the code* what the meaning of those
> numbers is, is to be deprecated in favour of an implementation that
> makes the semantic meaning explicit.
>
> And no, before anyone suggests it, an explanatory comment is not
> sufficient for this condition: the names and types used should make
> clear what the meaning of the expression is. A comment saying *why* is
> always appreciated; but if the comment needs to tell me *what* the
> code is doing or *how*, the code instead needs to be re-written to be
> explicit.
>
> --
>  \      “Saying that Java is nice because it works on all OSes is like |
>   `\     saying that anal sex is nice because it works on all genders” |
> _o__)                                                —http://bash.org/|
> Ben Finney

Thanks much for the interesting discussion. In case anyone wonders
what problem I was trying to solve in the first case, I was simply
parsing a large text file. I read in each line, searched for the key
text using line.find('search text') and if I found the text I was
looking for, parsed the line with a=line.split(' ') since there was
only spaces breaking up parts of the line. This provided a list "a"
from which I only wanted certain elements. I wanted to select just
those elements in a particular order and then join them as a comma
delimited string to output to a second file. This is why I wanted to
select only certain items in the list and generally in a non-
consecutive order. I think the original suggestion is probably the
best one:

b = [a[i] for i in [1, 5, 8]]

I understand the basic Python concept that there should be one obvious
way of doing something, so if there is a easier and better approach to
parsing text files (which I end up doing a lot of), feel free to
suggest it.

Thanks,

Eric
--
http://mail.python.org/mailman/listinfo/python-list


The spam to content ratio of this group

2009-04-01 Thread Eric
is getting very high. Why aren't captcha's used to prevent all of this
noise?

--
http://mail.python.org/mailman/listinfo/python-list


Wait or not?

2008-09-30 Thread Eric
I've been wanting to learn Python for a while now but I can't decide
on whether to wait for Python 3's final release and learn it or just
go ahead and learn 2.x. Would it be hard to make the transition being
a noob?
--
http://mail.python.org/mailman/listinfo/python-list


CRLF Newlines and libc

2009-07-27 Thread Eric
I am working on the subprocess.Popen module for Google Summer of Code.
Right now, I am having difficulty trying to work out how to deal with
my '\n' newlines being converted to '\r\n' newlines when reading from
a pipe on windows; see this blog post (http://subdev.blogspot.com/
2009/07/stdout.html) and this chain on Python-Dev (http://
mail.python.org/pipermail/python-dev/2009-July/090720.html).

Right now, unless there is way to disable the newline conversions, I
am thinking I will just have to document the caveat and call it a day.
Is there a better way to handle this?

Eric
-- 
http://mail.python.org/mailman/listinfo/python-list


distributing a binary package

2013-05-06 Thread Eric Frederich
Hello,

Hopefully a simple question.
Basically, I'd like to know how to create a proper setup.py script to
install a package.
The package exists as a single directory with a single __init__.py
file and (currently) 93 .so files.

Right now I just copy it into the site-packages directory but I'd like
to start using virtualenv / pip so I'd like to do the installation via
"python setup.py install".

I need to keep my build process external to this for performance
reasons (with a Makefile I can do parallel builds and I have a machine
with 12 cores).

My Makefile does all the work.  It produces a directory that simply
needs to be copied to site-packages but how do I craft a setup.py
script to do the actually installation?

Thanks,
~Eric
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: distributing a binary package

2013-05-07 Thread Eric Frederich
I see where I can specify a module that distutils will try to compile.
I already have the .so files compiled.

I'm sure its simple, I just can't find it or don't know what to look for.

On Mon, May 6, 2013 at 9:13 PM, Miki Tebeka  wrote:
>
>> Basically, I'd like to know how to create a proper setup.py script
> http://docs.python.org/2/distutils/setupscript.html
> --
> http://mail.python.org/mailman/listinfo/python-list
-- 
http://mail.python.org/mailman/listinfo/python-list


python sockets question

2013-05-15 Thread Eric Miller
Can python sockets be used to capture IP traffic when the traffic is 
originating from a non-python source?

Using a Lantronix UDS-1100 serial to IP converter. The goal is to write a small 
proof of concept piece in Python to capture serial data output by this device 
over IP.

I've done a couple test projects using sockets in python, but they were all 
done between python processes (python > python): listen() on one end, and 
connect(), sendall() etc on the other.

I think I can use sockets for this project, but before I invest a bunch of time 
into it, wanted to make sure it is a viable solution.

Can python sockets be used to capture IP traffic when the traffic is 
originating from a non-python source? I have full control over the IP and port 
that the device sends the serial data to, but there will be no python connect() 
initiated by the client. I can pre-pend then serial data with some connect() 
string if needed.

If sockets won't work, please recommend another solution...guessing it will be 
REST or similar.
-- 
http://mail.python.org/mailman/listinfo/python-list


properly catch SIGTERM

2012-07-19 Thread Eric Frederich
So I wrote a script which acts like a daemon.
And it starts with something like this

### Begin Code

import signal

STOPIT = False

def my_SIGTERM_handler(signum, frame):
global STOPIT
print '\n--- Caught SIGTERM; Attempting to quit gracefully ---'
STOPIT = True

signal.signal(signal.SIGTERM, my_SIGTERM_handler)
signal.signal(signal.SIGINT , my_SIGTERM_handler)

### End Code

My main loop looks something like this...

login()
while not STOPIT:
foo1()
foo2()
foo3()
if STOPIT:
break
bar1()
bar2()
bar3()

print 'bye'
logout()

This seems to work okay but just now I got this while hitting ctrl-c
It seems to have caught the signal at or in the middle of a call to
sys.stdout.flush()


--- Caught SIGTERM; Attempting to quit gracefully ---
Traceback (most recent call last):
  File "/home/user/test.py", line 125, in 
sys.stdout.flush()
IOError: [Errno 4] Interrupted system call


How should I fix this?
Am I doing this completely wrong?

Thanks,
~Eric
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: properly catch SIGTERM

2012-07-20 Thread Eric Frederich
On Fri, Jul 20, 2012 at 1:51 AM, Jason Friedman  wrote:

> > This seems to work okay but just now I got this while hitting ctrl-c
> > It seems to have caught the signal at or in the middle of a call to
> > sys.stdout.flush()
> >
> >
> > --- Caught SIGTERM; Attempting to quit gracefully ---
> > Traceback (most recent call last):
> >   File "/home/user/test.py", line 125, in 
> > sys.stdout.flush()
> > IOError: [Errno 4] Interrupted system call
> >
> >
> > How should I fix this?
> > Am I doing this completely wrong?
>
> Instead of rolling your own others have written Python code to
> implement daemons.  Try a search on "Python daemon".
>

I found a stackoverflow question that linked to this...
http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/
... I'm not sure how that would help.  They don't attempt to exit
gracefully.
I don't think my problem is the daemon part, it is the handling the SIGTERM
signal where I'm having trouble.
-- 
http://mail.python.org/mailman/listinfo/python-list


Using Python packaging tools to maintain source distributions in other languages?

2012-07-23 Thread eric . lemings
Greetings all,

I would like to leverage the Python packaging tools (e.g. distutils, 
setuptools, distribute, et. al.) to maintain (i.e. download, extract, 
configure, make, install, package) source distributions other than Python 
modules (e.g. zlib, openssl).

Are there any open-source packages/tools that already do this?  Any 
documentation in print or on the web that outlines a basic plan for doing such?

Any and all help greatly appreciated.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Using Python packaging tools to maintain source distributions in other languages?

2012-07-24 Thread eric . lemings
On Monday, July 23, 2012 11:59:10 PM UTC-6, Rusi wrote:
> On Jul 23, 11:16 pm, [email protected] wrote:
> > Greetings all,
> >
> > I would like to leverage the Python packaging tools (e.g. distutils, 
> setuptools, distribute, et. al.) to maintain (i.e. download, extract, 
> configure, make, install, package) source distributions other than Python 
> modules (e.g. zlib, openssl).
> >
> > Are there any open-source packages/tools that already do this?  Any 
> documentation in print or on the web that outlines a basic plan for doing 
> such?
> >
> > Any and all help greatly appreciated.
> 
> Ive heard good things about scons
> http://en.wikipedia.org/wiki/SCons

I've heard about SCons but don't know much about it.  From what little I've 
read, it's only a make tool replacement.  I'm looking for more "end-to-end" 
maintenance tools similar to -- perhaps built upon -- disutils, setuptools, and 
company.
-- 
http://mail.python.org/mailman/listinfo/python-list


remote read eval print loop

2012-08-16 Thread Eric Frederich
Hello,

I have a bunch of Python bindings for a 3rd party software running on the
server side.
I can add client side extensions that communicate over some http / xml type
requests.
So I can define functions that take a string and return a string.
I would like to get a simple read eval print loop working.

Without adding a bunch of syntax checking on the client side can I get the
behavior of the regular interpreter?
What I mean is things like going from >>> to ... after you start a block
(like if, while, for, etc).

Is this possible or can I not send over one line at a time and I'd have to
send over a complete block?

Thanks,
~Eric
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: remote read eval print loop

2012-08-17 Thread Eric Frederich
What I wanted to implement was a debugging console that runs right on the
client rather than on the server.
You'd have to be logged into the application to do anything meaningful or
even start it up.
All of the C functions that I created bindings for respect the security of
the logged in user.

Within the debugging console, after importing all of the bindings, there
would be no reason to import anything whatsoever.
With just the bindings I created and the Python language we could do
meaningful debugging.
So if I block the ability to do any imports and calls to eval I should be
safe right?

On Fri, Aug 17, 2012 at 7:09 AM, rusi  wrote:

> On Aug 17, 12:25 pm, Chris Angelico  wrote:
> > On Fri, Aug 17, 2012 at 12:27 PM, Steven D'Aprano
> >
> >  wrote:
> > > There is already awesome protocols for running Python code remotely
> over
> > > a network. Please do not re-invent the wheel without good reason.
> >
> > > See pyro, twisted, rpyc, rpclib, jpc, and probably many others.
> >
> > But they're all tools for building protocols. I like to make
> > line-based protocols
>
> Dont know if this is relevant.  If it is, its more in the heavyweight
> direction.
> Anyway just saw this book yesterday
>
> http://springpython.webfactional.com/node/39
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: remote read eval print loop

2012-08-21 Thread Eric Frederich
This isn't really for users.  It is for developers like me.
Yes it is a security hole but again, it is a debugger.

The people who will be using it can all ssh into the server machine with
the same ID that the server process is running on.
In fact, this is quite normal.

As it is right now, we log into these machines and start an interactive
Python and use the bindings to debug things.
This works well most of the time but when you do that you need to start
another session of the application.
It is useful to run code interactively from within an actual client session
where something has gone wrong.

In any case I got this working with a rudimentary SWT Java client
(yuck, but the application is based on Eclipse).

Below is the code I used.  It has a singleton interactive console object.
I sub-classed it and defined another method "process" which simply calls
the "push" method after wrapping stdout and stderr.
It returns anything that was printed to stdout, stderr, and the return
value of the "push" method.

So now from the client I can process one line at a time and it behaves much
like the real interactive console... you wouldn't even realize there is all
this client / server / WSDL / xml / https junk going on.

 BEGIN CODE

import sys
from code import InteractiveConsole

class MyBuffer(object):
def __init__(self):
self.buffer = []
def write(self, data):
self.buffer.append(data)
def get(self):
ret = ''.join(self.buffer)
self.buffer = []
return ret

class MyInteractiveConsole(InteractiveConsole):

def __init__(self, *args, **kwargs):
InteractiveConsole.__init__(self, *args, **kwargs)
self.mb_out = MyBuffer()
self.mb_err = MyBuffer()

def process(self, s):
sys.stdout, sys.stderr = self.mb_out, self.mb_err
more = self.push(s)
sys.stdout, sys.stderr = sys.__stdout__, sys.__stderr__
return self.mb_out.get(), self.mb_err.get(), more

print 'creating new interactive console'
mic = MyInteractiveConsole()


On Fri, Aug 17, 2012 at 10:06 AM, Chris Angelico  wrote:

> On Fri, Aug 17, 2012 at 11:28 PM, Eric Frederich
>  wrote:
> > Within the debugging console, after importing all of the bindings, there
> > would be no reason to import anything whatsoever.
> > With just the bindings I created and the Python language we could do
> > meaningful debugging.
> > So if I block the ability to do any imports and calls to eval I should be
> > safe right?
>
> Nope. Python isn't a secured language in that way. I tried the same
> sort of thing a while back, but found it effectively impossible. (And
> this after people told me "It's not possible, don't bother trying". I
> tried anyway. It wasn't possible.)
>
> If you really want to do that, consider it equivalent to putting an
> open SSH session into your debugging console. Would you give that much
> power to your application's users? And if you would, is it worth
> reinventing SSH?
>
> ChrisA
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


error importing smtplib

2012-11-15 Thread Eric Frederich
Hello,

I created some bindings to a 3rd party library.
I have found that when I run Python and import smtplib it works fine.
If I first log into the 3rd party application using my bindings however I
get a bunch of errors.

What do you think this 3rd party login could be doing that would affect the
ability to import smtp lib.

Any suggestions for debugging this further.  I am lost.

This works...

import smtplib
FOO_login()

This doesn't...

FOO_login()
import smtplib

Errors.

>>> import smtplib
ERROR:root:code for hash sha224 was not found.
Traceback (most recent call last):
  File "/opt/foo/python27/lib/python2.7/hashlib.py", line 139, in 
globals()[__func_name] = __get_hash(__func_name)
  File "/opt/foo/python27/lib/python2.7/hashlib.py", line 103, in
__get_openssl_constructor
return __get_builtin_constructor(name)
  File "/opt/foo/python27/lib/python2.7/hashlib.py", line 91, in
__get_builtin_constructor
raise ValueError('unsupported hash type %s' % name)
ValueError: unsupported hash type sha224
ERROR:root:code for hash sha256 was not found.
Traceback (most recent call last):
  File "/opt/foo/python27/lib/python2.7/hashlib.py", line 139, in 
globals()[__func_name] = __get_hash(__func_name)
  File "/opt/foo/python27/lib/python2.7/hashlib.py", line 103, in
__get_openssl_constructor
return __get_builtin_constructor(name)
  File "/opt/foo/python27/lib/python2.7/hashlib.py", line 91, in
__get_builtin_constructor
raise ValueError('unsupported hash type %s' % name)
ValueError: unsupported hash type sha256
ERROR:root:code for hash sha384 was not found.
Traceback (most recent call last):
  File "/opt/foo/python27/lib/python2.7/hashlib.py", line 139, in 
globals()[__func_name] = __get_hash(__func_name)
  File "/opt/foo/python27/lib/python2.7/hashlib.py", line 103, in
__get_openssl_constructor
return __get_builtin_constructor(name)
  File "/opt/foo/python27/lib/python2.7/hashlib.py", line 91, in
__get_builtin_constructor
raise ValueError('unsupported hash type %s' % name)
ValueError: unsupported hash type sha384
ERROR:root:code for hash sha512 was not found.
Traceback (most recent call last):
  File "/opt/foo/python27/lib/python2.7/hashlib.py", line 139, in 
globals()[__func_name] = __get_hash(__func_name)
  File "/opt/foo/python27/lib/python2.7/hashlib.py", line 103, in
__get_openssl_constructor
return __get_builtin_constructor(name)
  File "/opt/foo/python27/lib/python2.7/hashlib.py", line 91, in
__get_builtin_constructor
raise ValueError('unsupported hash type %s' % name)
ValueError: unsupported hash type sha512
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: error importing smtplib

2012-11-15 Thread Eric Frederich
Thanks for the idea.
sys.path was the same before and after the login

What else should I be checking?

On Thu, Nov 15, 2012 at 11:57 AM, Terry Reedy  wrote:

> On 11/15/2012 9:38 AM, Eric Frederich wrote:
>
>> Hello,
>>
>> I created some bindings to a 3rd party library.
>> I have found that when I run Python and import smtplib it works fine.
>> If I first log into the 3rd party application using my bindings however
>> I get a bunch of errors.
>>
>> What do you think this 3rd party login could be doing that would affect
>> the ability to import smtp lib.
>>
>
> I don't know what 'login' actually means,...
>
>
>  This works...
>>
>> import smtplib
>> FOO_login()
>>
>> This doesn't...
>>
>> FOO_login()
>> import smtplib
>>
>
> but my first guess is that FOO_login alters the module search path so that
> at least one of smtplib, hashlib, or the _xxx modules imported by hashlib
> is being imported from a different place. To check that
>
> import sys
> before = sys.path
> FOO_login()
> print sys.path==before
>
> Similar code can check anything else accessible through sys.
>
>
>  Errors.
>>
>>  >>> import smtplib
>> ERROR:root:code for hash sha224 was not found.
>>
>
> I am puzzled by this line before the traceback. I cannot find 'ERROR' in
> either smtplib or hashlib.
>
>
>  Traceback (most recent call last):
>>File "/opt/foo/python27/lib/**python2.7/hashlib.py", line 139, in
>> 
>>  globals()[__func_name] = __get_hash(__func_name)
>>File "/opt/foo/python27/lib/**python2.7/hashlib.py", line 103, in
>> __get_openssl_constructor
>>  return __get_builtin_constructor(**name)
>>File "/opt/foo/python27/lib/**python2.7/hashlib.py", line 91, in
>> __get_builtin_constructor
>>  raise ValueError('unsupported hash type %s' % name)
>> ValueError: unsupported hash type sha224
>>
> [snip similar messages]
>
> It is also unusual to get multiple tracebacks. *Exactly* how are you
> running python and is 2.7 what you intend to run?
>
> --
> Terry Jan Reedy
>
> --
> http://mail.python.org/**mailman/listinfo/python-list<http://mail.python.org/mailman/listinfo/python-list>
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: error importing smtplib

2012-11-15 Thread Eric Frederich
Sorry, only saw your first response, didn't see the others.

I compiled Python 2.7.2 myself with --enable-shared
To create standalone applications that interact with this 3rd party program
your main C file instead of having a "main" function has a FOO_user_main
function.
When you link your program you link against a provided foo_main.o file.

My python executable (called FOO_user_main) was created from python.c but
with main replaced with FOO_user_main no other differences.

I have been using this type of installation for a couple of years and
everything works fine.

I only get these errors/warnings on one environment out of 10 or so
development and qa machines.

Any help trying to figure out what is different before and after the login
would be appreciated.
Is there some place in /proc I could look to see what happened?

Thanks,
~Eric


On Thu, Nov 15, 2012 at 11:57 AM, Terry Reedy  wrote:

> On 11/15/2012 9:38 AM, Eric Frederich wrote:
>
>> Hello,
>>
>> I created some bindings to a 3rd party library.
>> I have found that when I run Python and import smtplib it works fine.
>> If I first log into the 3rd party application using my bindings however
>> I get a bunch of errors.
>>
>> What do you think this 3rd party login could be doing that would affect
>> the ability to import smtp lib.
>>
>
> I don't know what 'login' actually means,...
>
>
>  This works...
>>
>> import smtplib
>> FOO_login()
>>
>> This doesn't...
>>
>> FOO_login()
>> import smtplib
>>
>
> but my first guess is that FOO_login alters the module search path so that
> at least one of smtplib, hashlib, or the _xxx modules imported by hashlib
> is being imported from a different place. To check that
>
> import sys
> before = sys.path
> FOO_login()
> print sys.path==before
>
> Similar code can check anything else accessible through sys.
>
>
>  Errors.
>>
>>  >>> import smtplib
>> ERROR:root:code for hash sha224 was not found.
>>
>
> I am puzzled by this line before the traceback. I cannot find 'ERROR' in
> either smtplib or hashlib.
>
>
>  Traceback (most recent call last):
>>File "/opt/foo/python27/lib/**python2.7/hashlib.py", line 139, in
>> 
>>  globals()[__func_name] = __get_hash(__func_name)
>>File "/opt/foo/python27/lib/**python2.7/hashlib.py", line 103, in
>> __get_openssl_constructor
>>  return __get_builtin_constructor(**name)
>>File "/opt/foo/python27/lib/**python2.7/hashlib.py", line 91, in
>> __get_builtin_constructor
>>  raise ValueError('unsupported hash type %s' % name)
>> ValueError: unsupported hash type sha224
>>
> [snip similar messages]
>
> It is also unusual to get multiple tracebacks. *Exactly* how are you
> running python and is 2.7 what you intend to run?
>
> --
> Terry Jan Reedy
>
> --
> http://mail.python.org/**mailman/listinfo/python-list<http://mail.python.org/mailman/listinfo/python-list>
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: error importing smtplib

2012-11-16 Thread Eric Frederich
So I inspected the process through /proc//maps
That seemed to show what libraries had been loaded (though there is
probably an easier way to do this).

In any case, I found that if I import smtplib before logging in I see these
get loaded...

/opt/foo/python27/lib/python2.7/lib-dynload/_ssl.so
/lib64/libssl.so.0.9.8e

Then after logging in, I see this other .so get loaded...

/opt/bar/lib64/libssl.so.0.9.7

So that is what happens when when things are well and I don't get any error
messages.
However, when I do the log in first I see the /opt/bar .so file loaded first

/opt/bar/lib64/libssl.so.0.9.7

Then after importing smtplib I see the other two show up...

/opt/foo/python27/lib/python2.7/lib-dynload/_ssl.so
/lib64/libssl.so.0.9.8e

So I'm guessing the problem is that after I log in, the process has a
conflicting libssl.so file loaded.
Then when I try to import smtplib it tries getting things from there and
that is where the errors are coming from.

The question now is how do I fix this?




On Thu, Nov 15, 2012 at 4:37 PM, Terry Reedy  wrote:

> On 11/15/2012 1:48 PM, Eric Frederich wrote:
>
>> Thanks for the idea.
>> sys.path was the same before and after the login
>>
>
> Too bad. That seems to be a typical cause of import failure.
>
>
>  What else should I be checking?
>>
>
> No idea. You are working beyond my knowledge. But I might either look at
> the foo-login code carefully, or disable (comment out) parts of it to see
> what makes the import fail.
>
>
> --
> Terry Jan Reedy
>
> --
> http://mail.python.org/**mailman/listinfo/python-list<http://mail.python.org/mailman/listinfo/python-list>
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: error importing smtplib

2012-11-19 Thread Eric Frederich
I can do this in stand alone programs because my code does the import and
calls the login function so I can control the order of things.
Unfortunately stand alone programs are not the only ways in which I am
using these Python bindings.

You can customize and extend this 3rd party application at various
extension points all of which are invoked after login.
We have a lot of extensions written in Python.

I guess I will have to back to the BAR vendor and ask if it is okay to
remove their old .so file.
Perhaps their code will just work with the newer 0.9.8e or perhaps they'll
have to relink or recompile.

On Fri, Nov 16, 2012 at 5:00 PM, Terry Reedy  wrote:

> [easy] Do the import before the function call, which is the proper order
> and the one that works.
>
> --
> Terry Jan Reedy
>
> --
> http://mail.python.org/**mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


empty object from C

2012-12-07 Thread Eric Frederich
Hello,

>From C, I'd like to call a Python function that takes an object and sets
some attributes on it.
Lets say this is the function...

def foo(msg):
msg.bar = 123
msg.spam = 'eggs'

How do I create an empty object in C?
In Python I would do something like this...

class Msg(object):
pass

... and then instantiate an instance, and call the function.

msg = Msg()
foo(msg)



I know how to create an empty dictionary and I get get by with that, but
I'd like to create an object.

Thanks,
~Eric
-- 
http://mail.python.org/mailman/listinfo/python-list


problem with web browser module

2012-12-15 Thread Eric Johansson
I need to be able to invoke a specific webpage with Internet Explorer. 
If the browser is not up with that page, I needed to come up with that 
page. If the browser is already up, I only need to bring that browser 
and page to the top of the window piles.


When I use the web browser module today, it always seems to bring a new 
browser instance up. Is there anyway to get it to work with a single 
instance?


the use case is to invoke a specific evernote page and make it available 
for immediate dictation using speech recognition. There's a whole bunch 
of other things I need to do around the browser invocation but that's my 
problem and fortunately I know what I have to do.  I just need your help 
in making sure only a single browser instance is created and it 
references a single page. If I have multiple pages I need to refer to, 
it would be nice if they came up the separate tabs within the same 
browser instance.:-)


A clue or two would be welcome. Thanks

--- eric
--
http://mail.python.org/mailman/listinfo/python-list


Re: problem with web browser module

2012-12-16 Thread Eric Johansson

On Saturday, December 15, 2012 9:14:25 PM, Terry Reedy wrote:


I believe this worked with Firefox the last time I tested. I just read
the docs. Never tried IE. I believe details partly depend on browser.


thank you Terry. I will try with Firefox  but the main reason I'm using 
IE is simply because nuance has created a module  to make the text 
areas speech recognition friendly. So I will do some more work to find 
out how to make IE do what I needed it to do.


thank you again.


--
http://mail.python.org/mailman/listinfo/python-list


speaking at PyCon

2012-01-28 Thread Eric Snow
This is my first year speaking at PyCon, so I solicited
speaking/preparation advice from a bunch of folks, particularly
focusing on the PyCon speaking experience.  I've compiled the results
and put them online:

http://ref.rtfd.org/speakers

This is still rough, and feedback is welcome, as is more advice.  :)
For anyone speaking at the conference (or generally), I hope this will
be helpful.  Thanks!

-eric
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   3   4   5   6   7   8   9   10   >