Saving an audio file's waveform into an image

2008-05-09 Thread Julien
Hi,

I would like to pull out the waveform of an audio file and save it
into an image file, for example in GIF format. Is that achievable, and
if so, how?

I heard about the Snack module, but the project looks dead and un-
maintained.

Your advice would be greatly appreciated.

Thanks!

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


Re: threading - race condition?

2008-05-09 Thread John Nagle

skunkwerk wrote:

i'm getting the wrong output for the 'title' attributes for this
data.  the queue holds a data structure (item name, position, and list
to store results in).  each thread takes in an item name and queries a
database for various attributes.  from the debug statements the item
names are being retrieved correctly, but the attributes returned are
those of other items in the queue - not its own item.  however, the
model variable is not a global variable... so i'm not sure what's
wrong.

i've declared a bunch of worker threads (100) and a queue into which
new requests are inserted, like so:

queue = Queue.Queue(0)
 WORKERS=100
for i in range(WORKERS):
thread = SDBThread(queue)
thread.setDaemon(True)
thread.start()

the thread:

class SimpleDBThread ( threading.Thread ):
   def __init__ ( self, queue ):
self.__queue = queue
threading.Thread.__init__ ( self )
   def run ( self ):
while 1:
item = self.__queue.get()
if item!=None:
model = domain.get_item(item[0])
logger.debug('sdbthread item:'+item[0])
title = model['title']
scraped = model['scraped']
logger.debug("sdbthread title:"+title)

any suggestions?
thanks


  Hm.  We don't have enough code here to see what's wrong.
For one thing, we're not seeing how items get put on the queue.  The
trouble might be at the "put" end.

  Make sure that "model", "item", "title", and "scraped" are not globals.
Remember, any assignment to them in a global context makes them a global.

  You should never get "None" from the queue unless you put a "None"
on the queue.  "get()" blocks until there's work to do.

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


Re: The Importance of Terminology's Quality

2008-05-09 Thread J�rgen Exner
"Waylen Gumbal" <[EMAIL PROTECTED]> wrote:
> so why not just skip the thread or toss the OP in your 
>killfile so you don't see his postings. 

Done years ago.

>If others want to discuss his 
>topics, who are you or I to tell them not to?

They are very welcome to do so in an appropriate NG for those topics.

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


Re: python vs. grep

2008-05-09 Thread Ville Vainio
On May 8, 8:11 pm, Ricardo Aráoz <[EMAIL PROTECTED]> wrote:

> All these examples assume your regular expression will not span multiple
> lines, but this can easily be the case. How would you process the file
> with regular expressions that span multiple lines?

re.findall/ finditer, as I said earlier.


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


Re: anagram finder / dict mapping question

2008-05-09 Thread cokofreedom
>>> key = ''.join(sorted(word))

I tend to strip and lower the word as well, otherwise "Hello" and
"hello" do not compare...depends on what you want though!
Plus you might get a lot of "word\n" as keys...

My technique is the this way

def anagram_finder(words):
anagrams = {}
for word in words:
word = word.strip()
key = ''.join(sorted(word.lower()))
anagrams.setdefault(key, []).append(word)
return anagrams
--
http://mail.python.org/mailman/listinfo/python-list


Re: explain this function to me, lambda confusion

2008-05-09 Thread Duncan Booth
[EMAIL PROTECTED] wrote:

> Indeed, there are many ways this could be done.  Some are more
> concise, some are more efficient.  As I said, I did it the way I did
> it to try out lambdas.  Your way achieves the result, rather elegantly
> I think, but teaches me nothing about using lambdas.

Unfortunately what you wrote taught you nothing about using lambda either. 
I think you were looking for it to have mystic powers, when in fact all it 
gives you is an alternative way to define a function.

> 
> Pardon my tetchiness, but it is a little hard to receive such blunt
> and inflexible replies to my posts.

It was blunt because your post was so wide of the mark, yet it was well 
written and at least at first glance sounded plausible. Other people had 
even followed up on minor points having apparently not spotted the bigger 
problem.

Remember that what you post here is going to be archived by Google and 
instructing (or misleading) people for years to come so jumping hard on 
factual errors is (I think) worthwhile. (And I really appreciate it every 
time other people have jumped on things I've got wrong.)

On the other hand, there are plenty of people who use lambda in situations 
which are more or less appropriate. Just how appropriate they are is 
usually a matter of opinion, and while I may express my opinion when I 
think they are misusing them, that's all it is: an opinion. Everyone is 
free to disagree (and generally does).
--
http://mail.python.org/mailman/listinfo/python-list


Re: PHP + TinyButStrong Python replacement

2008-05-09 Thread Bruno Desthuilliers

pistacchio a écrit :

[EMAIL PROTECTED] ha scritto:

On 7 mai, 16:17, pistacchio <[EMAIL PROTECTED]> wrote:

George Sakkis ha scritto:

(snip)

What does it matter if it's a single file or a dozen under a package ?
"Installation" for pure Python packages can be as simple as copying
the package under any directory in your PYTHONPATH.

well, it doesn't matter if it's a single file or a package, but it
_does_ matter if you have to put them under the path where python is
installed because, in a typical shared web hosting environment (such the
one that i use) you don't have access to system directories.


You *never* have to install anything in the default path - install
your python libs wherever you want, and just make sure this wherever
is in your python path (usually via the PYTHONPATH environment
variable).



again, in a shared environment, you don't have access to environment 
variables.


Depends on the "shared environment". But even if you can't set 
PYTHONPATH, you can always import sys and append (or prepend) to 
sys.path before doing any other import.


> all you can do is copy files in your own little directory,
and that's it. this directory is never something like /share/python, but 
something like /home/averagejoe. and /home/averagejoe is not usually in 
the PYTHONPATH



Check out Mako (http://www.makotemplates.org/), it's pretty powerful
and fast.

woudl you suggest mako over cheetah?





As far as I'm concerned, I would.  Now if you're looking for a
somewhat barebone MVC framework, you may want to have a look at
web.py.



i've tried mako. sees to work fine for me, both for its potential and 
for its "installation" method. in fact i just copied it under my own 
directory


/home/averagejoe
  test.py
  /mako
mako stuff

and the following testcase worked well:

from mako.template import Template
mytemplate = Template("hello world!")
print mytemplate.render()

can i do the same with web.py?


Can't tell, never used it. But how to deploy it is very certainly 
documented on the project's page.


mind that i work under an apache 
environment (mod_python).


mod_python ? Fine. And, if I may ask, did you actually took time to read 
the FineManual(tm) ?-)


http://www.modpython.org/live/mod_python-3.3.1/doc-html/dir-other-pp.html


now, back to mako. can you provide an example of blocks and nested 
blocks in mako? the documentation doesn't seem to be too clear in this 
reguard.


for example, if i want to show a table with a list of restaurants 
(gathered from a db query), i can construct a template like this:



% for rest in restaurants:
  ${rest}
% endfor


but what if if each restaurant has a list of dishes (pasta, pizza, meat, 
pie)


Depends... What kind of object is 'rest' ? How is this list named ?


and some (or each) dish has the ingrediets?


Same question.

is it just like 
embedding pure python into the template ( like $(rest['dish'])  and 
$rest['dish']['ingredient']) )?


What goes inside ${} are ordinary Python expressions, yes.

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


Re: slicing lists

2008-05-09 Thread castironpi
On May 9, 1:23 am, "Ian Kelly" <[EMAIL PROTECTED]> wrote:
> On Wed, May 7, 2008 at 5:29 PM, Yves Dorfsman <[EMAIL PROTECTED]> wrote:
> > Is there a way to do:
> > x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
> > x[0,2:6]
>
> > That would return:
> > [0, 3, 4, 5, 6]
>
> > I am surprised this notation is not supported, it seems intuitive.
> > A concrete example of the sort of thing I want to do:
>
> > p = file('/etc/passwd').readlines()
> > q = [ e.strip().split(':')[0,2:] for e in p ]
>
> > (getting rid of the password / x field)
>
> Have a look at the itemgetter function from the operator module.
>
> g = itemgetter( 0, *range(2, 6) )
> p = file("/etc/passwd").readlines()
> q = [ g( e.strip().split(':') ) for e in p ]

The only thing is, is there is another natural meaning to [a,b:c].

Counting grids on the diagonals, the rational set is well defined:

0: 0, 0
1: 1, 0
2: 0, 1
3: 2, 0
4: 1, 1
5: 0, 2
6: 3, 0
7: 2, 1
...

Thencefore ( 2, 0 ) : ( 3, 0 ) is well defined.  Thencefore,

a,b:c,d

is not; x[a,b:c,d]= x[a]+ x[b:c]+ x[d].
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python GUIs and custom controls

2008-05-09 Thread Diez B. Roggisch

Joe P. Cool schrieb:

So far I have a little experience with Tkinter and wxPython. I wonder
which of the numerous Python GUI kits would be the best choice for a
multi platform application that makes heavy use of custom controls, 3D
views and the like? Thanks in advance for your hints and advice.


If you can work with the license (GPL), I suggest Qt4

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


Re: Am I missing something with Python not having interfaces?

2008-05-09 Thread Bruno Desthuilliers

Daniel Marcel Eichler a écrit :
Am Donnerstag 08 Mai 2008 00:12:26 schrieb 
[EMAIL PROTECTED]:



very often sees do-nothing catch-all try/catch blocks in Java - which
is way worse than just letting the exception propagate. I find all
this totally pointless, because there's just no way for a compiler to
check if your code is logically correct.


But it's enough if the called method exists and returns the correct 
type. At least it prevents a crash.


Then providing an appropriate default in the base class is enough too.


Interfaces work at
compile-time, while method-stubs raise at their first call, so in
worst case, never.

And then ? If it's never called, why bother implementing it ?


You never can't say when it's called at least, that's the point. 


Either the method is actually called somewhere and you'll now it pretty 
soon, or it isn't and you don't care.



That's the point. Interfaces garantee that a duck is a duck, an not
only a chicken that quack.

Who cares if it's a chicken as long as it quacks when you ask her to
? Now *This* is the whole point of chicken^Mduck typing, isn't it ?-)


Ducks can also swim and fly.  And if you need a really duck,


If you're code expects something that quacks, swims and flies, anything 
that quacks, swims and flies is ok. You just don't care if it's a duck 
or a flying whale with a quacking device tied to it.


but have 
onyl a chicken while the coder was to bored to make one...


Then the coder have a nice traceback, and it's not *your* problem - as 
long as the expectations are clearly documented, it's the user's (ie: 
coder) duty to provide something that fullfil the expectations.


Of course, in the practical world that all doesn't  matter. But in the 
theoretical world of the big coding farms, called business, that's one 
cornerstone of success, in the tinking of managers and so.


Sorry, I live in a very practical world - and we're by no mean running 
out of business here...


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


Re: Which way is faster for a simple web reporting system: django, web.py or cgi

2008-05-09 Thread Bruno Desthuilliers

idev a écrit :

Hi all,

May be this is a dump question, but it makes me crazy in my research.
I am not a developer but I have experience with web development (PHP)
in a past. Most my activities are around database administration and
design. For most database administration tasks I am using Python. Very
often I need to come up very quickly with web interface or web
application to a database, more then less complicated. The standard
set is:

* speed of the development (I think a framework is the way, but which
one?)
* user authorization (my preferences are sessions)
* form validation for input data
* file uploading
* export data to different format like csv, pdf, xml

For example I need to create a simple reporting system. Using
different filters like HTML drop down lists, radio buttons, check
boxes and etc., I need to generate different output to my team and
managers.

I realize that today is very popular and useful, using a framework.
Which Python framework or solution will be more faster to start (i.e.
for start, usually I have maximum two weeks, if a project looks like a
stable I can get three, four weeks), flexible (i.e. using SQL queries
together with views) and easier in integration: django, web.py, CGI or
something else?


Given your background and requirements, I'd strongly recommand Django.

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


Re: "prove"

2008-05-09 Thread Bruno Desthuilliers

Lucas Prado Melo a écrit :

Hello,
How could I "prove" to someone that python accepts this syntax using
the documentation (I couldn't find it anywhere):
classname.functionname(objectname)


Why do you need the documentation ? Just fire up your python shell and 
hack a Q&D example:


Python 2.5.1 (r251:54863, May  2 2007, 16:56:35)
[GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> class Foo(object):
... def bar(self):
... print "in %s bar" % self
...
>>> f = Foo()
>>> Foo.bar(f)
in <__main__.Foo object at 0xb7dccd2c> bar
>>> f.bar()
in <__main__.Foo object at 0xb7dccd2c> bar
>>>

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


Re: Newbie to python --- why should i learn !

2008-05-09 Thread Bruno Desthuilliers

[EMAIL PROTECTED] a écrit :

Hi,

i was reading/learning some hello world program in python.
I think its very simillar to Java/C++/C#.



Err... You saw a Python helloworld and a Java helloworld and you found 
them "very similar" ???



What's different (except
syntax) ?


dynamism (and not only wrt/ the type system), higher order functions, 
closures, lazy evaluation... and fun.



what can i do easily with python which is not easy in c++/java !?


Enjoy writing a working app focusing on the problem to solve instead of 
wasting time writing boilerplate code and going thru hoops just to 
satisfy the compiler.

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


Re: Best technology for agent/web server architecture

2008-05-09 Thread Florencio Cano
I have control over agent and client but I'm not sure how to use
pickle for this task. Do you suggest to pickle the objects that I want
to send and send it over a usual socket? I have searched a bit in
Google and I have seen that Pickle is insecure by default. What do you
think about this?

2008/5/8 M.-A. Lemburg <[EMAIL PROTECTED]>:

> SOAP would be a good choice if you want to send to data to other
> servers as well, e.g. Java-based ones.
>
> XML-RPC and JSON are better for simple data structures.
>
> If you have control over both client and server and don't
> need to bother with other backends or frontends, Python
> pickle is the best choice.
--
http://mail.python.org/mailman/listinfo/python-list


Re: "prove"

2008-05-09 Thread Duncan Booth
"Lucas Prado Melo" <[EMAIL PROTECTED]> wrote:

> Hello,
> How could I "prove" to someone that python accepts this syntax using
> the documentation (I couldn't find it anywhere):
> classname.functionname(objectname)


Language reference, mostly section 5.3 Primaries

call ::= 
 primary "(" [argument_list [","]
| expression genexpr_for] ")"

primary ::= 
 atom | attributeref
  | subscription | slicing | call

attributeref ::= 
 primary "." identifier

atom ::= 
 identifier | literal | enclosure


That shows fairly well how the classname.functioname bit works (it is an 
attributeref which is a primary which forms the first part of a call), 
but you'll have to wade through a fair bit of the grammar to show that 
argument_list can be an identifier.


argument_list ::= 
 positional_arguments ["," keyword_arguments]
 ["," "*" expression]
 ["," "**" expression]
| keyword_arguments ["," "*" expression]
["," "**" expression]
| "*" expression ["," "**" expression]
| "**" expression

positional_arguments ::= 
 expression ("," expression)*

... and so on ...
--
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie to python --- why should i learn !

2008-05-09 Thread Bruno Desthuilliers

pistacchio a écrit :
(snip)
Technically speaking, it (Python) is not, for example, strongly 
typed, 


You're confusing "strong" typing with static typing. Somewhat orthogonal 
issues.

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


Re: python newbie: some surprises

2008-05-09 Thread Bruno Desthuilliers

v4vijayakumar a écrit :

When I started coding in python, these two things surprised me.

1. my code is inconsistently indented with the combination of tabs and
spaces. Even lines looked intended, but it is not.


Then you have a problem with your code editor - not with Python.


2. python requires to pass "self" to all instance methods


Nope. Python requires that function used as instance methods take the 
instance as first argument (and that functions used as classmethods take 
the class as first argument). It's the method object's duty to actually 
pass the appropriate object to the function. The rational is that it 
allows to built methods above two more generic constructs (namely: 
functions and the descriptor protocol) instead of having to special-case 
them.



and I missed ":" often. :)


Your editor should not indent the next line then. Either you failed to 
correctly configure your editor, or it's broken.

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


Re: python newbie: some surprises

2008-05-09 Thread Bruno Desthuilliers

Yves Dorfsman a écrit :

Mensanator wrote:

2. python requires to pass "self" to all instance methods


Who uses methods?


Is this a joke ?


Very probably.


What are the alternatives ?


Err... functions ?-)

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


Re: python newbie: some surprises

2008-05-09 Thread Bruno Desthuilliers

Yves Dorfsman a écrit :
(snip)
I see the point of the OP. Couldn't the new-line be used as an 
equivalent of  ':', 



Technically, yes. OTHO, the ':' helps editors doing proper indentation.
--
http://mail.python.org/mailman/listinfo/python-list


the lvalue curse? let's play with this crazy idea ;)

2008-05-09 Thread XLiIV
I started playing with Python and love it since the very beginning,
programming using Python is so ...human-like? but one thing returns to
me almost everytime when I see/write the code


Let's take a look at two ways of thinking...
the standard one which is well-known and loved by almost everyone :)
and that crazy concept below which suprised evan me :wacko:


import time

ftime = time.time()
localtime = time.localtime(ftime)
localtime = list(localtime[:3])
localtime = [str(i) for i in localtime]
print '-'.join(localtime)


It's harder to read than the below concept, isn't?
Maybe I didn't used to this way of thinking yet. I hope it'll change
soon or i'll quit ;)



time.time() -> ftime -> time.localtime() -> p -> p[:3] -> g -> list(g)
-> '-'.join()


My example conclusion and not-ansewered-yet question...
-it's nice to read and choosing the good names to variables aren't so
important
-what is the purpose of the variables here? :)

I realize that there is no chance to implement it, but I really want
to share it :]

Peace,
T.

PS
forgive my my english
[shall I set it as a signature? ;) ]
--
http://mail.python.org/mailman/listinfo/python-list


xml.etree Syntax of path?

2008-05-09 Thread Thomas Guettler

Hi,

I think the documentation of xml.etree is missing something[1].

{{{
find(path)
Finds the first toplevel element with given tag. Same as 
getroot().find(path). path is the element to look for.
}}}

According to the source etree has limited support for xpath. I think it should 
be documented
what 'path' should look like to.


[1]
http://docs.python.org/lib/elementtree-elementtree-objects.html


--
Thomas Guettler, http://www.thomas-guettler.de/
E-Mail: guettli (*) thomas-guettler + de
--
http://mail.python.org/mailman/listinfo/python-list


Grabbing previous iteration in a dict

2008-05-09 Thread dannywebster
Hello all,

I have a dictionary of which i'm itervalues'ing through, and i'll be
performing some logic on a particular iteration when a condition is
met with trusty .startswith('foo').  I need to grab the previous
iteration if this condition is met.  I can do something with an extra
var to hold every iteration while iterating, but this is hacky and not
elegant.

Is there a mechanism whereby I can just index the dict value
subscripts like in an array? I could just rewind by 1 if so.

Cheerz

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


Re: RELEASED Python 2.6a3 and 3.0a5

2008-05-09 Thread Christian Heimes
Kay Schluehr schrieb:
> http://www.python.org/ftp/python/3.0/python-3.0a5.msi

> Error 404: File Not Found

> http://www.python.org/ftp/python/3.0/python-3.0a5.amd64.msi

> Error 404: File Not Found

The Windows binaries usually take a while. I'm adding Martin to the CC
list. His is most like building the files today.

Christian


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


Re: Free Memory

2008-05-09 Thread Christian Heimes
Dark Wind schrieb:
> Hi,
> 
> How can I free all the memory in python by deleting all variables. I am
> looking for the equivalent of 'clear' from Matlab.
> 
> I know del x deletes a variable x, but it doesn't free all the available
> memory.

del doesn't free an object. It only removes one reference to the object.

Christian

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


Re: pickle problem

2008-05-09 Thread Hrvoje Niksic
Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> writes:

>> Of course, if it makes sense to pickle sockets in the application, one
>> is can do so by defining __getstate__ and __setstate__:
>
> When does it make sense!?

When recreating the object from on-disk state requires reestablishing
the communication, as the example shows.  I'm not saying that doing
that is always a good idea, only that it can be done if/when needed.

> But if you unpickle it while the original connection is still open it
> can't connect.

Why not?  I was thinking "client socket", not "server socket".
--
http://mail.python.org/mailman/listinfo/python-list


Re: Grabbing previous iteration in a dict

2008-05-09 Thread Paul Rubin
[EMAIL PROTECTED] writes:
> I have a dictionary of which i'm itervalues'ing through, and i'll be
> performing some logic on a particular iteration when a condition is
> met with trusty .startswith('foo').  I need to grab the previous
> iteration if this condition is met.  I can do something with an extra
> var to hold every iteration while iterating, but this is hacky and not
> elegant.

You cannot rely on the elements of a dictionary being in any
particular order (dicts are internally hash tables), so the above
is almost certainly ont what you want.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Scanning through Windows registry...

2008-05-09 Thread Unknown Hero
On 7 touko, 14:25, Unknown Hero <[EMAIL PROTECTED]> wrote:
> I'll post my code here once I have time to write it, currently I'm
> rather busy. That is merely for optimization suggestions and for
> others who might need the same sort of code I did.
>
> Thank you once again.

Finally managed to get it to work (heh, I was pretty darn lost even
though I had the best help) but as promised, I'll post my code here
for those who might be interested in it. The biggest of thanks to Tim
Golden, who basically walked me step-by-step through this. Most of the
code is copied from his examples above.


#Goes through all keys and subkeys in the selected hive (defined as
root) and replaces the value 'old' with the value 'new'
#
#IMPORTANT! You should always back up the registry before attempting
to modify it.
#The author of this script CANNOT BE HELD RESPONSIVE for any damage
caused by running this script.
#
#To customize the script to your liking, you can alter the values old,
new, root.
#
#old and new can be any string value
#root has to be one of the following:
#
# _winreg.HKEY_LOCAL_MACHINE
# _winreg.HKEY_CURRENT_USER
# _winreg.HKEY_CLASSES_ROOT
# _winreg.HKEY_USERS
# _winreg.HKEY_CURRENT_CONFIG

import _winreg

HIVES = {
  "HKEY_LOCAL_MACHINE" : _winreg.HKEY_LOCAL_MACHINE,
  "HKEY_CURRENT_USER" : _winreg.HKEY_CURRENT_USER,
  "HKEY_CLASSES_ROOT" : _winreg.HKEY_CLASSES_ROOT,
  "HKEY_USERS" : _winreg.HKEY_USERS,
  "HKEY_CURRENT_CONFIG" : _winreg.HKEY_CURRENT_CONFIG

}

old = "This was value before"
new = "This is new value"

start = "HKEY_LOCAL_MACHINE\\"
startHandle = _winreg.HKEY_LOCAL_MACHINE

#Values for start and startHandle are: HKEY_LOCAL_MACHINE,
HKEY_CURRENT_USER, HKEY_CLASSES_ROOT, HKEY_USERS, HKEY_CURRENT_CONFIG


class RegKey:

  def __init__ (self, name, key):
 self.name = name
 self.key = key

  def __str__ (self):
return self.name

def walk (top):
  """walk the registry starting from the key represented by
  top in the form HIVE\\key\\subkey\\..\\subkey and generating
  key, subkey_names, values at each level.

  key is a lightly wrapped registry key, including the name
  and the HKEY object.
  subkey_names are simply names of the subkeys of that key
  values are 3-tuples containing (name, data, data-type).
  See the documentation for _winreg.EnumValue for more details.
  """
  try:
if "\\" not in top: top += "\\"
root, subkey = top.split ("\\", 1)
#print "KEY:", root + "\\" + subkey
key = _winreg.OpenKey (HIVES[root], subkey, 0, _winreg.KEY_READ |
_winreg.KEY_SET_VALUE)
subkeys = []
i = 0
while True:
  try:
subkeys.append (_winreg.EnumKey (key, i))
i += 1
  except EnvironmentError:
break

values = []
i = 0
while True:
  try:
values.append (_winreg.EnumValue (key, i))
i += 1
  except EnvironmentError:
break

yield RegKey (top, key), subkeys, values

for subkey in subkeys:
  for result in walk (top + "\\" + subkey):
yield result

  except WindowsError:
#print 'Could not open key', root + "\\" + subkey + "\n"
pass

basickeys = []
i = 0
while True:
  try:
basickeys.append (_winreg.EnumKey (startHandle, i))
i += 1
  except EnvironmentError:
print i, 'subkeys found!'
break

for x in range(len(basickeys)):
  for key, subkey_names, values in walk (start + basickeys[x]):
#print key
for (name, data, type) in values:
#  print "  ", name, "=>", data
  if type == _winreg.REG_SZ and old in data:
_winreg.SetValueEx (key.key, name, 0, type, data.replace (old,
new))



Not the most effecient code, I'm sure, but it does what I want it to
do :D

Thank you once more, Tim. Also, thank you, Mike, for your advice on
saving the registry. I would have forgotten to note backing up the
registry in the beginning if it wasn't for you bringing that up. :D
--
http://mail.python.org/mailman/listinfo/python-list


Re: the lvalue curse? let's play with this crazy idea ;)

2008-05-09 Thread Marc 'BlackJack' Rintsch
On Fri, 09 May 2008 02:13:34 -0700, XLiIV wrote:

> Let's take a look at two ways of thinking...
> the standard one which is well-known and loved by almost everyone :)
> and that crazy concept below which suprised evan me :wacko:
> 
> 
> import time
> 
> ftime = time.time()
> localtime = time.localtime(ftime)
> localtime = list(localtime[:3])
> localtime = [str(i) for i in localtime]
> print '-'.join(localtime)
> 
> 
> It's harder to read than the below concept, isn't?
> Maybe I didn't used to this way of thinking yet. I hope it'll change
> soon or i'll quit ;)

Maybe it's also harder to read than this::

  print '-'.join(map(str, time.localtime()[:3]))

Of course, if you don't mind the extra padding zeroes in day and month::

  print time.strftime('%Y-%m-%d')

> 
> time.time() -> ftime -> time.localtime() -> p -> p[:3] -> g -> list(g)
> -> '-'.join()
> 

You are a little bit inconsistent with the arguments.  `g` is explicitly
mentioned in ``list(g)``.  But why the intermediate names at all?

> My example conclusion and not-ansewered-yet question...
> -it's nice to read and choosing the good names to variables aren't so
> important
> -what is the purpose of the variables here? :)

Exactly.  But look at my snippet above: No intermediate names either.

> I realize that there is no chance to implement it, but I really want
> to share it :]

Maybe you should look into languages like SmallTalk or Io where everything
is done with method calls.  Your example in Io::

  Date now do("#{year}-#{month}-#{day}" interpolate linePrint)

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


Re: range with variable leading zeros

2008-05-09 Thread yhvh
> > x = [0010, 0210]
>
> You do realize that this is octal, right?
It's unfortunate I choose that, the numbers go beyond octal

> len is undefined for integers.  Perhaps you meant "len(str(x[1]))".
Yes sorry it was late at night :P


> You can, however, do this:
> >>> '%0*d' % (5, 123)
> '00123'

This is exactly what I needed Thank-you kindly
--
http://mail.python.org/mailman/listinfo/python-list


Re: xml.etree Syntax of path?

2008-05-09 Thread Stefan Behnel
Thomas Guettler wrote:
> I think the documentation of xml.etree is missing something[1].
> 
> {{{
> find(path)
> Finds the first toplevel element with given tag. Same as
> getroot().find(path). path is the element to look for.
> }}}
> 
> According to the source etree has limited support for xpath. I think it
> should be documented what 'path' should look like to.

You mean like this?

http://effbot.org/zone/element-xpath.htm

Note that the method is called "find()", not "execute_xpath()" or something.
If you want full XPath support, lxml is your friend.

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


simple question about Python list

2008-05-09 Thread dmitrey
hi all,
suppose I have 2 lists
list1 = ['elem0', 'elem1', 'elem2', 'elem3', 'elem4', 'elem5']
and
list2 = [0, 2, 4] # integer elements

howto (I mean most simple recipe, of course) form list3 that contains
elements from list1 with indexes from list2, i.e.

list3 = ['elem0', 'elem2', 'elem4']?

Thank you in advance, D.
--
http://mail.python.org/mailman/listinfo/python-list


Reusing IDLE file editor

2008-05-09 Thread Russell Blau
I have a need for some simple text-editing capabilities in a Tkinter program, 
and it occurred to me that IDLE is a Tkinter app that already has what I need 
in its file editor windows.  I thought it would be nice if I could just use one 
of those windows as a widget in my application, in place of a plain Tkinter 
Text widget. I took a quick look at idlelib/EditorWindow.pyw, but it appears 
that the program is not written as a reusable widget; it's hard-coded to be a 
toplevel window.

Before I start hacking at it myself, has anyone else modified IDLE to be able 
to reuse its windows in another application?  Or, alternatively, is there 
another freely-available (under the Python license or something compatible) 
Tkinter widget out there that has similar text-editing capabilities?


_
With Windows Live for mobile, your contacts travel with you.
http://www.windowslive.com/mobile/overview.html?ocid=TXT_TAGLM_WL_Refresh_mobile_052008--
http://mail.python.org/mailman/listinfo/python-list

here is the coolest site in the world, what I've talked about last time: http://tinyurl.com/4e4smx

2008-05-09 Thread kiskeke
here is the coolest site in the world, what I've talked about last
time: http://tinyurl.com/4e4smx
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to kill Python interpreter from the command line?

2008-05-09 Thread spectrumdt
Thanks for all the replies.

On May 8, 5:50 pm, Jean-Paul Calderone <[EMAIL PROTECTED]> wrote:
> Ctrl+C often works with Python, but as with any language, it's possible
> to write a program which will not respond to it.  You can use Ctrl+\
> instead (Ctrl+C sends SIGINT which can be masked or otherwise ignored,
> Ctrl+\ sends SIGQUIT which typically isn't)

Yes, thank you, this seems to work. :)

I did some more testing and found out that the problem seems to be
thread-related. If I have a single-threaded program, then Ctrl+C
usually works, but if I have threads, it is usually ignored. For
instance, the below program does not respond to Ctrl+C (but it does
die when issued Ctrl+\):



import threading

def loop():
  while True:
pass

threading.Thread(target=loop,args=()).start()
--
http://mail.python.org/mailman/listinfo/python-list


Re: simple question about Python list

2008-05-09 Thread Paul Hankin
On May 9, 11:04 am, dmitrey <[EMAIL PROTECTED]> wrote:
> list1 = ['elem0', 'elem1', 'elem2', 'elem3', 'elem4', 'elem5']
> and
> list2 = [0, 2, 4] # integer elements
>
> howto (I mean most simple recipe, of course) form list3 that contains
> elements from list1 with indexes from list2, i.e.

list3 = [list1[i] for i in list2]

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


Re: How to kill Python interpreter from the command line?

2008-05-09 Thread spectrumdt

Thanks for the replies.

On May 8, 5:50 pm, Jean-Paul Calderone <[EMAIL PROTECTED]> wrote:
> Ctrl+C often works with Python, but as with any language, it's possible
> to write a program which will not respond to it.  You can use Ctrl+\
> instead (Ctrl+C sends SIGINT which can be masked or otherwise ignored,
> Ctrl+\ sends SIGQUIT which typically isn't)

Yes, thank you, this seems to work. :)

I did some more testing and found out that the problem seems to be
thread-related. If I have a single-threaded program, then Ctrl+C
usually works, but if I have threads, it is usually ignored. For
instance, the below program does not respond to Ctrl+C (but it does
die when issued Ctrl+\):



import threading

def loop():
  while True:
pass

threading.Thread(target=loop,args=()).start()
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to kill Python interpreter from the command line?

2008-05-09 Thread dmitrey
in addition to killall and kill funcs mentioned above you could be
interested in pkill
see "man pkill" from terminal for more details

pkill python

or

pkill pyt

or

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


Re: simple question about Python list

2008-05-09 Thread dmitrey
Ok, I use Python 2.5 but I try my code to remain Python 2.4 and
(preferable) 2.3 compatible.
Are there other solutions?
D.

On 9 Тра, 13:17, Paul Hankin <[EMAIL PROTECTED]> wrote:
> On May 9, 11:04 am, dmitrey <[EMAIL PROTECTED]> wrote:
>
> > list1 = ['elem0', 'elem1', 'elem2', 'elem3', 'elem4', 'elem5']
> > and
> > list2 = [0, 2, 4] # integer elements
>
> > howto (I mean most simple recipe, of course) form list3 that contains
> > elements from list1 with indexes from list2, i.e.
>
> list3 = [list1[i] for i in list2]
>
> --
> Paul Hankin

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

Pythonwin

2008-05-09 Thread Clive_S
Hi

I am trying to use Python with ArcGIS.

I have installed Python 2.4. I have an icon for IDLE and command line.
I do not see Python PythonWin.

How do you install or launch pythonwin??

Thanks

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


Re: source beautifier

2008-05-09 Thread Stefan Behnel
Marco Mariani wrote:
> Is there a program (free, payware, whatever) like polystyle for
> linux/python?
> 
> http://www.polystyle.com/features/python-beautifier.jsp
> 
> I've never used it, but the example is quite clear.

I tend to believe that running these tools on some average Python code would
not even change whitespace. ;)


> I just need it for python -- but it should not force me to use PEP8.

IMHO, a tool that automatically corrects code to comply with PEP-8 would
actually be more helpful, but I guess that's pretty far reached.

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


Re: simple question about Python list

2008-05-09 Thread Russell Blau
On May 9, 6:25 am, dmitrey <[EMAIL PROTECTED]> wrote:
> Ok, I use Python 2.5 but I try my code to remain Python 2.4 and
> (preferable) 2.3 compatible.
> Are there other solutions?
> D.
>
> On 9 ôÒÁ, 13:17, Paul Hankin <[EMAIL PROTECTED]> wrote:
>
> > On May 9, 11:04šam, dmitrey <[EMAIL PROTECTED]> wrote:
>
> > > list1 = ['elem0', 'elem1', 'elem2', 'elem3', 'elem4', 'elem5']
> > > and
> > > list2 = [0, 2, 4] # integer elements
>
> > > howto (I mean most simple recipe, of course) form list3 that contains
> > > elements from list1 with indexes from list2, i.e.
>
> > list3 = [list1[i] for i in list2]
>
> > --
> > Paul Hankin

Why don't you try Paul's suggestion under Python 2.3 and see what
happens?
--
http://mail.python.org/mailman/listinfo/python-list


Re: simple question about Python list

2008-05-09 Thread Duncan Booth
dmitrey <[EMAIL PROTECTED]> wrote:

> On 9 ôÒÁ, 13:17, Paul Hankin <[EMAIL PROTECTED]> wrote:
>> On May 9, 11:04šam, dmitrey <[EMAIL PROTECTED]> wrote:
>>
>> > list1 = ['elem0', 'elem1', 'elem2', 'elem3', 'elem4', 'elem5']
>> > and
>> > list2 = [0, 2, 4] # integer elements
>>
>> > howto (I mean most simple recipe, of course) form list3 that contains
>> > elements from list1 with indexes from list2, i.e.
>>
>> list3 = [list1[i] for i in list2]
>>
> 
> Ok, I use Python 2.5 but I try my code to remain Python 2.4 and
> (preferable) 2.3 compatible.
> Are there other solutions?
> D.
> 

Did you try Paul's suggestion?

Python 2.3.5 (#1, Oct 13 2005, 09:17:23)
[GCC 3.2.3 20030502 (Red Hat Linux 3.2.3-52)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> list1 = ['elem0', 'elem1', 'elem2', 'elem3', 'elem4', 'elem5']
>>> list2 = [0, 2, 4]
>>> list3 = [list1[i] for i in list2]
>>> list3
['elem0', 'elem2', 'elem4']

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


Re: Pythonwin

2008-05-09 Thread Niklas Norrthon
On 9 Maj, 12:30, Clive_S <[EMAIL PROTECTED]> wrote:
> Hi
>
> I am trying to use Python with ArcGIS.
>
> I have installed Python 2.4. I have an icon for IDLE and command line.
> I do not see Python PythonWin.
>
> How do you install or launch pythonwin??

There is a distribution of PythonWin bundled with the
ArcGIS Desktop installation media, but it is not
installed by the ArcGIS installer.

You have three options:
1. Install it manually from the ArcGIS installation
media.
2. Find it on the web (google for it), download and
install.
3. (My recommendation) Don't bother. IDLE is pretty
good. Emacs even better (unless you hate emacs).

--
Niklas Norrthon
ESRI S-GROUP
--
http://mail.python.org/mailman/listinfo/python-list


Re: simple question about Python list

2008-05-09 Thread dmitrey
Hmm... I thought this issue is available from Python2.5 only. I have
no other interpreters in my recently installed KUBUNTU 8.04.

Thanks all,
D.

On 9 Тра, 13:41, Duncan Booth <[EMAIL PROTECTED]> wrote:
> dmitrey <[EMAIL PROTECTED]> wrote:
> > On 9 ôÒÁ, 13:17, Paul Hankin <[EMAIL PROTECTED]> wrote:
> >> On May 9, 11:04šam, dmitrey <[EMAIL PROTECTED]> wrote:
>
> >> > list1 = ['elem0', 'elem1', 'elem2', 'elem3', 'elem4', 'elem5']
> >> > and
> >> > list2 = [0, 2, 4] # integer elements
>
> >> > howto (I mean most simple recipe, of course) form list3 that contains
> >> > elements from list1 with indexes from list2, i.e.
>
> >> list3 = [list1[i] for i in list2]
>
> > Ok, I use Python 2.5 but I try my code to remain Python 2.4 and
> > (preferable) 2.3 compatible.
> > Are there other solutions?
> > D.
>
> Did you try Paul's suggestion?
>
> Python 2.3.5 (#1, Oct 13 2005, 09:17:23)
> [GCC 3.2.3 20030502 (Red Hat Linux 3.2.3-52)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.>>> 
> list1 = ['elem0', 'elem1', 'elem2', 'elem3', 'elem4', 'elem5']
> >>> list2 = [0, 2, 4]
> >>> list3 = [list1[i] for i in list2]
> >>> list3
>
> ['elem0', 'elem2', 'elem4']

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

multiple Python versions, but on Windows (how to handle registry updates)

2008-05-09 Thread Banibrata Dutta
Hi,

I already have Python25, and need to install Python24. I would prefer not to
remove Python25, but each Python version seems to update the registry, I
guess (not sure), overwriting each other's entries. Any way to have both
versions ?

-- 
regards,
Bani
--
http://mail.python.org/mailman/listinfo/python-list

Re: simple question about Python list

2008-05-09 Thread Bjoern Schliessmann
dmitrey wrote:

> Hmm... I thought this issue is available from Python2.5 only. I
> have no other interpreters in my recently installed KUBUNTU 8.04.

"aptitude install python2.4" helps.

Regards,


Björn

-- 
BOFH excuse #10:

hardware stress fractures

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


Re: simple question about Python list

2008-05-09 Thread Arnaud Delobelle


dmitrey wrote:
> Ok, I use Python 2.5 but I try my code to remain Python 2.4 and
> (preferable) 2.3 compatible.
> Are there other solutions?
> D.
>
> On 9 ���, 13:17, Paul Hankin <[EMAIL PROTECTED]> wrote:
> > On May 9, 11:04�am, dmitrey <[EMAIL PROTECTED]> wrote:
> >
> > > list1 = ['elem0', 'elem1', 'elem2', 'elem3', 'elem4', 'elem5']
> > > and
> > > list2 = [0, 2, 4] # integer elements
> >
> > > howto (I mean most simple recipe, of course) form list3 that contains
> > > elements from list1 with indexes from list2, i.e.
> >
> > list3 = [list1[i] for i in list2]
> >
> > --
> > Paul Hankin

This works under python 2.0+, I think.

Before that, you could have written:

list3 = map(list1.__getitem__, list2)

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

Re: Pythonwin

2008-05-09 Thread Roy H. Han
Hi Clive,

For ArcGIS, I use plain old VIM, IPython and IDLE.

If you really want PythonWin, then you can download Mark Hammond's Python
for Windows extensions: http://sourceforge.net/projects/pywin32/

Note also that with the pywin32 extensions, you can also use Python 2.5 to
access ArcGIS using

from win32com.client import Dispatch
arcgis = Dispatch('esriGeoprocessing.GpDispatch')

If you just need to access shapefiles, there is shapelib:
http://shapelib.maptools.org/
To make shapelib bindings for Python 2.5
1. Download *shapelib_1_2_10.zip *from http://dl.maptools.org/dl/shapelib/
2. Download *pyshapelib-0.3.zip* from
ftp://intevation.de/users/bh/pyshapelib
3. Extract *pyshapelib-0.3.zip*
4. Extract *shapelib_1_2_10.zip* to the folder containing pyshapelib.
Rename the extracted folder as *shapelib*
5. From the pyshapelib directory, run python setup.py build.  The script
looks in its parent folder for the shapelib folder.
5. From the pyshapelib directory, python setup.py install

Hope that helps,
Roy
**
On Fri, May 9, 2008 at 6:46 AM, Niklas Norrthon <[EMAIL PROTECTED]>
wrote:

> On 9 Maj, 12:30, Clive_S <[EMAIL PROTECTED]> wrote:
> > Hi
> >
> > I am trying to use Python with ArcGIS.
> >
> > I have installed Python 2.4. I have an icon for IDLE and command line.
> > I do not see Python PythonWin.
> >
> > How do you install or launch pythonwin??
>
> There is a distribution of PythonWin bundled with the
> ArcGIS Desktop installation media, but it is not
> installed by the ArcGIS installer.
>
> You have three options:
> 1. Install it manually from the ArcGIS installation
> media.
> 2. Find it on the web (google for it), download and
> install.
> 3. (My recommendation) Don't bother. IDLE is pretty
> good. Emacs even better (unless you hate emacs).
>
> --
> Niklas Norrthon
> ESRI S-GROUP
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list

Re: Scanning through Windows registry...

2008-05-09 Thread Unknown Hero
On 9 touko, 12:51, Unknown Hero <[EMAIL PROTECTED]> wrote:

> Finally managed to get it to work (heh, I was pretty darn lost even
> though I had the best help) but as promised, I'll post my code here
> for those who might be interested in it. The biggest of thanks to Tim
> Golden, who basically walked me step-by-step through this. Most of the
> code is copied from his examples above.
>
> [large piece of code here]
>
> Not the most effecient code, I'm sure, but it does what I want it to
> do :D
>
> Thank you once more, Tim. Also, thank you, Mike, for your advice on
> saving the registry. I would have forgotten to note backing up the
> registry in the beginning if it wasn't for you bringing that up. :D

Hmm... Improving your code is always fun :D but quick fixes to make it
replace search results that contain something more than 'old' here
don't
seem to work.

So I made it command-line, with arguments Hive, old, new.

If I ran the script as registry.py HKEY_LOCAL_MACHINE something
"something else"
and I had made dummy values to the registry like "there is something
here" it
won't update to "there is something else here".

I tried this, can Tim (or someone else) possibly help?

if type == _winreg.REG_SZ:
  Character = 0
  Correct = 0
  FoundStart = FoundEnd = 0
  Found = False
  for y in range(len(data)):
if Character < len(old):
  if old[Character] is data[y]:
Character = Character + 1
Correct = Correct + 1
  if Correct is len(old):
Found = True
Replace = ""
Character = 0
for y in range(len(data)):
  if old[0] is data[y]:
FoundStart = int(y)
FoundEnd = FoundStart + oldLength
for y in range(FoundStart):
  Replace = Replace + data[y]

for y in range(len(new)):
  Replace = Replace + new[y]

for y in range(FoundEnd, len(data)):
  Replace = Replace + data[y]

  if Found:
_winreg.SetValueEx (key.key, name, 0, type, data.replace
(old, Replace))


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


Re: How to kill Python interpreter from the command line?

2008-05-09 Thread Floris Bruynooghe
On May 9, 11:19 am, [EMAIL PROTECTED] wrote:
> Thanks for the replies.
>
> On May 8, 5:50 pm, Jean-Paul Calderone <[EMAIL PROTECTED]> wrote:
>
> > Ctrl+C often works with Python, but as with any language, it's possible
> > to write a program which will not respond to it.  You can use Ctrl+\
> > instead (Ctrl+C sends SIGINT which can be masked or otherwise ignored,
> > Ctrl+\ sends SIGQUIT which typically isn't)
>
> Yes, thank you, this seems to work. :)
>
> I did some more testing and found out that the problem seems to be
> thread-related. If I have a single-threaded program, then Ctrl+C
> usually works, but if I have threads, it is usually ignored. For
> instance, the below program does not respond to Ctrl+C (but it does
> die when issued Ctrl+\):
>
> import threading
>
> def loop():
>   while True:
>     pass
>
> threading.Thread(target=loop,args=()).start()

Your thread needs to be daemonised for this work.  Othewise your main
thread will be waiting for your created thread to finish.  E.g.:

thread = threading.Thread(target=loop)
thread.setDaemon(True)
thread.start()

But now it will exit immediately as soon as your main thread has
nothing to do anymore (which is right after .start() in this case), so
plug in another infinite loop at the end of this:

while True:
time.sleep(10)

And now your threaded app will stop when using C-c.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Pythonwin

2008-05-09 Thread ivan
Not related (except that it is about python and ArcGIS): Remember you
can set PYTHONINSPECT to enter interactive mode at the end of a
script. With a script set as an ArcGIS tool, you can then enter
interactive to play around or debug with all the ArcGIS stuff loaded.

Is there a better way people do this?

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


Re: xml.etree Syntax of path?

2008-05-09 Thread Thomas Guettler

Stefan Behnel schrieb:

Thomas Guettler wrote:

I think the documentation of xml.etree is missing something[1].

{{{
find(path)
Finds the first toplevel element with given tag. Same as
getroot().find(path). path is the element to look for.
}}}

According to the source etree has limited support for xpath. I think it
should be documented what 'path' should look like to.


You mean like this?

http://effbot.org/zone/element-xpath.htm


Yes, since etree is part of the standard library, the documentation
should be there, too. Or at least a link should be provided.

 Thomas

--
Thomas Guettler, http://www.thomas-guettler.de/
E-Mail: guettli (*) thomas-guettler + de
--
http://mail.python.org/mailman/listinfo/python-list


Function creation (what happened?)

2008-05-09 Thread Viktor
Can somebody give me an explanation what happened here (or point me to
some docs)?

Code:

HMMM = None

def w(fn):
print 'fn:', id(fn)
HMMM = fn
print 'HMMM:', id(HMMM)
def wrapper(*v, **kw):
fn(*v, **kw)
wrapper.i = fn
print 'wrapper:', id(wrapper)
return wrapper

class A:
@w
def __init__(self): pass

print 'A.__init__:', id(A.__init__)
print 'A.__init__.i:', id(A.__init__.i)
print 'HMMM:', id(HMMM)



Output:

fn: 10404208
HMMM: 10404208
wrapper: 10404272
A.__init__: 10376136
A.__init__.i: 10404208
HMMM: 505264624



Why did HMMM changed his id?!
--
http://mail.python.org/mailman/listinfo/python-list


Re: Scanning through Windows registry...

2008-05-09 Thread Unknown Hero
Ah, never mind, got it to work. Here's the code now. I hope I won't
run into another problems later :D



#Goes through all keys and subkeys in the selected hive (defined as
root) and replaces the value 'old' with the value 'new'
#
#IMPORTANT! You should always back up the registry before attempting
to modify it.
#The author of this script CANNOT BE HELD RESPONSIVE for any damage
caused by running this script.
#
#To customize the script to your liking, you can alter the values old,
new, root.
#
#old and new can be any string value
#root has to be one of the following:
#
# _winreg.HKEY_LOCAL_MACHINE
# _winreg.HKEY_CURRENT_USER
# _winreg.HKEY_CLASSES_ROOT
# _winreg.HKEY_USERS
# _winreg.HKEY_CURRENT_CONFIG

import _winreg #For accessing windows registry, included in Python
2.0.
import sys #For reading arguments (command line), included in every
Python release.

HIVES = {
  "HKEY_LOCAL_MACHINE" : _winreg.HKEY_LOCAL_MACHINE,
  "HKEY_CURRENT_USER" : _winreg.HKEY_CURRENT_USER,
  "HKEY_CLASSES_ROOT" : _winreg.HKEY_CLASSES_ROOT,
  "HKEY_USERS" : _winreg.HKEY_USERS,
  "HKEY_CURRENT_CONFIG" : _winreg.HKEY_CURRENT_CONFIG
}


class RegKey:

  def __init__ (self, name, key):
 self.name = name
 self.key = key

  def __str__ (self):
return self.name

def walk (top):
  """walk the registry starting from the key represented by
  top in the form HIVE\\key\\subkey\\..\\subkey and generating
  key, subkey_names, values at each level.

  key is a lightly wrapped registry key, including the name
  and the HKEY object.
  subkey_names are simply names of the subkeys of that key
  values are 3-tuples containing (name, data, data-type).
  See the documentation for _winreg.EnumValue for more details.
  """
  try:
if "\\" not in top: top += "\\"
root, subkey = top.split ("\\", 1)
#print "KEY:", root + "\\" + subkey
key = _winreg.OpenKey (HIVES[root], subkey, 0, _winreg.KEY_READ |
_winreg.KEY_SET_VALUE)
subkeys = []
i = 0
while True:
  try:
subkeys.append (_winreg.EnumKey (key, i))
i += 1
  except EnvironmentError:
break

values = []
i = 0
while True:
  try:
values.append (_winreg.EnumValue (key, i))
i += 1
  except EnvironmentError:
break

yield RegKey (top, key), subkeys, values

for subkey in subkeys:
  for result in walk (top + "\\" + subkey):
yield result

  except WindowsError:
#print 'Could not open key', root + "\\" + subkey + ", access
denied!\n"
pass

  except:
print 'Other error!'


def main(start, startHandle, old, new):
  basickeys = []
  i = 0
  while True:
try:
  basickeys.append (_winreg.EnumKey (startHandle, i))
  i += 1
except EnvironmentError:
#  print i, 'subkeys found!'
  break

  for x in range(len(basickeys)):
for key, subkey_names, values in walk (start + "\\" +
basickeys[x]):
#  print key
  for (name, data, type) in values:
#print "  ", name, "=>", data
if type == _winreg.REG_SZ:
  Character = 0
  Correct = 0
  FoundStart = FoundEnd = 0
  Found = False
  for y in range(len(data)):
try:
  if Character < len(old):
 #   print old[Character], data[y]
if old[Character] in data[y]:
  Character = Character + 1
  Correct = Correct + 1
except:
  pass
  if Correct is len(old):
#print 'Debug!'
Replace = ""
Character = 0
for y in range(len(data)):
  if not Found:
if old[0] in data[y]:
  FoundStart = int(y)
  FoundEnd = FoundStart + len(old)
  Found = True
#for y in range(FoundStart):
#  Replace = Replace + data[y]

for y in range(len(new)):
  Replace = Replace + new[y]

#for y in range(FoundEnd, len(data)):
#  Replace = Replace + data[y]
Found = True
  if Found:
#print "OLD:", old, "will be replaced with:", Replace
_winreg.SetValueEx (key.key, name, 0, type, data.replace
(old, Replace))


def help():
  #Show help
  print 'USAGE: Registry.py [HIVE] [OLD] [NEW]'
  print '  HIVE: The root key in registry you want to go through.'
  print 'HKEY_CLASSES_ROOT'
  print 'HKEY_CURRENT_USER'
  print 'HKEY_LOCAL_MACHINE'
  print 'HKEY_USERS'
  print 'HKEY_CURRENT_CONFIG'
  print ''
  print '  OLD:  The value to search for.'
  print 'Wrap multiword strings with \"\".'
  print ''
  print '  NEW:  The value which will replace OLD.'
  print 'Wrap multiword strings with \"\".'

#Check for arguments
#HIVE, old, new

while True:
  #Check if invalid number of arguments are given
  if len(sys.argv) is 1:
help()
break

#  for x in range(len(sys.argv)):
#print 'sys.argv[' + str(x) + ']:', sys.argv[x]

  #Check if hive is 

Re: Function creation (what happened?)

2008-05-09 Thread Chris Hulan
On May 9, 8:25 am, Viktor <[EMAIL PROTECTED]> wrote:
> Can somebody give me an explanation what happened here (or point me to
> some docs)?
>
> Code:
>
> HMMM = None
>
> def w(fn):
> print 'fn:', id(fn)
> HMMM = fn
> print 'HMMM:', id(HMMM)
> def wrapper(*v, **kw):
> fn(*v, **kw)
> wrapper.i = fn
> print 'wrapper:', id(wrapper)
> return wrapper
>
> class A:
> @w
> def __init__(self): pass
>
> print 'A.__init__:', id(A.__init__)
> print 'A.__init__.i:', id(A.__init__.i)
> print 'HMMM:', id(HMMM)
>
> Output:
>
> fn: 10404208
> HMMM: 10404208
> wrapper: 10404272
> A.__init__: 10376136
> A.__init__.i: 10404208
> HMMM: 505264624
>
> Why did HMMM changed his id?!

The HMMM inside w is local to that function and is not the same HMMM
that is defined just before w.
Have a look at http://docs.python.org/ref/global.html

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


Re: Function creation (what happened?)

2008-05-09 Thread Duncan Booth
Viktor <[EMAIL PROTECTED]> wrote:

> Can somebody give me an explanation what happened here (or point me to
> some docs)?
> 
> Code:
> 
> HMMM = None
> 
> def w(fn):
> print 'fn:', id(fn)
> HMMM = fn
> print 'HMMM:', id(HMMM)
> def wrapper(*v, **kw):
> fn(*v, **kw)
> wrapper.i = fn
> print 'wrapper:', id(wrapper)
> return wrapper
> 
> class A:
> @w
> def __init__(self): pass
> 
> print 'A.__init__:', id(A.__init__)
> print 'A.__init__.i:', id(A.__init__.i)
> print 'HMMM:', id(HMMM)
> 
> 
> 
> Output:
> 
> fn: 10404208
> HMMM: 10404208
> wrapper: 10404272
> A.__init__: 10376136
> A.__init__.i: 10404208
> HMMM: 505264624
> 
> 
> 
> Why did HMMM changed his id?!

It didn't: global HMMM refers to None both before and after executing 
the rest of your code. The other HMMM is local to a particular 
invocation of w. Try the same steps interactively (and try printing the 
values not just the ids) and it may be more obvious:

>>> HMMM = None
>>> print 'HMMM:', id(HMMM)
HMMM: 505264624
>>> def w(fn):
print 'fn:', id(fn)
HMMM = fn
print 'HMMM:', id(HMMM)
def wrapper(*v, **kw):
fn(*v, **kw)
wrapper.i = fn
print 'wrapper:', id(wrapper)
return wrapper

>>> class A:
@w
def __init__(self): pass


fn: 18299952
HMMM: 18299952
wrapper: 18300016
>>> print 'HMMM:', id(HMMM), HMMM
HMMM: 505264624 None
>>> 
--
http://mail.python.org/mailman/listinfo/python-list


Re: Function creation (what happened?)

2008-05-09 Thread Peter Otten
Viktor wrote:

> Can somebody give me an explanation what happened here (or point me to
> some docs)?
> 
> Code:
> 
> HMMM = None
> 
> def w(fn):
> print 'fn:', id(fn)
> HMMM = fn
> print 'HMMM:', id(HMMM)

This prints the id() of the local (to the function w()) HMMM variable

> def wrapper(*v, **kw):
> fn(*v, **kw)
> wrapper.i = fn
> print 'wrapper:', id(wrapper)
> return wrapper
> 
> class A:
> @w
> def __init__(self): pass
> 
> print 'A.__init__:', id(A.__init__)
> print 'A.__init__.i:', id(A.__init__.i)
> print 'HMMM:', id(HMMM)

while this prints the id() of the global HMMM variable. Python assumes that
a variable is local to a function if there is an assignment to that
variable anywhere inside that function.

If you want to change the variable (Python-lingo "rebind the name") HMMM
declare it as global in the function:

def w(fn):
global HMMM
# ...
HMMM = fn
# ...

Otherwise I've no idea what you are trying to do here...

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


Re: Function creation (what happened?)

2008-05-09 Thread Viktor
This completely slipped of my mind... :)

I'm trying to change the:
http://wordaligned.org/svn/etc/echo/echo.py

So if the function is method it prints ClassName.MethodName instead of
MethodName(self|klass|cls=<... ClassName>).

But it turned out that in the decorator, the wrapped function is
always just a TypeFunction (I cannot find out if the function is
method, classmethod, staticmethod or just a plain function - tried
with inspect also)... And what is most interesting, when I do:

def w(fn):
print 'fn:', id(fn)
return fn

class A:
@w
def __init__(self): pass

print 'A.__init__:', id(A.__init__)

It turns out that the function I receive in the wrapper (even when I
return the same function) is not the function which will finally be
attached to the class...

Is there a way to find out in the decorator "what will the decorated
function be"?
--
http://mail.python.org/mailman/listinfo/python-list


ANN: Pyrex 0.9.7

2008-05-09 Thread greg

Pyrex 0.9.7 is now available:

  http://www.cosc.canterbury.ac.nz/greg.ewing/python/Pyrex/

Highlights of this version:

* I have streamlined the integer for-loop syntax. Instead
  of the loop variable redundantly appearing in two places,
  it's now just

for x < i < y:
  ...

* If you declare a variable as a list or dict, then calls
  to some of its methods will be compiled into type-specific
  Python API calls instead of generic ones.

* Most built-in constants are referenced directly instead of
  via dict lookup.

* There are two new builtin functions, typecheck() and
  issubtype(), for checking the types of arguments more safely
  (since isinstance and issubclass can be fooled).

What is Pyrex?
--

Pyrex is a language for writing Python extension modules.
It lets you freely mix operations on Python and C data, with
all Python reference counting and error checking handled
automatically.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Pythonwin

2008-05-09 Thread Mike Driscoll
On May 9, 5:30 am, Clive_S <[EMAIL PROTECTED]> wrote:
> Hi
>
> I am trying to use Python with ArcGIS.
>
> I have installed Python 2.4. I have an icon for IDLE and command line.
> I do not see Python PythonWin.
>
> How do you install or launch pythonwin??
>
> Thanks
>
> Clive

I have PythonWin installed in my Start Menu --> Programs --> Python
2.5. I may have installed the ActiveState version though. Just check
if it's there on your system and if not, you can follow Niklas's
advice.

Mike

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


Re: How to kill Python interpreter from the command line?

2008-05-09 Thread Banibrata Dutta
Any chance that there is a "catch-all" in the code.
As per PEP8 and I'm sure common knowledge of all the folks programming in
Python for a while -- a
>>>catch:
could just lead to this problem.


On 5/9/08, Floris Bruynooghe <[EMAIL PROTECTED]> wrote:
>
> On May 9, 11:19 am, [EMAIL PROTECTED] wrote:
> > Thanks for the replies.
> >
> > On May 8, 5:50 pm, Jean-Paul Calderone <[EMAIL PROTECTED]> wrote:
> >
> > > Ctrl+C often works with Python, but as with any language, it's possible
> > > to write a program which will not respond to it.  You can use Ctrl+\
> > > instead (Ctrl+C sends SIGINT which can be masked or otherwise ignored,
> > > Ctrl+\ sends SIGQUIT which typically isn't)
> >
> > Yes, thank you, this seems to work. :)
> >
> > I did some more testing and found out that the problem seems to be
> > thread-related. If I have a single-threaded program, then Ctrl+C
> > usually works, but if I have threads, it is usually ignored. For
> > instance, the below program does not respond to Ctrl+C (but it does
> > die when issued Ctrl+\):
> >
> > import threading
> >
> > def loop():
> >   while True:
> > pass
> >
> > threading.Thread(target=loop,args=()).start()
>
> Your thread needs to be daemonised for this work.  Othewise your main
> thread will be waiting for your created thread to finish.  E.g.:
>
> thread = threading.Thread(target=loop)
> thread.setDaemon(True)
> thread.start()
>
> But now it will exit immediately as soon as your main thread has
> nothing to do anymore (which is right after .start() in this case), so
> plug in another infinite loop at the end of this:
>
> while True:
>time.sleep(10)
>
> And now your threaded app will stop when using C-c.
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
regards,
Banibrata
http://www.linkedin.com/in/bdutta
http://octapod.wordpress.com
--
http://mail.python.org/mailman/listinfo/python-list

Re: Pythonwin

2008-05-09 Thread Banibrata Dutta
if one has installed ActiveState Python 2.5, I think it'd have been
  Start Menu --> Programs --> ActiveSte ActivePython 2.5 --> 
and I think it delivers IDLE, not PythonWin.


On 5/9/08, Mike Driscoll <[EMAIL PROTECTED]> wrote:
>
> On May 9, 5:30 am, Clive_S <[EMAIL PROTECTED]> wrote:
> > Hi
> >
> > I am trying to use Python with ArcGIS.
> >
> > I have installed Python 2.4. I have an icon for IDLE and command line.
> > I do not see Python PythonWin.
> >
> > How do you install or launch pythonwin??
> >
> > Thanks
> >
> > Clive
>
> I have PythonWin installed in my Start Menu --> Programs --> Python
> 2.5. I may have installed the ActiveState version though. Just check
> if it's there on your system and if not, you can follow Niklas's
> advice.
>
> Mike
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
regards,
Banibrata
http://www.linkedin.com/in/bdutta
http://octapod.wordpress.com
--
http://mail.python.org/mailman/listinfo/python-list

Re: Function creation (what happened?)

2008-05-09 Thread George Sakkis
On May 9, 9:02 am, Viktor <[EMAIL PROTECTED]> wrote:
> This completely slipped of my mind... :)
>
> I'm trying to change the:http://wordaligned.org/svn/etc/echo/echo.py
>
> So if the function is method it prints ClassName.MethodName instead of
> MethodName(self|klass|cls=<... ClassName>).
>
> But it turned out that in the decorator, the wrapped function is
> always just a TypeFunction (I cannot find out if the function is
> method, classmethod, staticmethod or just a plain function - tried
> with inspect also)... And what is most interesting, when I do:
>
> def w(fn):
>     print 'fn:', id(fn)
>     return fn
>
> class A:
>     @w
>     def __init__(self): pass
>
> print 'A.__init__:', id(A.__init__)
>
> It turns out that the function I receive in the wrapper (even when I
> return the same function) is not the function which will finally be
> attached to the class...
>
> Is there a way to find out in the decorator "what will the decorated
> function be"?

The decorator does receive the correct function. The problem is that
at this point __init__ is still a plain function, not a method, i.e.
the sequence is:
   function -> decorated function -> method

There are several workarounds if you really want to differentiate
between functions and methods, none of them perfect:

- Apply the decorator after the class has been built, i.e. after the
functions have been wrapped in (unbound) methods:
A.__init__ = w(A.__init__)

- (Risky Hack): Guess whether a function is intended to be wrapped in
a method by checking whether its first argument is named "self".
Obviously this is not foolproof and it doesn't work for static/class
methods.

- Have two different decorators, one intended for plain functions and
one for functions-to-be-methods (e.g. @deco, @decomethod).

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


Re: "prove"

2008-05-09 Thread Lucas Prado Melo
On Fri, May 9, 2008 at 5:32 AM, Bruno Desthuilliers
<[EMAIL PROTECTED]> wrote:
> Why do you need the documentation ? Just fire up your python shell and hack
> a Q&D example:
I agree. I said it to this person, but he insisted I should use documentation...
--
http://mail.python.org/mailman/listinfo/python-list


Re: How can I add spaces where ever I have capital letters?

2008-05-09 Thread MRAB
On May 9, 3:04 am, "Eric Wertman" <[EMAIL PROTECTED]> wrote:
> Something like this.  I'm sure there are other ways to do it.
>
> import re
>
> def addspace(m) :
> return ' ' + m.group(0)
>
> strng = "ModeCommand"
>
> newstr =  re.sub('[A-Z]',addspace,strng)
>
Alternatively:

newstr = re.sub('([A-Z])',r' \1',strng)

> print newstr.strip()
>
> On Thu, May 8, 2008 at 9:12 PM, John Schroeder <[EMAIL PROTECTED]> wrote:
> > I have a string (which I got from the names of my classes) and I would like
> > to print out my CamelCase classes as titles.
>
> > I would like it to do this:
>
>  my_class_name = "ModeCommand"
> > ## Do some magic here
>  my_class_name
> > 'Mode Command'
>
> > Anyone know any easy way to do this?  Thanks.
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: Pythonwin

2008-05-09 Thread Banibrata Dutta
oops moment!

I was wrong. indeed, you should find PythonWin there, if you installed
ActiveState Python.


On 5/9/08, Banibrata Dutta <[EMAIL PROTECTED]> wrote:
>
> if one has installed ActiveState Python 2.5, I think it'd have been
>   Start Menu --> Programs --> ActiveSte ActivePython 2.5 --> 
> and I think it delivers IDLE, not PythonWin.
>
>
> On 5/9/08, Mike Driscoll <[EMAIL PROTECTED]> wrote:
>>
>> On May 9, 5:30 am, Clive_S <[EMAIL PROTECTED]> wrote:
>> > Hi
>> >
>> > I am trying to use Python with ArcGIS.
>> >
>> > I have installed Python 2.4. I have an icon for IDLE and command line.
>> > I do not see Python PythonWin.
>> >
>> > How do you install or launch pythonwin??
>> >
>> > Thanks
>> >
>> > Clive
>>
>> I have PythonWin installed in my Start Menu --> Programs --> Python
>> 2.5. I may have installed the ActiveState version though. Just check
>> if it's there on your system and if not, you can follow Niklas's
>> advice.
>>
>> Mike
>>
>> --
>> http://mail.python.org/mailman/listinfo/python-list
>>
>
>
>
> --
> regards,
> Banibrata
> http://www.linkedin.com/in/bdutta
> http://octapod.wordpress.com




-- 
regards,
Banibrata
http://www.linkedin.com/in/bdutta
http://octapod.wordpress.com
--
http://mail.python.org/mailman/listinfo/python-list

Re: "prove"

2008-05-09 Thread Lucas Prado Melo
Thanks for all the answers. I bet I will convince this guy!
--
http://mail.python.org/mailman/listinfo/python-list


Re: how to pass C++ object to another C++ function via Python function

2008-05-09 Thread grbgooglefan
Yes, that worked. I "protected" the variable which I did not want to
get freed. I incremented reference for that variable & it started
working.

Thanks for all your guidance.

On May 3, 5:23 am, "Gabriel Genellina" <[EMAIL PROTECTED]> wrote:
> Python will do nothing with the pointer inside a PyCObject - unless you  
> want to, and pass a cleanup function as the second argument to the  
> PyCObject constructor.
>
> --
> Gabriel Genellina- Hide quoted text -
>
> - Show quoted text -

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


Re: Function creation (what happened?)

2008-05-09 Thread Viktor
I figured out the first two solutions, but the third looks like the
most cleaner, think I'll use that one...

Thank you everyone. :)

On May 9, 3:24 pm, George Sakkis <[EMAIL PROTECTED]> wrote:
> The decorator does receive the correct function. The problem is that
> at this point __init__ is still a plain function, not a method, i.e.
> the sequence is:
>function -> decorated function -> method
>
> There are several workarounds if you really want to differentiate
> between functions and methods, none of them perfect:
>
> - Apply the decorator after the class has been built, i.e. after the
> functions have been wrapped in (unbound) methods:
> A.__init__ = w(A.__init__)
>
> - (Risky Hack): Guess whether a function is intended to be wrapped in
> a method by checking whether its first argument is named "self".
> Obviously this is not foolproof and it doesn't work for static/class
> methods.
>
> - Have two different decorators, one intended for plain functions and
> one for functions-to-be-methods (e.g. @deco, @decomethod).
>
> George

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


Web Framework suggestions for a RIA type application for managing lab specimens

2008-05-09 Thread rynt
Hello all.

I'm Looking for suggestions for which Python web framework(e.g.
Django, Turbogears,etc.) would work best to develop a cross platform
browser based system to manage lab specimens.

Requirements are:
a. highly secure
b. run on internet or intranet
e. RDBMS read/write intensive
d. be able to work on-line or off-line (with automatic updates to db
when coming back on-line)
e. be able to print reports and labels using a variety of
printers(laser, deskjet, label printers)
f. have a rich set of desktop-like components

Perhaps a web based app isn't the way to go.  Arguments for and
against gratefully accepted.

Pros and Cons for any frameworks gratefully accepted.

Perhaps a framework isn't really what's needed here, but a combination
of different web components and technologies?

Anyway, I'm grateful for any ideas you may be able to give me.

Thanks
Ruben

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


Re: python newbie: some surprises

2008-05-09 Thread v4vijayakumar
On May 9, 1:48 pm, Bruno Desthuilliers  wrote:
> v4vijayakumar a écrit :
>
> > When I started coding in python, these two things surprised me.
>
> > 1. my code is inconsistently indented with the combination of tabs and
> > spaces. Even lines looked intended, but it is not.
>
> Then you have a problem with your code editor - not with Python.
>

Editors can not be wrong. :)

I think there should be some way to say python compiler, to consider
tab and two blank spaces equal, when tab space = 2.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Pythonwin

2008-05-09 Thread Clive_S
Hi all

I downloaded (from Python) and installed python-2.4.4.msi

I have python and pythonw.exe in the Python 24 folder (but not in my
start menu).
When I click on the pythonw.exe it is not launched??

Thanks

Clive


On 9 May, 14:09, Mike Driscoll <[EMAIL PROTECTED]> wrote:
> On May 9, 5:30 am, Clive_S <[EMAIL PROTECTED]> wrote:
>
> > Hi
> > I am trying to use Python with ArcGIS.
> > I have installed Python 2.4. I have an icon for IDLE and command line.
> > I do not see Python PythonWin.
> > How do you install or launch pythonwin??
> > Thanks
> > Clive
>
> I have PythonWin installed in my Start Menu --> Programs --> Python
> 2.5. I may have installed the ActiveState version though. Just check
> if it's there on your system and if not, you can follow Niklas's
> advice.
>
> Mike

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


How to modify meaning of builtin function "not" to "!"?

2008-05-09 Thread grbgooglefan
I am creating functions, the return result of which I am using to make
decisions in combined expressions.
In some expressions, I would like to inverse the return result of
function.

E.g. function contains(source,search) will return true if "search"
string is found in source string.
I want to make reverse of this by putting it as:
if ( ! contains(s1,s2) ):
 return 1

I found that "!" is not accepted by Python & compile fails with
"invalid syntax".
Corresponding to this Boolean Operator we've "not" in Python.

How can I make "not" as "!"?
--
http://mail.python.org/mailman/listinfo/python-list


bytes1.shuffle( )

2008-05-09 Thread castironpi
random.shuffle( bytes1 )

if random == bytes:
   repunctuate( sentence )
else:
   random.shuffle( [ random ] )

sincerely exit, ()
--
http://mail.python.org/mailman/listinfo/python-list


回复: Re: Pythonwin

2008-05-09 Thread <潍坊风筝>

  In arcgis dvd , you can find a "desktop" file ,open the file ,then a 
"pythonwin" file,open the file ,then you install "pywin32-207.win32-py2.4.exe"
  THIS IS OK!
Banibrata Dutta <[EMAIL PROTECTED]> 写道:
if one has installed ActiveState Python 2.5, I think it'd have been 
  Start Menu --> Programs --> ActiveSte ActivePython 2.5 --> 
  and I think it delivers IDLE, not PythonWin.
  
 
  On 5/9/08, Mike Driscoll <[EMAIL PROTECTED]> wrote:   On May 9, 5:30 am, 
Clive_S <[EMAIL PROTECTED]> wrote:
> Hi
>
> I am trying to use Python with ArcGIS.
>
> I have installed Python 2.4. I have an icon for IDLE and command line.
> I do not see Python PythonWin.
>
> How do you install or launch pythonwin??
>
> Thanks
>
> Clive

I have PythonWin installed in my Start Menu --> Programs --> Python
2.5. I may have installed the ActiveState version though. Just check
if it's there on your system and if not, you can follow Niklas's
advice.

Mike

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




-- 
regards,
Banibrata
http://www.linkedin.com/in/bdutta
http://octapod.wordpress.com --
http://mail.python.org/mailman/listinfo/python-list

   
-
 雅虎邮箱,您的终生邮箱!--
http://mail.python.org/mailman/listinfo/python-list

RE: Pythonwin

2008-05-09 Thread Ahmed, Shakir
You need to install the same version on your pc, if you have 2.5 already 
installed you need to download 2.5 pythonwin from http://sourceforge.net

Hope it will work for you.
Thanks
sk


-Original Message-
From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf Of Clive_S
Sent: Friday, May 09, 2008 9:41 AM
To: python-list@python.org
Subject: Re: Pythonwin

Hi all

I downloaded (from Python) and installed python-2.4.4.msi

I have python and pythonw.exe in the Python 24 folder (but not in my
start menu).
When I click on the pythonw.exe it is not launched??

Thanks

Clive


On 9 May, 14:09, Mike Driscoll <[EMAIL PROTECTED]> wrote:
> On May 9, 5:30 am, Clive_S <[EMAIL PROTECTED]> wrote:
>
> > Hi
> > I am trying to use Python with ArcGIS.
> > I have installed Python 2.4. I have an icon for IDLE and command line.
> > I do not see Python PythonWin.
> > How do you install or launch pythonwin??
> > Thanks
> > Clive
>
> I have PythonWin installed in my Start Menu --> Programs --> Python
> 2.5. I may have installed the ActiveState version though. Just check
> if it's there on your system and if not, you can follow Niklas's
> advice.
>
> Mike

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

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


help needed!

2008-05-09 Thread drjekil

i have a script which will do a specific task for a file in a folder,now i
would like to do the same task  for the all files in that folder(25
files).how can i do that?

Thanks in advance.

-- 
View this message in context: 
http://www.nabble.com/help-needed%21-tp17148388p17148388.html
Sent from the Python - python-list mailing list archive at Nabble.com.

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


observer pattern (notification chain synchronization)

2008-05-09 Thread Alan Isaac

A question related to the observer pattern...

Suppose I have a variant: there are stocks, mutual funds, and investors.  Let us say that funds are observers for multiple stocks, and investors are observers for funds.  Once a "month" all stocks notify their observing funds of their end-of-month price, and *then* all fund to notify their observing investors of their end-of-month investment value. 


What is a good way to enforce this timing?  (I.e., a fund should not notify an 
its investors until all stocks have reported.)

Here is one way:

- for each fund, create a ``reportreceived`` dict that maps stocks to booleans 
(initially False)
- as each stock notifies its funds, the fund changes False to True and checks 
``all(reportreceived.values())`` to determine whether it is ok to notify 
investors.
- When it is ok, the fund notifies investors and resets all the ``reportreceived`` values. 


Is this sensible enough? What are standard and better ways?

Thank you, 
Alan Isaac 


PS I am drawing on the description of the observer pattern at
http://www.dofactory.com/Patterns/PatternObserver.aspx#_self1>
The real world aspects are just to add some concreteness.
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to modify meaning of builtin function "not" to "!"?

2008-05-09 Thread Ivan Voras
grbgooglefan wrote:
> I am creating functions, the return result of which I am using to make
> decisions in combined expressions.
> In some expressions, I would like to inverse the return result of
> function.
> 
> E.g. function contains(source,search) will return true if "search"
> string is found in source string.
> I want to make reverse of this by putting it as:
> if ( ! contains(s1,s2) ):
>  return 1
> 
> I found that "!" is not accepted by Python & compile fails with
> "invalid syntax".
> Corresponding to this Boolean Operator we've "not" in Python.
> 
> How can I make "not" as "!"?

"not" is a perfectly valid boolean operator in Python and means just
what "!" means in C. The equivalent binary operator is "~", just like in C.

>>> print not True
False
>>> print not 1
False
>>> print not 0
True
>>> print ~1
-2
>>> print ~0
-1




signature.asc
Description: OpenPGP digital signature
--
http://mail.python.org/mailman/listinfo/python-list

Re: Pythonwin

2008-05-09 Thread Gabriel Genellina
En Fri, 09 May 2008 10:40:38 -0300, Clive_S <[EMAIL PROTECTED]> escribió:

> I downloaded (from Python) and installed python-2.4.4.msi
>
> I have python and pythonw.exe in the Python 24 folder (but not in my
> start menu).
> When I click on the pythonw.exe it is not launched??

pythonw.exe is NOT PythonWin - it's a consoleless version of the standard 
Python interpreter.
PythonWin is part of the pywin32 package that you can download from 
https://sourceforge.net/projects/pywin32/ (make sure you get the right version)

-- 
Gabriel Genellina

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


Dynamic generation of images (was Re: Custom Classes?)

2008-05-09 Thread J. Cliff Dyer
On Thu, 2008-05-08 at 10:33 -0500, Victor Subervi wrote:
> Okay, trying this again with everything working and no ValueError or
> any other errors, here we go:
> 
> Load this code. Unless you use a similar login() script, you will want
> to edit your own values into the user, passwd, db and host:
> 
> #!/usr/bin/python
> 
> import MySQLdb
> 
> import sys,os
> sys.path.append(os.getcwd())
> from login import login
> user, passwd, db, host = login()
> 
> pic = "pic1"
> w = 20
> x = 0
> d = 6
> y = 1
> 
> getpic = "getpic" + str(w) + ".py"
> try:
>   os.remove(getpic)
> except:
>   pass
> code = """
> #!/usr/local/bin/python
> import cgitb; cgitb.enable()
> import MySQLdb
> import cgi
> import sys,os
> sys.path.append(os.getcwd())
> from login import login
> user, passwd, db, host = login()
> form = cgi.FieldStorage()
> picid = int(form["id"].value)
> x = int(form["x"].value)
> pics =
> {1:'pic1',2:'pic1_thumb',3:'pic2',4:'pic2_thumb',5:'pic3',6:'pic3_thumb',7:'pic4',8:'pic4_thumb',\
> 9:'pic5',10:'pic5_thumb',11:'pic6',12:'pic6_thumb'}
> pic = pics[x]
> db = MySQLdb.connect(host, user, passwd, db)
> cursor= db.cursor()
> sql = "select %s from products where id='%s';" % (pic, str(picid))
> 
> cursor.execute(sql)
> content = cursor.fetchall()[0][0].tostring()
> cursor.close()
> print 'Content-Type: image/jpeg'
> print
> print content
> """
> script = open(getpic, "w")
> script.write(code)
> script.close()
> 
> 
> 
> and then surf to:
> http://whatever.url/getpic20.py?id=6&x=1
> 
> 
> Also, please re-send the link on how to post good questions to the
> list. I cannot find it.
> TIA,
> Victor

Why are you dynamically creating getpic20.py?

Obviously, in the real script, you probably have several of them:
getpic1.py, getpic2.py, etc., but is there any reason you couldn't just
have one getpic.py, and pass the number in as a parameter in your GET
request, like this:

http://localhost/getpic.py?id=6&x=1&w=20

Then you can just have a static getpic.py.  I've stripped out useless
bits:

* You don't use sys or os, so why import them?
* MySQL makes it difficult for me to replicate your behavior, because I 
  don't have your DB setup.  The DB call has been replaced with a
  dictionary of keys into JPG data, pulled from the filesystem.  Change 
  filenames to jpegs on your own hard drive
* login is useless without MySQL.

So your new getpic.py (statically created) looks like this:

~~~ getpic.py ~~~
#!/usr/local/bin/python

import cgitb; cgitb.enable()
import cgi

pics = { 
1: open('pic.jpg').read(),
2: open('pic2.jpg').read()
}
# you could just pass the filename, and then you wouldn't have to load
the
# image data in advance, but this more closely mimics the concept of
your DB 
# setup.

form = cgi.FieldStorage()
x = int(form["x"].value)
pic = pics[x]

print 'Content-Type: image/jpeg'
print
print pic
~~~

Then if you want to include your pictures in a web page, you do

~~~ show_pics.html ~~~

  Pictures
  
pictures


  

~~~

This should work just as well when you refactor the script to pull from
the database.

Hope this helps.  Also, the article on asking good questions is
available here:  http://catb.org/~esr/faqs/smart-questions.html



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


RE: How to modify meaning of builtin function "not" to "!"?

2008-05-09 Thread Reedick, Andrew
> -Original Message-
> From: [EMAIL PROTECTED] [mailto:python-
> [EMAIL PROTECTED] On Behalf Of grbgooglefan
> Sent: Friday, May 09, 2008 9:41 AM
> To: python-list@python.org
> Subject: How to modify meaning of builtin function "not" to "!"?
> 
> I am creating functions, the return result of which I am using to make
> decisions in combined expressions.
> In some expressions, I would like to inverse the return result of
> function.
> 
> E.g. function contains(source,search) will return true if "search"
> string is found in source string.
> I want to make reverse of this by putting it as:
> if ( ! contains(s1,s2) ):
>  return 1
> 
> I found that "!" is not accepted by Python & compile fails with
> "invalid syntax".
> Corresponding to this Boolean Operator we've "not" in Python.
> 
> How can I make "not" as "!"?


Serious question:  Why would you want to?  'not' is easier to read (and type) 
than '!'.  Mentally, when you  see '!' you think 'not'.  It's also harder to 
overlook 'not', especially when compared to '!contains()'.  Finally, I imagine 
that Spanish speaking coders suffer enormous mental anguish when they see a 
right-side up '!' at the beginning of a sentence.

if ( ! contains(s1,s2) ):
 return 1

if ( !contains(s1,s2) ):
 return 1

if ( not contains(s1,s2) ):
 return 1

if ( ¡contains(s1,s2)):
 return 1




*

The information transmitted is intended only for the person or entity to which 
it is addressed and may contain confidential, proprietary, and/or privileged 
material. Any review, retransmission, dissemination or other use of, or taking 
of any action in reliance upon this information by persons or entities other 
than the intended recipient is prohibited. If you received this in error, 
please contact the sender and delete the material from all computers. GA625


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


Re: How to modify meaning of builtin function "not" to "!"?

2008-05-09 Thread castironpi
On May 9, 8:41 am, grbgooglefan <[EMAIL PROTECTED]> wrote:
> I am creating functions, the return result of which I am using to make
> decisions in combined expressions.
> In some expressions, I would like to inverse the return result of
> function.
>
> E.g. function contains(source,search) will return true if "search"
> string is found in source string.
> I want to make reverse of this by putting it as:
> if ( ! contains(s1,s2) ):
>      return 1
>
> I found that "!" is not accepted by Python & compile fails with
> "invalid syntax".
> Corresponding to this Boolean Operator we've "not" in Python.
>
> How can I make "not" as "!"?

I have found that not 8, not not 8, and ~8 are all valid.  Valid8 is
not.

NameError: name 'Valid8' is not defined, where defined is not defined,
and @Valid8 @Valid8 ...

Late-binding logicals are fine.  #Valid8
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to modify meaning of builtin function "not" to "!"?

2008-05-09 Thread Bruno Desthuilliers

grbgooglefan a écrit :

I am creating functions, the return result of which I am using to make
decisions in combined expressions.
In some expressions, I would like to inverse the return result of
function.

E.g. function contains(source,search) will return true if "search"
string is found in source string.


Do you really need a function for this ?

if "foo" in "foobar":
   print "do you really really need a function for this ?"



I want to make reverse of this by putting it as:
if ( ! contains(s1,s2) ):
 return 1


which is a convoluted way to write:

  return s2 not in s1



I found that "!" is not accepted by Python & compile fails with
"invalid syntax".
Corresponding to this Boolean Operator we've "not" in Python.

How can I make "not" as "!"?


Err... How to say... The boolean negation operator in Python is "not". 
So the only answer I can provide is : "use 'not' instead of '!'". And 
while we're at it : drop those useless parens.


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


Re: Pythonwin

2008-05-09 Thread Mike Driscoll
On May 9, 9:02 am, "Gabriel Genellina" <[EMAIL PROTECTED]> wrote:
> En Fri, 09 May 2008 10:40:38 -0300, Clive_S <[EMAIL PROTECTED]> escribió:
>
> > I downloaded (from Python) and installed python-2.4.4.msi
>
> > I have python and pythonw.exe in the Python 24 folder (but not in my
> > start menu).
> > When I click on the pythonw.exe it is not launched??
>
> pythonw.exe is NOT PythonWin - it's a consoleless version of the standard 
> Python interpreter.
> PythonWin is part of the pywin32 package that you can download 
> fromhttps://sourceforge.net/projects/pywin32/(make sure you get the right 
> version)
>
> --
> Gabriel Genellina

Ah. That's where I got it. Sorry for promulgating my own confusion!

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


Re: help needed!

2008-05-09 Thread Mike Driscoll
On May 9, 8:54 am, drjekil <[EMAIL PROTECTED]> wrote:
> i have a script which will do a specific task for a file in a folder,now i
> would like to do the same task  for the all files in that folder(25
> files).how can i do that?
>
> Thanks in advance.
>
> --
> View this message in 
> context:http://www.nabble.com/help-needed%21-tp17148388p17148388.html
> Sent from the Python - python-list mailing list archive at Nabble.com.

Use a loop, probably in combination with os.walk.

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


Can I "delete" the namespace of a module that i import?

2008-05-09 Thread gbin,Zhou
Hi,all.
   I see from "http://docs.python.org/tut/node11.html"; that "Name
spaces are created at different moments and have different lifetimes.
The namespace containing the built-in names is created when the Python
interpreter starts up, and is never deleted. The global namespace for
a module is created when the module definition is read in; normally,
module namespaces also last until the interpreter quits."
   So can I "delete" the namespace of a module that i import?
   thanks.
--
http://mail.python.org/mailman/listinfo/python-list


Re: help needed!

2008-05-09 Thread Mike Driscoll
On May 9, 8:54 am, drjekil <[EMAIL PROTECTED]> wrote:
> i have a script which will do a specific task for a file in a folder,now i
> would like to do the same task  for the all files in that folder(25
> files).how can i do that?
>
> Thanks in advance.
>
> --
> View this message in 
> context:http://www.nabble.com/help-needed%21-tp17148388p17148388.html
> Sent from the Python - python-list mailing list archive at Nabble.com.

Or use the glob module and a loop...

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


Re: Newbie to python --- why should i learn !

2008-05-09 Thread hdante
On May 8, 7:25 am, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]>
wrote:
> Hi,
>
> i was reading/learning some hello world program in python.
> I think its very simillar to Java/C++/C#. What's different (except
> syntax) ?

 All the languages have similar "power", in a theoretical sense. If
you can solve a problem with one, most of the time you'll be able to
solve it with the other. So we could say that the languages are
"equal".

 However, in practice, the syntax matters a lot. For example, they
will influence on the maintainability and the performance of your
application.

>
> what can i do easily with python which is not easy in c++/java !?

 Pretty much everything. Python syntax is minimalist, so it requires
much less code. There are many examples in Wikipedia, for example:

 http://en.wikipedia.org/wiki/User_datagram_protocol#Sample_code_.28Python.29
 http://pt.wikipedia.org/wiki/Radix_sort#C.C3.B3digo_em_Java
 http://en.wikipedia.org/wiki/Observer_pattern#Python

 etc.

>
> Tnx,
> Raxitwww.mykavita.com

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


Re: multiple Python versions, but on Windows (how to handle registry updates)

2008-05-09 Thread Gabriel Genellina
En Fri, 09 May 2008 07:58:33 -0300, Banibrata Dutta <[EMAIL PROTECTED]> 
escribió:

> I already have Python25, and need to install Python24. I would prefer not to
> remove Python25, but each Python version seems to update the registry, I
> guess (not sure), overwriting each other's entries. Any way to have both
> versions ?

They can coexist peacefully. The last one you install will be the default 
version to handle .py files automatically.

You may want to create a batch file like this:


@c:\python24\python.exe %*


(and a similar one for 2.5; put them somewhere on your PATH, like 
c:\windows\system32)
Usage: python24 somescript.py

-- 
Gabriel Genellina

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


Re: Web Framework suggestions for a RIA type application for managing lab specimens

2008-05-09 Thread Bruno Desthuilliers

rynt a écrit :

Hello all.

I'm Looking for suggestions for which Python web framework(e.g.
Django, Turbogears,etc.) would work best to develop a cross platform
browser based system to manage lab specimens.

Requirements are:
a. highly secure
b. run on internet or intranet
e. RDBMS read/write intensive
d. be able to work on-line or off-line (with automatic updates to db
when coming back on-line)


can't be handled by a web framework alone - you'll need client-side support.


e. be able to print reports and labels using a variety of
printers(laser, deskjet, label printers)


it's mostly a client-side problem.


f. have a rich set of desktop-like components


A web app is restricted to what's available in HTML (possibly using 
Javascript).


Perhaps a web based app isn't the way to go.  


Looks like you want a "rich" (desktop) GUI client. Note that (given 
proper design and architecture) you can have a same server-side backend 
for both, but that means quite a lot of code.


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


Re: observer pattern (notification chain synchronization)

2008-05-09 Thread J. Cliff Dyer
That looks like a good approach to me.  Alternative to a dict would just
be a count of reported stocks tested against the total number of stocks,
but if one stock reports twice before another reports at all, you'll get
funny results.  Your method is probably better, in the general case.

Cheers,
Cliff


On Fri, 2008-05-09 at 13:51 +, Alan Isaac wrote:
> A question related to the observer pattern...
> 
> Suppose I have a variant: there are stocks, mutual funds, and investors.  Let 
> us say that funds are observers for multiple stocks, and investors are 
> observers for funds.  Once a "month" all stocks notify their observing funds 
> of their end-of-month price, and *then* all fund to notify their observing 
> investors of their end-of-month investment value. 
> 
> What is a good way to enforce this timing?  (I.e., a fund should not notify 
> an its investors until all stocks have reported.)
> 
> Here is one way:
> 
> - for each fund, create a ``reportreceived`` dict that maps stocks to 
> booleans (initially False)
> - as each stock notifies its funds, the fund changes False to True and checks 
> ``all(reportreceived.values())`` to determine whether it is ok to notify 
> investors.
> - When it is ok, the fund notifies investors and resets all the 
> ``reportreceived`` values. 
> 
> Is this sensible enough? What are standard and better ways?
> 
> Thank you, 
> Alan Isaac 
> 
> PS I am drawing on the description of the observer pattern at
> http://www.dofactory.com/Patterns/PatternObserver.aspx#_self1>
> The real world aspects are just to add some concreteness.
> --
> http://mail.python.org/mailman/listinfo/python-list
> 

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


Re: Grabbing previous iteration in a dict

2008-05-09 Thread dannywebster
On May 9, 10:48 am, Paul Rubin  wrote:
> [EMAIL PROTECTED] writes:
> > I have a dictionary of which i'm itervalues'ing through, and i'll be
> > performing some logic on a particular iteration when a condition is
> > met with trusty .startswith('foo').  I need to grab the previous
> > iteration if this condition is met.  I can do something with an extra
> > var to hold every iteration while iterating, but this is hacky and not
> > elegant.
>
> You cannot rely on the elements of a dictionary being in any
> particular order (dicts are internally hash tables), so the above
> is almost certainly ont what you want.


Hi - thanks for your reply.  How about if I made the dict into a list
(of
which I have done).  How would I then reference the previous item?
Can they
be indexed?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Can I "delete" the namespace of a module that i import?

2008-05-09 Thread Mike Driscoll
On May 9, 9:06 am, "gbin,Zhou" <[EMAIL PROTECTED]> wrote:
> Hi,all.
>    I see from "http://docs.python.org/tut/node11.html"; that "Name
> spaces are created at different moments and have different lifetimes.
> The namespace containing the built-in names is created when the Python
> interpreter starts up, and is never deleted. The global namespace for
> a module is created when the module definition is read in; normally,
> module namespaces also last until the interpreter quits."
>    So can I "delete" the namespace of a module that i import?
>    thanks.

I did some searching and haven't found much. The closest I've found so
far is this old thread:

http://mail.python.org/pipermail/python-list/2000-February/022526.html

You might look at IDLE's code to see what it does when you tell it to
"restart" too.

Good luck!

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


Re: Newbie to python --- why should i learn !

2008-05-09 Thread Marcelo de Moraes Serpa
I sincerely think that most languages in existence today have its place.
Java has some great libraries and programs that were written in it. Try
writing an Eclipse clone in Python, I don't think it would go well.



On Fri, May 9, 2008 at 11:08 AM, hdante <[EMAIL PROTECTED]> wrote:

> On May 8, 7:25 am, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]>
> wrote:
> > Hi,
> >
> > i was reading/learning some hello world program in python.
> > I think its very simillar to Java/C++/C#. What's different (except
> > syntax) ?
>
>  All the languages have similar "power", in a theoretical sense. If
> you can solve a problem with one, most of the time you'll be able to
> solve it with the other. So we could say that the languages are
> "equal".
>
>  However, in practice, the syntax matters a lot. For example, they
> will influence on the maintainability and the performance of your
> application.
>
> >
> > what can i do easily with python which is not easy in c++/java !?
>
>  Pretty much everything. Python syntax is minimalist, so it requires
> much less code. There are many examples in Wikipedia, for example:
>
>
> http://en.wikipedia.org/wiki/User_datagram_protocol#Sample_code_.28Python.29
>  http://pt.wikipedia.org/wiki/Radix_sort#C.C3.B3digo_em_Java
>  http://en.wikipedia.org/wiki/Observer_pattern#Python
>
>  etc.
>
> >
> > Tnx,
> > Raxitwww.mykavita.com
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list

Re: The del statement

2008-05-09 Thread Michael Torrie
George Sakkis wrote:
> I think you're trying to imply that it is consistent with setting a
> value (same with getting). I guess what bugs me about "del" is that
> it's a keyword and not some universally well-known punctuation. Do you
> you feel that Python misses a "pop" keyword and respective
> expressions ?

Typically the word "pop" has a different meaning than you describe.
Most programmers think of pop in conjunction with push, for working with
FIFOs.  Normally pop would not be expected to take any arguments, or
maybe an argument of a number describing how many items to pop off of a
FIFO (stack).  Thus I don't think a pop method would be the right way to
go here.

I don't feel python misses a pop keyword because pop is already used as
methods of classes implementing stacks and FIFOs where appropriate.

> 
> (1) pop x: Remove x from the current namespace and return it.
> (2) pop x[i]: Instead of x.pop(i)
> (3) pop x.a: Equivalent to "_y=x.a; del x.a; return y"

The confusion over del does stem from it's behavior, so I can see where
you're coming from.  del doesn't delete anything; it just removes a
name.  However pop would be just as confusing in my opinion, given that
it's already associated with data structures.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Function creation (what happened?)

2008-05-09 Thread Gabriel Genellina
En Fri, 09 May 2008 10:02:01 -0300, Viktor <[EMAIL PROTECTED]> escribió:

> This completely slipped of my mind... :)
>
> I'm trying to change the:
> http://wordaligned.org/svn/etc/echo/echo.py
>
> So if the function is method it prints ClassName.MethodName instead of
> MethodName(self|klass|cls=<... ClassName>).
>
> But it turned out that in the decorator, the wrapped function is
> always just a TypeFunction (I cannot find out if the function is
> method, classmethod, staticmethod or just a plain function - tried
> with inspect also)... And what is most interesting, when I do:

The decorator receives the original, plain function (unless you chain 
decorators) and whatever it returns is used instead of the original function.

> def w(fn):
> print 'fn:', id(fn)
> return fn
>
> class A:
> @w
> def __init__(self): pass
>
> print 'A.__init__:', id(A.__init__)
>
> It turns out that the function I receive in the wrapper (even when I
> return the same function) is not the function which will finally be
> attached to the class...
> Is there a way to find out in the decorator "what will the decorated
> function be"?

Whatever you return from the decorator.
But the decorator returns a *function* and A.__init__ is a *method*, an 
instance method in fact. The function can be found as A.__dict__['__init__']. 
Try this:

m = A.__init__
print m, type(m), id(m)
f = A.__dict__['__init__']
print f, type(f), id(f)

A method combines a function with an instance that becomes the "self" argument. 
In your case you're building an "unbound" method because it's not tied to a 
particular instance, but even such unbound method is not the same thing as a 
plain function (it must ensure that its first argument, when called, is an A 
instance and not any other object).
The "magic" that converts a simple function into an instance method, for 
old-style classes like yours, was in the Class type itself. For new style 
classes, the descriptor protocol is used. See 
http://www.python.org/doc/newstyle/

-- 
Gabriel Genellina

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


Re: Grabbing previous iteration in a dict

2008-05-09 Thread Gary Herron

[EMAIL PROTECTED] wrote:

On May 9, 10:48 am, Paul Rubin  wrote:
  

[EMAIL PROTECTED] writes:


I have a dictionary of which i'm itervalues'ing through, and i'll be
performing some logic on a particular iteration when a condition is
met with trusty .startswith('foo').  I need to grab the previous
iteration if this condition is met.  I can do something with an extra
var to hold every iteration while iterating, but this is hacky and not
elegant.
  

You cannot rely on the elements of a dictionary being in any
particular order (dicts are internally hash tables), so the above
is almost certainly ont what you want.




Hi - thanks for your reply.  How about if I made the dict into a list
(of
which I have done).  How would I then reference the previous item?
Can they
be indexed?
--
http://mail.python.org/mailman/listinfo/python-list
  

Yes:

listOfItems = DICT.items()
for i in range(len(listOfItems)):
   k,v = listOfItems[i] # Current key,value pair
   if whatever:
   kPrev,vPrev = listOfItems[i-1]   # Previous key,value pair

Still, since there is no proscribed order in which the items are placed 
into the list, I wonder how this can be useful.   However, this *does* 
do what you asked.


Gary Herron

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


Re: Grabbing previous iteration in a dict

2008-05-09 Thread Hyuga
On May 9, 5:10 am, [EMAIL PROTECTED] wrote:
> I have a dictionary of which i'm itervalues'ing through, and i'll be
> performing some logic on a particular iteration when a condition is
> met with trusty .startswith('foo').  I need to grab the previous
> iteration if this condition is met.  I can do something with an extra
> var to hold every iteration while iterating, but this is hacky and not
> elegant.

Why is that so terrible?
previous = None
for key in mydict:
if key.starswith('foo') and previous is not None:
# ...do stuff...
previous = key

Doesn't seem too ugly to me.

> Is there a mechanism whereby I can just index the dict value
> subscripts like in an array? I could just rewind by 1 if so.

You can't rely on the keys in a dictionary being in any specific
order.  But if you want a list of the keys you can just call
mydict.keys() which will give a copy of the dictionary's keys in a
list.  Then you can iterate that and use it however you would use any
other list.  Note that it's a copy though.  It might help if you
better explained exactly what you need to do.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Grabbing previous iteration in a dict

2008-05-09 Thread Yves Dorfsman

[EMAIL PROTECTED] wrote:

You cannot rely on the elements of a dictionary being in any
particular order (dicts are internally hash tables), so the above
is almost certainly ont what you want.



Hi - thanks for your reply.  How about if I made the dict into a list
(of
which I have done).  How would I then reference the previous item?
Can they
be indexed?


Yes, I ran in a situation similar to yours, I read the content of a file, 
and had to both keep the order of the lines in the original file, and create 
a dictionary from the lines. So I created a class that contained both a 
dictionary and a tuple containing the keys of the dictionary in the original 
order. Something like this:


class mydict(object):

  def __init__(self, filename):
x = [ e.strip().split() for e in file(filename) ]
self.ordered_lines = tuple([ e[0] for e in x ])
self.dictionary = dict( zip(self.ordered_lines, [ e[1:] for e in x]) )

a = mydict('/some/file')
a.ordered_lines
a.dictionary



Yves.
http://www.SollerS.ca
--
http://mail.python.org/mailman/listinfo/python-list


  1   2   >