Re: list/dictionary as case statement ?

2007-01-02 Thread Hendrik van Rooyen
"Stef Mientki" <[EMAIL PROTECTED]> wrote:

> 
> If I'm not mistaken, I read somewhere that you can use 
> function-names/references in lists and/or dictionaries, but now I can't 
> find it anymore.
> 
> The idea is to build a simulator for some kind of micro controller (just 
> as a general practise, I expect it too be very slow ;-).
> 
> opcodes ={
>1: ('MOV', function1, ...),
>2: ('ADD', function2, ),
>3: ('MUL', class3.function3, )
>}
> 
> def function1
># do something complex
> 
> 
> Is this possible ?

the short answer is : "Yes"

a slightly longer answer depends on what you want to do

If you want to write a simple assembler, your dict will look something like:

Mnemonics_to_Opcodes = 
{"MOV": [Functionnameforopcodeandtwooperands,movopcode],
"NOP":[Functionnameforopcodeonly,nopopcode],
"SETB":[Functionnameforopcodeandoneoperand,setbopcode],
"JMP":[Functionnameforopcodeandoneoperand,jmpopcode],
...
}

if you want to write a simulator only that "executes" the hex or binary,
then your dict needs to be something like this:

Opcodes =
{movopcode:[MovFunction,movinstructionlen],
nopopcod:[NopFunction,nopinstructionlen],
setbopcode:[SetbFunction,setbinstructionlen],
jmpopcode:[JmpFunction,jmpinstructionlen],
...
}

and then you write an "instruction fetcher" based on the
Program Counter that uses the length data in the dict and
calls the various functions with the operands as fetched from
memory. The easiest is to make the PC a global...

It works well - and it is surprisingly fast too...
And its easy if the opcodes are all say one byte,
else you need an opcode length field too, and fancier
parsing.

This is not the hassle with this kind of thing - the hassle comes
in trying to simulate the behaviour of the I/O of a real system...

hth - Hendrik


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


Re: Iterate through list two items at a time

2007-01-02 Thread Gerard Flanagan

Dave Dean wrote:

> Hi all,
>   I'm looking for a way to iterate through a list, two (or more) items at a
> time.  Basically...
>
>   myList = [1,2,3,4,5,6]
>
> I'd like to be able to pull out two items at a time - simple examples would
> be:
> Create this output:
> 1 2
> 3 4
> 5 6
>
> Create this list:
> [(1,2), (3,4), (5,6)]
>

A "padding generator" version:

def chunk( seq, size, pad=None ):
'''
Slice a list into consecutive disjoint 'chunks' of
length equal to size. The last chunk is padded if necessary.

>>> list(chunk(range(1,10),3))
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> list(chunk(range(1,9),3))
[[1, 2, 3], [4, 5, 6], [7, 8, None]]
>>> list(chunk(range(1,8),3))
[[1, 2, 3], [4, 5, 6], [7, None, None]]
>>> list(chunk(range(1,10),1))
[[1], [2], [3], [4], [5], [6], [7], [8], [9]]
>>> list(chunk(range(1,10),9))
[[1, 2, 3, 4, 5, 6, 7, 8, 9]]
>>> for X in chunk([],3): print X
>>>
'''
n = len(seq)
mod = n % size
for i in xrange(0, n-mod, size):
yield seq[i:i+size]
if mod:
padding = [pad] * (size-mod)
yield seq[-mod:] + padding

--

Gerard

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


Re: A question about unicode() function

2007-01-02 Thread JTree
hi,
I just removed the unicode() method from my codes.
As John Machin said, I had an wrong understanding of unicode and ascii.

Paul Watson wrote:
> JTree wrote:
> > Thanks everyone!
> >
> > Sorry for my ambiguous question.
> > I changed the codes and now it works fine.
> >
> >
> >
> > JTree wrote:
> >> Hi,all
> >>  I encountered a problem when using unicode() function to fetch a
> >> webpage, I don't know why this happenned.
> >>  My codes and error messages are:
> >>
> >>
> >> Code:
> >> #!/usr/bin/python
> >> #Filename: test.py
> >> #Modified: 2006-12-31
> >>
> >> import cPickle as p
> >> import urllib
> >> import htmllib
> >> import re
> >> import sys
> >>
> >> def funUrlFetch(url):
> >> lambda url:urllib.urlopen(url).read()
> >>
> >> objUrl = raw_input('Enter the Url:')
> >> content = funUrlFetch(objUrl)
> >> content = unicode(content,"gbk")
> >> print content
> >> content.close()
> >>
> >>
> >> error message:
> >>
> >> C:\WINDOWS\system32\cmd.exe /c python test.py
> >> Enter the Url:http://www.msn.com
> >> Traceback (most recent call last):
> >>   File "test.py", line 16, in ?
> >> content = unicode(content,"gbk")
> >> TypeError: coercing to Unicode: need string or buffer, NoneType found
> >> shell returned 1
> >> Hit any key to close this window...
> >>
> >> Any suggestions would be appreciated!
> >>
> >> Thanks!
> 
> So...  How about posting the brief working code?

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


Synchronization methodology

2007-01-02 Thread Chris Ashurst
Hi, I'm coming in from a despised Java background, and I'm having some 
trouble wrapping my head around sharing an object between multiple 
instances of a single class (in simpler terms, I would say imagine a 
simple chat server that has to share a list of connected users to each 
instance of a connected user).

Usually, I would have a synchronized list instantiated inside each 
instance of a client class, which would do the trick, but since there's 
no synchronization in Python, I'm stuck staring at little tests 
involving a standalone non-threaded class instance that holds the list 
of users, and each connected user being passed this instance to be 
"synchronized".

Now, whilst this *works*, it just doesn't feel right, and I would 
appreciate it if anyone has any more Pythonic expressions of this paradigm.

Note that I have looked at Twisted (and I use it for other stuff), but 
I'm wanting to do things at a lower level (because I'm masochistic), and 
I feel like all the fun has been sucked out of programming by basically 
telling Twisted what I want and have it do it for me invisibly.

Thanks!


~Chris

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


Re: Iterate through list two items at a time

2007-01-02 Thread Dave Dean
Thanks for all the fast responses.  I'm particularly a fan of the zip
method, followed closely by the xrange example.  All, of course, are a lot
of help!
Thanks,
Dave


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


Re: Looking for python SIP/MGCP stacks

2007-01-02 Thread Anthony Baxter
On 1/3/07, Jenny Zhao (zhzhao) <[EMAIL PROTECTED]> wrote:
> Thanks Anthony.
>
> I am wondering where I can get Divmod Sine and Shtoom. Are they open
> source ?
>
> Thanks again
> Jenny

http://www.google.com/search?q=divmod+sine
http://www.google.com/search?q=shtoom
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Iterate through list two items at a time

2007-01-02 Thread Jeffrey Froman
Dave Dean wrote:

>  I'm looking for a way to iterate through a list, two (or more) items at a
> time.

Here's a solution, from the iterools documentation. It may not be the /most/
beautiful, but it is short, and scales well for larger groupings:

>>> from itertools import izip
>>> def groupn(iterable, n):
... return izip(* [iter(iterable)] * n)
... 
>>> list(groupn(myList, 2))
[(0, 1), (2, 3), (4, 5), (6, 7), (8, 9), (10, 11)]
>>> list(groupn(myList, 3))
[(0, 1, 2), (3, 4, 5), (6, 7, 8), (9, 10, 11)]
>>> list(groupn(myList, 4))
[(0, 1, 2, 3), (4, 5, 6, 7), (8, 9, 10, 11)]
>>> for a,b in groupn(myList, 2):
... print a, b
... 
0 1
2 3
4 5
6 7
8 9
10 11
>>> 

Jeffrey


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


Re: Iterate through list two items at a time

2007-01-02 Thread Gabriel Genellina

At Tuesday 2/1/2007 22:57, Dave Dean wrote:


  myList = [1,2,3,4,5,6]

I'd like to be able to pull out two items at a time - simple examples would
be:
Create this output:
1 2
3 4
5 6


b=iter(a)
for x in b:
   y=b.next()
   print x,y

b=iter(a)
for x,y in ((item, b.next()) for item in b):
   print x,y


Create this list:
[(1,2), (3,4), (5,6)]


b=iter(a)
[(item, b.next()) for item in b]

Note that they don't behave the same at the corner cases (empty list, 
single item, odd length...)



--
Gabriel Genellina
Softlab SRL 







__ 
Preguntá. Respondé. Descubrí. 
Todo lo que querías saber, y lo que ni imaginabas, 
está en Yahoo! Respuestas (Beta). 
¡Probalo ya! 
http://www.yahoo.com.ar/respuestas 

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

Re: Iterate through list two items at a time

2007-01-02 Thread skip

>> I'm looking for a way to iterate through a list, two (or more) items
>> at a time.  Basically...
>> 
>> myList = [1,2,3,4,5,6]
>> 
>> I'd like to be able to pull out two items at a time...

Dan> def pair_list(list_):
Dan> return [list_[i:i+2] for i in xrange(0, len(list_), 2)]

Here's another way (seems a bit clearer to me, but each person has their own
way of seeing things):

>>> import string
>>> string.letters
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> zip(string.letters[::2], string.letters[1::2])
[('a', 'b'), ('c', 'd'), ..., ('W', 'X'), ('Y', 'Z')]

It extends readily to longer groupings:

>>> zip(string.letters[::3], string.letters[1::3], string.letters[2::3])
[('a', 'b', 'c'), ('d', 'e', 'f'), ('g', 'h', 'i'), ...

Obviously, if your lists are long, you can substitute itertools.izip for
zip.  There's probably some easy way to achieve the same result with
itertools.groupby, but I'm out of my experience there...

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


Re: Iterate through list two items at a time

2007-01-02 Thread bearophileHUGS
Few alternative solutions (other are possible), I usually use a variant
of the first version, inside a partition function, the second variant
is shorter when you don't have a handy partition() function and you
don't want to import modules, and the forth one needs less memory when
the data is very long:

from itertools import izip, islice

data = [1,2,3,4,5,6,7]

for x1, x2 in (data[i:i+2] for i in xrange(0, len(data)/2*2, 2)):
print x1, x2

for x1, x2 in zip(data[::2], data[1::2]):
print x1, x2

for x1, x2 in izip(data[::2], data[1::2]):
print x1, x2

for x1, x2 in izip(islice(data,0,None,2), islice(data,1,None,2)):
print x1, x2

Bye,
bearophile

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


Re: Iterate through list two items at a time

2007-01-02 Thread Dan Bishop
On Jan 2, 7:57 pm, "Dave Dean" <[EMAIL PROTECTED]> wrote:
> Hi all,
>   I'm looking for a way to iterate through a list, two (or more) items at a
> time.  Basically...
>
>   myList = [1,2,3,4,5,6]
>
> I'd like to be able to pull out two items at a time...

def pair_list(list_):
return [list_[i:i+2] for i in xrange(0, len(list_), 2)]

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


Re: Writing more efficient code

2007-01-02 Thread bearophileHUGS
Jon Harrop:
> I think this sort of functionality would be a welcome addition to Python.

I don't know.


> Perhaps it can be written in Python?

Pyparsing and beautifulsoup show that practically useful parsing
modules can be done using Python alone too.
Set module of Python 2.3, translated to C in Python 2.4 and improved in
Python 2.5 shows that sometimes Python is fit to create prototypes that
can be debugged, and whose API can be improved, and they can later
translated to a faster language.
But the decimal module shows that sometimes such translation can become
a bit difficult.
The re module shows that external modules too can be good enough
compared of Perl/Ruby built-in regex syntax.
Beside Python, various much faster languages may be used, like D,
Pyrex, C, or your loved OCaml. Or theoretically even ShedSkin. I think
D may be fit, the "Pyd" Python <-> D bridge is quite good, and it's
improving. And D is reaching version 1.0.
OCaml maybe can be used to produce Python compiled modules, so it can
be a possibility too, but then very few people are able to maintain it,
so maybe it's better to use a more common language (even D is more
common, because its syntax is easy to grasp by C++ programmers).


> What is the easiest way to add such functionality to Python?

I think implementation language isn't the main problem. I think the
definition of the purpose and API are more difficult.
Mathematica allows you to define rules that let the system chose the
right function (among some with the same name) according to the input
pattern or the kind of input. Guido has discussed some about something
similar, the multimethods. There are some ways and tricks to add such
capabilities to Python, but I don't think they are fast and reliable
enough for real programs. Maybe Python 3.0 will change this some.
If you want just to create something like a regular engine that works
on lists, that contains matching rules, rewriting rules and calls to
many user-defined functions, then I think you can do it with Python
(with Psyco if you want) in few lines (a really basic RE on lists can
be defined in about 20 lines, maybe a good system may can be built with
2000-1 lines), but I don't know how much useful it can be, maybe it
can find some purpose (and maybe someone has already written such
module).


> I think that is an excellent idea. Who will pay me? ;-)

I don't know, probably no one. Most people don't even know how to use
such pattern matching programming paradigm. For Python it may become
just an experiment.

Bye,
bearophile

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


Iterate through list two items at a time

2007-01-02 Thread Dave Dean
Hi all,
  I'm looking for a way to iterate through a list, two (or more) items at a 
time.  Basically...

  myList = [1,2,3,4,5,6]

I'd like to be able to pull out two items at a time - simple examples would 
be:
Create this output:
1 2
3 4
5 6

Create this list:
[(1,2), (3,4), (5,6)]

I want the following syntax to work, but sadly it does not:
for x,y in myList:
  print x, y

I can do this with a simple foreach statement in tcl, and if it's easy in 
tcl it's probably not too hard in Python.

Thanks,
Dave 


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


Re: Writing more efficient code

2007-01-02 Thread Jon Harrop
[EMAIL PROTECTED] wrote:
> Jon Harrop:
>> I think most people could pick up the core ideas in a day and start
>> writing working programs.
> 
> Probably I am not that intelligent, I probably need some months :-) But
> that language has many good sides, and one day I'll probably try to
> learn it a bit.

It is very cool, and there are a growing number of resources about these
languages. You might also like to try Microsoft's F#, which runs
under .NET.

>> Mathematica is expensive but learning to use pattern matching is much
>> easier than learning how to write a pattern matcher and much less tedious
>> than reimplementing it yourself all the time (which is exactly what the
>> OP will end up doing).
> 
> I see. This is a very old post of mine, at the bottom there are few
> notes about the Mathematica pattern matching syntax:
> http://groups.google.com/group/comp.lang.python/msg/93ce3e9a08f5e4c7

Yes. Lots of good points. I think this sort of functionality would be a
welcome addition to Python. What is the easiest way to add such
functionality to Python? Perhaps it can be written in Python?

> To avoid reimplementing it yourself all the time then maybe someone
> (you?) can try to write a good pattern matcher for sequences for
> CPython. With such system it may become less important to switch to a
> different language ;-)

I think that is an excellent idea. Who will pay me? ;-)

-- 
Dr Jon D Harrop, Flying Frog Consultancy
Objective CAML for Scientists
http://www.ffconsultancy.com/products/ocaml_for_scientists/index.html?usenet
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: DOS, UNIX and tabs

2007-01-02 Thread Tom Plunket
Peter Decker wrote:

> > Maybe I'm also weird, but I use a variable-pitch font when programming
> > in Python.  So a "tab equals some number of spaces" really isn't useful
> > to me.  My setup is, "tab equals this much space".
> 
> A year ago I would have thought you were weird, but after reading a
> post by Ed Leafe, one of the creators of Dabo about using proportional
> fonts for readability, I thought I'd try it out, thinking that it was
> pretty wacky. Turns out that after a very brief adjustment period, I
> liked it!

Yep, I had a similar experience although a bit more forced.  The editor
that I was using was configured out-of-the-box with variable-pitch, and
I didn't want to bother figuring out how to change it for the quickie
stuff I was writing, then eventually I found that it no longer bothered
me...


-tom!

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


Re: Writing more efficient code

2007-01-02 Thread Jon Harrop
Beliavsky wrote:
> If in the newsgroup comp.lang.x somone asks how to do y, and you
> suggest using language z, without answering their question, which was
> how to do it in x, you will likely just annoy people and perhaps make
> it even less likely that they will try z.

Pattern matching isn't a language.

-- 
Dr Jon D Harrop, Flying Frog Consultancy
Objective CAML for Scientists
http://www.ffconsultancy.com/products/ocaml_for_scientists/index.html?usenet
-- 
http://mail.python.org/mailman/listinfo/python-list


Filename encoding on XP

2007-01-02 Thread kent sin
What encoding does the NTFS store the filename?

I got some downloaded files, some with Chinese filename, I can not
backup them to CD because the name is not accepted.

I use walk, then print the filename, there are some ? in it, but some
Chinese characters were display with no problem. I suspect the
encoding of the filename is not unicode. How do I find out more about
this?

-- 
Sin Hang Kin.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python embedded interpreter: how to initialize the interpreter ?

2007-01-02 Thread Ziga Seilnacht
[EMAIL PROTECTED] wrote:
> Hello,
>
> I've written a C embedded application. I want to open a python gui
> application in my C program but when I do :
>
> PyRun_String( "import gui.py", file_input, pDictionary, pDictionary );
>
> the interpreter emits an error: tkinter module not defined
>
> What script must I load to initialize the embedded python interpreter
> so as I have the same modules in the python command line and in the
> python embedded interpreter ? /usr/lib/python2.4/*.py ??
>
> Yann COLLETTE

Did you call the Py_Initialize() function before trying to execute that
statement? Note also that you might have to Py_SetProgramName(somepath)
before calling Py_Initialize(). See the documentation for details:
http://docs.python.org/ext/embedding.html
http://docs.python.org/api/embedding.html

Hope this helps,
Ziga

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


Re: array of class

2007-01-02 Thread Podi

> > Or more compactly:
> >
> > words = [Word(w) for w in 'this is probably what you want'.split()]
> > print words
>
> I didn't want to introduce yet some more "confusing" stuff !-)

Indeed, the for loop is perfectly fine and totally readable. Let's save
the "confusing stuff" to the Perl folks.

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


Need old pywin32/win32all for Win95

2007-01-02 Thread Bob Greschke
Does anyone have an old version of this?  I've got some old OEM stuff that 
will only handle Win95 because of some custom hardware drivers.  The build 
200 on sourceforge of pywin32 isn't old enough.  I'm trying to get pyserial 
up and running.  Python/Tkinter does OK at 233MHz! :)

Thanks!

Bob


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


Re: array of class

2007-01-02 Thread Bruno Desthuilliers
George Sakkis a écrit :
> Bruno Desthuilliers wrote:
> 
(snip)
>>words = []
>>for w in ['this', 'is', 'probably', 'what', 'you', 'want']:
>>   words.append(Word(w))
>>print words 
> 
> Or more compactly:
> 
> words = [Word(w) for w in 'this is probably what you want'.split()]
> print words

I didn't want to introduce yet some more "confusing" stuff !-)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list/dictionary as case statement ?

2007-01-02 Thread Bruno Desthuilliers
Stef Mientki a écrit :
> 
> If I'm not mistaken, I read somewhere that you can use 
> function-names/references in lists and/or dictionaries, 

Python's functions are objects too - instances of the (builtin) class 
'function'. So yes, you can use them like any other object (store them 
in containers, pass them as arguments, return them from functions etc).


> but now I can't 
> find it anymore.
> 
> The idea is to build a simulator for some kind of micro controller (just 
> as a general practise, I expect it too be very slow ;-).
> 
> opcodes ={
>   1: ('MOV', function1, ...),
>   2: ('ADD', function2, ),
>   3: ('MUL', class3.function3, )
>   }
> 
> def function1
>   # do something complex
> 
> 
> Is this possible ?

Why don't you just try ?

def mov(what, where):
   print "mov() called with %s : %s" % (what, where)

def add(what, towhat):
   print "add() called with %s : %s" % (what, towhat)


opcodes = {
   1: ('MOV', mov),
   2: ('ADD', add),
}

opcodes[1][1](42, 'somewhere')
opcodes[2][1](11, 38)

The third example is a bit less straightforward. Unless class3.function3 
is a classmethod or staticmethod, you'll need an instance of class3, 
either before constructing the 'opcodes' dict or when actually doing the 
call.

class SomeClass(object):
   def some_method(self):
 print "some_method called, self : %s" % self

some_obj = SomeClass()

opcodes[3] = ('MUL', some_obj.some_method)
opcodes[3][1]()

FWIW, using a dict of callables is a common Python idiom to replace the 
switch statement.

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


Re: list/dictionary as case statement ?

2007-01-02 Thread Stef Mientki
> 
> Yes. Functions are (so called) first class objects. You can refer to one 
> by name, and pass that reference around in variables and other data 
> structures.
> 
> That said, your code above won't work as written because function1 is 
> not in existence when you refer to it.
> 
Yes, I just found that out.

Thanks Gary and Grant,
this principle really works like a charm.

cheers,
Stef Mientki

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


Re: A question about unicode() function

2007-01-02 Thread Paul Watson
JTree wrote:
> Thanks everyone!
> 
> Sorry for my ambiguous question.
> I changed the codes and now it works fine.
> 
> 
> 
> JTree wrote:
>> Hi,all
>>  I encountered a problem when using unicode() function to fetch a
>> webpage, I don't know why this happenned.
>>  My codes and error messages are:
>>
>>
>> Code:
>> #!/usr/bin/python
>> #Filename: test.py
>> #Modified: 2006-12-31
>>
>> import cPickle as p
>> import urllib
>> import htmllib
>> import re
>> import sys
>>
>> def funUrlFetch(url):
>> lambda url:urllib.urlopen(url).read()
>>
>> objUrl = raw_input('Enter the Url:')
>> content = funUrlFetch(objUrl)
>> content = unicode(content,"gbk")
>> print content
>> content.close()
>>
>>
>> error message:
>>
>> C:\WINDOWS\system32\cmd.exe /c python test.py
>> Enter the Url:http://www.msn.com
>> Traceback (most recent call last):
>>   File "test.py", line 16, in ?
>> content = unicode(content,"gbk")
>> TypeError: coercing to Unicode: need string or buffer, NoneType found
>> shell returned 1
>> Hit any key to close this window...
>>
>> Any suggestions would be appreciated!
>>
>> Thanks!

So...  How about posting the brief working code?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: array of class

2007-01-02 Thread George Sakkis
Bruno Desthuilliers wrote:

> FWIW, I guess that what you want here may looks like this:
>
> class Word(object):
>def __init__(self, word=''):
>  self._word = word
>def __repr__(self):
>  return "" % (self._word, id(self))
>
>
> words = []
> for w in ['this', 'is', 'probably', 'what', 'you', 'want']:
>words.append(Word(w))
> print words

Or more compactly:

words = [Word(w) for w in 'this is probably what you want'.split()]
print words

George

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


Re: list/dictionary as case statement ?

2007-01-02 Thread Gary Herron
Stef Mientki wrote:
> If I'm not mistaken, I read somewhere that you can use 
> function-names/references in lists and/or dictionaries, but now I can't 
> find it anymore.
>
> The idea is to build a simulator for some kind of micro controller (just 
> as a general practise, I expect it too be very slow ;-).
>
> opcodes ={
>1: ('MOV', function1, ...),
>2: ('ADD', function2, ),
>3: ('MUL', class3.function3, )
>}
>
> def function1
># do something complex
>
>
> Is this possible ?
>
> thanks,
> Stef Mientki
>   

Yes. Functions are (so called) first class objects. You can refer to one 
by name, and pass that reference around in variables and other data 
structures.

That said, your code above won't work as written because function1 is 
not in existence when you refer to it.

Here's some working code which manipulates a reference to a function 
then calls it:

 >>> def fn():
... print "Hello world!"
...
 >>> x = fn
 >>> y = [fn,fn]
 >>> z = {1:fn, 2:fn}
 >>>
 >>> x()
Hello world!
 >>> y[0]()
Hello world!
 >>> y[1]()
Hello world!
 >>> z[1]()
Hello world!
 >>> z[2]()
Hello world!
 >>>

Gary Herron


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


Re: array of class

2007-01-02 Thread Carl Banks

mm wrote:
> How can I do a array of class?
>
> s1=[]  ## this array should hold classes
>
> ## class definition
> class Word:
>word=""
>
>
> ## empty words... INIT
> for i in range(100):  ## 0..99
>s1.append(Wort)
>
> s1[0].word="There"
> s1[1].word="should"
> s1[2].word="be"
> s1[3].word="different"
> s1[4].word="classes"
>
> ... but it's not.

I presume you want an list (not array) of objects (not classes).  In
that case, you're missing parentheses after Word.  You have to call the
class object, same as you'd call a function, so you have to follow it
with parentheses:

s1.append(Word())

You could, in fact, have an array of classes, and there are actually
reasons you might want to do that, but that's pretty advanced.


Carl Banks

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


Re: list/dictionary as case statement ?

2007-01-02 Thread Grant Edwards
On 2007-01-02, Stef Mientki <[EMAIL PROTECTED]> wrote:

> If I'm not mistaken, I read somewhere that you can use 
> function-names/references in lists and/or dictionaries, but
> now I can't find it anymore.
>
> The idea is to build a simulator for some kind of micro
> controller (just as a general practise, I expect it too be
> very slow ;-).
>
> opcodes ={
>1: ('MOV', function1, ...),
>2: ('ADD', function2, ),
>3: ('MUL', class3.function3, )
>}
>
> def function1
># do something complex
>
>
> Is this possible ?

Yes.  

What you're implementing is commonly referred to as a
"dispatcher", and they're often done with a dictionary exactly
as you show.

-- 
Grant Edwards   grante Yow!  I guess you guys got
  at   BIG MUSCLES from doing too
   visi.commuch STUDYING!
-- 
http://mail.python.org/mailman/listinfo/python-list


list/dictionary as case statement ?

2007-01-02 Thread Stef Mientki

If I'm not mistaken, I read somewhere that you can use 
function-names/references in lists and/or dictionaries, but now I can't 
find it anymore.

The idea is to build a simulator for some kind of micro controller (just 
as a general practise, I expect it too be very slow ;-).

opcodes ={
   1: ('MOV', function1, ...),
   2: ('ADD', function2, ),
   3: ('MUL', class3.function3, )
   }

def function1
   # do something complex


Is this possible ?

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


Re: array of class

2007-01-02 Thread Bruno Desthuilliers
mm a écrit :
> 
> How can I do a array of class?

s/array/list/

> s1=[]  ## this array should hold classes
> 
> ## class definition
> class Word:
>   word=""
> 
> 
> ## empty words... INIT
> for i in range(100):  ## 0..99
>   s1.append(Wort)

I guess that s/Wort/Word/

> s1[0].word="There"
> s1[1].word="should"
> s1[2].word="be"
> s1[3].word="different"
> s1[4].word="classes"
> 
> ... but it's not.

Err... Are you sure you really understand what's a class is and how it's 
supposed to be used ?

> 
> print s1
> 
> [,
> ,
> ,
> ,
> ,
> ,
> 
> ---
> 
> Here, this "classes" are all at the same position in memory.

Of course. You created a list of 100 references to the same class.

> So there 
> are no different classes in the array.

How could it be ? When did you put another class in the list ?

> So I access with s1[0], s1[1], s1[2], etc. always the same data.

Of course.

> Any idea?

Yes : read something about OO base concepts like classes and instances, 
then read the Python's tutorial about how these concepts are implemented 
in Python.

FWIW, I guess that what you want here may looks like this:

class Word(object):
   def __init__(self, word=''):
 self._word = word
   def __repr__(self):
 return "" % (self._word, id(self))


words = []
for w in ['this', 'is', 'probably', 'what', 'you', 'want']:
   words.append(Word(w))
print words
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How do I add users using Python scripts on a Linux machine

2007-01-02 Thread Piet van Oostrum
> Sebastian 'lunar' Wiesner <[EMAIL PROTECTED]> (SW) wrote:

>SW> Linux seems to ignore SUID bit on scripts:

The reason is that obeying SUID bits on scripts would be a security risk.
-- 
Piet van Oostrum <[EMAIL PROTECTED]>
URL: http://www.cs.uu.nl/~piet [PGP 8DAE142BE17999C4]
Private email: [EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why does Python never add itself to the Windows path?

2007-01-02 Thread Chris Lambacher
On Tue, Jan 02, 2007 at 09:08:41AM -0800, Ben Sizer wrote:
> Chris Lambacher wrote:
> 
> > On Sat, Dec 30, 2006 at 04:55:09PM -0800, Ben Sizer wrote:
> 
> > > Yet many scripts and applications require parameters, or to be executed
> > > from a certain directory. For example, setup.py. Or the various
> > > turbogears scripts. Or easy_install.
> 
> > Martin's point was that if you need to pass arguments, you can call the 
> > script
> > from the command line like so:
> > setup.py install
> >
> > The python part of the 'python setup.py install' idiom needs to be omitted 
> > on
> > Windows, but that does not mean that the solution is to automatically add it
> > to PATH.
> 
> Firstly, that solution only works for actual Python scripts; it doesn't
> solve the utility scripts that are often installed to the /scripts
> directory. It's a shame that many responses on this thread don't
> address that half of the issue. Am I the only person who installs
> packages that add scripts (not all of which are Python ones)?
Nope, but just adding the scripts directory to the PATH does not solve the
problem.  You also need to either create an executable launcher (.bat  or
.exe) for the script or mess with environment variables to tell Windows to
treat .py files a executable.  This issue is solved in Unix by toggling the
executable bit on the file in the file system.

Easy Install helps the situation by making an executable of the same name as
the script which calls the script.  There has been discussion on the distutils
mailing list about how to put this in the user's path.  No good solution has
been proposed.  If Easy Install were made the default distribution method, or
distutils spawned the ability to handle scripts in a similar manner, I would
be in favour of optionally adding scripts to PATH.  Whether that option is on
by default or not could be debated at that time.

> 
> Secondly, it's still a significant difference from the Unix-based
> installs. 
Its not really.  Unix installs default to being installed to the prefix /usr,
which just happens to put the executable in your path.  It does not modify the
user's path in any way.  If you install to some location that is not in your
path it is your responsibility to add that location to your path or provide an
explicit path.  Some of the problems caused by this are mitigated by the way
Unix identifies executables.
> You're right, the solution doesn't automatically have to be
> adding it to the PATH - but I'm yet to see a good argument for choosing
> not to, apart from "I don't like it when apps do that".
> 
> > The documentation is misleading... time for a but report:
> > http://sourceforge.net/tracker/index.php?func=detail&aid=1626300&group_id=5470&atid=105470
> 
> Fixing the docs is better than nothing, but I believe fixing the
> install to encourage uniform usage across all platforms is preferable,
> and that in this regard the documentation shows how it 'should' work.
> 
> > > There appears to be a freely-available binary at this address that may
> > > suffice:
> > > http://legroom.net/modules.php?op=modload&name=Open_Source&file=index&page=software&app=modpath
> 
> > Unfortunately the Python installer is not an InnoSetup installer.
> 
> The page I linked to is a bit misleading but there is an executable on
> that page. All you then have to do is invoke it with the relevant
> parameter.
Sorry, I saw the Inno version and the AutoIt and did not see the compiled
executable version.  I still think it will be more likely to be accepted if
the code was translated into Python, since shipping another executable will
not be required.
> 
> -- 
> Ben Sizer
> 
> -- 
> http://mail.python.org/mailman/listinfo/python-list
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Unsubscribing from the list

2007-01-02 Thread Dotan Cohen
On 02/01/07, Robert Kern <[EMAIL PROTECTED]> wrote:
> Dotan Cohen wrote:
> > I need to unsubscribe from this list. I've mailed
> > [EMAIL PROTECTED] but that did not unsubscribe me. I've
> > also gone to the list homepage and entered my user information, but
> > that just sent me a message that someone had tried to resubscribe this
> > username. What must one do to unsubscribe from python-list?
>
> Go here:
>
>   http://mail.python.org/mailman/listinfo/python-list
>
> Go to the bottom of the page. Next to the button "Unsubscribe or edit 
> options",
> enter your email address. Click the button. On the next page, click
> "Unsubscribe". Follow the instructions in the email that is sent to you.
>

Thanks. I read that page, got as far as this:
(The subscribers list is only available to the list administrator.)
and decided that there was no futher interest on the page for me. Thanks.

Dotan Cohen

http://what-is-what.com/what_is/xss.html
http://lyricslist.com/lyrics/artist_albums/95/bush.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Some basic newbie questions...

2007-01-02 Thread Kent Johnson
jonathan.beckett wrote:
  I'm just finding it a bit weird that some of the built in functions are
> static, rather than methods of objects (such as len() being used to
> find the length of a list).

Another explanation here:
http://effbot.org/pyfaq/why-does-python-use-methods-for-some-functionality-e-g-list-index-but-functions-for-other-e-g-len-list.htm

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


Remote askopenfilename()

2007-01-02 Thread half . italian
Hi all.

I'm trying to get Tkinter.askopenfilename() to list a directory tree on
a remote computer.  I've got some ideas, but nothing is slapping me in
the face.  Can someone point me in the right direction?

~Sean

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


How to format a number?

2007-01-02 Thread Clodoaldo
I want to format a number with thousands separator to the 'pt_br'
locale.

I'm trying like this:

>>> import locale
>>> locale.setlocale(locale.LC_ALL, ('pt_br', 'ascii'))
'pt_BR.ISO8859-1'
>>> locale.format('%d', 9876, True)
'9876'
>>> locale.localeconv()['thousands_sep']
''
>>> locale.localeconv()['mon_thousands_sep']
'.'

The thousands separator is defined only for the ['mon_thousands_sep']
key and not for the ['thousands_sep'] one. What should be done? Set the
['thousands_sep'] to '.' or somehow build the format string as a
monetary number? If any of the former, how?

Regards, Clodoaldo Pinto Neto

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


Re: Python embedded interpreter: how to initialize the interpreter ?

2007-01-02 Thread [EMAIL PROTECTED]
> >the interpreter emits an error: tkinter module not defined

Capitalize the 't', in Tkinter, its case sensitive.

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


wsdl2py question

2007-01-02 Thread Laszlo Nagy
Hi All!

I just installed ZSI and tried to generate client code for a wsdl. Here 
is the exception I got:

Traceback (most recent call last):
  File "/usr/local/bin/wsdl2py", line 9, in ?
wsdl2py()
  File 
"/usr/local/lib/python2.4/site-packages/ZSI/generate/commands.py", line 
222, in wsdl2py
wsm.writeClient(fd)
  File 
"/usr/local/lib/python2.4/site-packages/ZSI/generate/wsdl2python.py", 
line 211, in writeClient
sd.fromWsdl(service, **kw)
  File 
"/usr/local/lib/python2.4/site-packages/ZSI/generate/wsdl2python.py", 
line 294, in fromWsdl
mw.setUp(soc, port, input=False)
  File 
"/usr/local/lib/python2.4/site-packages/ZSI/generate/wsdl2python.py", 
line 348, in setUp
rpc,literal = soc.isRPC(), soc.isLiteral(input)
  File 
"/usr/local/lib/python2.4/site-packages/ZSI/generate/containers.py", 
line 441, in isLiteral
return IsLiteral(msgrole)
  File 
"/usr/local/lib/python2.4/site-packages/ZSI/generate/containers.py", 
line 65, in IsLiteral
raise ValueError, 'Missing soap:body binding.'
ValueError: Missing soap:body binding.

What does it mean? The wsdl is good for sure, I know other people using 
it from Java and .NET. I do not know too much about SOAP, this is why I 
wanted to generate the python code for my client, but now I'm stuck.

Thanks,

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


Re: array of class

2007-01-02 Thread hg
mm wrote:

> 
> How can I do a array of class?
> 
> s1=[]  ## this array should hold classes
> 
> ## class definition
> class Word:
>word=""
> 
> 
> ## empty words... INIT
> for i in range(100):  ## 0..99
>s1.append(Wort)
> 
> s1[0].word="There"
> s1[1].word="should"
> s1[2].word="be"
> s1[3].word="different"
> s1[4].word="classes"
> 
> ... but it's not.
> 
> 
> print s1
> 
> [,
> ,
> ,
> ,
> ,
> ,
> 
> ---
> 
> Here, this "classes" are all at the same position in memory. So there
> are no different classes in the array.
> 
> So I access with s1[0], s1[1], s1[2], etc. always the same data.
> 
> Any idea?
> 
> --
> Michael


do you mean object ?

your append should be append(Word()) as you need to create instances.

hg



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


array of class

2007-01-02 Thread mm

How can I do a array of class?

s1=[]  ## this array should hold classes

## class definition
class Word:
   word=""


## empty words... INIT
for i in range(100):  ## 0..99
   s1.append(Wort)

s1[0].word="There"
s1[1].word="should"
s1[2].word="be"
s1[3].word="different"
s1[4].word="classes"

... but it's not.


print s1

[,
,
,
,
,
,

---

Here, this "classes" are all at the same position in memory. So there 
are no different classes in the array.

So I access with s1[0], s1[1], s1[2], etc. always the same data.

Any idea?

--
Michael

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


Re: DOS, UNIX and tabs

2007-01-02 Thread Neil Cerutti
On 2007-01-02, Peter Decker <[EMAIL PROTECTED]> wrote:
> On 1/1/07, Tom Plunket <[EMAIL PROTECTED]> wrote:
>> Maybe I'm also weird, but I use a variable-pitch font when
>> programming in Python.  So a "tab equals some number of
>> spaces" really isn't useful to me.  My setup is, "tab equals
>> this much space".
>
> A year ago I would have thought you were weird, but after
> reading a post by Ed Leafe, one of the creators of Dabo about
> using proportional fonts for readability, I thought I'd try it
> out, thinking that it was pretty wacky. Turns out that after a
> very brief adjustment period, I liked it! I've been using
> proportional fonts ever since, and have found only one
> drawback: code that is indented with spaces looks butt-ugly.
> I'm glad I switched to tabs for my code.

I first came accross it in Stroustrup's _The C++ Programming
Language_. I liked the look and the idea immediately, but my
editor of choice (by historical accident) Vim, doesn't yet
support it.

-- 
Neil Cerutti
I've had a wonderful evening, but this wasn't it. --Groucho Marx
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why does Python never add itself to the Windows path?

2007-01-02 Thread Gabriel Genellina

At Tuesday 2/1/2007 13:58, Ben Sizer wrote:


> Notice that there is NO need to alter the system path. You just have
> to tell Windows where python.exe resides; there is a per-application
> path located at
> HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths.

>From what I can tell, that is solely for file associations. If so, it
will work if you type "setup.py install" but not if you type "python
setup.py install". For instance, I have an entry for Firefox in that
part of the registry, but if you try executing "firefox" at the command
line, it fails.


Typing "start firefox" at the command line should work.
It appears that cmd.exe does *not* use ShellExecute to find the 
executable, so this approach doesn't work as expected :(



--
Gabriel Genellina
Softlab SRL 







__ 
Preguntá. Respondé. Descubrí. 
Todo lo que querías saber, y lo que ni imaginabas, 
está en Yahoo! Respuestas (Beta). 
¡Probalo ya! 
http://www.yahoo.com.ar/respuestas 

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

Re: How do I add users using Python scripts on a Linux machine

2007-01-02 Thread Ravi Teja
> >
> > How about invoking scripts with SUID root set?
>
> Linux seems to ignore SUID bit on scripts:

Yes. My bad. The work around was to use native launchers. I don't
remember the details. Perhaps with the interpreter embedded to launch
it in-process and to hard code the script paths (or at least a config
file/script pointing to them) for security.

> Anyway, you should definitely think about security issues. Not all
> people out there are friendly...

I agree. SUID is often risky.

Web applications such as webmin that do administrative functions
through a web interface require extra precautions for security such as
restricting access to specific IPs.

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


Re: How do I add users using Python scripts on a Linux machine

2007-01-02 Thread Sebastian 'lunar' Wiesner
Carsten Haese <[EMAIL PROTECTED]> typed

> On Tue, 2007-01-02 at 17:17 +0100, Sebastian 'lunar' Wiesner wrote:
>> Ravi Teja <[EMAIL PROTECTED]> typed
>> 
>> > 
>> > Ivan Voras wrote:
>> >> Ramdas wrote:
>> >> > Well,
>> >> >
>> >> > I need to add users from a web interface for a web server, which
>> >> > runs only Python. I need to add users, set quotas and in future
>> >> > even look at managing ip tables to limit bandwidth.
>> >> >
>> >> > I know os.system(), but this has to be done through a form entry
>> >> > through a web interface.
>> >> >
>> >> > Anyways thanks, do advise if there more pythonic solutions
>> >>
>> >> What you're looking for is actually a pretty complex thing. You
>> >> *could* in theory manage /etc/passwd (and its "shadow" file) - you
>> >> can find crypto primitives like MD5 and DES on the 'net, but note
>> >> that you must run your script under the 'root' account in order to
>> >> write (and even read!) the passwd database. The same goes for
>> >> using os.system and the built-in OS utility. Be aware of security
>> >> implications if you're running your web server under the root
>> >> account.
>> > 
>> > How about invoking scripts with SUID root set?
>> 
>> Linux seems to ignore SUID bit on scripts:
> 
> I don't think that that has anything to do with Linux or not. The
> script is not the actual executable, hence its suid bit is irrelevant.

I don't think so. From what I know, the script is passed as executable
to the kernel loader, which interprets the shebang and feeds the script
through the correct interpreter. So the kernel loader sees the script
itself as executable instead of the interpreter binary. I've heard of
other Unix systems, which handle this differently (meaning that the
SUID bit on scripts has an effect), but I may be wrong.

> You'd have to set the suid bit on the python executable, but that
> would affect all python scripts, which is probably bad.

It _is_ bad!

-- 
Freedom is always the freedom of dissenters.
  (Rosa Luxemburg)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python2.5 frameobject - how to upgrade?

2007-01-02 Thread skip

Helmut> A personal question: Have you converted from Perl to Python, as
Helmut> well?

Never really needed to.  Anybody hiring me for my Perl expertise would be in
big trouble. ;-)

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


Python Guru needed in San Jose!

2007-01-02 Thread Brent Rogers -X (breroger - Spherion at Cisco)
Start the New Year off with a new Python job! 

Cisco Systems   (San Jose, CA)

Posted 16-Nov-2006

Technical Leader I (759661)

Description

We are looking for a Software Development Engineer who will work in
development of a new Cisco product. Architect and develop high
performance Linux embedded drivers and software. Product implements
networked services delivery including streaming and other real time
protocols. Candidate must have demonstrated deep understanding of Linux
OS and developed networking software on Linux. Work in a startup
environment inside a corporate company.

*   Proven track record of major contributions to successful
commercial Linux Real Time software development efforts. 
*   Strong Linux/Unix background (System Administration background
helpful) 
*   Ability to write scripts in some administrative language (TCL,
Perl, Python, a shell) 
*   A self starter able to work with a minimal supervision 
*   Uses acquired professional knowledge to determine method for
issue resolution. 
*   Uses expertise and creativity for innovative product
recommendation and solutions 

Typically requires BSEE/CS or equivalent with 10+ years relevant
experience in internetworking technologies and applications.

*   Contact: Brent Rogers, Recruiter 
*   Email: [EMAIL PROTECTED] 
*   Phone: 469-255-0254

 

Brent Rogers
Recruiter
Talent Acquisition and Management

[EMAIL PROTECTED]
Phone :469-255-0254
Mobile :469-223-2085


Cisco Systems. Inc.
2200 E. President George Bush 
Richardson, TX, 75082
United States
www.cisco.com/jobs



This e-mail may contain confidential and privileged material for the
sole use of the intended recipient. Any review, use, distribution or
disclosure by others is strictly prohibited. If you are not the intended
recipient (or authorized to receive for the recipient), please contact
the sender by reply e-mail and delete all copies of this message.   
 


 


spacer.gif
Description: spacer.gif


footerHead.gif
Description: footerHead.gif


footer.gif
Description: footer.gif
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: how to use execfile with argument under windows

2007-01-02 Thread Peter Otten
baur79 wrote:

> i need to execute this command line (different source for n times)
> 
> filename.exe -type png -source sourcearg -file filename.png

> i try with python (python script and filename.exe in same directory)

> execfile("filename.exe -type png -source sourcearg -file filename.png")

That does not do what you think it does, see

http://docs.python.org/lib/built-in-funcs.html#l2h-26

You need os.system() or, for more complex applications, the subprocess
module.

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


Re: how to use execfile with argument under windows

2007-01-02 Thread Matimus

>
> error output
> IOError: [Errno 2] No such file or directory:"filename.exe -type png
> -source sourcearg -file filename.png"

Use 'os.system' not 'execfile'. 'execfile' is for executing other
python scripts, not arbitrary command line.

Try this:

import os
...
...
os.system("filename.exe -type png -source sourcearg -file
filename.png")

> try
> execfile("d:\pathto\filename.exe -type png -source sourcearg -file
> filename.png")
>
> error output
> IOError: [Errno 2] No such file or directory:"d:\pathto\filename.exe
> filename.exe -type png -source sourcearg -file filename.png"

be careful with your '\'s they tend to get interpreted as escape
characters. You can prefix the string with an 'r', double them up or
use forward slashes.

One of the following should work:
r"d:\pathto\filename.exe -type png -source sourcearg -file
filename.png"
"d:\\pathto\\filename.exe -type png -source sourcearg -file
filename.png"
"d:/pathto/filename.exe -type png -source sourcearg -file filename.png"

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


Re: DOS, UNIX and tabs

2007-01-02 Thread Peter Decker
On 1/1/07, Tom Plunket <[EMAIL PROTECTED]> wrote:

> Maybe I'm also weird, but I use a variable-pitch font when programming
> in Python.  So a "tab equals some number of spaces" really isn't useful
> to me.  My setup is, "tab equals this much space".

A year ago I would have thought you were weird, but after reading a
post by Ed Leafe, one of the creators of Dabo about using proportional
fonts for readability, I thought I'd try it out, thinking that it was
pretty wacky. Turns out that after a very brief adjustment period, I
liked it! I've been using proportional fonts ever since, and have
found only one drawback: code that is indented with spaces looks
butt-ugly. I'm glad I switched to tabs for my code.

-- 

# p.d.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python2.5 frameobject - how to upgrade?

2007-01-02 Thread Helmut Jarausch
[EMAIL PROTECTED] wrote:
> Helmut> I'd like to install a package ('rekall') which uses
> Helmut> frame->f_nlocals which is no longer contained in frameobject.h.
> 
> Helmut> What's the recommended way to upgrade such an application?
> 
> I suspect PySequence_Length(frame->f_locals) will do the trick.

Yes, thanks, that fixed it,
Happy New Year to you.

A personal question: Have you converted from Perl to Python, as well?

-- 
Helmut Jarausch

Lehrstuhl fuer Numerische Mathematik
RWTH - Aachen University
D 52056 Aachen, Germany
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: Looking for python SIP/MGCP stacks

2007-01-02 Thread Jean-Paul Calderone
On Tue, 2 Jan 2007 09:02:17 -0800, "Jenny Zhao \(zhzhao\)" <[EMAIL PROTECTED]> 
wrote:
>Thanks Anthony.
>
>I am wondering where I can get Divmod Sine and Shtoom. Are they open
>source ?
>

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

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

Shtoom is LGPL.  Sine borrows some code from it, so it is probably LGPL as well.

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


Re: Why does Python never add itself to the Windows path?

2007-01-02 Thread Ben Sizer
Chris Lambacher wrote:

> On Sat, Dec 30, 2006 at 04:55:09PM -0800, Ben Sizer wrote:

> > Yet many scripts and applications require parameters, or to be executed
> > from a certain directory. For example, setup.py. Or the various
> > turbogears scripts. Or easy_install.

> Martin's point was that if you need to pass arguments, you can call the script
> from the command line like so:
> setup.py install
>
> The python part of the 'python setup.py install' idiom needs to be omitted on
> Windows, but that does not mean that the solution is to automatically add it
> to PATH.

Firstly, that solution only works for actual Python scripts; it doesn't
solve the utility scripts that are often installed to the /scripts
directory. It's a shame that many responses on this thread don't
address that half of the issue. Am I the only person who installs
packages that add scripts (not all of which are Python ones)?

Secondly, it's still a significant difference from the Unix-based
installs. You're right, the solution doesn't automatically have to be
adding it to the PATH - but I'm yet to see a good argument for choosing
not to, apart from "I don't like it when apps do that".

> The documentation is misleading... time for a but report:
> http://sourceforge.net/tracker/index.php?func=detail&aid=1626300&group_id=5470&atid=105470

Fixing the docs is better than nothing, but I believe fixing the
install to encourage uniform usage across all platforms is preferable,
and that in this regard the documentation shows how it 'should' work.

> > There appears to be a freely-available binary at this address that may
> > suffice:
> > http://legroom.net/modules.php?op=modload&name=Open_Source&file=index&page=software&app=modpath

> Unfortunately the Python installer is not an InnoSetup installer.

The page I linked to is a bit misleading but there is an executable on
that page. All you then have to do is invoke it with the relevant
parameter.

-- 
Ben Sizer

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


how to use execfile with argument under windows

2007-01-02 Thread baur79
Hi everybody

i need to execute this command line (different source for n times)

filename.exe -type png -source sourcearg -file filename.png


i try with python (python script and filename.exe in same directory)

import os
..
..
execfile("filename.exe -type png -source sourcearg -file filename.png")

error output
IOError: [Errno 2] No such file or directory:"filename.exe -type png
-source sourcearg -file filename.png"

try
execfile("d:\pathto\filename.exe -type png -source sourcearg -file
filename.png")

error output
IOError: [Errno 2] No such file or directory:"d:\pathto\filename.exe
filename.exe -type png -source sourcearg -file filename.png"


please help to solve problem
thanks

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


Re: Why does Python never add itself to the Windows path?

2007-01-02 Thread Thomas Heller
Ben Sizer schrieb:
> Gabriel Genellina wrote:
> 

>> Notice that there is NO need to alter the system path. You just have
>> to tell Windows where python.exe resides; there is a per-application
>> path located at
>> HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths.
>> In order to launch Python just writing "python" at the command
>> prompt, the installer should -instead of playing with the system
>> path- create a new key below App Paths, named "python.exe", and set
>> its default value to the full path of the installed python executable.
>> See
>> http://msdn.microsoft.com/library/en-us/shellcc/platform/shell/programmersguide/shell_basics/shell_basics_extending/fileassociations/fa_perceived_types.asp
> 
>>From what I can tell, that is solely for file associations. If so, it
> will work if you type "setup.py install" but not if you type "python
> setup.py install". For instance, I have an entry for Firefox in that
> part of the registry, but if you try executing "firefox" at the command
> line, it fails.

Not really.  It's for ShellExecute, which is used for the 'run' entry in the
start menu, or when you type 'start firefox' from the command line.

Thomas

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


Re: popen on windows

2007-01-02 Thread hubritic
Thanks for your reply. I figured it out. I was not closing the file
that path pointed to before executing the command. D'oh! So sometimes
it read the file that was created on the previous test run ...

Anyway, for the benefit of anyone who might be googling for a similar
question, what seems to work for running a command in Windows and
having it wait for the command to finish was (after closing the file
before I refer to it) was:

(this is python 2.4.3. I think subprocess was new in 2.4. See
documentation for subprocess module)

from subprocess import Popen
r = Popen(string_with_the_command, shell=True)
r.wait()

Sometimes the hardest part of python is to resist the urge to imagine
that things *must* be complicated and therefore the simpliest possible
solution can't possibly work ...



Daniel Klein wrote:
> On 27 Dec 2006 09:16:53 -0800, "hubritic" <[EMAIL PROTECTED]>
> wrote:
>
> >I am trying to set off commands on Windows 2003 from python.
> >Specifically, I am trying to use diskpart with a script file (pointed
> >to with path).
> >
> >cmd = ["diskpart",  "/s", path]
> >p = Popen(cmd, shell=True)
> >
> >The script is meant to loop through twice. It will do so if I comment
> >out the Popen call and print cmd instead. But when Popen is called, one
> >disk will be formated, but not the next.
>
> What is the value of 'path' ?
> 
> Does the command work from a Windows command prompt ?
> 
> Dan

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


RE: Looking for python SIP/MGCP stacks

2007-01-02 Thread Jenny Zhao (zhzhao)
Thanks Anthony.

I am wondering where I can get Divmod Sine and Shtoom. Are they open
source ?

Thanks again
Jenny 

-Original Message-
From: Anthony Baxter [mailto:[EMAIL PROTECTED] 
Sent: Saturday, December 30, 2006 2:38 AM
To: Jenny Zhao (zhzhao)
Cc: python-list@python.org
Subject: Re: Looking for python SIP/MGCP stacks

> I am using python to write a testing tools, currently this tool only 
> supports skinny protocol. I am planning to add SIP and MGCP support as

> well, wondering if you have written these protocol stacks before which

> can be leveraged from.

There's two I know of - shtoom and Divmod Sine. The latter is a more
complete implementation of SIP and probably what you want to use.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why does Python never add itself to the Windows path?

2007-01-02 Thread Ben Sizer
Gabriel Genellina wrote:

> At Saturday 30/12/2006 21:55, Ben Sizer wrote:
>
> >python setup.py install
> >
> >On Unix, you'd run this command from a shell prompt; on Windows, you
> >have to open a command prompt window (``DOS box'') and do it there; "
> >
> >Pretty much none of the instructions in that part of the docs will work
> >without you altering your path beforehand. Python's cross-platform
> >nature means people rightly expect the same instructions to work on
> >Linux and Windows from a standard installation. Right now, they don't.
>
> Notice that there is NO need to alter the system path. You just have
> to tell Windows where python.exe resides; there is a per-application
> path located at
> HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths.
> In order to launch Python just writing "python" at the command
> prompt, the installer should -instead of playing with the system
> path- create a new key below App Paths, named "python.exe", and set
> its default value to the full path of the installed python executable.
> See
> http://msdn.microsoft.com/library/en-us/shellcc/platform/shell/programmersguide/shell_basics/shell_basics_extending/fileassociations/fa_perceived_types.asp

>From what I can tell, that is solely for file associations. If so, it
will work if you type "setup.py install" but not if you type "python
setup.py install". For instance, I have an entry for Firefox in that
part of the registry, but if you try executing "firefox" at the command
line, it fails.

It also doesn't solve the issue of utility scripts being added to
Python's scripts directory.

-- 
Ben Sizer

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


Re: Python Wrapper for C# Com Object

2007-01-02 Thread Thomas Heller
[EMAIL PROTECTED] schrieb:
> [EMAIL PROTECTED] skrev:
> 
>> Hi,
>>
>> I wish to write a Python wrapper for my C# COM object but am unsure
>> where to start. I have a dll and a tlb file, and I can use this object
>> in C via the following code -
>>
>> // ConsolApp.cpp : Defines the entry point for the console application.
>> //
>> #include "stdafx.h"
>> #include "windows.h"
>> #include "stdio.h"
>> #import "C:\Documents and Settings\X\Mina dokument\Visual Studio
>> 2005\Projects\X_COMObject\X_COMObject\bin\Debug\X_COMObject.tlb"
>> using namespace X_COMObject;
>>
>> int _tmain(int argc, _TCHAR* argv[])
>> {
>>  CoInitialize(NULL);
>>
>>  X_COMObject::XCOM_InterfacePtr p(__uuidof(X_COMObject::XCOM_Class));
>>  XCOM_Interface *X_com_ptr ;
>>  X_com_ptr = p ;
>>  X_com_ptr->SetID(10);
>>  int x = X_com_ptr->GetID();
>>  printf("%d",x);
>>  getchar();
>>
>>  return 0;
>> }
>>
>> Can anyone offer me some tips as to how to do this in Python?
>>
>> Thanks very much for your help,
>>
>> Barry.
> 
> This is what I've done so far, but I know I'm not doing this correctly.
> Can anyone help me out?
> 
> #import pythoncom
> #pythoncom.CoInitialize()

The above is unneeded if you use comtypes as below (and is unneeded
when using pythoncom, as well).

> from comtypes.client import GetModule, CreateObject
> 
> module = GetModule("C:\\Documents and Settings\\X\\Mina
> dokument\\Visual Studio
> 2005\\Projects\\X_COMObject\\X_COMObject\\bin\\Debug\\X_COMObject.tlb")
> 
You don't intantiate the interface, you have to instantiate the COM object.
Something like

  CreateObject("XCOM_Class")

but of course you have to use the correct argument in the call - the progid
of the COM object.
Alternatively you can use the CoClass from the typelibrary, look into the
generated module in the comtypes\gen directory for a class derived from
comtypes.CoClass.

InternetExplorer, for example, can be started in these ways:

# using the progid:
ie = CreateObject("InternetExplorer.Application")

# using the clsid:
ie = CreateObject("{0002DF01---C000-0046}")


# using the coclass from the generated module:
mod = GetModule("shdocvw.dll")
ie = CreateObject(mod.InternetExplorer)

Thomas

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


Re: Why does Python never add itself to the Windows path?

2007-01-02 Thread Chris Lambacher
On Sat, Dec 30, 2006 at 04:55:09PM -0800, Ben Sizer wrote:
> Martin v. L?wis wrote:
> 
> > Ben Sizer schrieb:
> > > I've installed several different versions of Python across several
> > > different versions of MS Windows, and not a single time was the Python
> > > directory or the Scripts subdirectory added to the PATH environment
> > > variable. Every time, I've had to go through and add this by hand, to
> > > have something resembling a usable Python installation. No such
> > > problems on Linux, whether it be Mandrake/Mandriva, Fedora Core, or
> > > Kubuntu. So why is the Windows install half-crippled by default?
> >
> > For several reasons:
> > 1. Python can be used just fine without being on PATH. Python
> >scripts run fine both when double-clicked and when invoked in
> >the command line, and if you want to use an interactive
> >interpreter, you can find it readily on the Start menu.
> 
> Yet many scripts and applications require parameters, or to be executed
> from a certain directory. For example, setup.py. Or the various
> turbogears scripts. Or easy_install.
Martin's point was that if you need to pass arguments, you can call the script
from the command line like so:
setup.py install

The python part of the 'python setup.py install' idiom needs to be omitted on
Windows, but that does not mean that the solution is to automatically add it
to PATH.

> > 2. Many windows users (including myself) dislike setup routines that
> >manipulate PATH.
> 
> My opinion is that this is not as big a problem as some may feel that
> it is. Unlike Unix systems, the PATH variable is rarely used. Most
> applications are launched via the Start Menu, which uses absolute
> paths, or via file associations, also done via absolute paths. The
> chance of a naming collision only really arises when you start using
> the command line, which most people don't do.
> 
> However, among those who will use the command line, are some people new
> to Python, who will come across instructions like this:
> 
> 
> 
> 
> Pretty much none of the instructions in that part of the docs will work
> without you altering your path beforehand. Python's cross-platform
> nature means people rightly expect the same instructions to work on
> Linux and Windows from a standard installation. Right now, they don't.

The documentation is misleading... time for a but report:
http://sourceforge.net/tracker/index.php?func=detail&aid=1626300&group_id=5470&atid=105470

> > if Python is to be found in PATH, it
> >should rather be installed to a directory that is known to live
> >on PATH (or where CreateProcess searches, anyway, such
> >as system32). So if the installer had such a feature, it should
> >be optional, and it should default to "off".
> 
> It's a lot more anti-social to install to system32 than to modify the
> PATH variable. How easy is it to temporarily undo an installation to a
> system directory like that? What if you still want Python in your path
> but with less precedence than some other user directory?
I agree an optional add to PATH, should just add to the path rather than
install python.exe into a location on the path.
> 
> > 3. Most importantly: it is difficult to implement, and nobody has
> >contributed code to make it work.
> 
> There appears to be a freely-available binary at this address that may
> suffice:
> http://legroom.net/modules.php?op=modload&name=Open_Source&file=index&page=software&app=modpath
Unfortunately the Python installer is not an InnoSetup installer.  If you
converted this code to Python you might get farther since the MSI could call
an add2path script with the newly installed Python executable.  I am sure
submitting a patch for the installer option would also help your cause.

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


Re: How do I add users using Python scripts on a Linux machine

2007-01-02 Thread Carsten Haese
On Tue, 2007-01-02 at 17:17 +0100, Sebastian 'lunar' Wiesner wrote:
> Ravi Teja <[EMAIL PROTECTED]> typed
> 
> > 
> > Ivan Voras wrote:
> >> Ramdas wrote:
> >> > Well,
> >> >
> >> > I need to add users from a web interface for a web server, which
> >> > runs only Python. I need to add users, set quotas and in future
> >> > even look at managing ip tables to limit bandwidth.
> >> >
> >> > I know os.system(), but this has to be done through a form entry
> >> > through a web interface.
> >> >
> >> > Anyways thanks, do advise if there more pythonic solutions
> >>
> >> What you're looking for is actually a pretty complex thing. You
> >> *could* in theory manage /etc/passwd (and its "shadow" file) - you
> >> can find crypto primitives like MD5 and DES on the 'net, but note
> >> that you must run your script under the 'root' account in order to
> >> write (and even read!) the passwd database. The same goes for using
> >> os.system and the built-in OS utility. Be aware of security
> >> implications if you're running your web server under the root
> >> account.
> > 
> > How about invoking scripts with SUID root set?
> 
> Linux seems to ignore SUID bit on scripts:

I don't think that that has anything to do with Linux or not. The script
is not the actual executable, hence its suid bit is irrelevant. You'd
have to set the suid bit on the python executable, but that would affect
all python scripts, which is probably bad.

-Carsten


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


Re: trees, iterations and adding leaves

2007-01-02 Thread Gabriel Genellina

At Sunday 31/12/2006 14:25, vertigo wrote:


I use nltk package - but it should not matter here.


Yes, it does. The framework should provide some form of tree traversal.


So i wanted to 'travel thru my tree' to last node which should be changed:
>>> tree6 = Tree('main', ['sub1', 'sub2'])
>>> subtree = tree6[0]
>>> subtree
'sub1'
>>> subtree = Tree('newsub',[])
>>> subtree
('newsub': )
>>> tree6
('main': 'sub1' 'sub2')
The problem is that subtree is some kind of a new variable (not pointer)
so changing it i will not alter tree6.


This, yes, is a general Python question. When you bind something to 
the name "subtree", it doesn't matter what were "subtree" pointing to 
before. Read http://effbot.org/zone/python-objects.htm



How to alter tree6 while
'travelling along it's nodes',
without messy referencing as tree6[0][1][0][1][1][1][0].. ?


Without any further knowledge of the Tree objects, you could do 
something like this:


def traverse_tree(tree, *ids):
result = tree
while ids:
key = ids.pop(0)
tree = tree[key]
return tree

and say: traverse_tree(tree6, 0, 1, 0, 1, 1, 1, 0) or 
traverse_tree(tree6, *[0,1,0,1,1,1,0]) or traverse_tree(tree6, 
*[0,1,0,1,1])[0] = another_object



--
Gabriel Genellina
Softlab SRL 







__ 
Preguntá. Respondé. Descubrí. 
Todo lo que querías saber, y lo que ni imaginabas, 
está en Yahoo! Respuestas (Beta). 
¡Probalo ya! 
http://www.yahoo.com.ar/respuestas 

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

Re: How do I add users using Python scripts on a Linux machine

2007-01-02 Thread Sebastian 'lunar' Wiesner
Ravi Teja <[EMAIL PROTECTED]> typed

> 
> Ivan Voras wrote:
>> Ramdas wrote:
>> > Well,
>> >
>> > I need to add users from a web interface for a web server, which
>> > runs only Python. I need to add users, set quotas and in future
>> > even look at managing ip tables to limit bandwidth.
>> >
>> > I know os.system(), but this has to be done through a form entry
>> > through a web interface.
>> >
>> > Anyways thanks, do advise if there more pythonic solutions
>>
>> What you're looking for is actually a pretty complex thing. You
>> *could* in theory manage /etc/passwd (and its "shadow" file) - you
>> can find crypto primitives like MD5 and DES on the 'net, but note
>> that you must run your script under the 'root' account in order to
>> write (and even read!) the passwd database. The same goes for using
>> os.system and the built-in OS utility. Be aware of security
>> implications if you're running your web server under the root
>> account.
> 
> How about invoking scripts with SUID root set?

Linux seems to ignore SUID bit on scripts:

[EMAIL PROTECTED]:03:23] >> ~/test
--> cat uidtest.py
#!/usr/bin/python
import os

print 'uid:', os.getuid()
print 'effective uid:', os.geteuid()
os.system('whoami')

[EMAIL PROTECTED]:03:28] >> ~/test
--> ls -l uidtest.py
-rwsr-xr-x 1 root root 112 2007-01-02 17:03 uidtest.py

[EMAIL PROTECTED]:03:46] >> ~/test
--> /home/lunar/test/uidtest.py
uid: 1000
effective uid: 1000
lunar

Anyway, you should definitely think about security issues. Not all
people out there are friendly...

-- 
Freedom is always the freedom of dissenters.
  (Rosa Luxemburg)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Unsubscribing from the list

2007-01-02 Thread Robert Kern
Dotan Cohen wrote:
> I need to unsubscribe from this list. I've mailed
> [EMAIL PROTECTED] but that did not unsubscribe me. I've
> also gone to the list homepage and entered my user information, but
> that just sent me a message that someone had tried to resubscribe this
> username. What must one do to unsubscribe from python-list?

Go here:

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

Go to the bottom of the page. Next to the button "Unsubscribe or edit options",
enter your email address. Click the button. On the next page, click
"Unsubscribe". Follow the instructions in the email that is sent to you.

-- 
Robert Kern

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

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


Re: How do I add users using Python scripts on a Linux machine

2007-01-02 Thread Jan Dries
Ivan Voras wrote:
> Ramdas wrote:
>> Well,
>>
>> I need to add users from a web interface for a web server, which runs
>> only Python. I need to add users, set quotas and in future even look at
>> managing ip tables to limit bandwidth.
>>
>> I know os.system(), but this has to be done through a form entry
>> through a web interface.
>>
>> Anyways thanks, do advise if there more pythonic solutions
> 
> What you're looking for is actually a pretty complex thing. You *could*
> in theory manage /etc/passwd (and its "shadow" file) - you can find
> crypto primitives like MD5 and DES on the 'net, but note that you must
> run your script under the 'root' account in order to write (and even
> read!) the passwd database. The same goes for using os.system and the
> built-in OS utility. Be aware of security implications if you're running
> your web server under the root account.

A solution that is both more pythonic and avoids the problems listed 
above would be to migrate user management from /etc/passwd to an LDAP 
(though pam_ldap). That's the approach I took in a similar situation. 
Sure, it adds the overhead of setting up and running an LDAP, but 
managing users and their quota through python_ldap is much cleaner and 
more flexible than doing so using os.system(), certainly from within a 
web application.
That doesn't alter the fact though that security must be properly 
considered in any application that can add users.

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


Re: Python embedded interpreter: how to initialize the interpreter ?

2007-01-02 Thread Gabriel Genellina

At Sunday 31/12/2006 10:55, [EMAIL PROTECTED] wrote:


I've written a C embedded application. I want to open a python gui
application in my C program but when I do :

PyRun_String( "import gui.py", file_input, pDictionary, pDictionary );

the interpreter emits an error: tkinter module not defined


Does it work if you try it from the interpreter?


--
Gabriel Genellina
Softlab SRL 







__ 
Preguntá. Respondé. Descubrí. 
Todo lo que querías saber, y lo que ni imaginabas, 
está en Yahoo! Respuestas (Beta). 
¡Probalo ya! 
http://www.yahoo.com.ar/respuestas 

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

Re: Convert Perl to Python

2007-01-02 Thread Bruno Desthuilliers
Marc 'BlackJack' Rintsch a écrit :
> In <[EMAIL PROTECTED]>,
> Χρυσάνθη Αϊναλή wrote:
> 
> 
>>How can I convert a perl script to Python?
> 
> 
> Look what the Perl script does and then rewrite it in Python.  Automatic
> translations between programming languages, if possible, usually result in
> code that is not supposed to be read by human beings.  Every language has
> its idioms and a "literal" translation looks very odd to "native speakers"
> of the target language.

and might be quite inefficient too...

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

Re: Newbie query about secure embedded python

2007-01-02 Thread Paul Rubin
Richard Dwan <[EMAIL PROTECTED]> writes:
> My question is; is there a secure python interpreter
> that prevents malicious code from using C/C++ modules
> or built-in functions from causing damage to a users
> system.

You mean like a java sandbox?  There used to be one in Python (the
rexec/Bastion modules) but they were removed for security reasons
(i.e. they weren't secure and there was no way to fix the holes).
There seems to currently be no really reliable way to do what you're
asking.  Your best bet may be either a small JVM, or a very limited
special purpose language that you could implement in Python.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How do I add users using Python scripts on a Linux machine

2007-01-02 Thread Ravi Teja

Ivan Voras wrote:
> Ramdas wrote:
> > Well,
> >
> > I need to add users from a web interface for a web server, which runs
> > only Python. I need to add users, set quotas and in future even look at
> > managing ip tables to limit bandwidth.
> >
> > I know os.system(), but this has to be done through a form entry
> > through a web interface.
> >
> > Anyways thanks, do advise if there more pythonic solutions
>
> What you're looking for is actually a pretty complex thing. You *could*
> in theory manage /etc/passwd (and its "shadow" file) - you can find
> crypto primitives like MD5 and DES on the 'net, but note that you must
> run your script under the 'root' account in order to write (and even
> read!) the passwd database. The same goes for using os.system and the
> built-in OS utility. Be aware of security implications if you're running
> your web server under the root account.

How about invoking scripts with SUID root set?

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


Re: Can I beat perl at grep-like processing speed?

2007-01-02 Thread Bruno Desthuilliers
js a écrit :
> Just my curiosity.
> Can python beats perl at speed of grep-like processing?

Probably not.

> 
> $ wget http://www.gutenberg.org/files/7999/7999-h.zip
> $ unzip 7999-h.zip
> $ cd 7999-h
> $ cat *.htm > bigfile
> $ du -h bigfile
> du -h bigfile
> 8.2Mbigfile
> 
> -- grep.pl --
> #!/usr/local/bin/perl
> open(F, 'bigfile') or die;
> 
> while() {
>  s/[\n\r]+$//;
>  print "$_\n" if m/destroy/oi;
> }
> -- END --
> -- grep.py --
> #!/usr/bin/env python
> import re
> r = re.compile(r'destroy', re.IGNORECASE)
> 
> for s in file('bigfile'):
>  if r.search(s): print s.rstrip("\r\n")
> -- END --

Please notice that you're also benchmarking IO here - and perl seems to 
use a custom, highly optimized IO lib, that is much much faster than the 
system's one. I once made a Q&D cat-like comparison of perl, Python and 
C on my gentoo-linux box, and the perl version was insanely faster than 
the C one.

Now the real question is IMHO: is the Python version fast enough ?

My 2 cents..
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why does Python never add itself to the Windows path?

2007-01-02 Thread Gabriel Genellina

At Saturday 30/12/2006 21:55, Ben Sizer wrote:


python setup.py install

On Unix, you'd run this command from a shell prompt; on Windows, you
have to open a command prompt window (``DOS box'') and do it there; "

Pretty much none of the instructions in that part of the docs will work
without you altering your path beforehand. Python's cross-platform
nature means people rightly expect the same instructions to work on
Linux and Windows from a standard installation. Right now, they don't.


Notice that there is NO need to alter the system path. You just have 
to tell Windows where python.exe resides; there is a per-application 
path located at 
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths.
In order to launch Python just writing "python" at the command 
prompt, the installer should -instead of playing with the system 
path- create a new key below App Paths, named "python.exe", and set 
its default value to the full path of the installed python executable.
See 
http://msdn.microsoft.com/library/en-us/shellcc/platform/shell/programmersguide/shell_basics/shell_basics_extending/fileassociations/fa_perceived_types.asp



--
Gabriel Genellina
Softlab SRL 







__ 
Preguntá. Respondé. Descubrí. 
Todo lo que querías saber, y lo que ni imaginabas, 
está en Yahoo! Respuestas (Beta). 
¡Probalo ya! 
http://www.yahoo.com.ar/respuestas 

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

Re: OO question

2007-01-02 Thread Bruno Desthuilliers
[EMAIL PROTECTED] a écrit :
> First I want to say thanks everyone for helping me!
> 
> John Machin wrote:
> 
> 
>>[EMAIL PROTECTED] wrote:
>>
>>>I want to make an addressbook and I'm new to OO programming, so I
>>>wonder if this sounds reasonable.
>>>
>>>I think of making a class Address which contains all data about one
>>>person, that class can have UserDict as baseclass so I can access data
>>>like object['name'], etc..
>>
>>Stop right there. Class Address contains all data about one *person*?
>>Please consider renaming that class Person, and having a separate class
>>Address.
>>
>>Interruption for a reality check:  A person may be related to zero, one
>>or many addresses. An address may be related to zero, one or many
>>persons. The relationship may take many forms e.g. "lives at", "once
>>lived at", "has been noticed loitering outside", ...
> 
> 
> Lets say I have those two classes, Person and Address. How would one
> implement the relationship between them? First, a Person can have one
> or more addresses (or none), that could be represented as a list of
> Addresses, right? But then, if I have an Address I want to see which
> persons who live there, then I would have a list of Persons in each
> Address.
> 
> Is this doubly-linked way of doing it a good way of doing it,  or is
> there a better "OO way" I haven't learned yet?
> 

The most common solution so far for this kind of problems is to forget 
about "domain model" OO modeling and switch to relational modeling 
(usually using an SQL dbms). Else you end up rewriting an half-backed 
buggy ad-hoc relational system... FWIW, using OO does not imply using an 
OO domain model. You can restrict OO features to "technical" objects...

Now the good news is that there are Python packages like SQLAlchemy that 
gives you kind of "best of both world" solutions (OO domain model + 
relational support).

My 2 cents...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How do I add users using Python scripts on a Linux machine

2007-01-02 Thread Ivan Voras
Ramdas wrote:
> Well,
> 
> I need to add users from a web interface for a web server, which runs
> only Python. I need to add users, set quotas and in future even look at
> managing ip tables to limit bandwidth.
> 
> I know os.system(), but this has to be done through a form entry
> through a web interface.
> 
> Anyways thanks, do advise if there more pythonic solutions

What you're looking for is actually a pretty complex thing. You *could*
in theory manage /etc/passwd (and its "shadow" file) - you can find
crypto primitives like MD5 and DES on the 'net, but note that you must
run your script under the 'root' account in order to write (and even
read!) the passwd database. The same goes for using os.system and the
built-in OS utility. Be aware of security implications if you're running
your web server under the root account.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python2.5 frameobject - how to upgrade?

2007-01-02 Thread skip

Helmut> I'd like to install a package ('rekall') which uses
Helmut> frame->f_nlocals which is no longer contained in frameobject.h.

Helmut> What's the recommended way to upgrade such an application?

I suspect PySequence_Length(frame->f_locals) will do the trick.

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


Newbie query about secure embedded python

2007-01-02 Thread Richard Dwan
(Originally incorrectly posted to C++ SIG mailing
list)

Hello,

First let me apologise if this question is obvious -
I've never embedded python before and I am deciding of
it meets my needs.



My question is; is there a secure python interpreter
that prevents malicious code from using C/C++ modules
or built-in functions from causing damage to a users
system.


My objective is to have an embedded interpreted
language to drive all non CPU intensive application
behaviour with user / downloadable scripts to
customise the UI / scripting processing.

My concern with a simply embedding python is that this
would give arbitrary scripts the ability to make
system level changes (e.g. destructive abilities using
file access).  As I wish to encourage scripts to be
shared across the Internet this could not be
tolerated.

Python provides a very good script language to which I
can expose application specific functions/objects
using the already documented methods.  To use Python
with the above security restrictions I would need to
be able to disable all file / system built-ins when
running the interpreter across user scripts. In
addition, importing C/C++ functions would have to be
disabled as well.  As a complication, a set of
'approved C/C++ functions' such as numpy would need to
be supported in order to allow the user to do 'useful
processing' within the scripts driving the
application.

My naive solution would be to customise the
'PyImport_Import' and 'PyObject_CallObject' routines
used with user scripts so that:
--- an imported C/C++ module would be checked against
an approved list to prevent arbitrary C/C++ code from
being executed
--- built-in function calls would be checked against
an approved list to prevent system damaging calls from
being made
--- the application API that is exposed to the user
code must not expose to scripts a way of damaging
anything more than the data currently being
'processed'
--- the application would have to ensure that user
code is only executed within the secure interpreter
scope (e.g. not use callbacks to user script code
outside the secure interpreter)

Has the necessary secure python interpreter already
been created / a work in progress?



Many thanks for any advice you can give me,
Richard

Send instant messages to your online friends http://uk.messenger.yahoo.com 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: mutable numeric type

2007-01-02 Thread Diez B. Roggisch
Helmut Jarausch schrieb:
> [EMAIL PROTECTED] wrote:
>> Way to go.
>> Try doing this.
>> x = MutableNumeric(42)
>   ^^
> where is this defined?

In the OPs example.

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


python2.5 frameobject - how to upgrade?

2007-01-02 Thread Helmut Jarausch
Hi,

I'd like to install a package ('rekall') which uses
frame->f_nlocals
which is no longer contained in frameobject.h

What's the recommended way to upgrade such an application?

Many thanks for a hint,

Helmut Jarausch

Lehrstuhl fuer Numerische Mathematik
RWTH - Aachen University
D 52056 Aachen, Germany
-- 
http://mail.python.org/mailman/listinfo/python-list


Unsubscribing from the list

2007-01-02 Thread Dotan Cohen
I need to unsubscribe from this list. I've mailed
[EMAIL PROTECTED] but that did not unsubscribe me. I've
also gone to the list homepage and entered my user information, but
that just sent me a message that someone had tried to resubscribe this
username. What must one do to unsubscribe from python-list?

Thanks.

Dotan Cohen

http://what-is-what.com/what_is/internet.html
http://lyricslist.com/lyrics/artist_albums/356/moore_mandy.php
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Special Characters (Unicode, Ascii) in Python and MySQL

2007-01-02 Thread Carsten Haese
On Mon, 2007-01-01 at 21:57 -0800, ronrsr wrote:
> I have an MySQL database called zingers. The structure is:
> 
> zid - integer, key, autoincrement
> keyword - varchar
> citation - text
> quotation - text
> 
> I am having trouble storing text, as typed in latter two fields.
> Special characters and punctuation all seem not to be stored and
> retrieved correctly.
> 
> Special apostrophes and single quotes from Microsoft Word are causing a
> special problem, even though I have ''ed all 's
> 
> perhaps the encoding of the database itself should be different? it is
> currenlty latin_swedish_ci
> 
> Input and output is through a browser.
> 
> I think my problem may be that I need to encode the string before
> saving it in the databse. Can anyone point me in the right direction
> here?
> 
> 
> 
> here's the error message:
> 
> UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position
> 95: ordinal not in range(128)
>   args = ('ascii', "update zingers set keywords =
> 'a;Action;b;Religi... \n \n \n ' where zid = 422", 95, 96, 'ordinal not
> in range(128)')
>   encoding = 'ascii'
>   end = 96
>   object = "update zingers set keywords = 'a;Action;b;Religi... \n
> \n \n ' where zid = 422"
>   reason = 'ordinal not in range(128)'
>   start = 95
> 
> 
> 
> the characters I am trying to add are startquote and endquote copied
> and pasted from Microsoft Word.
> 
> 
> 
> Can anyone help me on this?

Apparently not, since you've already posted this problem on December
18th and got various responses. Did you read
http://effbot.org/pyfaq/how-do-i-escape-sql-values-when-using-the-db-api.htm as 
Fredrik suggested in the earlier thread?

-Carsten


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


How to get BOOST working on XP and Visual C++ 2005

2007-01-02 Thread Osiris
My experiences with BOOST on Windows XP and Visual C++ 2005

I'm new to Python.
I built software in more than ten other computer languages. I'm not
sure if that is not a handicap, when reading documentation of a system
like BOOST.
However:
It took me more than four full working days to get a Python/C/C++
'hello world!' program to work. There is a lot of documentation, but
somehow it did not 'click' with my previous experience. I think the
doc was written by very, very capable C++ and Python programmers, who
forgot how the world was before they got involved with Python.
A teacher/doc writer should never forget that, I think.
Mind you: the documentation is all there. Stressing the word ALL.
There is a lot of documentation. Which makes it very difficult to
choose the right piece.

My project is, to use old and tested and stable and error-free C-code
in a website built with Zope (www.zope.org) and Plone (www.plone.org).
So I think, C-code can be wrapped in some C++ and then, with the help
of Boost, be called from Python. Python is important when using Plone.

So let me summarize what I found out.

BOOST is a system to combine Python and C++. Call C++ compiled code
from Python, which is interpreted.
In the end, BOOST is a sort of "make" facility like found on Linux
(and Windows). In Boost it is called, not 'make.exe', but 'bjam.exe'.
You define a list of operations, which bjam executes for you. It runs
from the command line (I grew up, IT-wise, in the DOS-era. Hurray), it
has no GUI-like Windows front-end.

So the first step is to get bjam.exe from the net. There are two ways
to get it:
1.  download a ready-to-run bjam.exe from
http://downloads.sourceforge.net/boost/boost-jam-3.1.13-1-ntx86.zip?modtime=1149717367&big_mirror=0.
In the zip you will find the bjam.exe, which you put it in a place
where the system can always find it, like in c:\, or somewhere else in
the system's PATH.
2.  download the sources for bjam.exe and build it yourself:
http://downloads.sourceforge.net/boost/boost-jam-3.1.13.zip?modtime=1149717465&big_mirror=0
. I recommend not to do this, if you don't have to. And on Windows XP,
you don't have to. You could spend a lot of time to figure out how to
set up things before even building bjam.exe.

The second step is to get Boost libraries. These are for combining
with your C/C++ source, so Python can access the C/C++ code.
You download this stuff from Sourceforge:
http://downloads.sourceforge.net/boost/boost_1_33_1.zip?modtime=1133816391&big_mirror=0
It is a zip file that you unzip to a convenient location. I unzipped
to D:\ so I got a folder named d:\boost_1_31_1 with all the stuff in
it. I renamed this folder to d:\boost, to get rid of all the messy
version numbers.
To build the boost libraries from these sources, you need bjam, and
bjam makes use of your C/C++ compiler. In my case that was Microsoft
Visual C++ 2005, which has version number 8.0.
Now you have to make bjam and Visual C++ acquainted with the location
of supporting software. I made a BAT file to do this. This is what is
in that .BAT file, named SET.BAT and which I put in D:\boost:

d:
cd \boost
call e:\msvc\vc\vcvarsall.bat
set VC80_ROOT=e:\msvc\vc
set TOOLS=vc-8_0
set PYTHON_ROOT=c:\python24
set PYTHON_VERSION=2.4

I explain: 
e:\msvc is where I installed my Visual C++ system. The Microsoft
default location would be something like C:\Microsoft Visual C 2005\
etc, but I preferred D:\msvc.
Change the SET.BAT file as needed .
My IDLE (http://www.python.org/idle/) Python 2.4 is in C:\python24
The value 'vc-8_0' denotes the boost identification of my MS Visual
C++ system. If you use an other C++ system, it must be something else
(see http://www.boost.org/more/getting_started.html)

Now start a DOS box: Click the Start button in the lower left corner,
click on "run" and type "cmd".
There you switch to D:\ and change directory to \BOOST.
Execute the SET.BAT.
Then just type "bjam" (the system will find the program bjam itself,
because it is in the PATH)

Now get a lot of coffee, because the build will take a LONG time,
maybe 15 minutes or more.
You will see a lot of cpp-compiling and linking going on and some
warnings about 'deprecation', which are irrelevant.

When finished, keep the DOS box open. You will find BOOST stuff in
C:\boost, the default location for the compiling results.

Now try out an example. In the DOS box, go to
D:\boost\libs\python\example\tutorial, where you find a 'hello'
example and a Jamfile. Jamfile's are what a makefile is for make.: a
script for bjam to build all the 'hello' stuff needed for python.

Type 'bjam' again, and take a smaller amount of coffee. The system
will build the 'hello' stuff for you. Do not be alarmed about bjam
finding 1200+ 'targets' and rebuilding 40 of them, when only needing
to compile hello.cpp…. this is normal behaviour.

When bjam has finished, you will find 'hello' stuff in the
unbelievably deep folder
D:\boost\libs\python\example\tutorial\bin\tutorial\hello.pyd\vc-8_0\debu

Re: Why does Python never add itself to the Windows path?

2007-01-02 Thread Fuzzyman

Ben Sizer wrote:
[snip..]
> I have no problem with something being configurable, but I do have a
> problem with Windows users being forced to jump through unnecessary
> hoops that Unix and MacOS users don't have to endure. And I think the
> default should be to edit the PATH and allow you to explicitly disallow
> this: changing from the current behaviour is the right thing to do
> because the current behaviour is wrong, in terms of cross-platform
> compatibility and usability.
>

I strongly agree with these sentiments.

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

> -- 
> Ben Sizer

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


Re: mutable numeric type

2007-01-02 Thread Peter Otten
Andreas Beyer wrote:

> There has been quite some traffic about mutable and immutable data types
> on this list. I understand the issues related to mutable numeric data
> types. However, in my special case I don't see a better solution to the
> problem.
> Here is what I am doing:
> 
> I am using a third party library that is performing basic numerical
> operations (adding, multiplying, etc.) with objects of unknown type. Of
> course, the objects must support the numerical operators. In my case the
> third party library is a graph algorithm library and the assigned
> objects are edge weights. I am using the library to compute node
> distances, etc.
> 
> I would like to be able to change the edge weights after creating the
> edges. Otherwise, I would have to remove the edges and re-create them
> with the new values, which is quite costly. Since I also didn't want to
> change the code of the graph library, I came up with a mutable numeric
> type, which implements all the numerical operators (instances are of
> course not hashable). This allows me to change the edge weights after
> creating the graph.
> 
> I can do the following:
>  >>> x = MutableNumeric(10)
>  >>> y = MutableNumeric(2)
>  >>> x*y
> 20
>  >>> x.value = 1.3
>  >>> x*y
> 2.6001
>  >>>
> 
> The effect of numerical operations is determined by the contained basic
> data types:
>  >>> x.value = 3
>  >>> x/2
> 1
>  >>> x.value = 3.0
>  >>> x/2
> 1.5
>  >>>
> 
> Augmented operations change the instance itself:
>  >>> x.value = 0
>  >>> id(x)
> -1213448500
>  >>> x += 2
>  >>> x
> MutableNumeric(2)
>  >>> id(x) # show that same instance
> -1213448500
>  >>>
> 
> Is there anything wrong with such design? 

The library you are planning to feed with your mutable numbers has to be
designed with such somewhat unusual beasts in mind. For instance, it can no
longer cache intermediate values as their constituents may have changed
without notification.
Don't use that design unless the library's designers explicitly allow it or
at least after extensive testing. Be aware that in the latter case every
new version of the library may break your app beyond fixability.

> I am a bit surprised that 
> Python does not already come with such data type (which is really simple
> to implement). 

I'm guessing: Such a type is not normally useful -- and if you need it it is
really simple to implement :-)

Peter



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


Re: Difference between __init__ (again) and nothing ...

2007-01-02 Thread Bruno Desthuilliers
Stef Mientki a écrit :
> Marc 'BlackJack' Rintsch wrote:
> 
>> In <[EMAIL PROTECTED]>, Stef Mientki wrote:
>>
>>> What's the difference between using __init__ and using nothing,
>>> as the examples below.
>>>
>>> class cpu:
>>>PC = 4
>>
>>
>> This is a *class attribute*.  It's the same for all instances of `cpu`.
>>
>>> class cpu:
>>>def __init__:
def __init__(self):
>>>  self.PC = 4

By convention, ALL_UPPER names have a 'symbolic constant' semantic. 
Since Python is a very 'free' language (no attribute access restriction, 
no symbolic constants etc), it *strongly* relies on conventions.


>>
>> This is an *instance attribute* which is set in every instance of `cpu`.
>>
> thanks Marc,
> 
> Oh so obvious, why didn't I discovered that myself ;-)

Perhaps because it may not be that obvious at first sight ?-)

(that is, until you really understand Python's object model, which is 
really different from most mainstream OOPLs object models...)
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: simple ftputil ssl client

2007-01-02 Thread Stefan Schwarzer
On 2006-12-31 19:27, Croteam wrote:
> I trying to make ftputil client that uses ssl security.First I was try
> to make that with M2Crypto,but
> when I use it, I get the error:
>
> Traceback (most recent call last):
>   File "", line 1, in -toplevel-
> import M2Crypto
>   File "C:\Python24\lib\site-packages\M2Crypto\__init__.py", line 15,
> in -toplevel-
> import m2
>   File "C:\Python24\Lib\site-packages\M2Crypto\m2.py", line 28, in
> -toplevel-
> from __m2crypto import *
> ImportError: DLL load failed with error code 182

It seems this problem has nothing to do with ftputil, so it might
be best to post the question on the failed import alone with a
subject like

ImportError for M2Crypto: "DLL load failed with error code 182"

or even, since a Google search implies the problem doesn't occur
only for M2Crypto,

ImportError: "DLL load failed with error code 182"

With the current subject, people may think "I don't know ftputil"
and don't read your posting at all.

You might ask the question with the above subject on the
Python-Crypto mailing list which seems to be the best place for
M2Crypto-related questions. You should tell the version of
M2Crypto and the operating system you use. By the way, have you
tried other M2Crypto versions?

Can you import the module when the current directory is the one
containing the DLL? To check, change to the directory and start
the interactive Python interpreter. (If you use an IDE or
something similar, as your traceback suggests, that program might
change the directory before the import statement runs.)
Additionally, you can try to modify sys.path to contain the path
of the DLL before invoking the import statement. See also my
response on the ftputil mailing list.

> ...so now I trying to make it with pyOpenSSL or twistedmatrix ssl,but I
> don't know how.If anybody
> have any idea or example how to I make it,please help me!!!

Now the part specific to ftputil ;-) ...

If you can't use M2Crypto, try to make sure that you have a class
which is compatible with ftplib.FTP. You can pass such a class as
session_factory to ftputil.FTPHost's constructor. If you don't
have such a class, you might be able to write it yourself.

Stefan

-- 
Dr.-Ing. Stefan Schwarzer
SSchwarzer.com - Softwareentwicklung für Technik und Wissenschaft
http://sschwarzer.com
http://www.sschwarzer.net
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Difference between __init__ (again) and nothing ...

2007-01-02 Thread Stef Mientki
Marc 'BlackJack' Rintsch wrote:
> In <[EMAIL PROTECTED]>, Stef Mientki wrote:
> 
>> What's the difference between using __init__ and using nothing,
>> as the examples below.
>>
>> class cpu:
>>PC = 4
> 
> This is a *class attribute*.  It's the same for all instances of `cpu`.
> 
>> class cpu:
>>def __init__:
>>  self.PC = 4
> 
> This is an *instance attribute* which is set in every instance of `cpu`.
>
thanks Marc,

Oh so obvious, why didn't I discovered that myself ;-)

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


Re: mutable numeric type

2007-01-02 Thread Helmut Jarausch
[EMAIL PROTECTED] wrote:
> Way to go.
> Try doing this.
> x = MutableNumeric(42)
   ^^
where is this defined?

> y = x
> x += 42
> print y
> 


-- 
Helmut Jarausch

Lehrstuhl fuer Numerische Mathematik
RWTH - Aachen University
D 52056 Aachen, Germany
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why does Python never add itself to the Windows path?

2007-01-02 Thread Ben Sizer
Tom Plunket wrote:
> vbgunz wrote:

> > Some if not most python documentation assumes Python is on the path...
>
> Really?  I must live in different places in the docs, but I can't recall
> encountering any such documentation.

I have posted a few examples above: "Installing Python Modules"
(http://python.org/doc/2.2.3/inst/inst.html) is a key example. 3rd
party packages often expect you to type "python setup.py install".
Setuptools/easyinstall will give you an 'easy_install' script, but then
notes that you have to manually fix up the PATH yourself.

> Users who want it in their paths are certainly capable of putting it
> there.

By that logic, users who want Python are probably capable of unzipping
the archive and putting it somewhere semi-suitable. So why provide an
installer?

If you're going to provide an installer, it should do the whole job,
and get Python in a state that is reasonably consistent across all
platforms, where practical. Adding to the PATH variable isn't
impractical.

> I am in the camp that detests apps that automatically install
> tons of crap everywhere without prompts.

Why use hyperbole here? Is 13 or 14 bytes optionally added to a single
environment variable "tons of crap"? And did anybody insist that the
installer would have no prompts?

> Certainly, though, the
> suggestion that one pane in the installer offer to put it in the path
> would leave the default as it is today ("don't edit PATH"), though,
> right?  Doesn't make a whole lot of sense to add a new option and
> default it to something completely different from the old behavior, does
> it?

I have no problem with something being configurable, but I do have a
problem with Windows users being forced to jump through unnecessary
hoops that Unix and MacOS users don't have to endure. And I think the
default should be to edit the PATH and allow you to explicitly disallow
this: changing from the current behaviour is the right thing to do
because the current behaviour is wrong, in terms of cross-platform
compatibility and usability.

-- 
Ben Sizer

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


Re: Difference between __init__ (again) and nothing ...

2007-01-02 Thread Marc 'BlackJack' Rintsch
In <[EMAIL PROTECTED]>, Stef Mientki wrote:

> What's the difference between using __init__ and using nothing,
> as the examples below.
> 
> class cpu:
>PC = 4

This is a *class attribute*.  It's the same for all instances of `cpu`.

> class cpu:
>def __init__:
>  self.PC = 4

This is an *instance attribute* which is set in every instance of `cpu`.

In [8]: class CPU_1:
   ...: PC = 4
   ...:

In [9]: class CPU_2:
   ...: def __init__(self):
   ...: self.PC = 4
   ...:

In [10]: a = CPU_1()

In [11]: b = CPU_1()

In [12]: a.PC, b.PC
Out[12]: (4, 4)

In [13]: CPU_1.PC = 3.5

In [14]: a.PC, b.PC
Out[14]: (3.5, 3.5)

In [15]: c = CPU_2()

In [16]: d = CPU_2()

In [17]: c.PC, d.PC
Out[17]: (4, 4)

In [18]: c.PC = 3.5

In [19]: c.PC, d.PC
Out[19]: (3.5, 4)

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


Re: mutable numeric type

2007-01-02 Thread pgarrone
Way to go.
Try doing this.
x = MutableNumeric(42)
y = x
x += 42
print y

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


Re: Why does Python never add itself to the Windows path?

2007-01-02 Thread Ben Sizer
robert wrote:
> Ben Sizer wrote:
> > My opinion is that this is not as big a problem as some may feel that
> > it is. Unlike Unix systems, the PATH variable is rarely used.
>
> It is a big problem.
>
> It is not less than the majority of Python users (at least those who do 
> things on the command line) who deal with multiple Python versions.

So you think most Python users have more than one version of Python
installed? I disagree - but even if it is true, how come this isn't a
big problem on Unix? Can you name a single distribution that doesn't
install Python to the path?

> This would create funny PATH variables - almost a "psychic behavior with 
> history".

It is quite trivial to see if Python is already on the path, and act
differently based on that.

> Windows is at all less a multi user system. I don't even know a case where 
> two (Python) Programmers use _one_ box and then also want separate Python's - 
> just know home mates (parasites) who occasionally share the web browser or 
> so...

So... that's another reason why there's rarely a problem in setting
that PATH variable.

> Linking also a default python.exe into the system32 upon a (non-default) 
> checkbox mark in the installer should be simple, clear and do everything what 
> 99.9% want - and most "compatible" to *nix.

No, it doesn't : the /scripts directory is also important for many
Python packages and that isn't addressed by shifting python.exe into
system32.

-- 
Ben Sizer

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


Re: Unexpected output while walking dirs

2007-01-02 Thread Evan Carmi
wittempj  hotmail.com  gmail.com> writes:

> 
> If I do get this correct - you have files like \test\Mail\somename.msf
> and \test\Mail\somedirectory\someothername.msf, these files you want to
> move to \test\backup\timestamp\somename.msf and
> \test\backup\timestamp\somedirectory\someothername.msf.
> 
> In your code you start with collecting allfiles, and then you remove
> all except *,msf files. You can do this in one step to, by collecting
> only the wanted files in a listby applying the glob command from module
> glob :
> 
> allfiles = []
> for root, dirs, files in os.walk(top, topdown=False):
> targetfiles = glob.glob(os.path.join(root,'*.msf'))
> allfiles += targetfiles
> 
> Now allfiles contains the list of .msf files down from directory
> specified in variable top. From here I would create a list of 2-tuples,
> with as first element the full original filename, and as second element
> the desired backupname. Note that in your code you call the clock in a
> for loop, this might result in more directories.
> 
> backuproot = os.path.join(os.path.dirname(top), 'backup-msf',
> time.strftime('%Y%m%d%H%M%S'))
> backupfilenames = []
> for f in allfiles:
> backupfilenames.append((f, os.path.join(backuproot,
> os.path.basename(f
> 
> >From here it is easy to do the move.
> 
Thanks so much for your help, you got me started and I finished it with some
help from others as well. For anyone interested the working code is:

--
#!/usr/bin/python
#Author: Evan Carmi
#Date: 20060102
#Purpose: To uncorrupt Mozilla Thunderbird mail index files.
#Version: 1.00
import os, time, glob
 
srcRoot = 'f:\\test\\mail'
backupRoot = os.path.join(os.path.dirname(srcRoot), 'backup-msf',
time.strftime('%Y%m%d%H%M%S'))
 
for root, dirs, files in os.walk(srcRoot, topdown=False):
sources = glob.glob(os.path.join(root,'*.msf'))
pairs = []
 
for source in sources:
# If srcRoot is /foo/bar and source is /foo/bar/baz, let relativeSource
equal /baz
#let relativeSource be equal to the remainder of source when you take
away len(srcRoot)
idx = len(srcRoot)
relativeSource = source[idx:]
 
# Then let destination equal /quux/baz if backupRoot is /quux
destination = backupRoot + relativeSource
# relativeSource begins with a path separator, so os.path.join will
misinterpret it.
 
pair = (source, destination)
pairs.append(pair)
 
for pair in pairs:
os.renames(*pair)
# This is functionally equivalent to os.renames(pair[0], pair[1])

--

Thanks, Evan

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


Difference between __init__ (again) and nothing ...

2007-01-02 Thread Stef Mientki
What's the difference between using __init__ and using nothing,
as the examples below.


class cpu:
   PC = 4



class cpu:
   def __init__:
 self.PC = 4

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


Re: how to move files based on file-ending from dirs and subdirs to specific dir?

2007-01-02 Thread Evan Carmi
Marc 'BlackJack' Rintsch  gmx.net> writes:

> This line is quite complicated and I don't really grasp what it's doing.
> Maybe some comments, possible with examples, are needed here.  And maybe
> then you'll see why it doesn't work as wanted!?  If these are the
> destination paths and they should be at the same level as `top`, where is
> `top` here?  Shouldn't that be a prefix of all destination paths?
> 
> Ciao,
>   Marc 'BlackJack' Rintsch

I figured out the problem, with a lot of help. 
Thanks for the help
Evan


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


Re: doctesting

2007-01-02 Thread Ben Artin
In article <[EMAIL PROTECTED]>,
 belinda thom <[EMAIL PROTECTED]> wrote:

> I'd like to write a tester script that I can place in one place (say  
> ~/bin/python/tester.py) and then have it visible to me at the cmd- 
> line (by setting the path  variable appropriately). I have had no  
> luck in getting it to work, however.
> 
> It appears like the doctest code itself assumes that all modules to  
> be imported lie in some directory other than the one I invoked the  
> tester.py script from. In particular, simple imports in a .txt file  
> like:
> 
>>>> import foo
> 
> fail even though I've started the script in a directory that contains  
> file foo.py

import foo looks at sys.path which is based on PYTHONPATH in the environment. 
So, one way to do what you want is to have your script modify sys.path before 
importing other modules.

hth

Ben

-- 
If this message helped you, consider buying an item
from my wish list: 

I changed my name: 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: doctesting

2007-01-02 Thread Peter Otten
belinda thom wrote:

> I'd like to write a tester script that I can place in one place (say
> ~/bin/python/tester.py) and then have it visible to me at the cmd-
> line (by setting the path  variable appropriately). I have had no
> luck in getting it to work, however.
> 
> It appears like the doctest code itself assumes that all modules to
> be imported lie in some directory other than the one I invoked the
> tester.py script from. In particular, simple imports in a .txt file
> like:
> 
>>>> import foo
> 
> fail even though I've started the script in a directory that contains
> file foo.py
> 
> I only achieve success when I manually copy tester.py into this same
> directory (symlinks don't fix the problem).
> 
> This is a real drag b/c it means I have to copy this tester.py
> routine into _every_ directory that contains a .txt python unit test
> file. From a code-reuse point of view, this is pretty hideous...

For an executable script to be reachable its path must be listed in the PATH
environment variable whereas Python's import mechanism relies on PYTHONPATH
(and ultimately on sys.path).

http://docs.python.org/tut/node8.html#SECTION00811

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


[Off] WXP Fingerprint + Python...

2007-01-02 Thread durumdara
Hi!

I have an application (Python + wx) somewhere.
The users use they fingerprint to log[in/out].
But we have a problem that in this time the fingerprint logon is do REAL 
windows logon, so every user need a windows user too, and many times it 
need to close/open application, and Windows.

We need better solution.
We tried MS Fingerprint Reader, but that is working in same method: it 
store the fingerprints for every Windows user...

I need something better. Do anyone knows about a Fingerprint Software 
and device that can recognize many-many fingerprints, and it can 
associate the actual fingerprint with a VIRTUAL(! not windows user! a 
virtual!) user that stored in a DB?
This DB can store other infos, or an ID that we can use in another app...
Or a software hook needed (DLL hook) that can add possibility to catch 
the login/outs, and I can do anything else as I need.

Do anyone knows about same solution or product?

Thanks for help:
dd

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


doctesting

2007-01-02 Thread belinda thom
Hi,

I'd like to write a tester script that I can place in one place (say  
~/bin/python/tester.py) and then have it visible to me at the cmd- 
line (by setting the path  variable appropriately). I have had no  
luck in getting it to work, however.

It appears like the doctest code itself assumes that all modules to  
be imported lie in some directory other than the one I invoked the  
tester.py script from. In particular, simple imports in a .txt file  
like:

   >>> import foo

fail even though I've started the script in a directory that contains  
file foo.py

I only achieve success when I manually copy tester.py into this same  
directory (symlinks don't fix the problem).

This is a real drag b/c it means I have to copy this tester.py  
routine into _every_ directory that contains a .txt python unit test  
file. From a code-reuse point of view, this is pretty hideous...

Advice appreciated,

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


Re: how to move files based on file-ending from dirs and subdirs to specific dir?

2007-01-02 Thread Marc 'BlackJack' Rintsch
In <[EMAIL PROTECTED]>, Evan Carmi
wrote:

> top = 'f:\\test\\mail'
> 
> […]
>
> indexdest = []

Here you bind the name `indexdest` to an empty list but replace it in the
very next line with another list.  So this line is unnecessary.

> indexdest = ['%s\\..\\..\\%s\\%s\\%s' % (x , time.strftime('%Y%m%d%H%M%S'),
> os.path.basename(os.path.normpath(x+'\\..')), os.path.basename(x)) for x in 
> ind
> ex]

This line is quite complicated and I don't really grasp what it's doing.
Maybe some comments, possible with examples, are needed here.  And maybe
then you'll see why it doesn't work as wanted!?  If these are the
destination paths and they should be at the same level as `top`, where is
`top` here?  Shouldn't that be a prefix of all destination paths?

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

Re: Writing more efficient code

2007-01-02 Thread John Machin
On 2/01/2007 2:23 PM, gonzlobo wrote:
> Thanks to John, Paul & Jon for their responses. This list is great for 
> info.

Hi gonzlobo,

Please dont use private e-mail; post to the Python mailing-list / 
newsgroup, so that everybody can see what the eventual outcome is.

Please also answer the question that I asked: in effect, what you have 
showed looks like a hex dump of a binary fiie -- are you saying that the
data is actually transmitted over the serial bus in hex with spaces in 
between?

> 
> Jon,
> OCaml might be the best option, but my braincell is only good for 1
> language at a time. Hopefully python doesn't replace English.  :^)
> 
> Paul,
> Thanks for the snippets. It looks pretty complicated, but worth
> looking into. I'm all for reducing line of code (hopefully not for
> readability).
> 
> John M,
> You're right, my original example contained non-sensical data (I made
> it up for example's sake).

It wasn't me who wrote that, but I agree.

> 
> Here's a snippet of real data (it's a 10Mb/s serial bus, so there's
> *alot* of data).
> 007a 06 0321 80 00 34 d1 01 0b 3f f7 01 6b
> 007b 26 0311 00 00 00 00 1a bd 00 00 00 00
> 007c 06 0321 80 00 a0 04 81 eb 20 05 81 1b
> 007d 16 0614 00 00 00 00 00 00 00 00 00 00
> 007e 06 0321 80 00 20 00 01 07 a0 43 01 9b
> 007f 06 0301 80 00 a0 b9 82 2b 3f d6 02 ab
> 0080 06 0321 80 00 bf d4 01 5b a3 f0 01 db
> 0081 06 0301 80 00 31 9c 02 0b bf d7 02 15
> 0082 0f 0416 01 01 00 00 20 20 20 20 20 20
> 0083 06 0301 80 00 bf ff 02 6b bf f3 82 eb
> 0084 0f 0416 02 01 00 00 20 20 20 20 20 20
> 0085 06 0301 80 00 bf ed 82 1b a0 07 02 07
> 0086 06 0321 00 00 00 00 01 af 00 00 00 00
> 0087 26 0311 80 00 e0 ce 02 30 80 07 82 86
> 0088 06 0301 80 00 a0 4a 02 9b 3f df 02 5b
> 0089 06 0301 80 00 80 00 02 ce 80 00 02 b3
> 008a 06 0301 80 00 00 00 02 5f e0 00 02 89
> 008b 16 0614 00 fe 31 00 00 00 00 00 00 00
> 008c 43 03a1 01 00 80 00 02 5d 80 0b 06 5d
> 008d 06 0301 80 00 60 a1 92 c1 e0 a1 8a 21
> 008e 4f 0450 01 10 00 00 80 00 37 00 00 00
> 
> line = 007a 06 0321 80 00 34 d1 01 0b 3f f7 01 6b
  0v1v2v3v4v

> Label 321 actually contains:
> 
>time = line[:8]
>PID = line[12:16]
>d2 = line[17:19]
>d3 = line[20:22]
>d4 = line[23:25]
>d5 = line[26:28]
>d6 = line[29:31]
>d7 = line[32:34]
>d8 = line[35:37]
>d9 = line[38:40]
>d10 = line[41:43]
>d11 = line[44:46]

That's not Python 101, it's PYBOL :-) I haven't had to resort to the 
0v1 etc caper for a very long time.

Consider doing this:

ints = [int(x, 16) for x in line.split()]
time = ints[0]
d = ints[1:]
pid = d[1]
# what is the undescribed field in ints[1]?


> 
> d2 + d3 = Pitch Angle (* 0.01)

I asked you before what you mean by "combine" ... now I'll ask what you 
mean by "d2 + d3"

Do you mean this:
 pitch_angle = (d[3] * 256 + d[2]) * 0.01
?


> d4 + d5 = Roll Angle (* 0.05)
> d6 + d8 = Magnetic Heading (* 0.05)

What happened to d7?

> d9 + d10 = Pressure Altitude (* 1.0)
> d11 = various flags


> 
> My code is python 101 (uses lots of nested if's), so using
> dictionaries would be very helpful.

Here's my Python 102 ... we can help you get to 201 level with a bit 
more disclosure from you on the specifics ...

| >>> line = "007a 06 0321 80 00 34 d1 01 0b 3f f7 01 6b"
| >>> ints = [int(x, 16) for x in line.split()]
| >>> ints
| [122, 6, 801, 128, 0, 52, 209, 1, 11, 63, 247, 1, 107]
| >>> time = ints[0]
| >>> time
| 122
| >>> d = ints[1:]
| >>> d
| [6, 801, 128, 0, 52, 209, 1, 11, 63, 247, 1, 107]
| >>> unknown = d[0]
| >>> unknown
| 6
| >>> pid = d[1]
| >>> pid
| 801
| >>> hex(pid)
| '0x321'
| >>> pitch_angle = (d[3] * 256 + d[2]) * 0.01
| >>> pitch_angle
| 1.28
| >>>

Call me crazy, but I'm highly suspicious of 0x8000 becoming a pitch 
angle of 1.28 degrees ;-) Especially since other lines in your sample 
with pid == 0x321 have (mostly) d2d3 == 0x8000 also, except for one with 
0x000 -- I'm not an aeronautical engineer, but I would have expected 
other values for pitch angle.

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