mixing SWIG generated and Python-level usertype?

2005-02-01 Thread Bo Peng
Dear list,
My SWIG generated module (myModule) needs an array-like object (carray) 
to work. Carray objects are created both internally (in C++ level) and 
through Python so I have to load it when myModule initializes.

carray is modified from arraymodule.c and is quite simple:
static PyMethodDef a_methods[] =
{
  {"carray", a_array, METH_VARARGS, a_array_doc},
  {   /* sentinel */
NULL,NULL
  }
};
Currently, I load a_methods directly using code (error checking ignored)
  PyObject* mm = PyImport_AddModule("__main__");
  PyObject* dict = PyModule_GetDict(mm);
  PyObject*  v = PyCFunction_New(a_methods, NULL);
  PyDict_SetItemString(dict, a_methods->ml_name, v);
There are several problems with this approach:
1. use of __main__? carray can not be accessed directly within other 
libraries. ('from myModule import *' DOES NOT import carray!) I tried to 
use __builtins__ but it does not work for some reason out of my 
understanding of Python. I am not sure how to add carray to myModule 
dictionary.

2. No type object? I am not sure what is the purpose of ArrayType but 
the usual init_module should be
m = Py_InitModule3("carray", a_methods, module_doc);
d = PyModule_GetDict(m);
PyDict_SetItemString(dict, "ArrayType", (PyObject *)&Arraytype);

When I add ArrayType to __main__ , access to ArrayType leads to a quick 
core dump.

I do not feel comfortable with my current approach. Could anyone tell me 
some better (more standard) way?

Many thanks in advance.
Bo
--
http://mail.python.org/mailman/listinfo/python-list


Re: how to separate hexadecimal

2005-02-01 Thread Paul Rubin
jrlen balane <[EMAIL PROTECTED]> writes:
> ex. hexa = '0x87BE"  # what i want to do is:
>   a = 0x87, b = 0xBE# so that i could do this:
>   c = a + b#which should be equal to 0x145

Assuming you really want hexa to begin with the characters '0x', the
string slicing way is:

a, b = hexa[2:4], hexa[4:6]   # a = '87', b = 'BE'
c = int(a,16) + int(b, 16)

A more direct arithmetic way is:

   x = int(hexa, 16) # x = the integer 0x87be
   c = (x >> 8) + (x & 0xff)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to separate hexadecimal

2005-02-01 Thread Nick Coghlan
jrlen balane wrote:
i have a 4 digit hex number (2 bytes) and i want to separate it into 2
digit hex (1 byte each) meaning i want to get the upper byte and the
lower byte since i am going to add this two.
how am i going to do this?
should i treat it just like a normal string?
please help, thanks.
ex. hexa = '0x87BE"  # what i want to do is:
  a = 0x87, b = 0xBE# so that i could do this:
  c = a + b#which should be equal to 0x145
divmod does what you want:
Py> val = 0x87be
Py> hi, lo = divmod(val, 0x100)
Py> hex(hi), hex(lo)
('0x87', '0xbe')
Py> hex(hi + lo)
'0x145'
Cheers,
Nick.
--
Nick Coghlan   |   [EMAIL PROTECTED]   |   Brisbane, Australia
---
http://boredomandlaziness.skystorm.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: type of simple object

2005-02-01 Thread Pierre Barbier de Reuille
[EMAIL PROTECTED] a écrit :
Thank you guys.
My function should multiply every element  of a list, for example
"something"
and "something" can be an integer or another list.
If it deals with integer than it is ok, but
If it deals with list than it become false for example list*2 =
listlist, and what I really want is to mutlitply its member.
That's why I need to know the type of my data in "something".
As stated by another comment, I would do something like :
def multiply(object, factor):
  try:
return [ multiply(i,factor) for i in object ]
  except TypeError:
return object*factor
This function will, recursively multiply a nested list of numbers by 
"factor" ...

By the way I am new in python, I heard that it has a MatLab
capabilities, How good is that? Since It would be very nice when we can
do what MatLab do in python.
I think you are referring to the Numeric or the numarray modules. They 
offer matric computations close to chat Matlab offers. "numarray" is the 
newer version of "Numeric", but in case of small matrix, it performs 
slower (for various reasons). Then, you can find lots of information on 
the net concerning these two modules.


Sincerely Yours,
pujo
Pierre
--
http://mail.python.org/mailman/listinfo/python-list


how to separate hexadecimal

2005-02-01 Thread jrlen balane
i have a 4 digit hex number (2 bytes) and i want to separate it into 2
digit hex (1 byte each) meaning i want to get the upper byte and the
lower byte since i am going to add this two.
how am i going to do this?
should i treat it just like a normal string?
please help, thanks.

ex. hexa = '0x87BE"  # what i want to do is:
  a = 0x87, b = 0xBE# so that i could do this:
  c = a + b#which should be equal to 0x145
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How do you do arrays

2005-02-01 Thread Erik Max Francis
Dennis Lee Bieber wrote:
Classic BASIC actually splits the difference.
dim a(10)
allocates 11 elements, indexed 0..10 -- but most classes tend to ignore
element 0, and algorithms are as if only 10 elements exist starting at
1.
Basic also has the OPTION BASE instruction, which affects that.
--
Erik Max Francis && [EMAIL PROTECTED] && http://www.alcyone.com/max/
San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis
  War is like love, it always finds a way.
  -- Bertolt Brecht
--
http://mail.python.org/mailman/listinfo/python-list


Re: a quick question about namespaces

2005-02-01 Thread Steven Bethard
Jay donnell wrote:
in the code below 'print locals()' shows mc2. What is the equivalent
way to see the namespace that mc resides in?
class myClass:
--def func1(self):
self.mc = 1
mc2 = 3
print 'in myClass.func1'
print 'printing locals'
print locals()
print
I think you're looking for vars(self) or self.__dict__:
py> class MyClass(object):
... def func1(self):
... self.mc = 1
... mc2 = 3
... print locals()
... print vars(self)
... print self.__dict__
...
py> MyClass().func1()
{'self': <__main__.MyClass object at 0x027D8550>, 'mc2': 3}
{'mc': 1}
{'mc': 1}
HTH,
Steve
--
http://mail.python.org/mailman/listinfo/python-list


Re: variable declaration

2005-02-01 Thread Eric Pederson
"Thomas Bartkus" wrote

> As has been pointed out, it's not a big deal for a programmer who's 
> been
> there, done that. But the original posters example is a beginners trap 
> for
> certain.
> 
> *If* Python were a "beginners language", then it would be missing one 
> of
> it's training wheels.


If you put training wheels on your bicycle, it's not going to be any good for 
moderately serious cycling.  The OP was clearly not new to programming, and it 
was a hypothetical problem.

We're all adults here (even my 12 year old!) - and we have only beginners in my 
house.  This purported wart has never bothered me  -- Python is so friendly to 
develop in.  If this sort of code error bites my 12 year old, I'm sure he will 
be able to find it and feel good about fixing it.  It's not the kind of code 
error that has you shutting down your computer at 4AM, perplexed and frustrated 
- those feelings are usually attributable to subtle, complex, dastardly 
language features (unexpected behavoirs).  Just my opinion, of course.

Among the great and enlightening posts in this thread, I liked this:

QOTW?
"""We should concentrate on *real* problems, ones that exist in real code, not 
ones that mostly
exist in wild-eyed prose that consists of predictions of pain and death
that conspicuously fail to occur, no matter how many times they are
repeated or we are exhorted to heed them or face our doom. """

http://groups-beta.google.com/group/comp.lang.python/messages/178fef06830cc779?thread_id=a75da70b0845b6fe&mode=thread&noheader=1#doc_178fef06830cc779


[Go PyPy!]



Eric Pederson
http://www.songzilla.blogspot.com

:::
domainNot="@something.com"
domainIs=domainNot.replace("s","z")
ePrefix="".join([chr(ord(x)+1) for x in "do"])
mailMeAt=ePrefix+domainIs
:::

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


Re: Where are list methods documented?

2005-02-01 Thread Bryan
Skip Montanaro wrote:
Grant> where are the methods of basic types documented?  

The other day I suggested the most valuable doc page to bookmark is the
global module index.  Here's a demonstration.  Start at:
http://www.python.org/dev/doc/devel/modindex.html
Click "__builtin__", which takes you to
http://www.python.org/dev/doc/devel/lib/module-builtin.html
Click the "2" in "See Chapter 2", which takes you to
http://www.python.org/dev/doc/devel/lib/builtin.html#builtin
Scroll down to section 2.3.6 and choose your sequence poison.
I use the dev docs instead of the latest release docs because I generally
run from CVS on my system, however in this case it has the added advantage
that the link on the __builtin__ page is more useful.
Skip


wow, that's pretty obscure.  i barely even saw the link to chapter 2.  i always 
the modules index page open and i always wished there was an explicit link to 
lists, tuples, dict, set, etc.  maybe these explicit links could be at the top 
of the __builtins__ page.

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


Re: Newbie Question

2005-02-01 Thread Robey Holderith
On Tue, 01 Feb 2005 17:47:39 -0800, Joel Eusebio wrote:

> 
> Hi Everybody,
> 
> I'm pretty new to Python and would like to ask a few questions. I have this
> setup on a Fedora Core 3 box.
> 
> Python 2.3.4
> wxPython-common-gtk-ansi-2.5.3.1-fc2_py2.3
> mod_python-3.1.3-5
> Apache/2.0.52
> 
> I have a test.py which looks like this:
> from mod_python import apache
> def handler(req):
>req.write("Hello World!")
>return apache.OK
> 

This code looks like you are attempting to define a handler.  In this case
the handler needs to be properly set up in either your httpd.conf or a
.htaccess (assuming your configuration allows for that).

> Whenever I access test.py from my browser it says "The page cannot be found"
> , I have the file on /var/www/html, what did I miss?

You don't access handlers like you do CGI.  This problem likely lies in
your configuration and not in your code.  I would look at mod_python's
documentation some more and probably start with mod_python's
PublisherHandler for initial testing and experimentation.

-Robey Holderith

>  Thanks in advance,
> Joel


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


Re: Python Code Auditing Tool

2005-02-01 Thread Robey Holderith
On Tue, 01 Feb 2005 21:52:28 -0800, Paul Rubin wrote:

> Robey Holderith <[EMAIL PROTECTED]> writes:
>> Does anybody know of a tool that can tell me all possible exceptions that
>> might occur in each line of code?  What I'm hoping to find is something
>> like the following:
> 
> That is impossible.  The parameter to the raise statement is a class
> object, which can be anything.  I.e. you could say:
> 
>class ex1: pass
>class ex2: pass
> 
>if something(): my_ex = ex1
>else: my_ex = ex2
> 
>raise my_ex# static tool can't know what exception gets raised here.

I suppose that I am willing to lessen my expectations from _all_ to most.
;-) Regarding your example I could also do:

if something():
def nothing(): return 0
else:
def nothing(): return 1

But this doesn't stop IDEs from attempting to do auto-completion.  I'm not
trying to find hidden exceptions... just trying to easily get an idea of
what could go wrong on each line of code.

-Robey Holderith

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


How run valgrind on Python C extensions?

2005-02-01 Thread [EMAIL PROTECTED]
I have Python C extensions that are giving me seg faults that I'd
like to run valgrind on.

Can I use valgrind on these through python??  HOW???

Is it easy or must I do some work like recompiling python source
with the -g extension?

Thanks!

Chris

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


a quick question about namespaces

2005-02-01 Thread Jay donnell
in the code below 'print locals()' shows mc2. What is the equivalent
way to see the namespace that mc resides in?


class myClass:
--def func1(self):
self.mc = 1
mc2 = 3
print 'in myClass.func1'
print 'printing locals'
print locals()
print

Google mungs up the spacing so I put a - in place of spaces. Does
anyone know how to get around this spacing issue on google groups?

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


Re: curl and popen2

2005-02-01 Thread Robey Holderith
On Tue, 01 Feb 2005 17:48:53 -0800, lists04 wrote:

> Hi,
> 
> I have a problem with a curl request and running it under popen2.
> 
> If I run this request from the command line:
> curl -i http://www.yahoo.com/test --stderr errfile
> (also tried redirecting stdderr to a file 2>, nothing) the file errfile
> is empty indicating no error with the request.
> 
> However, when I do something similar in python:
 cmd="curl -i http://www.yahoo.com/test";
 output, input, err = popen2.popen3(cmd)
 error = err.readlines()
 error
> ['  % Total% Received % Xferd  Average Speed  Time
> Curr.\n', ' Dload  Upload Total
> Current  LeftSpeed\n', '\r100   9810   9810 0  24525
> 0 --:--:--  0:00:00 --:--:-- 24525\r100  24840  24840 0
> 62100  0 --:--:--  0:00:00 --:--:-- 1467k\n']
> 
> I looked in the man page for curl, it doesnt say that it writes some
> bandwidth statistics to stderr. Am I missing something or is this
> better directed to some other newsgroup? 
> 

Many of the more "sophisticated" command line applications use stderr to
write things that are intended directly for the user's eyes.  The idea is
that it is often useful to have the file itself be written to stdout so
that pipes can be used, but the user still needs to see what is going on. 
Try using "curl --silent -i http://www.yahoo.com/test";.  That should turn
off all of the "user-friendly" updates to stderr.

-Robey Holderith

> TIA
> 
> Hari


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


Re: Python Code Auditing Tool

2005-02-01 Thread Paul Rubin
Robey Holderith <[EMAIL PROTECTED]> writes:
> Does anybody know of a tool that can tell me all possible exceptions that
> might occur in each line of code?  What I'm hoping to find is something
> like the following:

That is impossible.  The parameter to the raise statement is a class
object, which can be anything.  I.e. you could say:

   class ex1: pass
   class ex2: pass

   if something(): my_ex = ex1
   else: my_ex = ex2

   raise my_ex# static tool can't know what exception gets raised here.
-- 
http://mail.python.org/mailman/listinfo/python-list


Python Code Auditing Tool

2005-02-01 Thread Robey Holderith
Does anybody know of a tool that can tell me all possible exceptions that
might occur in each line of code?  What I'm hoping to find is something
like the following:

given all necessary python source and a given line ( my.py:40 ) it would
generate a list of possible exception classes sorted by function
(preferably in a tree).

Example:
--

my.py:40 |parsestring(genstring())

Possible Exceptions:

-def parsestring():
  InvalidCharacterException
  EmptyStringException
  -class string, def split():
(All Exceptions that might occur directly in string.split() that are
not caught by parsestring())
(All functions called by string.split() and their exceptions and sub-
functions)
-def genstring():
  SomeException
  ...



This would be extremely useful for deciding how to write try: except
blocks and in figuring out what all possible errors that might occur would
be.

-Robey Holderith

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


Tkinter on dual screen

2005-02-01 Thread nik
hello,

i am writing an app which is running on a dual screen setup on windows
and OS X. is anyone doing this using Tkinter? are there problems with
it?

i know Tk() takes a "screenname" argument which specifies the screen.
but i am not sure about how well Tkinter copes with having two Tk
objects and i could not find any documentation as to what the screens
are called.

- what are the screen names for screen 1 / 2 on windows / linux / OS X?
- is there a Tk command that can check for multiple screens? ideally i
would like something like
names = getScreenNames()
that tells me how many screens there are and what they are called. then
i could write my app so that it runs on any OS and with any number of
screens. all the examples i have seen so far rely on a
platform-specific name which seems to come out of nowhere...
- are you running dual screen Tkinter and is it working? what are the
pitfalls?

thanks for any help!

nik

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


how to use python scripts in zope3

2005-02-01 Thread vijay
hi
Recently i started learning zope3 framework.
Unlike in zope2.7 , there is no Script(Python) component
in the addlist of zope3.
Also by inserting scripts in zpt it gives me error.
Somebody help me in using python script in zope3.
Thank you.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: hotspot profiler experience and accuracy?

2005-02-01 Thread Jeremy Bowers
On Tue, 01 Feb 2005 19:24:20 -0800, aurora wrote:

> I have a parser I need to optimize. It has some disk IO and a lot of
> looping over characters.
> 
> I used the hotspot profiler to gain insight on optimization options. The
> methods show up on on the top of this list seems fairly trivial and does
> not look like CPU hogger. Nevertheless I optimized it and have 25%
> performance gain according to hotspot's number.

I can't answer your other question, but general optimization advice, since
I've been in this situation a couple of times: Generally, you're not
going to win in an interpreted language like Python* looping over all
chars. You should either eliminate those loops if possible, or move the
guts of the looping into regular expressions, which are designed to do
that sort of thing as optimally as possible. (I've never looked at the
internals, but I believe the "compile()" function in the re module isn't
just a way of conveniently sticking a regex into a variable; you are
actually creating a compiled and reasonably optimized (as long as you
don't get crazy) character scanner that you simply Can Not beat in pure
Python.)

As a last-ditch scenario, you could go to a C extension, but regexs should
be good enough, and only beatable in the simplest of cases.

Write good REs (you could ask for help, but you should probably just test
it yourself; the key thing to try for, I think, is to put as much into one
RE as possible and ask the match object which thing matched but I may be
wrong; more experienced comments welcomed), and then run the profiler
again.

In general though, the precise numbers coming out of the profiler are less
important than their relationships; as long as the relationships are
maintained the data is still good.

*: At current technology levels. Yes, someday optimization will make
looping over characters in Python even faster than C, or so the theory
goes. That's not today, or even tomorrow, though.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Next step after pychecker

2005-02-01 Thread Steven Bethard
Terry Reedy wrote:
> Nothing about bytecode is part of the language spec.  And CPython
> bytecode is version specific.  If the CPython implementation changed
> from a virtual stack machine to a virtual register machine, as was
> once discussed, the stack-oriented byte code would be replaced by a
> register-oriented byte code or virtual machine language.
Thanks for the clarification.  I knew the byte-code changed from version 
to version, but of course so does the language, so that didn't tell me 
much. ;)  So I assume the language spec is basically the grammar and the 
Language Reference docs[1]?  Or is there something more formal?

Steve
[1] e.g. http://docs.python.org/ref/ref.html
--
http://mail.python.org/mailman/listinfo/python-list


Re: getting data from a port in use

2005-02-01 Thread Grant Edwards
On 2005-02-02, Dana Marcusanu <[EMAIL PROTECTED]> wrote:

> Yes. I want to write a very small web sniffer that gets data
> from a specified port.

OK, know we know what you're actually trying to do.  You should
have told us that to start with rather than leading us down the
wrong path with your little Python program.  When asking for
help, always clearly describe your _problem_ first.  Asking
what's wrong with a proposed solution without clearly
describing the problem you're trying to solve just wastes time:

http://www.catb.org/~esr/faqs/smart-questions.html

> I already looked at some of the existing ones on Internet, but
> they are not in Python (I am trying to learn Python!)

You picked a rather tricky little project.

> and they have a lot more features that I want. Thanks for your
> suggestion. I will check out pcap library.

Pcap is your only hope unless you want to do a lot of rather
nasty low level stuff (for which you'll probably have to write
a bunch of C code that does all the things that libpcap does).

You can't use the normal Python socket API to sniff data.  

You _could_ use popen to run tcpdump (which in turn uses pcap)
and then parse the output from pcap. I've done both, and IMO
using pcap directly is a lot easier.  It's also your only hope
of keeping up with any amount of traffic.

http://sourceforge.net/projects/pylibpcap
http://sourceforge.net/project/showfiles.php?group_id=14007&package_id=13826

Once upon a time, there was a rumor that somebody had a Win32
version of pylibpcap.

Good luck.  :)

-- 
Grant Edwards   grante Yow!  Did an Italian CRANE
  at   OPERATOR just experience
   visi.comuninhibited sensations in
   a MALIBU HOT TUB?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: web camera or else ? 15-30 fps processing of camera videos.

2005-02-01 Thread M.E.Farmer
JGCASEY wrote:
> The Artist Formerly Known as Kap'n Salty wrote:
> > Newbie wrote:
> > > I am doing some robotics projects but my main area of interest is
> > > trying out several algorithms for the processing of the stream of
> data
> > > coming from the video.
> > >
> > > I am wondering what type of camera I should invest in. Either I
> could
> > > buy a web cam and hope I can find a driver I could either modify
or
> > > use. i.e. every frame is somehow stored on the computer
> automagically
> > > or I could buy a camera not unlike the AVRcam
> > > (http://www.jrobot.net/Projects/AVRcam.html) or the CMUcam and
try
> to
> > > do the processing once the data has been streamed to the nearest
> > > computer ? or should I use an expensive video card, some CCTV
> camera
> > > and a frame grabber to digitize photos so they can be processed
> > > afterwards. I expect my processing algorithms to handle at least
15
> > > frames per second framerate once they are working ont the final
> set-up.
> > >
> > > My constraints are that I would like to avoid as much as possible
> > > complex set-ups even if that means buying a more expensive camera
> > > set-up. For the prototyping, I would like to try my algorithms
out
> > > using a combination of python and matlab (all very slow) and then
> > > expect the same architecture (image files location and flow) with
> > > speedier set-up like python+psyco or C. All the processing would
be
> > > done on a computer dedicated for that. Windows or Linux are
> possible.
> > >
> >
> > An easy approach to this is to use a wireless camera on your robot,
> with
> > the receiver attached to a frame grabber on a remote host. This
> allows
> > you your choice of camera (stand alone video transmitters are
widely
> > available), and you are not limited to only processing hardware you
> can
> > carry on board your robot. You also get full FPS. Frame-grabber
cards
>
> > are inexpensive and widely available for both Windows and Linux.
>
> I wanted to go down that path but cannot get
> information on how to access the images from
> the tv receiver card in real time using my
> own software.
>
> Do you use Java?
>
> John Casey
Ever do search on Google?
This was number 1 and 2 ;). I searched for "python video capture".
I have used this module and it works well, it also has a really nifty
ftp uploader demo script.
http://videocapture.sourceforge.net/

hth,
M.E.Farmer

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


Re: getting data from a port in use

2005-02-01 Thread Grant Edwards
On 2005-02-02, Dana Marcusanu <[EMAIL PROTECTED]> wrote:

> Yes. It hangs at accept. I always end up doing end task
> because it never passes the "accept" statement.

And you're sure that somebody tries to initiate a connection
after your program has gotten to the accept() line? 

> When I set the port I use netstat (netstat -bn) to get the
> ports that are in use.

What do you mean by  a port being "in use"?  Is there another
program already waiting for a connection on the port?  You keep
repeating the bit about "ports in use", but that phrase is too
vague.  Do you mean there is already an established connection
that uses that port?  If that's what you mean, it doesn't
matter one way or another.  What matters is whether there's
another program already bound to that port and listening for
new connections.

As I've already said: if you're trying to get data from already
established connections, you can't do it using accept.  You
have to use the pcap library.

You're going to have to accurately describe what you're trying
to do, or none of us are going to be able to help you.

-- 
Grant Edwards   grante Yow!  HERE!! Put THIS
  at   on!! I'm in CHARGE!!
   visi.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Where are list methods documented?

2005-02-01 Thread Hans Nowak
Nick Craig-Wood wrote:
Since I'm a unix person, I would have typed
  pydoc -k sort
But it doesn't come up with anything useful :-(
FYI, you can get this info using the not-very-intuitive
  pydoc __builtin__.list.sort
e.g.
(C:\Python23\Lib) $ pydoc __builtin__.list.sort
Help on method_descriptor in __builtin__.list:
__builtin__.list.sort = sort(...)
L.sort(cmpfunc=None) -- stable sort *IN PLACE*; cmpfunc(x, y) -> 
-1, 0, 1

(Rather terse...)
Info on the sort function (together with all the other list methods) is 
also available if you do

  pydoc list
...but for some reason, "pydoc list.sort" doesn't work on my machine 
(Python 2.3.4, Windows XP).

--
Hans Nowak
http://zephyrfalcon.org/
--
http://mail.python.org/mailman/listinfo/python-list


RE: getting data from a port in use

2005-02-01 Thread Tony Meyer
>>> I am trying to use Python to get the data received at a 
>>> specific port (in use) on my computer. I already tried below
>>> code which seems to hang at the statement accepting
>>> connections. 
>
> Yes. It hangs at accept. I always end up doing end task 
> because it never passes the "accept" statement.

What do you get from wherever you are trying to connect to the port (e.g.
telnet).  Does it connect, or fail to connect?

Note that (as others have said) if you are trying to intercept data from an
existing socket connection, this is not the way to do it.  (This will let
you use a port that another process has already claimed, and accept new
connections to it).

=Tony.Meyer

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


getting data from a port in use

2005-02-01 Thread Dana Marcusanu
Yes. I want to write a very small web sniffer that gets data from a
specified port. I already looked at some of the existing ones on Internet,
but they are not in Python (I am trying to learn Python!) and they have a
lot more features that I want. Thanks for your suggestion. I will check
out pcap library.

Dana

On 2005-02-01, Dana Marcusanu <[EMAIL PROTECTED]> wrote:

> I am trying to use Python to get the data received at a specific port
(in
> use) on my computer.

What do you mean "in use"? You mean you want to evesdropt on
data that's being sent to an existing connection?  If so,
you'll need to use something like the pcap library.

> I already tried below code which seems to hang at the
> statement accepting connections. I don't know what else I can try. Any
> suggestions will be welcome.

> import socket, select, os

> PORT = 2005
> s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
> s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
> s.bind((socket.gethostname(), PORT))
> s.listen(1)
> work_socket, addr = s.accept()
> data = s.recv(1024)

No matter what you're trying to do, this isn't right.  Once the
connection has been accepted, you have to read data from the
socket returned by the accept() call.

> print data
> s.close()

-- 
Grant Edwards   grante Yow!  Actually, what
  at   I'd like is a little
toy
   visi.comspaceship!! 



__ 
Do you Yahoo!? 
Yahoo! Mail - 250MB free storage. Do more. Manage less. 
http://info.mail.yahoo.com/mail_250
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Suggesion for an undergrad final year project in Python

2005-02-01 Thread Terry Reedy

"Sridhar" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Hi,
>
> I am doing my undergrade CS course.  I am in the final year, and would
> like to do my project involving Python.  Our instructors require the
> project to have novel ideas.  Can the c.l.p people shed light on this
> topic?

Some months ago, maybe a year ago, Brett Cannon asked on the Py-Dev mailing 
list a similar question about a CS master's thesis.  He got around 10 
sensible suggestions.  Perhaps a few could be scaled down to a senior 
thesis level.  In any case, you could check the archives at www.python.com 
of the pydev summaries that he prepares every two weeks ago.

Terry J. Reedy



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


hotspot profiler experience and accuracy?

2005-02-01 Thread aurora
I have a parser I need to optimize. It has some disk IO and a lot of  
looping over characters.

I used the hotspot profiler to gain insight on optimization options. The  
methods show up on on the top of this list seems fairly trivial and does  
not look like CPU hogger. Nevertheless I optimized it and have 25%  
performance gain according to hotspot's number.

But the numbers look skeptical. Hotspot claim 71.166 CPU seconds but the  
actual elapsed time is only 54s. When measuring elapsed time instead of  
CPU time the performance gain is only 13% with the profiler running and  
down to 10% when not using the profiler.

Is there something I misunderstood in reading the numbers?
--
http://mail.python.org/mailman/listinfo/python-list


RE: getting data from a port in use

2005-02-01 Thread Dana Marcusanu
Yes. It hangs at accept. I always end up doing end task because it never
passes the "accept" statement. When I set the port I use netstat (netstat
-bn) to get the ports that are in use. I use PythonWin 2.4. I am still
puzzled about the fact that it runs fine for you.
You are right about using the work_socket instead of s. My program never
ran to that line so I did not notice the error.

Thank you, Dana
--- Tony Meyer <[EMAIL PROTECTED]> wrote:

> > I am trying to use Python to get the data received at a 
> > specific port (in use) on my computer. I already tried below
> > code which seems to hang at the statement accepting
> > connections. 
> 
> Seems to hang, or does hang?  Using print statements will tell you
> whether
> that's where it's getting stuck or not.
> 
> > I don't know what else I can try. Any
> > suggestions will be welcome.
> > 
> > import socket, select, os 
> > 
> > PORT = 2005
> > s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
> > s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) 
> > s.bind((socket.gethostname(), PORT))
> > s.listen(1)
> > work_socket, addr = s.accept() 
> > data = s.recv(1024)
> [...]
> 
> This should be 'data = work_socket.recv(1024)'.
> 
> This script works for me with that change.  (i.e. I can run it with port
> 2005 already in use, connect to the port, and it will finish without
> error).
> 
> =Tony.Meyer
> 
> 




__ 
Do you Yahoo!? 
Take Yahoo! Mail with you! Get it on your mobile phone. 
http://mobile.yahoo.com/maildemo 
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: getting data from a port in use

2005-02-01 Thread Dana Marcusanu

--- Tony Meyer <[EMAIL PROTECTED]> wrote:

> > I am trying to use Python to get the data received at a 
> > specific port (in use) on my computer. I already tried below
> > code which seems to hang at the statement accepting
> > connections. 
> 
> Seems to hang, or does hang?  Using print statements will tell you
> whether
> that's where it's getting stuck or not.
> 
> > I don't know what else I can try. Any
> > suggestions will be welcome.
> > 
> > import socket, select, os 
> > 
> > PORT = 2005
> > s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
> > s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) 
> > s.bind((socket.gethostname(), PORT))
> > s.listen(1)
> > work_socket, addr = s.accept() 
> > data = s.recv(1024)
> [...]
> 
> This should be 'data = work_socket.recv(1024)'.
> 
> This script works for me with that change.  (i.e. I can run it with port
> 2005 already in use, connect to the port, and it will finish without
> error).
> 
> =Tony.Meyer
> 
> 


__
Do You Yahoo!?
Tired of spam?  Yahoo! Mail has the best spam protection around 
http://mail.yahoo.com 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Next step after pychecker

2005-02-01 Thread Terry Reedy

"Steven Bethard" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> I don't know much about what pychecker does, but if it works with the 
> bytecode, shouldn't it be fine for jython and IronPython?  I thought the 
> bytecode was part of the language spec, and what was CPython specific was 
> how the bytecodes were actually implemented...

Nothing about bytecode is part of the language spec.  And CPython bytecode 
is version specific.  If the CPython implementation changed from a virtual 
stack machine to a virtual register machine, as was once discussed, the 
stack-oriented byte code would be replaced by a register-oriented byte code 
or virtual machine language.

Jython compiles Python code to JVM (Java Virtual Machine) bytecode.  Parrot 
compile to Parrot bytecode.  Ironman compiles, I presume, to .Net CL or 
whatever it's called.

Terry J. Reedy



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


Re: Next step after pychecker

2005-02-01 Thread Skip Montanaro

Francis> "Every well-formed expression of the language can be assigned a
Francis> type that can be deduced from the constituents of the
Francis> expression alone." Bird and Wadler, Introduction to Functional
Francis> Programming, 1988

Francis> This is certainly not the case for Python since one and the
Francis> same variable can have different types depending upon the
Francis> execution context. Example :

Francis> 1- if a is None:
Francis> 2-   b = 1
Francis> 3- else:
Francis> 4-   b = "Phew"
Francis> 5- b = b + 1

Francis> One cannot statically determine the type of b by examining the
Francis> line 5- alone.

Do you have an example using a correct code fragment?  It makes no sense to
infer types in code that would clearly raise runtime errors:

>>> "Phew" + 1
Traceback (most recent call last):
  File "", line 1, in ?
TypeError: cannot concatenate 'str' and 'int' objects

Also, note that the type assigned to an expression may be nothing more than
"object".  Clearly that wouldn't be very helpful when trying to write an
optimizing compiler, but it is a valid type.

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


Re: [perl-python] string pattern matching

2005-02-01 Thread Erik Max Francis
Daniel Fackrell wrote:
It seems to me that application of one of these solutions reduces the
effectiveness of the other.  If enough persons killfile the threads, who
warns the newbies?  And so those who don't killfile the threads to ensure
that somebody is still guarding against misleading information to newbies
continue dealing with it manually.
My point was, a sufficiently persistent pest will always generate enough 
dissatisfaction to get people pointing out his uselessness.  Even when 
others killfile him, there will be those that stick around to point out 
his foolishness to others, including any newbies who might otherwise 
conclude that Xah Lee knows what the hell he's talking about.

And, in fact, that's exactly what we're seeing.  It just seems to me 
that any further institutionalization of criticism of Xah Lee's posts is 
unnecessary; it's already being handled, at low levels of annoyance that 
can be avoided by anyone with a killfile or mail filter.

--
Erik Max Francis && [EMAIL PROTECTED] && http://www.alcyone.com/max/
San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis
  Divorces are made in Heaven.
  -- Oscar Wilde
--
http://mail.python.org/mailman/listinfo/python-list


Re: Where are list methods documented?

2005-02-01 Thread Skip Montanaro

Grant> where are the methods of basic types documented?  

The other day I suggested the most valuable doc page to bookmark is the
global module index.  Here's a demonstration.  Start at:

http://www.python.org/dev/doc/devel/modindex.html

Click "__builtin__", which takes you to

http://www.python.org/dev/doc/devel/lib/module-builtin.html

Click the "2" in "See Chapter 2", which takes you to

http://www.python.org/dev/doc/devel/lib/builtin.html#builtin

Scroll down to section 2.3.6 and choose your sequence poison.

I use the dev docs instead of the latest release docs because I generally
run from CVS on my system, however in this case it has the added advantage
that the link on the __builtin__ page is more useful.

Skip



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


Re: a sequence question

2005-02-01 Thread Nick Coghlan
Steven Bethard wrote:
I think you can write that second one so that it works for iterables 
without a __len__:

py> def padded_partition(iterable, part_len, pad_val=None):
... itr = itertools.chain(
... iter(iterable), itertools.repeat(pad_val, part_len - 1))
... return itertools.izip(*[itr]*part_len)
...
py> list(padded_partition(itertools.islice(itertools.count(), 10), 2))
[(0, 1), (2, 3), (4, 5), (6, 7), (8, 9)]
py> list(padded_partition(itertools.islice(itertools.count(), 10), 3))
[(0, 1, 2), (3, 4, 5), (6, 7, 8), (9, None, None)]
I just unconditionally pad the iterable with 1 less than the partition 
size...  I think that works right, but I haven't tested it any more than 
what's shown.
I think you're right - I was looking at padding unconditionally, but because I 
was padding with the actual partition length, it didn't work correctly when the 
padding wasn't needed.

Padding with one less than the partition length fixes that quite neatly.
Cheers,
Nick.
--
Nick Coghlan   |   [EMAIL PROTECTED]   |   Brisbane, Australia
---
http://boredomandlaziness.skystorm.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: test_socket.py failure

2005-02-01 Thread Nick Coghlan
[EMAIL PROTECTED] wrote:
 At the interactive python prompt i did/got the following:
	bash-2.04$ ./python 
	Python 2.4 (#1, Jan 29 2005, 10:31:35) 
	[GCC 2.95.3 20010315 (release)] on linux2
	Type "help", "copyright", "credits" or "license" for 
	   more information.
	>>> import socket
	>>> socket.getservbyname('daytime', 'tcp')
	13
	
	 # The 13 looks ok but look what happen 
	 # when i asked only for the service, like
	 # the line that fails in test_socket.
	
	>>> socket.getservbyname('daytime')   
	Traceback (most recent call last):
	  File "", line 1, in ?
	socket.error: service/proto not found
	>>>
Hmm, when the second argument is omitted, the system call looks like:
getservbyname("daytime", NULL);
Based on "man getservbyname" on my Linux PC, that should give the behaviour we 
want - any protocol will match.

However:
Linux 2.6.4-52-default (Suse 9.1)
Glibc 2.3.3
gcc   3.3.3
So it may be that your older platform doesn't have this behaviour - I'd be very 
interested in what 'man getservbyname' has to say.

Cheers,
Nick.
--
Nick Coghlan   |   [EMAIL PROTECTED]   |   Brisbane, Australia
---
http://boredomandlaziness.skystorm.net
--
http://mail.python.org/mailman/listinfo/python-list


Python checkin driver version on windows

2005-02-01 Thread Chris Jameyson
Is there a way to check driver version information on windows through
Python?  

I'd like to pull driver version, digital sig from the same place that
'device manager' gets it's information.


I tried using file system object, but seems like GetFileVersion()
from version.dll only extracts versions for .dll and .exe.  I need
something so I can check .sys files.

Thanks in advance.



__ 
Do you Yahoo!? 
Read only the mail you want - Yahoo! Mail SpamGuard. 
http://promotions.yahoo.com/new_mail 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [perl-python] string pattern matching

2005-02-01 Thread Daniel Fackrell
- Henry Wadsworth Longfellow
"Erik Max Francis" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> Dan Perl wrote:
>
> > Perhaps someone will write a program to automatically follow up on every
> > [perl-python] posting?  The follow-up could just contain a statement
like
> > the one Daniel mentions.  Obviously the program would be written in
python.
> > ;-)
>
> I'm not really sure that such a disclaimer is explicitly necessary.
> Anyone looking at Xah Lee's posts will also see the threads they
> generate, which involve people pointing out all their errors.  Granted
> this won't happen with every single post, but since he's posting this
> stuff once a day, I don't think the chances of someone finding his posts
> and not seeing the related discussion and refutations is a big risk.
>
> For the rest of us, we can just killfile the threads easily enough.

It seems to me that application of one of these solutions reduces the
effectiveness of the other.  If enough persons killfile the threads, who
warns the newbies?  And so those who don't killfile the threads to ensure
that somebody is still guarding against misleading information to newbies
continue dealing with it manually.

Daniel Fackrell



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


Re: [perl-python] string pattern matching

2005-02-01 Thread Stephen Thorne
On Tue, 01 Feb 2005 21:19:34 -0500, Chris Smith
<[EMAIL PROTECTED]> wrote:
> Falls into the 'cure worse than the disease' category.
> It's really just a prompt to explore the corners of Gnus, and
> determine how to give X.L. the thorough ignoring he deserves.

*headdesk*

I'm using gmail, and I can set up the filter trivially
(from:[EMAIL PROTECTED] -> delete), but I just wasn't thinking clearly. I
was cursing not having the ability to use a procmail filter while the
solution was right in front of me.

Regards,
Stephen.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [perl-python] string pattern matching

2005-02-01 Thread Chris Smith
> Stephen Thorne <[EMAIL PROTECTED]> writes:

> On Tue, 1 Feb 2005 18:59:18 -0500, Dan Perl <[EMAIL PROTECTED]> wrote:
>> Perhaps someone will write a program to automatically follow up
>> on every [perl-python] posting?  The follow-up could just
>> contain a statement like the one Daniel mentions.  Obviously
>> the program would be written in python.  ;-)
>> 
>> Any suggestions on how to implement such a program?  How would
>> it detect a new posting?  How would it send the follow-up?
>> 
>> Anyway, I agree with Daniel and I think that would not only
>> warn newcomers to the group, but it would also allow many of us
>> to move on without worrying about the effect that the
>> perl-python postings may have on these newcomers.

> I'd just like the python-list@python.org mailing list to drop
> his posts on the floor so I don't have to read them.

> But thats me.

> Stephen.

Falls into the 'cure worse than the disease' category.
It's really just a prompt to explore the corners of Gnus, and
determine how to give X.L. the thorough ignoring he deserves.
R,
C 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Where are list methods documented?

2005-02-01 Thread Nick Coghlan
Tim Peters wrote:
2. Built-In Objects 
2.1 Built-in Functions 
2.2 Non-essential Built-in Functions 
2.3 Built-in Types 
2.3.1 Truth Value Testing 
2.3.2 Boolean Operations 
2.3.3 Comparisons 
2.3.4 Numeric Types 
2.3.5 Iterator Types 
2.3.6 Sequence Types 
2.3.7 Set Types 
2.3.8 Mapping Types 
2.3.9 File Objects 
2.3.10 Other Built-in Types 
2.3.11 Special Attributes 
2.4 Built-in Exceptions 
2.5 Built-in Constants

So, e.g., it doesn't mention floats or dicts by those names either. 
It's well worthwhile to spend some time browsing that entire chapter.
I wonder if adding a small table to the end of the introductory text in Section 
2.3 would help. Something like:


The documentation in this section is written in terms of type categories. The 
table below associates specific builtin types with the most relevant categories.

Type Category  Specific Built-in Types
 Booleanbool
 Numericint, long, float, complex
 Iterator   N/A
 Sequence   tuple
 String Sequencestr, unicode
 Mutable Sequence   list
 Setset, frozenset
 Mappingdict
 File   file
"""
Cheers,
Nick.
--
Nick Coghlan   |   [EMAIL PROTECTED]   |   Brisbane, Australia
---
http://boredomandlaziness.skystorm.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: how do i create such a thing?

2005-02-01 Thread Steve Holden
Lowell Kirsh wrote:
I'm not sure I get it. What's the purpose of using a delegate rather 
than having the object itself supply the return value?

Alex Martelli wrote:
Lowell Kirsh <[EMAIL PROTECTED]> wrote:

What might these exceptions be?

It's HIGHLY advisable to have your __getattr__ methods raise
AttributeError for any requested name that starts and ends with double
underscores, possibly with some specific and specifically designed
exceptions.

For example, delegation of such requests to some other object:
def __getattr__(self, name):
return getattr(self._delegate, name)
In such cases you may decide you do not need to block __specials__,
because you're OK with having self._delegate supply them or be
responsible to raise AttributeError if necessary.
Alex
The point is that you can keep a reference to some object, and it's the 
next best thing to having subclassed the object's class but with closer 
control.

regards
 Steve
A: Top-posting
Q: What puts things in the wrong order on newsgroup postings
--
Meet the Python developers and your c.l.py favorites March 23-25
Come to PyCon DC 2005  http://www.python.org/pycon/2005/
Steve Holden   http://www.holdenweb.com/
--
http://mail.python.org/mailman/listinfo/python-list


curl and popen2

2005-02-01 Thread lists04
Hi,

I have a problem with a curl request and running it under popen2.

If I run this request from the command line:
curl -i http://www.yahoo.com/test --stderr errfile
(also tried redirecting stdderr to a file 2>, nothing) the file errfile
is empty indicating no error with the request.

However, when I do something similar in python:
>>> cmd="curl -i http://www.yahoo.com/test";
>>> output, input, err = popen2.popen3(cmd)
>>> error = err.readlines()
>>> error
['  % Total% Received % Xferd  Average Speed  Time
Curr.\n', ' Dload  Upload Total
Current  LeftSpeed\n', '\r100   9810   9810 0  24525
0 --:--:--  0:00:00 --:--:-- 24525\r100  24840  24840 0
62100  0 --:--:--  0:00:00 --:--:-- 1467k\n']

I looked in the man page for curl, it doesnt say that it writes some
bandwidth statistics to stderr. Am I missing something or is this
better directed to some other newsgroup? 

TIA

Hari

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


Re: Newbie Question

2005-02-01 Thread Jeremy Bowers
On Tue, 01 Feb 2005 17:47:39 -0800, Joel Eusebio wrote:
> Whenever I access test.py from my browser it says "The page cannot be
> found" , I have the file on /var/www/html, what did I miss?
> 
>  Thanks in advance,
> Joel

In general, you will need to post the relevant entries from your Apache
error log and access log. A lot of things can go wrong between your Python
script and final output. 

However, if you're getting a 404, it means that you haven't associated the
URL to the file correctly. Again, a lot of things can prevent this, so
you're also going to need to post the relevant Apache configuration files.
Without that, I can't be any more specific.

I'm also concerned that you are conflating mod_python with Python CGI,
which work completely differently when it comes to associating code to
URLs. In general, you won't access a mod_python script by typing in a
URL to a file; that will either try to run it as a CGI or just display it
(depending on the configuration). But we'll work on this when you post the
necessary information and we can see what you are trying to do.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: variable declaration

2005-02-01 Thread Steve Holden
Thomas Bartkus wrote:
"Steve Holden" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
Thomas Bartkus wrote:

"Carl Banks" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]

How common is it for a local variable to be bound in
more than one place within a function?

How common?  It shouldn't happen at all and that was the point.
This seems a little excessive to me. Sample use case:
for something in lst:
  if type(something) != type(()):
something = tuple(something)

Hhhmmh!
I presume you are going through the list and want to gaurantee that every
item you encounter is a tuple!  So if it ain't - you just re-declare
"something" to be a tuple. What was formerly a single string, integer,
whathaveyou is now a tuple *containing* a single string, integer,
whathaveyou.
Do you do it that way because you can? Or  because you must?
   And
If the former - is it a good idea?
OR did I just miss your codes intent completely?
I suspect you missed the intent completely.
My first inclination would be to create a new variable (type = tuple) and
accept (or typecast) each "something" into it as required. The notion that
OK, but if you do that then surely the loop looks like
for something in lst:
somethingElse = something
if type(somethingElse) != type(()):
somethingElse = ...
you just morph "something" still seems rather abhorrent. It hadn't occurred
to me that iterating through a list like that means the iterater "something"
might need to constantly morph into a different type according to a lists
possibly eclectic contents.
Now I suspect I'm missing *your* point.
It might explain why the interpreter is incapable of enforcing a type.  It
would forbid iterating through lists containing a mix of different types.
EXCEPT- I must note, that other languages manage to pull off exactly such a
trick with a variant type. When you need to pull off a feat such as this,
you declare a variant type where the rules are relaxed *for that situation
only* and there is no need to toss the baby out with the bathwater.
Well I have to say that the longer I program (and I've been at it nearly 
forty years now) the more I am convinced that type declarations don't 
actually help. I can see their value in terms of code optimization, but 
there is no way that I see them as an error-detection mechanism. "You 
have tried to assign a string to an integer variable" just isn't a 
mistake I make a lot.

regards
 Steve
--
Meet the Python developers and your c.l.py favorites March 23-25
Come to PyCon DC 2005  http://www.python.org/pycon/2005/
Steve Holden   http://www.holdenweb.com/
--
http://mail.python.org/mailman/listinfo/python-list


Newbie Question

2005-02-01 Thread Joel Eusebio

Hi Everybody,

I'm pretty new to Python and would like to ask a few questions. I have this
setup on a Fedora Core 3 box.

Python 2.3.4
wxPython-common-gtk-ansi-2.5.3.1-fc2_py2.3
mod_python-3.1.3-5
Apache/2.0.52

I have a test.py which looks like this:
from mod_python import apache
def handler(req):
   req.write("Hello World!")
   return apache.OK

Whenever I access test.py from my browser it says "The page cannot be found"
, I have the file on /var/www/html, what did I miss?

 Thanks in advance,
Joel

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


Re: how do i create such a thing?

2005-02-01 Thread Lowell Kirsh
I'm not sure I get it. What's the purpose of using a delegate rather 
than having the object itself supply the return value?

Alex Martelli wrote:
Lowell Kirsh <[EMAIL PROTECTED]> wrote:

What might these exceptions be?

It's HIGHLY advisable to have your __getattr__ methods raise
AttributeError for any requested name that starts and ends with double
underscores, possibly with some specific and specifically designed
exceptions.

For example, delegation of such requests to some other object:
def __getattr__(self, name):
return getattr(self._delegate, name)
In such cases you may decide you do not need to block __specials__,
because you're OK with having self._delegate supply them or be
responsible to raise AttributeError if necessary.
Alex
--
http://mail.python.org/mailman/listinfo/python-list


Re: The next Xah-lee post contest

2005-02-01 Thread alex23

Luis M. Gonzalez wrote:
> I kind of like this guy... it's like he has a few bugs in his brain,
> but other parts are surprisingly interesting.

Which bits especially impress you, the rampant misogyny or the
unwarranted intellectual arrogance?

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


Re: Atlas and NumPy Problems

2005-02-01 Thread Robert Kern
Justin Lemkul wrote:
Hello all,
I am hoping someone out there will be able to help me.  I am trying to install 
a program that utilizes NumPy.  In installing NumPy, I realized that I was 
lacking Atlas.  I ran into the following problems installing Atlas and NumPy, 
as I realized that NumPy could be installed using the Mac OSX veclib already 
built in.  If anyone has any ideas on how to fix either of these, I would be 
most grateful.

I am fairly new to Python (I've been learning it myself), so I apologize if 
these questions are a bit foolish.  I've been fighting these problems for 
days, and I'm out of ideas.

I am running OS X v10.3, gcc v3.3, Python v2.3, ScientificPython v2.4.3, and 
am attempting to install NumPy 23.7
Did you try to follow my advice from the other thread? What does your 
setup.py look like?

--
Robert Kern
[EMAIL PROTECTED]
"In the fields of hell where the grass grows high
 Are the graves of dreams allowed to die."
  -- Richard Harter
--
http://mail.python.org/mailman/listinfo/python-list


Re: MySQLdb - Tuples

2005-02-01 Thread Lajos Kuljo
Dennis Benzinger wrote:
Lajos Kuljo wrote:
Hallo,
ich bin voll neu im Python-Programming, deshalb ist mein Problem 
wahrscheinlich trivial:

Wenn ich die Script
#33
#! /usr/bin/env python
import MySQLdb
db=MySQLdb.connect(host='localhost', db='photum_0_6_2', user='root', 
passwd='thkhgfgd')
c=db.cursor()
c.execute('select person from persons order by person')
tup=c.fetchall()
for a in tup:
  print a

ausführe, erhalte ich Dinge wie
('Dieter',)
('Hulda',)


Ich brauche die Klammern, Apostrphe und Kommas nicht (ich will nur die 
Inhalte) und kann ich sie nicht loswerden. Versucht habe ich u. a. print 
a[2:-3] was nur zwei Klammern bringt.
b=lstrip(a, "(") haut auch nicht hin.
Weiss jemand Rat?

Hab gerade kein MySQL da, aber änder mal
for a in tup:
print a
in
for a in tup:
print a[0]  # Das erste Element des Tupels
Dann wird statt des ganzen Tupels nur das erste Element ausgegeben.

P.S. Woher kommen diese Klammern und Apostrophen, vom MySQLdb?

Die Klammern und Apostrophe kommen daher, dass tup ein Tupel
(http://docs.python.org/lib/typesseq.html) mit einem Element
(der Person) ist.
Dennis
Thank you Dennis,
it works!
Sorry for the wrong language. I'm getting older.
Kind regards Lajos
--
http://mail.python.org/mailman/listinfo/python-list


Re: permutations, patterns, and probability

2005-02-01 Thread Steven Bethard
kpp9c wrote:
Greetings,
I am working on a program to produce patterns. What would like is for
it to  exhaustively produce all possible permutations of a sequence of
items but for each permutation produce variations, and also a sort of
stutter based on probability / weighted randomess.
Let us say we have tiles of four primary colors: ['Red', 'Blue',
'Green', 'Yellow']. Now we also have 4 alternatives or substitutes for
each color ['Maroon', 'Navy_Blue', 'Forest_Green', 'Dark_Brown']
We pick a unique permutation, say: ['Red', 'Blue', 'Yellow', 'Green']
Now I would like to pick the primary colors substitute (say 30% chance
for each element) so instead of our plain
['Red', 'Blue', 'Yellow', 'Green']
we might end up with:
['Red', 'Navy_Blue', 'Yellow', 'Forest_Green']
or
['Maroon', 'Navy_Blue', 'Yellow', 'Green']
Whatever... The main point is that sometimes the original color is
retained and sometimes the dark color is substituted.
Now I want to take this list and sometimes stutter an element so that
there is, let us say a 50% chance for each element, that it is
stuttered, and it may be repeated 1 (34%), 2(66%), or 3(33%) times. So
that we could get:
['Maroon','Maroon','Navy_Blue', 'Yellow','Yellow','Yellow','Yellow',
'Green']
The program would quit when all 24 (in the case of 4 elements) was
exhausted.
Playing around with this:
py> def alt_color(color, color_map=dict(Red='Maroon',
... Blue='Navy_Blue',
... Yellow='Forest_Green',
... Green='Dark_Brown')):
... if random.random() <= 0.3:
... return color_map[color]
... return color
...
py> def reps():
... if random.random() < 0.5:
... return 1
... return random.randint(2, 4)
...
py> def combinations(items, n):
... if n==0:
... yield []
... else:
... for i in xrange(len(items)):
... item_slice = items[i:i+1]
... for c in combinations(items[:i]+items[i+1:], n-1):
... yield item_slice + c
...
py> colors = ['Red', 'Blue', 'Yellow', 'Green']
py> some_colors = combinations(colors, len(colors)).next()
py> some_colors
['Red', 'Blue', 'Yellow', 'Green']
py> alt_colors = [alt_color(c) for c in some_colors]
py> alt_colors
['Red', 'Navy_Blue', 'Yellow', 'Green']
py> rep_colors = [c for color in alt_colors for c in [color]*reps()]
py> rep_colors
['Red', 'Red', 'Navy_Blue', 'Navy_Blue', 'Navy_Blue', 'Yellow', 'Green', 
'Green']

Hope some of that is helpful.
Steve
--
http://mail.python.org/mailman/listinfo/python-list


Re: How do you do arrays

2005-02-01 Thread Thomas Bunce
Thanks 
   Tom
In article <[EMAIL PROTECTED]>, "Dan Perl"
<[EMAIL PROTECTED]> wrote:

> A solution that I haven't seen mentioned by other postings in the thread is 
> to implement the array as a dictionary:
> 
> iMatrix = {}
> for index in range(majorlop1):
> k = random.choice(listvalues) + 1
> iMatrix[index] = k
> 
> Mind you, a dictionary does not behave *exactly* like an array.  For 
> instance, in your example, you may later do a "del iMatrix[2]" and then you 
> wouldn't really be able to use iMatrix like an array anymore.  But, 
> depending on your application, a dictionary may be perfectly suitable.
> 
> Hope this helps.
> 
> Dan
> 
> "Thomas Bunce" <[EMAIL PROTECTED]> wrote in message 
> news:[EMAIL PROTECTED]
> >I am new at Pyton and I am learning from book not classes
> > so please forgive my being slow
> >
> > The below does not work I get an Error of  File
> > "Matrix[index] = k
> > NameError: name 'iMatrix' is not defined"
> >
> > while  index < majorlop1:
> >   index = index + 1
> >   k = random.choice(listvalues) + 1
> >   iMatrix[index] = k
> >
> > The book statement of
> > array(typecode, initializer) does not make sence
> > to me how it henerates ore relaes to the org name
> > for the array.
> >
> > Thank You
> > Tom
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Awkwardness of C API for making tuples

2005-02-01 Thread John Machin

Dave Opstad wrote:
> In article <[EMAIL PROTECTED]>,
>  "John Machin" <[EMAIL PROTECTED]> wrote:
>
> > What is the purpose of this first loop?
>
> Error handling. If I can't successfully create all the PyInts then I
can
> dispose the ones I've made and not bother making the tuple at all.
> >
> > In what variable-length storage are you storing these (Python)
integers
> > during this first loop? Something you created with (a) PyMem_Malloc
(b)
> > malloc (c) alloca (d) your_own_malloc?
>
> (b) malloc. The sequence here is: 1) malloc; 2) check for malloc
> success; 3) loop to create PyInts (if failure, Py_DECREF those made
so
> far and free the malloc'ed buffer); 4) create new tuple (error checks

> again); and 5) PyTuple_SET_ITEM (no error checks needed)

Don't. If you _must_ allocate your own storage, use PyMem_Malloc.

>
> > 1. Determine the length of the required tuple; this may need a
loop,
> > but only to _count_ the number of C longs that you have.
> > 2. Use PyTuple_New.
> > 3. Loop to fill the tuple, using PyInt_FromLong and
PyTuple_SetItem.
>
> This would certainly be simpler, although I'm not sure I'm as clear
as
> to what happens if, say, in the middle of this loop a PyInt_FromLong
> fails. I know that PyTuple_SetItem steals the reference; does that
mean
> I could just Py_DECREF the tuple and all the pieces will be
> automagically freed? If so, I'll take your recommendation and rework
the
> logic this way.

This is what I believe happens. However even if you did need to do more
cleaning up, you shouldn't penalise the normal case i.e. when
PyInt_FromLong works. The only failure cause AFAIK is running out of
memory.
This should be rare unless it's triggered by your calling malloc :-)

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


Re: web camera or else ? 15-30 fps processing of camera videos.

2005-02-01 Thread JGCASEY

The Artist Formerly Known as Kap'n Salty wrote:
> Newbie wrote:
> > I am doing some robotics projects but my main area of interest is
> > trying out several algorithms for the processing of the stream of
data
> > coming from the video.
> >
> > I am wondering what type of camera I should invest in. Either I
could
> > buy a web cam and hope I can find a driver I could either modify or
> > use. i.e. every frame is somehow stored on the computer
automagically
> > or I could buy a camera not unlike the AVRcam
> > (http://www.jrobot.net/Projects/AVRcam.html) or the CMUcam and try
to
> > do the processing once the data has been streamed to the nearest
> > computer ? or should I use an expensive video card, some CCTV
camera
> > and a frame grabber to digitize photos so they can be processed
> > afterwards. I expect my processing algorithms to handle at least 15
> > frames per second framerate once they are working ont the final
set-up.
> >
> > My constraints are that I would like to avoid as much as possible
> > complex set-ups even if that means buying a more expensive camera
> > set-up. For the prototyping, I would like to try my algorithms out
> > using a combination of python and matlab (all very slow) and then
> > expect the same architecture (image files location and flow) with
> > speedier set-up like python+psyco or C. All the processing would be
> > done on a computer dedicated for that. Windows or Linux are
possible.
> >
>
> An easy approach to this is to use a wireless camera on your robot,
with
> the receiver attached to a frame grabber on a remote host. This
allows
> you your choice of camera (stand alone video transmitters are widely
> available), and you are not limited to only processing hardware you
can
> carry on board your robot. You also get full FPS. Frame-grabber cards

> are inexpensive and widely available for both Windows and Linux.

I wanted to go down that path but cannot get
information on how to access the images from
the tv receiver card in real time using my
own software.

Do you use Java?

John Casey

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


Save the Canvas!

2005-02-01 Thread Sean McIlroy
I'd like to be able to save a Tkinter Canvas in a format other than
postscript (preferably gif). Is there a tool out there for
accomplishing that? Any help will be much appreciated.

Peace,
STM
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [perl-python] string pattern matching

2005-02-01 Thread Erik Max Francis
Dan Perl wrote:
Perhaps someone will write a program to automatically follow up on every 
[perl-python] posting?  The follow-up could just contain a statement like 
the one Daniel mentions.  Obviously the program would be written in python. 
;-)
I'm not really sure that such a disclaimer is explicitly necessary. 
Anyone looking at Xah Lee's posts will also see the threads they 
generate, which involve people pointing out all their errors.  Granted 
this won't happen with every single post, but since he's posting this 
stuff once a day, I don't think the chances of someone finding his posts 
and not seeing the related discussion and refutations is a big risk.

For the rest of us, we can just killfile the threads easily enough.
--
Erik Max Francis && [EMAIL PROTECTED] && http://www.alcyone.com/max/
San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis
  Little things / Cut like knives / Hurt and sting
  -- Anggun
--
http://mail.python.org/mailman/listinfo/python-list


Re: [perl-python] string pattern matching

2005-02-01 Thread Stephen Thorne
On Tue, 1 Feb 2005 18:59:18 -0500, Dan Perl <[EMAIL PROTECTED]> wrote:
> Perhaps someone will write a program to automatically follow up on every
> [perl-python] posting?  The follow-up could just contain a statement like
> the one Daniel mentions.  Obviously the program would be written in python.
> ;-)
> 
> Any suggestions on how to implement such a program?  How would it detect a
> new posting?  How would it send the follow-up?
> 
> Anyway, I agree with Daniel and I think that would not only warn newcomers
> to the group, but it would also allow many of us to move on without worrying
> about the effect that the perl-python postings may have on these newcomers.

I'd just like the python-list@python.org mailing list to drop his
posts on the floor so I don't have to read them.

But thats me.

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


Re: [perl-python] string pattern matching

2005-02-01 Thread Dan Perl
Perhaps someone will write a program to automatically follow up on every 
[perl-python] posting?  The follow-up could just contain a statement like 
the one Daniel mentions.  Obviously the program would be written in python. 
;-)

Any suggestions on how to implement such a program?  How would it detect a 
new posting?  How would it send the follow-up?

Anyway, I agree with Daniel and I think that would not only warn newcomers 
to the group, but it would also allow many of us to move on without worrying 
about the effect that the perl-python postings may have on these newcomers.

BTW, I think Daniel's suggestion for the statement sounds pretty fair and 
pretty impartial.  Maybe it should just not use terms like "blatant".  And I 
would include something like "we support everyone's freedom to post to this 
newsgroup but we feel that python and perl beginners need to be warned about 
the quality of these tutorials".

Dan

"Daniel Fackrell" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Perhaps a message to the effect of "These messages are specifically 
> disowned
> by the groups to which they are posted, have historically been riddled 
> with
> blatant errors, and are assumed to continue in the same quality." should 
> be
> posted as a follow-up to each of these messages by XL in order to avoid
> having to spend the time to find the inaccuracies in each one 
> individually.
>
> Considering the response so far, a list of frequent posters and
> not-so-frequent posters who will vouch for the accuracy of the disclaimer
> might even be added.
>
> Daniel Fackrell
>
>
> 


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


permutations, patterns, and probability

2005-02-01 Thread kpp9c
Greetings,

I am working on a program to produce patterns. What would like is for
it to  exhaustively produce all possible permutations of a sequence of
items but for each permutation produce variations, and also a sort of
stutter based on probability / weighted randomess.

Let us say we have tiles of four primary colors: ['Red', 'Blue',
'Green', 'Yellow']. Now we also have 4 alternatives or substitutes for
each color ['Maroon', 'Navy_Blue', 'Forest_Green', 'Dark_Brown']

We pick a unique permutation, say: ['Red', 'Blue', 'Yellow', 'Green']

Now I would like to pick the primary colors substitute (say 30% chance
for each element) so instead of our plain

['Red', 'Blue', 'Yellow', 'Green']

we might end up with:

['Red', 'Navy_Blue', 'Yellow', 'Forest_Green']

or

['Maroon', 'Navy_Blue', 'Yellow', 'Green']

Whatever... The main point is that sometimes the original color is
retained and sometimes the dark color is substituted.

Now I want to take this list and sometimes stutter an element so that
there is, let us say a 50% chance for each element, that it is
stuttered, and it may be repeated 1 (34%), 2(66%), or 3(33%) times. So
that we could get:

['Maroon','Maroon','Navy_Blue', 'Yellow','Yellow','Yellow','Yellow',
'Green']

The program would quit when all 24 (in the case of 4 elements) was
exhausted.

I have code that makes weighted randomness. I have code that makes
permutations, but I am having trouble putting this all together...
While i work on it though that i might ask for help... I'd like for the
code to be reusable and am building a library of functions for
patterns.

cheers,
kevin


### This is not mine, it is from a python book... I believe the Lutz
book

def permute(list):
if not list:# shuffle any
sequence
return [list]   # empty
sequence
else:
res = []
for i in range(len(list)):
rest = list[:i] + list[i+1:]# delete
current node
for x in permute(rest): # permute the
others
res.append(list[i:i+1] + x) # add node at
front
return res

mport random

### This this is mine, but seems to work anyway hee hee

def windex(lst):
'''an attempt to make a random.choose() function that makes
weighted choices

accepts a list of tuples with the item and probability as a
pair
like: >>> x = [('one', 0.25), ('two', 0.25), ('three', 0.5)]
>>> y=windex(x)'''
n = random.uniform(0, 1)
for item, weight in lst:
if n < weight:
break
n = n - weight
return item

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


Re: Awkwardness of C API for making tuples

2005-02-01 Thread Dave Opstad
In article <[EMAIL PROTECTED]>,
 "John Machin" <[EMAIL PROTECTED]> wrote:

> What is the purpose of this first loop?

Error handling. If I can't successfully create all the PyInts then I can 
dispose the ones I've made and not bother making the tuple at all.
> 
> In what variable-length storage are you storing these (Python) integers
> during this first loop? Something you created with (a) PyMem_Malloc (b)
> malloc (c) alloca (d) your_own_malloc?

(b) malloc. The sequence here is: 1) malloc; 2) check for malloc 
success; 3) loop to create PyInts (if failure, Py_DECREF those made so 
far and free the malloc'ed buffer); 4) create new tuple (error checks 
again); and 5) PyTuple_SET_ITEM (no error checks needed)

> 1. Determine the length of the required tuple; this may need a loop,
> but only to _count_ the number of C longs that you have.
> 2. Use PyTuple_New.
> 3. Loop to fill the tuple, using PyInt_FromLong and PyTuple_SetItem.

This would certainly be simpler, although I'm not sure I'm as clear as 
to what happens if, say, in the middle of this loop a PyInt_FromLong 
fails. I know that PyTuple_SetItem steals the reference; does that mean 
I could just Py_DECREF the tuple and all the pieces will be 
automagically freed? If so, I'll take your recommendation and rework the 
logic this way.

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


Re: how about writing some gui to a known console application

2005-02-01 Thread alexrait1
I tried to delete this message, but I guess it was too late... or it
didn't work for me... sorry anyway.

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


Re: Next step after pychecker

2005-02-01 Thread Philippe Fremy

I do not want to discourage Philippe Fremy but I think that this would be very 
very difficult to do without modifying Python itself.
That's the conclusion I reached to too after lurking on the ocaml list.
What FP languages rely upon to achieve type inference is a feature named 
"strong typing". 
> [...]
This is certainly not the case for Python since one and the same variable can 
have different types depending upon the execution context. Example :

1- if a is None:
2-   b = 1
3- else:
4-   b = "Phew"
5- b = b + 1
One cannot statically determine the type of b by examining the line 5- alone.
There are even worse cases:
1- a=1
2- a= someObject.someMethod()
someObject might not have someMethod() and this would be caught by an 
AttributeError exception handler and 'a' will stay at 1.


Therefore, Fremy's dream can very well turn to some very complex expert system 
to make "educated" warning. Being "educated" is a lot harder than to be 
"brutal".
And even being brutal is not that easy to achieve...
Anyway, strong typing as defined above would change the Python language in 
some of its fundamental design. It would certainly be valuable to attempt the 
experience, and rename the new language (mangoose would be a pretty name).
Indeed. I understood that this is one of the things that could be 
provided by pypy.

What I understood (Jacek, this is an answer for you too) is that there 
are many usage patterns for python.

Some people use it for all of its advanced dynamic features. I use it in 
a java-like fashion. One could use it without the "OO crap", like a 
modern pascal replacement.

This is a strength of python that it lends itself to so many programming 
paradigm. However, one drawback is that python is not optimum in many of 
these paradigm (although it is sometimes the best proponent). In my 
case, dynamic typing is not a required feature. Typing immutability and 
type inferring is a lot more valuable.

I really hope that pypy will provide that kind of choice. Give me python 
with eiffel like contracts, super speed optimisation thank to type 
inference and I will be super happy.

Thank everyone for its feedback.
Any other idea of a fun python improvement project I could join without 
too much hassle ? I can't help but thinking that pychecker ought to be 
able to do a better job.

regards,
Philippe

Francis Girard
FRANCE
Le mardi 1 Février 2005 16:49, Diez B. Roggisch a écrit :
But it can be useful to restrict type variety in certain situations
e.g. prime number calculation :) And it would probably also be useful
to check violations of restrictions before running the program in
normal mode.
But that's what (oca)ml and the like do - they exactly don't force you to
specify a type, but a variable has an also variable type, that gets
inferned upon the usage and is then fixed.
--
Regards,
Diez B. Roggisch

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


Re: [perl-python] string pattern matching

2005-02-01 Thread Daniel Fackrell
Perhaps a message to the effect of "These messages are specifically disowned
by the groups to which they are posted, have historically been riddled with
blatant errors, and are assumed to continue in the same quality." should be
posted as a follow-up to each of these messages by XL in order to avoid
having to spend the time to find the inaccuracies in each one individually.

Considering the response so far, a list of frequent posters and
not-so-frequent posters who will vouch for the accuracy of the disclaimer
might even be added.

Daniel Fackrell



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


Re: web camera or else ? 15-30 fps processing of camera videos.

2005-02-01 Thread Matt D
Newbie wrote:
I am doing some robotics projects but my main area of interest is
trying out several algorithms for the processing of the stream of data
coming from the video.

Same for me!  From what I can tell, a cheap webcam will "just work" with 
a recent version of windows - i.e. plug it in using USB and then you can 
have programmatic access to the data and grab frames very easily.  This 
setup works fine with my digital camera working as a webcam - real £10 
webcams should be the same.  Not sure what Linux compatibility is like 
these days - for that I know for a fact that the Hauppauge USB WinTV 
thing works (or at least the hardware version I have works) with Linux.

For linux I found this (now on the wayback archive - original page is 
now 404): 
http://web.archive.org/web/20020322015936/http://staff.aist.go.jp/naoyuki.ichimura/research/tips/v4ln_e.htm

Hopefully that is some help.
Oh by the way, speed on a modern machine shouldn't be an issue - my 
badly written prototype in visual basic of all things (dont laugh - 
seemed like a good idea at the time!) was tracking a single coloured 
object reliably at significantly greater than 30fps (it automatically 
altered the window it searched in based on size and amount of movement 
of the object - at times it was approaching 100fps) on a modest by 
today's standards 1.4ghz pc, using a 320x240 stream.

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


Re: how about writing some gui to a known console application

2005-02-01 Thread Jeremy Bowers
On Tue, 01 Feb 2005 21:57:45 +, Grant Edwards wrote:

> On 2005-02-01, alexrait1 <[EMAIL PROTECTED]> wrote:
> 
>> Do something useful... (at least for me) For instance I need a gtk
>> frontend for pgp. So here you can have an opportunity to learn both
>> pyGTK and pgp. A lot of python code... :)
> 
> Um, to whom are you addressing your commands?

Presumably the "Suggesion[sic] for an undergrad final year project in
Python" thread.

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


Re: MySQLdb - Tuples

2005-02-01 Thread Dennis Benzinger
Lajos Kuljo wrote:
> Hallo,
> ich bin voll neu im Python-Programming, deshalb ist mein Problem 
> wahrscheinlich trivial:
> 
> Wenn ich die Script
> #33
> #! /usr/bin/env python
> import MySQLdb
> db=MySQLdb.connect(host='localhost', db='photum_0_6_2', user='root', 
> passwd='thkhgfgd')
> c=db.cursor()
> c.execute('select person from persons order by person')
> tup=c.fetchall()
> for a in tup:
>print a
> 
> ausführe, erhalte ich Dinge wie
> ('Dieter',)
> ('Hulda',)
> 
> 
> Ich brauche die Klammern, Apostrphe und Kommas nicht (ich will nur die 
> Inhalte) und kann ich sie nicht loswerden. Versucht habe ich u. a. print 
> a[2:-3] was nur zwei Klammern bringt.
> b=lstrip(a, "(") haut auch nicht hin.
> Weiss jemand Rat?

Hab gerade kein MySQL da, aber änder mal

for a in tup:
print a

in

for a in tup:
print a[0]  # Das erste Element des Tupels


Dann wird statt des ganzen Tupels nur das erste Element ausgegeben.


> P.S. Woher kommen diese Klammern und Apostrophen, vom MySQLdb?

Die Klammern und Apostrophe kommen daher, dass tup ein Tupel
(http://docs.python.org/lib/typesseq.html) mit einem Element
(der Person) ist.


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


ftplib help - delete from server after download results in 0-byte file

2005-02-01 Thread Peter A.Schott
Got a strange scenario going on here in that I could have sworn this worked
yesterday.  I am issuing binary retrieval calls to an FTP server, writing to a
file, close the file, then removing the file from the remote site.  When I do
this, I end up with 0 byte files.  I was hoping to avoid parsing a list of
remote and local files and matching them up that way because it would be easier
to remove on successful retrieve.  I'm including some sample code and really
hoping someone can point out where I'm messing up.

Thanks.


import os, ftplib
DPI = "C:/DestinationFolder/"
#Actually named different in code, but shorter for reading here.
#Note - objFTP is already opened - this is not the issue.

objFTP.cwd("/ksdata_in")

#I'm open to better ways to do this.  Can't use nlst if empty.
TestDir = objFTP.dir()
if TestDir <> None:
FTPRemoteList = objFTP.nlst()

#If the remote file is type SEM or PGP, do this.
for filename in [filename for filename in FTPRemoteList if \
(os.path.splitext(filename)[1] in [".sem",".SEM",".PGP",".pgp"])]:
try:
DestinationFile = open(os.path.join(DPI, filename), "wb")
print DestinationFile
objFTP.retrbinary("RETR " + filename, DestinationFile.write)
SQLLogging.LogFTP(filename, CompanyInput, 1, 'ToDrive')
DestinationFile.close()

#This is the culprit.  When this is active, it writes a 0 byte file locally
# and deletes the file on the server.
#objFTP.delete(filename)
except:
SQLLogging.LogFTP(filename, CompanyInput, 0, 'ToUs')
print Exception


#This is my workaround in the meantime.  If I've downloaded the files, get
#another remote listing and delete and files from remote that are downloaded
#locally and larger than 1Kbish for PGP files.  SEM files are 0 bytes.

TestDir = objFTP.dir()
if TestDir <> None:
FTPRemoteList = objFTP.nlist()
for filename in FTPRemoteList:
if os.path.isfile(os.path.join(DownloadedPathInput, filename)) 
and \
os.path.splitext(filename)[1] in [".pgp",".PGP"] and \
os.stat(os.path.join(DownloadedPathInput, filename))[6] > 1000:
objFTP.delete(filename)
if os.path.isfile(os.path.join(DownloadedPathInput, filename)) 
and \
os.path.splitext(filename)[1] in [".SEM",".sem"]:
objFTP.delete(filename)



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


Re: web camera or else ? 15-30 fps processing of camera videos.

2005-02-01 Thread The Artist Formerly Known as Kap'n Salty
Newbie wrote:
I am doing some robotics projects but my main area of interest is
trying out several algorithms for the processing of the stream of data
coming from the video.
I am wondering what type of camera I should invest in. Either I could
buy a web cam and hope I can find a driver I could either modify or
use. i.e. every frame is somehow stored on the computer automagically
or I could buy a camera not unlike the AVRcam
(http://www.jrobot.net/Projects/AVRcam.html) or the CMUcam and try to
do the processing once the data has been streamed to the nearest
computer ? or should I use an expensive video card, some CCTV camera
and a frame grabber to digitize photos so they can be processed
afterwards. I expect my processing algorithms to handle at least 15
frames per second framerate once they are working ont the final set-up.
My constraints are that I would like to avoid as much as possible
complex set-ups even if that means buying a more expensive camera
set-up. For the prototyping, I would like to try my algorithms out
using a combination of python and matlab (all very slow) and then
expect the same architecture (image files location and flow) with
speedier set-up like python+psyco or C. All the processing would be
done on a computer dedicated for that. Windows or Linux are possible.
An easy approach to this is to use a wireless camera on your robot, with 
the receiver attached to a frame grabber on a remote host. This allows 
you your choice of camera (stand alone video transmitters are widely 
available), and you are not limited to only processing hardware you can 
carry on board your robot. You also get full FPS. Frame-grabber cards 
are inexpensive and widely available for both Windows and Linux.

Hope that helps -- tAfkaks

--
(Replies: cleanse my address of the Mark of the Beast!)
Teleoperate a roving mobile robot from the web:
http://www.swampgas.com/robotics/rover.html
--
http://mail.python.org/mailman/listinfo/python-list


Atlas and NumPy Problems

2005-02-01 Thread Justin Lemkul
Hello all,

I am hoping someone out there will be able to help me.  I am trying to install 
a program that utilizes NumPy.  In installing NumPy, I realized that I was 
lacking Atlas.  I ran into the following problems installing Atlas and NumPy, 
as I realized that NumPy could be installed using the Mac OSX veclib already 
built in.  If anyone has any ideas on how to fix either of these, I would be 
most grateful.

I am fairly new to Python (I've been learning it myself), so I apologize if 
these questions are a bit foolish.  I've been fighting these problems for 
days, and I'm out of ideas.

I am running OS X v10.3, gcc v3.3, Python v2.3, ScientificPython v2.4.3, and 
am attempting to install NumPy 23.7

Thank you!

-Justin


ATLAS install problem:

n file included from
/Users/jalemkul/Desktop/ATLAS/include/
atlas_prefetch.h:8, from
../ATL_col2blk.c:33:/Users/jalemkul/Desktop/ATLAS/
include/atlas_altivec.h:6:27: altivec.h: No such file or
directory../ATL_col2blk.c: In function
`ATL_dcol2blk_aX':../ATL_col2blk.c:79: error: `vector' undeclared (first use
in this
function)../ATL_col2blk.c:79: error: (Each undeclared identifier is reported
only once../
ATL_col2blk.c:79: error: for each function it appears in.)../ATL_col2blk.c:79:
error: parse
error before "float"../ATL_col2blk.c:80: error: parse error before
"float"make[7]: ***
[ATL_dcol2blk_aX.o] Error 1make[7]: *** Waiting for unfinished
jobsmake[6]: *** [dlib]
Error 2make[5]: *** [dmmlib] 
Error 2make[4]: *** [res/atlas_cacheedge.h] 
Error2make[3]: *** [dinstall] 
Error 2make[2]: *** [MMinstall] 
Error 2   STAGE2-1-2: CacheEdge
DETECTIONmake -f Makefile INSTALL_LOG/atlas_cacheedge.h pre=d 2>&1 |
./xatlas_tee
INSTALL_LOG/dMMCACHEEDGE.LOGcd /Users/jalemkul/Desktop/ATLAS/tune/blas/gemm/
OSX_UNKNOWNAltiVec_2 ; make res/atlas_cacheedge.h pre=dmake dRunFindCEcd
/Users/
jalemkul/Desktop/ATLAS/src/blas/gemm/OSX_UNKNOWNAltiVec_2 ; make dlibmake
auxillib
dcleanuplib dusergemmcd /Users/jalemkul/Desktop/ATLAS/src/auxil/
OSX_UNKNOWNAltiVec_2 ; make libmake[7]: Nothing to be done for `lib'.cd KERNEL
; make
-f dMakefile dlibmake[7]: Nothing to be done for `dlib'.cd
/Users/jalemkul/Desktop/ATLAS/
src/blas/gemm/OSX_UNKNOWNAltiVec_2 ; make dusermmmake[7]: `dusermm' is up to
date.make -j 2 dlib.grd/usr/bin//gcc -o ATL_dcol2blk_aX.o -c -DL2SIZE=4194304
-I/Users/
jalemkul/Desktop/ATLAS/include -I/Users/jalemkul/Desktop/ATLAS/include/
OSX_UNKNOWNAltiVec_2 -I/Users/jalemkul/Desktop/ATLAS/include/contrib
-DATL_OS_OSX -DATL_AltiVec -DATL_AVgcc -DATL_AS_OSX_PPC -DATL_NCPU=2 -O
-maltivec -mabi=altivec -DDREAL -DALPHAX ../ATL_col2blk.c
/usr/bin//gcc -o ATL_drow2blkT_aX.o -c -DL2SIZE=4194304
-I/Users/jalemkul/Desktop/
ATLAS/include -I/Users/jalemkul/Desktop/ATLAS/include/OSX_UNKNOWNAltiVec_2
-I/Users/
jalemkul/Desktop/ATLAS/include/contrib   -DATL_OS_OSX -DATL_AltiVec
-DATL_AVgcc
-DATL_AS_OSX_PPC -DATL_NCPU=2 -O -maltivec -mabi=altivec -DDREAL -DALPHAX ../
ATL_row2blkT.c
In file included from
/Users/jalemkul/Desktop/ATLAS/include/atlas_prefetch.h:8,
 from ../ATL_row2blkT.c:32:
/Users/jalemkul/Desktop/ATLAS/include/atlas_altivec.h:6:27: altivec.h: No such
file or
directory
../ATL_row2blkT.c: In function `ATL_drow2blkT_NB_aX':
../ATL_row2blkT.c:64: error: `vector' undeclared (first use in this function)
../ATL_row2blkT.c:64: error: (Each undeclared identifier is reported only once
../ATL_row2blkT.c:64: error: for each function it appears in.)
../ATL_row2blkT.c:64: error: parse error before "float"
../ATL_row2blkT.c:65: error: parse error before "float"
../ATL_row2blkT.c:74: error: parse error before "float"
../ATL_row2blkT.c:75: error: parse error before "float"
In file included from
/Users/jalemkul/Desktop/ATLAS/include/atlas_prefetch.h:8,
 from ../ATL_col2blk.c:33:
/Users/jalemkul/Desktop/ATLAS/include/atlas_altivec.h:6:27: altivec.h: No such
file or
directory
../ATL_col2blk.c: In function `ATL_dcol2blk_aX':
../ATL_col2blk.c:79: error: `vector' undeclared (first use in this function)
make[6]: *** [ATL_drow2blkT_aX.o] Error 1
make[6]: *** Waiting for unfinished jobs
../ATL_col2blk.c:79: error: (Each undeclared identifier is reported only once
../ATL_col2blk.c:79: error: for each function it appears in.)
../ATL_col2blk.c:79: error: parse error before "float"
../ATL_col2blk.c:80: error: parse error before "float"
make[6]: *** [ATL_dcol2blk_aX.o] Error 1
make[5]: *** [dlib] Error 2
make[4]: *** [dmmlib] Error 2
make[3]: *** [res/atlas_cacheedge.h] Error 2
make[2]: ***
[/Users/jalemkul/Desktop/ATLAS/tune/blas/gemm/OSX_UNKNOWNAltiVec_2/
res/atlas_cachedge.h] Error 2
ERROR 572 DURING CACHE EDGE DETECTION!!.
cd ../.. ; make error_report arch=OSX_UNKNOWNAltiVec_2
make -f Make.top error_report arch=OSX_UNKNOWNAltiVec_2
uname -a 2>&1 >> bin/OSX_UNKNOWNAltiVec_2/INSTALL_LOG/ERROR.LOG
/usr/bin//gcc -v 2>&1  >> bin/OSX_UNKNOWNAltiVec_2/INSTALL_LOG/ERROR.LOG
Reading specs from /usr/libexec/gcc/darwin/ppc/3.3/specs
Thread model: posix
gcc versio

MySQLdb - Tuples

2005-02-01 Thread Lajos Kuljo
Hallo,
ich bin voll neu im Python-Programming, deshalb ist mein Problem 
wahrscheinlich trivial:

Wenn ich die Script
#33
#! /usr/bin/env python
import MySQLdb
db=MySQLdb.connect(host='localhost', db='photum_0_6_2', user='root', 
passwd='thkhgfgd')
c=db.cursor()
c.execute('select person from persons order by person')
tup=c.fetchall()
for a in tup:
  print a

ausführe, erhalte ich Dinge wie
('Dieter',)
('Hulda',)


Ich brauche die Klammern, Apostrphe und Kommas nicht (ich will nur die 
Inhalte) und kann ich sie nicht loswerden. Versucht habe ich u. a. print 
a[2:-3] was nur zwei Klammern bringt.
b=lstrip(a, "(") haut auch nicht hin.
Weiss jemand Rat?

P.S. Woher kommen diese Klammern und Apostrophen, vom MySQLdb?
--
http://mail.python.org/mailman/listinfo/python-list


Re: How do you do arrays

2005-02-01 Thread Dan Perl
A solution that I haven't seen mentioned by other postings in the thread is 
to implement the array as a dictionary:

iMatrix = {}
for index in range(majorlop1):
k = random.choice(listvalues) + 1
iMatrix[index] = k

Mind you, a dictionary does not behave *exactly* like an array.  For 
instance, in your example, you may later do a "del iMatrix[2]" and then you 
wouldn't really be able to use iMatrix like an array anymore.  But, 
depending on your application, a dictionary may be perfectly suitable.

Hope this helps.

Dan

"Thomas Bunce" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
>I am new at Pyton and I am learning from book not classes
> so please forgive my being slow
>
> The below does not work I get an Error of  File
> "Matrix[index] = k
> NameError: name 'iMatrix' is not defined"
>
> while  index < majorlop1:
>   index = index + 1
>   k = random.choice(listvalues) + 1
>   iMatrix[index] = k
>
> The book statement of
> array(typecode, initializer) does not make sence
> to me how it henerates ore relaes to the org name
> for the array.
>
> Thank You
> Tom 


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


Re: How do you do arrays

2005-02-01 Thread Thomas Bunce

It was when I saw a use of complex numbers as a usable statement I became
interested in Python

Tom


In article <[EMAIL PROTECTED]>,
[EMAIL PROTECTED] wrote:

> If you want do numerical calculations with vectors and matrices, you
> should probably use the Numarray module. Python's built-in lists are
> not intended for heavy numerical computations. They are more flexible
> than the arrays in languages like C and Fortran in that they can store
> elements of different types. One can write, for example,
> x = ["dog",1,2.3] .
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Next step after pychecker

2005-02-01 Thread John Roth
"Sylvain Thenault" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
On Tue, 01 Feb 2005 05:18:12 +0100, Philippe Fremy wrote:
Did you take a look at the starkiller [1] and pypy projects [2] ?
Has anything happened to Starkiller since PyCon 2004? The
latest mention I can find on Google is a blog entry (by Ted
Leung) on Aug 30 saying he wished someone would give the
author some money to finish it and publish it.
John Roth
--
http://mail.python.org/mailman/listinfo/python-list


Re: Redirecting stdout/err under win32 platform

2005-02-01 Thread David Douard
Alan,

I did search Google for this problem (not enough, thou).
In fact, I found some kind of solution (by myself, not that much on Google),
but it is not really satisfactory.

I have used win32 pipes to do so (win32api.CreatePipe). I can redirect
stdout/stderr to it from my python code (even redirecting the stdout/stderr
from my C lib). 
But I still have a problem with this solution (well, 2):
- it is *much* more complicated than any solution available on Unix like
systems (not really a problem, but),
- it not synchronous at all. And I'd like it to be so (or almost so).

David



yaipa wrote:

> David,
> 
> Googling comp.lang.python /w this string "stderr win32" yielded 109
> results.
> So I think if you poke around a bit you will find your answer in the
> archives.
> 
> Sorry for no direct help tonight...
> 
> Cheers,
> 
> --Alan
> David Douard wrote:
>> Hi everybody,
>>
>> let me explain by problem:
>> I am working on an application which consists in a C++ dll (numeric
>> computations) and a Python IHM (Python/Tk), which must run under
> Linux and
>> win32. My problem is the C++ lib does write stuffs on its stdout, and
> I
>> would like to print those messages in a Tk frame. When I run the
>> computation, it has it's own thread.
>>
>> So my question is : how van I redirect the dll's stdout to something
> I can
>> retrieve in Python (pipe, socket,...)?
>>
>> I can do it easily under Linux. I made tests with a socket which just
> works
>> fine. In the threaded function (that will do the heavy computation),
> I
>> write:
>>
>> import os, sys
>> from socket import *
>> s=socket(AF_UNIX, SOCK_STREAM)
>> s.connect(...)
>> os.dup2(sys.__stdout__.fileno(), s.fileno())
>> very_intensive_function(many_parameters)
>> s.close()
>>
>> That's OK under Linux, but does not work under win32 (even if I use
> an INET
>> localhost socket), cause I cannot do the os.dup2 trick (Windows does
> not
>> want to consider a socket as a file! What a shity system!).
>>
>> So my question is : is there a simple solution ? I have tested
> different
>> solutions. I am trying hacks with pipes created with the win32api.
> But I
>> have not yet managed this simple operation.
>>
>> Note that I have no access to the dll source code, so I cannot modify
> it so
>> it uses a named pipe (for example) as message output pipe instead os
>> stdout...
>> 
>> Thanks,
>> David

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


Re: How do you do arrays

2005-02-01 Thread Thomas Bunce
Learning Python O'Reilly book and Python In A Nut Shell and about 2 inchs
printed of Web information

   Tom

In article <[EMAIL PROTECTED]>,
"Kartic" <[EMAIL PROTECTED]> wrote:

> Tom,
> 
> It has to be iMatrix.append(k), not iMatrix[index] = k. Python will
> give an error - list assignment index out of range - for that.
> Just curious - what book are you following?
> 
> -Kartic
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: Next step after pychecker

2005-02-01 Thread Delaney, Timothy C (Timothy)
huy wrote:

> do not yet have good coverage. TDD is a quite hard to practice as a
> beginner. 

It's even harder to bolt onto an existing codebase :(

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


Re: Crude statistics on the standard library

2005-02-01 Thread IncessantRanting

F. Petitjean wrote:
[snip]
> Conclusion :
>  sre_compile and sre_parse should be coded with a __all__ attribute

Problem with this is that it would change the API for the two modules.
And the main reason for the dependencies is that sre_constants is
import-star'ed; same with sre_constants.

But yes, it wouldn't hurt to lower them.  But then again people are not
supposed to be using these modules directly; they are there to provide
support to the re module.

>  The standard library contains a module 'tzparse' which cannot be
imported !

It can, but you must have the 'TZ' environment variable set.  It's
deprecated and has been moved to lib-old as of Python 2.5 .

>  Most library modules do not begin with #!/usr/bin/env python and a
> coding cookie.
>

Not all modules are meant to be run as a script.  Plus, with the advent
of the '-m' argument for the interpreter it really isn't necessary.
And as for the encoding cookie, most modules have been around much
longer than that feature so they are almost all ASCII encoded.

-Brett

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


Re: Using HTTPSConnection and verifying server's CRT

2005-02-01 Thread Ng Pheng Siong
According to Marc Poulhiès  <[EMAIL PROTECTED]>:
> Btw, thanks for your answer (this will save me from using Perl!)

You're welcome.

> ## what are the diff between these two??
> #ctx.load_verify_info(cafile="/tmp/ca.crt")
> ctx.load_verify_locations(cafile="/tmp/ca.crt")

None. One is an alias for the other, to adhere to OpenSSL's naming
convention.

> $ ./ssl_peer_verif.py 
> Enter passphrase:
> send: 'GET / HTTP/1.1\r\nHost:
> my.ssl.server.domain:443\r\nAccept-Encoding: identity\r\n\r\n'
> reply: 'HTTP/1.1 200 OK\r\n'
> header: Date: Tue, 01 Feb 2005 08:41:51 GMT
> header: Server: Apache/2.0.46 (Red Hat)
> header: Last-Modified: Mon, 31 Jan 2005 14:50:50 GMT
> header: ETag: "4297-13-24658680"
> header: Accept-Ranges: bytes
> header: Content-Length: 19
> header: Connection: close
> header: Content-Type: text/html; charset=UTF-8
> THIS IS WORKING =)

Excellent! ;-)


-- 
Ng Pheng Siong <[EMAIL PROTECTED]> 

http://sandbox.rulemaker.net/ngps -+- M2Crypto, ZServerSSL for Zope, Blog
http://www.sqlcrypt.com -+- Database Engine with Transparent AES Encryption
-- 
http://mail.python.org/mailman/listinfo/python-list


web camera or else ? 15-30 fps processing of camera videos.

2005-02-01 Thread Newbie
I am doing some robotics projects but my main area of interest is
trying out several algorithms for the processing of the stream of data
coming from the video.

I am wondering what type of camera I should invest in. Either I could
buy a web cam and hope I can find a driver I could either modify or
use. i.e. every frame is somehow stored on the computer automagically
or I could buy a camera not unlike the AVRcam
(http://www.jrobot.net/Projects/AVRcam.html) or the CMUcam and try to
do the processing once the data has been streamed to the nearest
computer ? or should I use an expensive video card, some CCTV camera
and a frame grabber to digitize photos so they can be processed
afterwards. I expect my processing algorithms to handle at least 15
frames per second framerate once they are working ont the final set-up.

My constraints are that I would like to avoid as much as possible
complex set-ups even if that means buying a more expensive camera
set-up. For the prototyping, I would like to try my algorithms out
using a combination of python and matlab (all very slow) and then
expect the same architecture (image files location and flow) with
speedier set-up like python+psyco or C. All the processing would be
done on a computer dedicated for that. Windows or Linux are possible.

Any help from either comp.robotics.misc or c.l.p would be helpful.
Thanks in advance,

Jake.

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


Re: how about writing some gui to a known console application

2005-02-01 Thread Grant Edwards
On 2005-02-01, alexrait1 <[EMAIL PROTECTED]> wrote:

> Do something useful... (at least for me)
> For instance I need a gtk frontend for pgp.
> So here you can have an opportunity to learn both pyGTK and pgp. A lot
> of python code... :)

Um, to whom are you addressing your commands?

-- 
Grant Edwards   grante Yow!  Kids, don't gross me
  at   off... "Adventures with
   visi.comMENTAL HYGIENE" can be
   carried too FAR!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Suggesion for an undergrad final year project in Python

2005-02-01 Thread alexrait1
How about writing some gtk fronted to pgp.. That might be both useful
(at least for me) and teach you about pgp and pyGTK, that is writing
gui with python.

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


how about writing some gui to a known console application

2005-02-01 Thread alexrait1
Do something useful... (at least for me)
For instance I need a gtk frontend for pgp.
So here you can have an opportunity to learn both pyGTK and pgp. A lot
of python code... :)

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


Re: Suggesion for an undergrad final year project in Python

2005-02-01 Thread phil_nospam_schmidt
How about a tool that can compute the intersection/union/disjunction of
boolean expressions, and return the result as a boolean expression?
This is something I've had on my plate for awhile, but haven't been
able to get around to doing.

As a simple example, assume we have the following expressions:

e1 = (y)
e2 = ((not x) and (not y)) or ((not x) and (y) and (z))

The union of these two would be ((not x) or (y)). The simplest
representation of the result would be best.


To make it harder consider the following additional requirements:

1) Instead of just boolean variables, allow variables with more than
two discrete values (i.e., True and False). For example, if a variable
x can represent the values 1, 2, and 3, then an expression could test
for x!=3, or x>1, or even x in [1,3].

2) Use Python's native data structures to represent expressions. Using
the example above, we might have something like this:

e1 = [{'y':True}]
e2 = [{'x':False, 'y':False}, {'x':False, 'y':True, 'z':True}]

How you might extend this to non-boolean expressions would be up to
you.

3) Make it fast, and scalable to many variables (up to at least 50). I
haven't studied this extensively, but I believe a Quine-McKlusky method
is order n^2 with n being the number of variables, so this will quickly
blow up as the number of variables increases.

4) As my example in (2) suggested, make variable names strings. This
allows arbitrary names. For non-boolean discrete variables, allow any
arbitrary list of numbers or strings as elements.

5) Since a side-effect of the program will (probably) be the ability to
reduce expressions to their simplest representation, make this
capability a part of the public API, since that's a useful function in
itself.

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


Re: Where are list methods documented?

2005-02-01 Thread Timothy Fitz
[Tim Peters]
> The methods on mutable sequence types are documented in the Library
> manual's section on mutable sequence types:
>
>http://docs.python.org/lib/typesseq-mutable.html
>
 
And like -many- python programmers, when he thinks "List" he doesn't
immediately think "Mutable Sequence Type." The title should stay but
perhaps the tutorial should be updated to point people in the right
direction when they're "done" and need to know specifics? (This link
of the documentation was non-obvious to me also)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: pythonic equivalent of Mathematica's FixedPoint function

2005-02-01 Thread Russell Blau
"jelle" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> doh...
>
> https://sourceforge.net/projects/fixedpoint
>
> pardon me
>

I don't think that Tim's FixedPoint class is doing the same thing as
Mathematica's FixedPoint function (or even anything remotely similar).
Well, except for the fact that they both operate on numbers

You could probably write your own FixedPoint function without too much
difficulty, with the only tricky part being for it to know when to stop!

Russ

-- 
I don't actually read my hotmail account, but you can replace hotmail with
excite if you really want to reach me.



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


Re: Suggesion for an undergrad final year project in Python

2005-02-01 Thread Lucas Raab
Paul Robson wrote:
On Tue, 01 Feb 2005 12:11:47 +, Kartic wrote:

Sridhar said the following on 2/1/2005 2:11 AM:
Hi,
I am doing my undergrade CS course.  I am in the final year, and would
like to do my project involving Python.  Our instructors require the
project to have novel ideas.  Can the c.l.p people shed light on this
topic?
You try and implement some CS concepts you have learnt using Python. For 
example, if you had a course on parsing and compiler design, try to 
implement a simple language in Python.

Could I suggest going for an area that particularly interests you ; rather
than saying "what sort of project " come up with an area of interest -
this'll mean you probably have more knowledge and will put in more
effort - and then ask for ideas - ideally about something that is missing.
Exactly. If you have an interest in mathematics, then look into 
Numarray. Graphics: Panda3d, Blender, pygame... The list goes on. Feel 
free to append.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Printing Filenames with non-Ascii-Characters

2005-02-01 Thread vincent wehren
Marian Aldenhövel wrote:
Hi,
I am very new to Python and have run into the following problem. If I do
something like
  dir = os.listdir(somepath)
  for d in dir:
 print d

The program fails for filenames that contain non-ascii characters.

  'ascii' codec can't encode characters in position 33-34:
If you read this carefully, you'll notice that Python has tried and 
failed to *encode* a decoded ( = unicode) string using the 'ascii' 
codec. IOW, d seems to be bound to a unicode string. Which is unexpected 
unless maybe the argument passed to os.listdir (somepath) is a Unicode 
string, too. (If given a Unicode string as argument, os.listdir will 
return the list as a list of unicode names).

If you're printing to the console, modern Pythons will try to guess the 
console's encoding (e.g. cp850). I would expect a UnicodeEncodeError if 
the print fails because the characters do not map to the console's 
encoding, not the error you're seeing.

How *are* you running the program. In the console (cmd.exe)? Or from 
some IDE?

I have noticed that this seems to be a very common problem. I have read 
a lot
of postings regarding it but not really found a solution. Is there a simple
one?

What I specifically do not understand is why Python wants to interpret the
string as ASCII at all. Where is this setting hidden?
Don't be tempted to ever change sys.defaultencoding in site.py, this is 
site specific, meaning that if you ever distribute them, programs 
relying on this setting may fail on other people's Python installations.

--
Vincent Wehren
I am running Python 2.3.4 on Windows XP and I want to run the program on
Debian sarge later.
Ciao, MM
--
http://mail.python.org/mailman/listinfo/python-list


Re: How do you do arrays

2005-02-01 Thread Kartic
Tom - I answered your question even before you posted it!

You have to use iMatrix.append(k) and NOT iMatrix[index] = k.

Also,  what do you expect out of:
while index < majorlop1:
print '- %s %s' % ( iMatrix[index], sep)

This loop will never get executed because your previous loop finishes
due to the same condition index < majorlop1.

I am not sure what book you are using but I don't think it is a very
good one.

>  I would like to set the size of the List/array independent
> of having to intialialize it prior to use.

You can  do the following when you allocate your list.
iMatrix = [''] * size # where size is an integer
and this will give you a list of size empty elements. If you do this,
do not use iMatrix.append(). Use the array notation like you have in
you code currently.

Thanks
-Kartic

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


Re: variable declaration

2005-02-01 Thread Thomas Bartkus
"Michael Tobis" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]

> Since I'm very much a believer in Python as a beginner's language, that
> doesn't satisfy me. "Declarations are impractical" would satisfy me,
> but so far I'm not completely convinced of that.
>

As has been pointed out, it's not a big deal for a programmer who's been
there, done that. But the original posters example is a beginners trap for
certain.

*If* Python were a "beginners language", then it would be missing one of
it's training wheels.
Thomas Bartkus


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


Re: variable declaration

2005-02-01 Thread Christian Dieterich
On Dé Máirt, Feabh 1, 2005, at 12:19 America/Chicago, Alex Martelli 
wrote:

Michael Tobis <[EMAIL PROTECTED]> wrote:
   ...
I don't know that it's ever necessary to rebind, but it is, in fact,
common, and perhaps too easy. In numeric Python, avoiding rebinding
turns out to be a nontrivial skill.
Well, a for-statement is BASED on rebinding, for example.  Maybe you
don't mean to address rebinding per se, but rebinding in ``separate
statements''?  The ``separation'' needs to be defined carefully to make
while-loops work, too.  Normally, a while-statement's header clause
would be something like:
while :
where the expression depends on the values bound to some local
variables.  For the first evaluation, the variables need to be bound by
earlier statements; for the expression to eventually become false, it's
likely (unless we're talking about mutable objects) that the variables
need to be re-bound in the loop body.
For example, consider:
def f(a, b):
x = 0
while x < 10:
print x,
x = a*x + b
print
I think you guys are talking about rebinding of quite different 
objects. Rebinding x in the above example is not what Michael Tobis is 
talking about, I presume, though x is prone to the 'epselon' error. 
But, C'est la vie.

If x was some sort of counter (time step, iteration) and there was a 
Numeric array y to be processed in that loop,

def f(a, b):
  y = Numeric.zeros((100, 100), 'd')
  x = 0
  while x < 10:
x = a*x + b
y = a*y + b
it is actually important (e.g. in terms of performance) not to rebind 
y. Okay, in this case it is straightforward to change function f to 
function g, so that y does not get recreated (rebound).

def g(a, b):
  y = Numeric.zeros((100, 100), 'd')
  x = 0
  while x < 10:
x = a*x + b
y *= a
y += b
I don't know if y gets 'rebound' in a strict sense of the word. But y 
does not call it's constructor (which is expensive). And in terms of 
performance
y = Numeric.zeros((100, 100), 'd')
10.0100.010  574.050  574.050 profile:0(f(1,1))
1   -0.000   -0.000  416.640  416.640 profile:0(g(1,1))
  y = numarray.zeros((100, 100), 'd')
10.0200.020  231.359  231.359 profile:0(f(1,1))
10.0100.010   27.899   27.899 profile:0(g(1,1))
it's quite a difference.

would you require the programmer to find out a closed-form expression
for this recurrence relation, in order to avoid having to rebind the
name 'x'?  OK, in this particular case it may be OK, if you are willing
Using Numeric arrays or Numarrays, it might help to have some 
closed-form expression for the above (I'm quite sure there is, see 
daxpy in BLAS). But then, I'd say it's in the responsability of the 
programmer who did class Y to create y to prevent the user from using y 
= a*y + b. Either in the documentation or really strictly by not 
implementing + and * (only =+ and =*). This kind of 
restriction/declaration should not be in Python, but in the module that 
provides Y.

to put competence in college-level algebra as a prerequisite for using
Python.  But what if the rebinding in the body of the loop was to a 
more
I believe those using Numeric/Numarray might have heard of algebra and 
in-place operations. So, one could even argue that it's up to the user 
to find an efficient way to avoid rebinding of y.

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


Re: How do you do arrays

2005-02-01 Thread beliavsky
wes weston wrote:
> Thomas,
> If you were allowed to do what you're doing, the
> list first element would be getting skipped as "index"
> is always > 0. The thing is, you don't want the "index"
> var at all for adding to the list; just do jMatrix.append(k).
> You can iterate over the list with
> for x in jMatrix:
> print x
>
> Is it basic that indexes from 1 vs. 0? 'just about
> completely forgotten basic.
> wes

I think most versions of Basic have arrays that by default start with
1, as did their ancestor, Fortran, although other lower bounds can be
specified. VB.NET, Microsoft's successor to Visual Basic, requires
arrays to start with zero.

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


Re: a sequence question

2005-02-01 Thread todddeluca

Chris Wright wrote:
> Hi,
>
> 1) I want to iterate over a list "N at a time"
> sort of like:
>
> # Two at a time... won't work, obviously
>
>  >>> for a, b in [1,2,3,4]:
> ...   print a,b
> ...
> Traceback (most recent call last):
>File "", line 1, in ?
> TypeError: unpack non-sequence
>  >>>
>
>
> Is there a nifty way to do with with list comprehensions,
> or do I just have to loop over the list ?
>
> cheers and thanks
>
> chris wright

I wouldn't call this nifty, but it does use list comprehensions:
(n-(len(l)%n))%n is the amount of padding
(len(l)+(n-(len(l)%n))%n)/n is the number of groups (calculated by
adding the padding to the length of l and then dividing by n)

>>> l = range(10)
>>> n = 3
>>> [(l+[None]*((n-(len(l)%n))%n))[i*n:(i+1)*n] for i in
xrange((len(l)+(n-(len(l)%n))%n)/n)]
[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, None, None]]

Regards,
Todd

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


[perl-python] string pattern matching

2005-02-01 Thread Xah Lee
# -*- coding: utf-8 -*-
# Python

# Matching string patterns
#
# Sometimes you want to know if a string is of
# particular pattern.  Let's say in your website
# you have converted all images files from gif
# format to png format. Now you need to change the
# html code to use the .png files. So, essentially
# you want to replace strings of the form
#
# img src="*.gif"
# to
# img src="*.png"
#
# Python provides string pattern matching by the
# "re" module.  (String Pattern Matching is
# inanely known as Regular Expression (regex) in
# the computing industry. It is a misnomer and
# causes great unnecessary confusion.)


©import re
©
©text=''
©
©pattern = r'''src="([^"]+)\.gif"'''
©
©result = re.search(pattern, text)
©
©if result:
© print 'yes'
© print result.expand(r"\1") # the captured pattern
©else:
© print 'no'

#-
# if re.search(pattern, text) does not match, then the result is
None. If it matches, an object is returned. One can then use methods
such as .groups(), .expand(), .split() ... to find the matched parts,
or a given replacement string, or split the text into multiple part
by the regex...

# regex is quite confusing for beginners, but
# isn't really difficult to understand. It comes
# with practice.

# see
# http://python.org/doc/lib/module-re.html
# for detail.

# i'll have to study more to make complet example. Try it yourself.

-

# in perl, regex is its mainstay.
# very expressive with syntax, but not so in semantic,
# when compared to Python.

# for syntax variability, for example the following are all the same.

$text = "what ever is here to be matched";

if ( $text =~ ever) { print 'yes'} else {print "no"}
if ( $text =~ /ever/) { print 'yes'} else {print "no";}
if ( $text =~ m/ever/) { print 'yes'} else {print "no"}
if ( $text =~ m(ever)) { print 'yes'} else {print "no"}
if ( $text =~ [EMAIL PROTECTED]@) { print 'yes'} else {print "no"}

# for detail of its much ado about nothing nature,
# see perldoc perlre


this is perl-python a-day mailing list. To subscribe, see
http://xahlee.org/perl-python/python.html
Xah
  [EMAIL PROTECTED]
  http://xahlee.org/PageTwo_dir/more.html

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


Re: Next step after pychecker [StarKiller?]

2005-02-01 Thread Francis Girard
Hi,

Do you have some more pointers to the StarKiller project ? According to the 
paper some implementation of this very interesting project exists.

Thank you

Francis Girard

Le mardi 1 Février 2005 11:21, Sylvain Thenault a écrit :
> On Tue, 01 Feb 2005 05:18:12 +0100, Philippe Fremy wrote:
> > Hi,
>
> Hi
>
> > I would like to develop a tool that goes one step further than pychecker
> > to ensure python program validity. The idea would be to get close to what
> > people get on ocaml: a static verification of all types of the program,
> > without any kind of variable declaration. This would definitely brings a
> > lot of power to python.
> >
> > The idea is to analyse the whole program, identify constraints on
> > function arguments and check that these constraints are verified by other
> > parts of the program.
>
> Did you take a look at the starkiller [1] and pypy projects [2] ?
>
> > What is in your opinion the best tool to achieve this ? I had an
> > extensive look at pychecker, and it could certainly be extended to do
> > the job. Things that still concern me are that it works on the bytecode,
> > which prevents it from working with jython and the new .NET python.
> >
> > I am currently reading the documentation on AST and visitor, but I am
> > not sure that this will be the best tool either. The AST seems quite
> > deep and I am afraid that it will make the analysis quite slow and
> > complicated.
>
> are you talking about the ast returned by the "parser" module, or the ast
> from the "compiler" module ? The former is a higher abstraction, using
> specific class instances in the tree, and most importantly with all the
> parsing junk removed. See [3]. You may also be interested in pylint
> [4] which is a pychecker like program built in top of the compiler ast,
> and so doesn't require actual import of the analyzed code. However it's
> not yet as advanced as pychecker regarding bug detection.
>
> And finally as another poster said you should probably keep an eye open
> on the python 2.5 ast branch work...
>
> Hope that helps !
>
> [1]http://www.python.org/pycon/dc2004/papers/1/paper.pdf)
> [2]http://codespeak.net/pypy/index.cgi?home
> [3]http://www.python.org/doc/current/lib/module-compiler.ast.html
> [4]http://www.logilab.org/projects/pylint
>
> --
> Sylvain Thénault   LOGILAB, Paris (France).
>
> http://www.logilab.com   http://www.logilab.fr  http://www.logilab.org

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


Re: variable declaration

2005-02-01 Thread Michael Tobis
> All in all, I fail to see what gains would be expected by making
Python
> into a single-assignment or single-binding language, even on a module
by
> module basis, to repay this kind of awkwardness.

Just to be clear, if anyone was suggesting that, it wasn't me.

It would be helpful on occasion in a numarray development context to
have *specific* refererences be bound only once, and I wouldn't be
surprised if the compiler couldn't use that information to good
advantage too.

However, this subthread is about whether rebinding is completely
avoidable. Others including you have come up with better reasons than I
did that it's not.

If rebinding is normal, I think the 'epselon' bug can't be dismissed as
completely avoidable. This is something that I gather you disagree with
on the presumption that everyone who writes Python is sufficently
talented that they can use their skills to avoid getting too far into
this trap.

Since I'm very much a believer in Python as a beginner's language, that
doesn't satisfy me. "Declarations are impractical" would satisfy me,
but so far I'm not completely convinced of that.

mt

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


Re: How do you do arrays

2005-02-01 Thread wes weston
Thomas,
   If you were allowed to do what you're doing, the
list first element would be getting skipped as "index"
is always > 0. The thing is, you don't want the "index"
var at all for adding to the list; just do jMatrix.append(k).
   You can iterate over the list with
for x in jMatrix:
   print x
   Is it basic that indexes from 1 vs. 0? 'just about
completely forgotten basic.
wes
Thomas Bunce wrote:
Tryed it and this is what I got (I did go to the web sight)
tom(h=500)$ /tmp/501/Cleanup\ At\ Startup/ptesting-128981347.87.py.command; exit
Input the maximu number of tvalue: 114
Traceback (most recent call last):
  File "/Users/tom/Desktop/ptesting.py", line 20, in ?
iMatrix[index] = k
IndexError: list assignment index out of range
logout
[Process completed]
The complete listing:
#!/usr/bin/python
import random
import sys
import array
#
### generates a list of numbers between 1 and target
### and uses 23 % of these values.
#
iMatrix = []
tvalue = input('Input the maximu number of tvalue: ')
majorlop1 = int tvalue * .23)
listvalues = range(tvalue)
sep = '- '
index = 0
while index < majorlop1:
   index = index + 1
   k = random.choice(listvalues) + 1
   iMatrix[index] = k
   
while index < majorlop1:
   print '- %s %s' % (iMatrix[index], sep)
#
###
#
I would like to set the size of the List/array independent 
of having to intialialize it prior to use. 
If it help I will say the bad works I am using OSX

   Thanks Tom
In article <[EMAIL PROTECTED]>,
"Kartic" <[EMAIL PROTECTED]> wrote:

Tom,
Before you use iMatrix[index], you have to tell python to use iMatrix
as an array. You will do that using iMatrix = [] *outside* the loop.
iMatrix = []
while index < majorlop1: # rest of the loop statements
Since you are new, please take a look at the Python tutorial to get you
started.
http://docs.python.org/tut/tut.html
Thanks,
-Kartic
--
http://mail.python.org/mailman/listinfo/python-list


Re: Suggesion for an undergrad final year project in Python

2005-02-01 Thread Jorgen Grahn
On 31 Jan 2005 23:11:58 -0800, Sridhar <[EMAIL PROTECTED]> wrote:
> Hi,
> 
> I am doing my undergrade CS course.  I am in the final year, and would
> like to do my project involving Python.  Our instructors require the
> project to have novel ideas.  Can the c.l.p people shed light on this
> topic?

Seems to me you should find this novel idea and /then/ find the tools to
implement it. Hopefully Python would be one such good tool.

I don't have novel ideas anymore, so I can't help ...

The type interference engine for Python they talk about in some other
threads here would be a cool and useful, and "hard CS", project, but I
suspect it's too big a task. And it has been done for SML and other
languages so I don't know if it's strictly "novel".

/Jorgen

-- 
  // Jorgen GrahnR'lyeh wgah'nagl fhtagn!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Where are list methods documented?

2005-02-01 Thread Nick Craig-Wood
Tim Peters <[EMAIL PROTECTED]> wrote:
>  You could have gotten to the same place in several ways.
[snip]

Since I'm a unix person, I would have typed

  pydoc -k sort

But it doesn't come up with anything useful :-(

  $ pydoc -k sort
  MySQLdb.stringtimes - Use strings to handle date and time columns as a last 
resort.

...

In fact I've never had any luck with pydoc -k.  I think what it
searches through is too narrow - from its man page

Run "pydoc -k " to search for a keyword in the synopsis lines
of all available modules.

This is the NAME line that appears in pydoc I think.

If it did a full text search that would be much more useful, or at
least a search through all the names of the functions & variables that
are exported.

...

My top wish for pydoc is to have the rest of the documentation in it!
Each module has lots of nice documentation which is only available in
HTML format - I'd much rather type "pydoc whatever" to see it all,
rather than have to load my browser, and click through several layers
of web pages.

-- 
Nick Craig-Wood <[EMAIL PROTECTED]> -- http://www.craig-wood.com/nick
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: msvcp71.dll and Python 2.4 C++ extensions

2005-02-01 Thread Matthias Baas
On Tue, 01 Feb 2005 00:14:30 +0100, "Martin v. Löwis"
<[EMAIL PROTECTED]> wrote:
>> are there any guidelines about what to do if a Windows extension for
>> Python 2.4  requires the C++ runtime (msvcp71.dll)? 
>
>No; it should "just work fine". [...]

I fully agree with that. :) And that was actually the reason why I
posted here, because in my case it did not just work fine...

>> It doesn't
>> sound like a good idea to me if every package places another copy of
>> this dll somewhere in the Python directory.
>
>Why not? If your installer follows Windows logo compliance rules, it
>should check whether the DLL is already present; if it is, it should
>check whether the version installed is newer than the one it would
>install, and if so, should skip installation.

I'm creating the installer via the distutils by calling "setup.py
bdist_wininst". How can I configure distutils to have it create an
installer that does the above things?

How should an installer check if a DLL is already present? Are DLLs
registered with Windows so I can query a database? Or should the
installer search for the DLL in the directories specified in the PATH
variable and see if the DLL is there?
And what's the preferred location for such a DLL? Should it be placed
in a local directory that only belongs to the package or in a
directory where other C++ extension packages might also be able to use
it? But where would this be then? The Windows system directory seems
to be discouraged by Microsoft:

"An application should use and redistribute msvcr71.dll, and it should
avoid placing a copy or using an existing copy of msvcr71.dll in the
system directory. Instead, the application should keep a copy of
msvcr71.dll in its application directory with the program executable."
(see
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vclib/html/_crt_c_run.2d.time_libraries.asp)
I suppose the same applies for msvcp71.dll.

>> Python 2.4 does install the C runtime (msvcr71.dll) in the Windows
>> system32 directory, doesn't it?
>
>It depends. If this is an allusers installation, it does so. For a
>per-user installation, the user might not have sufficient privileges
>to install into system32, so the installer won't install it there.

Ah, ok. And yes, I did a "all users" installation.

>> (btw, shouldn't this be installed in
>> the Python directory instead?)
>
>No. If you install the DLL into the Python directory, Python
>will not work anymore because python24.dll (installed into system32)
>will not find this DLL. If you then also move python24.dll into
>the Python directory, COM components that require python24.dll will
>fail to run.

ok, I see.

>> So would it be possible that future
>> Python releases would also install the C++ runtime? 
>
>Why should it? Nothing in the Python distribution requires C++.

Well, yes, I know. But I don't see Python as a standalone application.
One of the great things about Python is that there are so many
extension modules for every kinds of purposes. So, making available
the C++ runtime would just pave the way for more of those extension
modules by making it easier to distribute binary packages that are
implemented in C++.

>> I think it's
>> better if the dll would only be installed once by Python instead of
>> several times by every extension that uses C++.
>
>Why is that better? The DLL versioning rules, and the shared DLL
>refcounting mechanisms will make sure that the installation works
>just fine.

I was referring to the possibility that the DLL might get installed
several times at several different locations which would be a waste of
disk space. If there's only one file, then I agree with the above
(however, what happens if I uninstall one package and this package
removes the DLL even when there are other packages installed that
still require the DLL?).

>> Currently, I do not package the C++ runtime and leave it up to the
>> user to install the dll if it isn't already somewhere on his system.
>> But this really is not a satisfying solution...
>
>Then you should probably include the DLL, or rewrite your extension
>to not use C++.

I'm afraid the latter will hardly ever be an option... ;)

For one smaller package I was compiling I solved the problem by
linking against the static versions of the C/C++ runtime. This will
also satisfy the "It-Should-Just-Work" constraint... :)  (however,
there still could be situations where this is not possible (the
sources might not be available, for example)).

- Matthias -

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


Re: Awkwardness of C API for making tuples

2005-02-01 Thread John Machin
Dave Opstad wrote:
> One of the functions in a C extension I'm writing needs to return a
> tuple of integers, where the length of the tuple is only known at
> runtime. I'm currently doing a loop calling PyInt_FromLong to make
the
> integers,

What is the purpose of this first loop?

In what variable-length storage are you storing these (Python) integers
during this first loop? Something you created with (a) PyMem_Malloc (b)
malloc (c) alloca (d) your_own_malloc?

> then PyTuple_New, and finally a loop calling PyTuple_SET_ITEM
> to set the tuple's items. Whew.

Whew indeed.

> Does anyone know of a simpler way? I can't use Py_BuildValue because
I
> don't know at compile-time how many values there are going to be. And

> there doesn't seem to be a PyTuple_FromArray() function.
>
> If I'm overlooking something obvious, please clue me in!

1. Determine the length of the required tuple; this may need a loop,
but only to _count_ the number of C longs that you have.
2. Use PyTuple_New.
3. Loop to fill the tuple, using PyInt_FromLong and PyTuple_SetItem.

Much later, after thoroughly testing your code, gingerly change
PyTuple_SetItem to PyTuple_SET_ITEM. Benchmark the difference. Is it
anywhere near what you saved by cutting out the store_in_temp_array
thing in the first loop?

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


  1   2   3   >