Re: Python/Tk not working in Linux

2006-08-12 Thread Marc 'BlackJack' Rintsch
In <[EMAIL PROTECTED]>, BinnyVA wrote:

> I am using Fedora Core 3 Linux and I have a problem with Tk in Python.
> Whenever I try to run a tk script, I get the error...
> 
> ---
> Traceback (most recent call last):
> File "Tk.py", line 1, in ?
> from Tkinter import *
> File "/usr/local/lib/python2.4/lib-tk/Tkinter.py", line 38, in ?
> import _tkinter # If this fails your Python may not be configured for
> Tk
> ImportError: No module named _tkinter
> ---

The `_tkinter` module is the binary "bridge" to the Tk system.  If it's
not found it's most likely that the relevant header files of tcl/tk where
not installed before compiling Python or there was a problem while
compiling this extension.

This seems to be your self compiled Python.  Are you sure you got the same
error when using the version from your distribution?  I would suspect you
get an `ImportError` on `Tkinter` there.  Some distributions move the
`Tkinter` stuff into an own package.  Search for a package called
`python-tk` or `python-tkinter` or similar.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PIL Image transform

2006-08-12 Thread Ben C
On 2006-08-11, Dean Card <[EMAIL PROTECTED]> wrote:

[snip]

> thanks for the reply.  I have been able to use the Image.PERSPECTIVE 
> transform via trial and error to get it to work properly for each transform. 
> What I am really looking for I guess is a way to calculate the 8 int tuple 
> to match the perspective change I am going for.  For a given image there may 
> be 5 elements that need to be 'painted' on with perspective.  A database 
> table will include the transform tuples based on the source image.  So, by 
> passing a starting image and a pattern image, the starting image can be 
> covered with.  Perhaps the best way to explain is visually
>
> http://seanberry.com/perspective.png
>
> What I need to know is how you take a surface like (P1, P5, P6, P2) and 
> describe it with the 8 int tuple?

You could try asking this in comp.graphics.algorithms. The question is
easily made non-Python-specific, just say you have a function in a
library that does this:

Transform each point {x,y} in an image into a new point {x1,y1} where
{x1,y1} = {(ax + by + c)/(gx + hy + 1), (dx + ey + f)/(gx + hy + 1)}

then ask how to choose the params a to h to achieve the effect
illustrated on http://seanberry.com/perspective.png.
-- 
http://mail.python.org/mailman/listinfo/python-list


unbound methods

2006-08-12 Thread [EMAIL PROTECTED]
I wrote a small class today at work playing with sockets in command
line windows. When attempting to call the handle function, I get a
TypeError.  "Unbound method handle() must be called with connection
instance as first argument (got nothing instead).  Any suggestions
would be greatly appreciated.  Thanks!

-chase

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


Re: unbound methods

2006-08-12 Thread Marc 'BlackJack' Rintsch
In <[EMAIL PROTECTED]>,
[EMAIL PROTECTED] wrote:

> I wrote a small class today at work playing with sockets in command
> line windows. When attempting to call the handle function, I get a
> TypeError.  "Unbound method handle() must be called with connection
> instance as first argument (got nothing instead).  Any suggestions
> would be greatly appreciated.  Thanks!

I'd suggest that you post some actual code plus traceback so we don't have
to guess.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: unbound methods

2006-08-12 Thread Peter Otten
[EMAIL PROTECTED] wrote:

> I wrote a small class today at work playing with sockets in command
> line windows. When attempting to call the handle function, I get a
> TypeError.  "Unbound method handle() must be called with connection
> instance as first argument (got nothing instead).  Any suggestions
> would be greatly appreciated.  Thanks!

That happens if you call a (normal) method on the class instead of on an
instance.

>>> class A:
... def method(self, *args): print args
...

This works:

>>> A().method(42)
(42,)

while this doesn't:

>>> A.method(42)
Traceback (most recent call last):
  File "", line 1, in ?
TypeError: unbound method method() must be called with A instance as first
argument (got int instance instead)

For details you need to post some code illustrating the problem.

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


wxPython ListBook Class, Label Position w/ ImageList

2006-08-12 Thread Chaos
By default the label position of an image list is below the image. Is
there any way to change this?

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


Re: reading from sockets

2006-08-12 Thread AndrewTK
> I'm assuming that your server waits to receive the word 'hello' before
> replying with the three strings (first, second, and third)?  So once your

Nope - actually it's a threaded "server", with the main thread simply
dumping network input to the console and command line input being
directly dumped to the network output stream.

I confess to having typed the three lines manually...!

It's at:
http://www.dcs.st-and.ac.uk/~atk1/perso/java/servers/RespondingServer.java

It launches on the command line with
java RespondingServer _port_

_port_ being the port number it should listen for data on.

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


Re: reading from sockets

2006-08-12 Thread AndrewTK
Follow up the actual python code is at
http://www.dcs.st-and.ac.uk/~atk1/singleclient.py

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


Re: Read a file with open command

2006-08-12 Thread gslindstrom
AlbaClause wrote:
> jean-jeanot wrote:
>


> Ummm, he did not say that your question was stupid.   The Zappa quote is
> included as part of what we refer to as a 'signature'.   In the case of
> Sybren Stuvel's posts to this newsgroup, the Frank Zappa quote is included
> in every message that he posts.  Not just messages that he posts to you.

First up, I *like* the Frank Zappa signature quote; it has a George
Carlin feel to it and takes a swipe at our overly-protective cultures
[side note: I bought an electric heating pad last night that came with
instructions not to use it in the bathtub!  Well, duh!].  But, can you
see where the signature on a response to a tutor list -- where people
are already feeling a bit intimidated and/or inadequate and therefore
may feel a wee bit "stupid" -- might be taken the wrong way?

I have spent many years teaching mathematics and physics in a classroom
setting and have come to realize that, as a teacher, just about
anything I say/do can be blown way out of proportion.  So I don't use
sarcasm or "fun" little put-downs and I treat every question as if it
is the most important matter because, to the student, it is.  Do I get
tired of answering the same thing over and over? Yes!!  Many times I
will ask if the student has read the textbook and, if not, I will
request they give it a try (much in the same way we ask if they have
read any tutorials), but I take Homeric efforts not to offend them and,
to that end, modify my behavior in order to teach them mathematics.

My point is that this is a wonderful service you tutors provide, but
the Zappa signature may not be the best choice for this setting. Most
people will read it and get a laugh (as did I), but how many have taken
it the way jean-jeanot did and walk away feeling insulted?  How many
will not post a response expressing their feelings, never post a
question again or, worst case, decide Python is not for them?

Again, I admire this list and those of you you maintain it.  These are
just my thoughts.  YMMV.

--greg

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


ANN: PyPsp 0.1

2006-08-12 Thread placid
First version of PyPsp is released. I have done limited testing as i
have limited free time to
devote to this project, but im doing my best.  There are a three
external modules that you need
to download see the README file for additional information.


Summary

  Playstation Portable(PSP) Video Manager written in Python. It
will use ffmpeg to do the conversion of video files. So basically it is
a framework around ffmpeg.It will provide better filename tracking on
both the PSP and the hard drive for firmware<=2.71


Getting It:

 http://sourceforge.net/projects/pypsp


Ideas, tips welcome!

Cheers

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


Re: Program - Leipzig Python Workshop

2006-08-12 Thread david_wahler
I'll be out of the office until approximately August 20th. If you have any 
questions, please email [EMAIL PROTECTED]

-- David Wahler


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


Re: long(Decimal) performance

2006-08-12 Thread Aahz
In article <[EMAIL PROTECTED]>,
ajaksu <[EMAIL PROTECTED]> wrote:
>
>Running long(Decimal) is pretty slow, and the conversion is based on
>strings. I'm trying to figure out whether there is a good reason for
>using strings like in decimal.py (that reason would be bound to bite me
>down the road).

I'm not sure why it's coded that, but it's somewhat irrelevant: right
now, work is being done to convert decimal.py to C code, which will
almost certainly be much faster than your code.  Generally speaking, you
should not be using Decimal now with any expectation of speed.
-- 
Aahz ([EMAIL PROTECTED])   <*> http://www.pythoncraft.com/

"Debugging is twice as hard as writing the code in the first place.
Therefore, if you write the code as cleverly as possible, you are, by
definition, not smart enough to debug it."  --Brian W. Kernighan
-- 
http://mail.python.org/mailman/listinfo/python-list


matplotlib, wxPanel inside a wxPanel

2006-08-12 Thread Sam
Hello,

I'm currently creating a GUI, which consists of a main frame that
contains a menu bar,a toolbar and an empty panel, let's call it
main_panel.
Ideally, I'd like the following functionality: upon choosing an item
from the menu bar, a particular graph will be displayed inside
main_panel.

Now I've taken a look at the 'embedding_in_wx' example files that come
with matplotlib. Using this example, I can place a graph in a panel
(let's call it graph_panel), and display this in a frame. I can also
get NavigationToolbar2 to work completely.

On the other hand, when i create graph_panel and put this inside of
main_panel, NavigationToolbar2 does not work. The graph and toolbar are
both displayed, but none of the buttons on the toolbar do anything.

I'm beginning to think that what i'm trying to do isn't actually
possible, and that i'll need to put it in a frame instead, which is a
pity.

Can anyone please advise if what i'm trying to do is possible and if
so, provide a small example? I'm running windows XP, python 2.4,
wxpython 2.6.

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


Re: iterator wrapper

2006-08-12 Thread alf
Simon Forman wrote:
>>
>>>|>> I = ([n] for n in i)
>>
>>This is nice but I am iterating thru hude objects (like MBs) so you know ...
>>
> 
> No, I don't know...  :-)

potentially my source lists are huge - so wanted to avoid unnecessary 
memory allocation


> My friend, I think you've misunderstood.  Observe:
> 
> |>> L = [n for n in range(3)]
> |>> G = (n for n in range(3))
> |>> L
> [0, 1, 2]
> |>> G
> 

well, I am in the python 2.3 word where generator comprehensions seem 
not to work. So I just took it a preallocated list comprehention. still 
wonder if there would be a difference between:

G = (n for n in range(3))  - this creates the huge list there
G = (n for n in xrange(3)) - this (at least to my understanding) 
  does not


> 
> List comprehensions [] create lists, generator comprehensions () create
> generators.
> 


> Generator comprehensions work "just-in-time", pulling items from
> whatever they're iterating over as they themselves are iterated over,
> as I hope this example makes clear:
> 
 >[...]

got it now ... thx or the lesson


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


Re: iterator wrapper

2006-08-12 Thread alf
Paul Rubin wrote:
> alf <[EMAIL PROTECTED]> writes:
> 
>>>|>> I = ([n] for n in i)
>>
>>This is nice but I am iterating thru hude objects (like MBs) so you know ...
> 
> 
> I don't understand the objection-- the above is entirely correct and
> produces the same iterator you'd get from
> 
> def wrap(i):
>for x in i:
>yield [x]
> I = wrap(i)
> 
> You could also use
>  
>import itertools
>I = itertools.imap(lambda x: [x], i)
> 
> which again does the same thing.


I did see [] instead of () :-). this was a source of confusion.


okay, we have 3 functionally equal solution - which is most pythonic :-) 
 seroiusly ...



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


[OT] why cd ripping on Linux is so slow

2006-08-12 Thread alf
Hi,

I try to ip some music CD and later convert it into mp3 for my mp3 
player, but can not get around one problem. ripping from Linux is 
extremely slow  like 0.5x of CD speed.

In contrary, on M$ Windows it takes like a few minutes to have CD ripped 
and compresses into wmf yet I do not knowhow to get pure wavs...

Hope I find someone here helping me with that 


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


Looking for a text file based wiki system written in Python

2006-08-12 Thread Jack
I'd like to set up a wiki system for a project I'm working on.
Since I'm not good at databases, and there's really not much
stuff to put into the wiki, I hope it is text file-based.
I used DokuWiki before, which is very nice but it's written
in PHP. Is there a similar system that's written in Python?
I found pwyky but it's functionality is a bit too simple. 


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


Re: Looking for a text file based wiki system written in Python

2006-08-12 Thread Gregor Horvath
Jack schrieb:
> I'd like to set up a wiki system for a project I'm working on.
> Since I'm not good at databases, and there's really not much
> stuff to put into the wiki, I hope it is text file-based.
> I used DokuWiki before, which is very nice but it's written
> in PHP. Is there a similar system that's written in Python?
> I found pwyky but it's functionality is a bit too simple. 


http://moinmoin.wikiwikiweb.de/

-- 
  Servus, Gregor
  http://www.gregor-horvath.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: long(Decimal) performance

2006-08-12 Thread ajaksu
Hi Aahz, thanks for the feedback!

Aahz wrote:
> I'm not sure why it's coded that, but it's somewhat irrelevant: right
> now, work is being done to convert decimal.py to C code, which will
> almost certainly be much faster than your code.  Generally speaking, you
> should not be using Decimal now with any expectation of speed.

Agreed and agreed.

Just to avoid that the buggy (and unreadable) versions above harm
anyone, here's a better attempt:

def dec2long(number):
""" Convert C{decimal.Decimal} to long """
decimal_string = str(number)
## Split 123.45E10 -> radix = 123.45, exponent = 10
if "e" in decimal_string:
radix, exponent = decimal_string.split("e")
elif "E" in decimal_string:
radix, exponent = decimal_string.split("E")
else:
radix, exponent = (decimal_string, 0)
if exponent:
exponent = int(exponent)
if "." in radix:
## radix = 123.45, radix_decimal_part_len = 2
radix_decimal_part_len = long(len(radix.split(".")[1]))
## radix = 123.45, radix_as_long = 123.45 * 10**2 = 12345
radix_as_long = long(Decimal(radix) *
(10L**radix_decimal_part_len))
##corrected_exponent = 10 - 2 = 8
corrected_exponent = exponent - radix_decimal_part_len
## return 12345 * 10**8
result =  radix_as_long * 10L** corrected_exponent
else:
radix_as_long = long(radix)
result = radix_as_long * 10L**exponent
else:
if "." in radix:
radix_integer_part = long(radix.split(".")[0])
else:
radix_integer_part = long(radix)
result = radix_integer_part
return result


Working from inside decimal.py allows things to work faster, but anyone
wanting speed REALLY shouldn't use Decimal :). Now I'm trying clnum
("Rational and arbitrary precision floating point numbers"):
http://cheeseshop.python.org/pypi/clnum/1.2

Cheers,
Daniel

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


Re: [OT] why cd ripping on Linux is so slow

2006-08-12 Thread Patrick Useldinger
alf wrote:
> Hi,
> 
> I try to ip some music CD and later convert it into mp3 for my mp3 
> player, but can not get around one problem. ripping from Linux is 
> extremely slow  like 0.5x of CD speed.
> 
> In contrary, on M$ Windows it takes like a few minutes to have CD ripped 
> and compresses into wmf yet I do not knowhow to get pure wavs...
> 
> Hope I find someone here helping me with that 

This is really OT, and you might be better off looking in Linux forums 
like http://www.linuxquestions.org/. That said, it's likely that your 
DMA is not switched on. Ask your question in the aforementioned forums, 
and make sure to state which distribution you are using.

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


Re: Using a dictionary to pass data to/from embedded python functions

2006-08-12 Thread Alex Martelli
wardm <[EMAIL PROTECTED]> wrote:

> I have created a Dict object in a C++ App that calls (embedded) Python
> functions.
  [[snip snip]]
> This python code throws an exception when it attempts to access the 
> "VarDictionary".
> Does anyone know why this fails ?

It fails due to some code of yours that you have not included: in other
words, the minimal application which embeds Python using _only_ the code
you show us does not exhibit the failure.

I wrote the following file za.c:

#include "Python.h"
#include "stdio.h"
#include "stdlib.h"

int main()
{
printf("start\n");
putenv("PYTHONPATH=.");
Py_Initialize();
printf("inited\n");
PyObject* m_pVarDictionary = PyDict_New();
printf("dict is %p\n", m_pVarDictionary);
PyObject* m_pInterfaceModule =
PyImport_AddModule("InterfaceModule");
printf("modu is %p\n", m_pInterfaceModule);
int status = PyModule_AddObject(m_pInterfaceModule, "VarDictionary"
,
m_pVarDictionary);
printf("stat is %d\n", status);
PyObject* m_pScriptModule = PyImport_ImportModule("MyScriptModule");
printf("impo is %p\n", m_pScriptModule);

PyObject* func = PyObject_GetAttrString(m_pScriptModule,
"functionName");
printf("func is %p\n", func);
if (func && PyCallable_Check(func)) {
   PyObject* ret = PyObject_CallObject(func, NULL);
   printf("retu is %p\n", ret);
}
printf("done\n");
return 0;
}

and the following file MyScriptModule.py:

import InterfaceModule

def functionName():
print "hello"
print dir(InterfaceModule)
print "that's all"
return

and proceeded to compile and execute as follows: [[Note: it does not
matter that I'm using 2.5, the code is just as fine with previous
versions -- it just happens that 2.5 is what I'm using right now in
order to help out with 2.5's beta testing]]:

brain:~/pyex alex$ gcc -c za.c -I/usr/local/include/python2.5
brain:~/pyex alex$ gcc -o za za.o -L/usr/local/lib/python2.5/config/
-lpython2.5
brain:~/pyex alex$ ./za

and observed exactly the kind of output I predicted [[Note: the exact
addresses printed of course do not matter]]:

start
inited
dict is 0x51c780
modu is 0x520230
stat is 0
impo is 0x5202d0
func is 0x513770
hello
['VarDictionary', '__doc__', '__name__']
that's all
retu is 0xe57c0
done
brain:~/pyex alex$ 

As you see, in particular, VarDictionary is right up there in
InterfaceModule's dir.


There's a well-known essay by Eric Raymond, "How to ask questions the
smart way", at  -- it
seems to me that you, quite commendably, follow most of Eric's advice,
but it's still worth reading -- the key point by which you could help us
to help you is what Eric mentions as "If you have a large, complicated
test case that is breaking a program, try to trim it and make it as
small as possible".

In this case, you should try to trim your code down to the smallest
program using this approach, which you believe should work in a certain
way but actually doesn't.  The exact code you posted plus the minimal
additions to make it a compilable program does work the way you appear
to desire, as I show above; therefore, there must be something else in
your code that is breaking things.  Do tiny steps of addition and
restructuring to move this minimal skeleton towards the direction of
your bigger program (that does not behave this way) until you've found
exactly the "largest" version that still succeeds, and the minisculely
larger "smallest" version that fails -- the tiny difference between the
two must then be the root of the problem, and if the reason is not clear
at that point then posting here again is exactly the right thing to do.

Perhaps you're falling afoul of the fact that (as documented e.g. at
) PyModule_AddObject is a
"convenience function" that steals a reference to the value -- so you
end up with just one reference to the dictionary object, and if for some
reason you decref it, the object gets garbage collected.  But, that's
just a wild guess on my part, since you have not shown us any code
performing (for example) any decrefs.


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


Re: Inconsistency producing constant for float "infinity"

2006-08-12 Thread Alex Martelli
Tim Peters <[EMAIL PROTECTED]> wrote:
   ...
> It has a much better chance of working from .pyc in Python 2.5.
> Michael Hudson put considerable effort into figuring out whether the
> platform uses a recognizable IEEE double storage format, and, if so,
> marshal and pickle take different paths that preserve infinities,
> NaNs, and signed zeroes.

Isn't marshal constrained to work across platforms (for a given Python
release), and pickle also constrainted to work across releases (for a
given protocol)?  I'm curious about how this still allows them to "take
different paths" (yeah, I _could_ study the sources, but I'm lazy:-)...


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


start a multi-sockets server (a socket/per thread) with different ports but same host

2006-08-12 Thread zxo102
Hi,
   I am doing a small project using socket server and thread in python.
 This is first time for me to use socket and thread things.
   Here is my case. I have 20 socket clients.  Each client send a set
of sensor data per second to a socket server.  The socket server will
do two things: 1. write data into a file via bsddb; 2. forward the data
to a GUI written in wxpython.
   I am thinking the code should work as follow (not sure it is
feasible)
  20 threads, each thread takes care of a socket server with a
different port.
   I want all socket servers start up and wait for client connection.
In the attached demo code, It stops at the startup of first socket
server somewhere in the following two lines and waits for client call:

   lstn.listen(5)
   (clnt,ap) = lstn.accept()

  Any ideas how to handle these 20 clients?  Really appreciate your
suggestions.

Thanks a lot.

Ouyang


import socket
import sys
import threading
class srvr(threading.Thread):
   v = ''
   vlock = threading.Lock()
   id = 0  # next available thread number
   def __init__(self,clntsock):
  threading.Thread.__init__(self)
  self.myid = srvr.id
  srvr.id += 1
  self.myclntsock = clntsock
   def run(self):
  while 1:
 k = self.myclntsock.recv(1)
 if k == '': break
 # update v in an atomic manner
 srvr.vlock.acquire()
 srvr.v += k
 srvr.vlock.release()
 self.myclntsock.send(srvr.v)
  self.myclntsock.close()

#lstn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#port = int(sys.argv[1])  # server port number
#lstn.bind(('', port))
#lstn.listen(5)
nclnt = 20
mythreads = []  # list of all the threads

for i in range(nclnt):
   lstn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
   lstn.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
   lstn.bind(('', 2000+i+1))
   lstn.listen(5)
   (clnt,ap) = lstn.accept()
   s = srvr(clnt)
   mythreads.append(s)
   s.start()

# shut down the server socket, since it's not needed anymore
#lstn.close()

# wait for all threads to finish
for s in mythreads:
   s.join()

print 'the final value of v is', srvr.v

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


Re: matplotlib, wxPanel inside a wxPanel

2006-08-12 Thread ajaksu
Sam wrote:
> Hello,

Hi there Sam :)

> I'm beginning to think that what i'm trying to do isn't actually
> possible, and that i'll need to put it in a frame instead, which is a
> pity.

Indeed, if that is the case... as I'll need to do exactly that! But see
below ;)

> On the other hand, when i create graph_panel and put this inside of
> main_panel, NavigationToolbar2 does not work. The graph and toolbar are
> both displayed, but none of the buttons on the toolbar do anything.

I've been bitten by things that sounded similar to this and were
related to sloppy cut'n'paste that resulted in different hierarchies of
wx elements. If you post your code we can try to spot mistakes like
those.

As a general advice, go for a clean frame with a main_panel, a
graph_panel and sprinkle "print" statements (specially around events)
to find out what is happening.

> Can anyone please advise if what i'm trying to do is possible and if
> so, provide a small example? I'm running windows XP, python 2.4,
> wxpython 2.6.

I'll try to get around that one later today, but on win98 :)

Daniel

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


self=pickle.load(file)? (Object loads itself)

2006-08-12 Thread Anton81
Hi!

it seems that

class Obj:
def __init__(self):
f=file("obj.dat")
self=pickle.load(f)
...

doesn't work. Can an object load itself with pickle from a file somehow?
What's an easy solution?

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


Recurse Directories and process files in directory

2006-08-12 Thread KraftDiner
Hi I need help writing a python script that traverses (recursivly) a
directory and its sub directories and processes all files in the
directory.  So at each directory if there are files in it I must build
a list of those files and process them by exectuing a system command
(exec?)

Can some one tell me what methods to use to:
a) Walk the directory tree
b) execute a system command with parameters.

TIA.

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


trouble with replace

2006-08-12 Thread f pemberton
I have a string (xdata) and theres a newline after every 17 characters
of the string. I was wondering how I can replace multiple substrings
multiple times within a string? To put it another way, this is what i
want to do.

Substring to find ("abcdef") replace it with ("highway")
search again, substring to find ("defgef") replace it with
("news").Search again and find ("effwer") replace it with
("monitor").Example string to search under is '''defgefabcdefy


  effwerbyuuuterrfr'''

I've tried using replace but its not working for me.
xdata.replace('abcdef', 'highway')
xdata.replace('defgef', 'news')
xdata.replace('effwer', 'monitor')
Basically I would want to get the output of   "newshighwayy


   monitorbyuuuterrfr"

Thanks, any help would be appreciated.

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


xtopdf: PDF creation / conversion toolkit: alpha release of v1.3

2006-08-12 Thread vasudevram

Hi group,

xtopdf: PDF creation / conversion toolkit: alpha release of v1.3


This is actually a somewhat preliminary announcement, but may be of
interest to developers / users  who know Python and/or have earlier
checked out my xtopdf PDF creation / conversion toolkit:


I've released (via my web site, not yet properly packaged/documented
and put on the SourceForge site, that will be done in some days), the
next version of xtopdf: v1.3. This version adds support for conversion
of CSV, TDV (Tab Delimited Values) and XLS (limited support) to PDF.
v1.3 also adds some GUI tools written using wxPython (v1.0 had only
command-line tools and a library for developers).


Users/developers will need to install wxPython and properly configure
it to work with their Python installation before they can use these GUI

tools. This is fairly straightforward on Windows using the .MSI or .EXE

(can't remember which it is right now) installer for wxPython, but on
Linux, you'll need to know how to handle the tools that are used to
build packages from source code, i.e. make, configure, etc. Also,
wxPython is a medium-sized package - it took around an hour or two to
fully build on my reasonably fast PC. So be patient (get yourself a
coffee or two, or do something else in another Linux console / window
while wxPython builds :-)


Those who know even basic Python should be able to install and run both

xtopdf v1.0 and the new stuff in v1.3, at least for the command-line
tools (the programs are quite simple).


Main SourceForge site for xtopdf v1.0:
http://sourceforge.net/projects/xtopdf


There are no releases between 1.0 and 1.3 :-)


URL for xtopdf v1.3 on my web site:
http://www.dancingbison.com/xtopdf-1.3.zip


URL for xtopdf v1.0 on my web site:
http://www.dancingbison.com/xtopdf-1.0.tar.gz


wxPython site:
http://wxpython.org


xtopdf requires both Python and the open source version of the
ReportLab toolkit.


ReportLab site:
http://www.reportlab.org


More details (for Windows) are available in a guide here:
http://itext.ugent.be/library/question.php?id=41


I'd appreciate any feedback, about bugs (v1.3 is tested but not a lot
yet, that will be done in next days), or how / what for anyone is using

it.


Apart from the "proper" packaging/documenting and upload to SourceForge

(and my web site), I shall be writing and posting more about how to use

it, etc. in the coming days.


Enjoy, and
Thanks
Vasudev


===
Vasudev Ram
Software consulting and training
http://www.dancingbison.com 
===

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


Re: start a multi-sockets server (a socket/per thread) with different ports but same host

2006-08-12 Thread Jean-Paul Calderone
On 12 Aug 2006 09:00:02 -0700, zxo102 <[EMAIL PROTECTED]> wrote:
>Hi,
>   I am doing a small project using socket server and thread in python.
> This is first time for me to use socket and thread things.
>   Here is my case. I have 20 socket clients.  Each client send a set
>of sensor data per second to a socket server.  The socket server will
>do two things: 1. write data into a file via bsddb; 2. forward the data
>to a GUI written in wxpython.
>   I am thinking the code should work as follow (not sure it is
>feasible)
>  20 threads, each thread takes care of a socket server with a
>different port.
>   I want all socket servers start up and wait for client connection.
>In the attached demo code, It stops at the startup of first socket
>server somewhere in the following two lines and waits for client call:
>

Threads aren't the best way to manage the concurrency present in this
application.  Instead, consider using non-blocking sockets with an
event notification system.  For example, using Twisted, your program
might look something like this:

from twisted.internet import reactor, protocol, defer

class CumulativeEchoProtocol(protocol.Protocol):
def connectionMade(self):
# Stop listening on the port which accepted this connection
self.factory.port.stopListening()

# Set up a list in which to collect the bytes which we receive
self.received = []


def connectionLost(self, reason):
# Notify the main program that this connection has been lost, so
# that it can exit the process when there are no more connections.
self.factory.onConnectionLost.callback(self)

def dataReceived(self, data):
# Accumulate the new data in our list
self.received.append(data)
# And then echo the entire list so far back to the client
self.transport.write(''.join(self.data))

def allConnectionsLost():
# When all connections have been dropped, stop the reactor so the
# process can exit.
reactor.stop()

def main():
# Set up a list to collect Deferreds in.  When all of these Deferreds
# have had callback() invoked on them, the reactor will be stopped.
completionDeferreds = []
for i in xrange(20):
# Make a new factory for this port
f = protocol.ServerFactory()

# Make a Deferred for this port's connection-lost event and make
# it available to the protocol by way of the factory.
d = defer.Deferred()
f.onConnectionLost = d
completionDeferreds.append(d)
f.protocol = CumulativeEchoProtocol

# Start listening on a particular port number with this factory
port = reactor.listenTCP(2000 + i + 1, f)

# Make the port object available to the protocol as well, so that
# it can be shut down when a connection is made.
f.port = port

# Create a Deferred which will only be called back when all the other
# Deferreds in this list have been called back.
d = defer.DeferredList(completionDeferreds)

# And tell it to stop the reactor when it fires
d.addCallback(lambda result: allConnectionsLost())

# Start the reactor so things can start happening
reactor.run()

if __name__ == '__main__':
main()

Hope this helps,

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


Re: self=pickle.load(file)? (Object loads itself)

2006-08-12 Thread Jean-Paul Calderone
On Sat, 12 Aug 2006 18:36:32 +0200, Anton81 <[EMAIL PROTECTED]> wrote:
>Hi!
>
>it seems that
>
>class Obj:
>def __init__(self):
>f=file("obj.dat")
>self=pickle.load(f)
>...
>
>doesn't work. Can an object load itself with pickle from a file somehow?
>What's an easy solution?

You are trying to implement a constructor (__new__) for the Obj class, but you 
have actually implemented the initializer (__init__).  In order to be able to 
control the actual creation of the instance object, you cannot use the 
initializer, since its purpose is to set up various state on an already created 
instance.  Instead, you may want to use a class method:

class Obj:
def fromPickleFile(cls, fileName):
return pickle.load(file(fileName))
fromPickleFile = classmethod(fromPickleFile)

You can then use this like so:

inst = Obj.fromPickleFile('obj.dat')

Jean-Paul


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


Re: self=pickle.load(file)? (Object loads itself)

2006-08-12 Thread Gary Herron
Anton81 wrote:
> Hi!
>
> it seems that
>
> class Obj:
> def __init__(self):
> f=file("obj.dat")
> self=pickle.load(f)
> ...
>
> doesn't work. Can an object load itself with pickle from a file somehow?
> What's an easy solution?
>
> Anton
>   
That won't work, but the following will. An object's attributes can be 
accessed and set through the __dict__ attribute, and its class through 
the __class__ attribute:


 >>> class A: # define class A
... pass
...
 >>> a = A() # create an instance
 >>> a.__dict__ # It has no attributes
{}
 >>> a.__dict__ = {'c':1, 'b':2} # Give it some
 >>> a.b # Verify
2
 >>> a.c
1
 >>> a.__class__ # Examine its class


 >>> class B:
... pass
...
 >>> a.__class__ = B # Change its class
 >>> a.__class__ # Verify


Both the __dict__ and the __class__.__name__ could be pickled.

Gary Herron


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


Re: trouble with replace

2006-08-12 Thread Marc 'BlackJack' Rintsch
In <[EMAIL PROTECTED]>, f pemberton
wrote:

> I've tried using replace but its not working for me.
> xdata.replace('abcdef', 'highway')
> xdata.replace('defgef', 'news')
> xdata.replace('effwer', 'monitor')

`replace()` does not work in place.  You have to bind the result to a name
like::

  xdata = xdata.replace('abcdef', 'highway')

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Recurse Directories and process files in directory

2006-08-12 Thread vasudevram

KraftDiner wrote:
> Hi I need help writing a python script that traverses (recursivly) a
> directory and its sub directories and processes all files in the
> directory.  So at each directory if there are files in it I must build
> a list of those files and process them by exectuing a system command
> (exec?)
>
> Can some one tell me what methods to use to:
> a) Walk the directory tree
> b) execute a system command with parameters.
>
> TIA.

Hi,
Try os.walk().
Don't remember the syntax right now, should be straightforward. Check
the standard Python docs that come with your Python installation. Or
start python and do:

import os
print os.walk.__doc__

And executing a system comand is os.system(...).

Caveat: there can be security risks with system(). Depends how you use
it and who you let use it with what arguments. Similar to risks with
CGI forms.

HTH
~~
Vasudev Ram
xtopdf - PDF creation/converson toolkit:
http://www.dancingbison.com/products.html
~~

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


Re: iterator wrapper

2006-08-12 Thread Simon Forman
alf wrote:
> Simon Forman wrote:
> >>
> >>>|>> I = ([n] for n in i)
> >>
> >>This is nice but I am iterating thru hude objects (like MBs) so you know ...
> >>
> >
> > No, I don't know...  :-)
>
> potentially my source lists are huge - so wanted to avoid unnecessary
> memory allocation
>
>
> > My friend, I think you've misunderstood.  Observe:
> >
> > |>> L = [n for n in range(3)]
> > |>> G = (n for n in range(3))
> > |>> L
> > [0, 1, 2]
> > |>> G
> > 
>
> well, I am in the python 2.3 word where generator comprehensions seem
> not to work. So I just took it a preallocated list comprehention. still
> wonder if there would be a difference between:
>
> G = (n for n in range(3))  - this creates the huge list there
> G = (n for n in xrange(3)) - this (at least to my understanding)
>   does not
>

Yes, you've got it, the xrange() version will not allocate a huge list.

It's not part of your main question, and I understand that there may be
reasons why you can't, but consider upgrading to 2.4 (or very soon now
2.5...)

Meanwhile, in 2.3 both John Machin's and Paul Rubin's solutions will do
the trick (as you already know ;-)  )

> >
> > List comprehensions [] create lists, generator comprehensions () create
> > generators.
> >
>
>
> > Generator comprehensions work "just-in-time", pulling items from
> > whatever they're iterating over as they themselves are iterated over,
> > as I hope this example makes clear:
> >
>  >[...]
>
> got it now ... thx or the lesson
>
>
> A.

No problem.  These are things I learned over time, it's fun to share
the knowledge. :)

Peace,
~Simon

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


Re: Recurse Directories and process files in directory

2006-08-12 Thread Gary Herron
KraftDiner wrote:
> Hi I need help writing a python script that traverses (recursivly) a
> directory and its sub directories and processes all files in the
> directory.  So at each directory if there are files in it I must build
> a list of those files and process them by exectuing a system command
> (exec?)
>
> Can some one tell me what methods to use to:
> a) Walk the directory tree
> b) execute a system command with parameters.
>   

You're in luck. Both these are easy.

os.walk iterates through the hierarchy of directories and their contents

os.system executes any command given as a string (which you can build 
however you want). Or you might use the newer "subprocess" module.

Gary Herron

> TIA.
>
>   

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


Re: hide python code !

2006-08-12 Thread Cameron Laird
In article <[EMAIL PROTECTED]>,
Bayazee <[EMAIL PROTECTED]> wrote:
>Hi,
>ThnaX for Your Answers ...
>i am an open source programmer ... ! and i never like to write a closed
>source app or hide my codes ! it just a question that i must
>answer/solve it!
>one of site ( www.python.ir ) users asked this question ! but
>unfortunately i have't any solution  to it ! so i ask it here to know
>your concepts ...
>so sorry for my inferior question
>but i realy want to know a way to do it(if it possible) ! and it is't
>mean that i want to do it !
>Best Regard's
>

I disagree with the respondents who have told you it's
impossible.  While I can't make time now to answer your
question fully, I recommend that you read up on Pyrex
and py2exe.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python/Tk not working in Linux

2006-08-12 Thread Cameron Laird
In article <[EMAIL PROTECTED]>,
Marc 'BlackJack' Rintsch  <[EMAIL PROTECTED]> wrote:
>In <[EMAIL PROTECTED]>, BinnyVA wrote:
>
>> I am using Fedora Core 3 Linux and I have a problem with Tk in Python.
>> Whenever I try to run a tk script, I get the error...
>> 
>> ---
>> Traceback (most recent call last):
>> File "Tk.py", line 1, in ?
>> from Tkinter import *
>> File "/usr/local/lib/python2.4/lib-tk/Tkinter.py", line 38, in ?
>> import _tkinter # If this fails your Python may not be configured for
>> Tk
>> ImportError: No module named _tkinter
>> ---
>
>The `_tkinter` module is the binary "bridge" to the Tk system.  If it's
>not found it's most likely that the relevant header files of tcl/tk where
>not installed before compiling Python or there was a problem while
>compiling this extension.
>
>This seems to be your self compiled Python.  Are you sure you got the same
>error when using the version from your distribution?  I would suspect you
>get an `ImportError` on `Tkinter` there.  Some distributions move the
>`Tkinter` stuff into an own package.  Search for a package called
>`python-tk` or `python-tkinter` or similar.
.
.
.
ALSO, Fedora has been a particular problem at times--I haven't
researched where FC3 is in this regard--because it distributed
non-standard Tk-s that yielded weird breakages.  If you're
caught in one of these conflicts, you might not be able to 
generate from sources correctly because development headers are
inconsistent with sources.

So:  you can generate all of Python and Tk from sources you
believe are clean; or you can take advantage of full binaries,
such as ActivePython, that someone else has made.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [OT] why cd ripping on Linux is so slow

2006-08-12 Thread alf
Patrick Useldinger wrote:
> 
> This is really OT:

yes it is


> and you might be better off looking in Linux forums 
> like http://www.linuxquestions.org/. That said, it's likely that your 
> DMA is not switched on.


thx for the hint and the reference - see hopefully I got to know where 
to find the answer.


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


Re: trouble with replace

2006-08-12 Thread f pemberton
Marc 'BlackJack' Rintsch wrote:
> In <[EMAIL PROTECTED]>, f pemberton
> wrote:
>
> > I've tried using replace but its not working for me.
> > xdata.replace('abcdef', 'highway')
> > xdata.replace('defgef', 'news')
> > xdata.replace('effwer', 'monitor')
>
> `replace()` does not work in place.  You have to bind the result to a name
> like::
>
>   xdata = xdata.replace('abcdef', 'highway')
>
> Ciao,
>   Marc 'BlackJack' Rintsch

lol, you probably will not believe me but I actually knew that already.
 I just forgot to add that part in my original post. When I try and
replace what happens is the first replace works fine but when I try and
do a second replace on a different part of the same string, the program
will print the string a second time(which I do not want). How can you
do 2 or more replaces in one line of code?

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


Re: iterator wrapper

2006-08-12 Thread alf
Simon Forman wrote:

> Yes, you've got it, the xrange() version will not allocate a huge list.
> 
> It's not part of your main question, and I understand that there may be
> reasons why you can't, but consider upgrading to 2.4 (or very soon now
> 2.5...)

upgrade to 2.4 is on the roadmap and will take place soon  the app 
is just too big and must be stable so since all works in 2.3 well we 
stick to it.

there are some parts (related to wx where I noted that 2.4 behaves 
differently so it needs some attention) ...


other reason is there is a number of users using customized python (on 
top of standard install there is wx, twistedmatrix, matplot and a lot of 
small libs/modules == 200MB) so it is kind of pin to migrate that from 
the deployment point of view. Tried to have Python on network drive but 
it is painfully slow. wonder what strategy should I choose while the 
priority is the stable app.

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


Re: wxPython ListBook Class, Label Position w/ ImageList

2006-08-12 Thread jean-michel bain-cornu
Hi,
> By default the label position of an image list is below the image. Is
> there any way to change this?
> 

If it exists, it's undocumented, and there is not a sample.
Did you ask the wx forum ? It's probably a better place to have this 
kind of information. If they provide you a C sample, I could help you to 
convert it in python.
Anyway, if you find out something, I'm interested...

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


Re: reading from sockets

2006-08-12 Thread Simon Forman
AndrewTK wrote:
> > I'm assuming that your server waits to receive the word 'hello' before
> > replying with the three strings (first, second, and third)?  So once your
>
> Nope - actually it's a threaded "server", with the main thread simply
> dumping network input to the console and command line input being
> directly dumped to the network output stream.
>
> I confess to having typed the three lines manually...!
>
> It's at:
> http://www.dcs.st-and.ac.uk/~atk1/perso/java/servers/RespondingServer.java
>
> It launches on the command line with
> java RespondingServer _port_
>
> _port_ being the port number it should listen for data on.

Hy.  I tried reading your Java code..  What can I say?  There's a
reason why I like Python...  :-)

I couldn't see anything obviously broken in your server, but there's
definitely nothing wrong with your python code, except that you call
flush() on the socket (fixed in your posted code but not in the linked
code.)

Here are the results of testing, with netcat substituted for your java
server:

# on the server side:
[EMAIL PROTECTED]:~ $ netcat -p 54321 -l
hellohi there
how are you
I'm fine thanks

[EMAIL PROTECTED]:~ $



# on the client side:
[EMAIL PROTECTED]:~ $ python delme.py
'hi there\n'
'how are you\n'
"I'm fine thanks\n"
[EMAIL PROTECTED]:~ $


So I'm guessing it's something wrong in your java server.

HTH,
~Simon

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


Re: start a multi-sockets server (a socket/per thread) with different ports but same host

2006-08-12 Thread zxo102
Jean-Paul,
Thanks a lot. The code is working. The python twisted is new to me too.
Here are my three more questions:
1. Since the code need to be started in a wxpyhon GUI (either by
clicking a button or up with the GUI),  do I have to run the code in a
thread (sorry, I have not tried it yet)?
2. How can I grab the client data in the code? Can you write two lines
for that? I really appreciate that.
3. After I change
self.transport.write(''.join(self.data))
   to
self.transport.write(''.join(data))
  and scan all the ports with the following code twice (run twice).
First round scanning says "succefully connected". But second round
scanning says "failed". I have to restart your demo code to make it
work.

Ouyang


import sys, threading, socket

class scanner(threading.Thread):
   tlist = []  # list of all current scanner threads
   maxthreads = int(sys.argv[2])  # max number of threads we're
allowing
   evnt = threading.Event()  # event to signal OK to create more
threads
   lck =  threading.Lock()  # lock to guard tlist
   def __init__(self,tn,host):
  threading.Thread.__init__(self)
  #self.threadnum = tn  # thread ID/port number
  self.threadnum = 2000+tn  # thread ID/port number
  self.host = host  # checking ports on this host
   def run(self):
  s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
  try:
 s.connect((self.host, self.threadnum))
 print "%d:  successfully connected" % self.threadnum
 s.close()
  except:
 print "%d:  connection failed" % self.threadnum
  # thread is about to exit; remove from list, and signal OK if we
  # had been up against the limit
  scanner.lck.acquire()
  scanner.tlist.remove(self)
  print "%d:  now active --" % self.threadnum, scanner.tlist
  if len(scanner.tlist) == scanner.maxthreads-1:
 scanner.evnt.set()
 scanner.evnt.clear()
  scanner.lck.release()
   def newthread(pn,hst):
  scanner.lck.acquire()
  sc = scanner(pn,hst)
  scanner.tlist.append(sc)
  scanner.lck.release()
  sc.start()
  print "%d:  starting check" % pn
  print "%d:  now active --" % pn, scanner.tlist
   newthread = staticmethod(newthread)

def main():
   host = sys.argv[1]
   #for i in range(1,100):
   for i in range(20):
  scanner.lck.acquire()
  print "%d:  attempting check" % i
  # check to see if we're at the limit before starting a new thread
  if len(scanner.tlist) >= scanner.maxthreads:
 # too bad, need to wait until not at thread limit
 print "%d:  need to wait" % i
 scanner.lck.release()
 scanner.evnt.wait()
  else:
 scanner.lck.release()
  scanner.newthread(i,host)
   for sc in scanner.tlist:
  sc.join()

if __name__ == '__main__':
main()






Jean-Paul Calderone 写道:

> On 12 Aug 2006 09:00:02 -0700, zxo102 <[EMAIL PROTECTED]> wrote:
> >Hi,
> >   I am doing a small project using socket server and thread in python.
> > This is first time for me to use socket and thread things.
> >   Here is my case. I have 20 socket clients.  Each client send a set
> >of sensor data per second to a socket server.  The socket server will
> >do two things: 1. write data into a file via bsddb; 2. forward the data
> >to a GUI written in wxpython.
> >   I am thinking the code should work as follow (not sure it is
> >feasible)
> >  20 threads, each thread takes care of a socket server with a
> >different port.
> >   I want all socket servers start up and wait for client connection.
> >In the attached demo code, It stops at the startup of first socket
> >server somewhere in the following two lines and waits for client call:
> >
>
> Threads aren't the best way to manage the concurrency present in this
> application.  Instead, consider using non-blocking sockets with an
> event notification system.  For example, using Twisted, your program
> might look something like this:
>
> from twisted.internet import reactor, protocol, defer
>
> class CumulativeEchoProtocol(protocol.Protocol):
> def connectionMade(self):
> # Stop listening on the port which accepted this connection
> self.factory.port.stopListening()
>
> # Set up a list in which to collect the bytes which we receive
> self.received = []
>
>
> def connectionLost(self, reason):
> # Notify the main program that this connection has been lost, so
> # that it can exit the process when there are no more connections.
> self.factory.onConnectionLost.callback(self)
>
> def dataReceived(self, data):
> # Accumulate the new data in our list
> self.received.append(data)
> # And then echo the entire list so far back to the client
> self.transport.write(''.join(self.data))
>
> def allConnectionsLost():
> # When all connections have been dropped, stop the reactor so the
> # process can exit.
> reactor.stop()
>
> def main():
> # Set up a list to collect Defer

Re: trouble with replace

2006-08-12 Thread Simon Forman
f pemberton wrote:
> Marc 'BlackJack' Rintsch wrote:
> > In <[EMAIL PROTECTED]>, f pemberton
> > wrote:
> >
> > > I've tried using replace but its not working for me.
> > > xdata.replace('abcdef', 'highway')
> > > xdata.replace('defgef', 'news')
> > > xdata.replace('effwer', 'monitor')
> >
> > `replace()` does not work in place.  You have to bind the result to a name
> > like::
> >
> >   xdata = xdata.replace('abcdef', 'highway')
> >
> > Ciao,
> > Marc 'BlackJack' Rintsch
>
> lol, you probably will not believe me but I actually knew that already.
>  I just forgot to add that part in my original post. When I try and
> replace what happens is the first replace works fine but when I try and
> do a second replace on a different part of the same string, the program
> will print the string a second time(which I do not want).

Um, don't print the string until after you're done replacing?  :-)

Seriously though, since there are no print statements, etc.., in your
posted code, it's hard to understand exactly what your problem is.

> How can you
> do 2 or more replaces in one line of code?

In any event, there is a neat method of "single-pass multiple string
substitution using a dictionary" here:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81330  It uses
a regular expression, so I'd guess it wouldn't be to hard to get it to
work in multiline mode.

Peace,
~Simon

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


Re: self=pickle.load(file)? (Object loads itself)

2006-08-12 Thread Simon Forman
Anton81 wrote:
> Hi!
>
> it seems that
>
> class Obj:
> def __init__(self):
> f=file("obj.dat")
> self=pickle.load(f)
> ...
>
> doesn't work. Can an object load itself with pickle from a file somehow?
> What's an easy solution?
>
> Anton

Why are you trying to do this?  Usually you would just say obj =
pickle.load(f) and be done with it (you could manipulate obj after it's
created, of course.)  Why do you want to do obj = Obj() but have the
obj come from "obj.dat"?

Just curious.

Peace,
~Simon

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


Re: trouble with replace

2006-08-12 Thread Simon Forman

Simon Forman wrote:
> f pemberton wrote:
> > Marc 'BlackJack' Rintsch wrote:
> > > In <[EMAIL PROTECTED]>, f pemberton
> > > wrote:
> > >
> > > > I've tried using replace but its not working for me.
> > > > xdata.replace('abcdef', 'highway')
> > > > xdata.replace('defgef', 'news')
> > > > xdata.replace('effwer', 'monitor')
> > >
> > > `replace()` does not work in place.  You have to bind the result to a name
> > > like::
> > >
> > >   xdata = xdata.replace('abcdef', 'highway')
> > >
> > > Ciao,
> > >   Marc 'BlackJack' Rintsch
> >
> > lol, you probably will not believe me but I actually knew that already.
> >  I just forgot to add that part in my original post. When I try and
> > replace what happens is the first replace works fine but when I try and
> > do a second replace on a different part of the same string, the program
> > will print the string a second time(which I do not want).
>
> Um, don't print the string until after you're done replacing?  :-)
>
> Seriously though, since there are no print statements, etc.., in your
> posted code, it's hard to understand exactly what your problem is.
>
> > How can you
> > do 2 or more replaces in one line of code?
>
> In any event, there is a neat method of "single-pass multiple string
> substitution using a dictionary" here:
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81330  It uses
> a regular expression, so I'd guess it wouldn't be to hard to get it to
> work in multiline mode.
>
> Peace,
> ~Simon

Or just:

xdata = xdata.replace('abcdef', 'highway').replace('defgef',
'news').replace('effwer', 'monitor')

Hahahahaha

~Simon

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


Re: matplotlib, wxPanel inside a wxPanel

2006-08-12 Thread ajaksu
It seems to work (only tested with embedding_in_wx4.py). I guess it's
something related to things nesting in a slightly wrong way, right
enough to show up but wrong enough to only show up :)

I hope this helps.
Daniel

Substitute embedding_in_wx4.py's CanvasFrame with:

class CanvasFrame(wxFrame):
def __init__(self):
# Begin just like embedding_in_wx4.py
wxFrame.__init__(self,None,-1,
 'CanvasFrame',size=(550,350))

self.figure = Figure(figsize=(5,4), dpi=100)
self.axes = self.figure.add_subplot(111)
t = range(0,30)
s = [randint(1, 30)* random() * x for x in t]
self.axes.plot(t,s)
# Add panels from deepest level
self.main_panel = wxPanel(self, -1)
# Parent is main_panel:
self.graph_panel = wxPanel(self.main_panel, -1)
# self.canvas is child of  graph_panel...
self.canvas = FigureCanvas(self.graph_panel, -1, self.figure)
# ... as is textgraph
self.text_graph = wxTextCtrl(self.graph_panel, -1, "Hello!\n" +
"I'm in graph_panel",
style=wxTE_MULTILINE)
self.toolbar = MyNavigationToolbar(self.canvas, True)
self.toolbar.Realize()
self.graph_panel_sizer = wxBoxSizer(wxVERTICAL)

tw, th = self.toolbar.GetSizeTuple()
fw, fh = self.canvas.GetSizeTuple()
self.toolbar.SetSize(wxSize(fw, th))
self.graph_panel_sizer.Add(self.toolbar, 0, wxEXPAND)

# After the toolbar, add its siblings to graph_panel_sizer
self.graph_panel_sizer.Add(self.canvas, 1, wxEXPAND)
self.graph_panel_sizer.Add(self.text_graph)
self.graph_panel.SetSizer(self.graph_panel_sizer)
self.graph_panel.Fit()
# graph_panel is done, just add it to main_panel's sizer.

self.main_panel_sizer =  wxBoxSizer(wxVERTICAL)
self.text_in = wxTextCtrl(self.main_panel, -1,
"Inside main_panel",
style=wxTE_MULTILINE)
# Here:
self.main_panel_sizer.Add(self.graph_panel,1, wxEXPAND)
self.main_panel_sizer.Add(self.text_in,0, wxEXPAND)
self.main_panel.SetSizer(self.main_panel_sizer)
self.main_panel.Fit()

self.sizer = wxBoxSizer(wxVERTICAL)
self.sizer.Add(self.main_panel, 1, wxEXPAND)
self.sizer_text = wxBoxSizer(wxHORIZONTAL)
self.text_hi = wxTextCtrl(self, -1, "Hello :)",
 style=wxTE_MULTILINE)
self.text_out = wxTextCtrl(self, -1,"Outside main_panel",
  style=wxTE_MULTILINE|wxEXPAND)

self.sizer_text.Add(self.text_hi, 0, wxEXPAND)
self.sizer_text.Add(self.text_out, 0, wxEXPAND)
self.sizer.Add(self.sizer_text, 0, wxEXPAND)
EVT_PAINT(self, self.OnPaint)
self.toolbar.update()
self.SetSizer(self.sizer)
self.Fit()

def OnPaint(self, event):
self.canvas.draw()
event.Skip()

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


Re: Looking for a text file based wiki system written in Python

2006-08-12 Thread Jack
Thanks! Because it was so well known, I thought it was database-based  :)
> http://moinmoin.wikiwikiweb.de/

Any good and simple text file-based blog system in Python? 


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


_PyLong_FromByteArray

2006-08-12 Thread Dan Christensen
My student and I are writing a C extension that produces a large
integer in binary which we'd like to convert to a python long.  The
number of bits can be a lot more than 32 or even 64.  My student found
the function _PyLong_FromByteArray in longobject.h which is exactly
what we need, but the leading underscore makes me wary.  Is it safe to
use this function?  Will it continue to exist in future versions of
python?  Or is there some other method we should use?  We'd like
something fairly efficient...

Thanks,

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


Re: Password authentication systems

2006-08-12 Thread Tim Scheidemantle
Enabling shadow passwords stores them in /etc/shadow which is not world 
readable unlike /etc/passwd.  They would be encrytped regardless of the 
file they are in.


AlbaClause wrote:
> [EMAIL PROTECTED] wrote:
>
>   
>> This may only be tangentially related to Python, but since I am coding
>> a password authentication system in Python, I thought I would ask here.
>>
>> In Linux (and presumably other *NIX systems that support it), when
>> shadow passwords are enabled, the actual password is not stored.
>> Instead an encrypted version is stored.  Then, to authenticate the
>> password, the system re-encrypts the user's input to see if it matches
>> the stored, encrypted version.
>>
>> 
>
> Correct me if I'm wrong, but I believe that all Linux passwords are
> encrypted whether you enable shadow passwords or not.   I believe that when
> you enable shadow passwords, the encrypted passwords are stored in a file
> other than 'passwd'.  Is this not correct?
>
>   
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Kill process based on window name (win32)

2006-08-12 Thread drodrig
Thank you Roger. Your advice did the trick. For anyone interested, the
basic code to terminate a process (politely) would be something like
this (hwnd is retrieved using win32gui.EnumerateWindows):

# Get the window's process id's
t, p = win32process.GetWindowThreadProcessId(hwnd)
# Ask window nicely to close
win32gui.PostMessage(hwnd, win32con.WM_CLOSE, 0, 0)
# Allow some time for app to close
time.sleep(10)
# If app didn't close, force close
try:
handle = win32api.OpenProcess(win32con.PROCESS_TERMINATE, 0, p)
if handle:
win32api.TerminateProcess(handle,0)
win32api.CloseHandle(handle)
except:
pass:

Roger Upole wrote:
> drodrig wrote:
> > Hi.
> >
> > I am trying to close/kill all processes that show visible windows on
> > Windows XP. So far I've created a script that uses win32gui.EnumWindows
> > to iterate through all windows, check for which windows are visible,
> > then send a WM_CLOSE message to the window to request that it closes.
> > Of course, not all apps want to close nicely. At this point I need to
> > use something like TerminateProcess to kill the app, but how do I find
> > the process id (hopefully based on the window id).
> >
> > Thanks for any help.
> >
>
> win32process.GetWindowThreadProcessId should do the trick.
> 
>Roger

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


OT: SCALE 5x - Call For Papers

2006-08-12 Thread Ilan Rabinovitch
Hello,

Sorry for the offtopic post.  Just wanted to let the python community
know about our Call For Papers.

We just announced the CFP for SCALE 5x, the 2007 Southern California
Linux Expo,  We are non-profit / community run Linux, open-source and
free software conference.
Our fifth annual show will be held on Feb 10-11, 2007 at the Los
Angeles Airport Westin.

If you are working on an interesting in presenting on python or another
topic open-source related topic -- We invite you to submit a
presentation proposal as part of our call for papers.  I am including
details bellow.

Past presentations are available online (including slides and audio):
2006 - http://www.socallinuxexpo.org/past/2006/hours.php
2005 - http://www.socallinuxexpo.org/past/2005/hours.php
2003 - http://www.socallinuxexpo.org/past/2003/presentations.php
2002 - http://www.socallinuxexpo.org/past/2002/presentations.php

If you have any questions please feel free to contact the Call For
Papers team at : kapadia =at= socallinuxexp.org


CFP PDF:  http://www.socallinuxexpo.org/scale5x/cfp/scale5x.pdf


We look forward to seeing you at SCALE 5x!

Best regards,
Ilan Rabinovitch
Conference Chair
Southern California Linux Expo
http://www.socallinuxexpo.org
818-442-1865 Voice


2007 Southern CAlifornia Linux Expo (SCALE 5x)  Call For Papers

The USC, Simi/Conejo, and UCLA Linux User Groups are proud to announce
the  5th Annual Southern California Linux Expo scheduled for February
10-11, 2007 at  the Westin  Los Angeles Airport Hotel.

We invite you to share your work on Linux and Open Source projects with
the rest  of the community as well as exchange ideas with some of the
leading experts in these  fields. Details about SCALE 5X as well as
archives for the last few years can be found  at
http://www.socallinuxexpo.com.

Topics of interest include, but are not limited to:
- Linux Core
- Linux Kernel Enhancements
- Linux in the Infrastructure - Tools and Appliances
- Linux for Embedded Systems
- Linux Virtualization
- User Experience
- Linux Desktop Environments
- Productivity Applications for Linux
- Linux Multimedia
- Linux Games
- Linux Security
- Linux Deployments and Experiences: War Stories
- Other Open Source Projects
- LAMP
- Voice over IP (VoIP)
- Administration techniques for specific distributions
- Open source Licensing
- Government policies with Open Source

The proposals should be submitted in form of a 1-page extended abstract
comprising:

1. Title for the talk
2. Name, Affiliation, Bio, a passport size picture (optional) and
contact email ad-  dress of the Presenter
3. What will be covered? A bulleted list or a brief description of the
main points to  be presented should be submitted. Please include enough
detail that will enable  the committee to evaluate the proposal.
4. Any specific requirements needed for the presentation other than an
overhead  projector and a microphone.


Submission formats in txt and pdf will be accepted. Presentations are
allotted a time  slot of about 45 minutes. All proposals are to be sent
to [EMAIL PROTECTED]


Important Dates:
=
20 July, 2006: CFP Opens
20 Nov, 2006: Last date for abstracts/proposals
20 Dec, 2006: Last date for notification of acceptance
10 Feb, 2007: Conference starts

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


Re: Python share CPU time?

2006-08-12 Thread Steve Holden
Yannick wrote:
> Thank you all for the detailled answers.
> 
> What I would like to achieve is something like:
> 
> # main loop
> while True:
> for robot in robots:
> robot.start()
> robot.join(0.2) # wait 200ms
> if robot.is_active():
> robot.stop()
> # run all the game physics, pause, frame/rate, etc...
> 
> Unfortunately the stop() call doesn't exist in Python.
> 
> By using a generator I would make the assumption that every robot is
> playing fair, and would yield often. But I cannot control this as
> eventually robots would be coded by third parties.
> 
> Using Python scheduler would allow me to share time equally between
> each robot, but then I would loose the ability to have a main thread
> organizing everything.
> 

I think the best way is to give each robot its own thread. That way the 
interpreter will share time between each of the robots (whether or not 
they sleep or yield) on a reasonably fair basis.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb   http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

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


Re: trouble with replace

2006-08-12 Thread Jason Nordwick
>>> pats = ['abcdef', 'defgef', 'effwer']
>>> reps = ['highway', 'news', 'monitor']
>>> s = 'defgefabcdefy\n\n\n  effwerbyuuuterrfr'
>>> reduce(lambda x,y: x.replace(*y), zip(pats,reps), s)
'newshighwayy\n\n\n  monitorbyuuuterrfr'



f pemberton wrote:
> I have a string (xdata) and theres a newline after every 17 characters
> of the string. I was wondering how I can replace multiple substrings
> multiple times within a string? To put it another way, this is what i
> want to do.
> 
> Substring to find ("abcdef") replace it with ("highway")
> search again, substring to find ("defgef") replace it with
> ("news").Search again and find ("effwer") replace it with
> ("monitor").Example string to search under is '''defgefabcdefy
> 
> 
>   effwerbyuuuterrfr'''
> 
> I've tried using replace but its not working for me.
> xdata.replace('abcdef', 'highway')
> xdata.replace('defgef', 'news')
> xdata.replace('effwer', 'monitor')
> Basically I would want to get the output of   "newshighwayy
> 
> 
>monitorbyuuuterrfr"
> 
> Thanks, any help would be appreciated.
> 

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


Re: Recurse Directories and process files in directory

2006-08-12 Thread BartlebyScrivener
KraftDiner wrote:
> Hi I need help writing a python script that traverses (recursivly) a
> directory and its sub directories and processes all files in the
> directory.

There's a great os.walk + wrapper in the Python cookbook. I once had an
unrelated problem with it, but check it out and see if it meets your
needs.

http://tinyurl.com/zwbrb

rd

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


Re: trouble with replace

2006-08-12 Thread Tim Chase
 pats = ['abcdef', 'defgef', 'effwer']
 reps = ['highway', 'news', 'monitor']
 s = 'defgefabcdefy\n\n\n  effwerbyuuuterrfr'
 reduce(lambda x,y: x.replace(*y), zip(pats,reps), s)


The reduce() method fairly works well if you have it as a 
dictionary as well:

 >>> m = {'effwer': 'monitor', 'abcdef': 'highway', 'defgef': 'news'}
 >>> s = 'defgefabcdefy\n\n\n  effwerbyuuuterrfr'
 >>> reduce(lambda x,y: x.replace(y, m[y]), m.keys(), s)
'newshighwayy\n\n\n  monitorbyuuuterrfr'

One does get somewhat unpredictable results if one of the 
replacements contains a target search pattern (or creates it in 
the resulting string):

 >>> s = 'onetwothree'
 >>> m = {'one':'two', 'two':'three', 'three':'one'}
 >>> reduce(lambda x,y: x.replace(y, m[y]), m.keys(),s)
'twothreetwo'
 >>> m['three'] = 'four'
 >>> m['four'] = 'two'
 >>> reduce(lambda x,y: x.replace(y, m[y]), m.keys(),s)
'twothreefour'

Just a few more ideas...

-tkc



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


Re: Inconsistency producing constant for float "infinity"

2006-08-12 Thread Tim Peters
[Tim Peters]
>...
>> It has a much better chance of working from .pyc in Python 2.5.
>> Michael Hudson put considerable effort into figuring out whether the
>> platform uses a recognizable IEEE double storage format, and, if so,
>> marshal and pickle take different paths that preserve infinities,
>> NaNs, and signed zeroes.

[Alex Martelli]
> Isn't marshal constrained to work across platforms (for a given Python
> release), and pickle also constrainted to work across releases (for a
> given protocol)?

Yes to both.

> I'm curious about how this still allows them to "take different
> paths" (yeah, I _could_ study the sources, but I'm lazy:-)...

Good questions.  Pickle first:  pickle, with protocol >= 1, has always
had a binary format for Python floats, which is identical to the
big-endian IEEE-754 double-precision storage format.  This is
independent of the native C double representation:  even on a non-IEEE
box (e.g, VAX or Cray), protocol >= 1 pickle does the best it can to
/encode/ native doubles in the big-endian 754 double storage /format/.
 This is explained in the docs for the "float8" opcode in
pickletools.py:

 The format is unique to Python, and shared with the struct
 module (format string '>d') "in theory" (the struct and cPickle
 implementations don't share the code -- they should).  It's
 strongly related to the IEEE-754 double format, and, in normal
 cases, is in fact identical to the big-endian 754 double format.
 On other boxes the dynamic range is limited to that of a 754
 double, and "add a half and chop" rounding is used to reduce
 the precision to 53 bits.  However, even on a 754 box,
 infinities, NaNs, and minus zero may not be handled correctly
 (may not survive roundtrip pickling intact).

The problem has been that C89 defines nothing about signed zeroes,
infinities, or NaNs, so even on a 754 box there was no consistency
across platforms in what C library routines like frexp() returned when
fed one of those things.  As a result, what Python's "best non-heroic
effort" code for constructing a 754 big-endian representation actually
did was a platform-dependent accident when fed a 754 special-case
value.  Likewise for trying to construct a native C double from a 754
representation of a 754 special-case value -- again, there was no
guessing what C library routines like ldexp() would return in those
cases.

Part of what Michael Hudson did for 2.5 is add code to guess whether
the native C double format /is/ the big-endian or little-endian 754
double-precision format.  If so, protocol >= 1 pickle in 2.5 uses much
simpler code to pack and unpack Python floats, simply copying from/to
native bytes verbatim (possibly reversing the byte order, depending on
platform endianness).  Python doesn't even try to guess whether a C
double is "normal", or an inf, NaN, or signed zero then, so can't
screw that up -- it just copies the bits blindly.

That's much better on IEEE-754 boxes, although I bet it still has
subtle problems.  For example, IIRC, 754 doesn't wholly define the
difference in storage formats for signaling NaNs versus quiet NaNs, so
I bet it's still theoretically possible to pickle a signaling NaN on
one 754 box and get back a quiet NaN (or vice versa) when unpickled on
a different 754 box.

Protocol 0 (formerly known as "text mode") pickles are still a crap
shoot for 754 special values, since there's still no consistency
across platforms in what the C string<->double routines produce or
accept for special values.

Now on to marshal.  Before 2.5, marshal only had a "text mode" storage
format for Python floats, much like protocol=0 pickle.  So, as for
pickle protocol 0, what marshal produced or reconstructed for a 754
special value was a platform-dependent accident.

Michael added a binary marshal format for Python floats in 2.5, which
uses the same code protocol >= 1 pickle uses for serializing and
unserializing Python floats (except that the marshal format is
little-endian instead of big-endian).  These all go thru
floatobject.c's _PyFloat_Pack8 and _PyFloat_Unpack8 now, and a quick
glance at those will show that they take different paths according to
whether Michael's native-format-guessing code decided that the native
format was ieee_big_endian_format, ieee_little_endian_format, or
unknown_format.  The long-winded pre-2.5 pack/unpack code is only used
in the unknown_format case now.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: _PyLong_FromByteArray

2006-08-12 Thread Tim Peters
[Dan Christensen]
> My student and I are writing a C extension that produces a large
> integer in binary which we'd like to convert to a python long.  The
> number of bits can be a lot more than 32 or even 64.  My student found
> the function _PyLong_FromByteArray in longobject.h which is exactly
> what we need, but the leading underscore makes me wary.  Is it safe to
> use this function?

Python uses it internally, so it better be ;-)

>  Will it continue to exist in future versions of python?

No guarantees, and that's why it has a leading underscore:  it's not
an officially supported, externally documented, part of the advertised
Python/C API.  It so happens that I added that function, because
Python needed some form of its functionality internally across
different C modules.  Making it an official part of the Python/C API
would have been a lot more work (which I didn't have time for), and
created an eternal new maintenance burden (which I'm not keen on
regardless ;-)).

In practice, few people touch this part of Python's implementation, so
I don't /expect/ it will go away, or even change, for years to come.
The biggest insecurity I can think of offhand is that someone may
launch a crusade to make some other byte-array <-> long interface
"official" based on a different way of representing negative integers.
 But even then I expect the current unofficial functions to remain,
since the 256's-complement representation remains necessary for the
`struct` module's "q" format, and for the `pickle` module's protocol=2
long serialization format.

> Or is there some other method we should use?

No.  That's why these functions were invented to begin with ;-)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Using a dictionary to pass data to/from embedded python functions

2006-08-12 Thread wardm
Thanks Alex for your help, (and advice on focusing the point of my 
question).

I was able to compile and run your example OK, but when I try to use the 
"VarDictionary" in the
MyScriptModule.py code, I get an exception.

I  added the following code to the C app just to add two entries to the 
Dictionary

 PyDict_SetItemString( m_pVarDictionary, "tk1", 
Py_BuildValue("s","test1Val"));
 PyDict_SetItemString( m_pVarDictionary, "tk2", 
Py_BuildValue("s","test2Val"));

Then tried various things in the Python code to display the contents of the 
"VarDictionary",
such as adding the "print VarDictionary" below.

import InterfaceModule

def functionName():
print "hello"
print dir(InterfaceModule)
print "that's all"
 print VarDictionary
return

Even though "VarDictionary " is in the Dir, every time I try to use the 
"VarDictionary" the program fails.
Am I doing something wrong when I try and reference "VarDictionary" in 
Python ?
I need to be able to get/set entries in VarDictionary from the Python 
function.


"Alex Martelli" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> wardm <[EMAIL PROTECTED]> wrote:
>
>> I have created a Dict object in a C++ App that calls (embedded) Python
>> functions.
>  [[snip snip]]
>> This python code throws an exception when it attempts to access the
>> "VarDictionary".
>> Does anyone know why this fails ?
>
> It fails due to some code of yours that you have not included: in other
> words, the minimal application which embeds Python using _only_ the code
> you show us does not exhibit the failure.
>
> I wrote the following file za.c:
>
> #include "Python.h"
> #include "stdio.h"
> #include "stdlib.h"
>
> int main()
> {
>printf("start\n");
>putenv("PYTHONPATH=.");
>Py_Initialize();
>printf("inited\n");
>PyObject* m_pVarDictionary = PyDict_New();
>printf("dict is %p\n", m_pVarDictionary);
>PyObject* m_pInterfaceModule =
> PyImport_AddModule("InterfaceModule");
>printf("modu is %p\n", m_pInterfaceModule);
>int status = PyModule_AddObject(m_pInterfaceModule, "VarDictionary"
> ,
>m_pVarDictionary);
>printf("stat is %d\n", status);
>PyObject* m_pScriptModule = PyImport_ImportModule("MyScriptModule");
>printf("impo is %p\n", m_pScriptModule);
>
>PyObject* func = PyObject_GetAttrString(m_pScriptModule,
> "functionName");
>printf("func is %p\n", func);
>if (func && PyCallable_Check(func)) {
>   PyObject* ret = PyObject_CallObject(func, NULL);
>   printf("retu is %p\n", ret);
>}
>printf("done\n");
>return 0;
> }
>
> and the following file MyScriptModule.py:
>
> import InterfaceModule
>
> def functionName():
>print "hello"
>print dir(InterfaceModule)
>print "that's all"
>return
>
> and proceeded to compile and execute as follows: [[Note: it does not
> matter that I'm using 2.5, the code is just as fine with previous
> versions -- it just happens that 2.5 is what I'm using right now in
> order to help out with 2.5's beta testing]]:
>
> brain:~/pyex alex$ gcc -c za.c -I/usr/local/include/python2.5
> brain:~/pyex alex$ gcc -o za za.o -L/usr/local/lib/python2.5/config/
> -lpython2.5
> brain:~/pyex alex$ ./za
>
> and observed exactly the kind of output I predicted [[Note: the exact
> addresses printed of course do not matter]]:
>
> start
> inited
> dict is 0x51c780
> modu is 0x520230
> stat is 0
> impo is 0x5202d0
> func is 0x513770
> hello
> ['VarDictionary', '__doc__', '__name__']
> that's all
> retu is 0xe57c0
> done
> brain:~/pyex alex$
>
> As you see, in particular, VarDictionary is right up there in
> InterfaceModule's dir.
>
>
> There's a well-known essay by Eric Raymond, "How to ask questions the
> smart way", at  -- it
> seems to me that you, quite commendably, follow most of Eric's advice,
> but it's still worth reading -- the key point by which you could help us
> to help you is what Eric mentions as "If you have a large, complicated
> test case that is breaking a program, try to trim it and make it as
> small as possible".
>
> In this case, you should try to trim your code down to the smallest
> program using this approach, which you believe should work in a certain
> way but actually doesn't.  The exact code you posted plus the minimal
> additions to make it a compilable program does work the way you appear
> to desire, as I show above; therefore, there must be something else in
> your code that is breaking things.  Do tiny steps of addition and
> restructuring to move this minimal skeleton towards the direction of
> your bigger program (that does not behave this way) until you've found
> exactly the "largest" version that still succeeds, and the minisculely
> larger "smallest" version that fails -- the tiny difference between the
> two must then be the root of the problem, and if the reason is not clear
> at that point then posting here again is exactly the right thing to do.
>
> 

Re: start a multi-sockets server (a socket/per thread) with different ports but same host

2006-08-12 Thread Jean-Paul Calderone
On 12 Aug 2006 10:44:29 -0700, zxo102 <[EMAIL PROTECTED]> wrote:
>Jean-Paul,
>Thanks a lot. The code is working. The python twisted is new to me too.
>Here are my three more questions:
>1. Since the code need to be started in a wxpyhon GUI (either by
>clicking a button or up with the GUI),  do I have to run the code in a
>thread (sorry, I have not tried it yet)?

You can try to use Twisted's wxPython integration support:

http://twistedmatrix.com/projects/core/documentation/howto/choosing-reactor.html#auto15

But note the warnings about how well it is likely to work.  Using a separate
thread might be the best solution.

>2. How can I grab the client data in the code? Can you write two lines
>for that? I really appreciate that.

I'm not sure what you mean.  The data is available in the `received' attribute
of the protocol instance.  Any code which needs to manipulate the data can get
that list and do whatever it likes with it.

>3. After I change
>self.transport.write(''.join(self.data))
>   to
>self.transport.write(''.join(data))
>  and scan all the ports with the following code twice (run twice).
>First round scanning says "succefully connected". But second round
>scanning says "failed". I have to restart your demo code to make it
>work.

I intentionally added code which shuts the server off after the first round
of connections is completed, since that seemed to be what your example
program was doing.  If you don't want this, just remove the shutdown code.

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


Re: wxPython ListBook Class, Label Position w/ ImageList

2006-08-12 Thread Chaos

jean-michel bain-cornu wrote:
> Hi,
> > By default the label position of an image list is below the image. Is
> > there any way to change this?
> >
>
> If it exists, it's undocumented, and there is not a sample.
> Did you ask the wx forum ? It's probably a better place to have this
> kind of information. If they provide you a C sample, I could help you to
> convert it in python.
> Anyway, if you find out something, I'm interested...
>
> Regards,
> jm

I didnt find an answer but I simple used the TreeControl and everythime
its clicked I use it to update the main frame

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


Re: Inconsistency producing constant for float "infinity"

2006-08-12 Thread Alex Martelli
Tim Peters <[EMAIL PROTECTED]> wrote:

   [snip]

thanks for an exhaustively satisfying explanation!


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


Re: Recurse Directories and process files in directory

2006-08-12 Thread Jason Nordwick
Use os.system to execute a string and os.walk to get a recursive list of files


>>> def processdir(curdir,subdirs,files):
... map(lambda f:os.system('\\cygwin\\bin\\wc -l "%s"' % f), 
[curdir+os.sep+x for x in files])
...
>>> map(lambda x:processdir(*x), os.walk('\\dev\qclient'));
6 \dev\qclient\.classpath
17 \dev\qclient\.project
774 \dev\qclient\bookmarks.html
8 \dev\qclient\kx\qclient\DirTree$1.class
20 \dev\qclient\kx\qclient\DirTree$2.class
17 \dev\qclient\kx\qclient\DirTree$3.class
8 \dev\qclient\kx\qclient\DirTree$4.class
18 \dev\qclient\kx\qclient\DirTree$5.class
9 \dev\qclient\kx\qclient\DirTree$CellRenderer.class
18 \dev\qclient\kx\qclient\DirTree$ServerPopupMenu.class
5 \dev\qclient\kx\qclient\DirTree$ServerTreeNode.class
28 \dev\qclient\kx\qclient\DirTree.class
148 \dev\qclient\kx\qclient\DirTree.java
11 \dev\qclient\kx\qclient\Q$Date.class
4 \dev\qclient\kx\qclient\Q$Dict.class
4 \dev\qclient\kx\qclient\Q$Flip.class
5 \dev\qclient\kx\qclient\Q$KException.class
12 \dev\qclient\kx\qclient\Q$Minute.class
12 \dev\qclient\kx\qclient\Q$Month.class
15 \dev\qclient\kx\qclient\Q$Second.class
18 \dev\qclient\kx\qclient\Q$Time.class
147 \dev\qclient\kx\qclient\Q.class
137 \dev\qclient\kx\qclient\Q.java
8 \dev\qclient\kx\qclient\QClient$1.class
11 \dev\qclient\kx\qclient\QClient$2.class
15 \dev\qclient\kx\qclient\QClient$3.class
9 \dev\qclient\kx\qclient\QClient$4.class
85 \dev\qclient\kx\qclient\QClient.class
185 \dev\qclient\kx\qclient\QClient.java
4 \dev\qclient\kx\qclient\QServer$DefaultListener.class
3 \dev\qclient\kx\qclient\QServer$Listener.class
28 \dev\qclient\kx\qclient\QServer.class
50 \dev\qclient\kx\qclient\QServer.java
59 \dev\qclient\kx\qclient\ServerDialog.class
146 \dev\qclient\kx\qclient\ServerDialog.java
14 \dev\qclient\kx\qclient\ServerDisplay$1.class
18 \dev\qclient\kx\qclient\ServerDisplay$StatusBar.class
19 \dev\qclient\kx\qclient\ServerDisplay.class
78 \dev\qclient\kx\qclient\ServerDisplay.java
[None, None, None]
>>>

KraftDiner wrote:
> Hi I need help writing a python script that traverses (recursivly) a
> directory and its sub directories and processes all files in the
> directory.  So at each directory if there are files in it I must build
> a list of those files and process them by exectuing a system command
> (exec?)
> 
> Can some one tell me what methods to use to:
> a) Walk the directory tree
> b) execute a system command with parameters.
> 
> TIA.
> 

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


Re: Make $1000's Monthly!

2006-08-12 Thread AlbaClause
[EMAIL PROTECTED] wrote:

> Make $1000's Monthly!
> Over 600 work at home firms are in need of survey takers, product
> assemblers, home mailers, mystery
> shopping
> Data entry and more!  Report contains complete contact details for over
> 650 companies now hiring!
> For this complete report of over 600 firms please visit
>
http://www.typeinternational.com/idevaffiliate/idevaffiliate.php?id=6589_52_3_87

Just to bring this thread back on topic, you could also make thousands of
dollars monthly by becoming a professional Python coder or consultant.  ;-)

-- 
--
There are several things that I will never be:
  *  I will never be attracted to females.
  *  I will never enjoy the company of others.
Exactly how these realities bode for my enemy, is not of my concern.

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


Re: Read a file with open command

2006-08-12 Thread AlbaClause
[EMAIL PROTECTED] wrote:

> AlbaClause wrote:
>> jean-jeanot wrote:
>>
> 
> 
>> Ummm, he did not say that your question was stupid.   The Zappa quote is
>> included as part of what we refer to as a 'signature'.   In the case of
>> Sybren Stuvel's posts to this newsgroup, the Frank Zappa quote is
>> included
>> in every message that he posts.  Not just messages that he posts to you.
> 
> First up, I *like* the Frank Zappa signature quote; it has a George
> Carlin feel to it and takes a swipe at our overly-protective cultures
> [side note: I bought an electric heating pad last night that came with
> instructions not to use it in the bathtub!  Well, duh!].  But, can you
> see where the signature on a response to a tutor list -- where people
> are already feeling a bit intimidated and/or inadequate and therefore
> may feel a wee bit "stupid" -- might be taken the wrong way?
> 
> I have spent many years teaching mathematics and physics in a classroom
> setting and have come to realize that, as a teacher, just about
> anything I say/do can be blown way out of proportion.  So I don't use
> sarcasm or "fun" little put-downs and I treat every question as if it
> is the most important matter because, to the student, it is.  Do I get
> tired of answering the same thing over and over? Yes!!  Many times I
> will ask if the student has read the textbook and, if not, I will
> request they give it a try (much in the same way we ask if they have
> read any tutorials), but I take Homeric efforts not to offend them and,
> to that end, modify my behavior in order to teach them mathematics.
> 
> My point is that this is a wonderful service you tutors provide, but
> the Zappa signature may not be the best choice for this setting. Most
> people will read it and get a laugh (as did I), but how many have taken
> it the way jean-jeanot did and walk away feeling insulted?  How many
> will not post a response expressing their feelings, never post a
> question again or, worst case, decide Python is not for them?
> 
> Again, I admire this list and those of you you maintain it.  These are
> just my thoughts.  YMMV.
> 
> --greg

This is getting a little off-topic, but my feeling is that if you're unable
to discern the difference between the substance of the message, and the
"personal style" of the author (eg: quote attributions and/or signature
lines) then you probably shouldn't be attempting to code in Python or any
other structured language.   

A newsgroup post is quite structured -- just as a Python script is -- there
is the header, which contains the subject, the sender, the recipient, and
other protocol information; and the text body.  The text body is also quite
structured.  The text body can contain a quote from a prior message, the
added comments that make up the substance of the message, and a
signature/tag line.  If a person has great difficulty in differentiating
the various parts of a newsgroup message, then perhaps structured
programming languages are not for them.

Perhaps we should begin a new message passing convention.   One where the
substance of the post is contained within braces -- like C/C++ code?  Just
kidding!  LOL

-- 
--
There are several things that I will never be:
  *  I will never be attracted to females.
  *  I will never enjoy the company of others.
Exactly how these realities bode for my enemy, is not of my concern.

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


Re: Using a dictionary to pass data to/from embedded python functions

2006-08-12 Thread Alex Martelli
wardm <[EMAIL PROTECTED]> wrote:

> Thanks Alex for your help, (and advice on focusing the point of my 
> question).
> 
> I was able to compile and run your example OK, but when I try to use the
> "VarDictionary" in the
> MyScriptModule.py code, I get an exception.
> 
> I  added the following code to the C app just to add two entries to the
> Dictionary
> 
>  PyDict_SetItemString( m_pVarDictionary, "tk1", 
> Py_BuildValue("s","test1Val"));
>  PyDict_SetItemString( m_pVarDictionary, "tk2", 
> Py_BuildValue("s","test2Val"));
> 
> Then tried various things in the Python code to display the contents of the
> "VarDictionary",
> such as adding the "print VarDictionary" below.
> 
> import InterfaceModule
> 
> def functionName():
> print "hello"
> print dir(InterfaceModule)
> print "that's all"
>  print VarDictionary

Note the wrong indentation in this latter print statement: this would
already cause a syntax error (unless the leading 'p' happened to be
aligned with the leading 'd' of 'def', in which case the function would
be terminated, the latest print would happen at import-time, and the
FOLLOWING statement:

> return

...would then be a syntax error (return outside of function).  But,
there's more:


> Even though "VarDictionary " is in the Dir, every time I try to use the
> "VarDictionary" the program fails.

"VarDictionary" is in the dir(...) *** of InterfaceModule ***, of
course, so you need to refer to it as InterfaceModule.VarDictionary in
your Python code -- the barename, nor qualified by modulename, just will
not work, of course!!!

Adding the two C code lines you quote, and changing the Python example
code to:

def functionName():
print "hello"
print dir(InterfaceModule)
print "VarDictionary is:", InterfaceModule.VarDictionary
print "that's all"

changes that part of the output to:

hello
['VarDictionary', '__doc__', '__name__']
VarDictionary is: {'tk2': 'test2Val', 'tk1': 'test1Val'} 
that's all


With all due respect, it looks like you're trying to run before you can
walk -- or more specifically, to embed Python in C++ before you become
familiar with the most elementary and fundamental aspects of Python,
such as indentation and the need to qualify compound names.  You might
want to consider getting a good Python book -- such as, my own Python in
A Nutshell (2nd ed), Aahz and Stef Maruch's Python For Dummies, Wesley
Chun's Core Python Programming (2nd ed) -- they're all very recent (mine
is just out, Aahz's and Stef's I believe is due to hit bookstores in
September or October), and any of them might serve you well (if you're
OK with books not necessarily covering the very latest release of Python
[and the issues you're having suggest that this is not really the
problem!], there are many other good books, such as Magnus Lie Hetland's
"Beginning Python", Beazley's "Python Essential Reference", Lutz and
Ascher's "Learning Python",  
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Make $1000's Monthly!

2006-08-12 Thread Alex Martelli
AlbaClause <[EMAIL PROTECTED]> wrote:
   ...
> Just to bring this thread back on topic, you could also make thousands of
> dollars monthly by becoming a professional Python coder or consultant.  ;-)

Yes, easily -- according to SD Magazine's yearly surveys, Python
programmers have been the best-paid ones for years in a row now (I
believe the worst-paid ones are Visual Basic programmers, as a group).


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


Re: Learning Python

2006-08-12 Thread Dr. Pastor
What a bright replies! It is a
pleasure to study them.
Thanks to you all.

== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet 
News==
http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ 
Newsgroups
= East and West-Coast Server Farms - Total Privacy via Encryption =
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Read a file with open command

2006-08-12 Thread John Machin
[EMAIL PROTECTED] wrote:
[snip]
> My point is that this is a wonderful service you tutors provide, but
> the Zappa signature may not be the best choice for this setting.

This is *not* the tutor list.

>Most people will read it and get a laugh (as did I), but how many have taken
> it the way jean-jeanot did and walk away feeling insulted?  How many
> will not post a response expressing their feelings, never post a
> question again or, worst case, decide Python is not for them?


Possibly one, were he still alive: St Aloysius "of whom it is said in
the book of the monk Eustachius that when he heard a man breaking wind
with deafening noise he immediately burst into tears and could only be
consoled by prayers" [from "The Good Soldier Švejk ..." by Jaroslav
Hašek [tr. Parrott (the Sir Cecil variety, not the Norwegian Blue)]]


Cheers,
John

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


Re: [OT] John Salerno

2006-08-12 Thread John Salerno
Alan Connor wrote:

> Almost certainly bogus. I wouldn't believe anything in this
> fellow's headers or articles.
>
> TROLL. 
> 
> I don't help trolls.

Ok, I don't know how seriously to take this post, so I won't spend much 
time addressing it. All I will say is yes, this is really me and I am 
asking a genuine question.
-- 
http://mail.python.org/mailman/listinfo/python-list


proxy for xmlrpc calls

2006-08-12 Thread Xavier
I'm attempting to write a proxy for xmlrpc calls.

I'm starting from this code;

class MagicObject:

 def __call__(self,*args,**kwargs):
 return MagicObject.__dict__['_stop'](self,self.n,*args,**kwargs)

 def __getattr__(self,name):
 if name in ('__str__','__repr__'): return lambda:'instance of 
%s at %s' % (str(self.__class__),id(self))
 if not self.__dict__.has_key('n'):self.n=[]
 self.n.append(name)
 return self

 def _stop(self,n,*args,**kwargs):
 self.n=[]
 return self.default(n,*args,**kwargs)

 def default(self,n,*args,**kwargs):
 return 'stop',n,args,kwargs



 >>c=MagicObject()
 >>x=c.beubeb.z(1,2,3,a='bbb')
 >>print x
('stop', ['beubeb', 'z'], (1, 2, 3), {'a': 'bbb'})

I did not write this, the source is here:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/435757

I want to expand this to do something like;

 >>a=MagicObject()
 >>x = a.b.c.d

Then on the last __getattr__ send a call over xmlrpc.
How do I determine when the last __getattr__ will be?

With method calls you know to send a call on xmlrpc when you hit 
__call__.  But if you're dealing with a getting nested attributes
what do you do?  How do I know when there are no more attributes?
I thought about getting the source code from
the correct frame, but I don't think thats a good solution.

Any ideas?
Thanks in advance.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Recurse Directories and process files in directory

2006-08-12 Thread David Lewis
On 2006-08-12 09:46:54 -0700, "KraftDiner" <[EMAIL PROTECTED]> said:

> Hi I need help writing a python script that traverses (recursivly) a
> directory and its sub directories and processes all files in the
> directory.

In addition to os.walk, I find Jason Orendorff's 'path' module very 
helpful and much easier to use. You can get at 
. With it, for 
instance, processing all the C source files in a directory, 
recursively, would look like:

theDir = path('pathToDir')
for theFile in theDir.walkFiles('*.c'):
# Do something

Best,
David

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


Re: Best way to construct an email - attach a html file and send

2006-08-12 Thread a
where is the link
thanks a lot for your kind help
Larry Bates wrote:
> a wrote:
> > What is the best way to construct an email in python and also attach a
> > html file
> >
> > the html file to be attached is not on disk, but should be dynamically
> > constructed in the python script
> >
> > I want to attach the django debug error to an email and mail it to
> > myself whenever there is an error in the application
> >
> > thanks a lot
> > py
> >
> Here is a link to a class that will allow you to attach files.  You
> can either write the HTML to a tempfile and attach or modify a
> little to accept a string or cstringIO object instead.  Hope it
> helps.
> 
> -Larry Bates

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


Re: [OT] John Salerno

2006-08-12 Thread jason
John Salerno wrote:
> Alan Connor wrote:
> 
>> Almost certainly bogus. I wouldn't believe anything in this
>> fellow's headers or articles.
>>
>> TROLL.
>> I don't help trolls.
> 
> 
> Ok, I don't know how seriously to take this post, so I won't spend much 
> time addressing it. All I will say is yes, this is really me and I am 
> asking a genuine question.

Basically just killfile alan connor. It will greatly improve the signal 
to noise ratio here. He's one of usenets most pathetic and whinest trolls.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [OT] John Salerno

2006-08-12 Thread Alan Connor
On alt.os.linux, in <[EMAIL PROTECTED]>, "John Salerno" wrote:

Correction: Someone who _sometimes_ calls himself "John Salerno"
wrote:

http://slrn.sourceforge.net/docs/README.offline>

So. You post using three different newsservers, which no one who
posts under the same alias all the time does.

And are attacking Linux in your original subject:

> Subject: and i thought windows made a mess of files...

With the typical display of non-literacy of a troll: No caps
where caps belong.

Your User-Agent string in your headers reads Windows, until
this thread, where it is modified only to say Linux instead of
Windows, but otherwise the same newsreader.

And there are virtually no Linux groups in your posting history 
for the last year.

You are a stinking troll and you will wear a gag when you are
in my newsreader. Nor will anyone be allowed to send replies to
yourarticles to my newsreader.

Regardless of which alias you are hiding behind at the moment,
with your tail between your legs where your balls should be.

No way I am going to help a stinking troll learn Linux.

If you are even trying to, that is...

Note: I won't be downloading any articles on this thread.

Alan

-- 
Challenge-Response Systems are the best garbage-mail blockers
in the world. Spammers and trolls can't beat them and you
don't need to be a geek to use them. A brief introduction:
http://home.earthlink.net/~alanconnor/cr.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Using a dictionary to pass data to/from embedded python functions

2006-08-12 Thread wardm
Thanks again for your help, I agree, it seems I need to read a good book on 
Python.

One last question, will Python allow me to add new items to 
InterfaceModule.VarDictionary
from the Python functions I call ?


"Alex Martelli" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> wardm <[EMAIL PROTECTED]> wrote:
>
>> Thanks Alex for your help, (and advice on focusing the point of my
>> question).
>>
>> I was able to compile and run your example OK, but when I try to use the
>> "VarDictionary" in the
>> MyScriptModule.py code, I get an exception.
>>
>> I  added the following code to the C app just to add two entries to the
>> Dictionary
>>
>>  PyDict_SetItemString( m_pVarDictionary, "tk1",
>> Py_BuildValue("s","test1Val"));
>>  PyDict_SetItemString( m_pVarDictionary, "tk2",
>> Py_BuildValue("s","test2Val"));
>>
>> Then tried various things in the Python code to display the contents of 
>> the
>> "VarDictionary",
>> such as adding the "print VarDictionary" below.
>>
>> import InterfaceModule
>>
>> def functionName():
>> print "hello"
>> print dir(InterfaceModule)
>> print "that's all"
>>  print VarDictionary
>
> Note the wrong indentation in this latter print statement: this would
> already cause a syntax error (unless the leading 'p' happened to be
> aligned with the leading 'd' of 'def', in which case the function would
> be terminated, the latest print would happen at import-time, and the
> FOLLOWING statement:
>
>> return
>
> ...would then be a syntax error (return outside of function).  But,
> there's more:
>
>
>> Even though "VarDictionary " is in the Dir, every time I try to use the
>> "VarDictionary" the program fails.
>
> "VarDictionary" is in the dir(...) *** of InterfaceModule ***, of
> course, so you need to refer to it as InterfaceModule.VarDictionary in
> your Python code -- the barename, nor qualified by modulename, just will
> not work, of course!!!
>
> Adding the two C code lines you quote, and changing the Python example
> code to:
>
> def functionName():
>print "hello"
>print dir(InterfaceModule)
>print "VarDictionary is:", InterfaceModule.VarDictionary
>print "that's all"
>
> changes that part of the output to:
>
> hello
> ['VarDictionary', '__doc__', '__name__']
> VarDictionary is: {'tk2': 'test2Val', 'tk1': 'test1Val'}
> that's all
>
>
> With all due respect, it looks like you're trying to run before you can
> walk -- or more specifically, to embed Python in C++ before you become
> familiar with the most elementary and fundamental aspects of Python,
> such as indentation and the need to qualify compound names.  You might
> want to consider getting a good Python book -- such as, my own Python in
> A Nutshell (2nd ed), Aahz and Stef Maruch's Python For Dummies, Wesley
> Chun's Core Python Programming (2nd ed) -- they're all very recent (mine
> is just out, Aahz's and Stef's I believe is due to hit bookstores in
> September or October), and any of them might serve you well (if you're
> OK with books not necessarily covering the very latest release of Python
> [and the issues you're having suggest that this is not really the
> problem!], there are many other good books, such as Magnus Lie Hetland's
> "Beginning Python", Beazley's "Python Essential Reference", Lutz and
> Ascher's "Learning Python", 


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


Re: Using a dictionary to pass data to/from embedded python functions

2006-08-12 Thread Alex Martelli
wardm <[EMAIL PROTECTED]> wrote:

> Thanks again for your help, I agree, it seems I need to read a good book on
> Python.
> 
> One last question, will Python allow me to add new items to 
> InterfaceModule.VarDictionary
> from the Python functions I call ?

Yes, no problem with that.


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


Re: [OT] John Salerno

2006-08-12 Thread John Salerno
Alan Connor wrote:

> So. You post using three different newsservers, which no one who
> posts under the same alias all the time does.
> 
> And there are virtually no Linux groups in your posting history 
> for the last year.

Wow, you need some help. I post at work on one server, and then also at 
home on another (and sometimes two), on both Windows and Linux, which I 
just installed last Saturday and am currently exploring for the first time.

If that isn't enough to convince you, then *you* are the troll.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: start a multi-sockets server (a socket/per thread) with different ports but same host

2006-08-12 Thread zxo102
Jean-Paul,
I just start to learn Twisted. Here is my simple case: I can find
the data sent by clients in dataReceived but I don't know which
client/which port the data is from. After I know where the data comes
from, I can do different things there, for example, write them into
different files via bsddb.  I am not sure if it is the correct way to
do it.


   def dataReceived(self, data):
   # Accumulate the new data in our list
   self.received.append(data)
   # And then echo the entire list so far back to the client
   self.transport.write(''.join(data))

   print "> data: ", data
   print " which Port? : ", self.factory.port  # unforunately it is
an object here.

   # if Port == 2001:
   #   write the data into a file via bsddb
   # if Port == 2002:
   #   write the data into another file via bsddb
   #  etc .


Ouyang

Jean-Paul Calderone 写道:

> On 12 Aug 2006 10:44:29 -0700, zxo102 <[EMAIL PROTECTED]> wrote:
> >Jean-Paul,
> >Thanks a lot. The code is working. The python twisted is new to me too.
> >Here are my three more questions:
> >1. Since the code need to be started in a wxpyhon GUI (either by
> >clicking a button or up with the GUI),  do I have to run the code in a
> >thread (sorry, I have not tried it yet)?
>
> You can try to use Twisted's wxPython integration support:
>
> http://twistedmatrix.com/projects/core/documentation/howto/choosing-reactor.html#auto15
>
> But note the warnings about how well it is likely to work.  Using a separate
> thread might be the best solution.
>
> >2. How can I grab the client data in the code? Can you write two lines
> >for that? I really appreciate that.
>
> I'm not sure what you mean.  The data is available in the `received' attribute
> of the protocol instance.  Any code which needs to manipulate the data can get
> that list and do whatever it likes with it.
>
> >3. After I change
> >self.transport.write(''.join(self.data))
> >   to
> >self.transport.write(''.join(data))
> >  and scan all the ports with the following code twice (run twice).
> >First round scanning says "succefully connected". But second round
> >scanning says "failed". I have to restart your demo code to make it
> >work.
>
> I intentionally added code which shuts the server off after the first round
> of connections is completed, since that seemed to be what your example
> program was doing.  If you don't want this, just remove the shutdown code.
> 
> Jean-Paul

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

Re: matplotlib, wxPanel inside a wxPanel

2006-08-12 Thread Sam
Hi Daniel,

Thanks very much for your quick response! You're right, it was a case
of the cut-and-paste blues, and me not really knowing what each part of
the code in the examples was actually doing.
A couple of things caught me out: first of all, i wasn't calling
SetSizer and Fit on the right panels...
Secondly, I stuffed up when trying to give graph_panel a parent of
main_panel. It turns out I was actually never doing this, so the
toolbar would appear, but none of the buttons would work.

Thanks again for your comments, they were very helpful,
Cheers
Sam

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


Re: [OT] John Salerno

2006-08-12 Thread Alan Connor
On alt.os.linux, in <[EMAIL PROTECTED]>, "jason" wrote:
> Path: 
> text.usenetserver.com!atl-c01.usenetserver.com!news.usenetserver.com!atl-c05.usenetserver.com!news.usenetserver.com!postnews.google.com!news3.google.com!border1.nntp.dca.giganews.com!nntp.giganews.com!wns13feed!worldnet.att.net!4.24.21.153!newsfeed3.dallas1.level3.net!news.level3.com!newsfeed1.easynews.com!easynews.com!easynews!easynews-local!fe12.news.easynews.com.POSTED!not-for-mail
> From: jason <[EMAIL PROTECTED]>
> User-Agent: Debian Thunderbird 1.0.2 (X11/20060724)
> X-Accept-Language: en-us, en
> MIME-Version: 1.0
> Newsgroups: alt.os.linux,comp.editors,comp.lang.python
> Subject: Re: [OT] John Salerno
> References: <[EMAIL PROTECTED]> <[EMAIL PROTECTED]> <[EMAIL PROTECTED]>
> In-Reply-To: <[EMAIL PROTECTED]>
> Content-Type: text/plain; charset=ISO-8859-1; format=flowed
> Content-Transfer-Encoding: 7bit
> Lines: 16
> Message-ID: <[EMAIL PROTECTED]>
> X-Complaints-To: [EMAIL PROTECTED]
> Organization: EasyNews, UseNet made Easy!
> X-Complaints-Info: Please be sure to forward a copy of ALL headers otherwise 
> we will be unable to process your complaint properly.
> Date: Sun, 13 Aug 2006 03:11:58 GMT
> Xref: usenetserver.com alt.os.linux:422390 comp.editors:161251 
> comp.lang.python:548515
> X-Received-Date: Sat, 12 Aug 2006 23:11:58 EDT (text.usenetserver.com)

http://slrn.sourceforge.net/docs/README.offline>

Posting through easynews. Let's see who else posts through
easynews on the groups I am subscribed to:

#From: "Ciaran Keating" <[EMAIL PROTECTED]>
#From: "Clayton Sutton" <[EMAIL PROTECTED]>
#From: "DanielP" <[EMAIL PROTECTED]>
#From: "Snoopy :-))" <[EMAIL PROTECTED]>
#From: "smtjs" <[EMAIL PROTECTED]>
#From: <[EMAIL PROTECTED]>
#From: "Ciaran Keating" <[EMAIL PROTECTED]>
#From: "Clayton Sutton" <[EMAIL PROTECTED]>
#From: "DanielP" <[EMAIL PROTECTED]>
#From: "Snoopy :-))" <[EMAIL PROTECTED]>
#From: "William B. Cattell" <[EMAIL PROTECTED]>
#From: <[EMAIL PROTECTED]>
#From: "Ciaran Keating" <[EMAIL PROTECTED]>
#From: "Clayton Sutton" <[EMAIL PROTECTED]>
#From: "DanielP" <[EMAIL PROTECTED]>
#From: "Snoopy :-))" <[EMAIL PROTECTED]>
#From: "William B. Cattell" <[EMAIL PROTECTED]>
#From: <[EMAIL PROTECTED]>
#From: Alan Connor <[EMAIL PROTECTED]>
 
A troll forging my name. I only post through Earthlink.
 
#From: Andrew Schulman <[EMAIL PROTECTED]>
#From: Aratzio <[EMAIL PROTECTED]>
#From: Bosco Pelone <[EMAIL PROTECTED]>
#From: Bretts Christ <[EMAIL PROTECTED]>
#From: Bretts of God <[EMAIL PROTECTED]>
#From: Bretts of The Apocalypse <[EMAIL PROTECTED]>
#From: Cam <[EMAIL PROTECTED]>
#From: Derek Munsley <[EMAIL PROTECTED]>
#From: Elo Magar <[EMAIL PROTECTED]>
#From: Gospel Bretts <[EMAIL PROTECTED]>
#From: Gospel Bretts <[EMAIL PROTECTED]>
#From: Hallelujah Bretts <[EMAIL PROTECTED]>
#From: Hallelujah Bretts <[EMAIL PROTECTED]>
#From: Holy Brett McCoy <[EMAIL PROTECTED]>
#From: Holy Bretts <[EMAIL PROTECTED]>
#From: Jason <[EMAIL PROTECTED]>
#From: John <[EMAIL PROTECTED]>
#From: John Blake <[EMAIL PROTECTED]>
#From: Mark Healey <[EMAIL PROTECTED]>
#From: Mark Healey <[EMAIL PROTECTED]>
#From: McBretts of God <[EMAIL PROTECTED]>
#From: Mike Coddington <[EMAIL PROTECTED]>
#From: Paul Colquhoun <[EMAIL PROTECTED]>
#From: Realto Margarino <[EMAIL PROTECTED]>
#From: River <[EMAIL PROTECTED]>
#From: SINNER <[EMAIL PROTECTED]>
#From: The Apostle Bretts <[EMAIL PROTECTED]>
#From: The Beloved Disciple Bretts <[EMAIL PROTECTED]>
#From: The Holy Apostle <[EMAIL PROTECTED]>
#From: The Holy Trinity of Bretts <[EMAIL PROTECTED]>
#From: The Reverend Doctor Bretts <[EMAIL PROTECTED]>
#From: To Garo <[EMAIL PROTECTED]>
#From: Uni <[EMAIL PROTECTED]>
#From: Wes Gray <[EMAIL PROTECTED]>
#From: WhyMe <[EMAIL PROTECTED]>
#From: ea aro <[EMAIL PROTECTED]>
#From: jason <[EMAIL PROTECTED]>
#From: le seigneur des rateaux <[EMAIL PROTECTED]>
#From: lordy <[EMAIL PROTECTED]>
#From: [EMAIL PROTECTED] (beginner_girl)

Looks like pretty much all trolls to me. 

Note: I won't be downloading any articles on this thread.

Alan

-- 
Challenge-Response Systems are the best garbage-mail blockers
in the world. Spammers and trolls can't beat them and you
don't need to be a geek to use them. A brief introduction:
http://home.earthlink.net/~alanconnor/cr.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: start a multi-sockets server (a socket/per thread) with different ports but same host

2006-08-12 Thread Bryan Olson
zxo102 wrote:
>I am doing a small project using socket server and thread in python.
>  This is first time for me to use socket and thread things.
>Here is my case. I have 20 socket clients.  Each client send a set
> of sensor data per second to a socket server.  The socket server will
> do two things: 1. write data into a file via bsddb; 2. forward the data
> to a GUI written in wxpython.
>I am thinking the code should work as follow (not sure it is
> feasible)
>   20 threads, each thread takes care of a socket server with a
> different port.
>I want all socket servers start up and wait for client connection.
> In the attached demo code, It stops at the startup of first socket
> server somewhere in the following two lines and waits for client call:
> 
>lstn.listen(5)
>(clnt,ap) = lstn.accept()

It will block there, waiting for connection.

>   Any ideas how to handle these 20 clients?  Really appreciate your
> suggestions.

One reserved port for each client strikes me as whacked,
as does coding a server to handle exactly 20 of them. Since
you say this is your first socket server, maybe you just
haven't seen the usual techniques.

Normally, one listener socket accepts all the connections.
Each call to accept() returns a new, independent socket for the
connection. You can then start a thread to handle the new
socket. Untested:


   listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
   listener.bind(('', 2000))
   listener.listen(5)
   while True:   # or some should_continue() thing
   sock, _ = listener.accept()
   thread.start_new_thread(service_function, (sock,))
   # Or start threads via class Threading


To update the GUI, you could use the Queue from the Python
library, and call wxPostEvent to tell the GUI go wake up and
check the queue.


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


Re: sys.platform documentation?

2006-08-12 Thread Martin v. Löwis
Michiel Sikma schrieb:
> However, in order to populate the list of platforms, I need to know
> which strings sys.platform can return. I haven't found any documentation
> on this, but I guess that I'm not looking in the right places! Do any of
> you know where I can find a list of possible return values from
> sys.platform? I'll settle for a Python C source code file, too, if it
> contains strings.

As others have indicated, sys.platform is derived from the name that
the system vendor gives their system. However, Python also adds
plat- to sys.path, so you can look at all the plat-*
directories in the Python distribution.

This gives you the list

aix3 aix4 atheos beos5 darwin freebsd2 freebsd3 freebsd4 freebsd5
freebsd6 freebsd7 generic irix5 irix6 linux2 mac netbsd1 next3 os2emx
riscos sunos5 unixware7

Of course, sys.platform can have additional values, when Python
gets compiled on a system for which no platform-specific directory
has been created.

Regads,
Martin
-- 
http://mail.python.org/mailman/listinfo/python-list