RELEASE: twill-0.8.2

2006-02-07 Thread titus
ANNOUNCING twill v0.8.2.

twill is a simple language for browsing the Web.  It's designed for
automated testing of Web sites, but it can be used to interact with
Web sites in a variety of ways.  In particular, twill supports form
submission, cookies, redirects, and HTTP authentication.

A twill script to use the I'm feeling lucky button on Google looks
like this:

setlocal query twill Python

go http://www.google.com/

fv 1 q $query
submit btnI # use the I'm feeling lucky button

show

(Note that using this script abuses Google's Terms of Service.  So don't.)

This is the eighth public release of twill, version 0.8.2.

You can install twill with easy_install, or download this release at

http://darcs.idyll.org/~t/projects/twill-0.8.2.tar.gz

Documentation is included in the .tar.gz and is also online at

http://www.idyll.org/~t/www-tools/twill/

Miscellaneous details:

twill is implemented in Python and uses pyparsing and mechanize.  In
addition to the existing simple command language, twill can easily be
extended with Python.  twill also provides a fairly simple and
well-documented wrapper around mechanize.

twill does not understand JavaScript, I'm sorry to say.

---

New features:

  * added robust-ified form parsing code;

  * updated to latest mechanize, ClientForm, ClientCookie code;

  * updated to latest pyparsing code (1.4.1);

  * updated to latest wsgi_intercept code;

  * 'set_output' can now be used to redirect twill output specifically;

  * added execute_script function;

  * added return values to a number of the simple command-line functions;

  * fixed bugs in 'showlinks', 'go';

Backwards incompatibility issues:

  * changed tidy config option names;

  * wsgi_intercept code now wants a function that does its own app object
caching.
-- 
http://mail.python.org/mailman/listinfo/python-announce-list

Support the Python Software Foundation:
http://www.python.org/psf/donations.html


[ANN] Pydev 1.0.1 release

2006-02-07 Thread Fabio Zadrozny
Hi All,

Pydev Extensions version 1.0.1 has been released
More details at http://www.fabioz.com/pydev


Pydev - Python IDE (Python Development Enviroment for Eclipse) version 
1.0.1 has been released.
More details at http://pydev.sf.net


Details for Release: 1.0 .1:

This was a 'single bug' release (it fixes an out-of-memory error when 
restoring the interpreter).

Cheers,

Fabio


-- 
Fabio Zadrozny
--
Software Developer

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

Pydev Extensions
http://www.fabioz.com/pydev

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


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

Support the Python Software Foundation:
http://www.python.org/psf/donations.html


Re: Question about idioms for clearing a list

2006-02-07 Thread Raymond Hettinger
[Steven D'Aprano]
  The Zen isn't only one way to do it. If it were, we
  wouldn't need iterators, list comps or for loops,
  because they can all be handled with a while loop (at
  various costs of efficiency, clarity or obviousness).
 
  del L[:] works, but unless you are Dutch, it fails the
  obviousness test.

[Fredrik Lundh]
 unless you read some documentation, that is.  del on sequences
 and mappings is a pretty fundamental part of Python.  so are slicings.

 both are things that you're likely to need and learn long before you
 end up in situation where you need to be able to clear an aliased
 sequence.

Fred is exactly correct.  Slicing is absolutely basic to Python.
Accordingly, it gets covered right at the beginning of the tutorial
(section 3.1).  Likewise, the del keyword is fundamental -- if you
can't get, set, and del, then you need to go back to collections
school.

Also specious is the suggestion that dir(L) or help(L) is useless.  The
entries for the __delitem__ and __delslice__ methods are no more hidden
than for __getitem__ or __add__.  The help entry goes a step further
and shows the translation to del x[y] and del x[i:j].

While the sentiment behind the list.clear() suggestion is noble, it is
an exercise in futility to design a language around the presumption
that other programmers are incapable of learning the basics of the
language.

There was a pithy Tim Peters quotation to the effect that he was
unpersuaded by language proposals predicated on some hypothetical
average programmer not being smart enough to understand something that
the rest of us find to be basic.


Raymond Hettinger

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


how to copy a Python object

2006-02-07 Thread mitsura
Hi,

I am new to Python and OO programming.
I need to copy a Python object (of a class I made myself).
new_obj = old_object doesn't seem to work since apparently new_obj is
then a referrence to old_obj.

I found out that there is a module called 'copy' that allows you to do
a shallow or a deep copy.
I need a deep copy since my object contains dicts to other objects that
also need to be copied.

However, when I do new_object = copy.deepcopy(old_object) I get a
series of errors. The most important one:

TypeError: object.__new__(PySwigObject) is not safe, use
PySwigObject.__new__()


So any help much appreciated.

With kind regards,

Kris

I am using Python 2.4

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


Re: Compiling

2006-02-07 Thread Ravi Teja

Martin v. Löwis wrote:
 Ravi Teja wrote:
  But more often I am looking to use Python libraries
  in other languages since I am more familiar with them and they
  typically tend to be more high level (the way I like it) than the
  standard libraries of others.

 Ah. In that case, the normal C API should work fine to call into Python
 in most cases, no? If not, have you tried the CXX package, or
 Boost::Python?

I am aware of those. But my other languages are not C/C++. Sure I
could first wrap them in a DLL written in C/C++ using CXX/Boost and
then call the DLL from the language in question. But that is more
trouble than it is worth.

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


Re: Question about idioms for clearing a list

2006-02-07 Thread Raymond Hettinger
[EMAIL PROTECTED]
 In my programs I have seen that there is another practical difference
 between version 1 and 3:
 (1) mylist[:] = []
 (3) mylist = []
 If you create a big mylist again and again many times, the version 1
 uses the memory more efficiently (probably less work for the garbage
 collector), and the program can be (quite) faster (this is true in some
 implementations different from CPython too).

There should be almost no difference in runtime between the two.  The
underlying CPython implementation caches list objects and is usually
able to create the new list without any calls to the memory allocator.
Likewise, garbage collection performs the same for both -- any objects
left with no references are immediately freed and any with only
circular references get freed when the collector runs.

The speed-up you observed likely occured with different code.  For
instance, given a large list, you can typically update or replace
individual elements faster than you can build-up a new list:

  L = [0] * 1000 # starting list
  for i in xrange(len(L)):
  L[i] += 1

beats:

  L = [0] * 1000 # starting list
  L = [L[i]+1 for i in xrange(len(L))]


Raymond

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


Re: Best way of finding terminal width/height?

2006-02-07 Thread Joel Hedlund
 You might want to try just setting a flag in the signal handler
 to see if that prevents the I/O operations on stdin/stdout from
 being interrupted.

Tried this:

source

import signal, os, sys
from terminal_info import get_terminal_size

terminal_size = get_terminal_size()

_bTerminalSizeChanged = False

def report_terminal_size_change(signum, frame):
global _bTerminalSizeChanged
_bTerminalSizeChanged = True

def update_terminal_size():
global _bTerminalSizeChanged, terminal_size
terminal_size = get_terminal_size()
_bTerminalSizeChanged = False

signal.signal(signal.SIGWINCH, report_terminal_size_change)

while True:
# Do lots of IO (I'm trying to provoke exceptions with signal)
open('/a/large/file').read()
#raw_input()
#sys.stdin.read()
#print open('/a/large/file').read()

if _bTerminalSizeChanged:
update_terminal_size()
print terminal_size

/source

As before, the only IO case above that doesn't throw exceptions is the 
uncommented one. 

 Yup, that's the exception.  Standard practice is to catch it and
 retry the I/O operation.

Hmm... I guess it's not that easy to retry IO operations on pipes and streams 
(stdin/stdout in this case)... And I tend to lean pretty heavily on those since 
I usually write UNIX style text filters.

So in case I haven't missed something fundamental I guess my best option is to 
accept defeat (of sorts :-) and be happy with picking a terminal width at 
program startup.

But anyway, it's been really interesting trying this out. 

Thank you Grant (och Jorgen) for all help and tips!
/Joel
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Detecting line endings

2006-02-07 Thread Sybren Stuvel
Fuzzyman enlightened us with:
 This is what I came up with. [...] Comments/corrections welcomed.

You could use a little more comments in the code, but apart from that
it looks nice.

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: UTF16, BOM, and Windows Line endings

2006-02-07 Thread Fuzzyman

Neil Hodgson wrote:
 Fuzzyman:

  Thanks - so I need to decode to unicode and *then* split on line
  endings. Problem is, that means I can't use Python to handle line
  endings where I don't know the encoding in advance.
 
  In another thread I've posted a small function that *guesses* line
  endings in use.

 You can normalise line endings:

   x = a\r\nb\rc\nd\n\re
   y = x.replace(\r\n, \n).replace(\r,\n)
   y
 'a\nb\nc\nd\n\ne'
   print y
 a
 b
 c
 d

 e

 The empty line is because \n\r is 2 line ends.


Thanks - that works, but replaces *all* instances of '\r' to '\n' -
even if they aren't used as line terminators. (Unlikely perhaps). It
also doesn't tell me what line ending was used.

Apparently files opened in universal mode - 'rU' - have a  newline
attribute. That makes it a bit easier. :-)

Fuzzyman
http://www.voidspace.org.uk/python/index.shtml 


 Neil

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


Re: Detecting line endings

2006-02-07 Thread Fuzzyman

Alex Martelli wrote:
 Fuzzyman [EMAIL PROTECTED] wrote:

  Hello all,
 
  I'm trying to detect line endings used in text files. I *might* be
  decoding the files into unicode first (which may be encoded using

 Open the file with 'rU' mode, and check the file object's newline
 attribute.


Ha, so long as it works with Python 2.2, that makes things a bit
easier.

Rats, I liked that snippet of code (I'm a great fan of list
comprehensions).   :-)

  My worry is that if '\n' *doesn't* signify a line break on the Mac,

 It does, since a few years, since MacOSX is version of Unix to all
 practical intents and purposes.


I wondered if that might be the case. I think I've worried about this
more than enough now.

Thanks

Fuzzyman
http://www.voidspace.org.uk/python/index.shtml

 
 Alex

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


Re: Detecting line endings

2006-02-07 Thread Fuzzyman

Alex Martelli wrote:
 Fuzzyman [EMAIL PROTECTED] wrote:

  Hello all,
 
  I'm trying to detect line endings used in text files. I *might* be
  decoding the files into unicode first (which may be encoded using

 Open the file with 'rU' mode, and check the file object's newline
 attribute.


Do you know if this works for multi-byte encodings ? Do files have
metadata associated with them showing the line-ending in use ?

I suppose I could test this...

All the best,


Fuzzy

  My worry is that if '\n' *doesn't* signify a line break on the Mac,

 It does, since a few years, since MacOSX is version of Unix to all
 practical intents and purposes.
 
 
 Alex

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


Re: HTMLDocument and Xpath

2006-02-07 Thread swilson
Got the answer - there's a bug in xpath.  I think the HTML parser
converts all the tags (but not the attributes) to uppercase.  Xpath
definitely does not like my first string but, these work fine:

test = Evaluate('//TD', doc_node.documentElement)
test = Evaluate('/HTML/BODY/TABLE/TR/TD', doc_node.documentElement)
test = Evaluate('/HTML/BODY/TABLE/TR/TD[1]', doc_node.documentElement)

Shawn

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


[ANN] Pydev 1.0.1 release

2006-02-07 Thread Fabio Zadrozny
Hi All,

Pydev Extensions version 1.0.1 has been released
More details at http://www.fabioz.com/pydev


Pydev - Python IDE (Python Development Enviroment for Eclipse) version 
1.0.1 has been released.
More details at http://pydev.sf.net


Details for Release: 1.0 .1:

This was a 'single bug' release (it fixes an out-of-memory error when 
restoring the interpreter).

Cheers,

Fabio


-- 
Fabio Zadrozny
--
Software Developer

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

Pydev Extensions
http://www.fabioz.com/pydev

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


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


Re: python

2006-02-07 Thread Simon Brunning
On 2/6/06, Brain Murphy [EMAIL PROTECTED] wrote:
 I am new to python and programming but i was wondering, what can i program
 with python??
 Brian

Uh, that's a hard one to answer. You can program just about anything
in Python except device drivers and operating systems - and I'm
prepaired tlo be proved wrong on those last two.

What do you *want* to program?

--
Cheers,
Simon B,
[EMAIL PROTECTED],
http://www.brunningonline.net/simon/blog/
-- 
http://mail.python.org/mailman/listinfo/python-list


Great Job Board

2006-02-07 Thread ema32
--_NextPart_9763-0843-0CE6F984-7AA4
Content-Type: text/plain
Content-Transfer-Encoding: 7bit

There is a great job board located at the employment section of
http://www.4charlesson.com . So pass it on to anyone looking for a job.
--_NextPart_9763-0843-0CE6F984-7AA4--
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: winguiauto

2006-02-07 Thread Simon Brunning
On 30 Jan 2006 11:05:58 -0800, puff [EMAIL PROTECTED] wrote:
 There seem to be a number of winguiauto(s) available on the net.  Is
 there any 'offical' version?

Official? Hmm, dunno. ;-)

The version from my site is a bit old. I've escaped Windows now, so
I'm not doing any work on Windows automation any more, but others are
taking it forward. You might look at
http://www.tizmoi.net/watsup/intro.html or
http://sourceforge.net/projects/pywinauto.

--
Cheers,
Simon B,
[EMAIL PROTECTED],
http://www.brunningonline.net/simon/blog/
-- 
http://mail.python.org/mailman/listinfo/python-list


45 [XPost] Libero ADSL: Statene alla Larga!!! 454226

2006-02-07 Thread Belgian
Wind, Infostrada e Libero vi stanno fregando!

Si lamentano una serie di disservizi con eMule tra cui il blocco della 
navigazione internet qualora eMule sia funzionante, l'impossibilità di far 
funzionare Kademlia, distacchi continui dai server ed2k, velocità ridicole 
della linea stessa qualora miracolosamente si riesca a scaricare (e limitazioni 
a velocità prossime a quelle di un 56k anche per l'utilizzo di altri p2p).

Tutto questo deriva dall'applicazione di un sistema di limitazione del traffico 
P2P acquistato dai provider (vedi l'articolo In Italia prove di guerra al P2P 
su Punto Informatico) che si basa sull'analisi dei pacchetti (Forse questo?).
In particolare da sottolineare le affermazioni di un manager Cisco secondo qui 
Si tratta di una piattaforma hardware e software che è stata applicata per la 
prima volta in Giappone, con successo, per limitare l'impatto del traffico 
peer-to-peer. ... Permette ai provider di fare bandwidth shaping, blocking o 
redirezione di traffico per togliere banda alle applicazioni peer-to-peer e 
riservarne quindi di più ad altri servizi.

Tradotto: gli operatori ADSL vi stanno fregando e noi sappiamo perchè.

Wind stessa ha ammesso l'utilizzo di questa tecnologia su Libero (vedi Un 
bidone le ADSL 4 Megabit? di PI):
Da qualche giorno abbiamo attivato un engine che, in caso di traffico elevato, 
dà priorità a quello più prezioso per l'utenza residenziale: navigazione, 
posta, VoIP. Il tutto, a scapito del resto, per esempio del peer to peer.

Quando avete sottoscritto il contratto adsl avete ottenuto accesso a INTERNET 
senza alcuna limitazione. Oggi il P2P è parte di internet, anzi il 70% del 
traffico mondiale di dati è proprio per il P2P (tra cui eMule).
Bloccando il P2P le compagnie telefoniche vengono meno al contratto 
sottoscritto e spero che qualcuno più esperto di noi (magari uno dei tanti 
movimenti consumatori) si affretti a intentare qualche causa legale: certa 
gente conosce solo il linguaggio degli avvocati e dei soldi.
Non fatevi fregare. Il P2P non è illegale. E' illegale scaricare materiale 
protetto da copyright. Non possono bloccare il P2P e dirvi di non usarlo (una 
delle risposte stupide dei call center). E' come vietare i coltelli da cucina 
perchè potrebbero essere usati per uccidere le persone.

Certo che questo metodo è interessante. Invece di COMPRARE altre linee dalla 
Telecom per soddisfare il traffico dei loro utenti, queste compagnie cercano di 
STROZZARE gli utenti dando loro sempre meno.
Non contente, promettono velocità sempre più alte (24 Mbit???) che però potete 
usare solo per navigare sul www.
Peccato nessuno dica che per navigare sul web basta e avanza una adsl 640Kbps 
da 20 euro al mese.

Due sono le cose: o questi signori si affrettano a sbloccare le linee o fareste 
meglio a disdire e passare a provider che non effettuano queste limitazioni 
(Alice adsl attualmente non ha questi problemi).

Se volete esempi di mail di protesta ed alcuni indirizzi utili consultate: 
Protesta contro i filtri p2p di libero (http://www.liberop2p.p2pforum.it/) dove 
troverete anche una guida a disdire Libero ADSL.

Da: Free Internet




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

Re: Question about idioms for clearing a list

2006-02-07 Thread Ben Sizer
Raymond Hettinger wrote:
 [Steven D'Aprano]
   The Zen isn't only one way to do it. If it were, we
   wouldn't need iterators, list comps or for loops,
   because they can all be handled with a while loop (at
   various costs of efficiency, clarity or obviousness).
  
   del L[:] works, but unless you are Dutch, it fails the
   obviousness test.

 [Fredrik Lundh]
  unless you read some documentation, that is.  del on sequences
  and mappings is a pretty fundamental part of Python.  so are slicings.
 
  both are things that you're likely to need and learn long before you
  end up in situation where you need to be able to clear an aliased
  sequence.

 Fred is exactly correct.  Slicing is absolutely basic to Python.
 Accordingly, it gets covered right at the beginning of the tutorial
 (section 3.1).

Yes, right after UTF encoding details, complex numbers, and various
mentions of shell scripts. I don't want to criticise the hard work that
went into making the tutorial but let's not pretend it's the epitome of
documentation or even necessary the most obvious reference for users.

 Likewise, the del keyword is fundamental -- if you
 can't get, set, and del, then you need to go back to collections
 school.

I have hardly used the del keyword in several years of coding in
Python. Why should it magically spring to mind in this occasion?
Similarly I hardly ever find myself using slices, never mind in a
mutable context.

del L[:] is not obvious, especially given the existence of clear() in
dictionaries. I'm not necessarily requesting a clear() method, but I am
requesting a little more understanding towards those who expected one.
The list interface is full of redundant convenience methods, so one
more would hardly be a surprise or an unreasonable thing for people to
expect. Again we unfortunately have a bit of an attitude problem
towards anyone posting here that doesn't know whatever the experts
think is obvious.

-- 
Ben Sizer

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


Re: fairly large webapp: from Java to Python. experiences?

2006-02-07 Thread bruno at modulix
[EMAIL PROTECTED] wrote:

(snip)

 Does anyone here have any experience with large(ish) webapps in Python?

Depends on the definition of large(ish). If you use KLOC as a metric,
you can expect a Python solution to be 5 to 10 time smaller, so what's a
'large' app in Java may end up as a small/medium app with Python !-)

 I was sniffing around the following A-team of toolkits: CherryPy,
 Cheetah, SQLObject, all behind Apache2. 

If you plan to run behind Apache2, you may want to have a look at
Myghty. It's somewhere between a framework and a templating system, and
the architecture is based on Perl's HTML::Mason, which has proven to be
successful. It adds to Mason the possibility to take a clean MVC
approach (as well as the more ServerPage oriented approach of Mason),
and can be deployed as either a mod_python handler, fastcgi, plain old
cgi, WSGI, and even as a standalone app (with a Python HTTPServer) for
developpement.

You may also want to take a look at Turbogears (CherryPy + SQLObject +
Kid + Mochikit) or Subway (CherryPy + SQLObject + Cheetah).


 Has anyone seen performance
 issues with Python webapps?

Actually, only with Plone or CPS (or other ZopeCMF based app). Zope
itself is pretty usable, but the whole CMF part is a monstruosity IMHO.

 Could one reasonably expect to have an easier time with maintainence
 and future modifications with using Python over Java?

Err... It of course depends on first having well written code and a
sensible design, but when it comes to agility - and as long as you stay
away from Zope's CMF !-) -, I bet that Python beats Java hands down.

 Any tips, stories, recommendations, and/or experiences are most
 welcome.

It took me about one month to write my first Zope application - an
ad-hoc mix of an online catalog and basic CMS (pages, news,
downloadables files, ...), with LDAP and PostgresSQL in the mix,
fulltext and advanced search, newsletter subscription, a 'members' zone
etc. I had to learn Zope during the process, and I guess I could
actually rewrite the whole thing in less than 2 weeks with a much better
design - but what, the app is in production for 2 years with near zero
corrective maintenance (the biggest problem we had was with system
updates messing with the psycopg adapter...), gives full satisfaction to
the customer, and has for now proven to be  very easy to modify and
evolve (so easy that we didn't even bothered to bill the customer for
much of the modification requests)...  And Zope is certainly not known
as the most agile or lightweight Python web framework/application server !-)



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


Re: Accessing Windows Serial Port

2006-02-07 Thread malv
Hi All,
Would anybody know whether PySerial would work over an usb/serial
adapter?
(what about usb/parallel adapters?)
Thx.
malv

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


Re: how to copy a Python object

2006-02-07 Thread [EMAIL PROTECTED]

[EMAIL PROTECTED] a écrit :

 Hi,

 I am new to Python and OO programming.
 I need to copy a Python object (of a class I made myself).
 new_obj = old_object doesn't seem to work since apparently new_obj is
 then a referrence to old_obj.

it is


 I found out that there is a module called 'copy' that allows you to do
 a shallow or a deep copy.
 I need a deep copy since my object contains dicts to other objects that
 also need to be copied.

yes but ...


 However, when I do new_object = copy.deepcopy(old_object) I get a
 series of errors. The most important one:
 
 TypeError: object.__new__(PySwigObject) is not safe, use
 PySwigObject.__new__()
 

you see ?
that illustrates there is no general solution to the deep copy problem


 So any help much appreciated.

just provide your own copy() operator on your class
you and only you can know how deep you want to copy things (it just
depends on the nature of said things)

 
 With kind regards,
 
 Kris
 
 I am using Python 2.4

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


Re: how to copy a Python object

2006-02-07 Thread mitsura
Already thanks for the reply,

but how to write your own copy operator? Won't you always be passing
referrences to new_obj?

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


Re: python

2006-02-07 Thread Salvatore
A new OS in Python :
http://unununium.org/introduction  :-)

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


Re: Code Feedback

2006-02-07 Thread mwt

Jorgen Grahn wrote:
 You might want to look into using doc strings properly. You have comments at
 the start of functions, but they read more like implementation notes than
 what this method does and why. But I only had a quick look.

Yeah. They were just my scaffolding notes to myself.

I'd hurry up with that Conrad if I were you, and get on with the
Hemingway. ;)

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


ftp: get list of files

2006-02-07 Thread eels
Hello,

I want to get a listing of my files at web server with ftp. I wantn 't
download the files.
With yyy = ftp.retrlines('LIST') I get this listing at stdout, but I
need this information at variable yyy.
How can I resolve this problem?

Thank's for your hints, Thomas

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


Re: get list of files

2006-02-07 Thread Fredrik Lundh
eels wrote:

 I want to get a listing of my files at web server with ftp. I wantn 't
 download the files.
 With yyy = ftp.retrlines('LIST') I get this listing at stdout, but I
 need this information at variable yyy.
 How can I resolve this problem?

as mentioned in the documentation, you need to provide a callback if
you want to collect the data from a retr operation.

   yyy = []
   ftp.retrlines(LIST, yyy.append)

should do the trick.

(also see the dir and nlst methods)

/F



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


Re: ftp: get list of files

2006-02-07 Thread Lawrence Oluyede
eels [EMAIL PROTECTED] writes:

 With yyy = ftp.retrlines('LIST') I get this listing at stdout, but I
 need this information at variable yyy.
 How can I resolve this problem?

As written in the doc retrlines has an optional parameter (a callback function)
called on each line retrieved, so you can do something like this:

from ftplib import FTP

def writeline(data):
fd.write(data + \n)

f = FTP('ftp.kernel.org')
f.login()

f.cwd('/pub/linux/kernel')
fd = open('README', 'wt')
f.retrlines('RETR README', writeline)
fd.close()
f.quit()


-- 
Lawrence - http://www.oluyede.org/blog
Anyone can freely use whatever he wants but the light at the end
of the tunnel for most of his problems is Python
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: RPy / R

2006-02-07 Thread Hans Georg Krauthaeuser
jason schrieb:
 Hello:
 
 I installed the following:
 
 python-2.4.2.msi
 pywin32-207.win32-py2.4.exe
 R-2.2.1-win32.exe
 rpy-0.4.6-R-2.0.0-to-2.2.1-py24.win32.exe
 
 on a Windows XP (SP2) box.
 
 When I try to run the following (source: 
 http://rpy.sourceforge.net/plotting-with-RPy.html) in IDLE
 
from rpy import *
x = range(0, 10)
y = [ 2*i for i in x ]
r.plot_default(x, y)

Jason,

the example runs here without problems.

My configuration:

Python 2.3.5 (#2, Aug 30 2005, 15:50:26)
[GCC 4.0.2 20050821 (prerelease) (Debian 4.0.1-6)] on linux2
Type copyright, credits or license() for more information.

 r.version
{'status': '', 'major': '2', 'language': 'R', 'os': 'linux-gnu', 'svn
rev': '36812', 'system': 'i486, linux-gnu', 'month': '12', 'platform':
'i486-pc-linux-gnu', 'year': '2005', 'arch': 'i486', 'day': '20',
'minor': '2.1'}

Seems to be a problem with your installation...

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


Re: get list of files

2006-02-07 Thread eels
Hello Fredrik,

thank's for your quick help.
Greetings Eels

Fredrik Lundh schrieb:

 eels wrote:

  I want to get a listing of my files at web server with ftp. I wantn 't
  download the files.
  With yyy = ftp.retrlines('LIST') I get this listing at stdout, but I
  need this information at variable yyy.
  How can I resolve this problem?

 as mentioned in the documentation, you need to provide a callback if
 you want to collect the data from a retr operation.

yyy = []
ftp.retrlines(LIST, yyy.append)

 should do the trick.
 
 (also see the dir and nlst methods)
 
 /F

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


Re: how to copy a Python object

2006-02-07 Thread Schüle Daniel
[EMAIL PROTECTED] wrote:
 Already thanks for the reply,
 
 but how to write your own copy operator? Won't you always be passing
 referrences to new_obj?

for example this would work

  class X(object):
... def __init__(self,lst):
... self.lst = lst
... def copy(self):
... return X(self.lst[:])
... def __str__(self):
... return lst has id %i % id(self.lst)
...
  x=X([1,2,3])
  y=x.copy()
  print x
lst has id 1078097132
  print y
lst has id 1078097228


but I don't like that in this case self.lst must be passed
through __init__
I can think of another variant

  class Y(object):
... def fill(self):
... self.lst = [randint(i*10,(i+1)*10) for i in xrange(5)]
... def __repr__(self):
... return lst has id = %i % id(self.lst)
... def copy(self):
... ret = Y()
... ret.lst = self.lst[:]
... return ret
...
  from random import randint
  y=Y()
  y.fill()
  y
lst has id = 1078097452
  print y
lst has id = 1078097452
  x=y.copy()
  x
lst has id = 1078097004

... anyone?
are there better approaches?

Regards, Daniel

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


Re: python

2006-02-07 Thread Steve Holden
Salvatore wrote:
 A new OS in Python :
 http://unununium.org/introduction  :-)
 
That page includes:


Is the project dead?

Maybe. Very little code was written in 2005. 2006 so far does not look 
better. What code has been written isn't very useful. ...


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

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


Re: Detecting line endings

2006-02-07 Thread Arthur
Alex Martelli wrote:
 Fuzzyman [EMAIL PROTECTED] wrote:
 
 
Hello all,

I'm trying to detect line endings used in text files. I *might* be
decoding the files into unicode first (which may be encoded using
 
 
 Open the file with 'rU' mode, and check the file object's newline
 attribute.

Do you think it would be sensible to have file.readline in universal 
newline support by default?

I just got flummoxed by this issue, working with a (pre-alpha) package 
by very experienced Python programmers who sent file.readline to 
tokenizer.py without universal newline support.  Went on a long (and 
educational) journey trying to figure out why my file was not being 
processed as expected.

Are there circumstances that it would be sensible to have tokenizer 
process files without universal newline support?

The result here was having tokenizer detect indentation inconstancies 
that did not exist - in the sense that the files were compiled and ran 
fine by Python.exe.

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


Re: Detecting line endings

2006-02-07 Thread Arthur
Arthur wrote:
 Alex Martelli wrote:
 
 I just got flummoxed by this issue, working with a (pre-alpha) package 
 by very experienced Python programmers who sent file.readline to 
 tokenizer.py without universal newline support.  Went on a long (and 
 educational) journey trying to figure out why my file was not being 
 processed as expected.

For example, the widely used MoinMoin source code colorizer sends files 
to tokenizer without universal newline support:

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

Is my premise that tokenizer needs universal newline support to be 
reliable correct?

What else could put it out of sync with the complier?

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


Re: Unable to get PIL to load jpeg images

2006-02-07 Thread peter . mosley
Someone out there must surely know - please!

Peter

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


Re: Question about idioms for clearing a list

2006-02-07 Thread Steve Holden
Raymond Hettinger wrote:
 [Steven D'Aprano]
[...]
 
 While the sentiment behind the list.clear() suggestion is noble, it is
 an exercise in futility to design a language around the presumption
 that other programmers are incapable of learning the basics of the
 language.
 
+1 QOTW

 There was a pithy Tim Peters quotation to the effect that he was
 unpersuaded by language proposals predicated on some hypothetical
 average programmer not being smart enough to understand something that
 the rest of us find to be basic.
 
Well, for those who can't find it you just provided a fairly pithy 
Raymond Hettinger quote :-)

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

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


Re: Accessing Windows Serial Port

2006-02-07 Thread Roel Schroeven
malv schreef:
 Hi All,
 Would anybody know whether PySerial would work over an usb/serial
 adapter?

If the driver for the adapter creates a virtual COM-port (i.e. it shows 
up as a serial port in Windows' device manager), it works. The software 
sees no difference between a real port and a fake one.

 (what about usb/parallel adapters?)

Never tried it, but I guess it will work too.

-- 
If I have been able to see further, it was only because I stood
on the shoulders of giants.  -- Isaac Newton

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


Natural Language Date Processing.

2006-02-07 Thread Andrew Gwozdziewycz
I've been looking recently for date processing modules that can parse  
dates in forms such as
next week or 6 days from next sunday.  PHP has a function that  
will do this called 'strtotime',
but I have not found a Python implementation. I've check the standard  
date, datetime and time
modules and also mx.Date* modules. Am I overlooking something here or  
does it not exist?
Anyone know of an implementation? Also, I realize that this is  
perhaps very English specific
so I apologize to any non-native English speakers.

---
Andrew Gwozdziewycz
[EMAIL PROTECTED]
http://ihadagreatview.org
http://plasticandroid.org


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


Re: Unable to get PIL to load jpeg images

2006-02-07 Thread Steve Holden
[EMAIL PROTECTED] wrote:
 Someone out there must surely know - please!
 
 Peter
 
Try image-sig@python.org - or better still, subscribe to the image SIG 
mailing list (then you'll see replies ...)

I've never had any problems loading JPEG images. It's probably a setup 
issue.

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

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


Tkinter: is there a has_focus method or property for a window?

2006-02-07 Thread Harlin Seritt
I have two windows. One is a main config window. The other is an 'Add
Setting' window. Both are using two different classes.

Once the Add Setting button is clicked on the Add Setting window, the
setting is written to file. At that time the main config window should
update its setting listing but it doesn't because it doesn't know it
should.

I do notice that when the Add Setting window closes, the focus goes
right back to the main config window. Is there a has focus event that
can trigger a command for this window?

Also, if there is another way to get this done, I am open to
suggestions.

Thanks,

Harlin Seritt

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


Re: Strange behavior with os call in cgi script

2006-02-07 Thread Jim
 But I do think that adding logging to a cgi script is a sensible thing to
 do for a beginner.
Let me second that.  I happen to write a lot of CGI, and ISTM that
while you can do it without logging, you are condemming yourself to a
lot of staring at the screen, head-scratching, and saying ``Now what
could *that* mean?''  That is, CGI programming without logging seems to
me to ba a lot like general programming in Perl.  :-}

Jim

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


Re: how to copy a Python object

2006-02-07 Thread Juho Schultz
[EMAIL PROTECTED] wrote:
 Already thanks for the reply,
 
 but how to write your own copy operator? Won't you always be passing
 referrences to new_obj?
 

If you need to modify the behaviour of copy or deepcopy, you can give 
your class __copy__ and __deepcopy__ methods. Then copy.copy and 
copy.deepcopy will use these. As a silly example, you could use:

def __copy__(self):
 raise IOError, 'Permission denied.'

http://www.python.org/doc/2.4.2/lib/module-copy.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Code Feedback

2006-02-07 Thread Sion Arrowsmith
mwt [EMAIL PROTECTED] wrote:
1) Is this good Python code? What should be changed to make it more
Pythonesque?

while not len(self.stacks)  0:

while not self.stacks:

An empty list is considered to be false, hence testing the list
itself is the same as testing len(l)  0 .

-- 
\S -- [EMAIL PROTECTED] -- http://www.chaos.org.uk/~sion/
  ___  |  Frankly I have no feelings towards penguins one way or the other
  \X/  |-- Arthur C. Clarke
   her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Question about idioms for clearing a list

2006-02-07 Thread Arthur
Raymond Hettinger wrote:
 
 There was a pithy Tim Peters quotation to the effect that he was
 unpersuaded by language proposals predicated on some hypothetical
 average programmer not being smart enough to understand something that
 the rest of us find to be basic.

Peters pithy ;)

As someone coming to Python as a well less than the average programmer, 
I agree wholeheartedly with Mr. Peters.

My ability to grok Python to any extent, from that starting point, was 
based on an understanding that it was my responsibility to come to 
Python, not it to me. And concerted, almost obsessive effort, And time.

OTOH - because of exactly these factors - I have actively resented and 
resisted promulgation of the Python is Easy meme.

Pity that this stance has separated me from a sense of belonging to the 
community, which seems to so highly value that meme.

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


Using RAW_SOCKETS on win XP SP2

2006-02-07 Thread billie
Hi all. I'd need to send a TCP SYN packet having a certain string as 
payload. I'm
using Python and an high level packet building library called Impacket to
build TCP and IP datagrams. I wrote this simple code that works on Linux but 
not on Windows XP SP2, probably because of SP2 security limitations. Do you 
got any idea about how could I solve this problem?
I found an article of Fyodor (author of nmap port scanner) about how to
solve this kind of SP2 limitations:
http://seclists.org/lists/nmap-hackers/2004/Jul-Sep/0003.html
...that says:

 Instead of sending raw IP packets, we move one layer down and send our
 raw IP packets in raw ethernet frames.

Do you got any idea about how could I implement a stuff like this?

Best regards.


from impacket import ImpactPacket
from socket import *

src = '10.0.0.1'
dst = '10.0.0.25'

s = socket(AF_INET, SOCK_RAW, IPPROTO_TCP)
s.setsockopt(IPPROTO_IP, IP_HDRINCL, 1)

ip = ImpactPacket.IP()
ip.set_ip_src(src)
ip.set_ip_dst(dst)

tcp = ImpactPacket.TCP()
tcp.set_SYN()
tcp.set_th_sport(43749)
tcp.set_th_dport(1000)
tcp.contains(ImpactPacket.Data('hello there'))

ip.contains(tcp)

s.sendto(ip.get_packet(), (dst, 0))


++  ERROR ++

s.sendto(ip.get_packet(), (dst, 0))
socket.error: (10022, 'Invalid argument')



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


Re: in over my head ascii

2006-02-07 Thread nephish
i'm not sure, but its kinda been a pain in the hinder for a newbie like
me to find it in their docs.
thanks for all the help guys, let you know how it goes

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


Re: Problem with odbc (pywin32) and unicode

2006-02-07 Thread Frank Millman

Frank Millman wrote:
 Hi all

 I am using odbc from pywin32 to connect to MS SQL Server. I am changing
 my program from the old (incorrect) style of embedding values in the
 SQL command to the new (correct) style of passing the values as
 parameters. I have hit a problem.

 The following all work -
 cur.execute(select * from users where userid = '%s' % 'frank')  #
 old style
 cur.execute(select * from users where userid = '%s' % u'frank')
 # old style
 cur.execute(select * from users where userid = ?, ['frank'])  #
 new style

 This does not work -
 cur.execute(select * from users where userid = ?, [u'frank'])  #
 new style

 I get the following error -
 OdbcError: Found an insert row that didn't have 1 columns [sic]

 It is the combination of new style and unicode that does not work.

 I realise that odbc is not fully DB-API compliant, but I have got away
 with it up to now. Does anyone know of a solution to this problem?

 Thanks

 Frank Millman


I am pleased to report that this has been fixed.

I have been liaising with Mark Hammond, and he has sent me a revised
version which behaves correctly.

This is from Mark -

I'd be happy for you to mention this fix will be in build 208 - I just
can't tell you when that will be :)

Frank

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


Re: How to I write DBASE files without ODBC

2006-02-07 Thread Larry Bates
Durumdara wrote:
 Hi !
 
 I have a text processor code and I want to put the results to standard
 files.
 HTML, XML, SQLite - they are ok.
 
 But I want to put these datas to DBF too, because when records are many,
 does not fit in Excel table (load from HTML). XML and SQLite need some
 development to get datas.
 
 I need some memo fields, not only standard field types. The fixed DBASE
 tables are simply writeable, but for memo I need some tool.
 ODBC is good for this, but I want to create standalone exe, without
 installation, and ODBC must be manually set...
 
 Can anybody known about DBASE handler module for Python ?
 
 Thanx for help: dd
 
 
 
We use py2exe and Inno Setup to create a setup.exe installation
program.  Part of the installation in Inno is to create the ODBC
object in the registry that is necessary for the program to access
ODBC data source.  All I did was to observe the changes in the
registry before and after manually setting up a ODBC datasource
and put that code in my Inno script.  Works like a charm.

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


Pythonwin - problem with non English character

2006-02-07 Thread Lad
Hello,
is there a way how to use PythonWin for editting of Python files that
consist non English characters? In my Python scripts I need to use(
print) Cyrilic characters and with PythonWin it is not possible . I use

PythonWin 2.3.4 (#53, May 25 2004, 21:17:02) [MSC v.1200 32 bit
(Intel)] on win32.
Thank you
L.

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


Re: Question about idioms for clearing a list

2006-02-07 Thread Ed Singleton
On 7 Feb 2006 00:27:05 -0800, Raymond Hettinger [EMAIL PROTECTED] wrote:

 There was a pithy Tim Peters quotation to the effect that he was
 unpersuaded by language proposals predicated on some hypothetical
 average programmer not being smart enough to understand something that
 the rest of us find to be basic.

The problem is that the average programmer in question isn't
hypothetical in this case.

I'm a fairly average programmer (better than average compared to my
immediate colleagues).  I've read every tutorial I can get my hands
on, but I have no _memory_  of ever coming across the del keyword, let
alone that it is fundamental to Python, and I have no idea what
collections school is.  I doubtless have read of it at some point, but
as no importance has ever been attached to it, I have probably not
remembered it.

Similarly, I remember slices simply because they are handy, not
because I have ever heard of them being fundamental before.

(I don't argue their fundamentalness one way or other, it's just that
you seem to think that all people who have learned Python have some
knowledge of this hugely important feature).

The other problem with your use of the quote is that the smartness of
the average programmer, or their ability to understand the feature, is
not in question.  It is their ability to know of the existence of the
feature, or to find out about it.

As a general rule of thumb, I would say that if a person is struggling
with a language, it is primarily a problem with the language, and than
problem with the documentation, and lastly a problem with the person.

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


Re: Question about idioms for clearing a list

2006-02-07 Thread Fredrik Lundh
Steve Holden wrote:

 While the sentiment behind the list.clear() suggestion is noble, it is
 an exercise in futility to design a language around the presumption
 that other programmers are incapable of learning the basics of the
 language.

 +1 QOTW

 There was a pithy Tim Peters quotation to the effect that he was
 unpersuaded by language proposals predicated on some hypothetical
 average programmer not being smart enough to understand something that
 the rest of us find to be basic.

 Well, for those who can't find it you just provided a fairly pithy
 Raymond Hettinger quote :-)

for the record, the original quote is:

The of course, while *I* have no problem with this at all, it's
surely too much for a lesser being flavor of argument always rings
hollow to me. Are you personally confused by the meanings for + that
exist today? *Objecting* to the variations is a different story; I'm
wondering whether you personally stumble over them in practice. I
don't; Steven doesn't; I doubt that you do either. I'm betting that
almost *nobody* ever does, in which case those less nimble colleagues
and students must be supernaturally feeble to merit such concern.
  -- Tim Peters, 29 Apr 1998

/F 



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


Re: Question about idioms for clearing a list

2006-02-07 Thread Ed Singleton
On 7 Feb 2006 02:02:42 -0800, Ben Sizer [EMAIL PROTECTED] wrote:
  Fred is exactly correct.  Slicing is absolutely basic to Python.
  Accordingly, it gets covered right at the beginning of the tutorial
  (section 3.1).

 Yes, right after UTF encoding details, complex numbers, and various
 mentions of shell scripts.

Now that is GPotD (Good Point of the Day) which is much better than
QotW as it's actually useful.

 I don't want to criticise the hard work that
 went into making the tutorial but let's not pretend it's the epitome of
 documentation or even necessary the most obvious reference for users.

  Likewise, the del keyword is fundamental -- if you
  can't get, set, and del, then you need to go back to collections
  school.

 I have hardly used the del keyword in several years of coding in
 Python. Why should it magically spring to mind in this occasion?
 Similarly I hardly ever find myself using slices, never mind in a
 mutable context.

 del L[:] is not obvious, especially given the existence of clear() in
 dictionaries. I'm not necessarily requesting a clear() method, but I am
 requesting a little more understanding towards those who expected one.
 The list interface is full of redundant convenience methods, so one
 more would hardly be a surprise or an unreasonable thing for people to
 expect. Again we unfortunately have a bit of an attitude problem
 towards anyone posting here that doesn't know whatever the experts
 think is obvious.

I agree wholeheartedly with this, particularly as there often seems to
be strong (and confusing) resistance to making Python easier and more
obvious.  I can only assume that it is by people who have forgotten
what it is like to be an average programmer.  (Paul Graham constantly
makes the same mistake when he goes on about how everyone should use
lisp).

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


Re: how to kill a python process?

2006-02-07 Thread MackS
Hi Jorgen

THanks for your help. I began writing a wrapper around python did (as
Donn suggested), but then noticed that this was due to not having
educated myself on the options you can pass to ps, pidof and top:

running pidof -x and using the 'c' command in top work pretty nicely.
That way I no longer see 23 'pythons' in the system : ) and know which
one to stop.

Mack

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


Re: Question about idioms for clearing a list

2006-02-07 Thread André
Ed Singleton wrote:

 I'm a fairly average programmer (better than average compared to my
 immediate colleagues).  I've read every tutorial I can get my hands
 on, but I have no _memory_  of ever coming across the del keyword, let
 alone that it is fundamental to Python, and I have no idea what
 collections school is.  I doubtless have read of it at some point, but
 as no importance has ever been attached to it, I have probably not
 remembered it.

I'm probably below average as a programmer, except when compared with
my immediate colleagues [1].  I wrote an extremely simple (albeit
non-conventional) tutorial on learning how to program with Python,
partly as a means to learn Python myself.  (Google for rur-ple if you
are curious.)  I introduced del shortly after I introduced lists.  I
think it is important that one learns at least a couple of example
usage of every Python keyword as soon as possible, before attempting to
write complicated programs.  The same probably goes for built-in
functions.

André

[1] Because I have none.

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


Re: Accessing Windows Serial Port

2006-02-07 Thread Grant Edwards
On 2006-02-07, malv [EMAIL PROTECTED] wrote:
 Hi All,
 Would anybody know whether PySerial would work over an usb/serial
 adapter?

Yes.

 (what about usb/parallel adapters?)

Don't know.

-- 
Grant Edwards   grante Yow!  I'm an East Side
  at   TYPE...
   visi.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: variables preceeded with @

2006-02-07 Thread Diez B. Roggisch
Thomas Girod wrote:

 Hello there.
 
 I recently started looking at turbogears and I found code such as :
 
  class Root(controllers.Root):
  @turbogears.expose(html=blog.templates.accueil)
  def index(self,**kw):
  return dict()
 
 
 What is this @ ? I looked around but couldn't find any references to
 this syntax.

It is called a decorator syntax, and is basically syntactic sugar for the
following:

class Foo(object):
def bar(self):
pass

bar = decorate(bar)

is 

class Foo(object):
@decorate
def bar(self):
pass


You can also have parameterized decorators, as the ones in TG:

class Foo(object):
def bar(self):
pass

bar = decorate_with_args(some argument)(bar)

is 

class Foo(object):
@decorate_with_args(some argument)
def bar(self):
pass


I suggest you read this to get on speed with decorators:

http://www.phyast.pitt.edu/~micheles/python/documentation.html



Regards,

Diez

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


Re: Question about idioms for clearing a list

2006-02-07 Thread Arthur
Arthur wrote:
 
 My ability to grok Python to any extent, from that starting point, was 
 based on an understanding that it was my responsibility to come to 
 Python, not it to me. And concerted, almost obsessive effort, And time.
 
 OTOH - because of exactly these factors - I have actively resented and 
 resisted promulgation of the Python is Easy meme.
 
 Pity that this stance has separated me from a sense of belonging to the 
 community, which seems to so highly value that meme.

What Python *is*, to me, is a game worth playing.  Not something I come 
across all that often.  And easy games, almost invariably, are not.

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


Re: * 'struct-like' list *

2006-02-07 Thread Ernesto
Thanks for the approach.  I decided to use regular expressions.  I'm
going by the code you posted (below).  I replaced the line re.findall
line with my file handle read( ) like this:

print re.findall(pattern, myFileHandle.read())

This prints out only brackets [].  Is a 're.compile' perhaps necessary
?


Raymond Hettinger wrote:

 # Approach for more loosely formatted inputs
 import re
 pattern = '''(?x)
 Name:\s+(\w+)\s+
 Age:\s+(\d+)\s+
 Birthday:\s+(\d+)\s+
 SocialSecurity:\s+(\d+)
 '''
 print re.findall(pattern, inputData)

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


Re: Natural Language Date Processing.

2006-02-07 Thread Andrew Gwozdziewycz
On 7 Feb 2006 05:51:40 -0800, [EMAIL PROTECTED]
 It seems that the string to be parsed has to be provided in the GNU
 date format.  One option would be to provide a function that calls out
 to the the GNU date program with whatever string you want to parse.

Actually, I looked at the source of the php function and it manually
parses it (i assume according to the GNU date rules). However, i'd
prefer not to have to port the function to python if someone else has
already done so, or has a more pythonic implementation.


--
Andrew Gwozdziewycz [EMAIL PROTECTED]
http://ihadagreatview.org
http://plasticandroid.org
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Numeric and matlab

2006-02-07 Thread malv
A convincing experience is to 'translate' some substantial matlab
matrix code into python.
You will at once see the difference between a true programming language
and matlab

Further, also look at matplotlib.
malv

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


Re: * 'struct-like' list *

2006-02-07 Thread Schüle Daniel
Ernesto wrote:
 Thanks for the approach.  I decided to use regular expressions.  I'm
 going by the code you posted (below).  I replaced the line re.findall
 line with my file handle read( ) like this:
 
 print re.findall(pattern, myFileHandle.read())
 
 This prints out only brackets [].  Is a 're.compile' perhaps necessary
 ?

if you see [] that means findall didn't find anything
that would match your pattern
if you re.compile your pattern beforehand that
would not make findall find the matched text
it's only there for the optimization

consider
lines = [line for line in file(foo.txt).readlines() if 
re.match(r\d+,line)]

in this case it's better to pre-compile regexp one and use it
to match all lines

number = re.compile(r\d+)
lines = [line for line in file(foo.txt).readlines() if number.match(line)]

fire interactive python and play with re and patterns
speaking from own experience ... the propability is
against you that you will make pattern right on first time

Regards, Daniel

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


Re: Question about idioms for clearing a list

2006-02-07 Thread Raymond Hettinger
 I'm a fairly average programmer (better than average compared to my
 immediate colleagues).  I've read every tutorial I can get my hands
 on, but I have no _memory_  of ever coming across the del keyword, let
 alone that it is fundamental to Python,

My thought is that get/set/del are fundamental ops in almost any
computing context:  songs on your iPod playlist, records in a database,
files in a directory, or elements in a Python list.

Individual element deletion doesn't seem to come-up as much in Python
because we tend to build data collections and then throw them away in
their entirity.  However, the concept becomes more prominent when
dealing with persistence or when mutating a collection in-place.  The
OP was specifically seeking to do in-place modifications and so found
himself in need of understanding the del-statement.  IMHO, it goes with
the territory.



 Similarly, I remember slices simply because they are handy, not
 because I have ever heard of them being fundamental before.

FWIW, I regard slices to be fundamental to the language not because
they are easy or that everyone automatically knows about them; rather,
I am just recognizing that the concept of slices pervades the language
and comes up in many different guises.  It is a lesson that should not
be skipped. That is why I think that the OP's problem is better solved
by improved documentation than by adding an unnecessary method to the
list API.



 As a general rule of thumb, I would say that if a person is struggling
 with a language, it is primarily a problem with the language, and than
 problem with the documentation, and lastly a problem with the person.

I would swap the first two.  No language has yet been invented
(including HTML and LOGO) that someone doesn't struggle with.  In
contrast, no documentation has ever been written that couldn't be
improved.

The problem with the person part goes last only because it suggests
immutability.  The reality is that incomplete learning is a fixable
problem (independent of language or doc issues).  If I never learn the
del-statement, should I be surprised that I stuggle with how to express
deletion?



Raymond

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


Regular Expression Syntax Help

2006-02-07 Thread Ernesto
I'm trying to get the right syntax for my regular expression.  The
string I'm trying to parse is:

# myString
[USELESS DATA]
Name:  David Dude
[USELESS DATA]

Right now, I'm using the following code:


pattern_Name= '''(?x)
Title:\s+(\w+)\s+
'''
names = re.findall(pattern_Name, myString)
print names

This prints out a list containing only the first names.  I want to
search the string until it finds a '\n' endline, but I experimented
with that, and couldn't find what I need.

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


Re: winguiauto

2006-02-07 Thread puff
Thanks Simon.  I looked at the other two and ended up using your
version unmodified as the changes in watsup and pywinauto dealt with
things unique to their needs.  Your code still addresses basic needs
and rather well at that.

Regards

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


Re: variables preceeded with @

2006-02-07 Thread Thomas Girod
Yum, food for thoughts. Thanks Diez.

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


Uses of The 4th Dimension (New Discovery by The Human Race!)

2006-02-07 Thread use4d


Uses of The 4th Dimension (New Discovery by The Human Race!)



-


Note Before: Everything you read on this page is The Truth.
What does this mean?
It means, if you try to do what is written here:
EXAMPLE: If you just make a wish,
it will be granted in The 4th Dimension
for you to enjoy there.
You have nothing to lose.



-


Since I discovered The 4th Dimension, one of the conclusions
I have reached is, The 4th Dimension is an infinite access to The
Truth.
Throughout this website, I use the term I wish - it is really a way
to voice a person's desire - and from the work I have done - it really
works.

From the saying: Ask and you shall receive, I have understood that
any
human being can make an infinity of wishes and receive The Truth
(the correct answer) to every question they may have, in the form of a
dream
- that same night.


META-PHYSICISTS CALL THIS TECHNIQUE: PROGRAMMING YOUR SLEEP.

--
With this method, the saying becomes:
Ask (FOR THE TRUTH) and you shall receive
(THE TRUTH IN THE FORM OF A DREAM THAT NIGHT)!

What does this mean?
It means you can receive THE TRUTH to any question you have in
your heart - answered FREE while you sleep, you
wake up in the morning wiser because you have
understood The Truth you asked for!

It's like getting 100% to every quiz or test in school,
because a teacher really requires THE CORRECT ANSWER
or The Truth to the questions on the quiz/test!

What is 1+1? The Truth:2.


-

From my research, I have also seen that other people have also known
about this dimension and have kept silent about it.

They have been conducting activities that I will term criminal, this
is why I have included a tract for Law Enforcement, so that they
can become aware that this dimension exists and they can use it as a
tool
to acquire The Truth to solve any and all crimes.


-

Use The 4th Dimension to find your soulmate

This is very easy to do - all you need to know is
The Truth of WHO your soulmate is.

To find your soulmate, do the following:



-

Say this out loud before you go to sleep:
I WISH TO KNOW THE TRUTH:
WHO IS MY SOULMATE?



-

Go to sleep and you will get The Truth
in the form of a dream that night.

Once you find out The Truth, why waste anymore time?
When you wake up, go find him or her and be happy.



-

What if your soulmate is in another country or far away?

No ProblemUse The 4th Dimension to make contact..
that is, use it like a telephone or a chat room.

Here's how...

Once you find out WHO your soulmate is, contact
his/her mind via The 4th Dimension in this way:



-

Say this out loud before you go to sleep:
I WISH TO MEET MY SOULMATE.



-

Go to sleep and you will meet THE MIND of your
soulmate THAT NIGHT in the form of a dream.

What does this mean?

It means you are ACTUALLY SPEAKING MIND - TO - MIND
with your soulmate, so when you wake up in the morning
(that is, your minds re-enter your physical bodies)
you remember your meeting - it really took place!

Keep meeting in this way until you can meet in the physical world.



-

Use The 4th Dimension to NEVER BE LIED TO AGAIN

This is one of the best benefits of using The 4th Dimension.

You can use it to stop a lie, before it takes root in your mind.

If a lie takes root in a person's mind,
that person is manipulated by that lie and the liar.

Lies also wastes a person's time and energy.

To stop ALL LIES before they take root, do the following:

Say this out loud before you go to sleep:

I WISH TO KNOW THE TRUTH:
IS [ INSERT NAME OF PERSON HERE ] LYING TO ME?

Go to sleep and you will receive The Truth about your question that
night.

This tool is invaluable, because it helps you understand the motive
of anything presented to you in the physical world (3rd Dimension).



-

Use The 4th Dimension as a University [ get an education ]

You can know and learn anything and everything (no matter how old
you are ), your heart desires - FREE - the important thing is
- is that you are learning The Truth abouut any matter
or subject.

You can learn and understand: Physics,
Mathematics, Science, Engineering,
Botany, Medicine, etc

All you have to 

Re: * 'struct-like' list *

2006-02-07 Thread Ernesto
Thanks !

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


Re: Regular Expression Syntax Help

2006-02-07 Thread Ernesto
The word Title there should be Name.

What I really need is the pattern for getting the entire string after
Name:  until a '\n' is found.

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


Re: in over my head ascii

2006-02-07 Thread nephish
ok, i am stuck again.

from the docs, the byte stream is supposed to look like this:

'S' 'T' 'X'   [length indicator] [message type] [message] 'E' 'N' 'X'

the length indicator it says is a four byte integer number of a value N
 ( N would be how long the message body is )

the message type comes from a table in the docs. In my case, the
message type is 200. This is also supposed to be sent as  a 4 byte
value.

so. how do i make 200 occupy 4 bytes ?

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


Re: Detecting line endings

2006-02-07 Thread Bengt Richter
On 6 Feb 2006 06:35:14 -0800, Fuzzyman [EMAIL PROTECTED] wrote:

Hello all,

I'm trying to detect line endings used in text files. I *might* be
decoding the files into unicode first (which may be encoded using
multi-byte encodings) - which is why I'm not letting Python handle the
line endings.

Is the following safe and sane :

text = open('test.txt', 'rb').read()
if encoding:
text = text.decode(encoding)
ending = '\n' # default
if '\r\n' in text:
text = text.replace('\r\n', '\n')
ending = '\r\n'
elif '\n' in text:
ending = '\n'
elif '\r' in text:
text = text.replace('\r', '\n')
ending = '\r'


My worry is that if '\n' *doesn't* signify a line break on the Mac,
then it may exist in the body of the text - and trigger ``ending =
'\n'`` prematurely ?

Are you guaranteed that text bodies don't contain escape or quoting
mechanisms for binary data where it would be a mistake to convert
or delete an '\r' ? (E.g., I think XML CDATA might be an example).

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


Re: Collecting snmp data - threads, processes, twisted?

2006-02-07 Thread Mike C. Fletcher
Antal Rutz wrote:
...
 I'd like to collect snmp data from varoius network devices parallel.
   
...
 Could you give me some advice how can I make my script really parallel?

 My options maybe:
 1. pySNMP (as it's full in python)
 2. subprocess (I'd like to make (find) a solution as threadpool.py)
 (running yapsnmp, pySNMP or even net-snmp?...)
 3. TwistedSNMP (seems too weird for me.. cannot imagine a simple 
 solution for my problem)
   
This kind of parallel mass-query operation is TwistedSNMP's primary 
focus (it was created for a commercial product that scans thousands of 
agents).  If you really want all of the queries to run in parallel (i.e. 
send out all the queries within milliseconds of each other):

agents = [ ... ]
dl = []
for agent in agents:
dl.append( agent.get( (oid,oid,oid) ) )
return defer.DeferredList( dl )

add a callback to the DeferredList which processes the 
(success,result_or_failure) list you get back.  If you want to process 
individual results/failures before the whole set returns, add the 
callback for that to the agent.get() result.

If you have thousands of devices you'll likely want to batch the queries 
into ~ 200 simultaneous queries and/or use multiple protocols (gives you 
more OS-level buffering).

Have fun,
Mike


  Mike C. Fletcher
  Designer, VR Plumber, Coder
  http://www.vrplumber.com
  http://blog.vrplumber.com

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


The problem of anonymity with decorators

2006-02-07 Thread Franck Pommereau
Dear all,

I would like to work around the anonymizing effect of decorators when
an exception is raised in the wrapped function. Let's consider the
following example:

def int_result (fun) :
def wrapped (*largs, **kwargs) :
result = fun(*largs, **kwargs)
if not isinstance(result, int) :
raise TypeError, should return int
return result
return wrapped

@int_result
def add (a, b) :
return a+b

print add(1, 2)
print add(foo, bar)

As expected, the last line results in raising TypeError:

Traceback (most recent call last):
  File wrapping.py, line 14, in ?
print add(foo, bar)
  File wrapping.py, line 5, in wrapped
raise TypeError, should return int
TypeError: should return int

My problem is that the errors comes from a function named wrapped
while I'd prefer to see here the name of the wrapped function. Indeed,
the code above is only a stripped down sample code but in my
application, I'll have a lot of functions, all wrapped the same way. So
I'd prefer a traceback like:

Traceback (most recent call last):
  File wrapping.py, line 14, in ?
print add(foo, bar)
  File wrapping.py, line 8, in add (wrapped)
@int_result
TypeError: should return int

Where the exception seems to come from the point where add was
wrapped, instead of from the inside of the wrapper.

I tried to change wrapper.__name__ and wrapper.func_name but it does not
change the traceback, and wrapper.func_code.co_name is read-only. I also
tried, unsuccessfully, to rename functions with:

import new
def rename (fun, name) :
return new.function(fun.func_code, {}, name)

So, my questions:
 - can I change a function name so that it affects the traceback when an
   exception is raised in the function?
 - is there some special trick to raise an exception making it, in
   appearance, coming from somewhere else?

Thanks in advance for any answer.

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


Re: Detecting line endings

2006-02-07 Thread Alex Martelli
Fuzzyman [EMAIL PROTECTED] wrote:
   ...
  Open the file with 'rU' mode, and check the file object's newline
  attribute.
 
 Do you know if this works for multi-byte encodings ? Do files have

You mean when you open them with the codecs module?

 metadata associated with them showing the line-ending in use ?

Not in the filesystems I'm familiar with (they did use to, in
filesystems used on VMS and other ancient OSs, but that was a very long
time ago).


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


Re: Natural Language Date Processing.

2006-02-07 Thread andychambers2002
From the docs for PHP's 'strtotime'

Parameters

time
The string to parse, according to the GNU Date Input Formats syntax.
Before PHP 5.0, microseconds weren't allowed in the time, since PHP 5.0
they are allowed but ignored.
...

It seems that the string to be parsed has to be provided in the GNU
date format.  One option would be to provide a function that calls out
to the the GNU date program with whatever string you want to parse.

I'm not aware of an existing function in Python that does this.

Regards,
Andy

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


Re: jython problem importing a py file

2006-02-07 Thread Khalid Zuberi
 didier.prophete writes:

 
 I tried everything I could think of (playing with the __init__.py, the
 PYTHONCLASS, the CLASSPATH), but nothing seems to work...
 
 I am doing something wrong here ? 
 
 -Didier
 

Take a look at the jython registry setting python.path:

  http://www.jython.org/docs/registry.html

So if you invoke jython with say:

  jython -Dpython.path=$TOP

your import should work.

- kz

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


Re: Detecting line endings

2006-02-07 Thread Fuzzyman

Bengt Richter wrote:
 On 6 Feb 2006 06:35:14 -0800, Fuzzyman [EMAIL PROTECTED] wrote:

 Hello all,
 
 I'm trying to detect line endings used in text files. I *might* be
 decoding the files into unicode first (which may be encoded using
 multi-byte encodings) - which is why I'm not letting Python handle the
 line endings.
 
 Is the following safe and sane :
 
 text = open('test.txt', 'rb').read()
 if encoding:
 text = text.decode(encoding)
 ending = '\n' # default
 if '\r\n' in text:
 text = text.replace('\r\n', '\n')
 ending = '\r\n'
 elif '\n' in text:
 ending = '\n'
 elif '\r' in text:
 text = text.replace('\r', '\n')
 ending = '\r'
 
 
 My worry is that if '\n' *doesn't* signify a line break on the Mac,
 then it may exist in the body of the text - and trigger ``ending =
 '\n'`` prematurely ?
 
 Are you guaranteed that text bodies don't contain escape or quoting
 mechanisms for binary data where it would be a mistake to convert
 or delete an '\r' ? (E.g., I think XML CDATA might be an example).


My personal use case is for reading config files in arbitrary encodings
(so it's not an issue).

How would Python handle opening such files when not in binary mode ?
That may be an  issue even on Linux - if you  open a windows file and
use splitlines does Python convert '\r\n' to '\n' ? (or does it leave
the extra '\r's in place, which is *different to the behaviour under
windows).

All the best,

Fuzzyman
http://www.voidspace.org.uk/python/index.shtml

 Regards,
 Bengt Richter

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


Re: Regular Expression Syntax Help

2006-02-07 Thread Raja Raman Sundararajan
try this. maybe this is what you want?

reg = re.compile('Name:.*\\n', re.IGNORECASE)

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


Re: Best way of finding terminal width/height?

2006-02-07 Thread Grant Edwards
On 2006-02-07, Joel Hedlund [EMAIL PROTECTED] wrote:

 As before, the only IO case above that doesn't throw
 exceptions is the uncommented one. 

 Yup, that's the exception.  Standard practice is to catch it and
 retry the I/O operation.

 Hmm... I guess it's not that easy to retry IO operations on
 pipes and streams (stdin/stdout in this case)...

You just call the failed read() or write() again.  Unless
there's some way that the read/write partially succeeded and
you don't have any way to know how many bytes were
read/written, If that's the case then Python's file object
read and write would appear to be broken by design.

 And I tend to lean pretty heavily on those since I usually
 write UNIX style text filters.

 So in case I haven't missed something fundamental I guess my
 best option is to accept defeat (of sorts :-) and be happy
 with picking a terminal width at program startup.

 But anyway, it's been really interesting trying this out. 

 Thank you Grant (och Jorgen) for all help and tips!

-- 
Grant Edwards   grante Yow!  BRILL CREAM is
  at   CREAM O' WHEAT in another
   visi.comDIMENSION...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Literal Escaped Octets

2006-02-07 Thread Bengt Richter
On Mon, 06 Feb 2006 04:40:31 GMT, Chason Hayes [EMAIL PROTECTED] wrote:

I am trying to convert raw binary data to data with escaped octets in
order to store it in a bytea field on postgresql server. I could do this
easily in c/c++ but I need to do it in python. I am not sure how to read
and evaluate the binary value of a byte in a long string when it is a non
printable ascii value in python. I read some ways to use unpack from the
struct module, but i really couldn't understand where that would help. I
looked at the MIMIEncode module but I don't know how to convert the object
to a string. Is there a module that will convert the data? It seems to me
that this question must have been answered a million times before but I
can't find anything.

Have you considered just encoding the data as text in hex or base64, e.g.,

  import binascii
  s = '\x00\x01\x02\x03ABCD0123'
  binascii.hexlify(s)
 '000102034142434430313233'
  binascii.b2a_base64(s)
 'AAECA0FCQ0QwMTIz\n'

which is also reversible later of course:
  h = binascii.hexlify(s)
  binascii.unhexlify(h)
 '\x00\x01\x02\x03ABCD0123'
  b64 = binascii.b2a_base64(s)
  binascii.a2b_base64(b64)
 '\x00\x01\x02\x03ABCD0123'

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


Re: Natural Language Date Processing.

2006-02-07 Thread Steven Bethard
Andrew Gwozdziewycz wrote:
 I've been looking recently for date processing modules that can parse 
 dates in forms such as next week or 6 days from next sunday.

This is, in fact, a fairly difficult problem in general.  See the TERN_ 
competition that's currently held yearly on this task.  There are a few 
taggers available that do this at:

 http://timex2.mitre.org/taggers/timex2_taggers.html

But none of them are available as Python modules.  You might be able to 
port the Perl script there, but it won't do as well as the ATEL program 
from CU which uses machine learning techniques.

.. _TERN: http://timex2.mitre.org/tern.html

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


Re: The problem of anonymity with decorators

2006-02-07 Thread Alex Martelli
Franck Pommereau [EMAIL PROTECTED] wrote:
   ...
 import new
 def rename (fun, name) :
 return new.function(fun.func_code, {}, name)

You need to make a new code object too:

def int_result(fun) :
def wrapped(*largs, **kwargs) :
result = fun(*largs, **kwargs)
if not isinstance(result, int) :
raise TypeError, should return int
return result
w = wrapped.func_code
c = new.code(w.co_argcount, w.co_nlocals, w.co_stacksize,
 w.co_flags, w.co_code, w.co_consts, w.co_names,
 w.co_varnames, w.co_filename, fun.func_name,
 w.co_firstlineno, w.co_lnotab,
 w.co_freevars, w.co_cellvars)
return new.function(c, fun.func_globals, fun.func_name,
fun.func_defaults, wrapped.func_closure)

Of course, you should refactor these last three statement into a

def remix(wrapped, fun): ...
return a function like 'wrapped' but w/name and defaults fm 'fun'
   
   ...same 3 statements as above, from w = ... onwards...



Alex

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


Dual Core outlook

2006-02-07 Thread malv
Multiprocessing has been pushed into the field as the chip
manufacturers can no longer deliver as they were used to for many
years.
The general public has been conditioned to believe that 1 + 1 = 2 but
this is in fact not that simple.
Although software manufacturers can with some effort adapt packages to
exploit these dual core architectures, the same is not true for other
development work were no large distribution of the application  is to
take place.
What is the outlook for programming languages in general?
Of course, multiprocessing has been used for many years but this always
involved a much higher level of sophistication on the part of the
designers. This point seems to be largely hidden from the public,
ignorant and semi-ignorant, by the chip manufacturers.
Will new languages see the light rendering the spreading of
applications over many processors quasi transparent?
What is the outlook for Python? Would Ironpython with .net do better?
What about talk by the Java lobby that Java would be very much suited
for taking advantage of dual-core? Is there any thruth to this?

These are questions that many Python users like myself would like to
find some answers for. One thing is clear. The old days will never come
back and the processor multiplication is likely to increase.
malv

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


Re: Question about idioms for clearing a list

2006-02-07 Thread Steven Bethard
Ben Sizer wrote:
 Likewise, the del keyword is fundamental -- if you
 can't get, set, and del, then you need to go back to collections
 school.
 
 I have hardly used the del keyword in several years of coding in
 Python. Why should it magically spring to mind in this occasion?
 Similarly I hardly ever find myself using slices, never mind in a
 mutable context.

I just grepped through my codebase, and while I do see a number of dels 
with dicts, and a number of dels with instance attributes, I see only 
two dels with lists, both from the same module.  So I think your point 
about infrequent use of del, at least with lists, is pretty valid.

I suspect this is reinforced by the fact that del is usually not the 
right way to go when using lists -- repeated dels in the middle of a 
list is almost always less efficient than other techniques due to the 
underlying array implementation.

That said, I didn't find anywhere in my codebase that I needed to clear 
a list (i.e. where ``L = []`` wasn't perfectly fine), while I do find a 
small number of dict clears.  So I guess I don't really care if clearing 
a list is a little less intuitive than clearing a dict.

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


Is Python good for web crawlers?

2006-02-07 Thread Tempo
I was wondering if python is a good language to build a web crawler
with? For example, to construct a program that will routinely search x
amount of sites to check the availability of a product. Or to search
for news articles containing the word 'XYZ'. These are just random
ideas to try to explain my question a bit further. Well if you have an
opinion about this please let me know becasue I am very interested to
hear what you have to say. Thanks.

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


problem with opening Python IDLE

2006-02-07 Thread Bennie Tilma
I'm having trouble with opening the python IDLE-program. When I try to start 
it, it gives an errormessage wich states that it can not make a connection, 
possibly because of a firewall. However, adding it to firewalls exeptions or 
even disabeling the firewall has no effect.


These are the errors:
1st. 'Socket error: Connection refused', with the name IDLE subprocess Error
2nd. 'IDLE's subprocess didn't make connection. Either IDLE can't start a 
subprocess or personal firewall software is blocking the connection.


The program I am trying to use is included with this message (it's purpose 
is to get a letter from the user and then pick a letter two places forward 
in the line, alphabetical order).


Bennie Tilma
[EMAIL PROTECTED]

_
Typ je SMS sneller binnen MSN Messenger 
http://www1.imagine-msn.com/Messenger/Expressions.aspx

letter = -1
letter_number = 0
message = []
print 'this program converts all letters into two letters forward'
print 'type 0(zero) to stop and show the message'
while letter != 'stop':
   letter = raw_input(type a letter: )
   if letter == 'a':
   letter_number = 1
   if letter == 'b':
   letter_number = 2
   if letter == 'c':
   letter_number = 3
   if letter == 'd':
   letter_number = 4
   if letter == 'e':
   letter_number = 5
   if letter == 'f':
   letter_number = 6
   if letter == 'g':
   letter_number = 7
   if letter == 'h':
   letter_number = 8
   if letter == 'i':
   letter_number = 9
   if letter == 'j':
   letter_number = 10
   if letter == 'k':
   letter_number = 11
   if letter == 'l':
   letter_number = 12
   if letter == 'm':
   letter_number = 13
   if letter == 'n':
   letter_number = 14
   if letter == 'o':
   letter_number = 15
   if letter == 'p':
   letter_number = 16
   if letter == 'q':
   letter_number = 17
   if letter == 'r':
   letter_number = 18
   if letter == 's':
   letter_number = 19
   if letter == 't':
   letter_number = 20
   if letter == 'u':
   letter_number = 21
   if letter == 'v':
   letter_number = 22
   if letter == 'w':
   letter_number = 23
   if letter == 'x':
   letter_number = 24
   if letter == 'y':
   letter_number = 25
   if letter == 'z':
   letter_number = 26
   if letter == ' ':
   letter_number = 0
alphabet = [' 
','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','a','b']

print 'the letter is: ', alphabet[letter_number]
message.append(alphabet[letter_number])
print message

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

Re: Is Python good for web crawlers?

2006-02-07 Thread Andrew Gwozdziewycz
On 7 Feb 2006 08:33:28 -0800, Tempo [EMAIL PROTECTED] wrote:
 I was wondering if python is a good language to build a web crawler
 with? For example, to construct a program that will routinely search x
 amount of sites to check the availability of a product. Or to search
 for news articles containing the word 'XYZ'. These are just random
 ideas to try to explain my question a bit further. Well if you have an
 opinion about this please let me know becasue I am very interested to
 hear what you have to say. Thanks.


Google supplies a basic webcrawler as a google desktop plugin called
Kongulo (http://sourceforge.net/projects/goog-kongulo/) which is
written in python. I would think python would be perfect for this sort
of application. Your bottleneck is always going to be downloading the
page.

--
Andrew Gwozdziewycz [EMAIL PROTECTED]
http://ihadagreatview.org
http://plasticandroid.org
-- 
http://mail.python.org/mailman/listinfo/python-list


Too Many if Statements?

2006-02-07 Thread slogging_away
Hi - I'm running Python 2.4.2 (#67, Sep 28 2005, 12:41:11) [MSC v.1310
32 bit (Intel)] on win32, and have a script that makes numerous checks
on text files, (configuration files), so discrepancies can be reported.
 The script works fine but it appears that I may have hit a wall with
'if' statements.

Due to the number of checks perfromed by the script on the text files,
(over 500), there are quite a few 'if' statements in the script, (over
1150).  It seems that it is at the point that when I add any additional
'if' statements the script will not run.  No error is produced - it
just returns to the python prompt much the same as when a successful
'Check Module' command is selected.  If I delete some other 'if'
statements the new ones work so it appears that it has hit a limit on
the number of 'if' statements.  This has stunted any further checks for
the script to make on the text files.

Hs anyone ever run into this sort of thing?

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


Re: The problem of anonymity with decorators

2006-02-07 Thread Michele Simionato
Using my decorator module
(http://www.phyast.pitt.edu/~micheles/python/documentation.html,
http://www.phyast.pitt.edu/~micheles/python/decorator.zip) you solve
the problem of the
name, but the traceback is still not perfect. You get:

# dec_traceback.py
from ms.decorator import decorator

@decorator
def int_result (fun, *largs, **kwargs) :
result = fun(*largs, **kwargs)
if not isinstance(result, int) :
raise TypeError, should return int
return result

@int_result
def add (a, b) :
return a+b

print add(1, 2)
print add(foo, bar)

# end dec_traceback.py

$ python dec_traceback.py
3
Traceback (most recent call last):
  File dec_traceback.py, line 15, in ?
print add(foo, bar)
  File string, line 2, in add
  File dec_traceback.py, line 7, in int_result
raise TypeError, should return int
TypeError: should return int

The reason of string is that the module internally uses 'exec'. There
should be a way around
that, anyway, but I have no time to check it right now.
Still, the module may be of inspiration to you.

Michele Simionato

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


sys.path and unicode folder names

2006-02-07 Thread Nir Aides
Hello,

Is there a solution or a work around for the sys.path problem with 
unicode folder names on Windows XP?

I need to be able to import modules from a folder with a non-ascii name.

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


Re: Detecting line endings

2006-02-07 Thread Fuzzyman

Alex Martelli wrote:
 Fuzzyman [EMAIL PROTECTED] wrote:
...
   Open the file with 'rU' mode, and check the file object's newline
   attribute.
 
  Do you know if this works for multi-byte encodings ? Do files have

 You mean when you open them with the codecs module?


No, if I open a UTF16 encoded file in universal mode - will it still
have the correct lineending attribute ?

I can't open with a codec unless an encoding is explicitly supplied.  I
still want to detect UTF16 even if the encoding isn't specified.

As I said, I ought to test this... Without metadata I wonder how Python
determines it ?

All the best,

Fuzzyman
http://www.voidspace.org.uk/python/index.shtml

  metadata associated with them showing the line-ending in use ?

 Not in the filesystems I'm familiar with (they did use to, in
 filesystems used on VMS and other ancient OSs, but that was a very long
 time ago).
 
 
 Alex

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


python-ldap

2006-02-07 Thread [EMAIL PROTECTED]
y0!
where can i get module of python-ldap to work with eclipse ide on
windows?

tks!

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


python-ldap

2006-02-07 Thread [EMAIL PROTECTED]
y0!
where can i get module of python-ldap to work with eclipse ide on
windows?

tks!

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


python-ldap

2006-02-07 Thread [EMAIL PROTECTED]
y0!
where can i get module of python-ldap to work with eclipse ide on
windows?

tks!

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


Re: Natural Language Date Processing.

2006-02-07 Thread Michael Amrhein
Andrew Gwozdziewycz schrieb:
 I've been looking recently for date processing modules that can parse 
 dates in forms such as
 next week or 6 days from next sunday.  PHP has a function that will 
 do this called 'strtotime',
 but I have not found a Python implementation. I've check the standard 
 date, datetime and time
 modules and also mx.Date* modules. Am I overlooking something here or 
 does it not exist?
 Anyone know of an implementation? Also, I realize that this is perhaps 
 very English specific
 so I apologize to any non-native English speakers.
 
 ---
 Andrew Gwozdziewycz
 [EMAIL PROTECTED]
 http://ihadagreatview.org
 http://plasticandroid.org
 
 

You may take a look at http://labix.org/python-dateutil
Have fun
Michael
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dual Core outlook

2006-02-07 Thread Xavier Morel
malv wrote:
 Of course, multiprocessing has been used for many years but this always
 involved a much higher level of sophistication on the part of the
 designers. This point seems to be largely hidden from the public,
 ignorant and semi-ignorant, by the chip manufacturers.
 Will new languages see the light rendering the spreading of
 applications over many processors quasi transparent?
 What is the outlook for Python? Would Ironpython with .net do better?
 What about talk by the Java lobby that Java would be very much suited
 for taking advantage of dual-core? Is there any thruth to this?
 
Python has support for OS threads, but it also has the GIL (a global 
lock from the interpreter). This means that Python behaves the same way 
Java or C# do as far as threads are concerned but for one field: 
multiprocessor (or multicore) situations.

While C# or Java can execute two threads of the same process on two 
separate cores/processors Python can't.

This means that you can't choke a multiprocessor/multicores machine with 
Python threads, and that if you want to scale in a 
multiprocessor/multicore environment (e.g. make use of all the available 
cores/processors) you have to use processes not threads (e.g. you have 
to launch multiple instances of the Python interpreter, each one having 
the ability to execute on a different core/processor).

Now the question is: do you want to do it? Do you have several extremely 
demanding computational threads? If yes, then Python probably isn't what 
you need (unless you implement your computations in specific C modules 
and get rid of the GIL issue). If not (a single computational thread and 
several low-resources GUI/network/whatever threads), it's a non-issue.
-- 
http://mail.python.org/mailman/listinfo/python-list


Is the Python types module superfluous?

2006-02-07 Thread Colin J. Williams
Travis Oliphant wrote:

 Gerard Vermeulen wrote:

 On Wed, 01 Feb 2006 11:15:09 -0500
 Colin J. Williams [EMAIL PROTECTED] wrote:

 [ currently numpy uses ndarray, with synonym ArrayType, for a 
 multidimensional array ]

  

 [Dbg] import types
 [Dbg] dir(types)
 ['BooleanType', 'BufferType', 'BuiltinFunctionType',
 'BuiltinMethodType', 'ClassType', 'CodeType', 'ComplexType',
 'DictProxyType', 'DictType', 'DictionaryType', 'EllipsisType',
 'FileType', 'FloatType', 'FrameType', 'FunctionType', 'GeneratorType',
 'Instance
 Type', 'IntType', 'LambdaType', 'ListType', 'LongType', 'MethodType',
 'ModuleType', 'NoneType', 'NotImplementedType', 'ObjectType',
 'SliceType', 'StringType', 'StringTypes', 'TracebackType', 'TupleType',
 'TypeType', 'UnboundMethodType', 'UnicodeType', 'XRan
 geType', '__builtins__', '__doc__', '__file__', '__name__']
 [Dbg]

   


 Isn't the types module becoming superfluous?

  

 That's the point I was trying to make.  ArrayType is to ndarray as 
 DictionaryType is to dict.  My understanding is that the use of 
 types.DictionaryType is discouraged.

 -Travis

I was simply trying to suggest that the name ArrayType is more
appropriate name that ndbigarray or ndarray for the multidimensional
array.  Since the intent is, in the long run, to integrate numpy with
the Python distribution, the use of a name in the style of the existing
Python types would appear to be better.

Is the types module becoming superfluous?  I've cross posted to c.l.p to
seek information on this.

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


Re: Too Many if Statements?

2006-02-07 Thread bruno at modulix
slogging_away wrote:
 Hi - I'm running Python 2.4.2 (#67, Sep 28 2005, 12:41:11) [MSC v.1310
 32 bit (Intel)] on win32, and have a script that makes numerous checks
 on text files, (configuration files), so discrepancies can be reported.
  The script works fine but it appears that I may have hit a wall with
 'if' statements.
 
 Due to the number of checks perfromed by the script on the text files,
 (over 500), there are quite a few 'if' statements in the script, (over
 1150).  It seems that it is at the point that when I add any additional
 'if' statements the script will not run.  No error is produced - it
 just returns to the python prompt much the same as when a successful
 'Check Module' command is selected.  If I delete some other 'if'
 statements the new ones work so it appears that it has hit a limit on
 the number of 'if' statements.  This has stunted any further checks for
 the script to make on the text files.
 
 Hs anyone ever run into this sort of thing?
 

Nope - but I never saw any code block with 1150+ tests in it neither :-/

Smells like a design problem anyway. Have you considered refactoring
your code ?


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


Re: Too Many if Statements?

2006-02-07 Thread snoe
slogging_away wrote:
 Hi - I'm running Python 2.4.2 (#67, Sep 28 2005, 12:41:11) [MSC v.1310
 32 bit (Intel)] on win32, and have a script that makes numerous checks
 on text files, (configuration files), so discrepancies can be reported.
  The script works fine but it appears that I may have hit a wall with
 'if' statements.

 Due to the number of checks perfromed by the script on the text files,
 (over 500), there are quite a few 'if' statements in the script, (over
 1150).  It seems that it is at the point that when I add any additional
 'if' statements the script will not run.  No error is produced - it
 just returns to the python prompt much the same as when a successful
 'Check Module' command is selected.  If I delete some other 'if'
 statements the new ones work so it appears that it has hit a limit on
 the number of 'if' statements.  This has stunted any further checks for
 the script to make on the text files.

 Hs anyone ever run into this sort of thing?

I can't say I've run into it before but your description makes me think
there are other approaches you could take. Does splitting the large
number of if statements into separate functions help at all?
If you're checking some text to see if a number of static strings are
contained therein, you could put the test strings into a list and loop
through...something like this (untested):

tests = [
'looking for this string',
'and this one',
'am i in the text'
] # etc...

for test in tests:
if test not in text:   
raise LookupError

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


Re: Too Many if Statements?

2006-02-07 Thread slogging_away
I don't consider myself to be a seasoned programmer so if you mean
redesigning the script to make the checks and therefore reduce the
number of 'if' statements, I'm not sure if that can be done.  The
script needs to make numerous checks for the existence of particular
strings within the configuration file.  It also uses 'if' statements to
determine what type of file is being examined, etc.. If an error is
encounterd it writes warning messages to a master file.  I guess what I
am trying to say is that in order to make the many checks on the
configuration files I do not know of any other way than to check for
the existance of particular statements, (strings), and then report on
those if they are incorrect or missing - hence at least one 'if'
statement for every check. 

I appreciate the feedback though!

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


Re: Is Python good for web crawlers?

2006-02-07 Thread Tempo
Why do you say that the bottleneck of the crawler will always be
downloading the page? Is it becasue there isn't already a modual to do
this and I will have to start from scratch? Or a bandwidth issue?

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


Re: Best way of finding terminal width/height?

2006-02-07 Thread Joel Hedlund
 You just call the failed read() or write() again.  Unless
 there's some way that the read/write partially succeeded and
 you don't have any way to know how many bytes were
 read/written, If that's the case then Python's file object
 read and write would appear to be broken by design.

Wow... I tried to set up an example that would fail, and it didn't. It seems 
the test only fails if I use the keyboard to cram stuff into stdin, and not if 
stdin is a regular pipe. 

Could this perhaps be some kind of misbehavior on behalf of my terminal 
emulator (GNOME Terminal 2.12.0 in Ubuntulinux 5.10)?

Example follows:

winch.py

import signal, os, sys
from terminal_info import get_terminal_size

terminal_size = get_terminal_size()

_bTerminalSizeChanged = False

def report_terminal_size_change(signum, frame):
global _bTerminalSizeChanged
_bTerminalSizeChanged = True

def update_terminal_size():
global _bTerminalSizeChanged, terminal_size
terminal_size = get_terminal_size()
_bTerminalSizeChanged = False

signal.signal(signal.SIGWINCH, report_terminal_size_change)

# Retry IO operations until successful.
io_successful = False
while not io_successful:
try:
s = sys.stdin.read()
io_successful = True
except IOError:
pass

io_successful = False
while not io_successful:
try:
sys.stdout.write(s)
io_successful = True
except IOError:
pass

/winch.py

Then run the prog and pipe a large chunk of text into stdin, and redirect 
stdout to a file:

$ cat /a/large/text/file | python winch.py  copy.of.the.large.file

Now, what happens for me is exactly what I wanted. I can resize the window as 
much as I like, and a diff 

$ diff /a/large/text/file copy.of.the.large.file

comes up empty. A perfectly good copy.

However, if I do this instead (try to use keyboard to push stuff into stdin):

$ python winch.py  copy.of.the.large.file

I expect python not to return until I press Ctrl-D on my keyboard, but it does 
return as soon as I enter more than one line of text and then resize the window 
(one unterminated line is ok). 

Example text to type in:
moo moo
cow cow

As soon as I have typed in something that includes a newline charater through 
the keyboard and try to resize the terminal, sys.stdin.read() will return 
whatever I put in no far and no exception raised.

Weird. Could it in fact my terminal that's screwing things up for me?

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


  1   2   3   >