Re: Object Reference question

2009-08-21 Thread josef
On Aug 21, 1:34 am, Miles Kaufmann  wrote:
> On Aug 20, 2009, at 11:07 PM, josef wrote:
>
> > To begin, I'm new with python. I've read a few discussions about
> > object references and I think I understand them.
>
> > To be clear, Python uses a "Pass By Object Reference" model.
> > x = 1
> > x becomes the object reference, while an object is created with the
> > type 'int', value 1, and identifier (id(x)). Doing this with a class,
> > x = myclass(), does the same thing, but with more or less object
> > attributes. Every object has a type and an identifier (id()),
> > according to the Python Language Reference for 2.6.2 section 3.1.
>
> > x in both cases is the object reference. I would like to use the
> > object to refer to the object reference.
>
> Stop right there.  'x' is not *the* object reference.  It is *an*  
> object reference (or in my preferred terminology, a label).  Suppose  
> you do:
>
> x = myclass()
> y = x

It would not make sense to do that in the context of the software I am
writing. The documentation will specifically state not to do that. If
the user does do that, then the user will be disappointed and possibly
angry.

>
> The labels 'x' and 'y' both refer to the same object with equal  
> precedence.  There is no mapping from object back to label; it is a  
> one-way pointer.  Also importantly, labels themselves are not objects,  
> and cannot be accessed or referred to.

I would just like to store the name of the one way pointer.

>
> (This is a slight oversimplification; thanks to Python's reflection  
> and introspection capabilities, it is possible to access labels to  
> some extent, and in some limited situations it is possible to use  
> stack inspection to obtain a label for an object.  But this is hackish  
> and error-prone, and should never be used when a more Pythonic method  
> is available.)

Hackish is fine. How error-prone is this method?
>
> > The following is what I would like to do:
> > I have a list of class instances dk = [ a, b, c, d ], where a, b, c, d
> > is an object reference. Entering dk gives me the object: [MyClass0
> > instance at 0x, MyClass1 instance at 0x0008, MyClass2 instance at
> > 0x0010 ... ]
>
> > I need the object reference name (a,b,c,d) from dk to use as input for
> > a file.
>
> It sounds like you should either be storing that name as an attribute  
> of the object, or using a dictionary ({'a': a, 'b': b, ...}).

That solution was mentioned in some of the discussions I read, but I
would like to stay away from something like: a = MyClass
(name='a', ...). Is it possible to assign an object reference name in
a class __init__ defintion?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: #elements of seq A in seq B

2009-08-21 Thread Peter Otten
Jan Kaliszewski wrote:

> 20-08-2009 o 13:01:29 Neal Becker  wrote:
> 
>> I meant #occurrences of characters from the set A in string B
> 
> But:
> 
> 1) separately for each element of A? (see Simon's sollution with
> defaultdict)
> 
> 2) or total number of all occurrences of elements of A? (see below)
> 
> 
> 20-08-2009 o 14:05:12 Peter Otten <[email protected]> wrote:
> 
>> identity = "".join(map(chr, range(256)))
>> n = len(b) - len(b.translate(identity, a))
> 
> Nice, though I'd prefer Simon's sollution:
> 
>  a = set(a)
>  n = sum(item in a for item in b)

Just to give you an idea why I posted the former:

$ python -m timeit -s"a = set('abc'); b = 'abcdefg'*10**5" 'sum(item in a 
for item in b)'
10 loops, best of 3: 195 msec per loop

$ python -m timeit -s"a = 'abc'; b = 'abcdefg'*10**5; id=''.join(map(chr, 
range(256)))" 'len(b) - len(b.translate(id, a))'
100 loops, best of 3: 4.97 msec per loop

Peter

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


Re: Object Reference question

2009-08-21 Thread Dave Angel

josef wrote:

To begin, I'm new with python. I've read a few discussions about
object references and I think I understand them.

To be clear, Python uses a "Pass By Object Reference" model.
x = 1
x becomes the object reference, while an object is created with the
type 'int', value 1, and identifier (id(x)). Doing this with a class,
x = myclass(), does the same thing, but with more or less object
attributes. Every object has a type and an identifier (id()),
according to the Python Language Reference for 2.6.2 section 3.1.

x in both cases is the object reference. I would like to use the
object to refer to the object reference. If I have a gross
misunderstanding, please correct me.

The following is what I would like to do:
I have a list of class instances dk = [ a, b, c, d ], where a, b, c, d
is an object reference. Entering dk gives me the object: [MyClass0
instance at 0x, MyClass1 instance at 0x0008, MyClass2 instance at
0x0010 ... ]

I need the object reference name (a,b,c,d) from dk to use as input for
a file. Where do I find the memory location of the object reference
and the object reference name memory location? I am unconcerned with
the fact that the memory location will change the next time I run a
python session. I will be using the object reference name for
processing right away.

My main focus of this post is: "How do I find and use object reference
memory locations?"

Thoughts?
Thanks,

Josef

  
There was a similar query here within the last couple of months, and 
lots of interesting discussion.  But I never saw a use case convincing 
enough for me to want to remember how the various suggestions worked.  
Just how are you planning to use this?  Are you planning to write a 
debugger?


Or are you trying to keep mnemonic names for all instances of a 
particular class?  Is this for a particular program's use, or are you 
trying to create a library to be used to reverse engineer some software 
you con't control?


Several of your phrasings imply you don't understand Python yet.

"memory location" - invisible to python use.  And although id() will 
give you a hash-code that's actually a memory address, there's no direct 
way to use it.  And names (attributes) don't necessarily have an address.
"the object reference name (a,b,c,d) from dk"  What is this?  There's 
nothing that even conceptually looks like that when you assign   dk = 
[a, b, c, d]



A given object may have one to many references, and some of these may 
have names.  If you constrain those names to be in a particular context, 
it may be possible to search for which name(s) currently happen(s) to 
point to the given object.  For example, if you have the following at 
top level in a module:


a = MyClass0()
b = MyClass1()
c = MyClass2()
dk = [a, b, c]

then, given the  id() of  dk[2], you could search the particular modules 
global name dictionary, and find c.  But for the following fragment, you 
could not:


a = MyClass0()
b = MyClass1()
c = MyClass2()
dk = [a, b, c]
c = 42

dk remains the same, but the dk[2] item no longer has any name 
referencing it.


At any given instant of time, most objects in a typical program have no 
name associated with them.  Many of them never did have a name.  What 
would you want if dk had been created as:


dk = [MyClass0(), MyClass1(), MyClass2()]

or if a, b, and/or c were local variables in a function that's long 
since quit running, or that has run many times, each time creating new 
objects?


DaveA

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


Re: PIL and Python

2009-08-21 Thread catafest
I don't extract data from jpegs.
I wanna put some data in this (copyright of my site) ...

On Aug 20, 2:01 pm, MaxTheMouse  wrote:
> On Aug 20, 10:23 am, catafest  wrote:
>
> > On my photo jpg i have this :
>
> > Image Type: jpeg (The JPEG image format)
> > Width: 1224 pixels
> > Height: 1632 pixels
> > Camera Brand: Sony Ericsson
> > Camera Model: W810i
> > Date Taken: 2009:07:09 08:16:21
> > Exposure Time: 1/19 sec.
> > ISO Speed Rating: 320
> > Flash Fired: Flash did not fire, compulsory flash mode.
> > Metering Mode: Center-Weighted Average
> > Software: R4EA031     prgCXC1250321_ORANGE_HN 4.5
>
> > This is the data i want edit it to make some copyright for my site.
>
> I don't know about PIL but you might want to try 
> exif.py.http://sourceforge.net/projects/exif-py/

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


Re: Object Reference question

2009-08-21 Thread Bruno Desthuilliers

josef a écrit :

To begin, I'm new with python. I've read a few discussions about
object references and I think I understand them.

To be clear, Python uses a "Pass By Object Reference" model.
x = 1
x becomes the object reference, while an object is created with the
type 'int', value 1, and identifier (id(x)). Doing this with a class,
x = myclass(), does the same thing, but with more or less object
attributes. Every object has a type and an identifier (id()),
according to the Python Language Reference for 2.6.2 section 3.1.

x in both cases is the object reference. 


Nope. It's *a* reference to the object - or, more exactly, a key in a 
mapping (the current namespace), which is associatied with a reference 
to the object. You can translate:


   x = 1

to:

  current_namespace['x'] = int(1)



I would like to use the
object to refer to the object reference. If I have a gross
misunderstanding, please correct me.

The following is what I would like to do:
I have a list of class instances dk = [ a, b, c, d ], where a, b, c, d
is an object reference. Entering dk gives me the object: [MyClass0
instance at 0x, MyClass1 instance at 0x0008, MyClass2 instance at
0x0010 ... ]

I need the object reference name (a,b,c,d) from dk to use as input for
a file.


???

Could you elaborate, please ?


 Where do I find the memory location of the object reference
and the object reference name memory location? 


short answer : you don't. Python is a high level language, 'memory 
location' is an implementation detail (and highly 
implementation-dependant), and *not* exposed (at least not in any usable 
way).



I am unconcerned with
the fact that the memory location will change the next time I run a
python session. I will be using the object reference name for
processing right away.

My main focus of this post is: "How do I find and use object reference
memory locations?"

Thoughts?


Yes : please explain the problem you're trying to solve. I mean, the 
*real* problem - what you want to achieve -, not what you think is the 
solution !-)

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


Re: difference between 2 arrays

2009-08-21 Thread Gabriel Genellina
En Thu, 20 Aug 2009 06:54:05 -0300, <""Michel Claveau -  
MVP"> escribió:



Yes, the module sets is written, in doc, like "deprecated".
But:
  - sets exist in Python 2.6 (& 2.5 or 2.4)
  - documentation of sets (module) is better tha, documentation of set  
(builtin)


The best: read the documentaion of the module, and use the builtin...


Any suggestion to improve the builtin set documentation? In what ways do  
you see one is better than the other?


--
Gabriel Genellina

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


Re: ncurses getch & unicode (was: decoding keyboard input when using curses)

2009-08-21 Thread Thomas Dickey
On Aug 20, 6:12 pm, Iñigo Serna  wrote:
> Hi again,
>
> 2009/8/20 Iñigo Serna 
> > I have the same problem mentioned 
> > inhttp://groups.google.com/group/comp.lang.python/browse_thread/thread/...some
> >  months ago.
>
> > Python 2.6 program which usesncursesmodule in a terminal configured to use 
> > UTF-8 encoding.
>
> > When trying to get input from keyboard, a non-ascii character (like ç) is 
> > returned as 2 integers < 255, needing 2 calls to getch method to get both.
> > These two integers \xc3 \xa7 forms the utf-8 encoded representation of ç 
> > character.
>
> >ncursesget_wch documentation states the function should return an unique 
> >integer > 255 with the ordinal representation of that unicode char encoded 
> >in UTF-8, \xc3a7.
>
> Answering myself, I've copied at the bottom of this email a working
> solution, but the question still remains: why win.getch() doesn't
> return the correct value?

The code looks consistent with the curses functions...

> Kind regards,
> Iñigo Serna
>
> ##
> # test.py
> import curses
>
> import locale
> locale.setlocale(locale.LC_ALL, '')
> print locale.getpreferredencoding()
>
> def get_char(win):
>     def get_check_next_byte():
>     c = win.getch()

You're using "getch", not "get_wch" (Python's ncurses binding may/may
not have the latter).
curses getch returns 8-bit values, get_wch would return wider values.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Waiting for a subprocess to exit

2009-08-21 Thread Ben Finney
Miles Kaufmann  writes:

> On Aug 20, 2009, at 10:13 PM, Ben Finney wrote:
> > Why would I use ‘os.waitpid’ instead of::
> >
> >process = subprocess.Popen("mycmd" + " myarg", shell=True)
> >process.wait()
> >status = process.returncode
>
> Really, you can just use:
>
>   process = subprocess.Popen("mycmd" + " myarg", shell=True)
>   status = process.wait()

Ah thanks, that's even better.

> I'm not sure why the documentation suggests using os.waitpid.

Could someone who knows how to drive the Python BTS please report that
against the ‘subprocess’ documentation?

-- 
 \   “I am amazed, O Wall, that you have not collapsed and fallen, |
  `\since you must bear the tedious stupidities of so many |
_o__)  scrawlers.” —anonymous graffiti, Pompeii, 79 CE |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem with arrays in a recursive class function

2009-08-21 Thread Bruno Desthuilliers

Aaron Scott a écrit :

I have a list of nodes, and I need to find a path from one node to
another. The nodes each have a list of nodes they are connected to,
set up like this:



class Node(object):
def __init__(self, connectedNodes):
self.connectedNodes = connectedNodes

nodes = {
1: Node([4]),
2: Node([3]),
3: Node([2, 4, 5]),
4: Node([1, 6, 3]),
5: Node([3, 7]),
6: Node([4, 9]),
7: Node([5, 8]),
8: Node([7, 9]),
9: Node([6, 8])
}



I made a quick brute-force pathfinder to solve it (in this case, a
path from node 1 to node 9). Here it is:



class PathFind(object):
def __init__(self, source, destination):
self.source = source
self.destination = destination
self.solved = []
def Search(self):
self.PathFind([self.source])

>

if self.solved:
print "Solutions: "
for i in self.solved:
print "\t" + str(i)


print "\t%s" % i


else:
print "Couldn't solve."
def PathFind(self, trail):
location = trail[-1]
if location == self.destination:
self.solved.append(trail)


I think you want
self.solved.append(trail[:])

Hint : Python doesn't use "pass by value".


 > The problem is the array trail[], which seems to survive from instance

to instance of PathFind(). I thought that by calling self.PathFind
(trail[:]), I was creating a new copy of trail[], 


Yes. But on the 'not solved' branch, you do mutate trail !-)
--
http://mail.python.org/mailman/listinfo/python-list


Sanitising arguments to shell commands (was: Waiting for a subprocess to exit)

2009-08-21 Thread Ben Finney
Miles Kaufmann  writes:

> I would recommend avoiding shell=True whenever possible. It's used in
> the examples, I suspect, to ease the transition from the functions
> being replaced, but all it takes is for a filename or some other input
> to unexpectedly contain whitespace or a metacharacter and your script
> will stop working--or worse, do damage (cf. the iTunes 2 installer
> debacle[1]).

Agreed, and that's my motivation for learning about ‘subprocess.Popen’.

> Leaving shell=False makes scripts more secure and robust; besides,
> when I'm putting together a command and its arguments, it's as
> convenient to build a list (['mycmd', 'myarg']) as it is a string (if
> not more so).

Which leads to another issue:

I'm modifying a program that gets its child process command arguments
from three places:

* hard-coded text within the program (e.g. the command name, and
  context-specific arguments for the specific operation to be performed)

* user-customised options to be added to the command line

* filenames from the program's own command line

For the hard-coded argument text, obviously they can simply be
hard-coded as list elements::

command_args = ["foo", "--bar"]

The filenames to be processed can also be appended one item per
filename.

However, the user-customised options are specified by the user in a
configuration file, as a single string argument::

[fooprogram]
additional_args = --baz 'crunch cronch' --wobble

This works fine if the command line is constructed by dumb string
concatenation; but obviously it fails when I try to construct a list of
command line arguments.

It's quite reasonable for the user to expect to be able to put any
partial shell command-line in that string option and expect it will be
processed by the shell, including any quoting or other escaping.

How can I take a string that is intended to be part of a command line,
representing multiple arguments and the shell's own escape characters as
in the above example, and end up with a sane command argument list for
‘subprocess.Popen’?

E.g.::

parser = optparse.OptionParser()
(options_args) = parser.parse_args(argv[1:])
filenames = args

config = configparser.ConfigParser()
config.read([system_config_file_path, user_config_file_path])
user_configured_args = config.get('fooprogram', 'additional_args')

command_args = ["foo", "--bar"]
somehow_append_each_argument(command_args, user_configured_args)
command_args.extend(filenames)

command_process = subprocess.Popen(command_args, shell=False)

The resulting ‘command_args’ list should be::

["foo", "--bar",
 "--baz", "crunch cronch", "--wobble",
 "spam.txt", "beans.txt"]

How can I write the ‘somehow_append_each_argument’ step to get that
result?

-- 
 \“Every sentence I utter must be understood not as an |
  `\  affirmation, but as a question.” —Niels Bohr |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Sanitising arguments to shell commands (was: Waiting for a subprocess to exit)

2009-08-21 Thread Chris Rebert
On Fri, Aug 21, 2009 at 2:08 AM, Ben Finney wrote:

> How can I take a string that is intended to be part of a command line,
> representing multiple arguments and the shell's own escape characters as
> in the above example, and end up with a sane command argument list for
> ‘subprocess.Popen’?

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

module shlex — Simple lexical analysis
New in version 1.5.2.
"The shlex class makes it easy to write lexical analyzers for simple
syntaxes resembling that of the Unix shell."

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


Re: Sanitising arguments to shell commands

2009-08-21 Thread Jean-Michel Pichavant

Ben Finney wrote:

Miles Kaufmann  writes:

  

I would recommend avoiding shell=True whenever possible. It's used in
the examples, I suspect, to ease the transition from the functions
being replaced, but all it takes is for a filename or some other input
to unexpectedly contain whitespace or a metacharacter and your script
will stop working--or worse, do damage (cf. the iTunes 2 installer
debacle[1]).



Agreed, and that's my motivation for learning about ‘subprocess.Popen’.
  


Can someone explain the difference with the shell argument ? giving for 
instance an example of what True will do that False won't. I mean, I've 
read the doc, and to be honest, I didn't get it.
I'm concerned because I'm using subprocess, but I guess my shell arg has 
been filled a little bit random..


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


Re: Object Reference question

2009-08-21 Thread Ben Finney
josef  writes:

> To be clear, Python uses a "Pass By Object Reference" model.

Yes. (I'm glad this concept has propagated to newcomers so well :-)

> x = 1
> x becomes the object reference

It becomes *a* reference to that object, independent of any other
references to that same object.

> while an object is created with the type 'int', value 1, and
> identifier (id(x)).

Not really “while”. The object creation happens first, then the
assignment statement binds a reference to that object.

> Doing this with a class, x = myclass(), does the same thing, but with
> more or less object attributes. Every object has a type and an
> identifier (id()), according to the Python Language Reference for
> 2.6.2 section 3.1.

Any expression can be on the right side of the assignment operator. The
expression will evaluate to some object, which the assignment will then
bind to the reference on the left side of the assignment operator.

> x in both cases is the object reference.

It is *an* object reference; that is, it's an identifier which refers to
an object. There's nothing about that identifier that makes it “the (one
and only) object reference”.

> I would like to use the object to refer to the object reference. If I
> have a gross misunderstanding, please correct me.

Yes, it's a simple misunderstanding: objects do not, in general, know
any of the references there may be to them.

> The following is what I would like to do: I have a list of class
> instances dk = [ a, b, c, d ], where a, b, c, d is an object
> reference.

Note that, after that list is created, each item in that list is *also*
a reference to the corresponding object. That is, ‘a’ is a reference to
an object, and ‘dk[0]’ is a *different* reference to the *same* object.
The object has no knowledge about those references.

> Entering dk gives me the object: [MyClass0 instance at 0x,
> MyClass1 instance at 0x0008, MyClass2 instance at 0x0010 ... ]

This is a hint that, when asked for a string representation, each of the
objects in that list can say little more than that they are of a
particular type, and are located at a particular memory address. They do
not know any of the references to themselves.

> I need the object reference name (a,b,c,d) from dk to use as input for
> a file.

You'll have to track that yourself.

A good way to keep track of name-to-object mappings is with Python's
built-in mapping type, ‘dict’::

dk = {'a': a, 'b': b, 'c': c, 'd': d}

(There are more efficient ways to create a dictionary without such
repetition, of course, but this is more illustrative of the point.)

You can then get a list (assembled in arbitrary sequence) of just the
keys, or just the values, or the key-value pairs, from the dict with its
‘keys’, ‘values’, and ‘items’ methods respectively::

>>> dk = {'a': a, 'b': b, 'c': c, 'd': d}
>>> dk.keys()
['a', 'c', 'd', 'b']
>>> dk.values()
[, , , ]
>>> dk.items()
[('b', ), ('c', ), 
('a',  ), ('d',  )]

Each of these is even better used as the iterable for a ‘for’ loop::

>>> for (key, value) in dk.items():
... print "Here is item named", key
... print value

> My main focus of this post is: "How do I find and use object reference
> memory locations?"

You don't. Use the references in your code, forget about the memory
addresses, and remember that container objects themselves contain
references, so use them for organising your objects.

-- 
 \ “Demagogue: One who preaches doctrines he knows to be untrue to |
  `\ men he knows to be idiots.” —Henry L. Mencken |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Sanitising arguments to shell commands

2009-08-21 Thread Ben Finney
Jean-Michel Pichavant  writes:

> Can someone explain the difference with the shell argument ? giving
> for instance an example of what True will do that False won't.

The ‘shell’ argument to the ‘subprocess.Popen’ constructor specifies
whether the command-line should be invoked directly (‘shell=False’) or
indirectly through invoking a shell (‘shell=True’).

If ‘shell=False’, the command-line arguments are used as direct
arguments to the kernel's “run this program for me”.

If ‘shell=True’ the command-line arguments are themselves passed to a
new instance of the user's current shell, as a command line that *it*
should invoke on the program's behalf. This allows the command line to
be manipulated and interpolated etc., the way it would be if typed at a
new shell prompt. Then, that shell will in turn ask the kernel “run this
program for me” as it normally does after processing the arguments.

> I mean, I've read the doc, and to be honest, I didn't get it. I'm
> concerned because I'm using subprocess, but I guess my shell arg has
> been filled a little bit random..

Use ‘shell=False’ by default (which, since that's the default for
‘subprocess.Popen’, means you can omit it entirely), and specify exactly
the command line arguments you want the kernel to execute. Only if you
know you want a shell process to be involved should you use
‘shell=True’.

-- 
 \ “Welchen Teil von ‘Gestalt’ verstehen Sie nicht?  [What part of |
  `\‘gestalt’ don't you understand?]” —Karsten M. Self |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Sanitising arguments to shell commands

2009-08-21 Thread Ben Finney
Chris Rebert  writes:

> module shlex — Simple lexical analysis
> New in version 1.5.2.
> "The shlex class makes it easy to write lexical analyzers for simple
> syntaxes resembling that of the Unix shell."

Exactly what I needed:

>>> import shlex
>>> user_configured_args = "--baz 'crunch cronch' --wobble"
>>> filenames = ["spam.txt", "beans.txt"]
>>> command_args = ["foo", "--bar"]
>>> command_args.extend(shlex.split(user_configured_args))
>>> command_args.extend(filenames)
>>> command_args
['foo', '--bar', '--baz', 'crunch cronch', '--wobble', 'spam.txt', 'beans.txt']

-- 
 \ “Pinky, are you pondering what I'm pondering?” “I think so, |
  `\Brain, but if we get Sam Spade, we'll never have any puppies.” |
_o__)   —_Pinky and The Brain_ |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Zipimport leaks memory?

2009-08-21 Thread Gabriel Genellina
En Thu, 20 Aug 2009 07:02:26 -0300, [email protected]  
 escribió:


We are currently trying to identify and fix all the memory leaks by just  
doing Py_Initialize-PyRun_SimpleFile(some simple script)-Py_Finalize and  
found that there are around 70 malloc-ed blocks which are not freed. One  
of the significant contributor to this number is the 'files' object in  
ZipImporter.  I am not able to identify the reason for this leak and was  
wondering if anyone on this list would help me out here.


So, here goes :

Since we have a zip file in our sys.path, this object is initialized and  
added to the zip_directory_cache dict during Py_Initialize. One point to  
note here is that there is no DECREF on the 'files' object after adding  
it to the zip_directory_cache dict.


When a module in a directory is imported(encoding.alias) then the  
reference count of 'files' is increased. When this module is unloaded  
during Py_Finalize-PyImport_Cleanup, the ref count of files object is  
decremented properly. So at the end of Py_Finalize the files object  
still has one reference count which is a result of it being an entry in  
the zip_directory_cache.


I didn't read the source, but isn't that the expected behavior? If the  
module is still referenced by zip_directory_cache, the reference count  
must be 1 or more.

Maybe zip_directory_cache should be cleared at interpreter shutdown?

--
Gabriel Genellina

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


Re: ncurses getch & unicode (was: decoding keyboard input when using curses)

2009-08-21 Thread Iñigo Serna
2009/8/21 Thomas Dickey :
> On Aug 20, 6:12 pm, Iñigo Serna  wrote:
>>     c = win.getch()
>
> You're using "getch", not "get_wch" (Python's ncurses binding may/may
> not have the latter).
> curses getch returns 8-bit values, get_wch would return wider values.

you are right, ncurses binding does not have get_wch, only getch, and
this last is the only one called in ncurses library bindings.


Anyway, I've written a patch to include the get_wch method in the bindings.
See http://bugs.python.org/issue6755


Thanks for the clarification,
Iñigo
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Sanitising arguments to shell commands

2009-08-21 Thread Jean-Michel Pichavant

Ben Finney wrote:

Jean-Michel Pichavant  writes:

  

Can someone explain the difference with the shell argument ? giving
for instance an example of what True will do that False won't.



The ‘shell’ argument to the ‘subprocess.Popen’ constructor specifies
whether the command-line should be invoked directly (‘shell=False’) or
indirectly through invoking a shell (‘shell=True’).

If ‘shell=False’, the command-line arguments are used as direct
arguments to the kernel's “run this program for me”.

If ‘shell=True’ the command-line arguments are themselves passed to a
new instance of the user's current shell, as a command line that *it*
should invoke on the program's behalf. This allows the command line to
be manipulated and interpolated etc., the way it would be if typed at a
new shell prompt. Then, that shell will in turn ask the kernel “run this
program for me” as it normally does after processing the arguments.

  

I mean, I've read the doc, and to be honest, I didn't get it. I'm
concerned because I'm using subprocess, but I guess my shell arg has
been filled a little bit random..



Use ‘shell=False’ by default (which, since that's the default for
‘subprocess.Popen’, means you can omit it entirely), and specify exactly
the command line arguments you want the kernel to execute. Only if you
know you want a shell process to be involved should you use
‘shell=True’.

  
Thank you Ben for the update. It's clear for me now, I've checked and I 
use it with no shell arg, except at one place, but I don't think it's 
intended and it happens to work anyway. I've added a small comment just 
in case it fails in the future.


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


Re: Sanitising arguments to shell commands

2009-08-21 Thread Rick King
shlex doesn't handle unicode input though, so, in general, it's not a 
good solution.


Rick King
Southfield MI


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

module shlex — Simple lexical analysis
New in version 1.5.2.
"The shlex class makes it easy to write lexical analyzers for simple
syntaxes resembling that of the Unix shell."
  

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


Logging with SMTP Error on Mac

2009-08-21 Thread Bev in TX
Hi,

I've done some Python programming, but I still consider myself a
Python newbie.  I have a Mac Pro OS X 10.5.8 system and I installed
Python 2.6.2 (the latest package available for the Mac) yesterday.

I was working through Matt Wilson's article on using the logging
module:
http://blog.tplus1.com/index.php/2007/09/28/the-python-logging-module-is-much-better-than-print-statements/
(If that does not work, then try: http://tinyurl.com/5v2lcy )

Everything worked great until his last example.  My ISP does not
provide e-mail, so I tried using gmail in the line that sets h2.  I
substituted "mailid" for my actual e-mail address in the following
examples; in my test I used my actual e-mail ID.  Also, I used the
full path to the newly installed Python 2.6.2; otherwise it picked up
the older Python 2.5:
#!/Library/Frameworks/Python.framework/Versions/2.6/bin/python

First attempt:
h2 = logging.handlers.SMTPHandler('smtp.gmail.com', '[email protected]',
['[email protected]'],'ERROR log')
However, that caused the following error to be issued:

Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/2.6/lib/
python2.6/logging/handlers.py", line 868, in emit
smtp.sendmail(self.fromaddr, self.toaddrs, msg)
  File "/Library/Frameworks/Python.framework/Versions/2.6/lib/
python2.6/smtplib.py", line 698, in sendmail
raise SMTPSenderRefused(code, resp, from_addr)
SMTPSenderRefused: (530, '5.7.0 Must issue a STARTTLS command first.
7sm3867994qwf.47', '[email protected]')

I also tried providing my gmail userid/password, I tried adding a 5th,
credential, argument, which is a tupple, (username,password) (new in
2.6).

Second attempt:
h2 = logging.handlers.SMTPHandler('smtp.gmail.com', '[email protected]',
['[email protected]'],'ERROR log',('[email protected]','gmail-
password'))
However, that caused the following error message:

Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/2.6/lib/
python2.6/logging/handlers.py", line 867, in emit
smtp.login(self.username, self.password)
  File "/Library/Frameworks/Python.framework/Versions/2.6/lib/
python2.6/smtplib.py", line 552, in login
raise SMTPException("SMTP AUTH extension not supported by
server.")
SMTPException: SMTP AUTH extension not supported by server.

I am able access gmail via Mac's Mail, in which it says that outgoing
mail is going to:
  smtp.gmail.com:mailid
I tried using that as the server in the Python script, but it could
not find that server.

Is this possible?  If I am doing something incorrectly, would someone
please indicate what it is?

Thanks,
Bev in TX
-- 
http://mail.python.org/mailman/listinfo/python-list


Using 'apply' as a decorator, to define constants

2009-08-21 Thread Jonathan Fine

Hi

It might seem odd to use 'apply' as a decorator, but it can make sense.

I want to write:
# Top level in module.
tags =  
where the list is most easily constructed using a function.

And so I write:
@apply
def tags():
value = []
# complicated code
return value

And now 'tags' has the result of running the complicated code.


Without using 'apply' as a decorator one alternative is
def tmp():
value = []
# complicated code
return value
tags = tmp()
del tmp


Like all uses of decorators, it is simply syntactic sugar.  It allows 
you to see, up front, what is going to happen.  I think, once I get used 
to it, I'll get to like it.


The way to read
@apply
def name():
 # code
is that we are defining 'name' to be the return value of the effectively 
anonymous function that follows.


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


Pydev 1.4.8 Released

2009-08-21 Thread Fabio Zadrozny
Hi All,

Pydev and Pydev Extensions 1.4.8 have been released

Details on Pydev Extensions: http://www.fabioz.com/pydev
Details on Pydev: http://pydev.sf.net
Details on its development: http://pydev.blogspot.com

Release Highlights in Pydev Extensions:
-

* Created public API for starting/finishing debug server
* Import based on unresolved variables works correctly when the
document is changed
* Ignore error works correctly when the document is changed
* No longer showing the replace button for the search


Release Highlights in Pydev:
--

* Debugger can jump to line
* Reloading module when code changes in the editor if inside debug session
* Usability improvement on the preferences pages (editor,
code-formatter, comment block and code-style showing examples)
* Pythonpath reported in the main tab was not correct for ironpython
launch configs
* Main module tab in launch configuration was not appearing for jython
* Multiline block comments considering the current indentation (and
working with tabs)
* Hover works correctly when the document is changed
* The interactive console no longer uses the UI thread (so, it doesn't
make eclipse halt anymore on slow requests to the shell)
* The interactive console save history now saves the contents in the
same way they're written
* When creating a python run, the classpath was being set (and
overridden), which should only happen in jython runs
* Fixed issue where a line with only tabs and a close parenthesis
would have additional tabs entered on code-formatting
* A Pydev (Jython) project can coexist with a JDT project (and
properly use its info -- only project references worked previously)
* Many small usability improvements (editors improved)
* Verbosity option added to run as unit-test
* No longer using respectJavaAccessibility=False for jython
* When there are too many items to show in the debugger, handle it gracefully



What is PyDev?
---

PyDev is a plugin that enables users to use Eclipse for Python, Jython
and Iron Python development -- making Eclipse a first class Python IDE
-- It comes with many goodies such as code completion, syntax
highlighting, syntax analysis, refactor, debug and many others.


Cheers,

-- 
Fabio Zadrozny
--
Software Developer

Aptana
http://aptana.com/python

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

Pydev - Python Development Environment for Eclipse
http://pydev.sf.net
http://pydev.blogspot.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Object Reference question

2009-08-21 Thread Simon Forman
On Aug 21, 2:07 am, josef  wrote:
> To begin, I'm new with python. I've read a few discussions about
> object references and I think I understand them.
>
> To be clear, Python uses a "Pass By Object Reference" model.
> x = 1
> x becomes the object reference, while an object is created with the
> type 'int', value 1, and identifier (id(x)). Doing this with a class,
> x = myclass(), does the same thing, but with more or less object
> attributes. Every object has a type and an identifier (id()),
> according to the Python Language Reference for 2.6.2 section 3.1.
>
> x in both cases is the object reference. I would like to use the
> object to refer to the object reference. If I have a gross
> misunderstanding, please correct me.

x is not the object reference, it's just a string used as a key in a
dict (the value is the object reference):

|>>> globals()
|{'__builtins__': , '__name__':
'__main__', '__doc__': None}
|>>> x = 1
|>>> globals()
|{'__builtins__': , '__name__':
'__main__', '__doc__': None, 'x': 1}


I don't understand what you're trying to do, but give up the idea of
"object reference memory locations".  Any name binding in python just
associates a string with a object in one of various namespace
dictionaries.

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


Conditionally skipping the contents of a with-statement

2009-08-21 Thread tsuraan
I'd like to write a Fork class to wrap os.fork that allows something like this:

with Fork():
  # to child stuff, end of block will automatically os._exit()
# parent stuff goes here

This would require (I think) that the __enter__ method of my Fork
class to be able to return a value or raise an exception indicating
that the block should not be run.  It looks like, from PEP343, any
exception thrown in the __enter__ isn't handled by with, and my basic
tests confirm this.  I could have __enter__ raise a custom exception
and wrap the entire with statement in a try/except block, but that
sort of defeats the purpose of the with statement.  Is there a clean
way for the context manager to signal that the execution of the block
should be skipped altogether?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Conditionally skipping the contents of a with-statement

2009-08-21 Thread Diez B. Roggisch

tsuraan schrieb:

I'd like to write a Fork class to wrap os.fork that allows something like this:

with Fork():
  # to child stuff, end of block will automatically os._exit()
# parent stuff goes here

This would require (I think) that the __enter__ method of my Fork
class to be able to return a value or raise an exception indicating
that the block should not be run.  It looks like, from PEP343, any
exception thrown in the __enter__ isn't handled by with, and my basic
tests confirm this.  I could have __enter__ raise a custom exception
and wrap the entire with statement in a try/except block, but that
sort of defeats the purpose of the with statement.  Is there a clean
way for the context manager to signal that the execution of the block
should be skipped altogether?


No. The only way would be something like this:

with Fork() as is_child:
if is_child:
   ...



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


Three-Phase-Diagrams with matplotlib

2009-08-21 Thread M. Hecht

Hello,

does anyone know whether it is possible to draw three-phase-diagrams with
matplotlib?

A three-phase-diagram is a triangular diagram applied in chemistry e.g. for
slags where
one has three main components of a chemical substance at the corners and
points or lines 
within the triangle marking different compositions of the substances in
percent, e.g.
in metallurgy 20% Al2O3, 45% CaO and 35% SiO2.


-- 
View this message in context: 
http://www.nabble.com/Three-Phase-Diagrams-with-matplotlib-tp25082083p25082083.html
Sent from the Python - python-list mailing list archive at Nabble.com.

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


Re: pypi category

2009-08-21 Thread Martin v. Löwis
> Would someone be able to inform me how a category can be added to the
> pypy list of categories?
> I'd like to add a CAD & Geometry category.
> ( I develop PythonOCC, wrappers for the OpenCASCADE CAD kernel, which
> is why )

Make a specific proposal to [email protected], along with a
list of packages that are already on PyPI that could use that
classifier.

Having a classifier that classifies zero or one package is pointless.

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


Re: 2.6 windows install

2009-08-21 Thread Martin v. Löwis
> Did you install Python to the network device from your XP box? That
> would explain why you can run it: the required registry settings &
> environment variables are added by the installer, none of which is
> occurring on any computer other than the one from which you installed.

In principle, Python doesn't need any registry settings or environment
variables in order to run.

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


Re: Using 'apply' as a decorator, to define constants

2009-08-21 Thread alex23
On Aug 21, 11:36 pm, Jonathan Fine  wrote:
> It might seem odd to use 'apply' as a decorator, but it can make sense.

Yes, it's an idiom I've used myself for property declarations, but one
I find myself using less often:

class ColourThing(object):
@apply
def rgb():
def fset(self, rgb):
self.r, self.g, self.b = rgb
def fget(self):
return (self.r, self.g, self.b)
return property(**locals())

Unfortunately, apply() has been removed as a built-in in 3.x. I'm not
sure if it has been relocated to a module somewhere, there's no
mention of such in the docs.

> Without using 'apply' as a decorator one alternative is
>      def tmp():
>          value = []
>          # complicated code
>          return value
>      tags = tmp()
>      del tmp

You can save yourself the tidy up by using the same name for the
function & the label:

def tags():
value = []
# ...
return value
tags = tags()

> Like all uses of decorators, it is simply syntactic sugar.  It allows
> you to see, up front, what is going to happen.  I think, once I get used
> to it, I'll get to like it.

The question is, is it really that useful, or is it just a slight
aesthetic variation? Given that apply(f, args, kwargs) is identical to
f(*args, **kwargs), it's understandable that's apply() isn't seen as
worth keeping in the language.

Why I've personally stopped using it: I've always had the impression
that decorators were intended to provide a convenient and obvious way
of augmenting functions. Having one that automatically executes the
function at definition just runs counter to the behaviour I expect
from a decorator. Especially when direct assignment... foo = foo
() ...is a far more direct and clear way of expressing exactly what is
happening.

But that's all IMO, if you feel it makes your code cleaner and don't
plan on moving to 3.x any time soon (come on in! the water's great!),
go for it :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Object Reference question

2009-08-21 Thread josef
On Aug 21, 4:26 am, Ben Finney  wrote:
> josef  writes:
> > To be clear, Python uses a "Pass By Object Reference" model.
>
> Yes. (I'm glad this concept has propagated to newcomers so well :-)

I found one really good discussion on python semantics versus other
languages. It gave me this gem of a quote:

"When I turn on the TV and see Chuck Norris, though, I know it's only
a reference to Chuck Norris, or I would be blinded.  The only case he
needs is "Pass By Roundhouse Kick"." -Chuckk

>
> > x = 1
> > x becomes the object reference
>
> It becomes *a* reference to that object, independent of any other
> references to that same object.
>
> > while an object is created with the type 'int', value 1, and
> > identifier (id(x)).
>
> Not really “while”. The object creation happens first, then the
> assignment statement binds a reference to that object.
>
> > Doing this with a class, x = myclass(), does the same thing, but with
> > more or less object attributes. Every object has a type and an
> > identifier (id()), according to the Python Language Reference for
> > 2.6.2 section 3.1.
>
> Any expression can be on the right side of the assignment operator. The
> expression will evaluate to some object, which the assignment will then
> bind to the reference on the left side of the assignment operator.
>
> > x in both cases is the object reference.
>
> It is *an* object reference; that is, it's an identifier which refers to
> an object. There's nothing about that identifier that makes it “the (one
> and only) object reference”.
>
> > I would like to use the object to refer to the object reference. If I
> > have a gross misunderstanding, please correct me.
>
> Yes, it's a simple misunderstanding: objects do not, in general, know
> any of the references there may be to them.
>
> > The following is what I would like to do: I have a list of class
> > instances dk = [ a, b, c, d ], where a, b, c, d is an object
> > reference.
>
> Note that, after that list is created, each item in that list is *also*
> a reference to the corresponding object. That is, ‘a’ is a reference to
> an object, and ‘dk[0]’ is a *different* reference to the *same* object.
> The object has no knowledge about those references.

This is surprising. My initial thought is that dk[0] hold the object
reference 'a,' but that wouldn't be true "pass by object reference."
When defining the object reference dk[0], python takes the object
reference 'a,' finds the object MyClass0(), and then assigns the
object identity to dk[0]? Or something close to that.

>
> > Entering dk gives me the object: [MyClass0 instance at 0x,
> > MyClass1 instance at 0x0008, MyClass2 instance at 0x0010 ... ]
>
> This is a hint that, when asked for a string representation, each of the
> objects in that list can say little more than that they are of a
> particular type, and are located at a particular memory address. They do
> not know any of the references to themselves.
>
> > I need the object reference name (a,b,c,d) from dk to use as input for
> > a file.
>
> You'll have to track that yourself.

I'm a bit shocked that there isn't a method for catching object
reference names. I think that something like a = MyClass0(name =
'a', ...) is a bit redundant. Are definitions treated the same way?
How would one print or pass function names?

>
> A good way to keep track of name-to-object mappings is with Python's
> built-in mapping type, ‘dict’::
>
>     dk = {'a': a, 'b': b, 'c': c, 'd': d}
>
> (There are more efficient ways to create a dictionary without such
> repetition, of course, but this is more illustrative of the point.)
>
> You can then get a list (assembled in arbitrary sequence) of just the
> keys, or just the values, or the key-value pairs, from the dict with its
> ‘keys’, ‘values’, and ‘items’ methods respectively::
>
>     >>> dk = {'a': a, 'b': b, 'c': c, 'd': d}
>     >>> dk.keys()
>     ['a', 'c', 'd', 'b']
>     >>> dk.values()
>     [, ,  instance at 0x3717>, ]
>     >>> dk.items()
>     [('b', ), ('c',  0x3462>), ('a',  ), ('d',   0x3717>)]
>
> Each of these is even better used as the iterable for a ‘for’ loop::
>
>     >>> for (key, value) in dk.items():
>     ...     print "Here is item named", key
>     ...     print value

I think I'll just add a 'name' to the classes' init defintion.

>
> > My main focus of this post is: "How do I find and use object reference
> > memory locations?"
>
> You don't. Use the references in your code, forget about the memory
> addresses, and remember that container objects themselves contain
> references, so use them for organising your objects.
>
> --
>  \     “Demagogue: One who preaches doctrines he knows to be untrue to |
>   `\                     men he knows to be idiots.” —Henry L. Mencken |
> _o__)                                                                  |
> Ben Finney

Thanks,

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


Problem with winreg - The object is not a PyHKEY object

2009-08-21 Thread Jamie
My goal is to remotely remove the registry keys for McAfee. I don't
know how winreg handles an exception if a key doesn't exist, but I
setup my script to skip the exception. But it doesn't seem to work
right.. I think the script should be self explanitory, please help!
Please forgive me, but I'm a python newbie.

## SCRIPT ##

import _winreg

print "Removing McAfee registry entries"
hkey = _winreg.ConnectRegistry(r'\
\00439140PC',_winreg.HKEY_LOCAL_MACHINE)
try:
_winreg.DeleteKey('SYSTEM\CurrentControlSet\Enum
\Root','LEGACY_MFEAPFK')
except:
pass

#try:
_winreg.DeleteKey('\SYSTEM\CurrentControlSet\Enum
\Root','LEGACY_MFEAVFK')
#except:
# pass

try:
_winreg.DeleteKey('\SYSTEM\CurrentControlSet\Enum
\Root','LEGACY_MFEBOPK')
except:
pass

try:
_winreg.DeleteKey('\SYSTEM\CurrentControlSet\Enum
\Root','LEGACY_MFEHIDK')
except:
pass

try:
_winreg.DeleteKey('\SYSTEM\CurrentControlSet\Enum
\Root','LEGACY_MFEHIDK01')
except:
pass

try:
_winreg.DeleteKey('\SYSTEM\CurrentControlSet\Enum
\Root','LEGACY_MFERKDK')
except:
pass

try:
_winreg.DeleteKey('\SYSTEM\CurrentControlSet\Enum
\Root','LEGACY_MFETDIK')
except:
pass

try:
_winreg.DeleteKey('\SYSTEM\CurrentControlSet\Enum
\Root','LEGACY_NAIAVFILTER1')
except:
pass

try:
_winreg.DeleteKey('\SYSTEM\CurrentControlSet\Enum
\Root','LEGACY_NAIAVFILTER101')
except:
pass

try:
_winreg.DeleteKey('\SYSTEM\CurrentControlSet\Enum
\Root','LEGACY_MCSHIELD')
except:
pass

try:
_winreg.DeleteKey('\SYSTEM\CurrentControlSet\Enum
\Root','MCTASKMANAGER')
except:
pass

try:
_winreg.DeleteKey('\SOFTWARE','McAfee')
except:
pass

try:
_winreg.DeleteKey('\SOFTWARE','Network Associates')
except:
pass

try:
_winreg.DeleteKey('\SYSTEM\CurrentControlSet\Services','AlertManager')
except:
pass

try:
_winreg.DeleteKey('\SYSTEM\CurrentControlSet
\Services','McAfeeFramework')
except:
pass

try:
_winreg.DeleteKey('\SYSTEM\CurrentControlSet\Services','McShield')
except:
pass

try:
_winreg.DeleteKey('\SYSTEM\CurrentControlSet
\Services','McTaskManager')
except:
pass

try:
_winreg.DeleteKey('\SYSTEM\CurrentControlSet\Services','mfeapfk')
except:
pass

try:
_winreg.DeleteKey('\SYSTEM\CurrentControlSet\Services','mfeavfk')
except:
pass

try:
_winreg.DeleteKey('\SYSTEM\CurrentControlSet\Services','mfebopk')
except:
pass

try:
_winreg.DeleteKey('\SYSTEM\CurrentControlSet\Services','mfehidk')
except:
pass

try:
_winreg.DeleteKey('\SYSTEM\CurrentControlSet\Services','mfehidk01')
except:
pass

try:
_winreg.DeleteKey('\SYSTEM\CurrentControlSet\Services','mferkdk')
except:
pass

try:
_winreg.DeleteKey('\SYSTEM\CurrentControlSet\Services','mfetdik')
except:
pass

try:
_winreg.DeleteKey('\SYSTEM\CurrentControlSet\Services','NaiAvFilter1')
except:
pass

try:
_winreg.DeleteKey('\SYSTEM\CurrentControlSet
\Services','NaiAvFilter101')
except:
pass

## END SCRIPT ##

## OUTPUT ##
Removing McAfee registry entries
Traceback (most recent call last):
File "uninstallMcafee.py", line 11, in 
_winreg.DeleteKey('\SYSTEM\CurrentControlSet\Enum
\Root','LEGACY_MFEAVFK')
TypeError: The object is not a PyHKEY object
## END OUTPUT ##
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Annoying octal notation

2009-08-21 Thread David
Il Thu, 20 Aug 2009 22:24:24 +0200, Johannes Bauer ha scritto:

> David schrieb:
> 
>> If I want an octal I'll use oct()! 
>> 
>> "Explicit is better than implicit..."
> 
> A leading "0" *is* explicit.

It isn't explicit enough, at least IMO.


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


Re: Annoying octal notation

2009-08-21 Thread David
Il Thu, 20 Aug 2009 15:18:35 -0700 (PDT), Mensanator ha scritto:

> (Just kidding! That works in 2.5 also. How are you using it where
> it's coming out wrong? I can see you pulling '012' out of a text
> file and want to calculate with it, but how would you use a
> string without using int()? Passing it to functions that allow
> string representations of numbers?)

Obviously it's not a progamming issue, just a hassle using the interpreter
on command line.

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


Re: Annoying octal notation

2009-08-21 Thread MRAB

David wrote:

Il Thu, 20 Aug 2009 22:24:24 +0200, Johannes Bauer ha scritto:


David schrieb:

If I want an octal I'll use oct()! 


"Explicit is better than implicit..."

A leading "0" *is* explicit.


It isn't explicit enough, at least IMO.


Is this better?

Python 3.1 (r31:73574, Jun 26 2009, 20:21:35) [MSC v.1500 32 bit 
(Intel)] on win

32
Type "help", "copyright", "credits" or "license" for more information.
>>> 010
  File "", line 1
010
  ^

I would've preferred it to be decimal unless there's a prefix:

Python 3.1 (r31:73574, Jun 26 2009, 20:21:35) [MSC v.1500 32 bit 
(Intel)] on win

32
Type "help", "copyright", "credits" or "license" for more information.
>>> 0x10
16
>>> 0o10
8

Ah well, something for Python 4. :-)
--
http://mail.python.org/mailman/listinfo/python-list


Re: PIL and Python

2009-08-21 Thread Michele Petrazzo
catafest wrote:
> I don't extract data from jpegs. I wanna put some data in this
> (copyright of my site) ...
> 

My wrap for freeimage, called freeimagepy :) can't, as now, wrote exif
information on the image, but since freeimage can do it, I think that
it's not so difficult to add this type of feature.
If you have some time for investigate and create a patch, I'll be happy
to include it into the mainline!

Contact me directly if you want to talk of need some help on how do it.

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


Re: Problem with winreg - The object is not a PyHKEY object

2009-08-21 Thread Stephen Hansen
On Fri, Aug 21, 2009 at 9:33 AM, Jamie  wrote:

> My goal is to remotely remove the registry keys for McAfee. I don't
> know how winreg handles an exception if a key doesn't exist, but I
> setup my script to skip the exception. But it doesn't seem to work
> right.. I think the script should be self explanitory, please help!
> Please forgive me, but I'm a python newbie.
>
> ## SCRIPT ##
>
> import _winreg
>
> print "Removing McAfee registry entries"
> hkey = _winreg.ConnectRegistry(r'\
> \00439140PC',_winreg.HKEY_LOCAL_MACHINE)
> try:
> _winreg.DeleteKey('SYSTEM\CurrentControlSet\Enum\Root','LEGACY_MFEAPFK')
> except:
> pass
>

You have to "open" the key first-- the first argument to .DeleteKey is not a
string.

E.g., do:

key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,
r'SYSTEM\CurrentControlSet\Enum\Root')
_winreg.DeleteKey(key, 'LEGACY_MFEAPFK'
_winreg.CloseKey(key)

The above is an example off the top of my head, not actually tested-- But
that's sorta your problem, I believe: .DeleteKey operates on a key /handle/
in its first argument, not a string. The second argument is a string.

HTH,

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


TypeError while checking for permissions with os.access() on windows xp

2009-08-21 Thread ryniek90

I've got some code that checks priviliges on two paths:
First - chosen by user
Second - hardcoded home directory represented by **os.getenv('HOME')** - 
(os.getenv('HOME') works both on Linux and Windows)


Here's the code:
"
def __check_set_perm(self, rd_obj_path, backup_dest):

   try:

   if os.path.exists(rd_obj_path):
   if os.access(rd_obj_path, os.R_OK) != True:
   print "Have no permissions on [%s] for reading 
operation.\nTrying to set them..." % os.path.split(rd_obj_path)[1]

   if not os.path.isdir(rd_obj_path):
   os.chmod(rd_obj_path, stat.S_IREAD)
   else:
   for root, dirs, files in os.walk(rd_obj_path):
   for f in files:
   os.chmod(os.path.join(root, f), 
stat.S_IREAD)
   print "Get permissions for reading on [%s] 
successfully." % os.path.split(rd_obj_path)[1]

   else:
   print "Have permissions on [%s] for reading." % 
os.path.split(rd_obj_path)[1]


   if os.access(backup_dest, os.W_OK) != True:
   print "Have no permissions on [%s] for writing 
operation.\nTrying to set them..." % os.path.split(backup_dest)[1]

   os.chmod(backup_dest, stat.S_IWRITE)
   print "Get permissions for reading on [%s] 
successfully." % os.path.split(backup_dest)[1]

   else:
   print "Have permissions on [%s] for writing." % 
os.path.split(backup_dest)[1]

   else:
   return "Can't find specified path - [%s]." % rd_obj_path
   sys.exit(0)

   except (Except), ex:
   return ex
"


This code is part of my backup script. When script checks for reading 
permission on 'user chosen path' it seems ok, but when it checks for 
writing permissions on 'home directory', (this line: **if 
os.access(backup_dest, os.W_OK) != True**), i get error:

**TypeError: coercing to Unicode: need string or buffer, NoneType found**
The second os.access check fails, but don't know why. When i turned 
os.W_OK to integer, i get the same error.
But when changed os.W_OK or that int to string, i get error that integer 
is required. I'm launching this code on WinXP Prof+SP3, on Administrator 
account. Is it bug in os.acces() or my code is written wrong?
Btw. i kow that os.chmod in windows can set only read-olny flag, so 
later i'll change the line with **os.chmod(path, stat.S_IWRITE)**


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


Re: Python and PHP encryption/decryption

2009-08-21 Thread Piet van Oostrum
> "Diez B. Roggisch"  (DBR) wrote:

>DBR> Jean-Claude Neveu schrieb:
>>> I'm looking for a recommendation about encryption/decryption packages for
>>> Python.
>>> 
>>> I'm working on a project that will require me to store some values in a
>>> database in encrypted format. I'll be storing them from a PHP script and
>>> retrieving them (decrypting them) using Python. I'm currently using PHP's
>>> mcrypt package to encrypt the values, and I'm using AES for encryption,
>>> so something AES-compatible would be ideal. However, the project is at
>>> the development stage so I can easily change how I'm encrypting things in
>>> PHP if there is a compelling reason on the Python side of things to do
>>> so.

>DBR> With PyCrypto[1] you have a wide range of choices, amongst others AES.

>DBR> If that's the best algorithm, or even the best python-package to implement
>DBR> it, I don't know.


>DBR> [1] http://www.dlitz.net/software/pycrypto/

Pycrypto had been stalled in development. The latest release was in
2005. There is now a new developer and that it were the link above goes,
but he has not yet released anything. so you will have to do with the
2005 release.

There is an alternative library: m2crypto
(http://chandlerproject.org/Projects/MeTooCrypto). It is built on top of
OpenSSL which is available for most platforms that have Python whereas
Pycrypto has its own C implementations of crypto algorithms. M2crypto
has a recent release. Also I think because OpenSSL is widely used, its
vulnerabilities are easier detected and corrected, whereas I don't think
that is the case for Pycrypto.

M2crypto is much bigger than you need for this project, however. If that
doesn't bother you I would recommend it.

-- 
Piet van Oostrum 
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: [email protected]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Annoying octal notation

2009-08-21 Thread Mensanator
On Aug 21, 11:40 am, David <[email protected]> wrote:
> Il Thu, 20 Aug 2009 15:18:35 -0700 (PDT), Mensanator ha scritto:
>
> > (Just kidding! That works in 2.5 also. How are you using it where
> > it's coming out wrong? I can see you pulling '012' out of a text
> > file and want to calculate with it, but how would you use a
> > string without using int()? Passing it to functions that allow
> > string representations of numbers?)
>
> Obviously it's not a progamming issue, just a hassle using the interpreter
> on command line.

Aha! Then I WAS right after all. Switch to 3.1 and you'll
soon be cured of that bad habit:

>>> 012 + 012
SyntaxError: invalid token (, line 1)


>
> David

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


Re: Annoying octal notation

2009-08-21 Thread John Nagle

Simon Forman wrote:

On Aug 20, 3:06 pm, David <[email protected]> wrote:

Hi all,

Is there some magic to make the 2.x CPython interpreter to ignore the
annoying octal notation?


No.  You would have to modify and recompile the interpreter. This is
not exactly trivial, see "How to Change Python's Grammar"
http://www.python.org/dev/peps/pep-0306/

However, see "Integer Literal Support and Syntax" 
http://www.python.org/dev/peps/pep-3127/

(Basically in 2.6 and onwards you can use 0oNNN notation.)


Yes, and making lead zeros an error as suggested in PEP 3127 is a good idea.
It will be interesting to see what bugs that flushes out.

In 2009, Unisys finally exited the mainframe hardware business, and the
last of the 36-bit machines, the ClearPath servers, are being phased out.
That line of machines goes back to the UNIVAC 2200 series, and the UNIVAC
1100 series, all the way back to the vacuum-tube UNIVAC 1103 from 1952.
It's the longest running series of computers in history, and code for all
those machines used octal heavily.

And it's over.  We can finally dispense with octal by default.

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


Re: Python on Crays

2009-08-21 Thread Mark Dickinson
On Aug 21, 12:21 am, Carrie Farberow  wrote:
> I am trying to build a statically-linked Python based on directions at:
>
> http://yt.enzotools.org/wiki/CrayXT5Installation
>
> I have tried this on multiple systems.  The first time I attempt to build 
> python, 'make' runs fine but 'make install' fails with the following error:
>
> Sorry: UnicodeError: ("\\N escapes not supported (can't load unicodedata 
> module)",)
>
> Any help regarding the source of this error and possible fixes would be 
> appreciated.

Hmm.  There's not a lot of information to go on here.
What version of Python is this? Python 2.6.2?
Have you tried Googling for that exact error message?

The following issue looks as though it might be relevant:

http://bugs.python.org/issue1594809

especially since it looks as though the directions you linked
to involve messing with the PYTHONPATH environment variable.

If you could post a log somewhere[*] showing the exact commands
that you executed, along with all the output (and especially
all the output from 'make' and 'make install'), that might help
someone diagnose the problem further.

Mark

[*] I'm not sure where, though.  Posting all that output directly
in a newsgroup message might not be considered very friendly.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Object Reference question

2009-08-21 Thread Simon Forman
On Aug 21, 12:12 pm, josef  wrote:
> > > I need the object reference name (a,b,c,d) from dk to use as input for
> > > a file.
>
> > You'll have to track that yourself.
>
> I'm a bit shocked that there isn't a method for catching object
> reference names. I think that something like a = MyClass0(name =
> 'a', ...) is a bit redundant. Are definitions treated the same way?
> How would one print or pass function names?

There's no such thing as "object reference names".  Object references
do not have names.

When you run a piece of code like "a = object()" a string "a" is used
as a key in a dictionary and the value is the "object reference".

Consider:

[None][0] = object()

(Create an anonymous list object with one item in it and immediately
replace that item with an anonymous object instance.)

There's no name to catch.

Objects know nothing about their "enclosing" namespace. So if you want
them to have names you have to explicitly give them name attributes.
(However, this won't affect their enclosing namespaces.)

As Bruno said, think of "foo = something" as shorthand for
"some_namespace_dictionary['foo'] = something".


The two exceptions to this are 'def' and 'class' statements which both
create name->object (key, value) pairs in their current namespace AND
give the objects they create '__name__' attributes (pretty much just
as an aid to debugging.)

In [1]: def foo(): pass
   ...:

In [2]: foo.__name__
Out[2]: 'foo'

In [3]: class foo(): pass
   ...:

In [4]: foo.__name__
Out[4]: 'foo'


> > A good way to keep track of name-to-object mappings is with Python's
> > built-in mapping type, ‘dict’::
>
> >     dk = {'a': a, 'b': b, 'c': c, 'd': d}
>
> > (There are more efficient ways to create a dictionary without such
> > repetition, of course, but this is more illustrative of the point.)
>
> > You can then get a list (assembled in arbitrary sequence) of just the
> > keys, or just the values, or the key-value pairs, from the dict with its
> > ‘keys’, ‘values’, and ‘items’ methods respectively::
>
> >     >>> dk = {'a': a, 'b': b, 'c': c, 'd': d}
> >     >>> dk.keys()
> >     ['a', 'c', 'd', 'b']
> >     >>> dk.values()
> >     [, ,  > instance at 0x3717>, ]
> >     >>> dk.items()
> >     [('b', ), ('c',  > 0x3462>), ('a',  ), ('d',   > 0x3717>)]
>
> > Each of these is even better used as the iterable for a ‘for’ loop::
>
> >     >>> for (key, value) in dk.items():
> >     ...     print "Here is item named", key
> >     ...     print value
>
> I think I'll just add a 'name' to the classes' init defintion.

That's the way to do it. :]

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


convert date time

2009-08-21 Thread Ronn Ross
I'm new to python and I'm getting a date time from a field in the database
that looks like this:
8/2/2009 8:36:16 AM (UTC)

I want to split it into two fields one with the date formatted like this:
-MM-DD  2009-08-02

and the time to be 24 hour or military time. How every you call it. Similar
to this:
15:22:00

I found it easy to truncate off the (UTC), but having trouble converting the
date. Can someone point me in the right direction?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: TypeError while checking for permissions with os.access() on windows xp

2009-08-21 Thread Simon Forman
On Aug 21, 1:33 pm, ryniek90  wrote:
> I've got some code that checks priviliges on two paths:
> First - chosen by user
> Second - hardcoded home directory represented by **os.getenv('HOME')** -
> (os.getenv('HOME') works both on Linux and Windows)
>
> Here's the code:
> "
> def __check_set_perm(self, rd_obj_path, backup_dest):
>
>         try:
>
>             if os.path.exists(rd_obj_path):
>                 if os.access(rd_obj_path, os.R_OK) != True:
>                     print "Have no permissions on [%s] for reading
> operation.\nTrying to set them..." % os.path.split(rd_obj_path)[1]
>                     if not os.path.isdir(rd_obj_path):
>                         os.chmod(rd_obj_path, stat.S_IREAD)
>                     else:
>                         for root, dirs, files in os.walk(rd_obj_path):
>                             for f in files:
>                                 os.chmod(os.path.join(root, f),
> stat.S_IREAD)
>                     print "Get permissions for reading on [%s]
> successfully." % os.path.split(rd_obj_path)[1]
>                 else:
>                     print "Have permissions on [%s] for reading." %
> os.path.split(rd_obj_path)[1]
>
>                 if os.access(backup_dest, os.W_OK) != True:
>                     print "Have no permissions on [%s] for writing
> operation.\nTrying to set them..." % os.path.split(backup_dest)[1]
>                     os.chmod(backup_dest, stat.S_IWRITE)
>                     print "Get permissions for reading on [%s]
> successfully." % os.path.split(backup_dest)[1]
>                 else:
>                     print "Have permissions on [%s] for writing." %
> os.path.split(backup_dest)[1]
>             else:
>                 return "Can't find specified path - [%s]." % rd_obj_path
>                 sys.exit(0)
>
>         except (Except), ex:
>             return ex
> "
>
> This code is part of my backup script. When script checks for reading
> permission on 'user chosen path' it seems ok, but when it checks for
> writing permissions on 'home directory', (this line: **if
> os.access(backup_dest, os.W_OK) != True**), i get error:
> **TypeError: coercing to Unicode: need string or buffer, NoneType found**
> The second os.access check fails, but don't know why. When i turned
> os.W_OK to integer, i get the same error.
> But when changed os.W_OK or that int to string, i get error that integer
> is required. I'm launching this code on WinXP Prof+SP3, on Administrator
> account. Is it bug in os.acces() or my code is written wrong?
> Btw. i kow that os.chmod in windows can set only read-olny flag, so
> later i'll change the line with **os.chmod(path, stat.S_IWRITE)**
>
> Thanks and cheers.

First, some nitpicking: Include the whole traceback when posting about
errors please.  Don't write "if some_boolean_expression != True:"
instead prefer "if not some_boolean_expression:".  Also, in your code
"except (Except), ex: return ex" the parentheses are redundant,
there's no "Except" Exception (unless you created one yourself) and
why are you catching and returning the Exception object?  (Also,
what's that "sys.exit(0)" doing in there? And why exit with 0 if there
was a problem? Exit code 0 means "no problem".)


Second, from what you've said backup_dest must be None:

>>> import os
>>> os.access(None, os.W_OK)

Traceback (most recent call last):
  File "", line 1, in 
os.access(None, os.W_OK)
TypeError: coercing to Unicode: need string or buffer, NoneType found

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


Re: convert date time

2009-08-21 Thread D'Arcy J.M. Cain
On Fri, 21 Aug 2009 14:14:32 -0400
Ronn Ross  wrote:
> I want to split it into two fields one with the date formatted like this:
> -MM-DD  2009-08-02
> 
> and the time to be 24 hour or military time. How every you call it. Similar
> to this:
> 15:22:00
> 
> I found it easy to truncate off the (UTC), but having trouble converting the
> date. Can someone point me in the right direction?

You don't say what database you are using but you may find it simpler
to do the conversion in your SELECT statement.  For example, see
http://www.postgresql.org/docs/8.3/static/functions-formatting.html for
PostgreSQL formatting functions.

-- 
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: Mac OS 9.2

2009-08-21 Thread Tommy Nordgren


On Aug 18, 2009, at 6:04 PM, madzientist wrote:


hi,

i have to work with mac OS 9.2 for legacy reasons...is there a
compiled version of python for this os ? i need to get input about
variable values from the user and then print out some text files that
make use of this input. a gui would be nice, but keyboard based input
would be ok too...

thanks much,

suresh

ps. if there isn't a version of pythn that will work, perhaps you
could suggest some other scripting language for 0S 9.2 ?
--  
http://mail.python.org/mailman/listinfo/python-list
	There was a port (MacPython) of versions 2.3 and 2.3 that worked on  
MacOS 9

Maybe Google will help you locate a copy.
--
What is a woman that you forsake her, and the hearth fire and the home  
acre,
to go with the old grey Widow Maker.  --Kipling, harp song of the Dane  
women

Tommy Nordgren
[email protected]



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


Re: Silly question

2009-08-21 Thread David C Ullrich
On Thu, 20 Aug 2009 17:45:11 -0700, John Machin wrote:

> On Aug 21, 5:33 am, David C Ullrich  wrote:
> 
>> So I'm slow, fine. (There were several times when I was using 1.5.3 and
>> wished they were there - transposing matrices, etc.)
> 
> 1.5.THREE ??

Not sure. 1.SOMETHING. Sorry about the CONFUSION...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: convert date time

2009-08-21 Thread Ronn Ross
On Fri, Aug 21, 2009 at 2:26 PM, D'Arcy J.M. Cain  wrote:

> On Fri, 21 Aug 2009 14:14:32 -0400
> Ronn Ross  wrote:
> > I want to split it into two fields one with the date formatted like this:
> > -MM-DD  2009-08-02
> >
> > and the time to be 24 hour or military time. How every you call it.
> Similar
> > to this:
> > 15:22:00
> >
> > I found it easy to truncate off the (UTC), but having trouble converting
> the
> > date. Can someone point me in the right direction?
>
> You don't say what database you are using but you may find it simpler
> to do the conversion in your SELECT statement.  For example, see
> http://www.postgresql.org/docs/8.3/static/functions-formatting.html for
> PostgreSQL formatting functions.
>
> --
> 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.
>
I apologize I should have made it clear that this date is stored in the db
as a string/varchar. The reason it is stored that way is before it's being
read in from a text file where it is formatted that way.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Using 'apply' as a decorator, to define constants

2009-08-21 Thread Jonathan Fine

alex23 wrote:


Unfortunately, apply() has been removed as a built-in in 3.x. I'm not
sure if it has been relocated to a module somewhere, there's no
mention of such in the docs.


The old use of apply()


You can save yourself the tidy up by using the same name for the
function & the label:

def tags():
value = []
# ...
return value
tags = tags()


I don't like that because there's no hint at
def tags():
that this is /not/ the value of tags.


Like all uses of decorators, it is simply syntactic sugar.  It allows
you to see, up front, what is going to happen.  I think, once I get used
to it, I'll get to like it.


The question is, is it really that useful, or is it just a slight
aesthetic variation? Given that apply(f, args, kwargs) is identical to
f(*args, **kwargs), it's understandable that's apply() isn't seen as
worth keeping in the language.


Yes, I agree with that, completely.


Why I've personally stopped using it: I've always had the impression
that decorators were intended to provide a convenient and obvious way
of augmenting functions. 


Yes, that was the intended use case.


Having one that automatically executes the
function at definition just runs counter to the behaviour I expect
from a decorator. 


I'd expect the name of the decorator to explain what is going on.  If 
apply() were a well known part of the language, that would be fine.



Especially when direct assignment... foo = foo
() ...is a far more direct and clear way of expressing exactly what is
happening.


Actually, I think the decorator approach is clearer.  But that's just my 
opinion, and not with the benefit of a lot of experience.



But that's all IMO, if you feel it makes your code cleaner and don't
plan on moving to 3.x any time soon (come on in! the water's great!),
go for it :)


Thank you for your comments, Alex.  And particularly for telling me that 
apply() is no longer a builtin for Python 3.


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


Re: convert date time

2009-08-21 Thread D'Arcy J.M. Cain
On Fri, 21 Aug 2009 14:43:55 -0400
Ronn Ross  wrote:
> On Fri, Aug 21, 2009 at 2:26 PM, D'Arcy J.M. Cain  wrote:
> > You don't say what database you are using but you may find it simpler
> > to do the conversion in your SELECT statement.  For example, see
> > http://www.postgresql.org/docs/8.3/static/functions-formatting.html for
> > PostgreSQL formatting functions.
> >
> I apologize I should have made it clear that this date is stored in the db
> as a string/varchar. The reason it is stored that way is before it's being
> read in from a text file where it is formatted that way.

You can still save it as a timestamp:

SELECT '8/2/2009 8:36:16 AM (UTC)'::timestamp(0);
  timestamp  
-
 2009-08-02 08:36:16
(1 row)

Your input format is read into PostgreSQL time types directly.  Same
may be true of other databases.

-- 
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: Silly question

2009-08-21 Thread David C Ullrich
On Thu, 20 Aug 2009 16:51:00 -0700, Aahz wrote:

> In article ,
> Benjamin Kaplan   wrote:
>>On Thu, Aug 20, 2009 at 2:13 PM, David C Ullrich
>>wrot= e:
>>>
>>> I just noticed that
>>> sequence[i:j:k]
>>
>>Well, I got some good news and some bad news. According to the docs, it
>>existed in 1.4 but the built-in sequences didn't support it until 2.3.
>>It's not used that often anyway so you haven't been missing much.
> 
> Except that it's canonical for one specific operation:
> 
> 'reverseme'[::-1]

It's like you guys are a bunch of programmers or something:

from math import sqrt

def Primes(n):
  """Return a list of the primes < n"""
  sieve = range(n)
  for k in range(2,int(sqrt(n))+2):
sieve[::k] = [1]*((n+k-1)/k)
  return [p for p in sieve if p > 1]




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


Re: Annoying octal notation

2009-08-21 Thread Derek Martin
John Nagle wrote:
> Yes, and making lead zeros an error as suggested in PEP 3127 is a
> good idea.  It will be interesting to see what bugs that flushes
> out.

James Harris wrote:
> It maybe made sense once but this relic of the past should have been
> consigned to the waste bin of history long ago.

Sigh.  Nonsense.  I use octal notation *every day*, for two extremely
prevalent purposes: file creation umask, and Unix file permissions
(i.e. the chmod() function/command).  

I fail to see how 0O012, or even 0o012 is more intelligible than 012.
The latter reads like a typo, and the former is virtually
indistinguishable from 00012, O0012, or many other combinations that
someone might accidentally type (or intentionally type, having to do
this in dozens of other programming languages).  I can see how 012 can
be confusing to new programmers, but at least it's legible, and the
great thing about humans is that they can be taught (usually).  I for
one think this change is completely misguided.  More than flushing out
bugs, it will *cause* them in ubiquity, requiring likely terabytes of
code to be poured over and fixed.  Changing decades-old behaviors
common throughout a community for the sake of avoiding a minor
inconvenience of the n00b is DUMB.

-- 
Derek D. Martin
http://www.pizzashack.org/
GPG Key ID: 0x81CFE75D



pgp5360ytwKYC.pgp
Description: PGP signature
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Silly question

2009-08-21 Thread David C Ullrich
On Fri, 21 Aug 2009 14:40:30 -0500, David C Ullrich wrote:

> On Thu, 20 Aug 2009 16:51:00 -0700, Aahz wrote:
> 
>> In article ,
>> Benjamin Kaplan   wrote:
>>>On Thu, Aug 20, 2009 at 2:13 PM, David C Ullrich
>>>wrot= e:

 I just noticed that
 sequence[i:j:k]
>>>
>>>Well, I got some good news and some bad news. According to the docs, it
>>>existed in 1.4 but the built-in sequences didn't support it until 2.3.
>>>It's not used that often anyway so you haven't been missing much.
>> 
>> Except that it's canonical for one specific operation:
>> 
>> 'reverseme'[::-1]
> 
> It's like you guys are a bunch of programmers or something:
> 
> from math import sqrt
> 
> def Primes(n):
>   """Return a list of the primes < n""" sieve = range(n)
>   for k in range(2,int(sqrt(n))+2):
> sieve[::k] = [1]*((n+k-1)/k)
>   return [p for p in sieve if p > 1]

Oops. Should have tested that a little more carefully
before posting. No time to fix it right now, customer just
got here. Let's just say we're looking for the primes
between sqrt(n) and n...



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


Re: ncurses getch & unicode (was: decoding keyboard input when using curses)

2009-08-21 Thread Thomas Dickey

On Fri, 21 Aug 2009, Iñigo Serna wrote:


2009/8/21 Thomas Dickey :

On Aug 20, 6:12 pm, Iñigo Serna  wrote:

    c = win.getch()


You're using "getch", not "get_wch" (Python's ncurses binding may/may
not have the latter).
curses getch returns 8-bit values, get_wch would return wider values.


you are right, ncurses binding does not have get_wch, only getch, and
this last is the only one called in ncurses library bindings.


Anyway, I've written a patch to include the get_wch method in the bindings.
See http://bugs.python.org/issue6755


Thanks for the clarification,


no problem (report bugs)


Iñigo



--
Thomas E. Dickey
http://invisible-island.net
ftp://invisible-island.net-- 
http://mail.python.org/mailman/listinfo/python-list


Re: zlib interface semi-broken

2009-08-21 Thread Travis
I've come up with a good test for issue5210 and uploaded it to the bug tracker.

This patch should be ready for inclusion now.
-- 
Obama Nation | My emails do not have attachments; it's a digital signature
that your mail program doesn't understand. | 
http://www.subspacefield.org/~travis/ 
If you are a spammer, please email [email protected] to get blacklisted.


pgpXcFtrYha4u.pgp
Description: PGP signature
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: proposal: add setresuid() system call to python

2009-08-21 Thread travis
On Fri, Jul 17, 2009 at 04:59:53PM -0400, Jean-Paul Calderone wrote:
> On Fri, 17 Jul 2009 15:01:41 -0500, [email protected] wrote:
>> I am suggesting that the setresuid function be added to python,
>> perhaps in the OS module, because it has the clearest semantics for
>> manipulating user ids.  The reason why is best described in the
>> following paper:
>
> Yes, it'd be good for Python to expose setresuid.  The best course of
> action is to file a ticket in the issue tracker.  Things will be sped
> along if you also attach a patch implementing the change. :)

I'm now working on this as issue6758 in the tracker.

Adding the calls to the os module doesn't seem like a good idea to me,
because the calls are not POSIX, and it appears that os maps to
posixmodule.c.

Since the authors of the paper (Wagner et. al.) are proposing a new
set of APIs to make all of this clearer, I'm thinking that I will
create a module specifically for dropping permissions.
-- 
Obama Nation | My emails do not have attachments; it's a digital signature
that your mail program doesn't understand. | 
http://www.subspacefield.org/~travis/ 
If you are a spammer, please email [email protected] to get blacklisted.


pgpty4aw4PVv5.pgp
Description: PGP signature
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Annoying octal notation

2009-08-21 Thread Benjamin Peterson
Simon Forman  gmail.com> writes:

> No.  You would have to modify and recompile the interpreter. This is
> not exactly trivial, see "How to Change Python's Grammar"
> http://www.python.org/dev/peps/pep-0306/

And even that's incorrect. You'd have to modify the tokenizer.



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


Re: 2.6 windows install

2009-08-21 Thread Matimus
On Aug 20, 10:21 am, "Tim Arnold"  wrote:
> Hi,
> I installed python2.6 to a netapp device. I can use it from my local windows
> machine (XP). But others cannot use it from their pcs.
>
> They get this response
> "The system cannot execute the specified program.".
>
> If they double click on python.exe, they get a window
>
> with: This application has failed to start because the application
>
> configuration is incorrect.  Reinstalling the application may fix this
>
> problem.
>
> When I installed it I didn't see any mention of an 'administrators' install,
> it just installed. The permissions on the directories where it installed are
> set wide-open for everyone.
>
> Any ideas on what I'm missing here?
>
> thanks,
> --Tim Arnold

The default windows install puts Python26.dll in \windows\system32. I
haven't tried this, but you could probably fix your install by moving
Python26.dll into the Python26 directory.

That being said, the usual thing to do would be to install it on each
machine.

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


Re: Annoying octal notation

2009-08-21 Thread Benjamin Peterson
Derek Martin  pizzashack.org> writes:

> More than flushing out
> bugs, it will *cause* them in ubiquity, requiring likely terabytes of
> code to be poured over and fixed.

2to3, however, can fix it for you extreme easily.





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


Re: Annoying octal notation

2009-08-21 Thread Derek Martin
On Fri, Aug 21, 2009 at 08:25:45PM +, Benjamin Peterson wrote:
> > More than flushing out bugs, it will *cause* them in ubiquity,
> > requiring likely terabytes of code to be poured over and fixed.
> 
> 2to3, however, can fix it for you extreme easily.

Sure, but that won't stop people who've been writing code for 20 years
from continuing to type octal that way...  Humans can learn fairly
easily, but UN-learning is often much harder, especially when the
behavior to be unlearned is still very commonly in use.

Anyway, whatever.  This change (along with a few of the other
seemingly arbitrary changes in 3.x) is annoying, but Python is still
one of the best languages to code in for any multitude of problems.

-- 
Derek D. Martin
http://www.pizzashack.org/
GPG Key ID: 0x81CFE75D



pgpqtjVMR59uV.pgp
Description: PGP signature
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Annoying octal notation

2009-08-21 Thread Piet van Oostrum
> Derek Martin  (DM) wrote:

>DM> I fail to see how 0O012, or even 0o012 is more intelligible than 012.
>DM> The latter reads like a typo, and the former is virtually
>DM> indistinguishable from 00012, O0012, or many other combinations that
>DM> someone might accidentally type (or intentionally type, having to do
>DM> this in dozens of other programming languages).  

You're right. Either hexadecimal should have been 0h or octal should
have been 0t :=)
-- 
Piet van Oostrum 
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: [email protected]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: 2.6 windows install

2009-08-21 Thread Martin v. Löwis
> The default windows install puts Python26.dll in \windows\system32. I
> haven't tried this, but you could probably fix your install by moving
> Python26.dll into the Python26 directory.

Only the admin installation should do that (for all users). The "just
for me" installation won't.

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


Re: proposal: add setresuid() system call to python

2009-08-21 Thread travis+ml-python
On Mon, Jul 20, 2009 at 04:10:35PM +0200, Hrvoje Niksic wrote:
> To emulate the os-module-type calls, it's better to raise exceptions
> than return negative values:
> 
> > def setresuid(ruid, euid, suid):
> > return _setresuid(__uid_t(ruid), __uid_t(euid), __uid_t(suid))
> 
> def setresuid(ruid, euid, suid):
> res = _setresuid(__uid_t(ruid), __uid_t(euid), __uid_t(suid))
> if res < 0:
> raise OSError('[Errno %d] %s' % (os.errno, errno.strerror(os.errno)))

I am working on a module to implement all of this, but that raise command
won't work in Python 2.6.1; it turns out that os.errno is a module, not
an integer.  Does anyone know how to do what I want (that is, how to access
the errno set in C functions)?
-- 
Obama Nation | My emails do not have attachments; it's a digital signature
that your mail program doesn't understand. | 
http://www.subspacefield.org/~travis/ 
If you are a spammer, please email [email protected] to get blacklisted.


pgpCAmvYfWNJs.pgp
Description: PGP signature
-- 
http://mail.python.org/mailman/listinfo/python-list


IDLE file saving problem

2009-08-21 Thread newb.py
I am learning Python and need to use use IDLE, but I am having a
problem. When I open a new window in IDLE and write my code, all is
well. The coloring works and is very helpful. However, when I save the
file I am working on, all the color disappears. And what is more
frustrating is that when I open the saved file, it opens in TextEdit,
so I have to copy it back into a new IDLE window to work on the code.

If someone could clear up this seemingly simple problem for me, I
would really appreciate it.

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


Re: IDLE file saving problem

2009-08-21 Thread MRAB

newb.py wrote:

I am learning Python and need to use use IDLE, but I am having a
problem. When I open a new window in IDLE and write my code, all is
well. The coloring works and is very helpful. However, when I save the
file I am working on, all the color disappears. And what is more
frustrating is that when I open the saved file, it opens in TextEdit,
so I have to copy it back into a new IDLE window to work on the code.

If someone could clear up this seemingly simple problem for me, I
would really appreciate it.


That happens if you don't provide the extension, eg you save as
"my_script" instead of "my_script.py". (Perhaps IDLE should add the
extension if the user doesn't.)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Annoying octal notation

2009-08-21 Thread MRAB

Piet van Oostrum wrote:

Derek Martin  (DM) wrote:



DM> I fail to see how 0O012, or even 0o012 is more intelligible than 012.
DM> The latter reads like a typo, and the former is virtually
DM> indistinguishable from 00012, O0012, or many other combinations that
DM> someone might accidentally type (or intentionally type, having to do
DM> this in dozens of other programming languages).  


You're right. Either hexadecimal should have been 0h or octal should
have been 0t :=)


I have seen the use of Q/q instead in order to make it clearer. I still
prefer Smalltalk's 16rFF and 8r377.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Three-Phase-Diagrams with matplotlib

2009-08-21 Thread Mark Lawrence

M. Hecht wrote:

Hello,

does anyone know whether it is possible to draw three-phase-diagrams with
matplotlib?

A three-phase-diagram is a triangular diagram applied in chemistry e.g. for
slags where
one has three main components of a chemical substance at the corners and
points or lines 
within the triangle marking different compositions of the substances in

percent, e.g.
in metallurgy 20% Al2O3, 45% CaO and 35% SiO2.



As noone else has responded try the matplotlib users' mailing list, see
http://sourceforge.net/mail/?group_id=80706

--
Kindest regards.

Mark Lawrence.

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


Re: IDLE file saving problem

2009-08-21 Thread r
On Aug 21, 4:10 pm, MRAB  wrote:
[snip]
> That happens if you don't provide the extension, eg you save as
> "my_script" instead of "my_script.py". (Perhaps IDLE should add the
> extension if the user doesn't.)

Yes, and much more needs improvement! I have made many changes already
and i am polishing an "IDLE 3000" for the good people of Pythonia,
stay tuned more to come
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Using 'apply' as a decorator, to define constants

2009-08-21 Thread Jonathan Gardner
On Aug 21, 6:36 am, Jonathan Fine  wrote:
>     �...@apply
>      def tags():
>          value = []
>          # complicated code
>          return value
>

Is this different from:

tags = []
# complicated code

I can see the argument that you are cleaning up a lot of intermediary
variables upon return, though.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Using 'apply' as a decorator, to define constants

2009-08-21 Thread Jonathan Gardner
On Aug 21, 9:09 am, alex23  wrote:
> On Aug 21, 11:36 pm, Jonathan Fine  wrote:
>
> class ColourThing(object):
>     @apply
>     def rgb():
>         def fset(self, rgb):
>             self.r, self.g, self.b = rgb
>         def fget(self):
>             return (self.r, self.g, self.b)
>         return property(**locals())
>

This is brilliant. I am going to use this more often. I've all but
given up on property() since defining "get_foo", "get_bar", etc... has
been a pain and polluted the namespace.


> Unfortunately, apply() has been removed as a built-in in 3.x. I'm not
> sure if it has been relocated to a module somewhere, there's no
> mention of such in the docs.

apply = lambda f: f()

It's one of those functions that is easier to define than import.


> Why I've personally stopped using it: I've always had the impression
> that decorators were intended to provide a convenient and obvious way
> of augmenting functions. Having one that automatically executes the
> function at definition just runs counter to the behaviour I expect
> from a decorator. Especially when direct assignment... foo = foo
> () ...is a far more direct and clear way of expressing exactly what is
> happening.
>

If anyone reads the decorator and doesn't think "this thing below is
defined as the result of this decorator function" then they don't
understand decorators at all.
-- 
http://mail.python.org/mailman/listinfo/python-list


Reading, writing files

2009-08-21 Thread seanm
In the book I am using, they give the following function as an
example:

def copyFile(oldFile, newFile):
f1 = open(oldFile, 'r')
f2 = open(newFile, 'w')
while True:
text = f1.read(50)
if text == "":
break
f2.write(text)
f1.close()
f2.close()
return

My question is why does this function successfully copy a 200
character file, oldFile, to newFile? The line of code that reads, text
= f1.read(50), does not seem to be iterative in any way to me. How is
this fuction succeding in adding each additional set up 50 characters
to the previous set of 50 characters read from oldFile?

How does it even succeed in copying a 25 character file? If oldFile
contains 25 characters, how does the program ever break out of the
'while True:' loop?

I just don't see it.

Again, much thanks to anyone who can clear this up.

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


Help Please

2009-08-21 Thread newb.py
In the book I am using, they give the following function as an
example:

def copyFile(oldFile, newFile):
f1 = open(oldFile, 'r')
f2 = open(newFile, 'w')
while True:
text = f1.read(50)
if text == "":
break
f2.write(text)
f1.close()
f2.close()
return

My question is why does this function successfully copy a 200
character file, oldFile, to newFile? The line of code that reads,
text
= f1.read(50), does not seem to be iterative in any way to me. How is
this fuction succeding in adding each additional set up 50 characters
to the previous set of 50 characters read from oldFile?
How does it even succeed in copying a 25 character file? If oldFile
contains 25 characters, how does the program ever break out of the
'while True:' loop?

I just don't see it.

Again, much thanks to anyone who can clear this up.

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


Re: Reading, writing files

2009-08-21 Thread Albert Hopkins
On Fri, 2009-08-21 at 15:21 -0700, seanm wrote:
> In the book I am using, they give the following function as an
> example:
> 
> def copyFile(oldFile, newFile):
> f1 = open(oldFile, 'r')
> f2 = open(newFile, 'w')
> while True:
> text = f1.read(50)
> if text == "":
> break
> f2.write(text)
> f1.close()
> f2.close()
> return
> 
> My question is why does this function successfully copy a 200
> character file, oldFile, to newFile? The line of code that reads, text
> = f1.read(50), does not seem to be iterative in any way to me. How is
> this fuction succeding in adding each additional set up 50 characters
> to the previous set of 50 characters read from oldFile?

The body of the loop will execute forever (unless cut short by the
"break" statement.  What the loop is essentially doing is reading 50
bytes at a time from f1 and writing it into f2.  When f1 reaches end of
file it will stop returning bytes (if text == "":) the loop is broken
and both files are closed.

> How does it even succeed in copying a 25 character file? If oldFile
> contains 25 characters, how does the program ever break out of the
> 'while True:' loop?
> 
> I just don't see it.

Have you read the documentation for file objects?

During the first iteration of the loop 25 bytes are read from f1. Then
they are written to f2.  During the next iteration there is nothing else
to be read from f1 so f1.read(50) returns "", which causes the loop to
break.

> Again, much thanks to anyone who can clear this up.
> 


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


Re: Help Please

2009-08-21 Thread Albert Hopkins
Why do you post the same question twice within 5 minutes of each other?


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


Re: Reading, writing files

2009-08-21 Thread MRAB

seanm wrote:

In the book I am using, they give the following function as an
example:

def copyFile(oldFile, newFile):
f1 = open(oldFile, 'r')
f2 = open(newFile, 'w')
while True:
text = f1.read(50)


This will read up to 50 characters from the input file. At the end of
the file it'll return an empty string (""). In fact, the only time it'll
return an empty string is at the end of the file.


if text == "":
break
f2.write(text)
f1.close()
f2.close()
return

My question is why does this function successfully copy a 200
character file, oldFile, to newFile? The line of code that reads, text
= f1.read(50), does not seem to be iterative in any way to me. How is
this fuction succeding in adding each additional set up 50 characters
to the previous set of 50 characters read from oldFile?

How does it even succeed in copying a 25 character file? If oldFile
contains 25 characters, how does the program ever break out of the
'while True:' loop?

I just don't see it.

Again, much thanks to anyone who can clear this up.


It reads some characters from the input file and then writes then to the
output file, and because of the 'while' loop it'll repeat action that
until the read returns an empty string, which will be when it has read
all the way to the end of file and tries to read some more.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Object Reference question

2009-08-21 Thread Ben Finney
josef  writes:

> On Aug 21, 4:26 am, Ben Finney  wrote:
> > Note that, after that list is created, each item in that list is
> > *also* a reference to the corresponding object. That is, ‘a’ is a
> > reference to an object, and ‘dk[0]’ is a *different* reference to
> > the *same* object. The object has no knowledge about those
> > references.
>
> This is surprising.

Perhaps so, depending on your initial assumptions. But it's quite
consistent: every time you use an object, you do so via some kind of
reference to that object. Those references are the way you get at the
same object again later.

> My initial thought is that dk[0] hold the object reference 'a,' but
> that wouldn't be true "pass by object reference."

Right. It stores an entirely *separate* reference to that object. The
reference ‘dk[0]’, a list item, and the reference ‘a’, a name, both
refer to the same object. Neither of those references knows anything
about the other.

> When defining the object reference dk[0]

Not “defining”. You're binding (“assigning”, if you like) a reference.

> python takes the object reference 'a,'

More accurately, it takes the object referred to by ‘a’. (Also, please
don't put the comma inside the quotes; it's syntactically significant,
and changes the meaning of what you're writing in code.)

> finds the object MyClass0()

No. ‘MyClass0()’ is syntax for “call MyClass0 and get its return value”.
The return value will be a new instance of the class — a *new* object
every time you use that syntax.

Rather, the object referred to by ‘a’ will be the result of evaluating
the identifier ‘a’. As a shortcut for discussion, you can talk about
“the object ‘a’”, but remember that the only things you're using in the
syntax of your Python code is object *references*, be they identifiers
(names) or some other kind of reference.

> and then assigns the object identity to dk[0]? Or something close to
> that.

You'd do well to read http://effbot.org/zone/python-objects.htm>
for a good, simple coverage of the Python object model.

> I'm a bit shocked that there isn't a method for catching object
> reference names.

Don't be; there is no such thing as an “object reference name”.

A name is an object reference. So is every other way of getting at a
Python object in your code.

> I think that something like a = MyClass0(name = 'a', ...) is a bit
> redundant.

It usually is, yes. Why do you think you need it? The natural way to
handle objects and names together in Python is with a mapping; a ‘dict’
instance.

> Are definitions treated the same way? How would one print or pass
> function names?

Functions are objects like any other, but since they're more likely to
want to know their own name, the name is stored as an attribute::

>>> def frobnicate_nodule(spam):
... """ Frobnicate the spam nodule. """
... 
>>> type(frobnicate_nodule)

>>> frobnicate_nodule.__name__
'frobnicate_nodule'

The fact that the function name is stored in one of those funky
double-underscore names is a big clue that the attribute is special (in
this case, because it gets assigned automatically by the Python
interpreter).

That's not the case for most types, though.

> I think I'll just add a 'name' to the classes' init defintion.

What is the larger problem you're trying to solve, and why do you think
it will be helped by instances knowing a name for themselves?

(Note: an object can never know *all* names for itself, let alone all
the other references to itself; and you must write your program in the
knowledge that no reference to an object has any intrinsic special
status against any of the other references to that object.)

-- 
 \“I spent a lot of money on wine and women, and like a fool I |
  `\ squandered the rest.” —Benny Hill |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Sanitising arguments to shell commands

2009-08-21 Thread Ben Finney
Rick King  writes:

> shlex doesn't handle unicode input though, so, in general, it's not a
> good solution.

Argh. Is there a Python bug tracker number for fixing that? Or is there
a better solution?

-- 
 \ “Pinky, are you pondering what I'm pondering?” “I think so, |
  `\   Brain, but if we have nothing to fear but fear itself, why does |
_o__) Elanore Roosevelt wear that spooky mask?” —_Pinky and The Brain_ |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: proposal: add setresuid() system call to python

2009-08-21 Thread Carl Banks
On Aug 21, 1:50 pm, [email protected] wrote:
> On Mon, Jul 20, 2009 at 04:10:35PM +0200, Hrvoje Niksic wrote:
> > To emulate the os-module-type calls, it's better to raise exceptions
> > than return negative values:
>
> > > def setresuid(ruid, euid, suid):
> > >     return _setresuid(__uid_t(ruid), __uid_t(euid), __uid_t(suid))
>
> > def setresuid(ruid, euid, suid):
> >     res = _setresuid(__uid_t(ruid), __uid_t(euid), __uid_t(suid))
> >     if res < 0:
> >         raise OSError('[Errno %d] %s' % (os.errno, 
> > errno.strerror(os.errno)))
>
> I am working on a module to implement all of this, but that raise command
> won't work in Python 2.6.1; it turns out that os.errno is a module, not
> an integer.  Does anyone know how to do what I want (that is, how to access
> the errno set in C functions)?

You are using ctypes, I presume?  Try replacing raise OSError with
this:

ctypes.pythonapi.PyErr_SetFromErrno(ctypes.py_object(OSError))

Not entirely sure it'll work with Python built with a static library,
but I think it will.


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


Re: Annoying octal notation

2009-08-21 Thread James Harris
On 21 Aug, 20:48, Derek Martin  wrote:

...

> James Harris wrote:
> > It maybe made sense once but this relic of the past should have been
> > consigned to the waste bin of history long ago.
>
> Sigh.  Nonsense.  I use octal notation *every day*, for two extremely
> prevalent purposes: file creation umask, and Unix file permissions
> (i.e. the chmod() function/command).  

You misunderstand. I was saying that taking a leading zero as
indicating octal is archaic. Octal itself is fine where appropriate.

The chmod command doesn't require a leading zero.

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


Re: Silly question

2009-08-21 Thread David C . Ullrich
On Fri, 21 Aug 2009 14:45:55 -0500, David C Ullrich
 wrote:

>[...]
>
>Oops. Should have tested that a little more carefully
>before posting. No time to fix it right now, customer just
>got here. Let's just say we're looking for the primes
>between sqrt(n) and n...

from math import sqrt

def Primes(n):
  """Return a list of the primes < n"""
  sieve = range(n)
  for k in range(2,int(sqrt(n))+2):
  sieve[2*k::k] = [1]*((n-k-1)/k)
  return [p for p in sieve if p > 1]


David C. Ullrich

"Understanding Godel isn't about following his formal proof. 
That would make a mockery of everything Godel was up to."
(John Jones, "My talk about Godel to the post-grads."
in sci.logic.)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Code formatting question: conditional expression

2009-08-21 Thread Aahz
In article <[email protected]>,
Ben Finney   wrote:
>"Diez B. Roggisch"  writes:
>>
>> excessblk = None
>> if total > P.BASE:
>> excessblk = ...
>>
>> You don't lose any vertical space,
>
>I don't see vertical space as such a scarce resource; we don't have an
>imminent newline shortage, to my knowledge. I value it far lower than,
>say, local readability.

We don't have a newline shortage, but we do have a pixel shortage.
-- 
Aahz ([email protected])   <*> http://www.pythoncraft.com/

"I support family values -- Addams family values" --www.nancybuttons.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Annoying octal notation

2009-08-21 Thread James Harris
On 21 Aug, 22:18, MRAB  wrote:
> Piet van Oostrum wrote:
> >> Derek Martin  (DM) wrote:
>
> >> DM> I fail to see how 0O012, or even 0o012 is more intelligible than 012.
> >> DM> The latter reads like a typo, and the former is virtually
> >> DM> indistinguishable from 00012, O0012, or many other combinations that
> >> DM> someone might accidentally type (or intentionally type, having to do
> >> DM> this in dozens of other programming languages).  
>
> > You're right. Either hexadecimal should have been 0h or octal should
> > have been 0t :=)
>
> I have seen the use of Q/q instead in order to make it clearer. I still
> prefer Smalltalk's 16rFF and 8r377.

Two interesting options. In a project I have on I have also considered
using 0q as indicating octal. I maybe saw it used once somewhere else
but I have no idea where. 0t was a second choice and 0c third choice
(the other letters of oct). 0o should NOT be used for obvious reasons.

So you are saying that Smalltalk has r where
r is presumably for radix? That's maybe best of all. It preserves the
syntactic requirement of starting a number with a digit and seems to
have greatest flexibility. Not sure how good it looks but it's
certainly not bad.

  0xff & 0x0e | 0b1101
  16rff & 16r0e | 2r1101

Hmm. Maybe a symbol would be better than a letter.

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


Re: Sanitising arguments to shell commands

2009-08-21 Thread Chris Rebert
On Fri, Aug 21, 2009 at 3:55 PM, Ben Finney wrote:
> Rick King  writes:
>
>> shlex doesn't handle unicode input though, so, in general, it's not a
>> good solution.
>
> Argh. Is there a Python bug tracker number for fixing that?

Indeed there is:
http://bugs.python.org/issue1170

It even has a patch. I wonder why it's unapplied.

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


Re: Annoying octal notation

2009-08-21 Thread Ben Finney
Derek Martin  writes:

> James Harris wrote:
> > It maybe made sense once but this relic of the past should have been
> > consigned to the waste bin of history long ago.
>
> Sigh. Nonsense. I use octal notation *every day*, for two extremely
> prevalent purposes: file creation umask, and Unix file permissions
> (i.e. the chmod() function/command).

Right. Until Unix stops using these (and whatever replaces it would have
to be pretty compelling, given the prevalence of these in octal
notation), or until people stop using Unix, these will be with us and
require octal notation.

That doesn't mean, of course, that we need to elevate it above
hexadecimal in our language syntax; ‘0o012’ will allow octal notation
for literals just fine.

> I fail to see how 0O012, or even 0o012 is more intelligible than 012.
> The latter reads like a typo

No, it reads like a very common notation for decimal numbers in natural
usage. It's very frequently not a typo, but an expression of a
three-digit decimal number that happens to be less than 100.

> and the former is virtually indistinguishable from 00012, O0012, or
> many other combinations that someone might accidentally type (or
> intentionally type, having to do this in dozens of other programming
> languages).

Only if you type the letter in uppercase. The lower-case ‘o’ is much
easier to distinguish.

Whether or not you find ‘0o012’ easily distinguishable as a non-decimal
notation, it's undoubtedly easier to distinguish than ‘012’.

> I can see how 012 can be confusing to new programmers, but at least
> it's legible, and the great thing about humans is that they can be
> taught (usually). I for one think this change is completely misguided.

These human programmers, whether newbies or long-experienced, also deal
with decimal numbers every day, many of which are presented as a
sequence of digits with leading zeros — and we continue to think of them
as decimal numbers regardless. Having the language syntax opposed to
that is a wart, a cognitive overhead with little benefit, and I'll be
glad to see it go in favour of a clearer syntax.

-- 
 \   “… one of the main causes of the fall of the Roman Empire was |
  `\that, lacking zero, they had no way to indicate successful |
_o__)  termination of their C programs.” —Robert Firth |
Ben Finney


pgpMYoSzxQpHv.pgp
Description: PGP signature
-- 
http://mail.python.org/mailman/listinfo/python-list


Invitation to connect on LinkedIn

2009-08-21 Thread Tim Heath
LinkedIn


Tim Heath requested to add you as a connection on LinkedIn:
--

Jaime,

I'd like to add you to my professional network on LinkedIn.

- Tim


View invitation from Tim Heath
http://www.linkedin.com/e/I2LlXdLlWUhFABKmxVOlgGLlWUhFAfhMPPF/blk/I287618177_3/0PnPsTcjwNdzsUcAALqnpPbOYWrSlI/svi/
--

DID YOU KNOW you can be the first to know when a trusted member of your network 
changes jobs? With Network Updates on your LinkedIn home page, you'll be 
notified as members of your network change their current position. Be the first 
to know and reach out!
http://www.linkedin.com/

 
--
(c) 2009, LinkedIn Corporation

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


Re: Annoying octal notation

2009-08-21 Thread Ben Finney
Derek Martin  writes:

> Sure, but that won't stop people who've been writing code for 20 years
> from continuing to type octal that way... Humans can learn fairly
> easily, but UN-learning is often much harder, especially when the
> behavior to be unlearned is still very commonly in use.

This is exactly the argument for removing ‘012’ octal notation: humans
(and programmers who have far less need for octal numbers than for
decimal numbers) are *already* trained, and reinforced many times daily,
to think of that notation as a decimal number. They should not need to
un-learn that association in order to understand octal literals in code.

> Anyway, whatever. This change (along with a few of the other seemingly
> arbitrary changes in 3.x) is annoying, but Python is still one of the
> best languages to code in for any multitude of problems.

Hear hear.

-- 
 \ “I wrote a song, but I can't read music so I don't know what it |
  `\is. Every once in a while I'll be listening to the radio and I |
_o__)say, ‘I think I might have written that.’” —Steven Wright |
Ben Finney


pgp270SOY9qGV.pgp
Description: PGP signature
-- 
http://mail.python.org/mailman/listinfo/python-list


Decompressing gzip over FTP

2009-08-21 Thread SeanMon
Is there a way to decompress a large (2GB) gzipped file being
retrieved over FTP on the fly?

I'm using ftplib.FTP to open a connection to a remote server, and I
have had no success connecting retrbinary to gzip without using an
intermediate file.

Is there any way to get a file-like object describing the remote file,
or a way to utilize gzip's decompression without providing it a file-
like object?

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


Re: Decompressing gzip over FTP

2009-08-21 Thread Christian Heimes

SeanMon schrieb:

Is there a way to decompress a large (2GB) gzipped file being
retrieved over FTP on the fly?

I'm using ftplib.FTP to open a connection to a remote server, and I
have had no success connecting retrbinary to gzip without using an
intermediate file.

Is there any way to get a file-like object describing the remote file,
or a way to utilize gzip's decompression without providing it a file-
like object?


gzip is really just a file format. In order to work with compressed 
streams you should use the low level zlib module.


http://docs.python.org/library/zlib.html#module-zlib

Have fun!

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


Re: Decompressing gzip over FTP

2009-08-21 Thread SeanMon
On Aug 21, 9:40 pm, Christian Heimes  wrote:
> SeanMon schrieb:
>
> > Is there a way to decompress a large (2GB) gzipped file being
> > retrieved over FTP on the fly?
>
> > I'm using ftplib.FTP to open a connection to a remote server, and I
> > have had no success connecting retrbinary to gzip without using an
> > intermediate file.
>
> > Is there any way to get a file-like object describing the remote file,
> > or a way to utilize gzip's decompression without providing it a file-
> > like object?
>
> gzip is really just a file format. In order to work with compressed
> streams you should use the low level zlib module.
>
> http://docs.python.org/library/zlib.html#module-zlib
>
> Have fun!
>
> Christian

Unfortunately, the file on the server is a gzip file, so I cannot
simply pipe the contents into a zlib.decompressobj (which does have
the ability to decompress in chunks, as I wish gzip did!).

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


Questions on XML

2009-08-21 Thread joy99
Dear Group,

I like to convert some simple strings of natural language to XML. May
I use Python to do this? If any one can help me, on this.

I am using primarily UTF-8 based strings, like Hindi or Bengali. Can I
use Python to help me in this regard?

How can I learn good XML aspects of Python. If any one can kindly name
me a book or URL.

I am using Python2.6 on Windows XP with IDLE as GUI.

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


Re: Using 'apply' as a decorator, to define constants

2009-08-21 Thread alex23
Jonathan Gardner  wrote:
> This is brilliant. I am going to use this more often. I've all but
> given up on property() since defining "get_foo", "get_bar", etc... has
> been a pain and polluted the namespace.

Unfortunately I can't remember who I first learned it from - it was
definitely in a post to this group - otherwise all credit would be
their's.

> It's one of those functions that is easier to define than import.

And so obvious now :)

> If anyone reads the decorator and doesn't think "this thing below is
> defined as the result of this decorator function" then they don't
> understand decorators at all.

Well, it's not so much a question of the reader's intelligence as that
Python already has a readily identifiable assignment operator. Having
a second mechanism for assignment with no real similarity to the first
just adds cognitive friction to reading the code...not because the
reader doesn't understand what is happening, but because it's not
obvious _why_ this second form would have been chosen.

Nothing that couldn't be mitigated with a comment, I guess.

# @apply used to prevent having to repeat references

That would work for me.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Using 'apply' as a decorator, to define constants

2009-08-21 Thread Steven D'Aprano
On Fri, 21 Aug 2009 15:17:40 -0700, Jonathan Gardner wrote:

>> Unfortunately, apply() has been removed as a built-in in 3.x. I'm not
>> sure if it has been relocated to a module somewhere, there's no mention
>> of such in the docs.
> 
> apply = lambda f: f()
> 
> It's one of those functions that is easier to define than import.

>>> apply = lambda f: f()
>>> __builtin__.apply(len, 'a')
1
>>> apply(len, 'a')
Traceback (most recent call last):
  File "", line 1, in 
TypeError: () takes exactly 1 argument (2 given)


It's a little bit more difficult to define it *correctly*. Here's a 
working version of apply:


def apply(object, *args, **kwargs):
"""apply(object[, args[, kwargs]]) -> value

Call a callable object with positional and keyword arguments.

>>> apply(max, 'one', 'two', 'three', 'four', key=len)
'three'

"""
return object(*args, **kwargs)

Note that this:

* actually does what apply() is supposed to do;
* defines the function name, useful for tracebacks;
* has a docstring, useful for interactive use and documentation;
* includes an example suitable for automated testing with doctest.



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


Re: Annoying octal notation

2009-08-21 Thread Steven D'Aprano
On Fri, 21 Aug 2009 14:48:57 -0500, Derek Martin wrote:

>> It maybe made sense once but this relic of the past should have been
>> consigned to the waste bin of history long ago.
> 
> Sigh.  Nonsense.  I use octal notation *every day*, for two extremely
> prevalent purposes: file creation umask, and Unix file permissions (i.e.
> the chmod() function/command).

And you will still be able to, by explicitly using octal notation.


> I fail to see how 0O012, or even 0o012 is more intelligible than 012.

The first is wrong, bad, wicked, and if I catch anyone using it, they 
will be soundly slapped with a halibut. *wink*

Using O instead of o for octal is so unreadable that I think it should be 
prohibited by the language, no matter that hex notation accepts both x 
and X.


> The latter reads like a typo, 

*Everything* reads like a typo if you're unaware of the syntax being used.


> and the former is virtually
> indistinguishable from 00012, O0012, or many other combinations that
> someone might accidentally type (or intentionally type, having to do
> this in dozens of other programming languages).

Agreed.


> I can see how 012 can
> be confusing to new programmers, but at least it's legible, and the
> great thing about humans is that they can be taught (usually).

And the great thing is that now you get to teach yourself to stop writing 
octal numbers implicitly and be write them explicitly with a leading 0o 
instead :)

It's not just new programmers -- it's any programmer who is unaware of 
the notation (possibly derived from C) that a leading 0 means "octal". 
That's a strange and bizarre notation to use, because 012 is a perfectly 
valid notation for decimal 12, as are 0012, 00012, 12 and so forth. 
Anyone who has learnt any mathematics beyond the age of six will almost 
certainly expect 012 to equal 12. Having 012 equal 10 comes as a surprise 
even to people who are familiar with octal.


> I for
> one think this change is completely misguided.  More than flushing out
> bugs, it will *cause* them in ubiquity, requiring likely terabytes of
> code to be poured over and fixed.  Changing decades-old behaviors common
> throughout a community for the sake of avoiding a minor inconvenience of
> the n00b is DUMB.

Use of octal isn't common. You've given two cases were octal notation is 
useful, but for every coder who frequently writes umasks on Unix systems, 
there are a thousand who don't.

It's no hardship to write 0o12 instead of 012.


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


Re: Questions on XML

2009-08-21 Thread David Smith
joy99 wrote:
> Dear Group,
> 
> I like to convert some simple strings of natural language to XML. May
> I use Python to do this? If any one can help me, on this.
> 
> I am using primarily UTF-8 based strings, like Hindi or Bengali. Can I
> use Python to help me in this regard?
> 
> How can I learn good XML aspects of Python. If any one can kindly name
> me a book or URL.
> 
> I am using Python2.6 on Windows XP with IDLE as GUI.
> 
> Best Regards,
> Subhabrata.

Take a look at xml.etree.ElementTree package and it's contents.  It's
included in the binary distributions of Python 2.6.  There are lot's of
books out covering XML and UTF-8 is exactly where you want to be w/ XML.

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


Re: 2.6 windows install

2009-08-21 Thread Kevin D . Smith

On 2009-08-21 10:39:09 -0500, "Martin v. Löwis"  said:


Did you install Python to the network device from your XP box? That
would explain why you can run it: the required registry settings &
environment variables are added by the installer, none of which is
occurring on any computer other than the one from which you installed.


In principle, Python doesn't need any registry settings or environment
variables in order to run.


That may be true, but it doesn't explain why python won't run.  I'm 
guessing that it has something to do with the msvc*90.dll files not 
getting installed.  If those dlls haven't been previously installed, 
they won't be on the client machine in order for python to use them.  
However, I haven't had any luck installing these files manually and 
getting python to work that way.


--
Kevin D. Smith

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


Re: 2.6 windows install

2009-08-21 Thread Kevin D . Smith
On 2009-08-21 11:43:31 -0500, Kevin D. Smith 
 said:



On 2009-08-21 10:39:09 -0500, "Martin v. Löwis"  said:


Did you install Python to the network device from your XP box? That
would explain why you can run it: the required registry settings &
environment variables are added by the installer, none of which is
occurring on any computer other than the one from which you installed.


In principle, Python doesn't need any registry settings or environment
variables in order to run.


That may be true, but it doesn't explain why python won't run.  I'm 
guessing that it has something to do with the msvc*90.dll files not 
getting installed.  If those dlls haven't been previously installed, 
they won't be on the client machine in order for python to use them.  
However, I haven't had any luck installing these files manually and 
getting python to work that way.


Installing those files from 
 
does seem to help, but python still gives an error of "The application 
failed to initialize properly (0xc0022)."  I'm not really sure 
where to go from here.


--
Kevin D. Smith

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


Re: Questions on XML

2009-08-21 Thread Rami Chowdhury



I am using primarily UTF-8 based strings, like Hindi or Bengali. Can I
use Python to help me in this regard?


I can say from experience that Python on Windows (at least, Python  
2.5 on 32-bit Vista) works perfectly well with UTF-8 files containing  
Bangla. I have had trouble with working with the data in IDLE,  
however, which seems to prefer ASCII by default.


-
Rami Chowdhury
"Never assume malice when stupidity will suffice." -- Hanlon's Razor
408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD)




On Aug 21, 2009, at 19:15 , joy99 wrote:


Dear Group,

I like to convert some simple strings of natural language to XML. May
I use Python to do this? If any one can help me, on this.

I am using primarily UTF-8 based strings, like Hindi or Bengali. Can I
use Python to help me in this regard?

How can I learn good XML aspects of Python. If any one can kindly name
me a book or URL.

I am using Python2.6 on Windows XP with IDLE as GUI.

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


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


Re: Questions on XML

2009-08-21 Thread Stefan Behnel
Rami Chowdhury wrote:
>> I am using primarily UTF-8 based strings, like Hindi or Bengali. Can I
>> use Python to help me in this regard?
> 
> I can say from experience that Python on Windows (at least, Python 2.5
> on 32-bit Vista) works perfectly well with UTF-8 files containing
> Bangla. I have had trouble with working with the data in IDLE, however,
> which seems to prefer ASCII by default.

Defaults almost never work for encodings. You have to be explicit: add an
encoding declaration to the top of your source file if you use encoded
literal strings in your code; use the codecs module with a suitable
encoding to read encoded text files, and use an XML parser when reading XML.

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


Re: Questions on XML

2009-08-21 Thread Kee Nethery


On Aug 21, 2009, at 7:15 PM, joy99 wrote:


Dear Group,

I like to convert some simple strings of natural language to XML. May
I use Python to do this? If any one can help me, on this.

I am using primarily UTF-8 based strings, like Hindi or Bengali. Can I
use Python to help me in this regard?


As a newbie, the thing that caused me trouble was importing a string  
into the XML parser. The parser seemed to want to open a file and I  
had a string. The solution was one of these:


from xml.etree import ElementTree as et
theXmlDataTree = et.parse(StringIO.StringIO(theXmlString))


from xml.etree import ElementTree as et
theXmlDataTree = et.ElementTree(et.XML(theXmlString))

Not sure which you would use nor what the differences are. I have the  
first set commented out in my code so for some reason I switched to  
the second set of code to take a string and pull it into the XML parser.


Once the string is in the parser, all the examples worked. It was  
getting it into the parser that had me stumped because none of the  
examples showed this situation, it appears to be obvious to someone  
who has used Python for a while.


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


Re: Questions on XML

2009-08-21 Thread joy99
On Aug 22, 10:53 am, Stefan Behnel  wrote:
> Rami Chowdhury wrote:
> >> I am using primarily UTF-8 based strings, like Hindi or Bengali. Can I
> >> use Python to help me in this regard?
>
> > I can say from experience that Python on Windows (at least, Python 2.5
> > on 32-bit Vista) works perfectly well with UTF-8 files containing
> > Bangla. I have had trouble with working with the data in IDLE, however,
> > which seems to prefer ASCII by default.
>
> Defaults almost never work for encodings. You have to be explicit: add an
> encoding declaration to the top of your source file if you use encoded
> literal strings in your code; use the codecs module with a suitable
> encoding to read encoded text files, and use an XML parser when reading XML.
>
> Stefan

Dear Group,
Thanx for your reply. Python works perfectly for Hindi and Bangla with
Win XP. I never had a trouble.
Best Regards,
Subhabrata.
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   >