BDFL Rossenbom, was Re: pythonOCC examples doesn't work?

2012-09-17 Thread Peter Otten
Dwight Hutto wrote:

>>> Alan Gauld quotes, "Putting on my moderator's hat", sometimes.
>>>
 is as you describe, a monarchy whose head but seldom exercises power;
>>>
>>>
>>> I think it's Rossenbom(or whoever the creator of the interpreter
>>> written in C is), "who says benevolent dictator for life"
>>>
>> [snip]
>> You don't know the name of the BDFL? I'm appalled! :-)
>>
> I know plenty of BDFL's, including that one, but the mods are not the
> creator.

Cue

I kno' plenty o' nuttin',
And nuttin's plenty fo' me...

to the tune of Josh Kirschwein (or whoever wrote that Ernie and Tess opera)

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


Re: Moving folders with content

2012-09-17 Thread Laszlo Nagy

On 2012-09-15 06:36, jyoun...@kc.rr.com wrote:

Hello,

I am working in both OS X Snow Leopard and Lion (10.6.8 and 10.7.4).
I'm simply wanting to move folders (with their content) from various
servers to the hard drive and then back to different directories on the
servers.

I want to be careful not to remove any metadata or resource forks from
the files in the directories.  I did a bit of researching on shutil, and
looks like it is similar to using "cp -p" and copystat(), which I believe
will keep the resource fork, etc.

Here's the code I came up with.  I'm curious if anyone finds fault with
this, or if there's a better way to do this?
Not in this particular case, because you know that these directories are 
on different computers. But instead of rmtree+copytree, I would rather 
use shutil.move() because it will use os.rename() when the source and 
the destination are on the same filesystem. Much much faster.

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


Re: Batching HTTP requests with httplib (Python 2.7)

2012-09-17 Thread Xavier Combelle

instead of

Le 14/09/2012 12:56, Dwight Hutto a écrit :

service_num_list = [num for num in range(0,5)]
for service_num in service_num_list:
eval("web_service_call%i(%i)" % (service_num,service_num))



service_num_list = [num for num in range(0,5)]
for service_num in service_num_list:
locals()["web_service_call%i" % (service_num,)](service_num)

would be safer eval is really bad

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


Re: Obnoxious postings from Google Groups (was: datetime issue)

2012-09-17 Thread Gene Heskett
On Sunday 16 September 2012 12:29:39 pandora.ko...@gmail.com did opine:

> > > http://mail.python.org/mailman/listinfo/python-list
> > 
> > email client to python-list@python.org
> 
> wait a minute! i must use my ISP's news server and then post o
> comp.lang.python no?

No.

> What is python-list@python.org how can i post there?

Install thunderbird.  Its a real email agent, even on a windows box.

But first you must subscribe as I discussed in a previous msg.

Cheers, Gene
-- 
"There are four boxes to be used in defense of liberty:
 soap, ballot, jury, and ammo. Please use in that order."
-Ed Howdershelt (Author)
My web page:  is up!
Q:  How was Thomas J. Watson buried?
A:  9 edge down.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python presentations

2012-09-17 Thread Alexander Blinne
On 16.09.2012 19:35, Steven D'Aprano wrote:
> On Sun, 16 Sep 2012 18:13:36 +0200, Alexander Blinne wrote:
>> def powerlist2(x,n):
>> if n==1:
>> return [1]
>> p = powerlist3(x,n-1)
>> p.append(p[-1]*x)
>> return p
> 
> Is that a typo? I think you mean to make a recursive call to powerlist2, 
> not a non-recursive call to powerlist3.

Yes, it is a typo. I originally tested 2 more versions, but tried to
change the numbering before posting. Bad idea :)
-- 
http://mail.python.org/mailman/listinfo/python-list


reportlab and python 3

2012-09-17 Thread Laszlo Nagy

Reportlab is on the wall of shame. http://python3wos.appspot.com/

Is there other ways to create PDF files from python 3? There is pyPdf. I 
haven't tried it yet, but it seem that it is a low level library. It 
does not handle "flowables" that are automatically split across pages. 
It does not handle "table headers" that are repeated automatically on 
the top of every page (when the table does not fit on a page). I need a 
higher level API, with features compareable to reportlab. Is there such 
thing?


Thanks,

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


Re: Python garbage collector/memory manager behaving strangely

2012-09-17 Thread Dave Angel
On 09/16/2012 11:25 PM, alex23 wrote:
> On Sep 17, 12:32 pm, "Jadhav, Alok" 
> wrote:
>> - As you have seen, the line separator is not '\n' but its '|\n'.
>> Sometimes the data itself has '\n' characters in the middle of the line
>> and only way to find true end of the line is that previous character
>> should be a bar '|'. I was not able specify end of line using
>> readlines() function, but I could do it using split() function.
>> (One hack would be to readlines and combine them until I find '|\n'. is
>> there a cleaner way to do this?)
> You can use a generator to take care of your readlines requirements:
>
> def readlines(f):
> lines = []
> while "f is not empty":
> line = f.readline()
> if not line: break
> if len(line) > 2 and line[-2:] == '|\n':
> lines.append(line)
> yield ''.join(lines)
> lines = []
> else:
> lines.append(line)

There's a few changes I'd make:
I'd change the name to something else, so as not to shadow the built-in,
and to make it clear in caller's code that it's not the built-in one.
I'd replace that compound if statement with
  if line.endswith("|\n":
I'd add a comment saying that partial lines at the end of file are ignored.

>> - Reading whole file at once and processing line by line was must
>> faster. Though speed is not of very important issue here but I think the
>> tie it took to parse complete file was reduced to one third of original
>> time.

You don't say what it was faster than.  Chances are you went to the
other extreme, of doing a read() of 1 byte at a time.  Using Alex's
approach of a generator which in turn uses the readline() generator.

> With the readlines generator above, it'll read lines from the file
> until it has a complete "line" by your requirement, at which point
> it'll yield it. If you don't need the entire file in memory for the
> end result, you'll be able to process each "line" one at a time and
> perform whatever you need against it before asking for the next.
>
> with open(u'infile.txt','r') as infile:
> for line in readlines(infile):
> ...
>
> Generators are a very efficient way of processing large amounts of
> data. You can chain them together very easily:
>
> real_lines = readlines(infile)
> marker_lines = (l for l in real_lines if l.startswith('#'))
> every_second_marker = (l for i,l in enumerate(marker_lines) if (i
> +1) % 2 == 0)
> map(some_function, every_second_marker)
>
> The real_lines generator returns your definition of a line. The
> marker_lines generator filters out everything that doesn't start with
> #, while every_second_marker returns only half of those. (Yes, these
> could all be written as a single generator, but this is very useful
> for more complex pipelines).
>
> The big advantage of this approach is that nothing is read from the
> file into memory until map is called, and given the way they're
> chained together, only one of your lines should be in memory at any
> given time.


-- 

DaveA

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


RE: Python garbage collector/memory manager behaving strangely

2012-09-17 Thread Jadhav, Alok
Thanks for your valuable inputs. This is very helpful. 


-Original Message-
From: Python-list
[mailto:python-list-bounces+alok.jadhav=credit-suisse@python.org] On
Behalf Of Dave Angel
Sent: Monday, September 17, 2012 6:47 PM
To: alex23
Cc: python-list@python.org
Subject: Re: Python garbage collector/memory manager behaving strangely

On 09/16/2012 11:25 PM, alex23 wrote:
> On Sep 17, 12:32 pm, "Jadhav, Alok" 
> wrote:
>> - As you have seen, the line separator is not '\n' but its '|\n'.
>> Sometimes the data itself has '\n' characters in the middle of the
line
>> and only way to find true end of the line is that previous character
>> should be a bar '|'. I was not able specify end of line using
>> readlines() function, but I could do it using split() function.
>> (One hack would be to readlines and combine them until I find '|\n'.
is
>> there a cleaner way to do this?)
> You can use a generator to take care of your readlines requirements:
>
> def readlines(f):
> lines = []
> while "f is not empty":
> line = f.readline()
> if not line: break
> if len(line) > 2 and line[-2:] == '|\n':
> lines.append(line)
> yield ''.join(lines)
> lines = []
> else:
> lines.append(line)

There's a few changes I'd make:
I'd change the name to something else, so as not to shadow the built-in,
and to make it clear in caller's code that it's not the built-in one.
I'd replace that compound if statement with
  if line.endswith("|\n":
I'd add a comment saying that partial lines at the end of file are
ignored.

>> - Reading whole file at once and processing line by line was must
>> faster. Though speed is not of very important issue here but I think
the
>> tie it took to parse complete file was reduced to one third of
original
>> time.

You don't say what it was faster than.  Chances are you went to the
other extreme, of doing a read() of 1 byte at a time.  Using Alex's
approach of a generator which in turn uses the readline() generator.

> With the readlines generator above, it'll read lines from the file
> until it has a complete "line" by your requirement, at which point
> it'll yield it. If you don't need the entire file in memory for the
> end result, you'll be able to process each "line" one at a time and
> perform whatever you need against it before asking for the next.
>
> with open(u'infile.txt','r') as infile:
> for line in readlines(infile):
> ...
>
> Generators are a very efficient way of processing large amounts of
> data. You can chain them together very easily:
>
> real_lines = readlines(infile)
> marker_lines = (l for l in real_lines if l.startswith('#'))
> every_second_marker = (l for i,l in enumerate(marker_lines) if (i
> +1) % 2 == 0)
> map(some_function, every_second_marker)
>
> The real_lines generator returns your definition of a line. The
> marker_lines generator filters out everything that doesn't start with
> #, while every_second_marker returns only half of those. (Yes, these
> could all be written as a single generator, but this is very useful
> for more complex pipelines).
>
> The big advantage of this approach is that nothing is read from the
> file into memory until map is called, and given the way they're
> chained together, only one of your lines should be in memory at any
> given time.


-- 

DaveA

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

=== 
Please access the attached hyperlink for an important electronic communications 
disclaimer: 
http://www.credit-suisse.com/legal/en/disclaimer_email_ib.html 
=== 

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


Re: Python garbage collector/memory manager behaving strangely

2012-09-17 Thread Steven D'Aprano
On Mon, 17 Sep 2012 06:46:55 -0400, Dave Angel wrote:

> On 09/16/2012 11:25 PM, alex23 wrote:
>> def readlines(f):
>> lines = []
>> while "f is not empty":
>> line = f.readline()
>> if not line: break
>> if len(line) > 2 and line[-2:] == '|\n':
>> lines.append(line)
>> yield ''.join(lines)
>> lines = []
>> else:
>> lines.append(line)
> 
> There's a few changes I'd make:
> I'd change the name to something else, so as not to shadow the built-in,

Which built-in are you referring to? There is no readlines built-in.

py> readlines
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'readlines' is not defined


There is a file.readlines method, but that lives in a different namespace 
to the function readlines so there should be no confusion. At least not 
for a moderately experienced programmer, beginners can be confused by the 
littlest things sometimes.


> and to make it clear in caller's code that it's not the built-in one.
> I'd replace that compound if statement with
>   if line.endswith("|\n":
> I'd add a comment saying that partial lines at the end of file are
> ignored.

Or fix the generator so that it doesn't ignore partial lines, or raises 
an exception, whichever is more appropriate.



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


Re: Python garbage collector/memory manager behaving strangely

2012-09-17 Thread Dave Angel
On 09/17/2012 07:47 AM, Steven D'Aprano wrote:
> On Mon, 17 Sep 2012 06:46:55 -0400, Dave Angel wrote:
>
>> On 09/16/2012 11:25 PM, alex23 wrote:
>>> def readlines(f):
>>> lines = []
>>> while "f is not empty":
>>> line = f.readline()
>>> if not line: break
>>> if len(line) > 2 and line[-2:] == '|\n':
>>> lines.append(line)
>>> yield ''.join(lines)
>>> lines = []
>>> else:
>>> lines.append(line)
>> There's a few changes I'd make:
>> I'd change the name to something else, so as not to shadow the built-in,
> Which built-in are you referring to? There is no readlines built-in.
>
> py> readlines
> Traceback (most recent call last):
>   File "", line 1, in 
> NameError: name 'readlines' is not defined
>
>
> There is a file.readlines method, but that lives in a different namespace 
> to the function readlines so there should be no confusion. At least not 
> for a moderately experienced programmer, beginners can be confused by the 
> littlest things sometimes.

You're right of course, and that's not restricted to beginners.  I've
been at this for over 40 years, and I make that kind of mistake once in
a while.  Fortunately, when I make such a mistake on this forum, you
usually pop in to keep me honest.  When I make it in code, I either get
a runtime error, or no harm is done.

>
>> and to make it clear in caller's code that it's not the built-in one.
>> I'd replace that compound if statement with
>>   if line.endswith("|\n":
>> I'd add a comment saying that partial lines at the end of file are
>> ignored.
> Or fix the generator so that it doesn't ignore partial lines, or raises 
> an exception, whichever is more appropriate.
>
>
>


-- 

DaveA

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


gc.get_objects()

2012-09-17 Thread Matteo Boscolo

Hi All,

I'm facing some trouble with a win32com application, it seems, that some 
com object (win32com) are still in the gc.get_objetc() list, even if I 
set to non the objetc and I'm out of the scope of that objects.


What I'm try to do is to remove this object  from the list. but I do 
know how..


the .__del__() method dose not work on this object...

there is someone that can give me some help on this ?

Regards,
Matteo

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


gedit : gdp : python word completion

2012-09-17 Thread Mayuresh Kathe

has anyone got the above working?
--
http://mail.python.org/mailman/listinfo/python-list


Re: gc.get_objects()

2012-09-17 Thread Steven D'Aprano
On Mon, 17 Sep 2012 14:42:56 +0200, Matteo Boscolo wrote:

> Hi All,
> 
> I'm facing some trouble with a win32com application, it seems, that some
> com object (win32com) are still in the gc.get_objetc() list, even if I
> set to non the objetc and I'm out of the scope of that objects.

You can't set an object to None. An object is itself. It is *always* 
itself, you can't tell Python to turn it into None.

What you can do is re-bind a *name* from an object to None.

Suppose you say:

x = Spam()

then there is a binding between name "x" and the object Spam(), which I 
will call "spam" from now on. When you then later say:

x = None

this does *not* convert spam into None, what it does is cuts the binding 
between name "x" and spam, and binds the name "x" to None. The object 
spam still exists.

If there are no other references to spam, then the garbage collector 
automatically destroys the spam object. But if there are still references 
to the spam object, then it will remain alive, and the gc will keep 
tracking it.

References can include:

* name bindings: x = spam

* list items: mylist.append(spam)

* dict keys and values: mydict[spam] = 42; mydict["key"] = spam

* attributes: myobject.attr = spam

* default values to function parameters: def foo(a, b=spam): ...

and probably others.


> What I'm try to do is to remove this object  from the list. but I do
> know how..


If you have a com object being tracked by the garbage collector, that 
means that it is still in use, somewhere in your program. You can't just 
tell the gc to stop tracking it. You need to find where you still have a 
reference to the object.


> the .__del__() method dose not work on this object...

The __del__ method does not delete an object. Remember, objects are only 
deleted when there are no references to it. Otherwise you could have some 
code that tries to use a deleted object, and you would get a system crash 
or BSOD. The __del__ method is called only when the object is *just 
about* to be deleted.

In general, you should avoid using __del__ methods. They interfere with 
the garbage collector's ability to resolve cycles. The problem is, what 
happens if an object contains a link to itself?

x = []
x.append(x)

Such cycles could be very deep:

a = []; b = []; c = []; d = []; ... y = []; z = []
a.append(b)
b.append(c)
c.append(d)
...
y.append(z)
z.append(a) ### a cycle appears ###

Now you have a cycle of 26 objects, each of which indirectly refers to 
itself.

Normally, Python's garbage collector can recognise such a cycle and 
safely break it, which then allows all of the objects to be deleted. But 
if you add a __del__ method to *even one* object, Python can no longer 
safely break the cycle, and so the objects will remain alive even when 
you can no longer reach them from your code.

So, in general, avoid the __del__ method unless you absolutely need it.


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


Re: Decorators not worth the effort

2012-09-17 Thread Jean-Michel Pichavant


- Original Message -
> Jean-Michel Pichavant wrote:
[snip]
> One minor note, the style of decorator you are using loses the
> docstring
> (at least) of the original function. I would add the
> @functools.wraps(func)
> decorator inside your decorator.

Is there a way to not loose the function signature as well ?

help (t.api.spuAgc)
> spuAgc(self, iterations, backoffTarget, step) method of ...



But once decorated with this:

def stdApi(func):
@functools.wraps(func)
def inner(self, *args, **kwargs):
rsp = func(self, *args, **kwargs)
result = TncCmnResult()
result.returnCode = self._getReturnCode(rsp)
return result
return inner

help (t.api.spuAgc)
> t.api.spuAgc(self, *args, **kwargs) method of 

Quite annoying :-/

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


Re: Obnoxious postings from Google Groups (was: datetime issue)

2012-09-17 Thread Jamie Paul Griffin
[ Joel Goldstick wrote on Sun 16.Sep'12 at 11:57:56 -0400 ]
 
> email client to python-list@python.org

If using Windows I would certainly use Thunderbird or even slrn news reader - I 
believe there is a version for Windows. Or you could install Interix subsystem 
which provides UNIX tools for Windows 7 Ultimate or Professional. You'd then 
have some more choice of MUA client or newsreader client in that environment. 
Cygwin is another alternative. 

UNIX systems just use whatever email client you like and subscribe to the list 
as explained several times by others. Fortunately for me I've got procmail 
deleting double posts because they are annoying. 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: gc.get_objects()

2012-09-17 Thread Chris Angelico
On Tue, Sep 18, 2012 at 12:16 AM, Steven D'Aprano
 wrote:
> The __del__ method does not delete an object. Remember, objects are only
> deleted when there are no references to it. Otherwise you could have some
> code that tries to use a deleted object, and you would get a system crash
> or BSOD.

There is a conceptually viable alternative: destroy an object
immediately and force all references to it to become some sentinel
value (eg None). Python currently doesn't have this, but it would be
rather convenient at times. Could be part of a construct like 'with'
to say "make this, use it, and then dispose of it".

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


Re: gc.get_objects()

2012-09-17 Thread Matteo Boscolo

from my gc.get_object()
I extract the sub system of the object that I would like to delete:

this is the object:
Class name 
win32com.gen_py.F4503A16-F637-11D2-BD55-00500400405Bx0x1x0.ITDProperty.ITDProperty

that is traked and the reference are:
get_referents     
     


RefCount 5
   (0x026ACB58>,)

RefCount 5
   '__int__': , 
'__module__': 'win32com.gen_py.F45

RefCount 8
   ITDProperty
RefCount 9
   
RefCount 9
   
get_referrers     
     


RefCount 15
   'python_version': 34014192, 'defaultUnnamedArg': 

RefCount 6
   win32com.gen_py.F4503A16-F637-11D2-BD55-00500400405Bx0x1x0.ITDProperty.I

RefCount 4
   (u'ItemsListCreator', u'trick', u'pVal'), (3, 49, 
'0', None), (16393, 10, None,

RefCount 4
   
RefCount 7
   
RefCount 5
  '{39AAEA35-F71F-11D2-BD59-00500400405B}': win32com.gen_py.F4503A16-F637-


how can I understand how to clean up this situation or were are the 
references that I need to delete ?


From the cad non python script I call an in process python com object, 
and before coming back to the cad application I need to clean up all com 
reference, because if I do not do that I corrupt the cad application .


so I urgently need to clean up all reference before coming back to the 
cad application.


any idea?

regards,
Matteo


Il 17/09/2012 18:09, Chris Angelico ha scritto:

On Tue, Sep 18, 2012 at 12:16 AM, Steven D'Aprano
 wrote:

The __del__ method does not delete an object. Remember, objects are only
deleted when there are no references to it. Otherwise you could have some
code that tries to use a deleted object, and you would get a system crash
or BSOD.

There is a conceptually viable alternative: destroy an object
immediately and force all references to it to become some sentinel
value (eg None). Python currently doesn't have this, but it would be
rather convenient at times. Could be part of a construct like 'with'
to say "make this, use it, and then dispose of it".

ChrisA


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


Re: gc.get_objects()

2012-09-17 Thread Oscar Benjamin
On 2012-09-17, Matteo Boscolo  wrote:
> from my gc.get_object()
> I extract the sub system of the object that I would like to delete:
>
> this is the object:
> Class name 
> win32com.gen_py.F4503A16-F637-11D2-BD55-00500400405Bx0x1x0.ITDProperty.ITDProperty
> that is traked and the reference are:
> get_referents     
>      
> 
> RefCount 5
>   ( 0x026ACB58>,)
> RefCount 5
>   '__int__': , 
> '__module__': 'win32com.gen_py.F45
> RefCount 8
>   ITDProperty
> RefCount 9
>   
> RefCount 9
>   
> get_referrers     
>      
> 
> RefCount 15
>   'python_version': 34014192, 'defaultUnnamedArg': 
> RefCount 6
>    win32com.gen_py.F4503A16-F637-11D2-BD55-00500400405Bx0x1x0.ITDProperty.I
> RefCount 4
>   (u'ItemsListCreator', u'trick', u'pVal'), (3, 49, 
> '0', None), (16393, 10, None,
> RefCount 4
>   
> RefCount 7
>   
> RefCount 5
>  '{39AAEA35-F71F-11D2-BD59-00500400405B}':  win32com.gen_py.F4503A16-F637-
>
> how can I understand how to clean up this situation or were are the 
> references that I need to delete ?
>
>  From the cad non python script I call an in process python com object, 
> and before coming back to the cad application I need to clean up all com 
> reference, because if I do not do that I corrupt the cad application .
>
> so I urgently need to clean up all reference before coming back to the 
> cad application.
>
> any idea?
>

http://mg.pov.lt/objgraph/
http://mg.pov.lt/blog/hunting-python-memleaks.html

I have previously used the code from one of the links above to hunt down a
reference leak. It gives a graphical view of the alive references which helps
to locate the source of the ref leak.

Oscar

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


Hiring Python Developer @ CA, USA

2012-09-17 Thread nithinmoha

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


Hiring Python Developer @ CA, USA

2012-09-17 Thread nithinmoha
Job Title: Python Django Consultant
Location: Scotts Valley, CA
Duration: Long Term / Full Time

Must:
•   Python - Must be an export in this language.  They currently use Python 
2.7
•   Proficient in Unix and source code versioning - They run RedHat and 
Fedora on the servers and development environments and use Subversion (SVN) for 
source code control.
•   Proficient in  Django (Python web framework)

Good to have but not necessary:
•   PostgreSQL knowledge
•   RESTful API development (Tastypie) within Django


Please send your updated resume to nithin @ gavsin.com

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


Re: Comparing strings from the back?

2012-09-17 Thread Ethan Furman

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


Re: using text file to get ip address from hostname

2012-09-17 Thread Thomas Rachel

Am 15.09.2012 18:20 schrieb Dan Katorza:


hello again friends,
thanks for everyone help on this.
i guess i figured it out in two ways.
the second one i prefer the most.

i will appreciate if someone can give me some tips.
thanks again

so...
-
First
-
#!/usr/bin/env python
#Get the IP Address


print("hello, please enter file name here>"),
import socket
for line in open(raw_input()):
 hostname = line.strip()
 print("IP address for {0} is 
{1}.".format(hostname,socket.gethostbyname(hostname)))


second

#!/usr/bin/env python
#Get the IP Address

import os

print("Hello, please enter file name here>"),
FILENAME = raw_input()
if os.path.isfile(FILENAME):
 print("\nFile Exist!")
 print("\nGetting ip from host name")
 print("\n")
 import socket
 for line in open (FILENAME):
 hostname = line.strip()
 print("IP address for {0} is 
{1}.".format(hostname,socket.gethostbyname(hostname)))
 else:
 print ("\nFinished the operation")
else:
 print ("\nFIle is missing or is not reasable"),
~


Comparing these, the first one wins if you catch and process exceptions. 
It is easier to ask for forgiveness than to get permission (EAFP, 
http://en.wikipedia.org/wiki/EAFP).


Bit I wonder that no one has mentionned that 
socket.gethostbyname(hostname) is quite old-age because it only returns 
IPv4 addresses (resp. only one of them).


OTOH, socket.getaddrinfo(hostname, 0, 0, socket.SOCK_STREAM) gives you a 
list of parameter tuples for connecting.


So which way you go above, you should change the respective lines to

for line in ...:
hostname = line.strip()
for target in socket.getaddrinfo(hostname, 0, socket.AF_UNSPEC,
socket.SOCK_STREAM):
print("IP address for {0} is {1}.".format(hostname,
target[4][0]))


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


how to use property?

2012-09-17 Thread Fernando Jiménez
Hi guys!

I'm noob in python and I would know how to correctly use the property. I
have read some things about it but I do not quite understand.

I found this:

class C(object):
def __init__(self):
self._x = None

@property
def x(self):
"""I'm the 'x' property."""
return self._x

@x.setter
def x(self, value):
self._x = value

@x.deleter
def x(self):
del self._x

But I think it's a bad habit to use _ to change the visibility of the
attributes as in JAVA.

How to correctly use the property?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to use property?

2012-09-17 Thread Dave Angel
On 09/17/2012 05:55 PM, Fernando Jiménez wrote:
> Hi guys!
>
> I'm noob in python and I would know how to correctly use the property. I
> have read some things about it but I do not quite understand.
>
> I found this:
>
> class C(object):
> def __init__(self):
> self._x = None
>
> @property
> def x(self):
> """I'm the 'x' property."""
> return self._x
>
> @x.setter
> def x(self, value):
> self._x = value
>
> @x.deleter
> def x(self):
> del self._x
>
> But I think it's a bad habit to use _ to change the visibility of the
> attributes as in JAVA.
>
> How to correctly use the property?
>
>
That's already correct.  But if you don't like _x, then use  
_rumplestiltskin.



-- 

DaveA

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


Re: how to use property?

2012-09-17 Thread Chris Angelico
On Tue, Sep 18, 2012 at 7:55 AM, Fernando Jiménez  wrote:
> Hi guys!
>
> I'm noob in python and I would know how to correctly use the property. I
> have read some things about it but I do not quite understand.
>
> But I think it's a bad habit to use _ to change the visibility of the
> attributes as in JAVA.
>
> How to correctly use the property?

The single leading underscore is nothing to do with visibility; it's a
courteous request that external referents not touch something. In a
"consenting adults" model, that's usually sufficient.

For the most part, in fact, you don't need @property at all. Just make
an object's members public and save yourself the trouble! Unlike the
recommendation in C++ and Java, Python doesn't ask you to hide things
and write code to make them available. Instead of starting with
getters and setters, just start with a flat property, and move to
getters/setters only when you find you need them.

The example you posted is adding nothing to the work flow, but it's a
good structure that you can tinker with. For instance, if you need to
log all changes for debugging purposes, @property will make that easy.
But for the bulk of attributes, it's complete overkill.

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


splitting numpy array unevenly

2012-09-17 Thread Wanderer
I need to divide a 512x512 image array with the first horizontal and vertical 
division 49 pixels in. Then every 59 pixels in after that. hsplit and vsplit 
want to start at the edges and create a bunch of same size arrays. Is there a 
command to chop off different sized arrays?

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


Re: Using Py_AddPendingCall

2012-09-17 Thread Antoine Pitrou
css322  gmail.com> writes:
> 
> (1) A worker thread calls Py_AddPendingCall and assigns a handler function.
> (2) When the Python interpreter runs, it calls the handler function whenever
it yields control to another thread

Not exactly. As the documentation says: "If successful, func will be called 
with the argument arg *at the earliest convenience*."
This is a deliberately vague wording to stress that the function will not be
called as early as you think. It *should* be called in a timely manner, but not
necessarily as soon as the thread switch happens.

Which begs the question:

> In this example, worker_thread is invoked in C as a pthread worker thread. 
> This
> loops infinitely, but the pending call handler is never invoked.

What is your main Python thread doing? Is it running Python code (*)? Or do you
have a main Python thread at all? The "main Python thread" is the one from which
Py_Initialize() was called.

(*) for example, running one of the following functions:
http://docs.python.org/dev/c-api/veryhigh.html

Regards

Antoine.


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


Re: Comparing strings from the back?

2012-09-17 Thread Neil Hodgson

Ethan Furman:

*plonk*


   I can't work out who you are plonking. While more than one of the 
posters on this thread seem worthy of a good plonk, by not including 
sufficient context, you've left me feeling puzzled. Is there a guideline 
for this in basic netiquette?


   Neil

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


Re: how to use property?

2012-09-17 Thread Terry Reedy

On 9/17/2012 6:12 PM, Chris Angelico wrote:

On Tue, Sep 18, 2012 at 7:55 AM, Fernando Jiménez  wrote:

Hi guys!

I'm noob in python and I would know how to correctly use the property. I
have read some things about it but I do not quite understand.

But I think it's a bad habit to use _ to change the visibility of the
attributes as in JAVA.

How to correctly use the property?


The single leading underscore is nothing to do with visibility; it's a
courteous request that external referents not touch something. In a
"consenting adults" model, that's usually sufficient.

For the most part, in fact, you don't need @property at all. Just make
an object's members public and save yourself the trouble! Unlike the
recommendation in C++ and Java, Python doesn't ask you to hide things
and write code to make them available. Instead of starting with
getters and setters, just start with a flat property, and move to
getters/setters only when you find you need them.


More examples:

A class has a data attribute that really is a simple attribute, no 
property. You define a subclass that needs a calculation for the 
attribute. So you use property in the subclass.


A class has an attribute that is a constant that must be computed. You 
do not want to compute is unless and until needed.


def get_x(self):
  try:
return self._x
  except AttributeError:
self._x = calculate_x()
return self._

For a read-only attribute, don't provide a setter. If you do not like 
"AttributeError: can't set attribute", provide one with a customized error.


But I think most of the data attributes in stdlib classes are straight 
attributes.


--
Terry Jan Reedy


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


Re: splitting numpy array unevenly

2012-09-17 Thread Martin De Kauwe
On Tuesday, September 18, 2012 8:31:09 AM UTC+10, Wanderer wrote:
> I need to divide a 512x512 image array with the first horizontal and vertical 
> division 49 pixels in. Then every 59 pixels in after that. hsplit and vsplit 
> want to start at the edges and create a bunch of same size arrays. Is there a 
> command to chop off different sized arrays?
> 
> 
> 
> Thanks

I don't know that I follow completely, but can't you just slice what you are 
after?

x = np.random.rand(512*512).reshape(512,512)
xx = x[0,:49]
And put the rest of the slices in a loop...?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to use property?

2012-09-17 Thread Dave Angel
On 09/17/2012 07:34 PM, Terry Reedy wrote:
> On 9/17/2012 6:12 PM, Chris Angelico wrote:
>> On Tue, Sep 18, 2012 at 7:55 AM, Fernando Jiménez
>>  wrote:
>>> Hi guys!
>>>
>>> I'm noob in python and I would know how to correctly use the
>>> property. I
>>> have read some things about it but I do not quite understand.
>>>
>>> But I think it's a bad habit to use _ to change the visibility of the
>>> attributes as in JAVA.
>>>
>>> How to correctly use the property?
>>
> 

> More examples:
>
> A class has a data attribute that really is a simple attribute, no
> property. You define a subclass that needs a calculation for the
> attribute. So you use property in the subclass.
>
> A class has an attribute that is a constant that must be computed. You
> do not want to compute is unless and until needed.
>
> def get_x(self):
>   try:
> return self._x
>   except AttributeError:
> self._x = calculate_x()
> return self._
>
> For a read-only attribute, don't provide a setter. If you do not like
> "AttributeError: can't set attribute", provide one with a customized
> error.
>
> But I think most of the data attributes in stdlib classes are straight
> attributes.
>

An important difference from every other language I've used:  The user
of the attribute does not need to change his code when you decide it
needs reimplementation as a property.

In C++ and java, for example, people will define getter and setter
methods just so they don't have to change them later.  Just "in case"
it's needed later.


-- 

DaveA

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


Re: splitting numpy array unevenly

2012-09-17 Thread Joshua Landau
On 17 September 2012 23:31, Wanderer  wrote:

> I need to divide a 512x512 image array with the first horizontal and
> vertical division 49 pixels in. Then every 59 pixels in after that. hsplit
> and vsplit want to start at the edges and create a bunch of same size
> arrays. Is there a command to chop off different sized arrays?
>

hsplits = [49]
sum_hsplits = 49
while sum_hsplits < 512:

hsplits.append(sum_hsplits)
sum_hsplits += 59


np.split(np.random.rand(512), hsplits)

If I understand correctly, this is a one-dimensional version of what you
want. Extending this to the second dimension should be quite easy.
However, I am not sure if I do understand what you want. Could
you elaborate on what you are trying to achieve?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to use property?

2012-09-17 Thread MRAB

On 2012-09-18 00:46, Dave Angel wrote:

On 09/17/2012 07:34 PM, Terry Reedy wrote:

On 9/17/2012 6:12 PM, Chris Angelico wrote:

On Tue, Sep 18, 2012 at 7:55 AM, Fernando Jiménez
 wrote:

Hi guys!

I'm noob in python and I would know how to correctly use the
property. I
have read some things about it but I do not quite understand.

But I think it's a bad habit to use _ to change the visibility of the
attributes as in JAVA.

How to correctly use the property?







More examples:

A class has a data attribute that really is a simple attribute, no
property. You define a subclass that needs a calculation for the
attribute. So you use property in the subclass.

A class has an attribute that is a constant that must be computed. You
do not want to compute is unless and until needed.

def get_x(self):
  try:
return self._x
  except AttributeError:
self._x = calculate_x()
return self._

For a read-only attribute, don't provide a setter. If you do not like
"AttributeError: can't set attribute", provide one with a customized
error.

But I think most of the data attributes in stdlib classes are straight
attributes.



An important difference from every other language I've used:  The user
of the attribute does not need to change his code when you decide it
needs reimplementation as a property.

In C++ and java, for example, people will define getter and setter
methods just so they don't have to change them later.  Just "in case"
it's needed later.


C# and Delphi (IIRC) also support properties.
--
http://mail.python.org/mailman/listinfo/python-list


Re: how to use property?

2012-09-17 Thread Ian Kelly
On Mon, Sep 17, 2012 at 6:26 PM, MRAB  wrote:
> On 2012-09-18 00:46, Dave Angel wrote:
>> An important difference from every other language I've used:  The user
>> of the attribute does not need to change his code when you decide it
>> needs reimplementation as a property.
>>
>> In C++ and java, for example, people will define getter and setter
>> methods just so they don't have to change them later.  Just "in case"
>> it's needed later.
>>
> C# and Delphi (IIRC) also support properties.

I don't know about Delphi, but in .NET changing between a public field
and a property breaks ABI.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: reportlab and python 3

2012-09-17 Thread Joel Rivera

On 2012-09-17 03:47, Laszlo Nagy wrote:

Reportlab is on the wall of shame. http://python3wos.appspot.com/

Is there other ways to create PDF files from python 3? There is
pyPdf. I haven't tried it yet, but it seem that it is a low level
library. It does not handle "flowables" that are automatically split
across pages. It does not handle "table headers" that are repeated
automatically on the top of every page (when the table does not fit 
on

a page). I need a higher level API, with features compareable to
reportlab. Is there such thing?

Thanks,

   Laszlo


On 2012-09-17 03:47, Laszlo Nagy wrote:

Reportlab is on the wall of shame. http://python3wos.appspot.com/

Is there other ways to create PDF files from python 3? There is
pyPdf. I haven't tried it yet, but it seem that it is a low level
library. It does not handle "flowables" that are automatically split
across pages. It does not handle "table headers" that are repeated
automatically on the top of every page (when the table does not fit 
on

a page). I need a higher level API, with features compareable to
reportlab. Is there such thing?

Thanks,

   Laszlo


I'm afraid that, no, and this is my story of suffering:

I been looking for something like that since the past month, first I 
try to port a library pypdflib[1]
with no success, cairo is not well supported yet and the different 
forks of PIL aren't working nicely

with 3.2 also carries a lot of dependencies, so I desist on that.

Then I try this pyfpdf [2] to improve another port, but.. I end up 
spending a LOT of time reading the
PDF and PNG SPEC and trying to unphpfy the code  (In fact I couldn't 
make it work png images with alpha mask),
so I start to get desperate and I took another approach, wrap another 
command.


First, I try with xhtml2pdf [3], but It does not have a great support 
for the css rule "@page"
which is pretty indispensable for me and in general wasn't very nice to 
generate precise pdf's,
the commercial alternative "prince" have some fame of being good but 
I'm not willing to spend
$3,800 on the license [4], also exists a few other commercial 
alternatives like pdftron [5]

which support python3.

And then after all of that my current effort is wrapping FOP [6], but 
instead of using XSL I reuse
mako to generate the fo file, I leverage the pain of writing XML by 
hand with mako which provides
the fo: namespace and some other tricks, at the time it seems robust 
and feature rich because of
the nature of xsl-fo, but who now's I'm just starting with this I'll be 
working in this approach

the following weeks.

And if by any mean you found a better alternative please let me know 
and if you are so kind

put the answer in this [7] stackoverflow question.

Cheers.

[1]: https://github.com/cyraxjoe/pypdflib
[2]: https://bitbucket.org/cyraxjoe/py3fpdf
[3]: https://github.com/chrisglass/xhtml2pdf
[4]: http://www.princexml.com/purchase
[5]: http://www.pdftron.com/
[6]: http://xmlgraphics.apache.org/fop/
[7]: http://stackoverflow.com/q/12021216/298371
--
Rivera²
--
http://mail.python.org/mailman/listinfo/python-list


'indent'ing Python in windows bat

2012-09-17 Thread David Smith

Hello, I'm essentially a newbie in Python.
My problem in searching the archives is not knowing what words to use to 
ask.


I'm converting windows bat files little by little to Python 3 as I find 
time and learn Python.

The most efficient method for some lines is to call Python like:
python -c "import sys; sys.exit(3)"

How do I "indent" if I have something like:
if (sR=='Cope'): sys.exit(1) elif (sR=='Perform') sys.exit(2) else 
sys.exit(3)


My sole result in many attempts is "Syntax Error."

Thank you for any help.

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


Re: 'indent'ing Python in windows bat

2012-09-17 Thread Dave Angel
On 09/17/2012 09:08 PM, David Smith wrote:
> Hello, I'm essentially a newbie in Python.
> My problem in searching the archives is not knowing what words to use
> to ask.
>
> I'm converting windows bat files little by little to Python 3 as I
> find time and learn Python.
> The most efficient method for some lines is to call Python like:
> python -c "import sys; sys.exit(3)"
>
> How do I "indent" if I have something like:
> if (sR=='Cope'): sys.exit(1) elif (sR=='Perform') sys.exit(2) else
> sys.exit(3)
>
> My sole result in many attempts is "Syntax Error."
>
> Thank you for any help.
>

I don't understand your actual problem.  Python is much more expressive
than batch, so why not actually convert it?

Write a file with an extension of .py, and run it the same way you'd run
a batch file.  This assumes you have Python 3 associated with the .py
extension.

Now it won't matter if the python code has one line, or 100.

-- 

DaveA

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


Docstring parsing and formatting

2012-09-17 Thread Ben Finney
Howdy all,

Where can I find a standard implementation of the docstring parsing and
splitting algorithm from PEP 257?


PEP 257 describes a convention of structure and formatting for
docstrings http://www.python.org/dev/peps/pep-0257/>. Docstrings
that conform to this convention can therefore be parsed into their
component parts, and re-formatted.

The PEP describes http://www.python.org/dev/peps/pep-0257/#id20>
and algorithm for parsing the docstring as found in the string literal.
It says “Docstring processing tools will …” and goes on to describe, in
prose and example code, how the parsing should be done.

Where is a common implementation of that algorithm? It seems that it
should be in the Python standard library, but I can't find it.

Ideally what I want is to be able to write:

import textwrap

(summary, description) = textwrap.pep257_parse(foo.__doc__)

and have ‘summary’ as the docstring's summary line, and ‘description’ as
the docstring's description (as described in http://www.python.org/dev/peps/pep-0257/#id19>).

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


Re: 'indent'ing Python in windows bat

2012-09-17 Thread Ian Kelly
On Mon, Sep 17, 2012 at 7:08 PM, David Smith  wrote:
> How do I "indent" if I have something like:
> if (sR=='Cope'): sys.exit(1) elif (sR=='Perform') sys.exit(2) else
> sys.exit(3)

How about:

if sR == 'Cope':
sys.exit(1)
elif sR == 'Perform':
sys.exit(2)
else:
sys.exit(3)

I don't really understand why you're trying to keep it all on one line.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: 'indent'ing Python in windows bat

2012-09-17 Thread Roy Smith
In article ,
 Ian Kelly  wrote:

> On Mon, Sep 17, 2012 at 7:08 PM, David Smith  wrote:
> > How do I "indent" if I have something like:
> > if (sR=='Cope'): sys.exit(1) elif (sR=='Perform') sys.exit(2) else
> > sys.exit(3)
> 
> How about:
> 
> if sR == 'Cope':
> sys.exit(1)
> elif sR == 'Perform':
> sys.exit(2)
> else:
> sys.exit(3)
> 
> I don't really understand why you're trying to keep it all on one line.

sys.exit({'Cope':1, 'Perform':2}.get(sR, 3))
-- 
http://mail.python.org/mailman/listinfo/python-list



Re: 'indent'ing Python in windows bat

2012-09-17 Thread Tim Roberts
David Smith  wrote:
>
>I'm converting windows bat files little by little to Python 3 as I find 
>time and learn Python.
>The most efficient method for some lines is to call Python like:
>python -c "import sys; sys.exit(3)"
>
>How do I "indent" if I have something like:
>if (sR=='Cope'): sys.exit(1) elif (sR=='Perform') sys.exit(2) else 
>sys.exit(3)
>
>My sole result in many attempts is "Syntax Error."

The other responses asking "why" are excellent, but this will do that
specific job:

sys.exit( {'Cope':1,'Perform':2}.get(sR,3) )

The best way to convert a batch file to Python is to convert the whole file
to a Python script.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: 'indent'ing Python in windows bat

2012-09-17 Thread Chris Rebert
On Mon, Sep 17, 2012 at 8:28 PM, Dennis Lee Bieber
 wrote:
> On Mon, 17 Sep 2012 21:08:32 -0400, David Smith 
> declaimed the following in gmane.comp.python.general:
>
>>
>> How do I "indent" if I have something like:
>> if (sR=='Cope'): sys.exit(1) elif (sR=='Perform') sys.exit(2) else
>> sys.exit(3)
>>
> If the sole purpose of the BAT file is to set return codes, I
> wouldn't bother using Python... Python is /not/ a shell language
> substitute

FWIW, it kinda was, for the Amoeba OS, originally:
http://docs.python.org/faq/general#why-was-python-created-in-the-first-place

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


How to queue functions

2012-09-17 Thread Dhananjay
Dear all,

I am trying to use multiprocessing module.
I have 5 functions and 2000 input files.

First, I want to make sure that these 5 functions execute one after the
other.
Is there any way that I could queue these 5 functions within the same
script ?


Next, as there are 2000 input files.
I could queue them by queue.put() and get back to run one by one using
queue.get() as follows:

for file in files:
if '.dat.gz' in file:
q.put(file)

while True:
item = q.get()
x1 = f1(item)
x2 = f2(x1)
x3 = f3(x2)
x4 = f4(x3)
final_output = f5(x4)


However, how can I input them on my 8 core machine, so that at a time 8
files will be processed (to the set of 5 functions; each function one after
the other) ?

I am bit confused with the multiprocessing, please suggest me some
directions 

Thank you


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


Re: Docstring parsing and formatting

2012-09-17 Thread Terry Reedy

On 9/17/2012 10:03 PM, Ben Finney wrote:

Howdy all,

Where can I find a standard implementation of the docstring parsing and
splitting algorithm from PEP 257?


I presume there is something in the code behind help().

--
Terry Jan Reedy

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


Re: 'indent'ing Python in windows bat

2012-09-17 Thread Terry Reedy

On 9/17/2012 9:08 PM, David Smith wrote:

Hello, I'm essentially a newbie in Python.
My problem in searching the archives is not knowing what words to use to
ask.

I'm converting windows bat files little by little to Python 3 as I find
time and learn Python.
The most efficient method for some lines is to call Python like:
python -c "import sys; sys.exit(3)"

How do I "indent" if I have something like:
if (sR=='Cope'): sys.exit(1) elif (sR=='Perform') sys.exit(2) else
sys.exit(3)


Quite aside from whether this is  good idea, I believe putting \n 
followed by spaces or \t in the quoted string should work. It does for exec.


--
Terry Jan Reedy

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


Re: 'indent'ing Python in windows bat

2012-09-17 Thread Dave Angel
On 09/18/2012 01:08 AM, Terry Reedy wrote:
> On 9/17/2012 9:08 PM, David Smith wrote:
>> Hello, I'm essentially a newbie in Python.
>> My problem in searching the archives is not knowing what words to use to
>> ask.
>>
>> I'm converting windows bat files little by little to Python 3 as I find
>> time and learn Python.
>> The most efficient method for some lines is to call Python like:
>> python -c "import sys; sys.exit(3)"
>>
>> How do I "indent" if I have something like:
>> if (sR=='Cope'): sys.exit(1) elif (sR=='Perform') sys.exit(2) else
>> sys.exit(3)
>
> Quite aside from whether this is  good idea, I believe putting \n
> followed by spaces or \t in the quoted string should work. It does for
> exec.
>

Don't forget, the OP uses Windows.  Last I looked, the cmd processor had
miserable escaping features.  But I could easily be wrong --  I haven't
used Windows deliberately for quite a while now.



-- 

DaveA

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