Re: Question about smtplib, and mail servers in general.

2005-09-20 Thread Steve Holden
Peter Hansen wrote:
> Steve Holden wrote:
> 
>>Peter Hansen wrote:
>>
>>>In any case, unless the mail server will allow "relaying", which most 
>>>don't these days (to prevent spamming), then it won't work the way you 
>>>are hoping unless *all* the 100 addresses are local ones, to be 
>>>delivered to users on the server you are sending the mail to.
>>>
>>>If the addresses are scattered all over the planet, and the server 
>>>allows relaying, then it's intended for exactly this sort of use 
>>>(other than if it's spam ;-) ), and no, you won't be putting a "drain" 
>>>on the server.
>>
>>To add one final note, if the "fromaddress" belongs to a domain that's 
>>properly handled by the SMTP server then you aren't relaying (since you 
>>are a legitimate domain user) so the mails should go through.
> 
> 
> I think that statement might not be widely valid any more, Steve.  In my 
> experience, lately, many if not most servers pay no attention to the 
> "MAIL FROM" address but instead allow relaying only from *IP addresses* 
> on the "internal" network (e.g. those served by an ISP, for example), 
> regardless of how the sender is identified.  On a Linux box with Qmail, 
> for example, one would have an /etc/tcp.smtp file which specifies for 
> which subnets relaying is allowed, and all others are disallowed 
> regardless of the claimed MAIL FROM address.
> 
> It's kind of a shame, really, that you can no longer trust either the 
> recipient *or* the sender addresses when using basic SMTP.  Damn spammers.
> 
I agree that there's an element of the moral imperative in my assertion 
that the mails "should" go through which is largely ignored by the real 
world nowadays. Some ISPs force you to use their SMTP servers no matter 
what the sending domain, which is rather annoying when you travel a lot. 
I end up having to vary my default SMTP server as I move.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC www.holdenweb.com
PyCon TX 2006  www.pycon.org

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


Re: print there!

2005-09-20 Thread Steven D'Aprano
On Tue, 20 Sep 2005 14:06:23 +0200, Fredrik Lundh wrote:

> Godwin Burby wrote:
> 
>> print 'c:\godwin\bl.csv',
>> for i,row in enumerate(reader):
>># inserts or updates the database
>>print i,
>> This displays on the screen as :
>> c:\godwin\bl.csv 1 2 3 4 5 6 7 8
>> ^
>> But i want it to show the above numbers on the same spot denoted by the
>> carat character. Can it be done with print statement or any other trick?
> 
> carriage return is your friend:
> 
> filename = 'c:\\godwin\\bl.csv',
> for i,row in enumerate(reader):
> # inserts or updates the database
> print "\r" + filename, i,
> print

That may not be enough. You may need to flush the print buffer using
sys.stout.flush().


-- 
Steven.


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


Re: Question About Logic In Python

2005-09-20 Thread Steven D'Aprano
On Tue, 20 Sep 2005 03:03:15 +, Ron Adam wrote:

> Steven D'Aprano wrote:
>> Are there actually any usage cases for *needing* a Boolean value? Any
>> object can be used for truth testing, eg:

[snip]

> Of course if any of the default False or True conditions are 
> inconsistent with the logic you use, you need to do explicit truth testing.

[snip]

> So..
> 
> bool(a and b) * value
> 
> Would return value or zero, which is usually what I want when I do this 
> type of expression.

That's all very interesting, and valuable advice for somebody who doesn't
understand how Python's logical operators work, but the question is, when
would you actually want that type of expression?

In practice, how often do you really care that your truth values have the
specific values 0 and 1 rather than anything false and anything true? In
what circumstances?



-- 
Steven.

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


Re: Question About Logic In Python

2005-09-20 Thread Steven D'Aprano
On Mon, 19 Sep 2005 22:31:05 +, Bengt Richter wrote:

> On Mon, 19 Sep 2005 23:46:05 +1000, Steven D'Aprano <[EMAIL PROTECTED]> wrote:

>>Are there actually any usage cases for *needing* a Boolean value? Any
>>object can be used for truth testing, eg:

[snip]

> making an index (it's an int subclass), as in
> 
>  >>> things = None, 0, 1, 0.0, 5.0, '', 'a', [], [1], {}, {1:2}
>  >>> for thing in things:
>  ...print 'if %-6r would act like if %s' % (thing, 
> ('False','True')[bool(thing)])
>  ...

That's a pretty artificial example though. Your general index ranges from
0 to n inclusive, where n is unlikely to be 1. That limits the usefulness
of the idiom sequence_or_mapping[bool(thing)] to a tiny set of cases.

As near as I can tell, explicitly converting objects to booleans is mostly
useful for demonstrating that booleans aren't needed for truth testing.


-- 
Steven.

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


Re: slicing functionality for strings / Python suitability forbioinformatics

2005-09-20 Thread Steven D'Aprano
On Mon, 19 Sep 2005 19:40:12 -0700, jbperez808 wrote:

> Having to do an array.array('c',...):
> 
>   >>> x=array.array('c','ATCTGACGTC')
>   >>> x[1:9:2]=array.array('c','')
>   >>> x.tostring()
>   'AACAGACATC'
> 
> is a bit klunkier than one would want, but I guess
> the efficient performance is the silver lining here.

There are a number of ways to streamline that. The simplest is to merely
create an alias to array.array:

from array import array as str

Then you can say x = str('c', 'ATCTGACGTC').

A little more sophisticated would be to use currying:

def str(value):
return array.array('c', value)

x = str('ATCTGACGTC')

although to be frank I'm not sure that something as simple as this
deserves to be dignified with the name currying.


Lastly, you could create a wrapper class that implements everything you
want. For a serious application, this is probably what you want to do
anyway:

class DNA_Sequence:
alphabet = 'ACGT'

def __init__(self, value):
for c in value:
if c not in self.__class__.alphabet:
raise ValueError('Illegal character "%s".' % c)
self.value = array.array('c', value)

def __repr__(self):
return self.value.tostring()

and so on. Obviously you will need more work than this, and it may be
possible to subclass array directly. 


-- 
Steven.

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


webbrowser failing

2005-09-20 Thread Thomas Thomas



Hi All,
 
import 
webbrowserurl=''webbrowser.open(url)
 
giving the error
 
Python 2.3.5 (#62, Feb  8 2005, 16:23:02) [MSC 
v.1200 32 bit (Intel)] on win32Type "help", "copyright", "credits" or 
"license" for more information.>>> ## working on region in file 
c:/DOCUME~1/ADMINI~1/LOCALS~1/Temp/python-1720WXU.py...Traceback (most 
recent call last):  File "", line 1, in ?  File 
"c:/DOCUME~1/ADMINI~1/LOCALS~1/Temp/python-1720WXU.py", line 3, in 
?    webbrowser.open(url)  File 
"C:\Python23\lib\webbrowser.py", line 43, in open    
get().open(url, new, autoraise)  File "C:\Python23\lib\webbrowser.py", 
line 250, in open    os.startfile(url)WindowsError: 
[Errno 2] The system cannot find the file specified: 
'http://www.cnn.com'>>> 
 
any help
Thomas
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: What am i doing Wrong?

2005-09-20 Thread Aldo Cortesi
Thus spake keithlackey ([EMAIL PROTECTED]):

>   class structure:
> def __init__(self, folders = []):
^

Here's your problem. To understand what's going on, you need to know two
things:

- Default arguments are only evaluated ONCE when the
  Python interpreter executes the class definition.
- A list is a mutable object.

So, what's happening is that both your class instances are
getting the _same_ list as a default instantiation argument.
You are modifying the list through the first class instance,
and then seeing the same change when you view the list via the
second class instance.

As a rule of thumb, simply never use a mutable object as a
default argument to a function or method unless you really
know what you're doing, and actually want the behaviour
you're going to get. In your case, you probably want
something like:

def __init__(self, folders = None):
if folders is None:
self.folders = []


Cheers,


Aldo

--
Aldo Cortesi
[EMAIL PROTECTED]
http://www.nullcube.com
Off: (02) 9283 1131
Mob: 0419 492 863
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie Question on ctypes

2005-09-20 Thread Sybren Stuvel
Efrat Regev enlightened us with:
>My question is, therefore, if I can build ctypes locally. I tried
>
> rpm -i python-ctypes-0.9.1-1.rf.src.rpm

That _installs_ the source package, not build it as you intended. Read
the RPM manual:

rpm --rebuild python-ctypes-0.9.1-1.rf.src.rpm

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: What am I doing wrong?

2005-09-20 Thread Sybren Stuvel
keithlackey enlightened us with:
>   def __init__(self, folders = []):
>   self.folders = folders

Read all about this very common mistake at
http://docs.python.org/tut/node6.html#SECTION00671

>   def add_folder(self, folder):
>   self.folders.append(tuple(folder))

The line above has a combination of spaces and tabs. Use either spaces
or tabs, but not both, to indent your code.

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


Newbie Question on ctypes

2005-09-20 Thread Efrat Regev
   Hello,

   (I apologize in advance if I'm posting to the wrong group. If so, 
could you please instruct me which is appropriate?)

   I'm trying to use uTidyLib, HTML-tidy's python binding. When I

import tidy

   Python says it can't import ctypes. Since I'm using FC4, I looked for 
a FC4 ctypes rpm. All I could find, however, were buildlog errors for 
ctypes on FC4.
   My question is, therefore, if I can build ctypes locally. I tried

rpm -i python-ctypes-0.9.1-1.rf.src.rpm

   but that didn't seem to work (python still couldn't import ctypes).

   Thanks in advance for all answers. I should point out that I'm not an 
expert in python or linux (in the combination, alas, even less).

   Thanks,

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


What am i doing Wrong?

2005-09-20 Thread keithlackey








I'm
relatively new to python and I've run into this problem.

 

 

DECLARING
CLASS

 

  class structure:

        def __init__(self, folders = []):    

      self.folders = folders

    

      def add_folder(self, folder):

    self.folders.append(tuple(folder))

 

 

 

Now
I try to make an instance of this class

 

  structure1 = structure()

  structure1.add_folder([('foo'),])

  print
structure1.folders

 

This returns:
[('foo',)]

 

This
works fine. But when I try to make another instance of that class...

 

  structure2 = structure()

  print
structure2.folders

 

This
now also returns: [('foo',)]

Even
though I haven’t added any folders to this new instance

 

What
am I doing wrong?

 

 






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

What am I doing wrong?

2005-09-20 Thread keithlackey
I'm relatively new to python and I've run into this problem.


DECLARING CLASS

class structure:
def __init__(self, folders = []):
self.folders = folders

def add_folder(self, folder):
self.folders.append(tuple(folder))



Now I try to make an instance of this class

structure1 = structure()
structure1.add_folder([('foo'),])
print structure1.folders

This returns: [('foo',)]

This works fine. But when I try to make another instance of that class...

structure2 = structure()
print structure2.folders

This now also returns: [('foo',)]
Even though I haven't added any folders to this new instance

What am I doing wrong?

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


Re: Free seminar on domain-specific modeling

2005-09-20 Thread Martijn Iseger

> Martijn Iseger wrote:
> 
>> Domain-specific modeling makes software development 5-10 times faster
>> than approaches based on UML or MDA. It accelerates development and
>> reduces complexity by automatically generating full code from
>> higher-abstraction design models.
>> 
> Wow, look everyone!  A silver bullet!
> 
Before slashing down in ignorance - educate yourself on www.dsmforum.org. 
After that: feel free to comment. I will make you look a lot more intelligent 
Peter Hansen.


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


Re: print there!

2005-09-20 Thread Godwin Burby
thanks :) It works beautifully.

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


Re: print there!

2005-09-20 Thread Godwin Burby
i think u've misunderstood my question. Your solution will print on a
new line as below:
c:\godwin\bl.csv 1
c:\godwin\bl.csv 2
c:\godwin\bl.csv 3
But i want this number to diplay their value increase on the same line
on the same sport itself without printing the filename multiple times
on multiple lines:
c:\godwin\bl.csv
 ^
If i were to do it in the c language i would use the conio.h and gotxy
function with printf.
printf("c:\\godwin\\bl.csv");
for(i=0;ihttp://mail.python.org/mailman/listinfo/python-list


Re: [python-win32] Getting tired with py2exe

2005-09-20 Thread Garth Johnson
Steve Holden wrote:

>Ignoring all the philosophical questions I'd like to thank you for all 
>your hard work on py2exe over the years, which has benefited the Windows 
>Python community immeasurably.
>
>regards
>  Steve
>  
>
here here!  I have just begun my trek into Python and am already relying 
upon Py2Exe for my projects.  Thank you for an effective, well designed 
tool that is easy to use.  It was one of the final deciding factors in 
our company's choice of languages.  (not the least of which was the ease 
of which our dev team took to Python after pretzling with perl).  I do 
hope you change your mind.

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


PyWeek 1 has completed, winners announced

2005-09-20 Thread richard
The first PyWeek Game Programming Challenge is now finished, and the results
are in: 

I consider it a success, and I'll be running it again. I'll be making some
small changes to the challenge format (mostly to do with the theme
selection) and I'll definitely be providing more information to competitors
next time about how to compete (how to plan, etc).

Phew. And there's some cool games in there too :)

It was interesting to see that the individual entries tended to be more
innovative than the team entries.


Richard

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


Re: re.search experts needed on fqdn stripping..

2005-09-20 Thread Mike Meyer
"rh0dium" <[EMAIL PROTECTED]> writes:
> After thinking about it for a bit longer i simplified it but still have
> the same problem..
>
> e =[]
> hosts = [ "poundcake.fpdn.com", "scorpion.fpdn.com", "loghost",
> "scorpian", "localhost", "lan" ]
>
> ignore = [ "localhost", "loghost", "timehost", "mailhost" ]
>
> for host in hosts:
> sn = re.split( "\.", host)

This should be host.split(".").

> if not sn[0] in ignore:
> e.append(host)
> ignore.append(sn[0])
> print e
>
> But this STILL gives me some problems..
> ['poundcake.nsc.com', 'scorpion.fqdn.com', 'scorpian', 'lan']
>
> Nope - OK I am an idiot - try spelling idiot..

Can I take it that you saw that "scorpion" is not the same as
"scorpian"?

BTW, if you're using 2.4 and don't care about portability, I'd make
ignore a set instead of a list.

 http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: testing a website from python

2005-09-20 Thread matt
Here's something I did recently at work.  (Thought it's testing http
digest authentication, the idea would the same (testNoAuth() is
probably doing what you want)).  It contains unittest code and is using
urllib2.
http://blog.spikesource.com/pyhton_testcases.htm

matt

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


Re: Finding where to store application data portably

2005-09-20 Thread Peter Hansen
Tony Houghton wrote:
> 
> I'm using pygame to write a game called Bombz which needs to save some
> data in a directory associated with it. In Unix/Linux I'd probably use
> "~/.bombz", in Windows something like
> "C:\Documents And Settings\\Applicacation Data\Bombz".
> 
> There are plenty of messages in the archives for this group about how to
> find the correct location in Windows, but what about Mac OS? There I
> don't know the correct location for this sort of thing at all. And there
> are other, more obscure systems like RISC OS (it may not have pygame but
> it definitely has python). Surely this is something that's crying out
> for an official function in os or sys.

Perhaps using "import user; user.home" would be adequate.  Note the 
documented side effects of doing that however.

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


Re: python script under windows

2005-09-20 Thread chanchal
typo, the correct command is:
c:\>python MyService.py -startup=auto install

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


Re: Question about smtplib, and mail servers in general.

2005-09-20 Thread Peter Hansen
Steve Holden wrote:
> Peter Hansen wrote:
>> In any case, unless the mail server will allow "relaying", which most 
>> don't these days (to prevent spamming), then it won't work the way you 
>> are hoping unless *all* the 100 addresses are local ones, to be 
>> delivered to users on the server you are sending the mail to.
>>
>> If the addresses are scattered all over the planet, and the server 
>> allows relaying, then it's intended for exactly this sort of use 
>> (other than if it's spam ;-) ), and no, you won't be putting a "drain" 
>> on the server.
> 
> To add one final note, if the "fromaddress" belongs to a domain that's 
> properly handled by the SMTP server then you aren't relaying (since you 
> are a legitimate domain user) so the mails should go through.

I think that statement might not be widely valid any more, Steve.  In my 
experience, lately, many if not most servers pay no attention to the 
"MAIL FROM" address but instead allow relaying only from *IP addresses* 
on the "internal" network (e.g. those served by an ISP, for example), 
regardless of how the sender is identified.  On a Linux box with Qmail, 
for example, one would have an /etc/tcp.smtp file which specifies for 
which subnets relaying is allowed, and all others are disallowed 
regardless of the claimed MAIL FROM address.

It's kind of a shame, really, that you can no longer trust either the 
recipient *or* the sender addresses when using basic SMTP.  Damn spammers.

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


Re: re.search experts needed on fqdn stripping..

2005-09-20 Thread rh0dium
OK Duh..

After thinking about it for a bit longer i simplified it but still have
the same problem..

e =[]
hosts = [ "poundcake.fpdn.com", "scorpion.fpdn.com", "loghost",
"scorpian", "localhost", "lan" ]

ignore = [ "localhost", "loghost", "timehost", "mailhost" ]

for host in hosts:
sn = re.split( "\.", host)
if not sn[0] in ignore:
e.append(host)
ignore.append(sn[0])
print e

But this STILL gives me some problems..
['poundcake.nsc.com', 'scorpion.fqdn.com', 'scorpian', 'lan']

Nope - OK I am an idiot - try spelling idiot..

Thanks



rh0dium wrote:
> Hi all,
>
> Ok I have a list
>
> hosts = [ "poundcake.fqdn.com", "scorpion.fqdn.com", "loghost",
> "scorpian", "localhost", "lan", "lan.fpdn.com" ]
>
> Assumptions:
> scorpian.fqdn.com == scorpian
> lan == lan.fqdn.com
>
> I want pear this list down based on the following:
> 1.  ignore loghost, localhost, timehost, mailhost
> 2.  Use the first found name used reguardless if it is the fqdn or not
>
> So what you would get back out is this..
>
> hosts = [ "poundcake.fqdn.com", "scorpion.fqdn.com", "lan" ]
>
> Now here is my code - and I have a problem with the splitting.  I am
> really looking for a cool ( but understandable ) way to simplify this..
>
> e =[]
> for host in hosts:
>
> sn = re.split( "\.", host)
>
> ig = 1
> ignore = [ "localhost", "loghost", "timehost", "mailhost" ]
> for i in ignore:
> if i == sn[0]:
> ig = 0
> if ig:
> print "%s not ignored" % sn[0]
> found = 0
> for n in e:
> sm = re.split( "\.", n)
> print "checking %s to %s" % (sm[0], sn[0])
> if sm[0] == sn[0]:
> print "match";
> found = 1
> if found == 0:
> print "appending %s " % host
> e.append(host)
>
> print e
>
>
> Which kicks out..
> poundcake not ignored
> appending poundcake.nsc.com
> scorpion not ignored
> checking poundcake to scorpion
> appending scorpion.nsc.com
> scorpian not ignored
> checking poundcake to scorpian
> checking scorpion to scorpian
> appending scorpian
> lan not ignored
> checking poundcake to lan
> checking scorpion to lan
> checking scorpian to lan
> appending lan
> ['poundcake.fpdn.com', 'scorpion.fpdn.com', 'scorpian', 'lan']
> 
> Crap still wrong.

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


Re: PyInstaller 1.0 - build single-file distributions for your Python programs

2005-09-20 Thread Giovanni Bajo
Giovanni Bajo wrote:

> PyInstaller 1.0 is out:
> http://pyinstaller.hpcf.upr.edu/pyinstaller


For the logs, the correct URL is:
http://pyinstaller.hpcf.upr.edu

The other was a redirector which is no longer valid after a site maintenance
session. I apologize for the inconvenience.
-- 
Giovanni Bajo


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


Re: Getting tired with py2exe

2005-09-20 Thread Giovanni Bajo
Bugs wrote:

> Whereas py2exe can create an executable that NEVER writes any files
> out to the filesystem, they are loaded instead directly from the
> executable?
> If so then that's a major difference and IMHO the py2exe method is
> superior.

To do this, py2exe uses a manually rewritten version of LoadLibrary (the win32
api call in charge of loading DLLs). Since nobody has access to the original
source code of LoadLibrary (across all Windows version), the rewritten version
is by definition incomplete and less stable; it might also be not forward
compatible (that is, your shipped application may break on Windows Vista, or if
you package applications compiled with newer Visual Studio versions).

So it's a trade-off problem. I'm not a fan of writing temporary files to disk,
but surely I prefer this to a potential compatibility headache; an executable
built by PyInstaller will dump some stuff into your temp directory, but it
won't run into compatibility problem when run on that computer or with that
DLL. Anyway, I'm not against adding things to PyInstaller in principle: if
there is enough request for such a feature, we might as well add it.
-- 
Giovanni Bajo


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


re.search experts needed on fqdn stripping..

2005-09-20 Thread rh0dium
Hi all,

Ok I have a list

hosts = [ "poundcake.fqdn.com", "scorpion.fqdn.com", "loghost",
"scorpian", "localhost", "lan", "lan.fpdn.com" ]

Assumptions:
scorpian.fqdn.com == scorpian
lan == lan.fqdn.com

I want pear this list down based on the following:
1.  ignore loghost, localhost, timehost, mailhost
2.  Use the first found name used reguardless if it is the fqdn or not

So what you would get back out is this..

hosts = [ "poundcake.fqdn.com", "scorpion.fqdn.com", "lan" ]

Now here is my code - and I have a problem with the splitting.  I am
really looking for a cool ( but understandable ) way to simplify this..

e =[]
for host in hosts:

sn = re.split( "\.", host)

ig = 1
ignore = [ "localhost", "loghost", "timehost", "mailhost" ]
for i in ignore:
if i == sn[0]:
ig = 0
if ig:
print "%s not ignored" % sn[0]
found = 0
for n in e:
sm = re.split( "\.", n)
print "checking %s to %s" % (sm[0], sn[0])
if sm[0] == sn[0]:
print "match";
found = 1
if found == 0:
print "appending %s " % host
e.append(host)

print e


Which kicks out..
poundcake not ignored
appending poundcake.nsc.com
scorpion not ignored
checking poundcake to scorpion
appending scorpion.nsc.com
scorpian not ignored
checking poundcake to scorpian
checking scorpion to scorpian
appending scorpian
lan not ignored
checking poundcake to lan
checking scorpion to lan
checking scorpian to lan
appending lan
['poundcake.fpdn.com', 'scorpion.fpdn.com', 'scorpian', 'lan']

Crap still wrong..

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


Re: Getting tired with py2exe

2005-09-20 Thread Giovanni Bajo
Simon John wrote:

> And if they want to use UPX, well that's up to them, but I've had some
> problems with it and don't particularly like the thought of runtime
> decompression and the two process thing.

UPX compression is totally optional, and it is even disabled by default. For
the log, I have been using UPX for many, many years and never had a problem
whatsoever, but surely there had been bugs.

Nonetheless, if you are so worried about it, I wonder how you can feel
comfortable with py2exe loading up DLLs with his own version of LoadLibrary. It
looks like potentially much more dangerous to me. Or maybe you never build
single-file distributions and you go with single-dir distributions... in which
case there is no "two process" thing.

> And when you can compress the
> distributable using 7zip or whatever, why bother keeping it compressed
> once downloaded?

Some people like the idea of "absolutely no installation process needed".
-- 
Giovanni Bajo


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


Re: Getting tired with py2exe

2005-09-20 Thread Giovanni Bajo
James Stroud wrote:

>> What about PyInstaller that was announced the other day? The feature
>> list looks great, and it appears the developers intend to maintain
>> and enhance the program indefinitely.
> ...
>>
>> http://pyinstaller.hpcf.upr.edu/pyinstaller
>
> That's one short "indefinitely":
>
> Not Found
> The requested URL /pyinstaller was not found on this server.
> Apache/2.0.53 (Fedora) Server at pyinstaller.hpcf.upr.edu Port 80

Yes, we had a short offline period today due to maintenance on the server,
sorry for that.
-- 
Giovanni Bajo


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


Re: are variables local only to try/except blocks?

2005-09-20 Thread Barry Searle

in the case of nested try/except code
generation, 
your suggestion could cause a problem:
# 1) this is fine:
doInitialStuff  # With no exceptions
excp = 0
try:
     doLotsHere()
except aParticularSetOfExceptions:
     excp = 1
if excp:
     handleException()
doLotsMoreStuff()

# 2) nested code generation has problem:
doInitialStuff  # With no exceptions
excp = 0
try:

     doMOREInitialStuff  # With no exceptions
     excp = 0
     try:
          doMORELotsHere()
     except aParticularSetOfExceptions:
          excp = 1   this causes the
problem
     if excp:
          handleException()
     doMORELotsMoreStuff()

     doLotsHere()
except aParticularSetOfExceptions:
     excp = 1
 excp=1 from inner nested code generation
if excp:
     handleException()
doLotsMoreStuff()

# 3) Hence I return to my planned template code generation:
excp = 0  Probaly need to do ONCE, to "bind"
variable ?
doInitialStuff  # With no exceptions
try:

     doMOREInitialStuff  # With no exceptions
     try:
          doMORELotsHere()
          excp = 0 # always reset excp as
last action
     except aParticularSetOfExceptions:
          excp = 1
     if excp:
          handleException()
     doMORELotsMoreStuff()

     doLotsHere()
     excp = 0 # always reset excp as last action
except aParticularSetOfExceptions:
     excp = 1
if excp:   should be fine
     handleException()
doLotsMoreStuff()


Barry Searle,    [EMAIL PROTECTED],  905-413-4020  (TL:969-4020)
Barry Searle/Toronto/[EMAIL PROTECTED]  (D3/639/8200/MKM)
"Architect, WebSphere Tools for WsAdmin Scripting and Automated Build
"







Steve Holden <[EMAIL PROTECTED]>

20/09/2005 04:11 PM




To
Barry Searle/Toronto/[EMAIL PROTECTED]


cc
python-list@python.org


Subject
Re: are variables local only
to try/except blocks?








I am taking the liberty of copying my response to
your off-list reply 
back to the c.l.py community. (and I don't normally top-post except in

politeness to other top-posters :-)

Seems to me you could avoid many of your problems by simply re-jigging

your template to read

doInitialStuff  # With presumably no exceptions
excp = 0
try:
     doLotsHere()
except aParticularSetOfExceptions:
     excp = 1
if excp:
     handleException()
doLotsMoreStuff()

If you have been experiencing problems with "unbound local variables"

this is almost certainly because, as you cast your template, there is 
the problem that if doLotsHere() raises an exception then the "excp"

variable will not be bound.

The reason for this is that Python variables (technically names) are 
only "created" (technically, associated with a value) when they
are 
bound by the execution of an assignment. If the exception is raised 
before the assignment then the variable still (technically) doesn't 
exist in the current namespace (which your average Pythonista might 
describe by saying that the name hasn't been bound).

There is *some* static analysis in Python to support name scoping, but

names must be bound by assignment in order to be referencable (?) 
without causing an AttributeError or NameError exception. That's a 
fundamental part of the way Python works.

Hence my suggestion that you assign the zero before you do anything that

might raise exceptions. You will also note I suggest you check for 
specific exceptions (you can check for more that one by using a tuple 
rather than a single exception), as otherwise you may very well end up

treating unanticipated exceptions inappropriately and masking their 
occurrence.

regards
  Steve

Barry Searle wrote:
> 
> Sorry, the quick sample was just to illustrate the problem and solution

> template.
> The generic template would be:
>   doInitialStuff()
>  try:
>     doLotsHere()
>     excp = 0
>  except:
>     excp = 1
>  #endTry
>  if (excp): doExceptionHandling()
>  doLotsMoreStuff()
> 
> The template will be used (is being used) for the automatic generation
> of a bunch of Jython code, and I wanted to be sure there were not
scope
> issues (i.e. that excp was not only defined within the try/except
blocks).
> 
> Barry Searle,    [EMAIL PROTECTED],  905-413-4020  (TL:969-4020)
> Barry Searle/Toronto/[EMAIL PROTECTED]  (D3/639/8200/MKM)
> "Architect, WebSphere Tools for WsAdmin Scripting and Automated
Build "
> 
> 
> 
> *Steve Holden <[EMAIL PROTECTED]>*
> 
> 20/09/2005 11:55 AM
> 
>                  
> To
>                  
> cc
>                  Barry
Searle/Toronto/[EMAIL PROTECTED]
> Subject
>                  Re:
are variables local only to try/except blocks?
> 
> 
>                  
> 
> 
> 
> 
> 
> BarrySearle wrote:
>  >  # Is this valid (or is excp local to try/except)?
>  >  try:
>  >     try:
>  >        doSomething1
>  >        excp = 0
> 
> This block is problematic because excp won;t be set if doSomething1
> raises an exception.
> 
>  >     except:
>  >        excp = 1
>  >     #endTry
>  >     if (_excp_): doSomething1 # is excp defined
here?
> 
> Presumably you are expecting doSomething1 to fail or

Re: Getting tired with py2exe

2005-09-20 Thread Scott David Daniels
Steve Holden wrote:
> Thomas Heller wrote:
> 
>> I'm slowly getting tired maintaining py2exe.  It is far from perfect,
>> although it has interesting features (I would say).

> Ignoring all the philosophical questions I'd like to thank you for all 
> your hard work on py2exe over the years, which has benefited the Windows 
> Python community immeasurably.

I second this.

--Scott David Daniels
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Finding where to store application data portably

2005-09-20 Thread Robert Kern
Tony Houghton wrote:
> I'm using pygame to write a game called Bombz which needs to save some
> data in a directory associated with it. In Unix/Linux I'd probably use
> "~/.bombz", in Windows something like
> "C:\Documents And Settings\\Applicacation Data\Bombz".
> 
> There are plenty of messages in the archives for this group about how to
> find the correct location in Windows, but what about Mac OS? There I
> don't know the correct location for this sort of thing at all. And there
> are other, more obscure systems like RISC OS (it may not have pygame but
> it definitely has python). Surely this is something that's crying out
> for an official function in os or sys.

On OS X, the data should probably go to
~/Library/Application Support/Bombz/

-- 
Robert Kern
[EMAIL PROTECTED]

"In the fields of hell where the grass grows high
 Are the graves of dreams allowed to die."
  -- Richard Harter

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


Re: [Py2exe-users] Re: Getting tired with py2exe

2005-09-20 Thread Bob Ippolito

On Sep 20, 2005, at 5:44 PM, Steve Holden wrote:

> Thomas Heller wrote:
>
>> I'm slowly getting tired maintaining py2exe.  It is far from perfect,
>> although it has interesting features (I would say).
>> The problem, apart from the work, is that it is good enough for me  
>> - I
>> can do everything that I need with it.  But I assume I use far less
>> libaries than other Python programmers, so a lot of bugs will  
>> never bite
>> me.
>> It is also interesting that the recently introduced bundle-files  
>> option,
>> which allows to build single-file exes has gained a lot of interest -
>> although the ONLY use case (so far) I have myself for it is to  
>> implement
>> inproc COM servers which will compatible with Python clients (and  
>> other
>> Python inproc COM servers) because of the total isolation of the  
>> Python
>> VMs.
>> Is anyone interested in taking over the maintainance,  
>> documentation, and
>> further development?
>> Should py2exe be integrated into another, larger, package?  Pywin32
>> comes to mind, but also Philip Eby's setuptools (that's why I post to
>> distutils-sig as well)...
>>
> Ignoring all the philosophical questions I'd like to thank you for  
> all your hard work on py2exe over the years, which has benefited  
> the Windows Python community immeasurably.

I'd like to thank you as well.  Although I'm primarily a Mac OS X  
(and various other *nix-ish things) user myself, I have used py2exe  
on several occasions to package a commercial product and to give  
various one-off applications to clients.

py2exe was also a large inspiration for py2app (which I have been  
neglecting lately).  py2exe (and py2app) currently do everything I  
need them do (albeit with a little prodding), so that's why I've done  
so little with it in the past few months.

I hope that the packager-future will be largely setuptools based and  
that the various platform-specific packagers will share a lot more  
code in the future (setuptools, modulegraph, etc.), making  
maintenance easier and more fun for everyone.  This was my primary  
use case when I was initially discussing the egg spec with PJE back  
around pycon-time (though I have been unfortunately useless  
implementing and evolving it).

Right now, I think the packagers and the packages are at odds,  
because the packagers need metadata that the packages don't provide  
(in a pre-setuptools universe)... so right now users (or the  
packagers) need to know a lot of magic incantations to make the  
various complicated Python packages work, where with setuptools based  
packages the magic incantations are built-in :)

-bob

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


Re: Crypto.Cipher.ARC4, bust or me doing something wrong?

2005-09-20 Thread Michael J. Fromberger
In article <[EMAIL PROTECTED]>,
 Michael Sparks <[EMAIL PROTECTED]> wrote:

> Hi,
> 
> 
> I suspect this is a bug with AMK's Crypto package from
> http://www.amk.ca/python/code/crypto , but want to
> check to see if I'm being dumb before posting a bug
> report.
> 
> I'm looking at using this library and to familiarise myself writing
> small tests with each of the ciphers. When I hit Crypto.Cipher.ARC4 I've
> found that I can't get it to decode what it encodes. This might be a
> case of PEBKAC, but I'm trying the following:
> 
> >>> from Crypto.Cipher import ARC4 as cipher
> >>> key = ""
> >>> obj = cipher.new(key)
> >>> obj.encrypt("This is some random text")
> ')f\xd4\xf6\xa6Lm\x9a%}\x8a\x95\x8ef\x00\xd6:\x12\x00!\xf3k\xafX'
> >>> X=_
> >>> X
> ')f\xd4\xf6\xa6Lm\x9a%}\x8a\x95\x8ef\x00\xd6:\x12\x00!\xf3k\xafX'
> >>> obj.decrypt(X)
> '\x87\xe1\x83\xc1\x93\xdb\xed\x93U\xe4_\x92}\x9f\xdb\x84Y\xa3\xd4b\x9eHu~'
> 
> Clearly this decode doesn't match the encode. Me being dumb or bug?
> 
> Any comments welcome :)

Michael,

Since ARC4 is a stream cipher, the keystream changes over time -- with 
ARC4, after each character enciphered.  To decrypt successfully, you 
need to make sure the decrypting keystream exactly matches the 
encrypting one.  

In your example, you used a different keystream to decrypt than you used 
to encrypt -- in this case, a little further downstream of the original 
encryption key.

Contrast your experience above with the following transcript:

>>> from Crypto.Cipher import ARC4 as cipher
>>> enc = cipher.new("abcdefgh")
>>> dec = cipher.new("abcdefgh")
>>> x = enc.encrypt("This is some random text")
>>> x
"\x05o\xd5XH|\xa4\xfc\xf7z\xecd\xe92\xfb\x05rR'\xbf\xc0F\xfc\xde"
>>> y = dec.decrypt(x)
>>> y
'This is some random text'
>>> enc.decrypt(x)
'M|[bI\x1ciG6A]\x13Hz\xb0\x19\xca\xf1-\x9a\x1a2\x9e%'

I hope this helps clear up your confusion.

Cheers,
-M

-- 
Michael J. Fromberger | Lecturer, Dept. of Computer Science
http://www.dartmouth.edu/~sting/  | Dartmouth College, Hanover, NH, USA
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ddd or eclipse with mod_python

2005-09-20 Thread Steve Holden
Trent Mick wrote:
> [Sakcee wrote]
> 
>>Hi
>>
>>I am using mod_python for web development, I am in need of some ide ,
>>can i use ddd or eclipse with pydev with mod_python.
>>
>>can these ide's handle requests from mod_python and run server side
>>scripts 
> 
> 
> You should be able to debug with Komodo(*):
> 
> Using the Python Remote Debugger
> 
> http://aspn.activestate.com/ASPN/docs/Komodo/3.1/komodo-doc-debugpython.html#Using_the_Python_Remote_Debugger
> 
> You can get a trial here:
> www.activestate.com/Komodo/Trial
> 
> Cheers,
> Trent
> 
> (*) Disclaimer: I work on Komodo.
> 
> 
WingWare's Wing IDE can also debug mod_python code. See

   http://www.wingware.com/

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC www.holdenweb.com
PyCon TX 2006  www.pycon.org

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


Finding where to store application data portably

2005-09-20 Thread Tony Houghton

I'm using pygame to write a game called Bombz which needs to save some
data in a directory associated with it. In Unix/Linux I'd probably use
"~/.bombz", in Windows something like
"C:\Documents And Settings\\Applicacation Data\Bombz".

There are plenty of messages in the archives for this group about how to
find the correct location in Windows, but what about Mac OS? There I
don't know the correct location for this sort of thing at all. And there
are other, more obscure systems like RISC OS (it may not have pygame but
it definitely has python). Surely this is something that's crying out
for an official function in os or sys.

-- 
The address in the Reply-To is genuine and should not be edited.
See  for more reliable contact 
addresses.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: MySQL & Python

2005-09-20 Thread Steve Holden
Ed Hotchkiss wrote:
> Just migrating now from ASP/to MySQL and Python.
>  
> I am trying to create a simple script to access a MySQL DB.
> The Module for MySQL looks very easy, however I do not understand one 
> thing ...
>  
> In ASP, you can just create a new DB with Access. In MySQL, how do I 
> create a database to start playing with? I see all of the commands to 
> edits tables and values and move a cursor, but I do not see how I 
> actually create THE INITIAL DB, any help would be appreciated. thanks.
> 
A good way would be to look at DB Manager:

   http://www.dbtools.com.br/

The free version is quite acceptable. Then there's SQLManager, at

   http://www.sqlmanager.net/

which is also goos for visual database work on MySQL databases. Hope 
this helps.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC www.holdenweb.com
PyCon TX 2006  www.pycon.org

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


Re: Getting tired with py2exe

2005-09-20 Thread Steve Holden
Thomas Heller wrote:
> I'm slowly getting tired maintaining py2exe.  It is far from perfect,
> although it has interesting features (I would say).
> 
> The problem, apart from the work, is that it is good enough for me - I
> can do everything that I need with it.  But I assume I use far less
> libaries than other Python programmers, so a lot of bugs will never bite
> me.
> 
> It is also interesting that the recently introduced bundle-files option,
> which allows to build single-file exes has gained a lot of interest -
> although the ONLY use case (so far) I have myself for it is to implement
> inproc COM servers which will compatible with Python clients (and other
> Python inproc COM servers) because of the total isolation of the Python
> VMs.
> 
> Is anyone interested in taking over the maintainance, documentation, and
> further development?
> 
> Should py2exe be integrated into another, larger, package?  Pywin32
> comes to mind, but also Philip Eby's setuptools (that's why I post to
> distutils-sig as well)...
> 
Ignoring all the philosophical questions I'd like to thank you for all 
your hard work on py2exe over the years, which has benefited the Windows 
Python community immeasurably.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC www.holdenweb.com
PyCon TX 2006  www.pycon.org

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


Re: functional or object-oriented?

2005-09-20 Thread beza1e1
I really should take a look at this CLOS, i think ... thanks for the
background information.

Do you think FP Python is appropriate or just syntactic sugar of a very
sophisticated kind? Now i switching back to OO a bit, but the
difference between data.value and date['value'] is not really in
Pythons dynamic world.

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


Re: Object default value

2005-09-20 Thread Scott David Daniels
James Stroud wrote:
> I think you want to overload the assignment operator here. I'm not sure that 
> is allowed in python (I've never seen it done)
> But I don't think assignment overloading is allowed in python:

Exactly correct.  Assignment is an operation on a namespace using a new
value, and does not involve the former value.  Something similar to
assignment overloading is possible with properties, but you need to be
using object attributes, not names in a module (or function locals).

class SomeDemo(object):
 def _read_foo(self):
 print 'Reading foo'
 return self._foo

 def _write_foo(self, value):
 print 'Writing foo as %r' % value
 return self._foo

 def _del_foo(self):
 print 'Deleting foo'
 del self._foo

 foo = property(_read_foo, _write_foo, _del_foo)

obj = SomeDemo()
obj.foo = 123
obj.foo += 1
del obj.foo

--Scott David Daniels
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Object default value

2005-09-20 Thread ago
In fact even IF I could get a default value to work as mentioned, then
I would be creating potential name conflicts between the
DataAttribute.DefaultValue and the other metadata. I.e. when calling
obj.attr.x I could refer to DataAttribute.x or DataAttribute.value.x.
It's a no go.

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


Re: Best Encryption for Python Client/Server

2005-09-20 Thread Ed Hotchkiss
hah :P awesome, I will be busy this week!
-edward 
On 20 Sep 2005 14:23:10 -0700, Paul Rubin <"http://phr.cx"@nospam.invalid> wrote:
Steve Holden <[EMAIL PROTECTED]> writes:> > Here's my mission: simple P2P class with encryption of whatever type
> > of file is being sent, and authentication via encrypted user> > name/password. So any type of file or login being sent over the net,> > any communication between the scripts should be encrypted,
> > regardless of whether it is client/server communication, or file> > transfer.> Robert's suggestion was a good one, as ssh (rather than SSH) is very> good at building encrypted tunnels between arbitrary processes.
If you want to use SSL in a similar fashion, try stunnel(http://www.stunnel.org).  Frankly I've never understood why ssh evenexists, but it's very widespread by now, and works pretty well within
its limitations.--http://mail.python.org/mailman/listinfo/python-list-- edward hotchkiss 
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: are variables local only to try/except blocks?

2005-09-20 Thread Steve Holden
Barry Searle wrote:
> 
> in the case of nested try/except code generation,
> your suggestion could cause a problem:
> # 1) this is fine:
> doInitialStuff  # With no exceptions
> excp = 0
> try:
> doLotsHere()
> except aParticularSetOfExceptions:
> excp = 1
> if excp:
> handleException()
> doLotsMoreStuff()
> 
> # 2) nested code generation has problem:
> doInitialStuff  # With no exceptions
> excp = 0
> try:
> 
> doMOREInitialStuff  # With no exceptions
> excp = 0
> try:
>  doMORELotsHere()
> except aParticularSetOfExceptions:
>  excp = 1   this causes the problem
> if excp:
>  handleException()
> doMORELotsMoreStuff()
> 
>  doLotsHere()
> except aParticularSetOfExceptions:
> excp = 1
>  excp=1 from inner nested code generation
> if excp:
> handleException()
> doLotsMoreStuff()
> 
> # 3) Hence I return to my planned template code generation:
> excp = 0  Probaly need to do ONCE, to "bind" variable ?

Yes, but I am bothered that you appear to feel there is a need to 1) 
record whether an exception occurred and then 2) handle the exception 
only when you have finished recording whether exceptions occurred and 
under what conditions.

> doInitialStuff  # With no exceptions
> try:
> 
> doMOREInitialStuff  # With no exceptions

In which case you might as well put the

   excp =0

here.

> try:
>  doMORELotsHere()
>  excp = 0 # always reset excp as last action

That doesn't make sense to me. If an exception isn't raised then excp 
will have the value it's always had, which is to say zero, so I don't 
see why you feel the need for this "resetting" to take place (unless 
there's a chance that doMORELotsHere() changes excp's value).

> except aParticularSetOfExceptions:
>  excp = 1
> if excp:
>  handleException()
> doMORELotsMoreStuff()
> 
>  doLotsHere()
> excp = 0 # always reset excp as last action
> except aParticularSetOfExceptions:
> excp = 1
> if excp:   should be fine
> handleException()
> doLotsMoreStuff()
> 
> 
[previous insanities deleted]

I don't believe there isn't a simpler way to do what you appear to want 
to do.

Since you are talking about machine-generated code we can agree not to 
care about ugly in terms of source, but I think we should be careful no 
to throw the baby out with the bath water here.

Rather than casting your question as code it may prove helpful simply to 
describe the problem in English, and then see if others on the group 
can't help you structure your code better.

Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC www.holdenweb.com
PyCon TX 2006  www.pycon.org
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Best Encryption for Python Client/Server

2005-09-20 Thread Paul Rubin
Steve Holden <[EMAIL PROTECTED]> writes:
> > Here's my mission: simple P2P class with encryption of whatever type
> > of file is being sent, and authentication via encrypted user
> > name/password. So any type of file or login being sent over the net,
> > any communication between the scripts should be encrypted,
> > regardless of whether it is client/server communication, or file
> > transfer.
> Robert's suggestion was a good one, as ssh (rather than SSH) is very
> good at building encrypted tunnels between arbitrary processes.

If you want to use SSL in a similar fashion, try stunnel
(http://www.stunnel.org).  Frankly I've never understood why ssh even
exists, but it's very widespread by now, and works pretty well within
its limitations.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Getting tired with py2exe

2005-09-20 Thread Bugs
Thomas Heller wrote:
[snip]
> 
> Is anyone interested in taking over the maintainance, documentation, and
> further development?
> 
> Should py2exe be integrated into another, larger, package?  Pywin32
> comes to mind, but also Philip Eby's setuptools (that's why I post to
> distutils-sig as well)...
> 

IMHO, it would be nice if the same folks (or groups working closely 
together) maintained both py2exe AND py2app.  Then they could share some 
code and concepts, create a unified and *consistent* solution on all 
supported platforms, etc.  Perhaps even creating a Linux version, with 
all 3 versions working identically...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Getting tired with py2exe

2005-09-20 Thread Bugs
Steve M wrote:
[snip]
>  * Dual packaging mode:
>* Single directory: build a directory containing an executable plus
> all
> the external binary modules (.dll, .pyd, .so) used by the program.
>* Single file: build a single executable file, totally
> self-contained,
> which runs without any external dependency.
[snip]

I've never used pyinstaller but even though it can create a single 
executable file, doesn't it still write files out to the filesystem to a 
  temp directory for actual execution?  Then cleans them up when the 
application quits?

Whereas py2exe can create an executable that NEVER writes any files out 
to the filesystem, they are loaded instead directly from the executable?

If so then that's a major difference and IMHO the py2exe method is superior.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Object default value

2005-09-20 Thread ago
> Is it safe to assume that the OP's next question will be how to invoke
functions without the ()'s?  To save you the trouble, then answer is
'no'.

You probably nailed it, thanks for the answer. I suspected that was the
case. I think I'll use __call__ + __set__

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


Re: Best Encryption for Python Client/Server

2005-09-20 Thread Steve Holden
Ed Hotchkiss wrote:
> No worries, I apologize for my outburst. I will check out the viability 
> of using an SSH module, or using pyCrypto or something to encrypt the data.
>  
Please don't apologise. It's one of c.l.py's charms that an exchange 
such as the one you had with Robert Kern results in a perfectly equable 
exchange of views rather than an escalatory flame war of the "fuck off 
and die" nature.

Please excuse my language, I've been reading too much Xah Lee lately.

> Here's my mission: simple P2P class with encryption of whatever type of 
> file is being sent, and authentication via encrypted user name/password. 
> So any type of file or login being sent over the net, any communication 
> between the scripts should be encrypted, regardless of whether it is 
> client/server communication, or file transfer. 
>  
Robert's suggestion was a good one, as ssh (rather than SSH) is very 
good at building encrypted tunnels between arbitrary processes.

> Now that I've finally stated what I want to do (sorry) Is SSH a good 
> option, or just using sockets with pycrypto? Thanks in advance.  
>  
I think I'd rather use the already-engineered ssh solution, relying as 
it does on well-thought-out asymmetric encryption. You might want to look at

http://www.ssh.com/support/documentation/online/ssh/winhelp/32/Tunneling_Explained.html

regards
  Steve

[or possibly http://www.googleityoumoron.com/?go=holden+python]
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC www.holdenweb.com
PyCon TX 2006  www.pycon.org

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


Re: Object default value

2005-09-20 Thread ago
I am trying to write a generic DataAttribute class in order to simplify
access to object attributes and attached attribute-metadata for end
users with little programming experience.

Requirement 1: accessing the "default" value should be easy (using
assignment operator, via descriptors like __get__ and __set__).

Requirement 2: access to the attribute-metadata should also be as
intuitive as possible.

Requirement 3: possibly the DataAttribute should also be callable, to
return for instance, an history of its values.

class DataAttribute(object):
 value=1 #default
 old=2
 

class Obj(object): attr=DataAttribute()

#From end user prospective, ideally:
obj=Obj()
x = obj.attr #x=1
xold = obj.attr.old #xold=2
obj.attr = 3 #obj.attr.value=3
xold = obj.attr.old #xold=1
xhistory = obj.attr(startdate, enddate) #xhistory = [[date1,
4],[date2,5],[date3,6]]
xtimestmap = x.attr.timestamp
print obj.attr == obj.attr.value #True

If I use __get__ then I cannot access the metadata.

I could create a separate Obj attribute for each metadata item, but
then I would litter the Obj namespace (typical object will have several
attributes each with lots of metadata) and potentially create name
conflicts. Not to mention that DataAttributes should be
attached/deleted on the fly and if each attribute becames a set of
attributes this operation is complex (metclasses?).

If I use __call__ + __set__ but then I am introducing an asymmetry:

x = obj.attr()
obj.attr = 2

I could use getters and setters but that is not really convenient nor
intuitive

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


Re: Classes derived from dict and eval

2005-09-20 Thread Robert Kern
Jeremy Sanders wrote:
> Hi -
> 
> I'm trying to subclass a dict which is used as the globals environment of
> an eval expression. For instance:
> 
> class Foo(dict):
> def __init__(self):
> self.update(globals())
> self['val'] = 42
>  
> def __getitem__(self, item):
> # this doesn't get called from the eval statement
> print "*", item
> return dict.__getitem__(self, item)
> 
> a = Foo()
> 
> print a['val']
> print eval('val*2+6', a)
> 
> The first print statements also prints "* val", but __getitem__ is never
> called by the evaluation in the eval statement.
> 
> Is this a bug? Does anyone have an idea for a workaround? I'm using
> Python 2.3.3.

In [1]: eval?
Type:   builtin_function_or_method
Base Class: 
String Form:
Namespace:  Python builtin
Docstring:
eval(source[, globals[, locals]]) -> value

Evaluate the source in the context of globals and locals.
The source may be a string representing a Python expression
or a code object as returned by compile().
The globals must be a dictionary and locals can be any mappping,
defaulting to the current globals and locals.
If only globals is given, locals defaults to it.

globals needs to be a real dictionary. The implementation uses the C
API, it doesn't use the overridden __getitem__. The locals argument,
apparently can be some other kind of mapping.

-- 
Robert Kern
[EMAIL PROTECTED]

"In the fields of hell where the grass grows high
 Are the graves of dreams allowed to die."
  -- Richard Harter

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


Re: are variables local only to try/except blocks?

2005-09-20 Thread Barry Searle

in the case of nested try/except code
generation, 
your suggestion could cause a problem:
# 1) this is fine:
doInitialStuff  # With no exceptions
excp = 0
try:
     doLotsHere()
except aParticularSetOfExceptions:
     excp = 1
if excp:
     handleException()
doLotsMoreStuff()

# 2) nested code generation has problem:
doInitialStuff  # With no exceptions
excp = 0
try:

     doMOREInitialStuff  # With no exceptions
     excp = 0
     try:
          doMORELotsHere()
     except aParticularSetOfExceptions:
          excp = 1   this causes the
problem
     if excp:
          handleException()
     doMORELotsMoreStuff()

     doLotsHere()
except aParticularSetOfExceptions:
     excp = 1
 excp=1 from inner nested code generation
if excp:
     handleException()
doLotsMoreStuff()

# 3) Hence I return to my planned template code generation:
excp = 0  Probaly need to do ONCE, to "bind"
variable ?
doInitialStuff  # With no exceptions
try:

     doMOREInitialStuff  # With no exceptions
     try:
          doMORELotsHere()
          excp = 0 # always reset excp as
last action
     except aParticularSetOfExceptions:
          excp = 1
     if excp:
          handleException()
     doMORELotsMoreStuff()

     doLotsHere()
     excp = 0 # always reset excp as last action
except aParticularSetOfExceptions:
     excp = 1
if excp:   should be fine
     handleException()
doLotsMoreStuff()


Barry Searle,    [EMAIL PROTECTED],  905-413-4020  (TL:969-4020)
Barry Searle/Toronto/[EMAIL PROTECTED]  (D3/639/8200/MKM)
"Architect, WebSphere Tools for WsAdmin Scripting and Automated Build
"







Steve Holden <[EMAIL PROTECTED]>

20/09/2005 04:11 PM




To
Barry Searle/Toronto/[EMAIL PROTECTED]


cc
python-list@python.org


Subject
Re: are variables local only
to try/except blocks?








I am taking the liberty of copying my response to
your off-list reply 
back to the c.l.py community. (and I don't normally top-post except in

politeness to other top-posters :-)

Seems to me you could avoid many of your problems by simply re-jigging

your template to read

doInitialStuff  # With presumably no exceptions
excp = 0
try:
     doLotsHere()
except aParticularSetOfExceptions:
     excp = 1
if excp:
     handleException()
doLotsMoreStuff()

If you have been experiencing problems with "unbound local variables"

this is almost certainly because, as you cast your template, there is 
the problem that if doLotsHere() raises an exception then the "excp"

variable will not be bound.

The reason for this is that Python variables (technically names) are 
only "created" (technically, associated with a value) when they
are 
bound by the execution of an assignment. If the exception is raised 
before the assignment then the variable still (technically) doesn't 
exist in the current namespace (which your average Pythonista might 
describe by saying that the name hasn't been bound).

There is *some* static analysis in Python to support name scoping, but

names must be bound by assignment in order to be referencable (?) 
without causing an AttributeError or NameError exception. That's a 
fundamental part of the way Python works.

Hence my suggestion that you assign the zero before you do anything that

might raise exceptions. You will also note I suggest you check for 
specific exceptions (you can check for more that one by using a tuple 
rather than a single exception), as otherwise you may very well end up

treating unanticipated exceptions inappropriately and masking their 
occurrence.

regards
  Steve

Barry Searle wrote:
> 
> Sorry, the quick sample was just to illustrate the problem and solution

> template.
> The generic template would be:
>   doInitialStuff()
>  try:
>     doLotsHere()
>     excp = 0
>  except:
>     excp = 1
>  #endTry
>  if (excp): doExceptionHandling()
>  doLotsMoreStuff()
> 
> The template will be used (is being used) for the automatic generation
> of a bunch of Jython code, and I wanted to be sure there were not
scope
> issues (i.e. that excp was not only defined within the try/except
blocks).
> 
> Barry Searle,    [EMAIL PROTECTED],  905-413-4020  (TL:969-4020)
> Barry Searle/Toronto/[EMAIL PROTECTED]  (D3/639/8200/MKM)
> "Architect, WebSphere Tools for WsAdmin Scripting and Automated
Build "
> 
> 
> 
> *Steve Holden <[EMAIL PROTECTED]>*
> 
> 20/09/2005 11:55 AM
> 
>                  
> To
>                  
> cc
>                  Barry
Searle/Toronto/[EMAIL PROTECTED]
> Subject
>                  Re:
are variables local only to try/except blocks?
> 
> 
>                  
> 
> 
> 
> 
> 
> BarrySearle wrote:
>  >  # Is this valid (or is excp local to try/except)?
>  >  try:
>  >     try:
>  >        doSomething1
>  >        excp = 0
> 
> This block is problematic because excp won;t be set if doSomething1
> raises an exception.
> 
>  >     except:
>  >        excp = 1
>  >     #endTry
>  >     if (_excp_): doSomething1 # is excp defined
here?
> 
> Presumably you are expecting doSomething1 to fail or

Re: Object default value

2005-09-20 Thread Diez B. Roggisch
ago wrote:
> Is it possible to have a default value associated python objects? I.e.
> to flag an attribute in such a way that the assignment operator for the
> object returns the default attribute instead of the object itself, but
> calls to other object attributes are properly resolved? (I don't think
> so, but I am not sure)

You're descriptions aren't very clear. Maybe you can put that in a 
greater context - what do you want to achieve?

And the assignment-operator isn't overloadable - that is for sure!

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


Re: Line Scan and Removal

2005-09-20 Thread D.Hering
Take a look at ADaM (& ESML for unifying format) and see if some of
their image processing tools can help you.

http://datamining.itsc.uah.edu/adam/documentation.html

Dieter

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


Re: Line Scan and Removal

2005-09-20 Thread Paul McGuire
"PyPK" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> i I need some help on some problem I am trying to think of.
>
> are there any algorithms available to do the following If not, any
> ideas?:
>
> I would like to Identify any lines of any orientation and width in an
> Image and
> remove them from the Image. Basically I would like to scan the entire
> Image for lines and remove them.
>
> so for example if I have an Image with a circle, a triangle and a line.
> Then my resultant Image should only have a circle.
>
> Can some one help me think through this process...
>
> Thanks
>
Google for "raster-to-vector" turned up this helpful link.
http://cardhouse.com/computer/vector.htm

-- Paul


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


Re: Object default value

2005-09-20 Thread Paul McGuire
> I think you want to overload the assignment operator here. I'm not sure
that
> is allowed in python (I've never seen it done).

You can't because assignment is not an operator in Python.

Is it safe to assume that the OP's next question will be how to invoke
functions without the ()'s?  To save you the trouble, then answer is 'no'.

Python is simple, VB is simple, but Python is not VB.

-- Paul


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


Classes derived from dict and eval

2005-09-20 Thread Jeremy Sanders
Hi -

I'm trying to subclass a dict which is used as the globals environment of
an eval expression. For instance:

class Foo(dict):
def __init__(self):
self.update(globals())
self['val'] = 42
 
def __getitem__(self, item):
# this doesn't get called from the eval statement
print "*", item
return dict.__getitem__(self, item)

a = Foo()

print a['val']
print eval('val*2+6', a)

The first print statements also prints "* val", but __getitem__ is never
called by the evaluation in the eval statement.

Is this a bug? Does anyone have an idea for a workaround? I'm using
Python 2.3.3.

Thanks

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


Re: Object default value

2005-09-20 Thread James Stroud
See this recent clpy thread:

http://www.thescripts.com/forum/thread19253.html

On Tuesday 20 September 2005 13:05, ago wrote:
> The print statement was only for illustrative purposes, when calling
> varx=myobj I need to receive obj.x as opposed to the instance of obj,
> but I also need to call vary=myobj.y. Something like that exists for
> com objects/VB, for instance an excel range object uses value as the
> default attribute, so that you can write
>
> set rng=range(...);
> x=rng
> y=rng.value
> 'x==y
> z=rng.attributeXYZ

-- 
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Getting tired with py2exe

2005-09-20 Thread Simon John
James Stroud wrote:

[snip]
> > http://pyinstaller.hpcf.upr.edu/pyinstaller

> That's one short "indefinitely":
>
> Not Found
> The requested URL /pyinstaller was not found on this server.
> Apache/2.0.53 (Fedora) Server at pyinstaller.hpcf.upr.edu Port 80

It seems that the URL is http://pyinstaller.hpcf.upr.edu

>From the website it seems this is a continuation of McMillan Installer,
which they claim is "far superior" to py2exe! Personally I gave up on
MMI, prefering py2exe on Windows and cx_Freeze on UNIX.

And if they want to use UPX, well that's up to them, but I've had some
problems with it and don't particularly like the thought of runtime
decompression and the two process thing. And when you can compress the
distributable using 7zip or whatever, why bother keeping it compressed
once downloaded?

Ah well, I wish you, whoever takes over py2exe and the PyInstaller guys
the best of luck!

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


Re: Object default value

2005-09-20 Thread James Stroud
I think you want to overload the assignment operator here. I'm not sure that 
is allowed in python (I've never seen it done). You can overload the 
equality, lt, gt, le, ge operators (==, <, ...) such that

class Thing:
  x = 5
  def __str__(self):
return str(self.x)
  def __eq__(self, other):
  if hasattr(other, 'x'):
  return self.x == other.x
  else:
return self.x == other

py> athing = Thing()
py> athing.x
5
py> bob = athing.x
py> athing == bob  # having overlaoded equality for athing
True
py> athing is bob  # not the same object
False

But I don't think assignment overloading is allowed in python:

py> athing = Thing()
py> print athing  # having overloaded __str__()
5
py> bob = athing
py> type(bob) # will not be an int ==> python language constraint


James

On Tuesday 20 September 2005 13:05, ago wrote:
> The print statement was only for illustrative purposes, when calling
> varx=myobj I need to receive obj.x as opposed to the instance of obj,
> but I also need to call vary=myobj.y. Something like that exists for
> com objects/VB, for instance an excel range object uses value as the
> default attribute, so that you can write
>
> set rng=range(...);
> x=rng
> y=rng.value
> 'x==y
> z=rng.attributeXYZ

-- 
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: are variables local only to try/except blocks?

2005-09-20 Thread Steve Holden
I am taking the liberty of copying my response to your off-list reply 
back to the c.l.py community. (and I don't normally top-post except in 
politeness to other top-posters :-)

Seems to me you could avoid many of your problems by simply re-jigging 
your template to read

doInitialStuff  # With presumably no exceptions
excp = 0
try:
 doLotsHere()
except aParticularSetOfExceptions:
 excp = 1
if excp:
 handleException()
doLotsMoreStuff()

If you have been experiencing problems with "unbound local variables" 
this is almost certainly because, as you cast your template, there is 
the problem that if doLotsHere() raises an exception then the "excp" 
variable will not be bound.

The reason for this is that Python variables (technically names) are 
only "created" (technically, associated with a value) when they are 
bound by the execution of an assignment. If the exception is raised 
before the assignment then the variable still (technically) doesn't 
exist in the current namespace (which your average Pythonista might 
describe by saying that the name hasn't been bound).

There is *some* static analysis in Python to support name scoping, but 
names must be bound by assignment in order to be referencable (?) 
without causing an AttributeError or NameError exception. That's a 
fundamental part of the way Python works.

Hence my suggestion that you assign the zero before you do anything that 
might raise exceptions. You will also note I suggest you check for 
specific exceptions (you can check for more that one by using a tuple 
rather than a single exception), as otherwise you may very well end up 
treating unanticipated exceptions inappropriately and masking their 
occurrence.

regards
  Steve

Barry Searle wrote:
> 
> Sorry, the quick sample was just to illustrate the problem and solution 
> template.
> The generic template would be:
>   doInitialStuff()
>  try:
> doLotsHere()
> excp = 0
>  except:
> excp = 1
>  #endTry
>  if (excp): doExceptionHandling()
>  doLotsMoreStuff()
> 
> The template will be used (is being used) for the automatic generation
> of a bunch of Jython code, and I wanted to be sure there were not scope
> issues (i.e. that excp was not only defined within the try/except blocks).
> 
> Barry Searle,[EMAIL PROTECTED],  905-413-4020  (TL:969-4020)
> Barry Searle/Toronto/[EMAIL PROTECTED]  (D3/639/8200/MKM)
> "Architect, WebSphere Tools for WsAdmin Scripting and Automated Build "
> 
> 
> 
> *Steve Holden <[EMAIL PROTECTED]>*
> 
> 20/09/2005 11:55 AM
> 
>   
> To
>   
> cc
>   Barry Searle/Toronto/[EMAIL PROTECTED]
> Subject
>   Re: are variables local only to try/except blocks?
> 
> 
>   
> 
> 
> 
> 
> 
> BarrySearle wrote:
>  >  # Is this valid (or is excp local to try/except)?
>  >  try:
>  > try:
>  >doSomething1
>  >excp = 0
> 
> This block is problematic because excp won;t be set if doSomething1
> raises an exception.
> 
>  > except:
>  >excp = 1
>  > #endTry
>  > if (_excp_): doSomething1 # is excp defined here?
> 
> Presumably you are expecting doSomething1 to fail or succeed in some
> non-deterministic way? Otherwise this will just raise the same exception
> again!
> 
>  > excp = 0
>  >  except:
>  > excp = 1
>  > #endTry
>  > if (excp): doSomething2 # is excp defined here?
>  >
>  >
>  >  # valid, but more verbose (and maybe redundant?)
>  >  excp = 0
>  >  try:
>  > excp = 0
>  > try:
>  >doSomething1
>  >excp = 0  # reset incase future inner block
>  > except:
>  >excp = 1
>  > #endTry
>  > if (_excp_): doSomething1
>  > excp = 0  # reset incase inner block set excp=1
>  >  except:
>  > excp = 1
>  > #endTry
>  > if (excp): doSomething2
>  >
>  > I am not so interested in what a particular version of the
>  > Python/Jython interpreter does, but rather what is "right".
>  >
>  > Pls "CC" replies to [EMAIL PROTECTED] (as well as newsgroup)
>  > Barry Searle,[EMAIL PROTECTED]
>  >
> Your approach to exception handling is a little simplistic, resulting on
> code that reads about as well as a plate of spaghetti.
> 
> What are you actually trying to *do*? What problem do you need to solve?
> 
> regards
>  Steve
> -- 
> Steve Holden   +44 150 684 7255  +1 800 494 3119
> Holden Web LLC www.holdenweb.com
> PyCon TX 2006  www.pycon.org
> 


-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC www.holdenweb.com
PyCon TX 2006  www.pycon.org
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Object default value

2005-09-20 Thread ago
The print statement was only for illustrative purposes, when calling
varx=myobj I need to receive obj.x as opposed to the instance of obj,
but I also need to call vary=myobj.y. Something like that exists for
com objects/VB, for instance an excel range object uses value as the
default attribute, so that you can write

set rng=range(...); 
x=rng
y=rng.value
'x==y
z=rng.attributeXYZ

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


Re: Object default value

2005-09-20 Thread Larry Bates
The prints can be done by defining an __str__ method on the
class, but I don't think you will get the type(obj) to work
the way you want.

class obj(object):
__default=1
y=2

def __str__(self):
return str(self.__default)

myobj=obj()
print "myobj=", myobj
print "myobj.y=", myobj.y

>>> myobj= 1
>>> myobj.y= 2

ago wrote:
> Is it possible to have a default value associated python objects? I.e.
> to flag an attribute in such a way that the assignment operator for the
> object returns the default attribute instead of the object itself, but
> calls to other object attributes are properly resolved? (I don't think
> so, but I am not sure)
> 
> Example:
> 
> class obj(object):
>  x=1 #assume x is somehow made into a default value
>  y=2
> 
> Ideally this should be the result:
> 
> myobj=obj()
> print myobj #-> 1
> print myobj.y #-> 2
> x=myobj
> print x #-> 1
> print type(x) #int
> 
> Those are my half-working solutions so far:
> 
> 1) using __get__ descriptor within the class,
> 
> def __get__(self,parent,parenttype): return self.x
> 
> then
> 
> print myobj #works
> print myobj.y #does not work! equivalent to: print 1.y
> 
> 2) Use a __call__ method without a __get__ descriptor.
> 
> def __call__(self): return self.x
> 
> then:
> 
> print myobj() #works, but not the same as: print myobj
> print myobj.y #works
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Line Scan and Removal

2005-09-20 Thread PyPK
i I need some help on some problem I am trying to think of.

are there any algorithms available to do the following If not, any
ideas?:

I would like to Identify any lines of any orientation and width in an
Image and
remove them from the Image. Basically I would like to scan the entire
Image for lines and remove them.

so for example if I have an Image with a circle, a triangle and a line.
Then my resultant Image should only have a circle.

Can some one help me think through this process...

Thanks

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


Re: Question about smtplib, and mail servers in general.

2005-09-20 Thread Mike Meyer
Peter Hansen <[EMAIL PROTECTED]> writes:
> Daniel Dittmar wrote:
>> Chris Dewin wrote:
>>> Hi. I've been thinking about using smtplib to run a mailing list
>>> from my website.
>>>
>>> s = smtplib.SMTP("server")
>>> s.sendmail(fromaddress, toaddresess, msg)
>>>
>>> I know that in this instance, the toaddresses variable can be a variable
>>> of type list.
>>>
>>> Suppose the list contains well over 100 emails. Would that create some
>>> sort of drain on the mail server? Would I be better off doing it in some
>>> other way?
>> Not really an answer to your question, but it's probably considered
>> bad style to publish the email addresses of the recipients via the
>> address list. Use a neutral To-address (best: the mailing list
>> address) and add the recipients via bcc: headers.
>
> Not only not an answer, but also not a valid point in this case.  The
> list of recipients used in the sendmail() call (which become RCPT TO:
> commands in SMTP) do *not* show up in the received emails.

Not quite. The email address each letter is actually delivered to
generally shows up in one or more Received: headers in the received
email. Some MTAs will add a header (qmail adds Delivered-To:, for
instance) with that same address in it when they deliver the mail
locally. Most MUAs don't display those, but they are there.  There may
be an MTA that will pass a single message along to multiple recipients
after adding all of them to one or more headers. I don't know that
such exist - but I wouldn't trust that they don't.

Since you shouldn't trust email to be secure in any case, this isn't a
big deal. Note that using Bcc: doesn't help with this issue - the
addresses a message is delivered to *have* to be in the envelope. Bcc
puts them there and not in the headers.

http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Monitoring a directory for changes

2005-09-20 Thread Martin v. Löwis
Florian Lindner wrote:
> is there a python lib (preferably in the std lib) to monitor a directory for
> changes (adding / deleting files) for Linux 2.6?

I recommend to use the python-fam library: sf.net/projects/python-fam.
On Debian, just install the python-fam package.

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


Object default value

2005-09-20 Thread ago
Is it possible to have a default value associated python objects? I.e.
to flag an attribute in such a way that the assignment operator for the
object returns the default attribute instead of the object itself, but
calls to other object attributes are properly resolved? (I don't think
so, but I am not sure)

Example:

class obj(object):
 x=1 #assume x is somehow made into a default value
 y=2

Ideally this should be the result:

myobj=obj()
print myobj #-> 1
print myobj.y #-> 2
x=myobj
print x #-> 1
print type(x) #int

Those are my half-working solutions so far:

1) using __get__ descriptor within the class,

def __get__(self,parent,parenttype): return self.x

then

print myobj #works
print myobj.y #does not work! equivalent to: print 1.y

2) Use a __call__ method without a __get__ descriptor.

def __call__(self): return self.x

then:

print myobj() #works, but not the same as: print myobj
print myobj.y #works

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


Re: Simpler transition to PEP 3000 "Unicode only strings"?

2005-09-20 Thread Martin v. Löwis
Petr Prikryl wrote:
> Would this break any existing code?

Yes, it would break code which currently contains

# -*- coding: utf-8 -*-

and also contains byte string literals.

Notice that there is an alternative form of the UTF-8
declaration: if the Python file starts with an UTF-8
signature (BOM), then it is automatically considered
as UTF-8, with no explicit conding:-declaration
required. Set IDLE's Options/General/Default Source
Encoding to UTF-8 to have IDLE automatically use the
UTF-8 signature when saving files with non-ASCII
characters.

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'.

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


Re: Release of Shed Skin 0.0.2: Easy Windows/OSX Installation

2005-09-20 Thread Michael Sparks
Mark Dufour wrote:
> Shed Skin is an experimental Python-to-C++ compiler. Along with
> GNU/Linux, version 0.0.2 should now also install easily under Windows
> 2000/XP and OSX. Please give it a try and let me know if there are
> still some problems.

ss.py writes a make file, but unfortunately doesn't detect correctly whether
you need libdl linked in or not. As a result the generated Makefile for the
test includes this for me:

MAINOBJ=test.o
test:   $(MAINOBJ) /home/zathras/Documents/shedskin-0.0.2/libss.a
$(CC) $(CCFLAGS)
$(MAINOBJ) /home/zathras/Documents/shedskin-0.0.2/libss.a -lgc -o test

Whereas it would need to be the following because I'm under linux:

MAINOBJ=test.o
test:   $(MAINOBJ) /home/michaels/Documents/shedskin-0.0.2/libss.a
$(CC) $(CCFLAGS)
$(MAINOBJ) /home/michaels/Documents/shedskin-0.0.2/libss.a -lgc -ldl -o
test

(The reason I'm not suggesting just throwing in -ldl is because that will
then break on other platforms... You need to detect whether it's needed or
not for the platform it's currently compiling for)

Regards,


Michael.

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


Re: Getting tired with py2exe

2005-09-20 Thread James Stroud
On Tuesday 20 September 2005 11:43, Steve M wrote:
> What about PyInstaller that was announced the other day? The feature
> list looks great, and it appears the developers intend to maintain and
> enhance the program indefinitely.
...
>
> http://pyinstaller.hpcf.upr.edu/pyinstaller

That's one short "indefinitely":

Not Found
The requested URL /pyinstaller was not found on this server.
Apache/2.0.53 (Fedora) Server at pyinstaller.hpcf.upr.edu Port 80

James

-- 
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Getting tired with py2exe

2005-09-20 Thread Steve M
What about PyInstaller that was announced the other day? The feature
list looks great, and it appears the developers intend to maintain and
enhance the program indefinitely.

http://groups.google.com/group/comp.lang.python/browse_thread/thread/b487056b7b1f99bc/583da383c1749d9f?q=ANN&rnum=1&hl=en#583da383c1749d9f

http://pyinstaller.hpcf.upr.edu/pyinstaller

Feature highlights:
* Packaging of Python programs into standard executables, that work on
computers without Python installed.
 * Multiplatform: works under Windows, Linux and Irix.
 * Multiversion: works under any version of Python since 1.5.
 * Dual packaging mode:
   * Single directory: build a directory containing an executable plus
all
the external binary modules (.dll, .pyd, .so) used by the program.
   * Single file: build a single executable file, totally
self-contained,
which runs without any external dependency.
 * Support for automatic binary packing through the well-known UPX
compressor.
 * Optional console mode (see standard output and standard error at
runtime).
 * Selectable executable icon (Windows only).
 * Fully configurable version resource section in executable (Windows
only).
 * Support for building COM servers (Windows only).

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


Re: Would you pls tell me a tool to step debug python program?

2005-09-20 Thread SPE - Stani's Python Editor
SPE ships with a debugger as well: http://pythonide.stani.be It's free
& open source.

Johnny Lee wrote:
> Hi,
>I've met a problem to understand the code at hand. And I wonder
> whether there is any useful tools to provide me a way of step debug?
> Just like the F10 in VC...
> 
> Thanks for your help.
> 
> Regards,
> Johnny

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


Re: Monitoring a directory for changes

2005-09-20 Thread Reinhold Birkenfeld
Florian Lindner wrote:
> Hello,
> is there a python lib (preferably in the std lib) to monitor a directory for
> changes (adding / deleting files) for Linux 2.6?

There isn't, but if you don't want to use dnotify/inotify, it is trivial to
implement: use a timer and check the listdir() return value.

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


Re: Organising a python project

2005-09-20 Thread Ron Adam
[EMAIL PROTECTED] wrote:

> Dear all,
> 
> Can anyone point me to a resource that describes the best way of
> organising a python project? My project (gausssum.sf.net) is based
> around a class, and has a GUI that allows 'easy-access' to the methods
> of the class. What is the best or typical directory structure that
> allows the easy creation of binary packages for linux and windows,
> source distributions, etc.
> 
> Rather than make up my own way, I'd prefer to know if there is a
> typical python way...
> 
> Regards,
> baoilleach


Here's what I've settled on for windows. This also keeps my src dir 
clean and separate form all the additional install files needed. I don't 
use automatic version control or CVS yet,  but this seems to work well 
enough for me.  You could probably just add the neccisary script to 
create linux distribution as well.

projectname <- main project directory

projectname1 <- version dir
dist <- py2exe output dir
docs <- addition documents, license, etc, dir
icons<- icons file(s) for exe file dir
src  <- stand alone python source dir
notes<- addition development notes dir
Output   <- inno setup output dir
makeexe.py   <- py2exe script
pack.iss <- inno setup script

projectname2 <- next version...
...  #  copy the previous version to start.
...


Below is my basic py2exe script. You'll need to change it to suite your 
own needs of course.  The rmtree is my own module to remove directories 
and contents.  The newest version of py2exe I think does a better job of 
cleaning up I think.

Cheers,
Ron



# makeexe.py
"""
 Create a stand alone distribution using py2exe.
"""

from distutils.core import setup
import py2exe
import sys
import os
from mytools import rmtree

sys.path += ['.\\src']

try: rmtree.rmtree('dist')
except OSError: pass

try: rmtree.rmtree('build')
except OSError: pass

# Avoid having to use the command line.
# If run without args, build executables, in quiet mode.
if len(sys.argv) == 1:
 #sys.argv.append("-h")  # show options
 sys.argv.append("py2exe")

opts = {
 "py2exe": {
 "optimize": "2",
 }
 }

setup(
 options = opts,
 name = 'Aztec',
 windows = [{
 "script": "src\\aztec.py",
 "icon_resources": [(1, "icons\\aztec.ico")],
 }]
 )

os.rename('dist\\aztec.exe', 'dist\\aztec.scr')

try: rmtree.rmtree('build')
except OSError: pass





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


Re: vendor-packages directory

2005-09-20 Thread Terry Reedy

"Rich Burridge" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> I work in the Accessibility Program Office at Sun Microsystems. I'm
> part of a team that is using Python to create a screen reader called
> Orca, that'll help blind people (and people with low vision) have
> access to the GNOME desktop for Solaris and Linux.
>   http://cvs.gnome.org/viewcvs/*checkout*/orca/docs/doc-set/orca.html

Very nice.  I am old enough to know I might need such a program some day.

> Orca in turn uses several packages that interface between Python and the
> various "native" libraries in the GNOME desktop:
>
>   * pyorbit   - Python bindings for ORBit2
>   * pygtk - GTK+ Python bindings
>   * gnome-python  - Python bindings for various GNOME libraries
>
> We will be presenting our project in front of one of the archirectural
> review committees within Sun soon, in order to try to get this software
> in a future release of the Solaris operating system. It's Open Sources,
> so other Linux vendors will also be able to pick it up (if they so 
> desire),
> to include with their software distributions.
>
> We've been given a heads-up on the following problem.
>
> Until now we've been using "/usr/lib/python2.4/site-packages" as the
> directory to install the various Python files that these packages use.

My impression is that this is exactly the intended place for general-use 
support packages.

> We have been told that this directory is inappropriate for vendor 
> supplied
> packages,

As you of course know, 'appropriateness' in in the eye of the beholder. 
>From Python's viewpoint, there is no difference that I know of between 
'vender' supplied packages and 'sharer' supplied packages.  So this looks 
to me like arbitrary whim.  Is there any rationale that I am missing.

> Now we could easily create a "/usr/lib/python2.4/vendor-packages"
[... snip]

If there are other package writers who don't use site-packages, perhaps 
they will read this and share their experiences and solutions.

> What I'd like to see is a future release of Python automatically checking
> for this directory and appending it to the list of directories that it'll
> search.

Python has done fine, it seems, without this.  What benefit would I and 
hundreds of thousands of other people get from having such a directory on 
our machines?

> Here's a patch to do this:
>
> --- Python-2.4.1/Lib/site.py Mon Sep 19 12:37:00 PDT 2005
> +++ Python-2.4.1-new/Lib/site.py Mon Sep 19 12:37:00 PDT 2005
> @@ -182,7 +182,11 @@
>   "lib",
>   "python" + sys.version[:3],
>   "site-packages"),
> -os.path.join(prefix, "lib", "site-python")]
> +os.path.join(prefix, "lib", "site-python"),
> +os.path.join(prefix,
> + "lib",
> + "python" + sys.version[:3],
> + "vendor-packages")]
>  else:
>  sitedirs = [prefix, os.path.join(prefix, "lib", 
> "site-packages")]
>  if sys.platform == 'darwin':

Patches generally belong on one of the Python sourceforge trackers.  If you 
decide to pursue this, this could go either under Patches or maybe RFEs.

> Is this something that would be considered for a future Python release?

My guess would be no, better to persuade whoever to let you use Python as 
intended.  But I don't really know.  The decision would be made either by 
GvR, who will not see this here, or one of the top developers, who might or 
might not.  But I am pretty sure you would need a better rationale than 'my 
superior is hung up on the directory name' or 'Perl has two package 
directories'.  Support from other package venders would definitely be a 
plus.

Terry J. Reedy



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


Monitoring a directory for changes

2005-09-20 Thread Florian Lindner
Hello,
is there a python lib (preferably in the std lib) to monitor a directory for
changes (adding / deleting files) for Linux 2.6?

Thanks,

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


Re: mailing from with python

2005-09-20 Thread Tim Williams (gmail)
On 20/09/05, M.N.A.Smadi <[EMAIL PROTECTED]> wrote:
> hi;
> if i want to send a mail message using the "mail" client on a machine
> that has smtp protocol is there an easy way (i.e. like bash where you
> would just type mail -s SUBJECT message RECIPIENT) to do it from a
> python script?

Any mail client using SMTP will be outbound only,  you wouldn't be
able to send mail "through" the client using SMTP.

>From a post earlier today :)

s = smtplib.SMTP("server")
s.sendmail(fromaddress, toaddresess, msg)

You can send email directly to your local server (or direct to the
recipeint server) directly from your python "script"

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


Re: Crypto.Cipher.ARC4, bust or me doing something wrong?

2005-09-20 Thread Michael Sparks
Jp Calderone wrote:

> On Tue, 20 Sep 2005 16:08:19 +0100, Michael Sparks <[EMAIL PROTECTED]>
> wrote:
>>Hi,
>>
>>
>>I suspect this is a bug with AMK's Crypto package from
>>http://www.amk.ca/python/code/crypto , but want to
>>check to see if I'm being dumb before posting a bug
>>report.
>>
>>I'm looking at using this library and to familiarise myself writing
>>small tests with each of the ciphers. When I hit Crypto.Cipher.ARC4 I've
>>found that I can't get it to decode what it encodes. This might be a
>>case of PEBKAC, but I'm trying the following:
>>
> from Crypto.Cipher import ARC4 as cipher
> key = ""
> obj = cipher.new(key)
> obj.encrypt("This is some random text")
>>')f\xd4\xf6\xa6Lm\x9a%}\x8a\x95\x8ef\x00\xd6:\x12\x00!\xf3k\xafX'
> X=_
> X
>>')f\xd4\xf6\xa6Lm\x9a%}\x8a\x95\x8ef\x00\xd6:\x12\x00!\xf3k\xafX'
> obj.decrypt(X)
>>'\x87\xe1\x83\xc1\x93\xdb\xed\x93U\xe4_\x92}\x9f\xdb\x84Y\xa3\xd4b\x9eHu~'
>>
>>Clearly this decode doesn't match the encode. Me being dumb or bug?
>>
>>Any comments welcome :)
>>
> 
> You need two ARC4 instances.  Performing any operation alters the internal
> state (as it is a stream cipher), which is why your bytes did not come out
> intact.

Ahh. That makes perfect sense. (I thought it must be me missing something)

Many thanks! 

:-)

Regards,


Michael.

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


Re: Two questions on PyDev for Eclipse

2005-09-20 Thread Fabio Zadrozny
Fabio Zadrozny wrote:

>Hi,
>
>for 2: as far as I know, eclipse must have 'local', or at least 
>'emulated' local access, so, if you have samba access, it should do what 
>you want.
>
>for 1... I use it a LOT without any problems for some really big 
>projects ( with about 2.000 python modules -- not counting the python 
>installation) -- but as I also develop it, so, I may be kind of 
>impartial ;-)
>  
>
I meant partial ;-)

>Cheers,
>
>Fabio
>
>Kenneth McDonald wrote:
>
>  
>
>>The first is general; what are users' experience with PyDev for  
>>Eclipse. It looks pretty good to me right now, but I've only started  
>>playing with it. Converting to Eclipse is a major effort, and if  
>>there are problems which would prevent pydev from being useful right  
>>now, I'd certainly appreciate knowing about them.
>>
>>The second question is specific; is it possible to use Eclipse to  
>>edit a remote file, i.e. through SFTP or something equivalent? My  
>>current (limited) understanding of Eclipse is that it maintains an on- 
>>disk directory of files in a project. Unfortunately, for what I'm  
>>doing, a fair number of the files (mostly Python files) I'm editing  
>>are on a remote server, so whatever editor I use, the ability to edit  
>>remote files would be a big help.
>>
>>Thanks,
>>Ken
>> 
>>
>>
>>
>
>
>  
>


-- 
Fabio Zadrozny
--
Software Developer

ESSS - Engineering Simulation and Scientific Software
www.esss.com.br

PyDev - Python Development Enviroment for Eclipse
pydev.sf.net
pydev.blogspot.com


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


mailing from with python

2005-09-20 Thread M.N.A.Smadi
hi;
if i want to send a mail message using the "mail" client on a machine 
that has smtp protocol is there an easy way (i.e. like bash where you 
would just type mail -s SUBJECT message RECIPIENT) to do it from a 
python script?

thanks
moe smadi
-- 
http://mail.python.org/mailman/listinfo/python-list


How to Handle exceptions using OpenerDirector

2005-09-20 Thread swarna pulavarty




Hi all, 
 
 I am trying to figure out a way to handle exceptions for error code 4xx , and 5xx 's . I came to know that these can be handled using OpenerDirector class and urllib2 module in Python. I could'nt find the right syntax or examples of how to use these Handlers.
 
Any help is greatly appreciated !
 
 
Swarna.



		 
Yahoo! India Matrimony: Find your partner now.-- 
http://mail.python.org/mailman/listinfo/python-list

Re: vendor-packages directory

2005-09-20 Thread Steve Holden
Rich:

You made it to the States, then? How ironic, I've just been working in 
VA for nine years, but recently returned to Scotland and ended up living 
in Linlithgow, known to most Sun long-timers.

Hope mp is still providing good service.

Rich Burridge wrote:
> Hi,
> 
> I work in the Accessibility Program Office at Sun Microsystems. I'm
> part of a team that is using Python to create a screen reader called
> Orca, that'll help blind people (and people with low vision) have
> access to the GNOME desktop for Solaris and Linux.
> 
[...]

Sorry to hijack your inquiry for personal reasons, but your name leaped 
out at me from the newsreader.

I'm not a developer so I can't really tell you whether that patch will 
be accepted. Since they are talking about "vendor supplied" software, 
there's really no reason why the vendor in question shouldn't make sure 
(probably by the addition of a .pth file) that the required directory is 
added to the search path.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC www.holdenweb.com
PyCon TX 2006  www.pycon.org

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


Using PyGILState_Ensure

2005-09-20 Thread Ralf Riemer
Hi,

I have some questions concerning the global interpreter lock:

I am working with Windows XP Professional Version 5.1, Python version 2.4.1
and Microsoft Visual C++.Net Version 7.1.
>From Python I call a function from a C++ dll using
calldll.call_foreign_function. This C++ function does a callback of a python
function.
Do get it running I use PyGILState_Ensure before PyEval_CallObject and
PyGILState_Release afterwards.
The code looks like this:

static PyObject *my_callback = NULL;

...

// my_callback is set from Python using a 
function SetCallback
...


/* Time to call the callback */
ppyobjArgList = Py_BuildValue("()", NULL);  
   
//General Interpreter Lock (essential for succesful
calling of any python function)
PyGILState_STATE gstate;
//Ensure that the current thread is ready to call
the Python C API 
gstate = PyGILState_Ensure();

ppyobjResult = PyEval_CallObject(my_callback,
ppyobjArgList);
if (!((DWORD_PTR)ppyobjResult))
{
//Error handling
...
} else {
Py_DECREF(ppyobjResult);
}
 
Py_DECREF(ppyobjArgList);

PyGILState_Release(gstate);

Now my questions:
Are there any risks aquiring the global interpreter lock?
Do I invoke by PyEval_CallObject a new python process? (I suppose not)
How long my this call of PyEval_CallObject last? Are there restictions to
the code I use in the called function.
Is it allowed to force the thread to wait (by aquiring the GIL)?
Is there a risk that windows hangs up?
Doing several calls of my dll function with the callback, is there a risk
that the calls overlap and information gets lost?

Thanks for your help!
Ralf

-- 
Lust, ein paar Euro nebenbei zu verdienen? Ohne Kosten, ohne Risiko!
Satte Provisionen für GMX Partner: http://www.gmx.net/de/go/partner
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Alternatives to Stackless Python?

2005-09-20 Thread Stephan Diehl
On Tue, 20 Sep 2005 08:50:44 -0700, [EMAIL PROTECTED] wrote:

> After recently getting excited about the possibilities that stackless
> python has to offer
> (http://harkal.sylphis3d.com/2005/08/10/multithreaded-game-scripting-with-stackless-python/)
> and then discovering that the most recent version of stackless
> available on stackless.com was for python 2.2 I am wondering if
> Stackless is dead/declining and if so, are there any viable
> alternatives that exist today?

Well, it's not dead and the last recent version is for python 2.3
The developer of stackless, Christian Tismer, is one of the main
developers of the PyPy project. (http://codespeak.net/pypy)
For this reason, there is an extremely good chance that the ideas
behind stackless will survive :-) .
Visit www.stackless.com for further info.
---
Stephan
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Best Encryption for Python Client/Server

2005-09-20 Thread Robert Kern
Ed Hotchkiss wrote:
> No worries, I apologize for my outburst. I will check out the viability
> of using an SSH module, or using pyCrypto or something to encrypt the data.
>  
> Here's my mission: simple P2P class with encryption of whatever type of
> file is being sent, and authentication via encrypted user name/password.
> So any type of file or login being sent over the net, any communication
> between the scripts should be encrypted, regardless of whether it is
> client/server communication, or file transfer. 
>  
> Now that I've finally stated what I want to do (sorry) Is SSH a good
> option, or just using sockets with pycrypto? Thanks in advance.  

As I've said before, authoring new security protocols yourself is rarely
a good idea. You *will* get it wrong even if you get the actual
encryption parts right. SSH has implemented a good security model, and
piggybacking on that is preferable to writing your own authentication
protocol. With SSH, you have two clear options, use the SCP protocol
(Secure CoPy) or doing your own file transfers through an
SSH-established and -authenticated tunnel (google:stunnel). A Python
implementation of SSH is provided by the package Paramiko.

Good luck.

-- 
Robert Kern
[EMAIL PROTECTED]

"In the fields of hell where the grass grows high
 Are the graves of dreams allowed to die."
  -- Richard Harter

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


Re: vendor-packages directory

2005-09-20 Thread Michael Ekstrand
On Tuesday 20 September 2005 10:22, Rich Burridge wrote:
> [lots of well-written and logical information about a proposed
> vendor-packages directory snipped] 
> Is this something that would be considered for a future Python
> release?

+1 to that from me... it looks like good idea - have you submitted the 
patch to SourceForge?

Alternatively, though, there is another option, and it seems to be what 
Debian tries to encourage: the distribution places its packages 
in /usr/lib/python2.3/site-packages. The local administrator can then 
place his/her packages in /usr/local/lib/python2.3/site-packages. Both 
locations are searched.

Unfortunately, the Python distutils default 
to /usr/lib/python2.3/site-packages, so that administrator-installed 
packages are also placed in /usr/lib with the vendor/distro packages. 
If this was changed, so that /usr/local/lib... actually became the 
default for locally-installed packages, that would be a good thing 
IMHO. But it is probably not as elegant as a vendor-packages directory.

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


Getting tired with py2exe

2005-09-20 Thread Thomas Heller
I'm slowly getting tired maintaining py2exe.  It is far from perfect,
although it has interesting features (I would say).

The problem, apart from the work, is that it is good enough for me - I
can do everything that I need with it.  But I assume I use far less
libaries than other Python programmers, so a lot of bugs will never bite
me.

It is also interesting that the recently introduced bundle-files option,
which allows to build single-file exes has gained a lot of interest -
although the ONLY use case (so far) I have myself for it is to implement
inproc COM servers which will compatible with Python clients (and other
Python inproc COM servers) because of the total isolation of the Python
VMs.

Is anyone interested in taking over the maintainance, documentation, and
further development?

Should py2exe be integrated into another, larger, package?  Pywin32
comes to mind, but also Philip Eby's setuptools (that's why I post to
distutils-sig as well)...

Thomas

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


Re: How to write this iterator?

2005-09-20 Thread George Sakkis
"Jordan Rastrick" <[EMAIL PROTECTED]> wrote:

> I've written this kind of iterator before, using collections.deque,
> which personally I find a little more elegant than the list based
> approach:

Nice, that's *much* more elegant and simple ! Here's the class-based version 
with append; note that
interleave is modified to put back the popped iterator before yield, otherwise 
append doesn't work
properly:

from collections import deque

class Interleave(object):
"""Iterator that cycles over one or more iterables, yielding one item from
each iterable at a time. Once an iterable is exhausted, it is removed from
the cycle. This iterator is exhausted when all participating iterables are
exhausted.

>>> it = Interleave("abc","12345","XY")
>>> list(it)
['a', '1', 'X', 'b', '2', 'Y', 'c', '3', '4', '5']
>>> list(it)
[]
"""

def __init__(self, *iterables):
iters = self.__iters = deque(map(iter, iterables))
def generator():
while iters:
it = iters.popleft()
try:
next = it.next()
except StopIteration:
continue
else:
iters.append(it)
yield next
self.__this_iter = generator()

def append(self,iterable):
"""Adds an iterable to the existing cycle of iterables.

The given iterable is added in front of the current position in the
cycle so that it's called only after all the others.

>>> example = Interleave("abc", "12345")
>>> [example.next() for i in range(3)]
['a', '1', 'b']
>>> example.append("XY")
>>> list(example)
['2', 'c', 'X', '3', 'Y', '4', '5']
"""
self.__iters.append(iter(iterable))

def __iter__(self):
return self

def next(self):
return self.__this_iter.next()


if __name__ == '__main__':
import doctest
doctest.testmod()


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


Re: Where is my exception

2005-09-20 Thread Laszlo Zsolt Nagy

>The program prints out "point 1" but it does not print "point 2". What 
>am I missing?
>  
>
Sorry from all. I should have been looked at the processor before I 
posted. There is no exception. It was an infinite loop inside the try 
block, but it was called from an event handler. I did not notice that my 
CPU is at 100%. :-(

   Les


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


Re: Crypto.Cipher.ARC4, bust or me doing something wrong?

2005-09-20 Thread Jp Calderone
On Tue, 20 Sep 2005 16:08:19 +0100, Michael Sparks <[EMAIL PROTECTED]> wrote:
>Hi,
>
>
>I suspect this is a bug with AMK's Crypto package from
>http://www.amk.ca/python/code/crypto , but want to
>check to see if I'm being dumb before posting a bug
>report.
>
>I'm looking at using this library and to familiarise myself writing
>small tests with each of the ciphers. When I hit Crypto.Cipher.ARC4 I've
>found that I can't get it to decode what it encodes. This might be a
>case of PEBKAC, but I'm trying the following:
>
 from Crypto.Cipher import ARC4 as cipher
 key = ""
 obj = cipher.new(key)
 obj.encrypt("This is some random text")
>')f\xd4\xf6\xa6Lm\x9a%}\x8a\x95\x8ef\x00\xd6:\x12\x00!\xf3k\xafX'
 X=_
 X
>')f\xd4\xf6\xa6Lm\x9a%}\x8a\x95\x8ef\x00\xd6:\x12\x00!\xf3k\xafX'
 obj.decrypt(X)
>'\x87\xe1\x83\xc1\x93\xdb\xed\x93U\xe4_\x92}\x9f\xdb\x84Y\xa3\xd4b\x9eHu~'
>
>Clearly this decode doesn't match the encode. Me being dumb or bug?
>
>Any comments welcome :)
>

You need two ARC4 instances.  Performing any operation alters the internal 
state (as it is a stream cipher), which is why your bytes did not come out 
intact.

  >>> import Crypto.Cipher.ARC4 as ARC4
  >>> o = ARC4.new('hello monkeys')
  >>> p = ARC4.new('hello monkeys')
  >>> p.decrypt(o.encrypt('super secret message of doom'))
  'super secret message of doom'
  >>>

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


Crypto.Cipher.ARC4, bust or me doing something wrong?

2005-09-20 Thread Michael Sparks
Hi,


I suspect this is a bug with AMK's Crypto package from
http://www.amk.ca/python/code/crypto , but want to
check to see if I'm being dumb before posting a bug
report.

I'm looking at using this library and to familiarise myself writing
small tests with each of the ciphers. When I hit Crypto.Cipher.ARC4 I've
found that I can't get it to decode what it encodes. This might be a
case of PEBKAC, but I'm trying the following:

>>> from Crypto.Cipher import ARC4 as cipher
>>> key = ""
>>> obj = cipher.new(key)
>>> obj.encrypt("This is some random text")
')f\xd4\xf6\xa6Lm\x9a%}\x8a\x95\x8ef\x00\xd6:\x12\x00!\xf3k\xafX'
>>> X=_
>>> X
')f\xd4\xf6\xa6Lm\x9a%}\x8a\x95\x8ef\x00\xd6:\x12\x00!\xf3k\xafX'
>>> obj.decrypt(X)
'\x87\xe1\x83\xc1\x93\xdb\xed\x93U\xe4_\x92}\x9f\xdb\x84Y\xa3\xd4b\x9eHu~'

Clearly this decode doesn't match the encode. Me being dumb or bug?

Any comments welcome :)


Michael.
-- 
[EMAIL PROTECTED], http://kamaelia.sourceforge.net/
British Broadcasting Corporation, Research and Development
Kingswood Warren, Surrey KT20 6NP

This message (and any attachments) may contain personal views
which are not the views of the BBC unless specifically stated.

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


Re: testing a website from python

2005-09-20 Thread Laszlo Zsolt Nagy
M.N.A.Smadi wrote:

>hi;
>
>I just want to test that a given website is up or not from a python 
>script.  I thought of using wget as an os command.  Any better ideas?
>  
>
urllib

http://www.python.org/doc/current/lib/module-urllib.html

If you only want to test if the HTTP port is open or not:

socket

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

   Les

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


testing a website from python

2005-09-20 Thread M.N.A.Smadi
hi;

I just want to test that a given website is up or not from a python 
script.  I thought of using wget as an os command.  Any better ideas?

thanks
moe smadi
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: QCheckListItem signal question

2005-09-20 Thread Artur M. Piwko
In the darkest hour on 20 Sep 2005 08:07:47 -0700,
David Boddie <[EMAIL PROTECTED]> screamed:
> You could connect the currentChanged() or clicked() signals in your
> QListView to a slot in some other object (perhaps the parent of the
> QListView). When the signal is emitted, you can examine the state of
> the item passed to the slot.
>

Yes, but those signals don't let me distinguish between item change
and check/uncheck. I found the way - override QCheckListItem method
activate().

-- 
[ Artur M. Piwko : Pipen : AMP29-RIPE : RLU:100918 : From == Trap! : SIG:212B ]
[ 17:58:41 user up 10740 days,  5:53,  1 user, load average: 0.06, 0.06, 0.06 ]

 My computer NEVER cras
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: win32 service and time.sleep()

2005-09-20 Thread Steve Holden
rbt wrote:
> I have a win32 service written in Python. It works well. It sends a
> report of the status of the machine via email periodically. The one
> problem I have is this... while trying to send an email, the script
> loops until a send happens and then it breaks. Should it be unable to
> send, it sleeps for 10 minutes with time.sleep(600) and then wakes and
> tries again. This is when the problem occurs. I can't stop the service
> while the program is sleeping. When I try, it just hangs until a reboot.
> Can some suggest how to fix this?

One way would be to maintain a Queue.Queue containing the messages that 
need to be sent and, rather than sleeping to retry just retrying when 
enough time has elapsed. That way you can keep pumping messages and so 
on to your heart's content, though you will have to keep track of the 
messages still to be sent.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC www.holdenweb.com
PyCon TX 2006  www.pycon.org

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


Where is my exception

2005-09-20 Thread Laszlo Zsolt Nagy
I have this code in a wxWidgets program:

class HtmlHintWindow(wx.Frame):
def __init__(self,pos,hint,config):
global _current_hint_window
# Determine the size of the screen
self.screensize = wx.ClientDisplayRect()[2:]
# Calculate the size of the hint ;-)
self.renderer = MegaXMLRenderer()
self.renderer.LoadStyle(config.style)
self.cookie, self.parsed_xml = self.renderer.Parse(hint)
print "point 1"
try:
self.image = self.renderer.Render(
self.cookie,
self.parsed_xml,
(0,0,self.screensize[0],self.screensize[1]),
draw=True
)
finally:
print "point 2"
raise

The program prints out "point 1" but it does not print "point 2". What 
am I missing?

   Les

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


Re: are variables local only to try/except blocks?

2005-09-20 Thread Steve Holden
BarrySearle wrote:
>  # Is this valid (or is excp local to try/except)?
>  try:
> try:
>doSomething1
>excp = 0

This block is problematic because excp won;t be set if doSomething1 
raises an exception.

> except:
>excp = 1
> #endTry
> if (_excp_): doSomething1 # is excp defined here?

Presumably you are expecting doSomething1 to fail or succeed in some 
non-deterministic way? Otherwise this will just raise the same exception 
again!

> excp = 0
>  except:
> excp = 1
> #endTry
> if (excp): doSomething2 # is excp defined here?
> 
> 
>  # valid, but more verbose (and maybe redundant?)
>  excp = 0
>  try:
> excp = 0
> try:
>doSomething1
>excp = 0  # reset incase future inner block
> except:
>excp = 1
> #endTry
> if (_excp_): doSomething1
> excp = 0  # reset incase inner block set excp=1
>  except:
> excp = 1
> #endTry
> if (excp): doSomething2
> 
> I am not so interested in what a particular version of the
> Python/Jython interpreter does, but rather what is "right".
> 
> Pls "CC" replies to [EMAIL PROTECTED] (as well as newsgroup)
> Barry Searle,[EMAIL PROTECTED]
> 
Your approach to exception handling is a little simplistic, resulting on 
code that reads about as well as a plate of spaghetti.

What are you actually trying to *do*? What problem do you need to solve?

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC www.holdenweb.com
PyCon TX 2006  www.pycon.org

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


Re: win32 service and time.sleep()

2005-09-20 Thread Laszlo Zsolt Nagy
rbt wrote:

>I have a win32 service written in Python. It works well. It sends a
>report of the status of the machine via email periodically. The one
>problem I have is this... while trying to send an email, the script
>loops until a send happens and then it breaks. Should it be unable to
>send, it sleeps for 10 minutes with time.sleep(600) and then wakes and
>tries again. This is when the problem occurs. I can't stop the service
>while the program is sleeping. When I try, it just hangs until a reboot.
>Can some suggest how to fix this?
>  
>
Yes. Generally, most of the win32 services work like this:

- the main thread listens to win32 service commands
- when starting the service, you should create a new worker thread that 
does the job for you
- when stopping the service, your service should report 
win32service.SERVICE_STOP_PENDING immediately, and ask the worker thread 
to terminate
- you should be continuously reporting win32service.SERVICE_STOP_PENDING 
until your workder thread has stopped

Here is a simple module that uses a 'Processor' class and a new thread 
to do the work.
(The full program is here: http://mess.hu/download/SimpleHTTPService.zip )

class Service(win32serviceutil.ServiceFramework):
_svc_name_ = SERVICE_NAME
_svc_display_name_ = SERVICE_DISPLAY
def __init__(self, args):
win32serviceutil.ServiceFramework.__init__(self, args)
self.stopped = threading.Event()
self.stopped.clear()
self.logger = getLogger(SERVICE_NAME)

def SvcStop(self):
self.logger.info("Got SvcStop, trying to stop service...")
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
self.stopped.set()

def SvcDoRun(self):
"""Write an event log record - in debug mode we will also see 
this message printed."""
try:
import servicemanager
servicemanager.LogMsg(
servicemanager.EVENTLOG_INFORMATION_TYPE,
servicemanager.PYS_SERVICE_STARTED,
(self._svc_name_, '')
)
self.logger.info("Started.")
self.logger.debug("Creating processor instance")
processor = Processor(self.stopped)
self.logger.debug("Starting processor thread")
thread.start_new_thread(processor.Process,())
self.logger.debug("Waiting for the processor thread to finish")
self.stopped.wait()
self.logger.debug("Stopping")
time.sleep(1)
while not processor.stopped.isSet():

self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING, 5000)
time.sleep(5)
servicemanager.LogMsg(
servicemanager.EVENTLOG_INFORMATION_TYPE,
servicemanager.PYS_SERVICE_STOPPED,
(self._svc_name_, "")
)
self.logger.info("Stopped")
except:
self.logger.error('',exc_info = sys.exc_info())


if __name__=='__main__':
win32serviceutil.HandleCommandLine(Service)
-- 
http://mail.python.org/mailman/listinfo/python-list


Dr. Dobb's Python-URL! - weekly Python news and links (Sep 19)

2005-09-20 Thread Diez B. Roggisch
QOTW:  "Python makes data-driven programming easy :-)" -- Kent

"Python rewards abstraction." -- Alex Martelli


As unicode becomes more and more prevalent, the issue of regular
expressions matching unicode character sets occurs more often. A
current thread has advice:
http://groups.google.com/group/comp.lang.python/msg/a4b7d3e24a514afd

Todd Steury learns about large float representations in python - and
that applying some algebra sometimes yields better results than the
naive approach:
http://groups.google.com/group/comp.lang.python/msg/7f5afb4976277ddc

pyparsing, the de-facto-standard for parser generation in python, is
available at version 1.3.3: 

http://groups.google.com/group/comp.lang.python.announce/msg/ff39b02ac712ac79

A new PyRex version addressing bugs ships:

http://groups.google.com/group/comp.lang.python.announce/msg/b30bd0575b6bd080

Metaclasses are so complicated as to make some of their artifacts
appear buggy - but luckily they aren't ...
http://groups.google.com/group/comp.lang.python/msg/a1190851125ce7b5

.NET 3.0 features provoke a discussion on python's nested-tuple
function arguments:
http://groups.google.com/group/comp.lang.python/msg/ee80ba95b76d76b

Stackless receives popular publicity for its gaming ability:

http://developers.slashdot.org/developers/05/09/17/182207.shtml?tid=156&tid=10
Note how dramatically memory-management perspectives can differ:
http://developers.slashdot.org/comments.pl?sid=162565&cid=13587741

Sudoku puzzles are fun to solve -- both "in real", and by writing
software solvers. Python-based solvers on different levels of
complexity can be seen here:
http://groups.google.com/group/comp.lang.python/msg/f7cb534119b877b9

Accessing COM-components from python is usually done with
win32com -- but in certain corner cases, comtypes serves you better
(or at all):
http://groups.google.com/group/comp.lang.python/msg/e4075543c2d30200

Creating histograms is a common problem -- another problem is which one
is the preferred way to do so:

http://groups.google.com/group/comp.lang.python/browse_frm/thread/60d405c5282ad36a/faa050cc5d76f6f0?q=dictionary&rnum=2#faa050cc5d76f6f0



Everything Python-related you want is probably one or two clicks away in
these pages:

Python.org's Python Language Website is the traditional
center of Pythonia
http://www.python.org
Notice especially the master FAQ
http://www.python.org/doc/FAQ.html

PythonWare complements the digest you're reading with the
marvelous daily python url
 http://www.pythonware.com/daily  
Mygale is a news-gathering webcrawler that specializes in (new)
World-Wide Web articles related to Python.
 http://www.awaretek.com/nowak/mygale.html 
While cosmetically similar, Mygale and the Daily Python-URL
are utterly different in their technologies and generally in
their results.

For far, FAR more Python reading than any one mind should
absorb, much of it quite interesting, several pages index
much of the universe of Pybloggers.
http://lowlife.jp/cgi-bin/moin.cgi/PythonProgrammersWeblog
http://www.planetpython.org/
http://mechanicalcat.net/pyblagg.html

comp.lang.python.announce announces new Python software.  Be
sure to scan this newsgroup weekly.

http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce

Steve Bethard, Tim Lesher, and Tony Meyer continue the marvelous
tradition early borne by Andrew Kuchling, Michael Hudson and Brett
Cannon of intelligently summarizing action on the python-dev mailing
list once every other week.
http://www.python.org/dev/summary/

The Python Package Index catalogues packages.
http://www.python.org/pypi/

The somewhat older Vaults of Parnassus ambitiously collects references
to all sorts of Python resources.
http://www.vex.net/~x/parnassus/   

Much of Python's real work takes place on Special-Interest Group
mailing lists
http://www.python.org/sigs/

Python Success Stories--from air-traffic control to on-line
match-making--can inspire you or decision-makers to whom you're
subject with a vision of what the language makes practical.
http://www.pythonology.com/success

The Python Software Foundation (PSF) has replaced the Python
Consortium as an independent nexus of activity.  It has official
responsibility for Python's development and maintenance. 
http://www.python.org/psf/
Among the ways you can support PSF is with a donation.
http://www.python.org/psf/donate.html

Kurt B. Kaiser publishes a weekly report on faults and patches.
http://w

Alternatives to Stackless Python?

2005-09-20 Thread [EMAIL PROTECTED]
After recently getting excited about the possibilities that stackless
python has to offer
(http://harkal.sylphis3d.com/2005/08/10/multithreaded-game-scripting-with-stackless-python/)
and then discovering that the most recent version of stackless
available on stackless.com was for python 2.2 I am wondering if
Stackless is dead/declining and if so, are there any viable
alternatives that exist today?

I found LGT http://lgt.berlios.de/ but it didn't seem as if the
NanoThreads module had the same capabilites as stackless.

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


Re: Two questions on PyDev for Eclipse

2005-09-20 Thread Fabio Zadrozny
Hi,

for 2: as far as I know, eclipse must have 'local', or at least 
'emulated' local access, so, if you have samba access, it should do what 
you want.

for 1... I use it a LOT without any problems for some really big 
projects ( with about 2.000 python modules -- not counting the python 
installation) -- but as I also develop it, so, I may be kind of 
impartial ;-)

Cheers,

Fabio

Kenneth McDonald wrote:

>The first is general; what are users' experience with PyDev for  
>Eclipse. It looks pretty good to me right now, but I've only started  
>playing with it. Converting to Eclipse is a major effort, and if  
>there are problems which would prevent pydev from being useful right  
>now, I'd certainly appreciate knowing about them.
>
>The second question is specific; is it possible to use Eclipse to  
>edit a remote file, i.e. through SFTP or something equivalent? My  
>current (limited) understanding of Eclipse is that it maintains an on- 
>disk directory of files in a project. Unfortunately, for what I'm  
>doing, a fair number of the files (mostly Python files) I'm editing  
>are on a remote server, so whatever editor I use, the ability to edit  
>remote files would be a big help.
>
>Thanks,
>Ken
>  
>


-- 
Fabio Zadrozny
--
Software Developer

ESSS - Engineering Simulation and Scientific Software
www.esss.com.br

PyDev - Python Development Enviroment for Eclipse
pydev.sf.net
pydev.blogspot.com


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


Re: Python Doc Problem Example: os.path.split

2005-09-20 Thread Steve Holden
Peter Hansen wrote:
> Diez B. Roggisch wrote:
[...]
>>But I stand by the nano-tube-narrow mind-set of Xah Lee. Besides his
>>tourette syndrome he also is simply unwilling to read documentation if
>>it is not what _he_ expects it to be.
> 
> 
> It's interesting to note that c.l.p still manages to give cordial and 
> helpful replies when his posts are not offensive ... in spite of us all 
> repeatedly being labelled "fuckers" and worse.
> 
That's the friendly fuckers on c.l.py for you ...

> I strongly suspect (and here I manage to get this on-topic, to the shock 
> of all) that he learned English from something written (apparently) by 
> Monty Python, and mistakenly thought this was how most people speak in 
> public (see http://www.sigg3.net/myself/fuck.html for but one copy).
> 
While this surmise does bring us close to being on-topic I fear you are 
being far more charitable than is justified here. But I *am* getting a 
bit fucking tired of his rather limited style of discourse.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC www.holdenweb.com
PyCon TX 2006  www.pycon.org

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


  1   2   >