Re: embedding Python: how to avoid memory leaks?

2006-03-10 Thread Martin v. Löwis
Torsten Bronger wrote:
I couldn't get the PyRun_*File* calls to work on Windows,
presumably because of the FILE* problem mentioned in the docs.

> Well, I don't really *know*, but it's hard to believe to me that the
> file descriptor format changed within the Microsoft product series.

The layout of the FILE type indeed didn't change. However, passing
FILE* across different versions of msvcrt will still crash; google
for details. In particular, if you build an application with VC6,
it will be linked with msvcrt4.dll. If you combine this with Python
2.4 (which is linked with msvcr71.dll), you cannot use PyRun_*File*.

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


Re: Simple questions on use of objects (probably faq)

2006-03-10 Thread Brian Elmegaard
Michael <[EMAIL PROTECTED]> writes:

> Based on the code that runs, you want* this:
>
> [(y[x+1].x-y[x].x) for x in range(len(y)-1) ]

Yes.

> Since personally I find that a lot clearer than:
>
> map(float.__sub__, [X.x for X in y[1:]], [X.x for X in y[:-1] ])

Me too.

-- 
Brian (remove the sport for mail)
http://www.et.web.mek.dtu.dk/Staff/be/be.html
http://www.rugbyklubben-speed.dk
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Simple questions on use of objects (probably faq)

2006-03-10 Thread Brian Elmegaard
Steven D'Aprano <[EMAIL PROTECTED]> writes:

> With this method in the class, your solution is easier than ever:

Nice solution.

-- 
Brian (remove the sport for mail)
http://www.et.web.mek.dtu.dk/Staff/be/be.html
http://www.rugbyklubben-speed.dk
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: creating variable in root namespace from module

2006-03-10 Thread Steve Holden
MakaMaka wrote:
> Hi,
> I have a scope related question that I haven't been able to find an
> answer to anywhere.  Is there a way to have a function in an imported
> module add variables to the scope of the calling script?  Basically,
> can I have the following:
> 
> #root.py
> import some_module.py
> 
> some_module.afunction() # <== create a variable x1=1 and add it to the
> scope of root.py
> 
> print x1  # <== would print 1
> 
> I know this can be accomplished by passing the what globals() returns
> into the function; however, I'm wondering if there is a way to do this
> without passing anything to the function.
> 
There are clever technical ways to do this, but what's the use case? 
There's almost certainly a better way to accomplish what you want.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd www.holdenweb.com
Love me, love my blog holdenweb.blogspot.com

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


Re: How to pop random item from a list?

2006-03-10 Thread Peter Otten
marduk wrote:

> item = mylist.pop(random.randint(0,len(mylist)))

This is broken because randint(a, b) may return b.
I prefer randrange(len(mylist)) over randint(0, len(mylist)-1) as a fix.

Peter

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


Re: Python Evangelism

2006-03-10 Thread Thomas G. Willis
...In any case, I'm sure Django was a great musician, but theproduct needs a better name to have any chance of displacing Rails.
|>oug

Yes he was an amazing guitarist. If you ever listen to his stuff, keep
in mind he had 2 working fingers on his fret hand, and ripping on a
guitar that would be considered impossible to play by todays standards.

When I saw Django as a python based web framework, I got a positive vibe from the name of it. But then I'm also a guitarist.
 -- Thomas G. Willis---http://i-see-sound.comhttp://tomwillis.sonicdiscord.com
America, still more rights than North Korea
-- 
http://mail.python.org/mailman/listinfo/python-list

Password entering system

2006-03-10 Thread Tuvas
I want to write a GUI program (Preferably in Tkinter) that will allow
for the entering of passwords, stared out like a normal program does.
Is that possible? Thanks!

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


API/C memory mananegemnt problem

2006-03-10 Thread fumana
Hi everybody,
I have a problem with Python/C API and memory management.

I'm using 
Python 2.3.5 (#1, Jan  4 2006, 16:44:27)
[GCC 4.0.2 20050901 (prerelease) (SUSE Linux)] on linux2

In my C-module I have a loop like this:
***

int size=1000;

output=(double *) calloc(size, sizeof(double));

py_output=PyList_New(0);

for(i=0; ihttp://mail.python.org/mailman/listinfo/python-list


Re: First script, please comment and advise

2006-03-10 Thread bruno at modulix
Pedro Graca wrote:
> [EMAIL PROTECTED] wrote:
> 
>>My version is similar to Just one:
>>
>>from random import shuffle
>>
>>def scramble_text(text):
>>"""Return the words in input text string scrambled
>>except for the first and last letter."""
>>def scramble_word(word):
> 
> 
> Nice. You can have functions inside functions.
> However I think scramble_word() deserves being a callable function by
> itself.
> 
> Can a "sub-function" be called directly from outside the defining
> function?
> 

"directly", no, but since Python's functions are objects, you can return
a function from another function. The nice thing is that the inner
function will carry it's environnement along (it's called a "closure").


def make_adder(add_val=1):
  def adder(num):
return num + add_val
  return adder

add1 = make_adder()
add1(42)

add42 = make_adder(42)
add42(3)


-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Evangelism

2006-03-10 Thread Kay Schluehr
Magnus Lycka wrote:

> They do this on purpose in the U.S. A country full
> of religious fanatics, where it's impossible to be
> elected president unless you claim that you are a
> devoted Christian and say "God bless America" every
> time you open your mouth.

Maybe Pythonistas should make a cultural investment in emergent
markets?

http://www.khandro.net/mysterious_naga.htm

Kay

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


Re: API/C memory mananegemnt problem

2006-03-10 Thread Fredrik Lundh
[EMAIL PROTECTED] wrote:

> In my C-module I have a loop like this:
> ***
>
> int size=1000;
>
> output=(double *) calloc(size, sizeof(double));
> py_output=PyList_New(0);
> for(i=0; i   tmp=PyFloat_FromDouble(output[i]);
>   PyList_Append(py_output, tmp);

 Py_DECREF(tmp); // append adds a reference

> }
>
> free(outout);
>
> return py_output;

or with proper error handling:

   int size=1000;
   output=(double *) calloc(size, sizeof(double));
   if (!output) {
   PyErr_NoMemory();
   return NULL;
   }
   py_output=PyList_New(0);
   if (!py_output)
  goto error;
   for(i=0; i



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


Why python doesn't use syntax like function(, , x) for default parameters?

2006-03-10 Thread Dmitry Anikin
I mean, it's very convenient when default parameters
can be in any position, like
def a_func(x = 2, y = 1, z):
...
(that defaults must go last is really a C++ quirk which
is needed for overload resolution, isn't it?)

and when calling, just omit parameter when you want to
use defaults:
a_func(, , 3)

There are often situations when a function has independent
parameters, all having reasonable defaults, and I want to
provide just several of them. In fact, I can do it using
keyword parameters, but it's rather long and you have to
remember/lookup names of parameters.

Is there some contradiction in python syntax which disallows
an easy implementation of this feature, or just nobody bothered
with this? If former is the case, please show me why, because
I badly need this feature in embedded python app (for
compatibility with other language that uses such syntax) and might
venture to implement it myself, so don't want to waste time
if it's gonna break something.
Or maybe it might be an idea for enhancement proposal?

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


Re: A better RE?

2006-03-10 Thread bruno at modulix
Magnus Lycka wrote:
> I want an re that matches strings like "21MAR06 31APR06 1236",
> where the last part is day numbers (1-7), i.e it can contain
> the numbers 1-7, in order, only one of each, and at least one
> digit. I want it as three groups. I was thinking of
> 
> r"(\d\d[A-Z]\d\d) (\d\d[A-Z]\d\d) (1?2?3?4?5?6?7?)"
> 
> but that will match even if the third group is empty,
> right? Does anyone have good and not overly complex RE for
> this?

Simplest:

>>> exp = r"(\d{2}[A-Z]{3}\d{2}) (\d{2}[A-Z]{3}\d{2}) (\d+)"
>>> re.match(exp, s).groups()
('21MAR06', '31APR06', '1236')

but this could give you false positive, depending on the real data.

If you want to be as strict as possible, this becomes a little bit hairy.

> P.S. I know the "now you have two problems reply..."

!-)

-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: embedding Python: how to avoid memory leaks?

2006-03-10 Thread Wolfgang
Hallo,

> >>> I couldn't get the PyRun_*File* calls to work on Windows,
> >>> presumably because of the FILE* problem mentioned in the docs.
> >>
> >> Which compiler do you use?
> >
> > MSVC++ (version 6 from memory -- I do most of my development on
> > the Mac and fire up Virtual PC occasionally to test Win builds).
>
> Well, I don't really *know*, but it's hard to believe to me that the
> file descriptor format changed within the Microsoft product series.

Yes it is hard to believe but true.
Even debug and release versions have incompatible file pointer.
It's not possible to pass af FILE* from a debug app to the embedded
release python.dll.

A workaround is to create the FILE* with the python api functions and
pass this pointer back to python.

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


API/C memory mananegemnt problem

2006-03-10 Thread Marco Fumana
Thank for your help.

I have try to follow your suggestion but I seem to fail.

Now my C-module (call it C_Core) code is:

***
/* create_list function */
int size=1000;

output=(double *) calloc(size, sizeof(double));
py_output=PyList_New(0);
for(i=0; ihttp://mail.python.org/mailman/listinfo/python-list


Re: Python Evangelism

2006-03-10 Thread Tim Churches
Kay Schluehr wrote:
> Magnus Lycka wrote:
> 
>> They do this on purpose in the U.S. A country full
>> of religious fanatics, where it's impossible to be
>> elected president unless you claim that you are a
>> devoted Christian and say "God bless America" every
>> time you open your mouth.
> 
> Maybe Pythonistas should make a cultural investment in emergent
> markets?
> 
> http://www.khandro.net/mysterious_naga.htm

I notice the above page mentions Glykon - see also
http://www.livius.org/gi-gr/glykon/glykon.html

I think that Glykon should be invited to be the sponsoring divinity for
PyCon next year. I hear that worship of pagan gods is, like everything
else, bigger in Texas.

Tim C


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


Re: Why python doesn't use syntax like function(, , x) for default parameters?

2006-03-10 Thread Duncan Booth
Dmitry Anikin wrote:

> Is there some contradiction in python syntax which disallows
> an easy implementation of this feature, or just nobody bothered
> with this? If former is the case, please show me why, because
> I badly need this feature in embedded python app (for
> compatibility with other language that uses such syntax) and might
> venture to implement it myself, so don't want to waste time
> if it's gonna break something.
> 
I think you would find it hard to implement exactly that in Python. Of 
course what you can do easily enough is invent a magic 'missing' value and 
map Python calls of:

   a_func(missing, missing, 3)

to a call of:

   a_func(,,3)

in your other language. It seems to me though that writing:

   a_func(z=3)

ought to be clearer to anyone reading the code, especially when you come 
back to your code in 6 months time and find:

   b_func(,,,12)


Remember Python is a dynamic language, so the compiler cannot tell which 
function you are actually calling. In a statically bound language parameter 
defaults are often restricted to constant values and the default values are 
simply inserted in place of any missing arguments when the call is 
compiled. That isn't possible in Python, so the interpreter has to insert 
the missing values when you actually make the call. The code to do that is 
complex enough with the current restrictions.

To allow arbitrary arguments to be defaulted, I think you would have to add 
a new magic value to represent a missing parameter, make the compiler pass 
that in place of any omitted positional parameters, and then make the 
function call code check all parameters to see if they are missing values 
and if so substitute the actual default. It would be possible, but it  
doesn't really give you any additional power since you can already do that 
in the cases where you need it by using keyword arguments or by passing an 
explicit value to mean 'replace this parameter by some other canned value'.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: creating variable in root namespace from module

2006-03-10 Thread Duncan Booth
MakaMaka wrote:

> I have a scope related question that I haven't been able to find an
> answer to anywhere.  Is there a way to have a function in an imported
> module add variables to the scope of the calling script?  Basically,
> can I have the following:
> 
> #root.py
> import some_module.py
> 
> some_module.afunction() # <== create a variable x1=1 and add it to the
> scope of root.py
> 
> print x1  # <== would print 1
> 
> I know this can be accomplished by passing the what globals() returns
> into the function; however, I'm wondering if there is a way to do this
> without passing anything to the function.

Try:

x1 = some_module.afunction()

This has the advantage that in some other script you can decide to give the 
variable a meaningful name, and it doesn't have to be the same as the name 
you used in your first script.

You can easily extend this technique to set several variables in the 
calling script:

x1, y2, z3 = some_module.afunction()

You don't even have to restrict yourself to global variables, this 
technique will even work to let the function set variables in another 
function's local namespace or attributes on some arbitrary object.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Help with a reverse dictionary lookup

2006-03-10 Thread bruno at modulix
rh0dium wrote:
> Hi all,
> 
> I have a dict which looks like this..
> 
> dict={'130nm': {'umc': ['1p6m_1.2-3.3_fsg_ms']},
> '180nm': {'chartered': ['2p6m_1.8-3.3_sal_ms'], 'tsmc':
> ['1p6m_1.8-3.3_sal_log', '1p6m_1.8-3.3_sal_ms']},
> '250nm': {'umc': ['2p6m_1.8-3.3_sal_ms'], 'tsmc':
> ['1p6m_2.2-3.5_sal_log', '1p6m_1.8-3.3_sal_ms']}
> }
> 
> For clarification:
> 130nm,180nm,250nm refer to Nodes
> tsmc,chartered,umc refer to Foundries
> 1p6m..blah, 2p6m..blah refer to Process
> 
> I want a function which can do this:
> 
> nodes = getNodes()
>   should return a list [130nm,180nm,250nm]
> 
> nodes = getNodes(Foundry="umc")
>   should return a list [130nm,250nm]
> 
> nodes = getNodes(Process="2p6m_1.8-3.3_sal_ms")
>   should return a list [180nm,250nm]
> 
> nodes = getNodes(Foundry="umc", Process="2p6m_1.8-3.3_sal_ms")
>   should return a list [250nm]
> 
> nodes = getNodes(Foundry="foo", Process="2p6m_1.8-3.3_sal_ms")
>   should return None
> 
> Obviously I want to extend this to Each area ( i.e., getFoundry(),
> getProcess() ) but I can do that.  I just don't know how to easily do
> this reverse kind of look up?  Can someone help me on this?
> 

Not tested:


import pprint

data={
'130nm': {
  'umc': ['1p6m_1.2-3.3_fsg_ms']
},
'180nm': {
  'chartered': ['2p6m_1.8-3.3_sal_ms'],
  'tsmc': ['1p6m_1.8-3.3_sal_log', '1p6m_1.8-3.3_sal_ms']
},
'250nm': {
  'umc': ['2p6m_1.8-3.3_sal_ms'],
  'tsmc':['1p6m_2.2-3.5_sal_log', '1p6m_1.8-3.3_sal_ms']
}
}


# --
class DataFinder(object):
def __init__(self, data):
self._data = data
self._nodes = data.keys()
self._foundries_nodes = {}
self._procs_nodes = {}
self._procs_foundries = {}

for node, foundries in data.items():
for foundry, procs in foundries.items():
self._foundries_nodes.setdefault(foundry,
 []).append(node)
for proc in procs:
self._procs_nodes.setdefault(proc, []).append(node)
self._procs_foundries.setdefault(proc,
 []).append(foundry)
self._foundries = self._foundries_nodes.keys()
self._procs = self._procs_foundries.keys()

# --
# API
# --
def get_nodes(foundry=None, process=None):
if foundry is None and process is None:
return self._nodes[:]
if process is None:
return self._get_nodes_for_foundry(foundry)
if foundry is None:
return self._get_nodes_for_proc(proc)
return self._get_nodes_for_foundry_and_proc(foundry, proc)

def get_foundries(node=None, process=None):
if node is None and process is None:
return self._foundries[:]
if process is None:
return self._get_foundries_for_node(node)
if node is None:
return self._get_foundries_for_proc(node)
return self._get_foundries_for_node_and_proc(node, proc)

# TODO : get_procs

#---
# IMPL
# --
def _get_foundries_for_node(self, node):
return self._foundries_nodes.get(node)

def _get_foundries_for_proc(self, proc):
return self._procs_foundries.get(proc)

def _get_foundries_for_node_and_proc(self, node, proc):
return list(set(self._get_foundries_for_node(node))
& set(self._get_foundries_for_proc(proc)))

# --
def _get_nodes_for_foundry(self, foundry):
return self._foundries_nodes.get(foundry)

def _get_nodes_for_proc(self, proc):
return self._procs_nodes.get(proc)

def _get_nodes_for_foundry_and_proc(self, foundry, proc):
return list(set(self._get_nodes_for_foundry(foundry))
& set(self._get_nodes_for_proc(proc)))

# --
# MISC
# --
def _inspect(self):
ft = pprint.pformat
s = """
 ---
+ data :
%s
+ foundries_nodes :
%s
+ procs_nodes :
%s
+ procs_foundries :
%s
""" % (ft(self._data),
   ft(self._foundries_nodes),
   ft(self._procs_nodes),
   ft(self._procs_foundries)
   )
print s



HTH
-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Embedded Python

2006-03-10 Thread John Dean
Hi
Is it possible to execute a whole script using the C API function
PyRun_String? At moment I load the script into a buffer. Then I get each
line of the script and pass it PyRun_String. This seems very inefficient. It
would be more efficient if I could pass the complete string buffer to
PyRun_String and execute the script as a whole

-- 
Best Regards
John
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Evangelism

2006-03-10 Thread Juho Schultz
Magnus Lycka wrote:
> rtilley wrote:
> 
>>
>> I think it's the name. Python. Let's change it to something nicer. 
>> Think about it... if you found a Ruby, you'd pick it up and put it in 
>> your pocket. If you ran across a Python, you'd run away.
> 
> 
> I think you have a point, but I also think it's a bit
> late to change it after 15 years or so, considering all
> books, web sites etc. We're stuck with Python, and can
> only do the best of that. Actually, in Swedish, "Jag
> mår pyton" i.e. "I feel like python" means "I feel
> sick", and "det luktar pyton" i.e. "it smells python",
> means "it stinks". That doesn't make Python easier to
> sell here... Still to late to change...
> 

In Finnish "ajaa käärme pyssyyn" ("force a snake into a rifle") means 
doing something almost impossible. If you have to put a snake into a 
rifle, try Python - a bite does not kill you. So it works both ways.

> I think a good example on the problem with letting
> techies like us do naming is that grand successor
> of Unix developed by the great minds at Bell Labs.
> 
> First, they name it after a movie which is famous
> for being exceptionally bad--Plan 9 (from outer space).
> Really grand company there!
> 
> Then, when they make a real product of it, they call
> it Inferno, and some part of it gets called Limbo.
> 
"Inferno - the Lamborghini Diablo of operating systems"
What is the problem here?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Embedded Python

2006-03-10 Thread Fredrik Lundh
John Dean wrote:

> Is it possible to execute a whole script using the C API function
> PyRun_String? At moment I load the script into a buffer. Then I get each
> line of the script and pass it PyRun_String. This seems very inefficient. It
> would be more efficient if I could pass the complete string buffer to
> PyRun_String and execute the script as a whole

so why don't you try it? ;-)





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


Re: Python Evangelism

2006-03-10 Thread Ant
> It's not too late to rename the cheese shop though.
> (We don't need even more stink...)

What kind of cheese do you guys eat anyway ;-)

It's not the names that are the problem as far as markleing goes - they
are not dull names, which means they won't be forgotten. This is a good
thing! As is the humour - who amongst  us are going to forget where the
repository for community projects are? Unlike RubyJewels, RubyBaubles
or whatever ;-)

As long as the names are memorable, marketing isn't an issue if it
want's to be done. For example the famous British inventors Wallace and
Gromit could be asked to endorse Python, ("Look Gromit - a Cheese
shop!"). And there is a successful web-based credit card called an Egg
card.

A Python is a good powerful image to have associated with the language.
What does Ruby say? That the language is pretty? And Perl? Misleading
advertising there then ;-) Ever seen a Python? Powerful, elegant, and
can digest just about anything you can feed it... good image I reckon!

I'm obviously not suggesting we do such a thing, just pointing out a
couple of things:

1) There's nothing wrong with the names we've got.
2) Some people on this newsgroup need to clean their fridges out more
often!

-- 
Ant...

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


Re: Python Evangelism

2006-03-10 Thread Terry Hancock
On Thu, 9 Mar 2006 19:33:38 -0500
"Thomas G. Willis" <[EMAIL PROTECTED]> wrote:
> On 3/9/06, Terry Hancock <[EMAIL PROTECTED]>
> wrote:
> >
> > On Thu, 9 Mar 2006 10:33:12 -0500
> > "Thomas G. Willis" <[EMAIL PROTECTED]> wrote:
> > > I get particulalry annoyed now with linux when I start
> > > up synaptic and my choices are cluttered with several
> > > programs who might help me in some way, but the only
> > > difference described in the description is that they
> > > were implemented in language XXX.  I don't really
> > > consider that a choice, it's more noise than anything.
> >
> > Well, it's a matter of audience. I like to know what
> > language programs are written in because I might want to
> > modify them, and I don't feel equally confident in every
> > language.  A program written in C is less "open" to me
> > personally than one written in Python (even though C is
> > something I have used). A program written in Lisp or
> > Prolog might as well be closed source for my purposes --
> > I'd have as much luck begging the developers to make
> > changes as to attempt them myself.
> >
> > This is a non-issue for programs that already "just
> > work", which is why a utility like bittorrent needn't
> > bother advertising its language.  It also can be a
> > red-herring if a language is written in C or Java, but
> > has an excellent Python scripting environment.
> >
> > So, while I can appreciate that it may seem like noise
> > to someone who never imagines tinkering with the sources
> > and it isn't a 100% indicator of what I want to know,
> > it can be really useful to tinkerers (and it shouldn't
> > be surprising that tinkerers design a system that's good
> > for tinkerers).
> >
> > There are of course, desktop distributions that cut all
> > that cruft down to "best of breed" applications for the
> > end user.
> >
> I see your points Terry. And I understand the need for
> tinkerers and the value of knowing what options are
> available in a given language.
> 
> But, I  think relying on the language as a selling
> point/feature is short sighted. I can't recall any program
> that has gained mass acceptance  who's selling point was
> "written in ..."

That makes sense if the author's objective is "mass
acceptance". But that's not what you get "paid" for on
an open source project.

Payment -- in the form of contributions to your project --
occurs because you attract people who share your interest
in working on the code.

Of course, this really depends a lot on who the author is,
and what their motivations were in creating the package.

But in the classic "scratch an itch"/"single developer
working in their spare time" scenario, it's pretty 
common.

It's also probably a bit much to expect "savvy marketing"
from said back room developer. ;-)

It helps if you think of it as a "swap meet" instead
of a "department store". :-)

> In the case of language evangelism, It'd be nice if kick
> ass programs were produced that revolutionized computing
> and how people communicate. If they were written in a
> language that I already know and can extend if I desire,
> even better.  if the equation were flipped and it was just
> a program written in a language I know, but does not do
> anything of value for me that isn't already fulfilled
> elsewhere, then it essentially holds no value.

That would be true if programs were atomic.  But it
quite frequently happens that a program which provides
a "mundane" piece of programming infrastructure (say
an email client) is a useful part to add to that
"revolutionary" application that you've been tinkering
with for the last few months.

Anyway, I think most of us are into evolution more than
revolution. The latter is more newsworthy, but the former
is where most of the action is most of the time.  Kind
of like any field in science or engineering. :-)

> why did you reply to me instead of the list?

Thumbfingered, I guess. ;-)  I've responded to both and
left myself quoted.  Normally, my client *does* respond
automatically to the list, I'm not sure why it didn't
this time.

Cheers,
Terry

-- 
Terry Hancock ([EMAIL PROTECTED])
Anansi Spaceworks http://www.AnansiSpaceworks.com

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


Re: Best way to have a for-loop index?

2006-03-10 Thread Terry Hancock
On 9 Mar 2006 16:32:24 -0800
[EMAIL PROTECTED] wrote:
> I write a lot of code that looks like this:
> 
> for myElement, elementIndex in zip( elementList,
> range(len(elementList))):
> print "myElement ", myElement, " at index:
> ",elementIndex
> 
> My question is, is there a better, cleaner, or easier way
> to get at the element in a list AND the index of a loop
> than this?

In fact it is so common a need, there is a built-in
function called "enumerate" that does the 'zip' for
you:

for elementIndex, myElement in enumerate(elementList):
print "myElement ", myElement, " at index: ",elementIndex

-- 
Terry Hancock ([EMAIL PROTECTED])
Anansi Spaceworks http://www.AnansiSpaceworks.com

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


Re: Why python doesn't use syntax like function(, , x) for default parameters?

2006-03-10 Thread Terry Hancock
On 10 Mar 2006 09:51:01 GMT
Duncan Booth <[EMAIL PROTECTED]> wrote:
> Dmitry Anikin wrote:
> > Is there some contradiction in python syntax which
> > disallows an easy implementation of this feature, or
> > just nobody bothered with this? If former is the case,
> > please show me why, because I badly need this feature in
> > embedded python app (for compatibility with other
> > language that uses such syntax) and might venture to
> > implement it myself, so don't want to waste time if it's
> > gonna break something.
> > 
> I think you would find it hard to implement exactly that
> in Python. Of  course what you can do easily enough is
> invent a magic 'missing' value and  map Python calls of:
> 
>a_func(missing, missing, 3)
> 
> to a call of:
> 
>a_func(,,3)

It's not uncommon, of course, to use "None" for this
purpose. I have a lot of code that does something like:

def myfunc(a, b, c):
if a is None:
a = []
...


-- 
Terry Hancock ([EMAIL PROTECTED])
Anansi Spaceworks http://www.AnansiSpaceworks.com

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


Re: Python Evangelism

2006-03-10 Thread Terry Hancock
On Fri, 10 Mar 2006 20:44:55 +1100
Tim Churches <[EMAIL PROTECTED]> wrote:
> I think that Glykon should be invited to be the sponsoring
> divinity for PyCon next year. I hear that worship of pagan
> gods is, like everything else, bigger in Texas.

Ignoring the silly Python jokes, *is* PyCON going to be in
Texas next year?  I wasn't sure what would happen, since it
was in Washington DC the last (first?) 3 years, according to
the website.  Would be great for me if true, since I live
there.

-- 
Terry Hancock ([EMAIL PROTECTED])
Anansi Spaceworks http://www.AnansiSpaceworks.com

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


Re: urlerror, urllib2: "no address" ... why or debug tips?

2006-03-10 Thread Rene Pijlman
[EMAIL PROTECTED]:
>Help please with a URLError.

Post your code (a small self-contained example, preferrably) and the URL.

-- 
René Pijlman
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Evangelism

2006-03-10 Thread Steve Holden
Terry Hancock wrote:
> On Fri, 10 Mar 2006 20:44:55 +1100
> Tim Churches <[EMAIL PROTECTED]> wrote:
> 
>>I think that Glykon should be invited to be the sponsoring
>>divinity for PyCon next year. I hear that worship of pagan
>>gods is, like everything else, bigger in Texas.
> 
> 
> Ignoring the silly Python jokes, *is* PyCON going to be in
> Texas next year?  I wasn't sure what would happen, since it
> was in Washington DC the last (first?) 3 years, according to
> the website.  Would be great for me if true, since I live
> there.
> 
Yes, 2007 will be at the same place as 2006.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd www.holdenweb.com
Love me, love my blog holdenweb.blogspot.com

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


[wxPython] howto prevent Frame reszing?

2006-03-10 Thread Cell
Hi,

I have searched for this but the only thing I can find is somebody that
tells
wx.RESIZE_BORDER is the style to look for.

When I apply this in my code I am still able to resize the frame.

Somebody can help me here?

For example:

class FrameName(wx.MiniFrame):
   def __init__(
   self, parent, title, pos=wx.DefaultPosition,
size=wx.DefaultSize,
   style=wx.DEFAULT_FRAME_STYLE|wx.RESIZE_BORDER):
   wx.MiniFrame.__init__(self, parent, -1, title, pos, (300,300),
style)

Is the (mini) Frame that I have now.

It would be nice if somebody can help me out..
Thanks in advance (btw, I am new to wxPython) :)

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


Re: A bit OT: Python prompts display as nested mail quotes in Thunderbird

2006-03-10 Thread Joel Hedlund
> They already ARE "plain text" (I don't know of anyone submitting
> MIME/HTML enhanced content on this group).

I know.

> it would mean all other quoted text would not look "quoted" in your reader.

I.e. they would have '>' chars at line start. That is *excatly* what I want and 
what I asked in my post. I don't need colored lines in the margin to understand 
quotes.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A better RE?

2006-03-10 Thread Eddie Corns
Magnus Lycka <[EMAIL PROTECTED]> writes:

>I want an re that matches strings like "21MAR06 31APR06 1236",
>where the last part is day numbers (1-7), i.e it can contain
>the numbers 1-7, in order, only one of each, and at least one
>digit. I want it as three groups. I was thinking of

Just a small point - what does "in order" mean here? if it means that eg 1362
is not valid then you're stuck because it's context sensitive and hence not
regular.

I can't see how any of the fancy extensions could help here but maybe I'm just
lacking insight.

Now if "[\1-7]" worked you'd be home and dry.

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


Re: A better RE?

2006-03-10 Thread Fredrik Lundh
Eddie Corns wrote:


> >I want an re that matches strings like "21MAR06 31APR06 1236",
> >where the last part is day numbers (1-7), i.e it can contain
> >the numbers 1-7, in order, only one of each, and at least one
> >digit. I want it as three groups. I was thinking of
>
> Just a small point - what does "in order" mean here? if it means that eg 1362
> is not valid then you're stuck because it's context sensitive and hence not
> regular.
>
> I can't see how any of the fancy extensions could help here but maybe I'm
> just lacking insight.

import re

p = re.compile("(?=[1234567])(1?2?3?4?5?6?7?)$")

def test(s):
m = p.match(s)
print repr(s), "=>", m and m.groups() or "none"

test("")
test("1236")
test("1362")
test("12345678")

prints

'' => none
'1236' => ('1236',)
'1362' => none
'12345678' => none





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


Which GUI toolkit is THE best?

2006-03-10 Thread invitro81
Hello

I've recently learnt python and I do love it! I congratulate all those 
geeks who produce this nice language; well, because I could be called a 
nearby newbee I've decided to improve my abilities by writing my own 
nice editor with python; so I've to choose among all those GUI toolkit's 
available there..

But I've no idea which one I should use to start with.. I've read that 
tkinter seems to be the de facto standart in the pyhon community; but 
why? Is it the best available one or are theire other reasons? I read 
also a litte about wxpython and pygtk.. both are appealing to me but 
again to make a choice is difficult; is there also some guy liking pyqt 
is it worse or should it be avoided because of the licencing policy for 
qt (which I also like..)?

* Which one is the most fun to program with?
* Which one is the most easy to learn?
* Which one looks best?
* Which one is the most productive to program with?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A better RE?

2006-03-10 Thread Jim

Eddie Corns wrote:
> Just a small point - what does "in order" mean here? if it means that eg 1362
> is not valid then you're stuck because it's context sensitive and hence not
> regular.
I'm not seeing that.  Any finite language is regular -- as a last
resort you could list all ascending sequences of 7 or fewer digits (but
perhaps I misunderstood the original poster's requirements).

Jim

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


how to validate a proxy is alive?

2006-03-10 Thread JuHui
If a proxy is alive then return true, else return fals after 1 second.
thanks

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


Re: A better RE?

2006-03-10 Thread Eddie Corns
"Fredrik Lundh" <[EMAIL PROTECTED]> writes:

>Eddie Corns wrote:


>> >I want an re that matches strings like "21MAR06 31APR06 1236",
>> >where the last part is day numbers (1-7), i.e it can contain
>> >the numbers 1-7, in order, only one of each, and at least one
>> >digit. I want it as three groups. I was thinking of
>>
>> Just a small point - what does "in order" mean here? if it means that eg 1362
>> is not valid then you're stuck because it's context sensitive and hence not
>> regular.
>>
>> I can't see how any of the fancy extensions could help here but maybe I'm
>> just lacking insight.

>import re

>p = re.compile("(?=[1234567])(1?2?3?4?5?6?7?)$")

>def test(s):
>m = p.match(s)
>print repr(s), "=>", m and m.groups() or "none"

>test("")
>test("1236")
>test("1362")
>test("12345678")

>prints

>'' => none
>'1236' => ('1236',)
>'1362' => none
>'12345678' => none

>

I know I know!  I cancelled the article about a minute after posting it.

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


Re: how to validate a proxy is alive?

2006-03-10 Thread Rene Pijlman
JuHui:
>If a proxy is alive then return true, else return fals after 1 second.

What kind of proxy? Design pattern? Protocol? Which one?

-- 
René Pijlman
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A bit OT: Python prompts display as nested mail quotes in Thunderbird

2006-03-10 Thread Joel Hedlund
> Do you have the Quote Colors extension? 

I do now. :-)

> You can also disable the use of colors in the options, but that will 
> remove the colors for all messages.

Or I can tell it to display colored '>' chars. Marvellous!

Thanks for the advice! You're a real help.

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


open2 problem

2006-03-10 Thread mapik . ua
Hi. I have such problem with os.popen2 function:

 //test.py file
 #!/usr/local/bin/python
 print "start"
 x= raw_input()
 print "end"

 //main.py file
 #!/usr/local/bin/python
 import os
 i,o = os.popen2('./tester.py')
 print o.readline()
 i.write("hi")
 print o.readline()
 i.close()
 o.close()

When I run main.py its hung so I break it running and get exception
error:
  Traceback (most recent call last):
  File "./tester.py", line 4, in ?
x= raw_input()
Traceback (most recent call last):
KeyboardInterrupt
  File "./c.py", line 5, in ?
print o.readline()
KeyboardInterrupt

But if I in main.py make some changes its work fine, but i need to read
first line for analyzing:
 //main.py file
 #!/usr/local/bin/python
 import os
 i,o = os.popen2('./tester.py')
 i.write("hi")
 print o.readline()
 print o.readline()
 i.close()
 o.close()

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


Re: how to validate a proxy is alive?

2006-03-10 Thread JuHui
I want to get a html page content via a http proxy.
befor this, I want to check the proxy. how to validate it?
thanks

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


Re: Which GUI toolkit is THE best?

2006-03-10 Thread Peter Decker
On 3/10/06, invitro81 <[EMAIL PROTECTED]> wrote:

> But I've no idea which one I should use to start with.. I've read that
> tkinter seems to be the de facto standart in the pyhon community; but
> why? Is it the best available one or are theire other reasons? I read
> also a litte about wxpython and pygtk.. both are appealing to me but
> again to make a choice is difficult; is there also some guy liking pyqt
> is it worse or should it be avoided because of the licencing policy for
> qt (which I also like..)?
>
> * Which one is the most fun to program with?
> * Which one is the most easy to learn?
> * Which one looks best?
> * Which one is the most productive to program with?

GUI toolkits are not simple things to be productive with. Most people
I know tried out a few briefly, found one that fit their needs and/or
programming style better, and then adopted that as their choice. Given
the complexity of GUIs in general, developers tend to be 'fluent' in
one at a time - it's just too much to remember when switching between
different kits.

So most of the answers you get will invariably be tilted toward the
choice that an individual made. Their reasons for that choice may not
be the same as your reasons, so my advice to you would be to check
them all out for a few hours apiece, and make a choice based on your
impressions.

Having said that, my choice for UI toolkit is wxPython, based on its
use of native controls on all platforms. I disliked the syntax it
inherited from wxWidgets, the C++ project it is based on, but then I
found Dabo, whose UI layer wraps wxPython, giving you all the power
and beauty of wxPython, with none of the ugliness.
--

# p.d.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Which GUI toolkit is THE best?

2006-03-10 Thread Cell

invitro81 schreef:

> Hello
>
> I've recently learnt python and I do love it! I congratulate all those
> geeks who produce this nice language; well, because I could be called a
> nearby newbee I've decided to improve my abilities by writing my own
> nice editor with python; so I've to choose among all those GUI toolkit's
> available there..
>
> But I've no idea which one I should use to start with.. I've read that
> tkinter seems to be the de facto standart in the pyhon community; but
> why? Is it the best available one or are theire other reasons? I read
> also a litte about wxpython and pygtk.. both are appealing to me but
> again to make a choice is difficult; is there also some guy liking pyqt
> is it worse or should it be avoided because of the licencing policy for
> qt (which I also like..)?
>
>   * Which one is the most fun to program with?
>   * Which one is the most easy to learn?
>   * Which one looks best?
>   * Which one is the most productive to program with?

Read this http://wxpython.org/quotes.php ;-)

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


Re: Why python doesn't use syntax like function(, , x) for default parameters?

2006-03-10 Thread Roy Smith
"Dmitry Anikin" <[EMAIL PROTECTED]> wrote:
> There are often situations when a function has independent
> parameters, all having reasonable defaults, and I want to
> provide just several of them. In fact, I can do it using
> keyword parameters, but it's rather long and you have to
> remember/lookup names of parameters.

Specifying the names of the keyword parameters costs you a little typing 
once, but saves everybody (including yourself) a lot of grief later when 
you're trying to figure out what the heck your code does 6 months later.

> I badly need this feature in embedded python app (for
> compatibility with other language that uses such syntax)

Can you tell us more about what it is that you're trying to do?

> Or maybe it might be an idea for enhancement proposal?

You can always write up a PEP, but to be honest, this doesn't sound like 
one that would meet with much enthusiasm from the community.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why python doesn't use syntax like function(, , x) for default parameters?

2006-03-10 Thread Steve Holden
Dmitry Anikin wrote:
> I mean, it's very convenient when default parameters
> can be in any position, like
> def a_func(x = 2, y = 1, z):
> ...
> (that defaults must go last is really a C++ quirk which
> is needed for overload resolution, isn't it?)
> 
I've no idea why C++ required defaults last; it certainly seems wise to 
avoid confusion with the positionals in Python.

> and when calling, just omit parameter when you want to
> use defaults:
> a_func(, , 3)
> 
Yerch! So now you've forced all arguments to be positional? This doesn't 
seem like an improvement. And it's just plain fugly.

> There are often situations when a function has independent
> parameters, all having reasonable defaults, and I want to
> provide just several of them. In fact, I can do it using
> keyword parameters, but it's rather long and you have to
> remember/lookup names of parameters.
> 
Whereas you can invariably remember their positions? I don't think so.

> Is there some contradiction in python syntax which disallows
> an easy implementation of this feature, or just nobody bothered
> with this? If former is the case, please show me why, because
> I badly need this feature in embedded python app (for
> compatibility with other language that uses such syntax) and might
> venture to implement it myself, so don't want to waste time
> if it's gonna break something.
> Or maybe it might be an idea for enhancement proposal?
> 
The thing about enhancement proposals is that they are supposed to 
*improve* the language. Frankly I wouldn't see this as any kind of 
enhancement.

If you have a large program to translate from another language you will 
probably find that a modest application of Python suffices to translate 
all the calls into whatever form turns out to be required in Python.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd www.holdenweb.com
Love me, love my blog holdenweb.blogspot.com

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


Re: how to validate a proxy is alive?

2006-03-10 Thread robert
JuHui wrote:
> I want to get a html page content via a http proxy.
> befor this, I want to check the proxy. how to validate it?
> thanks
> 

most simple by a socket-connect / error if non-existing:

 >>> s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
 >>> s.connect(('nonexisting-proxy-server',3129))
Traceback (most recent call last):
   File "", line 1, in ?
   File "", line 1, in connect
error: (10061, 'Connection refused')
 >>> s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
 >>> s.connect(('existing-proxy-server',3128))
 >>> 1
1
 >>>



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


Re: open2 problem

2006-03-10 Thread Felipe Almeida Lessa
Em Sex, 2006-03-10 às 04:49 -0800, [EMAIL PROTECTED] escreveu:
> Hi. I have such problem with os.popen2 function:

Why don't you use the subprocess module? See
http://docs.python.org/lib/module-subprocess.html 

-- 
"Quem excele em empregar a força militar subjulga os exércitos dos
outros povos sem travar batalha, toma cidades fortificadas dos outros
povos sem as atacar e destrói os estados dos outros povos sem lutas
prolongadas. Deve lutar sob o Céu com o propósito primordial da
'preservação'. Desse modo suas armas não se embotarão, e os ganhos
poderão ser preservados. Essa é a estratégia para planejar ofensivas."

  -- Sun Tzu, em "A arte da guerra"

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

Re: how to validate a proxy is alive?

2006-03-10 Thread JuHui
cool!
thanks !

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


Re: open2 problem

2006-03-10 Thread mapik . ua
> Why don't you use the subprocess module?

 I have tried subprocess module and got the same problem

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


Re: A better RE?

2006-03-10 Thread Eddie Corns
"Jim" <[EMAIL PROTECTED]> writes:


>Eddie Corns wrote:
>> Just a small point - what does "in order" mean here? if it means that eg 1362
>> is not valid then you're stuck because it's context sensitive and hence not
>> regular.
>I'm not seeing that.  Any finite language is regular -- as a last
>resort you could list all ascending sequences of 7 or fewer digits (but
>perhaps I misunderstood the original poster's requirements).

No, that's what I did.  Just carelessnes on my part, time I had a holiday!

Eddie

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


Re: Why python doesn't use syntax like function(, , x) for default parameters?

2006-03-10 Thread Antoon Pardon
Op 2006-03-10, Roy Smith schreef <[EMAIL PROTECTED]>:
> "Dmitry Anikin" <[EMAIL PROTECTED]> wrote:
>> There are often situations when a function has independent
>> parameters, all having reasonable defaults, and I want to
>> provide just several of them. In fact, I can do it using
>> keyword parameters, but it's rather long and you have to
>> remember/lookup names of parameters.
>
> Specifying the names of the keyword parameters costs you a little typing 
> once, but saves everybody (including yourself) a lot of grief later when 
> you're trying to figure out what the heck your code does 6 months later.

Could you explain what is so hard in figuring out:

  func(,,4)

We sure don't seem to have a problem with figuring out things like

  lst[::2]


Personnaly in a situation where it is likely that the first
parameter is going to take a default and the second parameter
is going to vary a lot, I would have prefered that to be
visible in how the function is called, instead of a call
with only one argument being interpreted as being the value
for the second parameter.

More specifically I would have preferred the possibility
of range(,n) and this being equivallent to range(0,n)
instead of range(n) being equivallent to range(0,n).

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


Re: Which GUI toolkit is THE best?

2006-03-10 Thread Eric Brunel
On Fri, 10 Mar 2006 13:36:18 +0100, invitro81 <[EMAIL PROTECTED]> wrote:

> Hello
>
> I've recently learnt python and I do love it! I congratulate all those  
> geeks who produce this nice language; well, because I could be called a  
> nearby newbee I've decided to improve my abilities by writing my own  
> nice editor with python; so I've to choose among all those GUI toolkit's  
> available there..
>
> But I've no idea which one I should use to start with.. I've read that  
> tkinter seems to be the de facto standart in the pyhon community; but  
> why? Is it the best available one or are theire other reasons? I read  
> also a litte about wxpython and pygtk.. both are appealing to me but  
> again to make a choice is difficult; is there also some guy liking pyqt  
> is it worse or should it be avoided because of the licencing policy for  
> qt (which I also like..)?
>
>   * Which one is the most fun to program with?
>   * Which one is the most easy to learn?
>   * Which one looks best?
>   * Which one is the most productive to program with?

It all depends on what features are the most important for you. Here is  
some help to answer the question yourself:
http://www.awaretek.com/toolkits.html

HTH
-- 
python -c "print ''.join([chr(154 - ord(c)) for c in  
'U(17zX(%,5.zmz5(17;8(%,5.Z65\'*9--56l7+-'])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why python doesn't use syntax like function(, , x) for default parameters?

2006-03-10 Thread Diez B. Roggisch
Antoon Pardon wrote:

>>
>> Specifying the names of the keyword parameters costs you a little typing
>> once, but saves everybody (including yourself) a lot of grief later when
>> you're trying to figure out what the heck your code does 6 months later.
> 
> Could you explain what is so hard in figuring out:
> 
>   func(,,4)
> 
> We sure don't seem to have a problem with figuring out things like
> 
>   lst[::2]

That is the usual polemics. Its a HUGE difference if I'm supposed to
remember 2 default values that are 0 and , in a
specialized syntax, than arbitrary values

f(,3)

in some arbitrary function. 
 
Diez
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A better RE?

2006-03-10 Thread Paul McGuire
"Magnus Lycka" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> I want an re that matches strings like "21MAR06 31APR06 1236",
> where the last part is day numbers (1-7), i.e it can contain
> the numbers 1-7, in order, only one of each, and at least one
> digit. I want it as three groups. I was thinking of
>
> r"(\d\d[A-Z]\d\d) (\d\d[A-Z]\d\d) (1?2?3?4?5?6?7?)"
>
> but that will match even if the third group is empty,
> right? Does anyone have good and not overly complex RE for
> this?
>
> P.S. I know the "now you have two problems reply..."

For the pyparsing-inclined, here are two versions, along with several
examples on how to extract the fields from the returned ParseResults object.
The second version is more rigorous in enforcing the days-of-week rules on
the 3rd field.

Note that the month field is already limited to valid month abbreviations,
and the same technique used to validate the days-of-week field could be used
to ensure that the date fields are valid dates (no 31st of FEB, etc.), that
the second date is after the first, etc.

-- Paul
Download pyparsing at http://pyparsing.sourceforge.net.


data  = "21MAR06 31APR06 1236"
data2 = "21MAR06 31APR06 1362"

from pyparsing import *

# define format of an entry
month = oneOf("JAN FEB MAR APR MAY JUN JUL AUG SEP OCT NOV DEC")
date = Combine( Word(nums,exact=2) + month + Word(nums,exact=2) )
daysOfWeek = Word("1234567")
entry = date.setResultsName("startDate") + \
date.setResultsName("endDate") + \
daysOfWeek.setResultsName("weekDays") + \
lineEnd

# extract entry data
e = entry.parseString(data)

# various ways to access the results
print e.startDate, e.endDate, e.weekDays
print "%(startDate)s : %(endDate)s : %(weekDays)s" % e
print e.asList()
print e
print

# get more rigorous in testing for valid days of week field
def rigorousDayOfWeekTest(s,l,toks):
# remove duplicates from toks[0], sort, then compare to original
tmp = "".join(sorted(dict([(ll,0) for ll in toks[0]]).keys()))
if tmp != toks[0]:
raise ParseException(s,l,"Invalid days of week field")

daysOfWeek.setParseAction(rigorousDayOfWeekTest)
entry = date.setResultsName("startDate") + \
date.setResultsName("endDate") + \
daysOfWeek.setResultsName("weekDays") + \
lineEnd

print entry.parseString(data)
print entry.parseString(data2) # <-- raises ParseException


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


import and shared global variables

2006-03-10 Thread Michael Brenner
Hi,

I'm implementing a plugin-based program, structured like the example
below (where m1 in the main module, loading m2 as a plugin).  I wanted
to use a single global variable (m1.glob in the example) to store some
config data that the plugins can access.  However, the output shown
belown seems to imply that glob is *copied* or recreated during the
import in m2.  Am I missing something? I thought m1 should be in
sys.modules and not be recreated during the import in m2.

After browsing c.l.p, it seems that this is probably somehow due to the
circular import.  However, I do not really see why this should be a
problem here.  Interestingly, the problem disappears when I put the code
in m1 in a real main() function instead of "if __name__" etc.  Though
this seems to solve my problem, I still want to understand what's
happening.

Thanks,

michael


m1.py:
--
glob = [1]
if __name__ == "__main__":
 glob.append(2)
 print "m1.main().1:", glob
 m2 = __import__("m2")
 m2.test()
 print "m1.main().2:", glob
--

m2.py:
--
def test():
 import m1
 print "m2.test():", m1.glob
-

Output:
m1.main().1: [1, 2]
m2.test(): [1]
m1.main().2: [1, 2]

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


import and shared global variables

2006-03-10 Thread Michael Brenner
Hi,

I'm implementing a plugin-based program, structured like the example 
below (where m1 in the main module, loading m2 as a plugin).  I wanted 
to use a single global variable (m1.glob in the example) to store some 
config data that the plugins can access.  However, the output shown 
belown seems to imply that glob is *copied* or recreated during the 
import in m2.  Am I missing something? I thought m1 should be in 
sys.modules and not be recreated during the import in m2.

After browsing c.l.p, it seems that this is probably somehow due to the 
circular import.  However, I do not really see why this should be a 
problem here.  Interestingly, the problem disappears when I put the code 
in m1 in a real main() function instead of "if __name__" etc.  Though 
this seems to solve my problem, I still want to understand what's 
happening.

Thanks,

michael


m1.py:
--
glob = [1]
if __name__ == "__main__":
 glob.append(2)
 print "m1.main().1:", glob
 m2 = __import__("m2")
 m2.test()
 print "m1.main().2:", glob
--

m2.py:
--
def test():
 import m1
 print "m2.test():", m1.glob
-

Output:
m1.main().1: [1, 2]
m2.test(): [1]
m1.main().2: [1, 2]
-- 
http://mail.python.org/mailman/listinfo/python-list


Adding Multiple Attachments to SMTP mail (msg.add_header)

2006-03-10 Thread EdWhyatt
Hi all, I hope there is someone out there who can help me out - it has
to be something obvious.

I am simulating mail traffic, and want to include multiple attachments
to my mail. I have created a temporary array containing a number of
files - for now just 2.

Debugging my code, I can see that I am correctly storing the files in
the array, and then 1 by 1 adding one file at a time to the message
header.

When the program is complete, the resultant mail has 2 attachments, as
hoped. However, it is the second file attached twice, rather than the
two unique files.

I attach my code for passing the information to  msg.add_header:

(AttNum = 2)

for doatt in range(AttNum):
msg.add_header('Content-Disposition', 'attachment',
filename=ATTselection[doatt])
doatt = doatt + 1
outer.attach(msg)

..
body = MIMEText(Text)
outer.attach(body)

Like I said, it is correctly sending the 2 seperate files from my
ATTselection array, but ultimately attaching the last file twice.

If anyone can help/suggest something please please let me know!

Thanks,
Ed

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


How to best update remote compressed, encrypted archives incrementally?

2006-03-10 Thread robert
Hello,

I want to put (incrementally) changed/new files from a big file tree 
"directly,compressed and password-only-encrypted" to a remote backup 
server incrementally via FTP,SFTP or DAV  At best within a closed 
algorithm inside Python without extra shell tools.
(The method should work with any protocol which allows somehow read, 
write & seek to a remote file.)
On the server and the transmission line there should never be 
unencrypted data.

Usually one would create a big archive, then compress, then encrypt 
(e.g. with gpg -c file) , then transfer. However for that method you 
need to have big free temp disk space and most costing: transfer always 
the complete archive.
With proved block-file encryption methods like GPG I don't get the 
flexibility needed for my task, I guess?

ZIP2 format allows encryption (Is this ZIP encryption method supported 
with Python somehow/basically?). Somehow it would be possible to 
navigate in a remote ZIP (e.g. over FTP) . But ZIP encryption is also 
known to be very weak and can be cracked within some hours computing 
time, at least when every file uses the same password.

Another method would be to produce slice files: Create inremental 
TAR/ZIP archives, encrypt them locally with "gpg -c"  and put them as 
different files. Still a fragile setup, which allows only rough control, 
needs a common archive time stamp (comparing individual file attributes 
is not possible), and needs external tools.

Very nice would be a method which can directly compare agains and update 
a single consistent file like
ftp:///archive.zip.gpg

Is something like this possible?

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


Re: Any python HTML generator libs?

2006-03-10 Thread Matt Goodall
Steve Holden wrote:
> Sullivan WxPyQtKinter wrote:
> 
>>Hi, everyone.  Simply put, what I need most now is a python lib to
>>generate simple HTML.
>>
>>I am now using XML to store my lab report records. I found python
>>really convinient to manipulate XML, so I want to make a small on-line
>>CGI program to help my colleagues to build their lab report records
>>into XML, for storage, HTML display (for others to browse) and search.
>>
>>With python's standard lib, the DOM object could realize the XML
>>storage and search quite easily, but for HTML generation,  it is a
>>great headache.
>>
>>I tried to turn to the in-line server-side python script PSP(something
>>like asp and php) instead of CGI. However, since the report data is
>>always of very complex data structures, it is really hard to write most
>>things in-line. For example, a PCR reaction is expected to be shown in
>>this format or alike on a web browser:
>>
>>PCR
>>Sample: Sm1032
>>Operater: SullivanZ
>>TimeStamp: hh:mm mm-dd-
>>Reaction:
>>   Reagent1:
>> Name:
>> Concentration: mM
>> Volumn:XXX uL
>>   Reagent2:
>>
>>
>>
>>Since there are hundreds of PCR reaction and other operations in the
>>lab report, in-line PSP is not a suitable solution. But writing HTML
>>directly with print statement is a great pain.
>>
>>Will XSTL be useful? Is my problem somewho related with XML-SIG?
>>Looking forward to your precious suggestion.
>>
> 
> The triple-quoted string with string substitution is your friend. Try 
> writing something(s) like:
> 
> results = {'secnum': 1, 'type': 'string', 'color': 'blue'}
> 
> print """\
> Section %(secnum)s
> Elements of type %(type)s should be coloured %(color)s
> """ % results

Don't forget that you may need to escape the application's data for
inclusion in HTML:

results = {'secnum': 1, 'type': 'string', 'color': 'blue',
'user':'Matt Goodall <[EMAIL PROTECTED]>'}

print """\
Section %(secnum)s
Elements of type %(type)s should be coloured %(color)s
Contributed by: %(user)s
""" % results

Will print:

Section 1
Elements of type string should be coloured blue
Contributed by: Matt Goodall <[EMAIL PROTECTED]>

The '<' and '>' surrounding my email address breaks the HTML.

To fix that you need to escape results['user'] with cgi.escape or
xml.sax.saxutils.escape. Oh, and don't forget to escape anything
destined for an HTML attribute differently, see sax.saxutils.quoteattr.

A triple-quoted string is beautifully simple but it's not quite as much
a friend as it might initially seem. ;-)

I don't intend to get into a XML- vs text- based templating flame war
;-) but, IMHO, the solution is to use a templating language that
understands where the value is used in the template.

Kid is a great example of an XML-based templating language but there are
many others. Some have probably been mentioned in this thread already.

Another interesting solutions is to use something like Nevow's tags module:

from nevow import flat, tags as T

results = {'secnum': 1, 'type': 'string', 'color': 'blue',
'user':'Matt Goodall <[EMAIL PROTECTED]>'}

doc = T.div[
T.h1['Section ', results['secnum']],
T.p['Elements of type ', results['type'],
' should be coloured ', results['color']],
T.p['Contributed by: ', results['user']],
]

print flat.flatten(doc)

This time you get valid HTML with no effort whatsoever:

Section 1Elements of type string should be coloured
blueContributed by: Matt Goodall
<[EMAIL PROTECTED]>

You even get to write HTML in a slightly more Pythonic way (even if it
does abuse Python just a little :wink:), but Nevow will happily load a
template containing actual XHTML from disk if you prefer.

The only real "problem" using Nevow for this is that you will need to
install Twisted too. I suspect you'll find a couple of Nevow tag
implementations that don't need Twisted if you ask Google.

Anyway! This was just to demonstrate an alternate approach than to
evangelise about Nevow. I hope it was at least interesting. :)

Cheers, Matt

Nevow:
http://divmod.org/trac/wiki/DivmodNevow
Twisted:
http://twistedmatrix.com/trac

-- 
 __
/  \__ Matt Goodall, Pollenation Internet Ltd
\__/  \w: http://www.pollenation.net
  __/  \__/e: [EMAIL PROTECTED]
 /  \__/  \t: +44 (0)113 2252500
 \__/  \__/
 /  \  Any views expressed are my own and do not necessarily
 \__/  reflect the views of my employer.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why python doesn't use syntax like function(, , x) for default parameters?

2006-03-10 Thread Roy Smith
In article <[EMAIL PROTECTED]>,
 Antoon Pardon <[EMAIL PROTECTED]> wrote:

> Op 2006-03-10, Roy Smith schreef <[EMAIL PROTECTED]>:
> > "Dmitry Anikin" <[EMAIL PROTECTED]> wrote:
> >> There are often situations when a function has independent
> >> parameters, all having reasonable defaults, and I want to
> >> provide just several of them. In fact, I can do it using
> >> keyword parameters, but it's rather long and you have to
> >> remember/lookup names of parameters.
> >
> > Specifying the names of the keyword parameters costs you a little typing 
> > once, but saves everybody (including yourself) a lot of grief later when 
> > you're trying to figure out what the heck your code does 6 months later.
> 
> Could you explain what is so hard in figuring out:
> 
>   func(,,4)

Because while I probably remember what func does (especially if it's well 
named), it's less likely that I remember all the arguments it takes, and 
even less that I remember what order they come in.

Let's say I've got a function which makes a network connection.  It takes 
optional arguments for a port number to connect to, a timeout (in seconds) 
and a buffer size (in kbytes) to use.  If we used your syntax, what does 
"connect (,,20)" mean?  You have to go look up the definition of the 
function to find out, don't you?  But, if I wrote "connect (port=20)", it's 
obvious to anybody reading the code what the 20 is.
-- 
http://mail.python.org/mailman/listinfo/python-list


Does -U option really exist?

2006-03-10 Thread Petr Prikryl
"Martin v. Löwis" once (20 Sep 2005) wrote in reply 
to my question... 

Simpler transition to PEP 3000 "Unicode only strings"?

> As for dropping the u prefix on string literals: 
> Just try the -U option of the interpreter some time,
> which makes all string literals Unicode. If you manage 
> to get the standard library working this way, you 
> won't need a per-file decision anymore: just start 
> your program with 'python -U'. 

I have failed to find the -U option in Python 2.4.2.
Is it something under development?

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


Re: import and shared global variables

2006-03-10 Thread Tim Hochberg
Michael Brenner wrote:
> Hi,
> 
> I'm implementing a plugin-based program, structured like the example 
> below (where m1 in the main module, loading m2 as a plugin).  I wanted 
> to use a single global variable (m1.glob in the example) to store some 
> config data that the plugins can access.  However, the output shown 
> belown seems to imply that glob is *copied* or recreated during the 
> import in m2.  Am I missing something? I thought m1 should be in 
> sys.modules and not be recreated during the import in m2.
> 
> After browsing c.l.p, it seems that this is probably somehow due to the 
> circular import.  However, I do not really see why this should be a 
> problem here.  Interestingly, the problem disappears when I put the code 
> in m1 in a real main() function instead of "if __name__" etc.  Though 
> this seems to solve my problem, I still want to understand what's 

What happens here is that there does end up being two copies of m1: the 
one named __main__ and the one imported as m1. If you think about this, 
there has to be two copies -- otherwise how could sometimes __name__ be 
__main__ and sometimes not.

Anyway, there are several options. The simplest one here is not to 
modify anything locally from __main__ block. Instead import m1, and 
modify that copy. That is:

glob = [1]
if __name__ == "__main__":
  import m1
  m1.glob.append(2)
  print "m1.main().1:", m1.glob
  m2 = __import__("m2")
  m2.test()
  print "m1.main().2:", glob


Regards,

-tim


> happening.
> 
> Thanks,
> 
>   michael
> 
> 
> m1.py:
> --
> glob = [1]
> if __name__ == "__main__":
>  glob.append(2)
>  print "m1.main().1:", glob
>  m2 = __import__("m2")
>  m2.test()
>  print "m1.main().2:", glob
> --
> 
> m2.py:
> --
> def test():
>  import m1
>  print "m2.test():", m1.glob
> -
> 
> Output:
> m1.main().1: [1, 2]
> m2.test(): [1]
> m1.main().2: [1, 2]

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


File Permissions

2006-03-10 Thread VJ
Hi All

I need to get the user permission of a file using python. I was trying
the following code which i found on google grups

 st = os.stat(myfile)
mode = st[stat.ST_MODE]
if mode & stat.ST_IREAD:
print "readable"
if mode & stat.ST_IWRITE:
print "writable"
if mode & stat.ST_IEXEC:
print "executable"

I am getting a error saying

" Traceback (most recent call last):
  File "./test.py", line 23, in ?
if mode & stat.ST_IREAD:
AttributeError: 'module' object has no attribute 'ST_IREAD' "

any idea how to resolve this error ??

Basically i want to write into a file .If the permissions are not there
then print a error message.
How do i achive this ???

Thanks,
VJ

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


Re: import and shared global variables

2006-03-10 Thread Diez B. Roggisch
> I'm implementing a plugin-based program, structured like the example
> below (where m1 in the main module, loading m2 as a plugin).  I wanted
> to use a single global variable (m1.glob in the example) to store some
> config data that the plugins can access.  However, the output shown
> belown seems to imply that glob is *copied* or recreated during the
> import in m2.  Am I missing something? I thought m1 should be in
> sys.modules and not be recreated during the import in m2.

Yes, you are missing that your first glob is in __main__.glob, _not_ in
m1.glob.

To make that happen, use something like this:

glob = [1]
def main():
   pass

if __name__ == "__main__":
import m1
m1.main()


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


Re: File Permissions

2006-03-10 Thread Sebastjan Trepca
Those constants are in stat module so add "import stat" before the program.

On 10 Mar 2006 06:20:18 -0800, VJ <[EMAIL PROTECTED]> wrote:
> Hi All
>
> I need to get the user permission of a file using python. I was trying
> the following code which i found on google grups
>
>  st = os.stat(myfile)
> mode = st[stat.ST_MODE]
> if mode & stat.ST_IREAD:
> print "readable"
> if mode & stat.ST_IWRITE:
> print "writable"
> if mode & stat.ST_IEXEC:
> print "executable"
>
> I am getting a error saying
>
> " Traceback (most recent call last):
>   File "./test.py", line 23, in ?
> if mode & stat.ST_IREAD:
> AttributeError: 'module' object has no attribute 'ST_IREAD' "
>
> any idea how to resolve this error ??
>
> Basically i want to write into a file .If the permissions are not there
> then print a error message.
> How do i achive this ???
>
> Thanks,
> VJ
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why python doesn't use syntax like function(,,x) for default parameters?

2006-03-10 Thread Juho Schultz
Antoon Pardon wrote:
> Op 2006-03-10, Roy Smith schreef <[EMAIL PROTECTED]>:
> 
>>"Dmitry Anikin" <[EMAIL PROTECTED]> wrote:
>>
>>>There are often situations when a function has independent
>>>parameters, all having reasonable defaults, and I want to
>>>provide just several of them. In fact, I can do it using
>>>keyword parameters, but it's rather long and you have to
>>>remember/lookup names of parameters.
>>
>>Specifying the names of the keyword parameters costs you a little typing 
>>once, but saves everybody (including yourself) a lot of grief later when 
>>you're trying to figure out what the heck your code does 6 months later.
> 
> 
> Could you explain what is so hard in figuring out:
> 
>   func(,,4)
> 

Your func has only three parameters, and only one non-default.
I think "all have reasonable defaults, I want to provide several"
means you might end up with bugs like this.

func(,,,1.2e-3,7.6e18,3.124576,3567.0,)
func(,,1.24e3,1,21.26e4,,,1220,57,35,0) # bug
TypeError: func() takes exactly 8 arguments (9 given)

Now what are the correct arguments?
1220.57, 35,and 0
1220,57.35, and 0
1220,57,and 35.0

With keywords parameters, this is easy to answer.

func(y=1.2e-3, z=7.6e18, i=3.124576, j=3567.0)
func(x=1.24e3, y=1, z=21.26e4, j=1220, k=57,35, w=0) # bug

SyntaxError: non-keyword arg after keyword arg.
-- 
http://mail.python.org/mailman/listinfo/python-list


Python and C

2006-03-10 Thread diffuser78
I was a C Programmer for a while. Lately started to learn Python for
one small project at school. I joined a small company where they use
C++ for development.

Can we use Python and C together ? I mean create some classes in Python
and some number crunching algorithms coded in C (for speed) and
integreate both of them.

Could somebody just show a real small example or give pointers to the
same.

Thanks

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


Re: File Permissions

2006-03-10 Thread Sybren Stuvel
VJ enlightened us with:
> Basically i want to write into a file .If the permissions are not
> there then print a error message.  How do i achive this ???

f = file('somefile', 'w')

then catch the exception that's thrown when it can't be done.

Sybren
-- 
The problem with the world is stupidity. Not saying there should be a
capital punishment for stupidity, but why don't we just take the
safety labels off of everything and let the problem solve itself? 
 Frank Zappa
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: creating an executable?

2006-03-10 Thread Larry Bates
John Salerno wrote:
> Well, now that I can time my laundry, I need to make it runnable. I
> tried looking for info on the freeze module in the help file, but it
> didn't seem to come up with much. According to the Python wiki, freeze
> is for making executables for Unix.
> 
> Can I make an executable with just the standard distribution, or do I
> need a separate module?
> 
> Thanks.

You didn't ask about an installer, but I thought I'd make the suggestion
anyway.  The combination of py2exe and Inno Installer works EXTREMELY
well for distributing software on Windows platform.  Use py2exe to
create .exe and support files, use Inno to wrap it up into a neat single
setup.exe file for distribution.

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


Re: Python and C

2006-03-10 Thread Diez B. Roggisch
[EMAIL PROTECTED] wrote:

> I was a C Programmer for a while. Lately started to learn Python for
> one small project at school. I joined a small company where they use
> C++ for development.
> 
> Can we use Python and C together ? I mean create some classes in Python
> and some number crunching algorithms coded in C (for speed) and
> integreate both of them.
> 
> Could somebody just show a real small example or give pointers to the
> same.

There is even a whole section  in the documentation geared towards that -
and to spoil the fun of actually reading it: Yes, Python and C go aleong
_very_ well, and for C++ there are several specialized wrapping generators
that e.g. make PyQt go round. Check out SIP or boost.python or SWIG.

http://docs.python.org/api/api.html

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


Re: Python and C

2006-03-10 Thread Diez B. Roggisch
> http://docs.python.org/api/api.html


That should have been

http://docs.python.org/ext/ext.html

but you need the other one sooner or later.

Diez

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


Re: processing the genetic code with python?

2006-03-10 Thread brainy_muppet


>
> I'm writing your name down and this is the last time I'm doing homework
> for you.
>
> James
>
>

Wow, you are really a pretentious asshole. If you don't want to provide
people with help, don't bother. 

And that code's incorrect anyway.

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


Numbers in python

2006-03-10 Thread brainy_muppet
Basically, I have a code with is almost finished but I've having
difficultly with the last stage of the process. I have a program that
gets assigns different words with a different value via looking them up
in a dictionary:

eg if THE is in the writing, it assigns 0.965

 and once the whole passage is read it returns all the numbers in the
format as follows:

['0.965', '1.000', '0.291', '1.000', '0.503']

However, I can't seem to get the program to treat the numbers as
numbers. If I put them in the dictionary as 'THE' = int(0.965) the
program returns 1.0 and if I put 'THE' = float(0.965) it returns
0.9655549 or something similar. Neither of these are right! I
basically need to access each item in the string as a number, because
for my last function I want to multiply them all together by each
other.

I have tried two bits of code for this last bit, but neither are
working (I'm not sure about the first one but the second one should
work I think if I could figure out how to return the values as
numbers):

1st code
value = codons[x] * codons[x+1]
x = (int)
x = 0

print value

x +=2

if (xhttp://mail.python.org/mailman/listinfo/python-list


Re: Password entering system

2006-03-10 Thread Tuvas
I actually decided to write my own, the thing I needed to know was the
show option to entry. That was the key!

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


Re: File Permissions

2006-03-10 Thread Juho Schultz
VJ wrote:
> Hi All
> 
> Basically i want to write into a file .If the permissions are not there
> then print a error message.
> How do i achive this ???
> 
> Thanks,
> VJ
> 

One way would be a try-except block, and leave the permission checking 
error message generation, etc. to the operating system.

try:
 outfile = file(outfilename,"w")
except IOError, errormsg
 print "Could not write to file %s: %s" % (outfilename, errormsg)

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


Re: Adding Multiple Attachments to SMTP mail (msg.add_header)

2006-03-10 Thread Larry Bates
EdWhyatt wrote:
> Hi all, I hope there is someone out there who can help me out - it has
> to be something obvious.
> 
> I am simulating mail traffic, and want to include multiple attachments
> to my mail. I have created a temporary array containing a number of
> files - for now just 2.
> 
> Debugging my code, I can see that I am correctly storing the files in
> the array, and then 1 by 1 adding one file at a time to the message
> header.
> 
> When the program is complete, the resultant mail has 2 attachments, as
> hoped. However, it is the second file attached twice, rather than the
> two unique files.
> 
> I attach my code for passing the information to  msg.add_header:
> 
> (AttNum = 2)
> 
> for doatt in range(AttNum):
> msg.add_header('Content-Disposition', 'attachment',
> filename=ATTselection[doatt])
> doatt = doatt + 1
> outer.attach(msg)
> 
> ..
> body = MIMEText(Text)
> outer.attach(body)
> 
> Like I said, it is correctly sending the 2 seperate files from my
> ATTselection array, but ultimately attaching the last file twice.
> 
> If anyone can help/suggest something please please let me know!
> 
> Thanks,
> Ed
> 

Take a look at the following:

http://motion.sourceforge.net/related/send_jpg.py

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52243

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


why use special config formats?

2006-03-10 Thread tomerfiliba
hey

i've been seeing lots of config-file-readers for python. be it
ConfigObj (http://www.voidspace.org.uk/python/configobj.html) or the
like. seems like a trend to me.
i came to this conclusion a long time ago: YOU DON'T NEED CONFIG FILES
FOR PYTHON. why re-invent stuff and parse text by yourself, why the
interpreter can do it for you? and anyway, i find this a very ugly
format:
http://www.voidspace.org.uk/python/configobj.html#the-config-file-format

there are two use cases for configuration: static vs. dynamic
configuration.

for the most common case, static configuration, you just have a
human-edited config file holding key-and-value pairs. so just add to
your package a file called config.py, and import it.

for example, if that's our package structure:
PyApache/
__init__.py
config.py
server.py

then server.py would do:
...
import config
listener_sock.bind((config.host, config.port))
...

and config.py would look like:
# the port to bind to
port = 80
host = "localhost"
timeout  = 300
enable_keep_alives = False
options = [1, 2, 3]
...

isn't python suitable enough to hold your configuration?

the second case, dynamic configuration, is when you need to alter your
configuration at runtime or programatically, so the configuration
doesnt need to be human-readable. for that case -- use pickle. and
Bunch (as shown on the aspn python cookbook)

class Bunch(object):
def __init__(self, **kw):
 self.__dict__.update(kw)

create the initial config file:
config = Bunch(port = 80, host = "localhost", timeout = 300, ...)
pickle.dump(open("config.pkl", "wb"), config)

of course you can nest Bunch'es inside one another, i.e.,
config = Bunch(
# global config
port = 80,
host = "localhost",

# this is per-user configuration
users = {
"malcom_x" : Bunch(
http_path = "/home/joe/httpdocs",
cgi_path = "/home/joe/cgi-bin",
options = ["i love lucy", "bush is gay"]
),
...
 },
 ...
)

and now you use it:
# global configuration
config = pickle.load(open("config.pkl"))
listener_sock.bind((config.host, config.port))
# and per-user configuration
from getpass import getuser
print config.users[getuser()].http_path
...

that way, if you need to programatically change your configuration,
just change and pickle.dump() it. 

hope it helps,
-tomer

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


Re: Numbers in python

2006-03-10 Thread Diez B. Roggisch
> However, I can't seem to get the program to treat the numbers as
> numbers. If I put them in the dictionary as 'THE' = int(0.965) the
> program returns 1.0

It certainoly does _not_ return 1.0 - it returns 1. And that is all it can
return for being an integer that has by definition no fractional part.

> and if I put 'THE' = float(0.965) it returns 
> 0.9655549 or something similar. Neither of these are right! I
> basically need to access each item in the string as a number, because
> for my last function I want to multiply them all together by each
> other.

It _is_ the right number if you use floats - you just have to take into
account that 10-based fractions can't always be represented properly by
2-based IEEE floating points, resulting in rounding errors. Which is what
you see.

http://wiki.python.org/moin/RepresentationError?highlight=%28float%29

Either you don't care about the minor differences, the use float. Or you do,
then use the decimal-class introduced in python 2.4

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


Re: File Permissions

2006-03-10 Thread Sybren Stuvel
Sebastjan Trepca enlightened us with:
> Those constants are in stat module so add "import stat" before the
> program.

Yeah, but just opening the file is more Pythonic than first checking
if it can be opened in the first place.

Sybren
-- 
The problem with the world is stupidity. Not saying there should be a
capital punishment for stupidity, but why don't we just take the
safety labels off of everything and let the problem solve itself? 
 Frank Zappa
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Which GUI toolkit is THE best?

2006-03-10 Thread Thomas Guettler
Am Fri, 10 Mar 2006 13:36:18 +0100 schrieb invitro81:

> Hello
> 
> I've recently learnt python and I do love it! I congratulate all those 
> geeks who produce this nice language; well, because I could be called a 
> nearby newbee I've decided to improve my abilities by writing my own 
> nice editor with python; so I've to choose among all those GUI toolkit's 
> available there..
>
> But I've no idea which one I should use to start with.. I've read that 
> tkinter seems to be the de facto standart in the pyhon community; but 
> why?

No, tkinter is not the standard. It is justed part of the standard
library.

Here is what I think:

tkinter (or better TK) has no good table widget.

The licence for QT is GPL, this means you cannot use it in commercial
application. That is why I never looked at it.

wx is better than tkinter. But it is big and there are too many
layers: WxPython -> WxWidgets -> gtk 
I tried some examples, but it didn't "feel" good.

Now I use pygtk. I code everything, I don't used glade or something
like this.

 HTH,
   Thomas

-- 
Thomas Güttler, http://www.thomas-guettler.de/
E-Mail: guettli (*) thomas-guettler + de
Spam Catcher: [EMAIL PROTECTED]

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


Re: Numbers in python

2006-03-10 Thread Duncan Booth
 wrote:

> If I put them in the dictionary as 'THE' = int(0.965) the
> program returns 1.0 and if I put 'THE' = float(0.965) it returns
> 0.9655549 or something similar. Neither of these are right!

Your system seems to be really screwed. int(0.965) should be 0, and 
float(0.965) should be 0.96497 or something similar.

Read
http://www.python.org/doc/faq/general/#why-are-floating-point-calculations-so-inaccurate

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


Re: why use special config formats?

2006-03-10 Thread tomerfiliba
and just as i was writing, this was added to lang.python.announce:

http://groups.google.com/group/comp.lang.python.announce/browse_thread/thread/7a6cbcd8070627a0/24a7b35599f65794#24a7b35599f65794

-tomer

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


Re: Numbers in python

2006-03-10 Thread Fredrik Lundh
[EMAIL PROTECTED] wrote:

> Basically, I have a code with is almost finished but I've having
> difficultly with the last stage of the process. I have a program that
> gets assigns different words with a different value via looking them up
> in a dictionary:
>
> eg if THE is in the writing, it assigns 0.965
>
> and once the whole passage is read it returns all the numbers in the
> format as follows:
>
> ['0.965', '1.000', '0.291', '1.000', '0.503']
>
> However, I can't seem to get the program to treat the numbers as
> numbers. If I put them in the dictionary as 'THE' = int(0.965) the
> program returns 1.0 and if I put 'THE' = float(0.965) it returns
> 0.9655549 or something similar. Neither of these are right!

int(0.965) is 0 and int("0.965") is an error, so I'm not sure what you
did to get 1.0.

but 0.965 and 0.96497 is indeed the same thing, when
stored as binary floating point numbers:

>>> 0.965
0.96497
>>> 0.965 == 0.96497
True

for an explanation, see this page:

http://docs.python.org/tut/node16.html

in your case, explicitly formatting the numbers on the way might be good
enough, e.g.

print "%.3f" % value

for details, see:

http://docs.python.org/lib/typesseq-strings

if you really need support for decimal floating point arithmetics, see:

http://docs.python.org/lib/module-decimal.html

 



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


Re: is there any overheard with try/except statements?

2006-03-10 Thread Magnus Lycka
John Salerno wrote:
> Thanks guys! I had a feeling exceptions were nothing like in C languages 
> (i.e. a pain to deal with).  :)

Since when does C have exceptions? (You're not confusing C with C++
or C#?)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: is there any overheard with try/except statements?

2006-03-10 Thread Magnus Lycka
John Salerno wrote:
> One of the things I learned with C# is that it's always better to handle 
> any errors that might occur within the codes itself (i.e. using if 
> statements, etc. to catch potential out of range indexing) rather than 
> use too many try/catch statements, because there is some overhead every 
> time the program encounters the try.

"Premature optimization is the root of all evil (or at least most of
it) in programming."
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A better RE?

2006-03-10 Thread Magnus Lycka
Schüle Daniel wrote:
>  >>> txt = "21MAR06 31APR06 1236"
> 
>  >>> m = '(?:JAN|FEB|MAR|APR|MAI|JUN|JUL|AUG|SEP|OCT|NOV|DEZ)'
> # non capturing group (:?)
> 
>  >>> p = re.compile(r"(\d\d%s\d\d) (\d\d%s\d\d) 
> (?=[1234567])(1?2?3?4?5?6?7?)" % (m,m))
> 
>  >>> p.match(txt).group(1)
> '21MAR06'
> 
>  >>> p.match(txt).group(2)
> '31APR06'
> 
>  >>> p.match(txt).group(3)
> 1236
> 

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


Re: A better RE?

2006-03-10 Thread Magnus Lycka
Fredrik Lundh wrote:
> Magnus Lycka wrote:
> r"(\d\d[A-Z]{3}\d\d) (\d\d[A-Z]{3}\d\d)  (?=[1234567])(1?2?3?4?5?6?7?)"
> 

Thanks a lot. (I knew about {3} of course, I was in a hurry
when I posted since I was close to missing my train...)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Numbers in python

2006-03-10 Thread brainy_muppet
'It certainoly does _not_ return 1.0 - it returns 1. And that is all it
can
return for being an integer that has by definition no fractional part.
'

For goodness sake, it was a typo, I'm so sorry!

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


Re: Numbers in python

2006-03-10 Thread Diez B. Roggisch
> It certainoly does _not_ return 1.0 - it returns 1. And that is all it can
> return for being an integer that has by definition no fractional part.

Duncan was right of course. It returns 0.

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


Re: why use special config formats?

2006-03-10 Thread Sybren Stuvel
[EMAIL PROTECTED] enlightened us with:
> i came to this conclusion a long time ago: YOU DON'T NEED CONFIG
> FILES FOR PYTHON. why re-invent stuff and parse text by yourself,
> why the interpreter can do it for you?

Because you generally don't want to give the configuration file writer
full control over the Python virtual machine.

> for the most common case, static configuration, you just have a
> human-edited config file holding key-and-value pairs. so just add to
> your package a file called config.py, and import it.

Which only works if there is only one configuration file per
installation of your package, and is writable by the users that need
to configure it. For example, per-user database connection parameters
should be in $HOME/.programrc on UNIX systems. A program's preference
settings should be stored in a user-writable file to, preferably in
the user's homedir.

Sybren
-- 
The problem with the world is stupidity. Not saying there should be a
capital punishment for stupidity, but why don't we just take the
safety labels off of everything and let the problem solve itself? 
 Frank Zappa
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Numbers in python

2006-03-10 Thread brainy_muppet
'It certainoly does _not_ return 1.0 - it returns 1. And that is all it
can
return for being an integer that has by definition no fractional part.
'

For goodness sake, it was a typo, I'm so sorry!

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


Re: import and shared global variables

2006-03-10 Thread Michael Brenner
Ah, thanks everybody! I had thought that, although the name was set to 
"__main__", the module that was stored in sys.modules was m1 
nevertheless, not a copy.
Well, having to write "import m1" inside m1.py seems a bit peculiar - 
it's probably nicer to keep the "__main__" module free from stuff that 
has to be imported by others.  Would a module global.py (defining glob 
and imported by whoever needs it) be more pythonic? (I didn't want to do 
that because I really want to resist the temptation of introducing 
glob1, glob2, glob3...)

michael



> To make that happen, use something like this:
> 
> glob = [1]
> def main():
>pass
> 
> if __name__ == "__main__":
> import m1
> m1.main()
> 
> 
> Diez

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


Performance impact of using decorators

2006-03-10 Thread vinjvinj
I'm building an application with cherrypy and have started using
decorators quite extensively. A lot of my exposed functions look like:

@expose
@startTransactrionAndBuildPage
@partOfTabUi(tabId)
@convert(arg1=int, arg2=str)
def do_main_page(self, arg1, arg2):
   some code


I've become really fond of decorators and use them quite a lot. I've
also ready that function calls are expensive in python. In the above
example, does the interpreter call 5 different functions?

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


Re: Which GUI toolkit is THE best?

2006-03-10 Thread Sybren Stuvel
Thomas Guettler enlightened us with:
> The licence for QT is GPL, this means you cannot use it in
> commercial application. That is why I never looked at it.

Ehmm... from their website:

The Qt Commercial License is the correct license to use for the
construction of proprietary, commercial software. The license allows
you to:
- Build commercial software and software whose source code you
  wish to keep private.
- Freely choose licensing for the software you are writing
  (Proprietary, Open Source or both).
- Be able to gain access to Qt Solutions, Trolltech support and
  commercial-only Qt components such as commercial database
  drivers and the Visual Studio Integration on Windows. 

Sybren
-- 
The problem with the world is stupidity. Not saying there should be a
capital punishment for stupidity, but why don't we just take the
safety labels off of everything and let the problem solve itself? 
 Frank Zappa
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Numbers in python

2006-03-10 Thread Sybren Stuvel
[EMAIL PROTECTED] enlightened us with:
> if I put 'THE' = float(0.965) it returns 0.9655549 or something
> similar.

That's for the same reasons as you can't write 1/3rd in decimal
notation. Computers can't write 1/10th in binary notation.

Sybren
-- 
The problem with the world is stupidity. Not saying there should be a
capital punishment for stupidity, but why don't we just take the
safety labels off of everything and let the problem solve itself? 
 Frank Zappa
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: is there any overheard with try/except statements?

2006-03-10 Thread John Salerno
Magnus Lycka wrote:
> John Salerno wrote:
>> Thanks guys! I had a feeling exceptions were nothing like in C 
>> languages (i.e. a pain to deal with).  :)
> 
> Since when does C have exceptions? (You're not confusing C with C++
> or C#?)

I meant C-based languages, like C#.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Performance impact of using decorators

2006-03-10 Thread Alex Martelli
vinjvinj <[EMAIL PROTECTED]> wrote:

> I'm building an application with cherrypy and have started using
> decorators quite extensively. A lot of my exposed functions look like:
> 
> @expose
> @startTransactrionAndBuildPage
> @partOfTabUi(tabId)
> @convert(arg1=int, arg2=str)
> def do_main_page(self, arg1, arg2):
>some code
> 
> I've become really fond of decorators and use them quite a lot. I've
> also ready that function calls are expensive in python. In the above
> example, does the interpreter call 5 different functions?

At def-execution time, presumably 6 (the two decorators w/o args, plus 2
each for those w/args); at call time, it depends what the decorators are
doing (if each adds exactly one wrapping closure, for example, there
will indeed be 5 nested calls). Unfortunately I do not know much of
today's cherrypy internals, so I don't know what each decorator is doing
internally.


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


Re: why use special config formats?

2006-03-10 Thread tomerfiliba
if you are really so scared of letting others exploit your config
scripts, then use the second, pickled fashion. that way you can store
the file at $HOME/blah-config.pkl, and everybody's happy.

still, my point is we dont need special config mechanisms, since the
builtin ones, like object persistency (sp) or python scripts are good
enough, less buggy, and dont require you to learn thousands of config
formats.

and you can even edit pickled files by hand (protocol 0 i believe).
it's not that complicated.


-tomer

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


Re: Why python doesn't use syntax like function(, , x) for default parameters?

2006-03-10 Thread Antoon Pardon
Op 2006-03-10, Diez B. Roggisch schreef <[EMAIL PROTECTED]>:
> Antoon Pardon wrote:
>
>>>
>>> Specifying the names of the keyword parameters costs you a little typing
>>> once, but saves everybody (including yourself) a lot of grief later when
>>> you're trying to figure out what the heck your code does 6 months later.
>> 
>> Could you explain what is so hard in figuring out:
>> 
>>   func(,,4)
>> 
>> We sure don't seem to have a problem with figuring out things like
>> 
>>   lst[::2]
>
> That is the usual polemics. Its a HUGE difference if I'm supposed to
> remember 2 default values that are 0 and , in a
> specialized syntax,

Those default values are not 0 and , you may have
only experience with situations where they behave as such but that
is not the same.

> than arbitrary values
> f(,3)
>
> in some arbitrary function. 

If you need to know these values then you will need to know them
just as much when a keyword is used or when the default values
are used later. Calling

  f(3) or f(arg5=3)

Will give you no more a clue about the missing default values
than calling

  f(,3)

At least in the last call you are given a clue about missing
arguments.

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


Re: Why python doesn't use syntax like function(, , x) for default parameters?

2006-03-10 Thread Antoon Pardon
Op 2006-03-10, Roy Smith schreef <[EMAIL PROTECTED]>:
> In article <[EMAIL PROTECTED]>,
>  Antoon Pardon <[EMAIL PROTECTED]> wrote:
>
>> Op 2006-03-10, Roy Smith schreef <[EMAIL PROTECTED]>:
>> > "Dmitry Anikin" <[EMAIL PROTECTED]> wrote:
>> >> There are often situations when a function has independent
>> >> parameters, all having reasonable defaults, and I want to
>> >> provide just several of them. In fact, I can do it using
>> >> keyword parameters, but it's rather long and you have to
>> >> remember/lookup names of parameters.
>> >
>> > Specifying the names of the keyword parameters costs you a little typing 
>> > once, but saves everybody (including yourself) a lot of grief later when 
>> > you're trying to figure out what the heck your code does 6 months later.
>> 
>> Could you explain what is so hard in figuring out:
>> 
>>   func(,,4)
>
> Because while I probably remember what func does (especially if it's well 
> named), it's less likely that I remember all the arguments it takes, and 
> even less that I remember what order they come in.

Do you have trouble remembering that range(n) is actually providing the
second parameter to the function and what it does?

> Let's say I've got a function which makes a network connection.  It takes 
> optional arguments for a port number to connect to, a timeout (in seconds) 
> and a buffer size (in kbytes) to use.  If we used your syntax, what does 
> "connect (,,20)" mean?  You have to go look up the definition of the 
> function to find out, don't you?  But, if I wrote "connect (port=20)", it's 
> obvious to anybody reading the code what the 20 is.

I don't consider this an argument. We already have the problem that we
need to figure out what connect(20) means. connect(,,20) will at least
make it clear that some parameters are missing. My syntax doesn't
make it easier to introduce inclarities than python can.

Sure connect(port=20) provides extra clarity, but nobody seems to have
a problem with range(n) where n suddenly is the second parameter and
we use the default for the first. If we want to allow things like that
I would prefer range(,n) that at least makes it clear what is going on.

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


  1   2   3   >