Re: import reassignment different at module and function scope

2009-01-30 Thread Chris Rebert
On Fri, Jan 30, 2009 at 11:31 PM, Brendan Miller  wrote:
> -BEGIN PGP SIGNED MESSAGE-
> Hash: SHA1
>
> If I:
>
> import sys
>
> sys = sys.version
>
> This executes find but:
>
> import sys
>
> def f():
>sys = sys.version
>
> This gives an error indicating that the sys on the right hand side of =
> is undefined. What gives?

More specifically, you get:
UnboundLocalError: local variable 'sys' referenced before assignment

Here's what's happening (IIRC):
Python sees (during "compilation") an assignment to 'sys' within the
function and (since there's no 'global' declaration within the
function) infers that the name 'sys', within the scope of the
function, *always* refers a local variable. IIRC, it does this for
significant optimization purposes.
However, when the function gets run and it goes to evaluate the
right-side of the assignment, it tries to lookup 'sys' as a local
variable, which obviously fails since it was never previously assigned
a value in the scope of the function, hence the error.

You can fix this by either renaming 'sys' within the function to something else:

def f():
version = sys.version #now sys is no longer treated as local

or you can indicate that you want to refer to the global sys variable:

def f():
global sys #tell python we mean the global sys
sys = sys.version #this will rebind 'sys' in the outer, global scope


Cheers,
Chris

-- 
Follow the path of the Iguana...
http://rebertia.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: Number of bits/sizeof int

2009-01-30 Thread Jon Clements
On Jan 31, 7:29 am, John Machin  wrote:
> On Jan 31, 6:03 pm, Jon Clements  wrote:
>
> > Hi Group,
>
> > This has a certain amount of irony (as this is what I'm pretty much
> > after):-
> > Fromhttp://docs.python.org/dev/3.0/whatsnew/3.1.html:
> > "The int() type gained a bit_length method that returns the number of
> > bits necessary to represent its argument in binary:"
>
> > Any tips on how to get this in 2.5.2 as that's the production version
> > I'm stuck with.
>
> For a positive integer, the simplest method (not necessarily the
> fastest) is to count how many times you need to shift it right to make
> it become zero.
> For non-positive integers, what answers do you want?

Thankfully, all integers are positive!

Must have been having a blonde moment, 'cos as soon as I read your
answer it was "of course that works". Not concerned about 'fast' as I
hardly think with DB and disk I/O I'm going to worry about bit-
shifting...

Much appreciated John,

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


Re: Number of bits/sizeof int

2009-01-30 Thread Gabriel Genellina
En Sat, 31 Jan 2009 05:03:27 -0200, Jon Clements   
escribió:



This has a certain amount of irony (as this is what I'm pretty much
after):-

From http://docs.python.org/dev/3.0/whatsnew/3.1.html:

"The int() type gained a bit_length method that returns the number of
bits necessary to represent its argument in binary:"

Any tips on how to get this in 2.5.2 as that's the production version
I'm stuck with.


I'm sure *everyone* will now post his favourite algorithm... If you search  
the archives, you'll find *tons* of versions. Ok, my take:


def number_of_bits(num):
  assert num>=0
  nbits = 1
  max = 2
  while max<=num:
nbits += 1
max += max
  return nbits

--
Gabriel Genellina

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


Re: Number of bits/sizeof int

2009-01-30 Thread Scott David Daniels

Jon Clements wrote:

... From http://docs.python.org/dev/3.0/whatsnew/3.1.html:
"The int() type gained a bit_length method that returns the number of
bits necessary to represent its argument in binary:"

Any tips on how to get this in 2.5.2 as that's the production version
I'm stuck with.



Well, what are your arg constraints?  Integers in 0 .. 2**53?
math.frexp(n)[1]

--Scott David Daniels
scott.dani...@acm.org
--
http://mail.python.org/mailman/listinfo/python-list


import reassignment different at module and function scope

2009-01-30 Thread Brendan Miller
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

If I:

import sys

sys = sys.version

This executes find but:

import sys

def f():
sys = sys.version

This gives an error indicating that the sys on the right hand side of =
is undefined. What gives?
-BEGIN PGP SIGNATURE-
Version: GnuPG v1.4.9 (GNU/Linux)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iEYEARECAAYFAkmD/mMACgkQ4eGWG/zYzOmrWgCbBLuD2HNDJJly3Z1KCPoNOB1G
sDgAoJ+gMCt9hWKuDUN30VUP40zqtbmJ
=+pND
-END PGP SIGNATURE-
--
http://mail.python.org/mailman/listinfo/python-list


Re: Number of bits/sizeof int

2009-01-30 Thread John Machin
On Jan 31, 6:03 pm, Jon Clements  wrote:
> Hi Group,
>
> This has a certain amount of irony (as this is what I'm pretty much
> after):-
> Fromhttp://docs.python.org/dev/3.0/whatsnew/3.1.html:
> "The int() type gained a bit_length method that returns the number of
> bits necessary to represent its argument in binary:"
>
> Any tips on how to get this in 2.5.2 as that's the production version
> I'm stuck with.

For a positive integer, the simplest method (not necessarily the
fastest) is to count how many times you need to shift it right to make
it become zero.
For non-positive integers, what answers do you want?

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


Re: Why doesn't eval of generator expression work with locals?

2009-01-30 Thread Hendrik van Rooyen

"Gabriel Genellina"  wrote:


>Consider this expression: g = (x+A for x in L for y in M). This is  
>currently expanded more or less like this:
>
>def foo(L):
>   for x in L:
> for y in M:
>   yield x+A
>g = foo(iter(L))
>
>(as your example above) Note that L has a special status -- it's the only  
>expression evaluated at the time g is defined. It *could* have been like  
>this:
>
>def foo()
>   for x in L:
> for y in M:
>   yield x+A
>g = foo()
>
>or even like this:
>
>def foo(L, M, A):
>   for x in L:
> for y in M:
>   yield x+A
>g = foo(iter(L), iter(M), A)
>
>In particular, I like the 2nd (all late binding). Seems this topic was  
>discussed many times [1] when PEP289 [2] was proposed, and "practicality  
>beats purity".

Ok thanks - I see where you are coming from now.
It never ceases to amaze me how different we all are -
Given a choice, I would have chosen the last alternative,
as it feels more natural to me - the one you like feels to
me as if it were too tightly coupled, somehow. - almost
as if you were using named globals in a function instead
of passing arguments in.

But hey - I have long since learned that it is of no use to
rant against the way something works, if you cannot
easily change it - one can just figure out what it does, 
and then figure out how to use it to get it to do what one
wants.

Thanks for an interesting discussion.

- Hendrik


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


Number of bits/sizeof int

2009-01-30 Thread Jon Clements
Hi Group,

This has a certain amount of irony (as this is what I'm pretty much
after):-
>From http://docs.python.org/dev/3.0/whatsnew/3.1.html:
"The int() type gained a bit_length method that returns the number of
bits necessary to represent its argument in binary:"

Any tips on how to get this in 2.5.2 as that's the production version
I'm stuck with.

Cheers,

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


Re: error on building 2.6.1. (_ctypes)

2009-01-30 Thread Gabriel Genellina
En Fri, 30 Jan 2009 16:52:07 -0200, Bernard Rankin   
escribió:


> I am trying to build python 2.6 on a machine (web server) that I do  
not have

root access to. (has 2.4 installed)
>
> Python 2.5 builds fine, but I am getting an error when I run "make"  
for 2.6.1.


Mmm... my 2.6.1 source show different line numbers, maybe you should  
check it's

the right file?


Wow, good catch.

I just re-downloaded the archive and it works fine.

I know for certain that I did no editing to the files, and even tried  
expanding the original tar.gz a couple of times.


There must be a corrupted package somewhere among the official Python  
mirrors.  (Sadly, I overwrote the old tar.gz file when I got the new  
one.)


Oops... so bad. The python.org releases have PGP signatures and MD5  
published so you can verify their authenticity.


--
Gabriel Genellina

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


Re: relpath problem on windows

2009-01-30 Thread Gabriel Genellina

En Fri, 30 Jan 2009 14:30:53 -0200, eliben  escribió:


I'm having a problem with 2.6's new os.path.relpath function.

This is correct:

relpath(r'd:\abc\jho', r'd:\abc')
=> 'jho'

But this isn't:
relpath(r'd:\jho', r'd:\\')
=> '..\jho'


Looks like a real bug to me -- please submit it to http://bugs.python.org/


Neither is this:
relpath(r'd:\jho', r'd:')
=> '..\..\..\jho'


d: means "the current directory on drive d:", and it could be something  
like d:\a\b\c


--
Gabriel Genellina

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


Re: error C3861: 'Py_InitModule'

2009-01-30 Thread duprez
Ok, I found the reason, you now need to do a bit more work and use
PyModule_Create().

Also, for anyone else that may stumble on this, you need to refer to
the online Dev doc's that get updated regularly (which I regrettably
forgot about) which are here -> http://docs.python.org/dev/3.0/

thanks,
Mick.


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


Re: Want to write a script to do the batch conversion from domain name to IP.

2009-01-30 Thread Gabriel Genellina
En Fri, 30 Jan 2009 12:53:33 -0200, Hongyi Zhao   
escribió:



See the following errors I in my case:

$ python
'import site' failed; use -v for traceback



import socket

Traceback (most recent call last):
 File "", line 1, in 
ImportError: No module named socket


Those errors indicate that Python is not working correctly in your system.  
You should fix it before going on.



Another issue is: how can I perform all of these steps in a python
script?


Start reading the tutorial and working the examples:  
http://docs.python.org/tutorial/
In a short time (maybe shorter than you expect) you'll manage enough of  
Python to do this.
Come back when you have specific questions, or try the tutor list:  
http://mail.python.org/mailman/listinfo/tutor


--
Gabriel Genellina

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


Re: ImportError in embedded Python Interpreter

2009-01-30 Thread Gabriel Genellina
En Fri, 30 Jan 2009 08:50:45 -0200,   
escribió:



Okay, thats just the question. I did that what you wrote but it
doesn't really works.
What is, if Py_SetProgramName() gets a NULL Pointer, if argv[0] is
empty?


Why so? Are you in an embedded environment or something that doesn't have  
a filesystem? Calling Py_SetProgramName with an absolute path would be the  
easiest way to make it work.


--
Gabriel Genellina

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


Re: Why doesn't eval of generator expression work with locals?

2009-01-30 Thread Gabriel Genellina
En Fri, 30 Jan 2009 06:42:22 -0200, Peter Otten <__pete...@web.de>  
escribió:



Gabriel Genellina wrote:

g = (x+B for x in A)


I think it helps understanding if you translate the above to


A = [1,2,3]
B = 1
def f(a):

... for x in a:
... yield x+B
...

g = f(A)
A = [4,5,6]
B = 10
print list(g)

[11, 12, 13]

This is not altogether unintuitive, but I think I would prefer if it  
worked

like


A = [1,2,3]
B = 1
def f(a, b):

... for x in a:
... yield x+b
...

g = f(A, B)
A = [4,5,6]
B = 10
list(g)

[2, 3, 4]

i. e. every name were bound early. Of course this wouldn't help with
locals() which would still be called in different scopes.


Yep -- although I would like all names were late bound instead. But as I  
posted in another message, in this case "practicality beat purity" and a  
special case was made for the leftmost iterable.


--
Gabriel Genellina

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


RE: nth root

2009-01-30 Thread Tim Roberts
Dan,
 
Thanks - you're probably right - just my intuition said to me that rather than 
calculating that the 13th root of 4021503534212915433093809093996098953996019232
is 3221.2904208350265
there must be a quicker way of finding out its between 3221 and 3222
 
but perhaps not.
 
Tim



From: Dan Goodman [mailto:dg.gm...@thesamovar.net]
Sent: Sat 31-Jan-09 3:11 PM
To: python-list@python.org
Subject: Re: nth root



Takes less than 1 sec here to do (10**100)**(1./13) a million times, and
only about half as long to do (1e100)**(1./13), or about 14 times as
long as to do .2**2. Doesn't look like one could hope for it to be that
much quicker as you need 9 sig figs of accuracy to get the integer part
of (10**100)**(1./13) (floats have about 7 and doubles about 16).

Dan

Tim wrote:
> In PythonWin I'm running a program to find the 13th root (say) of
> millions of hundred-digit numbers.  I'm using
> n = 13
> root = base**(1.0/n)
> which correctly computes the root to a large number of decimal
> places, but therefore takes a long time.  All I need is the integer
> component.  Is there a quicker way?
> 
>
>
> 
>
> --
> http://mail.python.org/mailman/listinfo/python-list

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


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


Re: Why doesn't eval of generator expression work with locals?

2009-01-30 Thread Gabriel Genellina
En Fri, 30 Jan 2009 07:08:29 -0200, Hendrik van Rooyen  
 escribió:



"Gabriel Genellina"  wrote:

Of course this is clearly stated in the Language Reference "Variables  
used

in the generator expression are evaluated lazily in a separate scope when
the next() method is called for the generator object (in the same fashion
as for normal generators). However, the in expression of the leftmost for
clause is immediately evaluated in the current scope..." -- but this
behaviour is still surprising and not obvious to me. ("not obvious" means
that things could have been different, choosing this was a design
decision).

I am not so sure that it could have been done differently -
I see it something like this:  (going back to almost your
original example, and reversing the position of globals
and locals to make it shorter)


def foo(things):

 for thing in things:
  yield thing()#it is obvious this is in the local scope of foo


boo = foo([locals,globals])
boo.next()
{'thing': , 'things': [locals>,

]}



and so it is, when you feed it the locals function
[...]
Now I don't think that you could really do it differently -
the right hand side of the generator expression is exactly
like my passed argument "things", in all cases as far as
I can see, and this means that the right hand side is
evaluated when it is "passed", and the left hand side
is whatever is done in the "for thing in things:" loop.
All the generator expression does is that it saves you
the trouble of defining the function - it kind of does it
for you, and calls it, and returns the generator object,
and throws the function away, all in one hit. (this is not
necessarily the real mechanism, but the effect is exactly
as if it were)


Yes, but this is not the only alternative. You *decided* that foo and bar  
will take one argument - this means that it uses early binding and it is  
evaluated when the generator expression is created. This is a design  
decision, and it could have been different.
The left-part of the generator expression (in the function analogy, the  
"yield" expression) is late bound - it is completely evaluated at every  
iteration, using whatever values are currently bound to external (free)  
variables. The same *could* happen with the right part too -- although  
this is not what was decided.


Consider this expression: g = (x+A for x in L for y in M). This is  
currently expanded more or less like this:


def foo(L):
  for x in L:
for y in M:
  yield x+A
g = foo(iter(L))

(as your example above) Note that L has a special status -- it's the only  
expression evaluated at the time g is defined. It *could* have been like  
this:


def foo()
  for x in L:
for y in M:
  yield x+A
g = foo()

or even like this:

def foo(L, M, A):
  for x in L:
for y in M:
  yield x+A
g = foo(iter(L), iter(M), A)

In particular, I like the 2nd (all late binding). Seems this topic was  
discussed many times [1] when PEP289 [2] was proposed, and "practicality  
beats purity".


[1] http://mail.python.org/pipermail/python-dev/2004-April/date.html
[2] http://www.python.org/dev/peps/pep-0289/

--
Gabriel Genellina

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


Re: Mathematica 7 compares to other languages

2009-01-30 Thread William James
w_a_x_...@yahoo.com wrote:

> On Dec 25, 5:24 am, Xah Lee  wrote:
> 
> > The JavaScript example:
> > 
> > // Javascript. By William James
> > function normalize( vec ) {
> > var div=Math.sqrt(vec.map(function(x) x*x).reduce(function(a,b)
> > a+b))   return vec.map(function(x) x/div)
> > 
> > }
> > 
> > is also not qualified. (it is syntax error in SpiderMonkey engine
> > “JavaScript-C 1.7.0 2007-10-03”)
> 
> Since you are using the latest version of Mathematica, you should
> also use the latest version of SpiderMonkey.
> 
> The function works outside of a web browser with jslibs, and it
> works in Firefox 3.0.1.
> 
> 
> 
> 
> 
> 
> // Tested with Firefox 3.0.1.
> // SpiderMonkey JavaScript 1.6 added map().
> // 1.8 added reduce() and function shorthand:
> // function(x) { return x * x }
> //   can now be:
> // function(x) x * x
> 
> // Javascript. By William James
> function normalize( vec ) {
> var div=Math.sqrt(vec.map(function(x) x*x).reduce(function(a,b) a+b))
>   return vec.map(function(x) x/div)
> }
> 
> window.alert( normalize( [2,3,4] ).toSource() )
> 
> 
> 
> 
> 

Reduce:

procedure normalize vec;
  begin scalar div;
div := for each u in vec sum u^2;
return map(~x/div, vec)
  end;

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


error C3861: 'Py_InitModule'

2009-01-30 Thread duprez
Hi All,
Using python 3.0, VS2005, WinXP SP3

I know this looks like a simple one but i just installed Python 3.0
(no other Python installations etc) and I'm trying to convert my
perfectly working 2.5 C code for an embedded interpreter to 3.0.
I've changed all of my string functions etc to remove those errors and
I've studied the doc's and searched but I'm still getting the error
regarding Py_InitModule, it's as if it no longer exists but I can't
find anything different in the doc's.
My intellisense and all works fine and all the other python functions
are fine, just this one, does anyone have any ideas? Have I missed a
change that has not made it to the doc's??

thanks,
Mick.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Securing a database

2009-01-30 Thread Aahz
In article ,
  wrote:
>
>My company provides some services online, which now they are planning
>to make it offline and sell to customers who can use it in their
>networks.

How critical is it that this application work completely offline?  I
suggest that you seriously consider making your application crippleware
unless it can "call home" -- that is, certain key bits work only with
online access even if the majority of the app is local.  This may or may
not include the secure database, but if the data is local, it can still
get hacked.
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

Weinberg's Second Law: If builders built buildings the way programmers wrote 
programs, then the first woodpecker that came along would destroy civilization.
--
http://mail.python.org/mailman/listinfo/python-list


Re: nth root

2009-01-30 Thread Dan Goodman
Takes less than 1 sec here to do (10**100)**(1./13) a million times, and 
only about half as long to do (1e100)**(1./13), or about 14 times as 
long as to do .2**2. Doesn't look like one could hope for it to be that 
much quicker as you need 9 sig figs of accuracy to get the integer part 
of (10**100)**(1./13) (floats have about 7 and doubles about 16).


Dan

Tim wrote:
In PythonWin I'm running a program to find the 13th root (say) of 
millions of hundred-digit numbers.  I'm using

n = 13
root = base**(1.0/n)
which correctly computes the root to a large number of decimal 
places, but therefore takes a long time.  All I need is the integer 
component.  Is there a quicker way?
 





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


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


FINAL REMINDER: OSCON 2009: Call For Participation

2009-01-30 Thread Aahz
The O'Reilly Open Source Convention has opened up the Call For
Participation -- deadline for proposals is Tuesday Feb 3.

OSCON will be held July 20-24 in San Jose, California.

For more information, see
http://conferences.oreilly.com/oscon
http://en.oreilly.com/oscon2009/public/cfp/57
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

Weinberg's Second Law: If builders built buildings the way programmers wrote 
programs, then the first woodpecker that came along would destroy civilization.
--
http://mail.python.org/mailman/listinfo/python-list


Re: search speed

2009-01-30 Thread rdmurray
Quoth Tim Chase :
> PS:  as an aside, how do I import just the fnmatch function?  I 
> tried both of the following and neither worked:
> 
>from glob.fnmatch import fnmatch
>from glob import fnmatch.fnmatch
> 
> I finally resorted to the contortion coded below in favor of
>import glob
>fnmatch = glob.fnmatch.fnmatch

What you want is:

from fnmatch import fnmatch

fnmatch is its own module, it just happens to be in the (non __all__)
namespace of the glob module because glob uses it.

--RDM

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


RE: nth root

2009-01-30 Thread Tim Roberts
Unfortunately, unless I'm doing something wrong, this appears to take 20 times 
as long... :-)
 
What on earth are numpy and psyco?  Do I need to watch the Lord of the Rings?
 
Tim
 
 
Tim wrote:
> In PythonWin I'm running a program to find the 13th root (say) of
> millions of hundred-digit numbers.  I'm using
> n = 13
> root = base**(1.0/n)
> which correctly computes the root to a large number of decimal
> places, but therefore takes a long time.  All I need is the integer
> component.  Is there a quicker way?
> 
Have you tried an iterative approach?

def root_13(x):
 step = 1
 while step ** 13 < x:
 step *= 2
 root = 0
 while step:
 if (root + step) ** 13 <= x:
 root += step
 step //= 2
 return root

Probably not that fast in Python, though. numpy or psyco might help.
--
http://mail.python.org/mailman/listinfo/python-list

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


Re: More mod_wsgi weirdness: process restarts on redirect

2009-01-30 Thread rdmurray
Quoth Ron Garret :
> In article ,
>  Joshua Kugler  wrote:
> 
> > Ron Garret wrote:
> > > My question is: is this supposed to be happening?  Or is this an
> > > indication that something is wrong, and if so, what?
> > 
> > You are probably just hitting a different instance of Apache, thus the
> > different process ID.
> 
> Yep, that's what it turned out to be.  I thought I had a 
> WSGIDaemonProcess processes=1 directive in my config, but I had it in 
> the wrong place (a different vhost) so it wasn't actually active.
> 
> But that leaves me wondering why the redirect would reliably trigger 
> switching processes.  The reason I thought that I had the correct 
> configuration and only had one process is that when I reloaded the 
> non-redirected page I *always* got the same process ID.  How does 
> mod_wsgi decide which process  (and which thread for that matter) to use?

My WAG would be that when doing a refresh your client used a persistent
http connection, and thus talked again to the same Apache child, but when
it got a redirect it dropped the old connection and opened up a new one,
thus having a high probability of hitting a new child.  But that is,
as I say, a WAG.

--RDM

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


SimpleXMLRPCServer question

2009-01-30 Thread rdmurray
Quoth flagg :
> I am working on a very basic xmlrpc server, which will expose certain
> functions for administering BIND zone files.  The big problem I am
> having is parsing the incoming xmlrpc request.  Basically part of the
> xmlrpc request will help deterime which zone file is edited.I have
> been looking at the do_POST() method from SimpleXMLRPCDispatcher and
> it seems like I could code something which overides that method,
> however I am new to programming am at a loss, i might even be making
> this tougher than it needs to be.   Is there a way to parse the
> incoming xmlrpc request before the function it is calling is executed?

Wouldn't you be overriding '_dispatch' on SimpleXMLRPCServer instead?

It's been a while since I looked at XMLRPC, but why wouldn't you have
a operation names, with the zone file to operate on as an argument?
Then you'd just be defining your operations as methods on your
SimpleXMLRPCServer, and they'd use the argument to determine which file
to operate on.

If that doesn't make sense, either I've forgotten how XMLRPC works,
or you should explain your requirements a bit more.

--RDM

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


Re: search speed

2009-01-30 Thread Tim Chase

I have written a Python program that serach for specifik customer in
files (around 1000 files)
the trigger is LF01 + CUSTOMERNO


While most of the solutions folks have offered involve scanning 
all the files each time you search, if the content of those files 
doesn't change much, you can build an index once and then query 
the resulting index multiple times.  Because I was bored, I threw 
together the code below (after the "---" divider) which does 
what you detail as best I understand, allowing you to do


  python tkc.py 31415

to find the files containing CUSTOMERNO=31415  The first time, 
it's slow because it needs to create the index file.  However, 
subsequent runs should be pretty speedy.  You can also specify 
multiple customers on the command-line:


  python tkc.py 31415 1414 7

and it will search for each of them.  I presume they're found by 
the regexp "LF01(\d+)" based on your description, that the file 
can be sensibly broken into lines, and the code allows for 
multiple results on the same line.  Adjust accordingly if that's 
not the pattern you want or the conditions you expect.


If your source files change, you can reinitialize the database with

  python tkc.py -i

You can also change the glob pattern used for indexing -- by 
default, I assumed they were "*.txt".  But you can either 
override the default with


  python tkc.py -i -p "*.dat"

or you can change the source to default differently (or even skip 
the glob-check completely...look for the fnmatch() call).  There 
are a few more options.  Just use


  python tkc.py --help

as usual.  It's also a simple demo of the optparse module if 
you've never used it.


Enjoy!

-tkc

PS:  as an aside, how do I import just the fnmatch function?  I 
tried both of the following and neither worked:


  from glob.fnmatch import fnmatch
  from glob import fnmatch.fnmatch

I finally resorted to the contortion coded below in favor of
  import glob
  fnmatch = glob.fnmatch.fnmatch

-


#!/usr/bin/env python
import dbm
import os
import re
from glob import fnmatch
fnmatch = fnmatch.fnmatch
from optparse import OptionParser

customer_re = re.compile(r"LF01(\d+)")

def build_parser():
  parser = OptionParser(
usage="%prog [options] [cust#1 [cust#2 ... ]]"
)
  parser.add_option("-i", "--index", "--reindex",
action="store_true",
dest="reindex",
default=False,
help="Reindex files found in the current directory "
  "in the event any files have changed",
)
  parser.add_option("-p", "--pattern",
action="store",
dest="pattern",
default="*.txt",
metavar="GLOB_PATTERN",
help="Index files matching GLOB_PATTERN",
)
  parser.add_option("-d", "--db", "--database",
action="store",
dest="indexfile",
default=".index",
metavar="FILE",
help="Use the index stored at FILE",
)
  parser.add_option("-v", "--verbose",
action="count",
dest="verbose",
default=0,
help="Increase verbosity"
)
  return parser

def reindex(options, db):
  if options.verbose: print "Indexing..."
  for path, dirs, files in os.walk('.'):
for fname in files:
  if fname == options.indexfile:
# ignore our database file
continue
  if not fnmatch(fname, options.pattern):
# ensure that it matches our pattern
continue
  fullname = os.path.join(path, fname)
  if options.verbose: print fullname
  f = file(fullname)
  found_so_far = set()
  for line in f:
for customer_number in customer_re.findall(line):
  if customer_number in found_so_far: continue
  found_so_far.add(customer_number)
  try:
val = '\n'.join([
  db[customer_number],
  fullname,
  ])
if options.verbose > 1:
  print "Appending %s" % customer_number
  except KeyError:
if options.verbose > 1:
  print "Creating %s" % customer_number
val = fullname
  db[customer_number] = val
  f.close()

if __name__ == "__main__":
  parser = build_parser()
  opt, args = parser.parse_args()
  reindexed = False
  if opt.reindex or not os.path.exists("%s.db" % opt.indexfile):
db = dbm.open(opt.indexfile, 'n')
reindex(opt, db)
reindexed = True
  else:
db = dbm.open(opt.indexfile, 'r')
  if not (args or reindexed):
parser.print_help()
  for arg in args:
print "%s:" % arg,
try:
  val = db[arg]
  print
  for item in val.splitlines():
print " %s" % item
except KeyError:
  print "Not found"
  db.close()


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


Re: Importing modules

2009-01-30 Thread rdmurray
Quoth Mudcat :
> [attribution omitted by Mudcat]
> > I think you've probably had issues with circular imports (i.e. mutual
> > dependencies), unless you can precisely remember what you were doing and
> > what went wrong.
>
> That's possible, but circular imports become more of a hazard if you
> have to import in several locations. Unify that to one file, and those
> problems are much easier to avoid.

Personally I've never run into circular import problems when importing
library functions.  Then, again, I always use 'from x import y' (or
'y as z' for those modules that use non-unique names for things, like
os.path.split).

Where I've run into circular import problems when when _my_ modules
were circularly importing things.  Which just meant that my code needed
some refactoring.

> > I can make up three or four different logical groupings in my
> > applications... so what is 'logical' could not be the same for everyone,
> > or from every point of view.
>
> That's not the point. The point is that multiple imports can be a
> limiting factor if the module imports don't happen to align with the
> model they'd like to use for their file layout.

I'm inclined to agree with you that organizing code around which other
modules it imports is (usually) not the optimal organization.  But it is
worth _considering_, because sometimes it does reveal a useful pattern
to refactor by.

> However playing around with the files, I guess it is possible to
> create a file that just does imports and then reference them all just
> like you would any other extension of the namespace. I created a file
> called imports and was able to access the sys module within it by
> importing all from imports and calling sys. That way at least all you
> have to do is import the one file each time.

If you are talking about making a file and then doing from X import *,
I'd shudder a little bit looking at such code.  It just doesn't feel
like the python way :).  Which doesn't mean you shouldn't do it, if it
works for you, it is more of a personal preference thing.

What I'd respond to better (and I almost started doing this in my
code...but it's more typing so in the end I didn't) is to have a module,
say 'lib', and just do 'import lib'.  Then everything is called through
'lib': lib.os.path.split('/some/path'), etc, etc.

The difference is that that is explicit.  If I'm reading your code
and I see that, I look at the top and I see the import for 'lib', and I
know to look for a lib module.  If you use the from X import * pattern,
I lose that ability.  Sure, I can look at the top, and see the 'from X
import *', and if that's the only 'from *' import I can guess that the
functions not defined in the file come from that one...but all of that
takes more brain cycles.  It just doesn't feel as clean :)

But, in the end, it is mostly personal preference.  I'm sure there are
Pythonistas out there whose lips will curl when seeing
'from os.path import split as pathsplit, join as pathjoin' in my code :)

--RDM

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


Re: nth root

2009-01-30 Thread MRAB

Tim wrote:
In PythonWin I'm running a program to find the 13th root (say) of 
millions of hundred-digit numbers.  I'm using

n = 13
root = base**(1.0/n)
which correctly computes the root to a large number of decimal 
places, but therefore takes a long time.  All I need is the integer 
component.  Is there a quicker way?
 

Have you tried an iterative approach?

def root_13(x):
step = 1
while step ** 13 < x:
step *= 2
root = 0
while step:
if (root + step) ** 13 <= x:
root += step
step //= 2
return root

Probably not that fast in Python, though. numpy or psyco might help.
--
http://mail.python.org/mailman/listinfo/python-list


Re: verilog like class w/ bitslicing & int/long classtype

2009-01-30 Thread rdmurray
Quoth Stef Mientki :
> Marc 'BlackJack' Rintsch wrote:
> > On Fri, 30 Jan 2009 00:25:03 +0100, Stef Mientki wrote:
> >
> >   
> >> try this:
> >>
> >> class MyRegClass ( int ) :
> >>   def __init__ ( self, value ) :
> >> self.Value = value
> >>   def __repr__ ( self ) :
> >> line = hex ( self.Value )
> >> line = line [:2] + line [2:].upper()
> >> return line
> >> 
> >
> > def __repr__(self):
> > return '0x%X' % self.value
> >
> >   
> >>   __str__ = __repr__
> >> 
> >
> > This is unnecessary, the fallback of `__str__` is `__repr__` already.
> >
> >   
> well this is what my Python is doing:
> 
> without  _str__ = __repr__
>  >>print shadow_register
> 170
> 
> with  _str__ = __repr__
>  >>print shadow_register
> 0xAA


>>> '__str__' in dir(170)
True

That is, the superclass (int) has an __str__, so you have to override it.

--RDM

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


SimpleXMLRPCServer question

2009-01-30 Thread flagg
I am working on a very basic xmlrpc server, which will expose certain
functions for administering BIND zone files.  The big problem I am
having is parsing the incoming xmlrpc request.  Basically part of the
xmlrpc request will help deterime which zone file is edited.I have
been looking at the do_POST() method from SimpleXMLRPCDispatcher and
it seems like I could code something which overides that method,
however I am new to programming am at a loss, i might even be making
this tougher than it needs to be.   Is there a way to parse the
incoming xmlrpc request before the function it is calling is executed?


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


nth root

2009-01-30 Thread Tim
In PythonWin I'm running a program to find the 13th root (say) of millions
of hundred-digit numbers.  I'm using
n = 13
root = base**(1.0/n)
which correctly computes the root to a large number of decimal places, but
therefore takes a long time.  All I need is the integer component.  Is there
a quicker way?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Adding a positive number and a negative number

2009-01-30 Thread John Machin
On Jan 31, 4:10 am, Scott David Daniels  wrote:
> Grant Edwards wrote:
> > On 2009-01-30, MRAB  wrote:
> >> Eric Kang wrote:
> >>> In two's complement representation, can adding one positive
> >>> and one negative give you overflow?
> >> No.
> > AFAIK, in Python adding integers never gives you overlow
> > regardless of sign.
>
> Right, but he wants his homework answer.

For extra brownie points, here's a simple proof of the more general
proposition that adding a non-negative integer p and a non-positive
integer n can't overflow whatever the representation.

Let a be the most negative integer and b the most positive. So we're
given a <= n <= 0 <= p <= b and need to show that a <= (p + n) <= b.

max(p) is b, max(n) is 0, so max(p + n) is b.
Similarly min(p + n) is a.
Q.E.D.

IEEE 754 floating point? I don't know. Go read the standard :-)

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


Re: Swapping values of two variables

2009-01-30 Thread Grant Edwards
On 2009-01-31, Aahz  wrote:

>>But could the swapping be done using less extra memory than this? What
>>is the minimum amount of extra memory required to exchange two 32-bit
>>quantities? What would be the pseudocode that achieves this minimum?
>
> This looks like a homework problem to me

It looks 100% like a homework problem.

-- 
Grant

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


Re: is python Object oriented??

2009-01-30 Thread Hung Vo
On Fri, Jan 30, 2009 at 5:15 PM, Chris Rebert  wrote:

> On Thu, Jan 29, 2009 at 9:56 PM, Hung Vo  wrote:
> 
> > I'm new to Python and also wondering about OOP in Python.
> >
> > I want to justify the above question (is Python Object-Oriented?).
> > Does Python follow the concepts/practices of Encapsulation,
> > Polymorphism and Interface, which are quite familiar to Java
> > programmers?
>
> If you're looking for a benchmark for object-orientedness, Smalltalk,
> not Java, is the canonical language to compare against.


I was introduced to OOP via C++/Java, so its quite nature to compare and
contrast with the languages you know even they seem not to be original. I
definitely will learn about Smalltalk.


>
> Anyway, to your three-pronged question:
> - Yes, Python supports polymorphism. I find it hard to think of an
> example of an OO language that doesn't.
>
> - Python does not support interfaces in the Java sense (although there
> are a few third-party libraries that add such support); neither does
> Smalltalk. Instead, both Smalltalk and Python use duck-typing to
> similar effect. See http://en.wikipedia.org/wiki/Duck_typing


Its seem to me that duck typing is a special case of static vs dynamic type
debate and clearly Python is a dynamic type philoshopy's follower.

>
> - Python supports encapsulation. Prefixing an attribute/method with an
> underscore indicates that other programmers should treat it as
> 'private'. However, unlike B&D languages, Python itself does nothing
> to enforce this privacy, leaving it instead to the good judgement of
> the programmer, under the philosophy that "We're all consenting adults
> here". This allows people to meddle with internals, at their own risk,
> if it ends up being absolutely necessary. The enforcement point is
> largely academic anyway, as most languages' reflection APIs let you
> poke at ostensibly "private" things.


I like the flexibility of not being enforced to the encapsulation rules,
however, you're right, we do at our own risk and have to tradeoff the
flexibility with the secure a static type system like Java provides.

P.S. You appear to have posted the same message 3 times(!), which is a
> bit annoying for readers.


sorry for this annoyance. I dont know why a new post was made whenever i
cliked on the topic link. Probably, there's something wrong with google
group. on investigating...

>
> --
> Follow the path of the Iguana...
> http://rebertia.com
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: naming and binding (subtle Python 3 change)

2009-01-30 Thread Alan G Isaac

On 1/29/2009 10:50 PM Terry Reedy apparently wrote:

http://bugs.python.org/issue5106



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


Re: writing large dictionaries to file using cPickle

2009-01-30 Thread Aaron Brady
On Jan 30, 2:44 pm, perfr...@gmail.com wrote:
> On Jan 28, 6:08 pm, Aaron Brady  wrote:
>
>
>
> > On Jan 28, 4:43 pm, perfr...@gmail.com wrote:
>
> > > On Jan 28, 5:14 pm, John Machin  wrote:
>
> > > > On Jan 29, 3:13 am, perfr...@gmail.com wrote:
>
> > > > > hello all,
>
> > > > > i have a large dictionary which contains about 10 keys, each key has a
> > > > > value which is a list containing about 1 to 5 million (small)
> > > > > dictionaries. for example,
>
> > > > > mydict = {key1: [{'a': 1, 'b': 2, 'c': 'hello'}, {'d', 3, 'e': 4, 'f':
> > > > > 'world'}, ...],
> > > > >                 key2: [...]}
>
> > > > > in total there are about 10 to 15 million lists if we concatenate
> > > > > together all the values of every key in 'mydict'. mydict is a
> > > > > structure that represents data in a very large file (about 800
> > > > > megabytes).
>
> > snip
>
> > > in reply to the other poster: i thought 'shelve' simply calls pickle.
> > > if thats the case, it wouldnt be any faster, right ?
>
> > Yes, but not all at once.  It's a clear winner if you need to update
> > any of them later, but if it's just write-once, read-many, it's about
> > the same.
>
> > You said you have a million dictionaries.  Even if each took only one
> > byte, you would still have a million bytes.  Do you expect a faster I/
> > O time than the time it takes to write a million bytes?
>
> > I want to agree with John's worry about RAM, unless you have several+
> > GB, as you say.  You are not dealing with small numbers.
>
> in my case, i just write the pickle file once and then read it in
> later. in that case, cPickle and shelve would be identical, if i
> understand correctly?

No not identical.  'shelve' is not a dictionary, it's a database
object that implements the mapping protocol.  'isinstance( shelve,
dict )' is False, for example.

> the file i'm reading in is ~800 MB file, and the pickle file is around
> 300 MB. even if it were 800 MB, it doesn't make sense to me that
> python's i/o would be that slow... it takes roughly 5 seconds to write
> one megabyte of a binary file (the pickled object in this case), which
> just seems wrong. does anyone know anything about this? about how i/o
> can be sped up for example?

You can try copying a 1-MB file.  Or something like:

f= open( 'temp.temp', 'w' )
for x in range( 10 ):
f.write( '0'* 10 )

You know how long it takes OSes to boot, right?

> the dictionary might have a million keys, but each key's value is very
> small. i tried the same example where the keys are short strings (and
> there are about 10-15 million of them) and each value is an integer,
> and it is still very slow. does anyone know how to test whether i/o is
> the bottle neck, or whether it's something specific about pickle?
>
> thanks.

You could fall back to storing a parallel list by hand, if you're just
using string and numeric primitives.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Adding a positive number and a negative number

2009-01-30 Thread Steve Holden
Scott David Daniels wrote:
> Grant Edwards wrote:
>> On 2009-01-30, MRAB  wrote:
>>> Eric Kang wrote:
 In two's complement representation, can adding one positive
 and one negative give you overflow?
>>> No.
>> AFAIK, in Python adding integers never gives you overlow
>> regardless of sign.
> 
> Right, but he wants his homework answer.

And Python doesn't use pure two's complement notation when it promotes
regular integers to longs.

regards
 Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

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


Re: problem with program - debugging leading nowhere

2009-01-30 Thread Matthew Sacks
this works.
thanks!

On Fri, Jan 30, 2009 at 3:59 PM, Jervis Whitley  wrote:
>
>
>>
>>
>>
>>
>> error message:
>> Traceback (most recent call last):
>>  File "", line 1, in 
>> IndentationError: expected an indented block (, line 39)
>>
>> code:
>> http://pastebin.com/f2f971f91
>
> Hi,
>
> It looks like you have commented out a line on line 30, you need to place
> something
> in here, as python is expecting an indented level after your 'if'. (how
> about a pass statement or a print saying some placeholder help details.)
>
> On a side note, I've only had a quick skim, you shouldn't compare o to an
> empty string "" using the 'is', is tests identity not equality. So what you
> are saying is
> is o the exact same empty string that I am creating "" (obviously it never
> will be, because you just created it then with "") . Use the equality
> operator == instead.
> or in your case !=.
>
> Cheers,
>
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: problem with program - debugging leading nowhere

2009-01-30 Thread Ben Finney
Matthew Sacks  writes:

> i am trying to figure out what has gone wrong in my python program. it
> is complaining that there is an indendation error. should be simple
> enough but im stuck on this one. if anyone can help unjolt me it would
> be appreciated.

Step one: Ensure the problem doesn't get worse. Set your text editor
to use spaces for indentation and to *never* put an ASCII TAB
character (U+0009) into your source code. They are, by default,
invisibly indistinguishable from a sequence of spaces, and completely
unnecessary.

Step two: Run your program with ‘python -t’ instead of ‘python’, to
determine if your problem in this instance is caused by using TAB
characters for indentation.

Step three: When asking people to help with understanding an error
message, it helps to post the actual (complete) error message :-)

-- 
 \ “Sittin' on the fence, that's a dangerous course / You can even |
  `\   catch a bullet from the peace-keeping force” —Dire Straits, |
_o__)   _Once Upon A Time In The West_ |
Ben Finney
--
http://mail.python.org/mailman/listinfo/python-list


Re: accessing elements of a tuple

2009-01-30 Thread John Machin
On Jan 31, 9:42 am, Matthew Sacks  wrote:
> >First of all, list is a reserved word.  Don't use it as a variable name.
>
> I was using it as an example in this case.
>
> >mylist[0][1] if I understand the question.
>
> This works. Thank you.
>
> On Fri, Jan 30, 2009 at 2:39 PM, Tim Chase
>
>  wrote:
> >> let me re-phrase that question:
> >> i would like to access the element of individual tuples inside of a
> >> list, by using an index.
> >> so i have the list contents
>
> >> print list
> >> [('--datasourcename', 'DB'), ('--password', '123')]
>
> >> How can I access "DB" from the list directly using an index?
>
> >> right now I would have to grab the tuple and the use the index of the
> >> tuple
>
> > Well, you can use
>
> >  lst[0][1]

But that sort of code rapidly becomes unreadable. Unpacking the list
and unpacking the tuple into named components will be more
understandable when you revisit the code.
--
http://mail.python.org/mailman/listinfo/python-list


Re: problem with program - debugging leading nowhere

2009-01-30 Thread John Machin
On Jan 31, 10:43 am, Matthew Sacks  wrote:
> i am trying to figure out what has gone wrong in my python program. it
> is complaining that there is an indendation error. should be simple
> enough but im stuck on this one. if anyone can help unjolt me it would
> be appreciated.
>
> thank you
>
> error message:
> Traceback (most recent call last):
>   File "", line 1, in 
> IndentationError: expected an indented block (, line 39)
>
> code:http://pastebin.com/f2f971f91

How are you running that? All that  stuff is not very
informative. I put your source into a pastebin.py:

>>> import pastebin
Traceback (most recent call last):
  File "", line 1, in 
  File "pastebin.py", line 31
elif o is not "":
   ^
IndentationError: expected an indented block

Dunno how you managed line 39.

What you have there is:
for o, a in optlist:
if o == "-h":
#usage()
elif o is not "":
which is equivalent to:
for o, a in optlist:
if o == "-h":
elif o is not "":
which is not such a good idea.

BTW, why aren't you using optparse?

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


Re: Swapping values of two variables

2009-01-30 Thread Aahz
In article ,
Eric Kang   wrote:
>
>In python, I set:
>
>x=1
>y=3
>
>z = x
>x = y
>y = z
>
>
>This gave me 3 1, which are the values of x and y swapped.
>The following would have given me the same result:
>x, y = y, x
>
>
>
>But could the swapping be done using less extra memory than this? What
>is the minimum amount of extra memory required to exchange two 32-bit
>quantities? What would be the pseudocode that achieves this minimum?

This looks like a homework problem to me
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

Weinberg's Second Law: If builders built buildings the way programmers wrote 
programs, then the first woodpecker that came along would destroy civilization.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Function Application is not Currying

2009-01-30 Thread J�rgen Exner
Jon Harrop  wrote:
>I had hoped someone else would correct you but they haven't. So...

That is because ...

>Xah Lee wrote:

... everyone with more than 5 cents of brain has killfiled him a long
time ago.

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


problem with program - debugging leading nowhere

2009-01-30 Thread Jervis Whitley
-- Forwarded message --
From: Jervis Whitley 
Date: Sat, Jan 31, 2009 at 10:59 AM
Subject: Re: problem with program - debugging leading nowhere
To: Matthew Sacks 
Cc: python-list@python.org





>
>
>
> error message:
> Traceback (most recent call last):
>  File "", line 1, in 
> IndentationError: expected an indented block (, line 39)
>
> code:
> http://pastebin.com/f2f971f91
>

Hi,

It looks like you have commented out a line on line 30, you need to place
something
in here, as python is expecting an indented level after your 'if'. (how
about a pass statement or a print saying some placeholder help details.)

On a side note, I've only had a quick skim, you shouldn't compare o to an
empty string "" using the 'is', is tests identity not equality. So what you
are saying is
is o the exact same empty string that I am creating "" (obviously it never
will be, because you just created it then with "") . Use the equality
operator == instead.
or in your case !=.

Cheers,


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


Re: problem with program - debugging leading nowhere

2009-01-30 Thread Jervis Whitley
>
>
>
> error message:
> Traceback (most recent call last):
>  File "", line 1, in 
> IndentationError: expected an indented block (, line 39)
>
> code:
> http://pastebin.com/f2f971f91
>

Hi,

It looks like you have commented out a line on line 30, you need to place
something
in here, as python is expecting an indented level after your 'if'. (how
about a pass statement or a print saying some placeholder help details.)

On a side note, I've only had a quick skim, you shouldn't compare o to an
empty string "" using the 'is', is tests identity not equality. So what you
are saying is
is o the exact same empty string that I am creating "" (obviously it never
will be, because you just created it then with "") . Use the equality
operator == instead.
or in your case !=.

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


problem with program - debugging leading nowhere

2009-01-30 Thread Matthew Sacks
i am trying to figure out what has gone wrong in my python program. it
is complaining that there is an indendation error. should be simple
enough but im stuck on this one. if anyone can help unjolt me it would
be appreciated.

thank you



error message:
Traceback (most recent call last):
  File "", line 1, in 
IndentationError: expected an indented block (, line 39)

code:
http://pastebin.com/f2f971f91
--
http://mail.python.org/mailman/listinfo/python-list


Re: search speed

2009-01-30 Thread Jervis Whitley
>
>
> Today this works fine, it saves me a lot of manuall work, but a seach
> takes around 5 min,
> so my questin is is there another way of search in a file
> (Today i step line for line and check)
>

If the files you are searching are located at some other location on a
network, you may find that much of the 5 minutes is actually the network
delay in fetching each file. (Although you said something about your dir
being cached?)

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


Re: accessing elements of a tuple

2009-01-30 Thread Matthew Sacks
>First of all, list is a reserved word.  Don't use it as a variable name.
I was using it as an example in this case.

>mylist[0][1] if I understand the question.
This works. Thank you.

On Fri, Jan 30, 2009 at 2:39 PM, Tim Chase
 wrote:
>> let me re-phrase that question:
>> i would like to access the element of individual tuples inside of a
>> list, by using an index.
>> so i have the list contents
>>
>> print list
>> [('--datasourcename', 'DB'), ('--password', '123')]
>>
>> How can I access "DB" from the list directly using an index?
>>
>> right now I would have to grab the tuple and the use the index of the
>> tuple
>
> Well, you can use
>
>  lst[0][1]
>
> to get it.  Or, if you're parsing through the list, you can use tuple
> unpacking:
>
>  for name, value in lst:
>print "%s = %s" % (name, value)
>
> As an aside, it looks like you're doing parameter parsing.  The standard
> library has the optparse module which takes a lot of pain out of parsing
> parameters.
>
> -tkc
>
>
>
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: accessing elements of a tuple

2009-01-30 Thread Tim Chase

let me re-phrase that question:
i would like to access the element of individual tuples inside of a
list, by using an index.
so i have the list contents

print list
[('--datasourcename', 'DB'), ('--password', '123')]

How can I access "DB" from the list directly using an index?

right now I would have to grab the tuple and the use the index of the tuple


Well, you can use

  lst[0][1]

to get it.  Or, if you're parsing through the list, you can use 
tuple unpacking:


  for name, value in lst:
print "%s = %s" % (name, value)

As an aside, it looks like you're doing parameter parsing.  The 
standard library has the optparse module which takes a lot of 
pain out of parsing parameters.


-tkc



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


Re: Does the Python community really follow the philospy of "Community Matters?"

2009-01-30 Thread Steve Holden
Ivan Illarionov wrote:
> r wrote:
>> Where are the community projects supporting Python? -- besides the
>> core devlopment. Seem s that nobody is interested unless their pay-pal
>> account is involved. I find this all quite disappointing.
> 
> Hi r,
> 
> Can you just type
> 
>import antigravity
> 
> and join us up there?
> 
> Hatred for Ruby and Perl seems to oppose natural Python forces,
> that's why you can't see community spirit. Let your hatred go and
> start
> flying already.
> 
Indeed. What r has not yet grasped is that to be in favor of one thing
you don't necessarily have to be against everything else. For example,
if it hadn't been for generous help from the Perl community (as
represented by http://www.yapc.org/) the first PyCon would never have
got off the ground. The competition between languages for the attention
of programmers isn't a zero-sum game.

I think there has perhaps been some slight decrease in the tolerance
level as expressed on this list over the last couple of years, but I
don't think it's (yet) anything to be concerned about. It's mostly a
matter of teaching by example. I'd like to think I usually set a good
example, but I've certainly been known to get crabby from time to time.

regards
 Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

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


Re: accessing elements of a tuple

2009-01-30 Thread Ian Pilcher
Matthew Sacks wrote:
> How can I access "DB" from the list directly using an index?

list[0][1]

... or did I misunderstand your question?

-- 

Ian Pilcher arequip...@gmail.com

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


Re: accessing elements of a tuple

2009-01-30 Thread D'Arcy J.M. Cain
On Fri, 30 Jan 2009 14:23:31 -0800
Matthew Sacks  wrote:
> let me re-phrase that question:
> i would like to access the element of individual tuples inside of a
> list, by using an index.
> so i have the list contents
> 
> print list
> [('--datasourcename', 'DB'), ('--password', '123')]
> 
> How can I access "DB" from the list directly using an index?

First of all, list is a reserved word.  Don't use it as a variable name.

mylist[0][1] if I understand the question.

I don't know what you are trying to accomplish but is this snippet
useful?

opts = dict([(x[0][2:], x[1]) for x in mylist if x[0][:2] == '--'])
print opts['datasourcename']

-- 
D'Arcy J.M. Cain  |  Democracy is three wolves
http://www.druid.net/darcy/|  and a sheep voting on
+1 416 425 1212 (DoD#0082)(eNTP)   |  what's for dinner.
--
http://mail.python.org/mailman/listinfo/python-list


Re: self-aware list of objects able to sense constituent member alterations?

2009-01-30 Thread Robert Kern

On 2009-01-29 18:22, Reckoner wrote:


I haven't looked at Enthought  in awhile. I want to avoid having to
installing the entire Enthought  toolsuite, however. Would I have to
do that for Traits?


No, Traits can be installed by itself unless if you want its GUI capabilities.

  http://pypi.python.org/pypi/Traits

--
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth."
  -- Umberto Eco

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


Re: accessing elements of a tuple

2009-01-30 Thread Matthew Sacks
let me re-phrase that question:
i would like to access the element of individual tuples inside of a
list, by using an index.
so i have the list contents

print list
[('--datasourcename', 'DB'), ('--password', '123')]

How can I access "DB" from the list directly using an index?

right now I would have to grab the tuple and the use the index of the tuple

On Fri, Jan 30, 2009 at 2:20 PM, Matthew Sacks  wrote:
> i am trying to access elements of a tuple without using the [1:5] notation.
> the contents of the tuple are as follows:
> ('--datasourcename', 'DB')
>
> I want to access everything in the second argument, but i am not sure
> how to go about this without converting to a string.
>
> thanks in advance
>
--
http://mail.python.org/mailman/listinfo/python-list


accessing elements of a tuple

2009-01-30 Thread Matthew Sacks
i am trying to access elements of a tuple without using the [1:5] notation.
the contents of the tuple are as follows:
('--datasourcename', 'DB')

I want to access everything in the second argument, but i am not sure
how to go about this without converting to a string.

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


Re: What's new in 3.0 about threading?

2009-01-30 Thread Terry Reedy

郑义 wrote:

Hello
I have questions about threading:

import threading
class myThread(threading.Thread):
def run(self):
print('hello,threads')
if __name__=='__main__':
threads=myThread()
threads.start()

Above program does't work at 'Run Module' in IDLE,


What does 'doesn't work' mean?  If you get an error traceback, post it.

Possible problem: IDLE runs on top of pythonw.exe (not python.exe) which 
does not open a window (IDLE runs its own window).  So I would not be 
surprised if output from separate thread in pythonw process gets lost. 
If that is the problem, try having the run() method send something back 
to the main thread, say through a Queue, and print from there after 
starting the subthread.


but it works well 
under executing scripts.Is it anything wrong?

WindowXP,Python 3.0
Thanks.




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


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


Re: Does the Python community really follow the philospy of "Community Matters?"

2009-01-30 Thread Terry Reedy

Stephen Hansen wrote:
On Fri, Jan 30, 2009 at 12:38 AM, r 

Personally, I work for a division in our company that has converted over 
the last few years our entire software line from an old, Windows-only 
mix of C and VCL-stuff, to a serious mid-sized product which recently 
clocked in at about 165k lines of Python code (about 600k more in third 
party libs!) that's fast, effective, flexible, multi-platform and highly 
responsive to our customer's evolving needs. We actually did a complete 
rewrite from the ground up -- a dangerous thing to do, but the legacy 
product was so out of date that it had to be done... and I don't think 
any other set of tools would have been able to let us do so as well, in 
as short of a period of time, or as iteratively and in cooperation with 
our customer base.


Thank you for sharing this.  If it has not been already, could this be 
shared as a Python success story on the site?  (With proprietary detail 
omitted as needed for approval, of course.)


tjr

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


Re: relpath problem on windows

2009-01-30 Thread Scott David Daniels

eliben wrote:

I'm having a problem with 2.6's new os.path.relpath function.

> ... But this isn't [correct]:

relpath(r'd:\jho', r'd:\\')
=> '..\jho'
Neither is this:
relpath(r'd:\jho', r'd:')
=> '..\..\..\jho'

What am I missing?


There is no way to write a raw string for text ending in a single
backslash.  r'd:\\' == 'd:'
What you want is relpath(r'd:\jho', 'd:\\')

But it turns out this doesn't work, either.
File a bug.

--Scott David Daniels
scott.dani...@acm.org
--
http://mail.python.org/mailman/listinfo/python-list


Re: Odd syntactic NON-error?

2009-01-30 Thread Simon Brunning
2009/1/30 Alaric Haag :

> So, is the "secret" that the period is syntactically an "operator" like
> + or * ?

Exactly that: .

Sh!

-- 
Cheers,
Simon B.
--
http://mail.python.org/mailman/listinfo/python-list


python is a python

2009-01-30 Thread x
python is a python



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


Re: verilog like class w/ bitslicing & int/long classtype

2009-01-30 Thread Stef Mientki

Marc 'BlackJack' Rintsch wrote:

On Fri, 30 Jan 2009 00:25:03 +0100, Stef Mientki wrote:

  

try this:

class MyRegClass ( int ) :
  def __init__ ( self, value ) :
self.Value = value
  def __repr__ ( self ) :
line = hex ( self.Value )
line = line [:2] + line [2:].upper()
return line



def __repr__(self):
return '0x%X' % self.value

  

  __str__ = __repr__



This is unnecessary, the fallback of `__str__` is `__repr__` already.

  

well this is what my Python is doing:

without  _str__ = __repr__
>>print shadow_register
170

with  _str__ = __repr__
>>print shadow_register
0xAA

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


Re: search speed

2009-01-30 Thread Stefan Behnel
Diez B. Roggisch wrote:
> that's not necessarily the best thing to do if things have a
> record-like structure. The canonical answer to this is then to use a
> database to hold the data, instead of flat files. So if you have any
> chance to do that, you should try & stuff things in there.

It's worth mentioning to the OP that Python has a couple of database
libraries in the stdlib, notably simple things like the various dbm
flavoured modules (see the anydbm module) that provide fast
string-to-string hash mappings (which might well be enough in this case),
but also a pretty powerful SQL database called sqlite3 which allows much
more complex (and complicated) ways to find the needle in the haystack.

http://docs.python.org/library/persistence.html

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


Re: is python Object oriented??

2009-01-30 Thread Christian Heimes
Michael Torrie schrieb:
>> It all depends on implementation, I think even we can make "C" object
>> oriented with proper implementation.
> 
> Indeed, any code based on gobject libraries can be object-oriented in
> design and function.

The Python C API is a good example for well designed and object oriented
C code.

Christian

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


Re: Rounding to the nearest 5

2009-01-30 Thread David

Benjamin J. Racine wrote:

Doesn't this work?

round_by_5.py


import sys

def round_by_5(x= sys.argv[0]):
x = x/5.
x = round(x)
x = x*5
print(x)
return x 


Ben R.


I am learning, I got this to work fine;
#!/usr/bin/python

import sys

def round_by_5(x = sys.argv[1]):
x = int(x)/5
x = round(x)
x = x*5
print int(x)

round_by_5(sys.argv[1])


--
Powered by Gentoo GNU/LINUX
http://www.linuxcrazy.com
pgp.mit.edu

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


Re: writing large dictionaries to file using cPickle

2009-01-30 Thread perfreem
On Jan 28, 6:08 pm, Aaron Brady  wrote:
> On Jan 28, 4:43 pm, perfr...@gmail.com wrote:
>
> > On Jan 28, 5:14 pm, John Machin  wrote:
>
> > > On Jan 29, 3:13 am, perfr...@gmail.com wrote:
>
> > > > hello all,
>
> > > > i have a large dictionary which contains about 10 keys, each key has a
> > > > value which is a list containing about 1 to 5 million (small)
> > > > dictionaries. for example,
>
> > > > mydict = {key1: [{'a': 1, 'b': 2, 'c': 'hello'}, {'d', 3, 'e': 4, 'f':
> > > > 'world'}, ...],
> > > >                 key2: [...]}
>
> > > > in total there are about 10 to 15 million lists if we concatenate
> > > > together all the values of every key in 'mydict'. mydict is a
> > > > structure that represents data in a very large file (about 800
> > > > megabytes).
>
> snip
>
> > in reply to the other poster: i thought 'shelve' simply calls pickle.
> > if thats the case, it wouldnt be any faster, right ?
>
> Yes, but not all at once.  It's a clear winner if you need to update
> any of them later, but if it's just write-once, read-many, it's about
> the same.
>
> You said you have a million dictionaries.  Even if each took only one
> byte, you would still have a million bytes.  Do you expect a faster I/
> O time than the time it takes to write a million bytes?
>
> I want to agree with John's worry about RAM, unless you have several+
> GB, as you say.  You are not dealing with small numbers.

in my case, i just write the pickle file once and then read it in
later. in that case, cPickle and shelve would be identical, if i
understand correctly?

the file i'm reading in is ~800 MB file, and the pickle file is around
300 MB. even if it were 800 MB, it doesn't make sense to me that
python's i/o would be that slow... it takes roughly 5 seconds to write
one megabyte of a binary file (the pickled object in this case), which
just seems wrong. does anyone know anything about this? about how i/o
can be sped up for example?

the dictionary might have a million keys, but each key's value is very
small. i tried the same example where the keys are short strings (and
there are about 10-15 million of them) and each value is an integer,
and it is still very slow. does anyone know how to test whether i/o is
the bottle neck, or whether it's something specific about pickle?

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


Re: search speed

2009-01-30 Thread Stefan Behnel
D'Arcy J.M. Cain wrote:
> On Fri, 30 Jan 2009 15:46:33 +0200
> Justin Wyer  wrote:
>> $ find  -name "*" -exec grep -nH "LF01" {} \;
>> | cut -d ":" -f 1 | sort | uniq
> 
> I know this isn't a Unix group but please allow me to suggest instead;
> 
>   $ grep -lR LF01 

That's a very good advice. I had to pull some statistics from a couple of
log files recently some of which were gzip compressed. The obvious Python
program just eats your first CPU's cycles parsing data into strings while
the disk runs idle, but using the subprocess module to spawn a couple of
gzgrep's in parallel that find the relevant lines, and then using Python to
extract and aggregate the relevant information from them does the job in
no-time.

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


Re: Odd syntactic NON-error?

2009-01-30 Thread Alaric Haag
In article 
<20090130173948.12853.732928641.divmod.quotient@henry.divmod.com>,
 Jean-Paul Calderone  wrote:

> On Fri, 30 Jan 2009 11:36:45 -0600, Alaric Haag  wrote:
> >Hello,
> >
> >I just noticed that I've been successfully importing a module I wrote
> >which contains a class definition that begins with (docstring removed):
> >
> >class TDF():
> >def __init__(self, name='', mode=tscan. GP_NOCLOBBER):
> >
> >Note the "space" which shouldn't be here---^
> 
> The space is irrelevant.
> 
>   >>> object. __init__
>   
>   >>> object.__init__ is object. __init__
>   True
>   >>> 
> 
> Jean-Paul
> --
> http://mail.python.org/mailman/listinfo/python-list

It strikes me as strange that Python (which I love btw) would be so 
loose in its syntax when "spaces matter" at the beginning of a line. 

I now see that a space could precede the period too, as in:

   x = foo . method()

So, is the "secret" that the period is syntactically an "operator" like 
+ or * ?

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


Re: Get thread pid

2009-01-30 Thread Christian Heimes
Alejandro schrieb:
> Hi:
> 
> I have Python program running under Linux, that create several
> threads, and I want to now the corresponding PID of the threads.

May I ask why you want to get the TID? You can't do anything useful with
it. You can't kill a thread safely, neither from within Python nor from
the outside world. thread.get_ident() gives you an id. On pthread based
systems the function uses pthread_self().
For TLS, Python has builtin classes that are hooked into Python's
internal threading system.

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


Re: is python Object oriented??

2009-01-30 Thread Michael Torrie
Veerendra Ganiger wrote:
> Python is not purely object oriented programming, because we can write
> functions without any class.
> You are right, predefined class attributes are available when we write or
> execute a piece of python code without defining class, that means it's just
> using objects for it's purpose. It does not mean its purely object oriented.

To be clear, python does not force you to lay out your code according to
some strict object-oriented paradigm.  But Python itself is still purely
object-oriented, as is your script when parsed.

This function without a class that you mentioned, is in fact an object
with attributes.  You can pass a function around just like any other
object.  Even calling a function is invoked like so:

myfunc.__call__(params)

So necessitating that code be inside a class has nothing to do with
object-oriented programming.  Let's not forget that classes are
themselves objects (metaobjects in smalltalk parlance if I recall
correctly).

Now python does not have any way besides lambda expressions of creating
unbound function objects, but in practice this doesn't matter as I can
rebind names freely.  I can still do:

a=myfunc
myfunc=some other expression or object

> It all depends on implementation, I think even we can make "C" object
> oriented with proper implementation.

Indeed, any code based on gobject libraries can be object-oriented in
design and function.
--
http://mail.python.org/mailman/listinfo/python-list


Re: search speed

2009-01-30 Thread John Machin
D'Arcy J.M. Cain  druid.net> writes:

> 
> On Fri, 30 Jan 2009 15:46:33 +0200
> Justin Wyer  gmail.com> wrote:
> > $ find  -name "*" -exec grep -nH "LF01" {} \;
> > | cut -d ":" -f 1 | sort | uniq
> 
> I know this isn't a Unix group but please allow me to suggest instead;
> 
>   $ grep -lR LF01 


and if the OP is on Windows: an alternative to cygwin is the GnuWin32 collection
of Gnu utilities ported to Windows. See http://gnuwin32.sourceforge.net/ ...
you'll want the Grep package but I'd suggest the CoreUtils package as worth a
detailed look, and do scan through the whole list of packages while you're 
there.

HTH,
John




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


Re: is python Object oriented??

2009-01-30 Thread Michael Torrie
Hung Vo wrote:
> I'm new to Python and also wondering about OOP in Python.
> 
> I want to justify the above question (is Python Object-Oriented?).
> Does Python follow the concepts/practices of Encapsulation,
> Polymorphism and Interface, which are quite familiar to Java
> programmers?

I'd say that actually Python uses encapsulation extensively throughout
the language.   Every object in Python has attributes.  Thus every
object encapsulates (contains) attributes (which are themselves objects).

I think the term "encapsulation" is often misinterpreted by some (Java
programmers in particular) to mean some kind of enforced black-box
methodology.  In effect they feel that getters and setters is the
definition of encapsulation.  This is really not true, especially if you
go back to the original OO languages, such as Smalltalk.

So if you are asking, does python enforce some kind of bizarre black box
 access semantics (requiring getters and setters), the answer is an
emphatic "no!"

Interfaces have nothing to do with OO programming as a matter of a
fundamental principle. Interfaces exist in Java to compensate for
flaws/features in the language.  Particularly the lack of multiple
inheritance which is a blessing/curse in Java.  Python just doesn't need
interfaces.  Protocols for communication with an object do not need to
be formally enforced.  For example the popular database API that most
python database libraries use just makes sure it implements certain
methods.  Thus it doesn't matter if I'm using mysql, postgresql, or
oracle.  I still call the object's "connect" method.  Such a breath of
fresh air compared to Java, in my opinion.  Such informality can be a
bit of a hindrance to some I guess.

After this entire thread, it's funny that people are still chiming in
saying, "so is it really OOP" after having it explained in so many ways.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Does the Python community really follow the philospy of "Community Matters?"

2009-01-30 Thread Ivan Illarionov
r wrote:
> Where are the community projects supporting Python? -- besides the
> core devlopment. Seem s that nobody is interested unless their pay-pal
> account is involved. I find this all quite disappointing.

Hi r,

Can you just type

   import antigravity

and join us up there?

Hatred for Ruby and Perl seems to oppose natural Python forces,
that's why you can't see community spirit. Let your hatred go and
start
flying already.

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


Re: Function Application is not Currying

2009-01-30 Thread Tim Greer
Jon Harrop wrote:

> I had hoped someone else would correct you but they haven't. So...

The lack of replies aren't about anyone correcting him or not, it's that
the guy just posts anything he can to spamvertize his site and tell
everyone how brilliant he thinks he is.  It's just a method he uses to
try and feel important and also get people to his site (and for the
search engines to rank it higher).  He's a known troll and spammer in a
lot of groups due to this.  The guy rarely has anything relevant to the
groups he posts to.  Most people I know of have come to just filter out
his posts.
-- 
Tim Greer, CEO/Founder/CTO, BurlyHost.com, Inc.
Shared Hosting, Reseller Hosting, Dedicated & Semi-Dedicated servers
and Custom Hosting.  24/7 support, 30 day guarantee, secure servers.
Industry's most experienced staff! -- Web Hosting With Muscle!
--
http://mail.python.org/mailman/listinfo/python-list


Re: Function Application is not Currying

2009-01-30 Thread Jon Harrop

I had hoped someone else would correct you but they haven't. So...

Xah Lee wrote:
> Here are some examples of a function that returns a function as
> result, but is not currying.
> 
> Mathematica example:
> 
> f[n_]:=Function[n^#];
> f[7][2]
> (* returns 49 *)
> 
> Emacs lisp example:
> 
> (defmacro f (n) (list 'lambda (list 'x) (list 'expt n 'x) ) )
> (funcall (f 7) 2)
> 
> Perl example:
> 
> sub f {$n=$_[0]; sub { $n ** $_[0]} };
> print &{ f(7) } (2);
> 
> Javascript example:
> 
> function f(n) {return function (x) {return Math.pow(x,n);}; }
> alert (f(7) (2));
> 
> However, the above are not languages that support currying,

That is incorrect. Mathematica, Lisp, Perl and Javascript all support
currying.

> which is a feature that Haskell & Ocaml has.

That is correct. Here is an OCaml equivalent:

  let f =
fun n ->
  fun m ->
n ** m

> To be more concrete, in the context of a given computer language, to
> say that it support curring, is to mean that the compiler understand
> the concept to certain degree. More to the point, the language is
> inherently able to take a function of more than one arg and
> deconstruct it to several functions of single arg.

That is incorrect. You only need a language with first-class functions.

I believe you are confusing the syntactic support in OCaml and Haskell for
something more. It simply allows you to rewrite the above as:

  let f n m = n ** m

or:

  let f = fun n m -> n ** n

-- 
Dr Jon D Harrop, Flying Frog Consultancy Ltd.
http://www.ffconsultancy.com/?u
--
http://mail.python.org/mailman/listinfo/python-list


Re: A replacement to closures in python?

2009-01-30 Thread Stephen Hansen
On Fri, Jan 30, 2009 at 10:36 AM, Noam Aigerman  wrote:












Hi,

I want to create an array of functions, each doing the same
thing with a change to the parameters it uses… something like:I'm not really sure what you're trying to accomplish so there may be a better answer, but in this case if you just pass the name as a keyword arg to the function you're defining it'd work. That way you're saving the current state of 'name' when defining the function, instead of having it look it up at runtime.I.e.arr = ['john', 'terry', 'graham']funcs = []for name in arr:    def func(name=name):    print 'Hi', name    funcs.append(func)for f in funcs:    f()--Stephen



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


Re: Importing modules

2009-01-30 Thread Aahz
In article <631e2879-6171-417e-8254-7f78c8cfc...@i24g2000prf.googlegroups.com>,
alex23   wrote:
>
>If you're having to set up your imports in a specific order, odds are
>you have either a circular dependency or are overusing 'from 
>import *'. You should -never- (IMO) do something like 'from library> import x, y, z' in module 'a' and then 'from a import *' in
>module 'b'. If 'b' uses x, y & z, it should import them itself. If you
>-must- use 'import *', specify exactly what should be exported via
>'__all__'...in most cases, it should be restricted to only objects
>defined within that module.

There's one other way to run into this problem: I forget the exact
mechanics, but if you mix up absolute and relative imports for modules
inside packages, you can get namespace problems.  (It's also possible
newer versions of Python don't have this issue.)
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

Weinberg's Second Law: If builders built buildings the way programmers wrote 
programs, then the first woodpecker that came along would destroy civilization.
--
http://mail.python.org/mailman/listinfo/python-list


Re: error on building 2.6.1. (_ctypes)

2009-01-30 Thread Bernard Rankin



> 
> > I am trying to build python 2.6 on a machine (web server) that I do not 
> > have 
> root access to. (has 2.4 installed)
> > 
> > Python 2.5 builds fine, but I am getting an error when I run "make" for 
> > 2.6.1.
> > 
> > 
> > /home/username/local-src/Python-2.6.1/Modules/_ctypes/_ctypes.c:3941: 
> > error: 
> syntax error before '*' token
> > /home/username/local-src/Python-2.6.1/Modules/_ctypes/_ctypes.c:3942: 
> > warning: 
> function declaration isn't a prototype
> > /home/username/local-src/Python-2.6.1/Modules/_ctypes/_ctypes.c: In 
> > function 
> `CFuncPtr_nonzero':
> > /home/username/local-src/Python-2.6.1/Modules/_ctypes/_ctypes.c:3943: 
> > error: 
> `self' undeclared (first use in this function)
> 
> Mmm... my 2.6.1 source show different line numbers, maybe you should check 
> it's 
> the right file?
> 

Wow, good catch.

I just re-downloaded the archive and it works fine.   

I know for certain that I did no editing to the files, and even tried expanding 
the original tar.gz a couple of times.   

There must be a corrupted package somewhere among the official Python mirrors.  
(Sadly, I overwrote the old tar.gz file when I got the new one.)


  

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


A replacement to closures in python?

2009-01-30 Thread Noam Aigerman
Hi,

I want to create an array of functions, each doing the same thing with a
change to the parameters it uses... something like:

arr=['john','terry','graham']

funcs=[]

for name in arr:

def func():

print 'hello, my name is '+name

funcs.append(func)

for f in funcs:

f()

 

And I would like that to print

hello, my name is john

hello, my name is terry

hello, my name is graham

of course... 

Now I understand why the above code doesn't work as I want it to, but is
there some simple workaround for it? 

Thanks, Noam 

 

 

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


RE: Rounding to the nearest 5

2009-01-30 Thread Benjamin J. Racine
Doesn't this work?

round_by_5.py

>>>

import sys

def round_by_5(x= sys.argv[0]):
x = x/5.
x = round(x)
x = x*5
print(x)
return x 

Ben R.


-Original Message-
From: python-list-bounces+bjracine=glosten@python.org 
[mailto:python-list-bounces+bjracine=glosten@python.org] On Behalf Of 
D'Arcy J.M. Cain
Sent: Friday, January 30, 2009 6:07 AM
To: Steven D'Aprano
Cc: python-list@python.org
Subject: Re: Rounding to the nearest 5

On 30 Jan 2009 06:23:17 GMT
Steven D'Aprano  wrote:
> On Fri, 30 Jan 2009 00:24:47 -0500, D'Arcy J.M. Cain wrote:
> > That appears to be rounding to nearest 10, not 5.  Clarify your 
> > requirements first.
> 
> Look again. 36 => 35.

You are correct.  I should have ommitted my first sentence and emphasized the 
second.  :-)

-- 
D'Arcy J.M. Cain  |  Democracy is three wolves
http://www.druid.net/darcy/|  and a sheep voting on
+1 416 425 1212 (DoD#0082)(eNTP)   |  what's for dinner.
--
http://mail.python.org/mailman/listinfo/python-list
--
http://mail.python.org/mailman/listinfo/python-list


Re: Odd syntactic NON-error?

2009-01-30 Thread Jean-Paul Calderone

On Fri, 30 Jan 2009 11:36:45 -0600, Alaric Haag  wrote:

Hello,

I just noticed that I've been successfully importing a module I wrote
which contains a class definition that begins with (docstring removed):

class TDF():
   def __init__(self, name='', mode=tscan. GP_NOCLOBBER):

Note the "space" which shouldn't be here---^


The space is irrelevant.

 >>> object. __init__
 
 >>> object.__init__ is object. __init__
 True
 >>> 


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


Odd syntactic NON-error?

2009-01-30 Thread Alaric Haag
Hello,

I just noticed that I've been successfully importing a module I wrote 
which contains a class definition that begins with (docstring removed):

class TDF():
def __init__(self, name='', mode=tscan. GP_NOCLOBBER):

Note the "space" which shouldn't be here---^

I'm running Python 2.5.2. 

What does the interpreter "think" I'm doing? It's not flagged by pylint 
either, so I suspect there's a reasonable explanation.

Alaric

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


Python Developer needed for Greenwich, CT assignment

2009-01-30 Thread ronaldjweiss
Senior Python Programmer needed to develop, enhance and expand a Trade
Capture application at a hedge fund client.  The technical platform
includes MySQL running both on Windows and UNIX.

Requirements:
3-6+ years solid Python development skills and experience in the
brokerage industry a must.  SQL and UNIX required.

This is a 6 - 12 month contract that could extend indefinitely.

Ron Weiss

THE BMW GROUP, INC.
   Technology placement in the securities industry
40 Exchange Place, Suite 700, New York, NY 10005
212-943-8800
r...@careerobject.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: Why doesn't this work in Eclipse ? (Simple pexpect code that works in bash)

2009-01-30 Thread Gary Duzan
On Jan 30, 11:03 am, Linuxguy123  wrote:
> I'm trying to build a small Python app in Eclipse under Fedora 10.
>
> I have the following code:
>
> import os
> import sys
> import pexpect
>
> child = pexpect.spawn('/bin/bash')
> child.interact()
>
> When I run it in Eclipse, I get:
>
> Traceback (most recent call last):
>   File "/home/xxx/workspace/FixPermissions/src/default/main.py", line
> 56, in 
>     child.interact()
>   File "/usr/lib/python2.5/site-packages/pexpect.py", line 1489, in
> interact
>     mode = tty.tcgetattr(self.STDIN_FILENO)
> termios.error: (22, 'Invalid argument')
>
> Yet if I run it in a bash shell, it works:
>
> [ ... ]
>
> Why doesn't it run under Eclipse and how do I fix it so it does ?

   That code assumes the stdin of the parent is a real (or possibly
pseudo-) terminal, which appears not to be the case for programs run
through Eclipse.

 Gary Duzan

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


What's new in 3.0 about threading?

2009-01-30 Thread 郑义
Hello
I have questions about threading:

import threading
class myThread(threading.Thread):
def run(self):
print('hello,threads')
if __name__=='__main__':
threads=myThread()
threads.start()

Above program does't work at 'Run Module' in IDLE,but it works well under
executing scripts.Is it anything wrong?
WindowXP,Python 3.0
Thanks.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Does the Python community really follow the philospy of "Community Matters?"

2009-01-30 Thread MRAB

Stephen Hansen wrote:
On Fri, Jan 30, 2009 at 12:38 AM, r > wrote:


On Jan 30, 2:26 am, John Machin mailto:sjmac...@lexicon.net>> wrote:
[snip]
 > This doesn't appear to match the description. Perhaps the PSU has
 > subverted my comp)(*&^...@!
 > NO CARRIER

Oops -- Good catch John,
Even perfect people like myself make mistakes :). Here is the
aforementioned thread where a Python user was chastised for daring to
say Python has a clearer syntax than Perl thereby easing
maintainability: OH NO! *big hand wave*

http://groups.google.com/group/comp.lang.python/browse_thread/thread/b1214df115ac01ce/c7cfe1fa9634cc2a?hl=en&lnk=gst&q=perl+bashing#c7cfe1fa9634cc2a



These Perl mongers have no business doing their mongling here, go to
c.l.Perl!


He was not chastised, nor threatened as you previously said; he was 
welcomed to Python in all of its awesomeness, and given a pointer about 
community etiquette.



[snip]
I have tons of positive things to say about Python: lots of people in 
The Community do. And we've all worked with other languages and have 
reasons why we don't like those tools, and people are fine to share 
those reasons. But that's a different thing then flinging bile and 
ranting about how horrible Language-X is or how Perfect-For-All-Things 
Python is.



[snip]
It's probably unpythonic to bash other languages. Python is so good that 
there's no need. :-)

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


Re: Get thread pid

2009-01-30 Thread Jean-Paul Calderone

On Fri, 30 Jan 2009 08:33:53 -0800 (PST), Alejandro 
 wrote:

On Jan 30, 9:11 am, Jean-Paul Calderone  wrote:

[clarification about threads]


Thank you for the clarification. I will reformulate my question:

pstree and also ntop (but not top) show a number for each thread, like
for instance:

$pstree -p 9197
python(9197)€ˆ€{python}(9555)
†€{python}(9556)
†€{python}(9557)
†€{python}(9558)
†€{python}(9559)
†€{python}(9560)
†€{python}(9561)
†€{python}(9562)
†€{python}(9563)
„€{python}(9564)

Is is possible to get the number corresponding to each thread?

The reason I am interested is because one of my thread is hogging the
CPU, and want to find which one is the culprit.


I think someone mentioned calling gettid using ctypes earlier in this
thread.  Unfortunately, this is somewhat convoluted:

   exar...@charm:~$ python
   Python 2.5.2 (r252:60911, Jul 31 2008, 17:28:52)
   [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2
   Type "help", "copyright", "credits" or "license" for more information.
   >>> import ctypes, os, threading, time
   >>> os.system("pstree -p " + str(os.getpid()))
   python(11427)───sh(11429)───pstree(11430)
   0
   >>> threading.Thread(target=time.sleep, args=(1000,)).start()
   >>> os.system("pstree -p " + str(os.getpid()))
   python(11427)─┬─sh(11436)───pstree(11437)
 └─{python}(11431)
   0
   >>> ctypes.CDLL('libc.so.6').syscall(224)
   11427
   >>> 


224 comes from grepping /usr/include for SYS_gettid.  This is Linux
specific, and probably even architecture specific.  For a quick
debug hack, perhaps this is good enough, though.

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


Re: Adding a positive number and a negative number

2009-01-30 Thread Scott David Daniels

Grant Edwards wrote:

On 2009-01-30, MRAB  wrote:

Eric Kang wrote:

In two's complement representation, can adding one positive
and one negative give you overflow?

No.

AFAIK, in Python adding integers never gives you overlow
regardless of sign.


Right, but he wants his homework answer.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Swapping values of two variables

2009-01-30 Thread Grant Edwards
> Grant Edwards wrote:
> > On 2009-01-30, MRAB  wrote:
> >
> >>> What is the minimum amount of extra memory required to exchange two
> >>> 32-bit quantities? What would be the pseudocode that achieves this
> >>> minimum?
> >> x ^= y
> >> y ^= x
> >> x ^= y
> >>
> >> This is really only of use when working in assembly language.
> >
> > And rarely then. ;)
> >
> > [Readability counts everywhere.]
>
> It can be useful if you want to swap the contents of 2 registers in ARM
> assembly language:
>
> EOR r0,r0,r1
> EOR r1,r0,r1
> EOR r0,r0,r1
>
> The quickest alternative is to use MOV:
>
> MOV r2,r0
> MOV r0,r1
> MOV r1,r2
>
> The same number of instructions, program bytes, and clock
> cycles, but requiring an additional register!

Yea, I guess the ARM's SWP instruction only works on
register<->memory.  That said, I don't remember ever needing to
swap the contents of two register when working in ARM assembly
language (yes I have done some).  I always just use the value
in the register where it is.  Swap with top of stack (for which
the SWP instruction works) can be useful for implementing some
sorts of stack-based VMs, but register-register swap just
doesn't seem to be something one needs to do (which probably
explains why there's no instruction to do it).

Given the choice between the cryptic version that doesn't
require a third register, and the obvious version that uses a
third register, I'll usually choose the latter.  There aren't
that many people left who'll recognize what the triple-xor
sequence is doing -- so if I ever would use it, I'd probably
make it a macro.

-- 
Grant Edwards   grante Yow! This ASEXUAL PIG
  at   really BOILS my BLOOD
   visi.com... He's so ... so
   ... URGENT!!
--
http://mail.python.org/mailman/listinfo/python-list


Re: search speed

2009-01-30 Thread Scott David Daniels

Tim Rowe wrote:

 But even without going to a full database solution it might
be possible to make use of the flat file structure. For example, does
the "LF01" have to appear at a specific position in the input line? If
so, there's no need to search for it in the complete line. *If* there
is any such structure then a compiled regexp search is likely to be
faster than just 'if "LF01" in line', and (provided it's properly
designed) provides a bit of extra insurance against false positives.


Clearly this is someone who regularly uses grep or perl.  If you
know the structure, like the position in a line, something like
the following should be fast:

with open(somename) as source:
 for n, line in enumerate(source):
 if n % 5 == 3 and line[5 : 9] == 'LF01':
 print ('Found on line %s: %s' % (1 + n, line.rstrip())

Be careful with your assertion that a regex is faster, it is certainly
not always true.  Measure speed, don't take mantras as gospel.

--Scott David Daniels
scott.dani...@acm.org
--
http://mail.python.org/mailman/listinfo/python-list


Re: Does the Python community really follow the philospy of "Community Matters?"

2009-01-30 Thread Stephen Hansen
On Fri, Jan 30, 2009 at 12:38 AM, r  wrote:

> On Jan 30, 2:26 am, John Machin  wrote:
> [snip]
> > This doesn't appear to match the description. Perhaps the PSU has
> > subverted my comp)(*&^...@!
> > NO CARRIER
>
> Oops -- Good catch John,
> Even perfect people like myself make mistakes :). Here is the
> aforementioned thread where a Python user was chastised for daring to
> say Python has a clearer syntax than Perl thereby easing
> maintainability: OH NO! *big hand wave*
>
> http://groups.google.com/group/comp.lang.python/browse_thread/thread/b1214df115ac01ce/c7cfe1fa9634cc2a?hl=en&lnk=gst&q=perl+bashing#c7cfe1fa9634cc2a
>
> These Perl mongers have no business doing their mongling here, go to
> c.l.Perl!


He was not chastised, nor threatened as you previously said; he was welcomed
to Python in all of its awesomeness, and given a pointer about community
etiquette.

"excessive Perl bashing" ... "considered tasteless" ... Come on. That's so
mild of a warning that you can barely call it that. Considering the comment
after "the occasional snide comment should be fine :-)" complete with a
smiley even should make it very clear that a simple and *friendly* pointer
on getting along in a new community was given.

It was great advice, too. No one has a problem with talking about Python's
strengths, or how good Python has worked for them; or even comparing it to
other languages in a reasoned way (though those conversations have all been
had ten thousand years ago)... its the vitriolic bashing of other languages
that isn't wanted because there's no point to it at all. It does nothing at
all but make us look like mongers, zealots, and childish to boot.

Advocating the language is a great thing to do. Evangelizing it makes us
look like idiots.

You catch grief because your evangelization of the language is *so*
completely over the top that it comes off almost as trollish-- the
reverse-troll technique is not all that uncommon. Like with
http://groups.google.com/group/comp.lang.python/msg/b8a079b8b780be19 -- and
the talk of throwing off shackles and embracing the Freedom That Python
Gives You. Its so completely excessive that it can't even be taken
seriously.

You ask if community matters to Python? It does, absolutely. I just don't
think you understand that community. Its there. Its full of tons of people
in many walks of life who use Python to get things done, and who absolutely
love doing so -- its full of people who use the language and the tools it
provides to accomplish real things easier, faster (to accomplish a goal, not
to execute a chunk of code) and without sacrificing long-term
maintainability. My impression of the community is simply that its a more
quiet one: advocacy instead of evangelism.

I'd rather talk about how to accomplish something in a Pythonic way, or how
to help use Python to solve your problems in a way that is natural to do in
Python -- and convert you that way, then to worry about a "war with Ruby"
and such nonsense. Personally, I love Python. I wouldn't take a job writing
in either Perl or Ruby: but those who like that language are welcome to it.

Personally, I work for a division in our company that has converted over the
last few years our entire software line from an old, Windows-only mix of C
and VCL-stuff, to a serious mid-sized product which recently clocked in at
about 165k lines of Python code (about 600k more in third party libs!)
that's fast, effective, flexible, multi-platform and highly responsive to
our customer's evolving needs. We actually did a complete rewrite from the
ground up -- a dangerous thing to do, but the legacy product was so out of
date that it had to be done... and I don't think any other set of tools
would have been able to let us do so as well, in as short of a period of
time, or as iteratively and in cooperation with our customer base.

I have tons of positive things to say about Python: lots of people in The
Community do. And we've all worked with other languages and have reasons why
we don't like those tools, and people are fine to share those reasons. But
that's a different thing then flinging bile and ranting about how horrible
Language-X is or how Perfect-For-All-Things Python is.

--Stephen

P.S. Sorry for waxing verbosely.
--
http://mail.python.org/mailman/listinfo/python-list


Announcing Pyflakes 0.3.0

2009-01-30 Thread Jean-Paul Calderone

I am proud to announce the release of Pyflakes 0.3.0.  This release fixes
several bugs, improves compatibility with recent versions of Python, and
new flake checks.

Pyflakes is a static analysis tool for Python source.  It is focused on
identifying common errors quickly without executing Python code.  It is
a handy supplement to your project's test suite.

Read more about Pyflakes and the 0.3.0 release on the website:

  http://divmod.org/trac/wiki/DivmodPyflakes

Jean-Paul Calderone
Divmod, Inc.

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


Re: Get thread pid

2009-01-30 Thread ma
I think issue here is that you're invoking a system call (using either the
subprocess module or os.popen*) from your threads. Those *are* external
processes and will show up under pstree since they have a parent process. If
you're using subprocess.Popen() the object that is returned has an attribute
'pid' that can be accessed (which would serve your purpose).

Please note that *this is NOT a thread id*


On Fri, Jan 30, 2009 at 11:33 AM, Alejandro
wrote:

> On Jan 30, 9:11 am, Jean-Paul Calderone  wrote:
> > [clarification about threads]
>
> Thank you for the clarification. I will reformulate my question:
>
> pstree and also ntop (but not top) show a number for each thread, like
> for instance:
>
> $pstree -p 9197
> python(9197)€ˆ€{python}(9555)
>  †€{python}(9556)
> †€{python}(9557)
> †€{python}(9558)
> †€{python}(9559)
> †€{python}(9560)
> †€{python}(9561)
> †€{python}(9562)
> †€{python}(9563)
>  „€{python}(9564)
>
> Is is possible to get the number corresponding to each thread?
>
> The reason I am interested is because one of my thread is hogging the
> CPU, and want to find which one is the culprit.
>
> Regards,
> Alejandro.
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: More mod_wsgi weirdness: process restarts on redirect

2009-01-30 Thread Ron Garret
In article 
<63cf7deb-f15c-4259-aa24-1b8da8468...@r41g2000prr.googlegroups.com>,
 Graham Dumpleton  wrote:

> On Jan 30, 11:01 am, Ron Garret  wrote:
> > In article ,
> >  Joshua Kugler  wrote:
> >
> > > Ron Garret wrote:
> > > > My question is: is this supposed to be happening?  Or is this an
> > > > indication that something is wrong, and if so, what?
> >
> > > You are probably just hitting a different instance of Apache, thus the
> > > different process ID.
> >
> > Yep, that's what it turned out to be.  I thought I had a
> > WSGIDaemonProcess processes=1 directive in my config, but I had it in
> > the wrong place (a different vhost) so it wasn't actually active.
> > http://code.google.com/p/modwsgi/wiki/ProcessesAndThreading
> > But that leaves me wondering why the redirect would reliably trigger
> > switching processes.  The reason I thought that I had the correct
> > configuration and only had one process is that when I reloaded the
> > non-redirected page I *always* got the same process ID.  How 
> > doesmod_wsgidecide which process  (and which thread for that matter) to 
> > use?
> 
> Details on process/threading in mod_wsgi available at:
> 
>   http://code.google.com/p/modwsgi/wiki/ProcessesAndThreading
> 
> When using WSGIDaemonProcess directive, if you want a single process
> it is better to allow it to default to a single process and not have
> 'processes=1'. As soon as you say 'processes=1' it will trigger
> wsgi.multiprocess to be True rather than default of False. This may
> sound counter intuitive, but is a little back door to allow
> wsgi.multiprocess to be set to True somehow when distributing an
> application across a cluster of machines where it does need to be True
> even if each machine only has a single process for that application.
> Tthat wsgi.multiprocess is True will not usually matter unless you are
> trying to use debugging middleware that require that there only be a
> single process.
> 
> As to why you were getting a different process, because you were
> actually running in embedded mode due to WSGIDaemonProcess/
> WSGIProcessGroup being in wrong context, then what process was used
> was really up to Apache and how it works. Specifically it can have
> multiple processes that can listen on the HTTP port (80). Because only
> one should be listening at a time it uses a cross process mutex lock
> to mediate access. When a process handles a request, it gives up the
> lock. If using worker MPM then another thread in same process may get
> lock, or for either worker MPM or prefork MPM, then another process
> could get it. Which actually gets it is a bit indeterminate as simply
> depends on which process the operating system lets have the lock next.
> So, there is no strict rule one can say as to who would get it next.
> 
> Graham
> Graham

Thanks!

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


Re: Sloooooowwwww WSGI restart

2009-01-30 Thread Ron Garret
In article 
<146f6796-37b5-4220-bdb1-5119cb3ac...@z6g2000pre.googlegroups.com>,
 Graham Dumpleton  wrote:

> On Jan 30, 9:53 am, Ron Garret  wrote:
> > In article <498171a5$0$3681$426a7...@news.free.fr>,
> >  Bruno Desthuilliers 
> >
> >  wrote:
> > > Ron Garret a écrit :
> > > > In article ,
> > > >  Aleksandar Radulovic  wrote:
> > > (snip)
> > > >> Secondly, why are you restarting apache after code changes? In normal
> > > >> circumstances, you shouldn't have to do that.
> >
> > > > I thought (and experiment confirms) that only the main WSGI app file
> > > > gets reloaded automatically when it changes, not the libraries.
> >
> > > Depends on how you configure mod_wsgi. Read the part about "Process
> > > Reloading Mechanism" here:
> > >http://code.google.com/p/modwsgi/wiki/ReloadingSourceCode
> >
> > I'm running Debian Etch, which means I have an older version of
> > mod_wsgi, which means I don't have the process reloading mechanism.
> 
> Back port available at:
> 
>   http://packages.debian.org/etch-backports/libapache2-mod-wsgi
> 
> Graham

Cool!  Thanks!

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


Re: Get thread pid

2009-01-30 Thread Alejandro
On Jan 30, 9:11 am, Jean-Paul Calderone  wrote:
> [clarification about threads]

Thank you for the clarification. I will reformulate my question:

pstree and also ntop (but not top) show a number for each thread, like
for instance:

$pstree -p 9197
python(9197)€ˆ€{python}(9555)
 †€{python}(9556)
 †€{python}(9557)
 †€{python}(9558)
 †€{python}(9559)
 †€{python}(9560)
 †€{python}(9561)
 †€{python}(9562)
 †€{python}(9563)
 „€{python}(9564)

Is is possible to get the number corresponding to each thread?

The reason I am interested is because one of my thread is hogging the
CPU, and want to find which one is the culprit.

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


relpath problem on windows

2009-01-30 Thread eliben
I'm having a problem with 2.6's new os.path.relpath function.

This is correct:

relpath(r'd:\abc\jho', r'd:\abc')
=> 'jho'

But this isn't:
relpath(r'd:\jho', r'd:\\')
=> '..\jho'

Neither is this:
relpath(r'd:\jho', r'd:')
=> '..\..\..\jho'

What am I missing?



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


Re: Get thread pid

2009-01-30 Thread ma
Actually, the command given "ps axH" uses H which shows threads as if they
were processes. If you check the pid of these "processes," you would find
that they are all equivalent.


On Fri, Jan 30, 2009 at 9:56 AM, Alejandro wrote:

> On Jan 30, 4:00 am, Ove Svensson  wrote:
> > Pidis a process identifier. Threads are not processes. All your threads
> > execute within the context if a single process, hence they should have
> > the samepid. Threads may have athreadid but it is not the same as thepid.
>
> According to this document (http://heather.cs.ucdavis.edu/~matloff/
> Python/PyThreads.pdf),
> at least in Linux, threads are process:
>
> "Here each thread really is a process, and for example will show up on
> Unix systems when one runs the appropriate ps process-list command,
> say ps axH. The threads manager is then the OS."
>
> If you look at my original post, pstree does show different PIDs for
> the threads.
>
> Regards,
> Alejandro.
>
>
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: Get thread pid

2009-01-30 Thread Jean-Paul Calderone

On Fri, 30 Jan 2009 06:56:10 -0800 (PST), Alejandro 
 wrote:

On Jan 30, 4:00 am, Ove Svensson  wrote:

Pidis a process identifier. Threads are not processes. All your threads
execute within the context if a single process, hence they should have
the samepid. Threads may have athreadid but it is not the same as thepid.


According to this document (http://heather.cs.ucdavis.edu/~matloff/
Python/PyThreads.pdf), at least in Linux, threads are process:

"Here each thread really is a process, and for example will show up on
Unix systems when one runs the appropriate ps process-list command,
say ps axH. The threads manager is then the OS."

If you look at my original post, pstree does show different PIDs for
the threads.


That document is quite misleading.  Threads are not processes.  They are
*similar* to processes.  They share many qualities of processes.  But they
are not processes.  The "H" option for ps is *explicitly* documented (in
recent versions of ps) as a way to make ps lie to you:

  H   Show threads as if they were processes

In times long since past, threads on Linux were even more like processes
than they are now.  Then, it might have even been defensible to say that
they were processes, but that was an implementation detail.  These days,
threads on Linux are provided by something called NPTL (whereas they used
to be provided by something called LinuxThreads).  When using NPTL, threads
do not have distinct PIDs.

So, if you want to learn more about threads on Linux, you should check out
the NPTL documentation.  It is a much more reliable authority than any
Python documentation regarding the nature of threads on Linux.

Hope this helps,

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


Why doesn't this work in Eclipse ? (Simple pexpect code that works in bash)

2009-01-30 Thread Linuxguy123
I'm trying to build a small Python app in Eclipse under Fedora 10.

I have the following code:

import os
import sys
import pexpect

child = pexpect.spawn('/bin/bash')
child.interact()

When I run it in Eclipse, I get:

Traceback (most recent call last):
  File "/home/xxx/workspace/FixPermissions/src/default/main.py", line
56, in 
child.interact()
  File "/usr/lib/python2.5/site-packages/pexpect.py", line 1489, in
interact
mode = tty.tcgetattr(self.STDIN_FILENO)
termios.error: (22, 'Invalid argument')


Yet if I run it in a bash shell, it works:

$ python
Python 2.5.2 (r252:60911, Sep 30 2008, 15:41:38)
[GCC 4.3.2 20080917 (Red Hat 4.3.2-4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> import sys
>>> import pexpect
>>> child = pexpect.spawn('/bin/bash')
>>> child.interact()
[...@localhost ~]$ ls

[...@localhost ~]$ exit
>>>
>>>

Why doesn't it run under Eclipse and how do I fix it so it does ?

Thanks

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


Re: Swapping values of two variables

2009-01-30 Thread Christian Heimes
Steven D'Aprano schrieb:
> Ints in Python are *objects*, not 32-bit quantities. An int is 12 bytes 
> (96 bits) in size; a long will use as much memory as needed. If your 
> application needs to optimize a swap of two ints, then Python is probably 
> going to be much too memory-intensive for you.

An int object consumes more than 12 bytes of memory. It depends on the
system architecture, too. It's usually 16 bytes on a 32bit system and 24
bytes on a 64bit system.
The actual size can be computed by sizeof(ptr) + sizeof(long) +
sizeof(ssize_t). The size is rounded up to the next multiple of 8 bytes
due to address alignment.

Christian

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


  1   2   >