Re: Request for a change in the csv module.

2007-03-13 Thread Diez B. Roggisch
Paulo da Silva schrieb:
> [EMAIL PROTECTED] escreveu:
>> On Mar 12, 4:26 pm, Paulo da Silva <[EMAIL PROTECTED]> wrote:
> ...
> 
>> locale.setlocale(locale.LC_NUMERIC, 'pt_BR.ISO8859-1')
>> csv_writer = csv.writer(open("foo.csv","w"), dialect='excel')
>> rows = (('testing', 1.23), ('testing', 2.34))
>> formatted_rows = ((string, locale.format('%g', number)) for
>> (string,number) in rows)
>> csv_writer.writerows(formatted_rows)
> 
> 
> That works but it is a pain to use.

Why? I think it's straightforward.

> May be I'll sublass csv or even I'll write one myself.
> It would be much better to be able to specify an additional
> variabel to the Dialect class and change csv.

I don't think so. The csv module is about the subtleties that can occur 
when parsing textual data with possible escape chars and the like, and 
creating that data.

But IHMO its up to the user to feed it with just textual data. Because 
automatically converting numbers falls flat on it's face in case of 
special requirements like a limit on the number of digits to render and 
the like. Better do that in a simple and straightforward preprocessing 
state, as shown above.

The same is essentially true for dates as well, btw. How do you want to 
deal with them?

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


Re: Starting Python... some questions

2007-03-13 Thread Bruno Desthuilliers
[EMAIL PROTECTED] a écrit :
> I started using Python a couple of days ago - here are a few
> questions:
> 
> * Doesn't the __main__() method automatically execute when I run my
> python program?

Which "__main__" method ???

Anyway, the answer is no. Every code at the top-level (which includes 
import, class and def statements...) is executed when the module is 
first loaded - whether as a proper module (ie: imported from somewhere 
else) or as a main program (ie-> python mymodule.py). In the first case, 
the special variable __name__ is set to the module's name, in the second 
to '__main__'. So you can rely on this to have code executed when the 
module is used as a program. The usual idiom is

# mymodule.py
(imports here)
(classes and defs here)

def main(argv):
   (code of main function here)
   return 0

if __name__ == '__main__':
   import sys
   sys.exit(main(sys.argv))


> * Only when I do an import of my test.py file within python and then
> run test.__main__() 

BTW, you should *not* use names with 2 leadings and 2 trailing 
underscores. These names are reserved for Python implementation stuff.

> I can see where my bugs are. Is this correct?

Nope. You can also spot bugs by reading the code or running it thru the 
debugger !-)

More seriously : using the above idiom (or any variant of - the 
important part being the conditional on __name__ == '__main__'), you can 
just
$ python mymodule.py

to run your program.

> (right now this is my only way of running my python program and see
> where I have problems)

> * Once I've done an import and then I wish to make a change to the
> file I've imported I have to quit Python, restart and import that
> module again in order for the module to be refreshed. Is there no "re-
> import" ?

reload(module_object)

But it's of very limited use. The best thing to do is usually to have a 
simple test file that setup the desired state (imports etc) that you 
execute after each change, passing the -i option to the python 
interpreter (this will leave the interpreter in interactive mode after 
execution of the test file, so you can inspect your objects, test things 
etc).

> * Finally, could someone tell me why I'm having problems with the
> small module below?
>   - Python pretends I provide chassis_id() with three parameters, even
> though I clearly only provide it with two - why?

Without even reading the code, I can tell you it's an instance or 
classmethod with either a wrong declaration or wrongly called.

> 
> #!/usr/bin/python
> import scapy
> import struct
> 
> class lldp_class:

Do yourself a favor: use new-style classes. Also, it would be better to 
stick to usual naming conventions (Python relies heavily on conventions):
http://www.python.org/dev/peps/pep-0008/

   class Lldp(object):

>   def __init__(self):
>   self.chassis_id_tlv = None
> 
>   def chassis_id(subtype, chassis_info):

Bingo. You need to have self as the first argument. The instance is 
passed as the first argument of a method.

 def chassis_id(self, subtype, chassis_info):

>   if subtype == 4:
>   chassis_data = struct.pack("!B",chassis_info)
>   subtype_data = struct.pack("!B",subtype)
>   self.chassis_id_tlv = subtype_data + chassis_data
> 
> def __main__():


   def main():

>   p = lldp_class()
>   p.chassis_id(4, "01:80:C2:00:00:0E")

For the record: this is interpreted as:
 lldp_class.chassis_id(p, 4, "01:80:C2:00:00:0E")


>   payload = p.chassis_id_tlv
>   ether = scapy.Ether(dst="01:02:03:04:05:06")
>   fullpayload = ether + payload
>   sendp(fullpayload)
> 

if __name__ == '__main__':
 main()

As a side note, it looks like there are a couple point where your design 
may be improved. Like passing subtype and chassis_info to the __init__ 
of your class.

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


Re: Starting Python... some questions

2007-03-13 Thread Bruno Desthuilliers
Steven D'Aprano a écrit :
> On Mon, 12 Mar 2007 21:39:11 -0700, jezonthenet wrote:
> 
>> I started using Python a couple of days ago - here are a few
>> questions:
>>
>> * Doesn't the __main__() method automatically execute when I run my
>> python program?
> 
> 
> No. 
> 
> 
>> * Only when I do an import of my test.py file within python and then
>> run test.__main__() I can see where my bugs are. Is this correct?
>> (right now this is my only way of running my python program and see
>> where I have problems)
> 
> That's a good way of choosing to run __main__ manually, but there are
> other ways.
> 
> If you add a line to the end of your program:
> 
> __main__()
> 
> 
> the function will be executed whenever the program runs. That is both when
> you import it, and when you run it from the command line.
> 
> To ensure it doesn't run when you import, do this:
> 
> 
> if __name__ == "__main__":
> __main__()
> 
> 
> 
>> * Once I've done an import and then I wish to make a change to the
>> file I've imported I have to quit Python, restart and import that
>> module again in order for the module to be refreshed. Is there no "re-
>> import" ?
> 
> Yes there is. Do this:
> 
> import my_module
> # do things
> # edit the file
> # don't forget to save changes (that always catches me out)
> reload(my_module)
> 
> 
>> * Finally, could someone tell me why I'm having problems with the
>> small module below?
>>   - Python pretends I provide chassis_id() with three parameters, even
>> though I clearly only provide it with two - why?
>>
>> Thanks!
>>
>> #!/usr/bin/python
>> import scapy
>> import struct
>>
>> class lldp_class:
>>  def __init__(self):
>>  self.chassis_id_tlv = None
>>
>>  def chassis_id(subtype, chassis_info):
>>  if subtype == 4:
>>  chassis_data = struct.pack("!B",chassis_info)
>>  subtype_data = struct.pack("!B",subtype)
>>  self.chassis_id_tlv = subtype_data + chassis_data
> 
> Class methods

s/Class/Instance/

classmethods are methods that takes the class as first parameter.

> always take a first parameter that points to the
> class instance. 

(snip)

> Just remember to always put "self" as the first argument to a class
> method, 

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


mod_python's mechanism

2007-03-13 Thread memcached
Hello,
I'm just curious that does mod_python have the same or similiar mechanism 
comparing to mod_perl?
Thanks!

AOL now offers free email to everyone.  Find out more about what's free from 
AOL at AOL.com.
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Signed zeros: is this a bug?

2007-03-13 Thread Hendrik van Rooyen
 "Paddy" <[EMAIL PROTECTED]> wrote

> 
> Hey, I'm still learnin'. Sweet!
> 
contrary to popular belief, the answer to life,
the universe, happiness and everything is
not 42, but the above.

- Hendrik

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


Re: Python in a desktop environment

2007-03-13 Thread Bruno Desthuilliers
David Cramer a écrit :
> On Mar 12, 9:56 am, Bruno Desthuilliers  [EMAIL PROTECTED]> wrote:
>> Diez B. Roggisch a écrit :
>>
>>> Bruno Desthuilliers wrote:
 Grant Edwards a écrit :
 (snip)
> Python is _far_ more robust than C++.
 I wouldn't say so - robustness is a quality of a program, not of a
 language !-)
>>> Nope. Dealing with dangling references and double frees, complex
>>> copy-semantics that change only by a feeble character or via overloaded and
>>> thus hard to comprehend assignment operators are all properties of C++,
>> Indeed
>>
>>> and
>>> tremendously afflict robustness IMHO.
>> robustness of programs written with this language, yes.
>>
>> NB : I'm afraid the smiley got lost somewhere between screen and
>> readers, so here comes another one !-)
> 
> Everyone seems to have misunderstood what I want.

Possibly.

> I'm a Python
> developer, I don't give a rats ass about what people say about C#,
> Python, or c++, they all have their uses. My main reasoning for
> considering C++ as the backend is some things (reading memory for
> example) are much easier to do in C++ than in Python,

Depends. But anyway nothing prevents you from having a few functions in 
a C extension for this part...

> and we already
> have a lot written in C++.
 >
> The argument about robustness, has nothing to do with how nicely
> formatted the language is, or how great the tracebacks are,

Certainly not. It has to do with readability (which helps spotting 
obvious bugs), simplicity (which helps understanding the whole damn 
thing), and automatic memory management (which really makes a 
difference, even for seasonned C and C++ programmers).

> it's
> strictly about how high the memory cost is and how much CPU it's going
> to take. 

This is a performance issue, not a robustness issue. Wrong qualificative !-)

> Python is well known for being high on memory and C++ being
> compiled can be a lot faster for things.

Even compiled to native code, Python wouldn't probably be much faster - 
it's way too dynamic. Or this would require 30+ years of work (like 
we've seen for Lisp).

If you have performance-critical parts that can't be solved by a 
pure-python solution or a binding to an external lib, then yes, it makes 
sens to recode these parts in a lower-level language. But this is not 
exactly "a python front-end for a C++ backend", it's "a python program 
with some C or C++ extensions".

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


Re: Program __main__ function

2007-03-13 Thread André Malo
Ben Finney wrote:

> Ben Finney <[EMAIL PROTECTED]> writes:
> 
>> Now, when I write unit tests for my program (i.e. a Python module
>> designed to be run as a command), it can still be imported safely
>> into my unit tests, and all the code gets covered by test cases
>> except the three-line stanza at the end.
> 
> All I need now is for Python to automatically execute a '__main__'
> function if the module name is '__main__' (which it seems the OP
> expected should happen), and unit test coverage could be 100% :-)

Short hint to go further:
exec file('/usr/lib/python2.4/timeit.py') in {'__name__': '__main__'}

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


Re: Request for a change in the csv module.

2007-03-13 Thread Szabolcs Nagy

> It would be much better to be able to specify an additional
> variabel to the Dialect class and change csv.

no it wouldn't
this is a locale specific problem so it should be handled there

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


Re: Starting an external, independent process from a script

2007-03-13 Thread Henrik Lied
I've tried os.spawnv and os.spawn, but these give no error and no
result.


Henrik Lied skreiv:
> Hi there!
>
> I'm trying to create a video uploading service (just to learn). The
> system is mostly based on Django, but the question I'm looking an
> answer for is more related to Python.
>
> So, the user gets to upload a video file. This can either be a mpg,
> avi or mp4-file. When the file is saved to its location, I want to
> convert it to FLA (Flash Video). I'm currently using Mplayers
> Mencoder, and this works great. The Mencoder is retrieved through
> running os.system("mencoder variables here")
>
> The problem with this is that the user has to wait until the movie is
> done encoding until he can go around with his business. I don't look
> upon this as ideal.
>
> So - I want to spawn a new system process. I need some good pointers
> on how to do this right.
>
> Any input? :-)
>
> Thanks a lot in advance!

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


RE: Readline()

2007-03-13 Thread Taylor, Stuart
i have a thread class which should read the output from the procedure
line by line and finish when the thread is set to kill:
 
class KillableThread(threading.Thread):
def __init__(self, name="thread", *args, **kwargs):
threading.Thread.__init__(self, *args, **kwargs)
self.name = name
self.killed = 0
def kill(self):
self.killed = 1
def run(self):
self.id = threading._get_ident()
self.Proc  =
subprocess.Popen(["python","-tt","output_file.py"], cwd =
os.getcwd(),stdin=subprocess.PIPE, stdout = subprocess.PIPE, stderr =
subprocess.STDOUT)
retval= None 
while retval == None and not self.killed:
line = self.Proc.stdout.readline()
retval=self.Proc.poll()
 
to replicate my problem the output_file.py requires a user input. i ask
for a user input as my thread will sit waiting on
self.Proc.stdout.readline(). This is the point i want to have a timeout
or be able to end my thread as there is no output from the output_file. 
 
The main approch i cannot implement is to be able to kill the thread as
it remains hung on readlines()
 



From: Sick Monkey [mailto:[EMAIL PROTECTED] 
Sent: 13 March 2007 01:51
To: Taylor, Stuart
Cc: python-list@python.org
Subject: Re: Readline()


Maybe if you show us your code we can better assist you.  

But maybe you can use a global variable or a try-catch method to keep
threads from staying alive and help better control your code.  


On 3/12/07, Taylor, Stuart <[EMAIL PROTECTED]> wrote: 

I have been working on running an external process using
subprocess.popen for a few days. 
The process is ran over the network to another machine. 
One thing I have found is that if I perform readline() on the
stdout it will hang if the process loses connection. 

I have tried a few things in a test example: one is to use
stdin.write then stdin.flush() which send a string that readline() will
read and it ends correctly but doesn't work on the project I need it to
work on. Another is to try using threads and ignoar the thread when  the
process has lost connection but this still leaves the open thread alive
even when the main app has finished. 

I am relatively new to python and I may be making a fundemantal
mistake in my implementation, can anyone please inform me of whether
sticking with subprocess.popen and readline() is the correct procedure
for this sort of task? 

And if anyone can point me in the correct implementation of this
problem I would be gratefull. 


Thank you 

Stuart 


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



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

Re: number generator

2007-03-13 Thread Duncan Booth
Dick Moores <[EMAIL PROTECTED]> wrote:

> But let's say there is one more constraint--that for each n of the N 
> positive integers, there must be an equal chance for n to be any of 
> the integers between 1 and M-N+1, inclusive. Thus for M == 50 and N 
>== 5, the generated list of 5 should be as likely to be [1,46,1,1,1] 
> as [10,10,10,10,10] or [14, 2, 7, 1, 26].

I don't think what you wrote actually works. Any combination including a 46 
must also have four 1s, so the digit 1 has to be at least 4 times as likely 
to appear as the digit 46, and probably a lot more likely than that.

On the other hand, making sure that each combination occurs equally often 
(as your example might imply) is doable but still leaves the question 
whether the order of the numbers matters: are [1,46,1,1,1] and [1,1,46,1,1]  
the same or different combinations?

The sorted/sample/xrange solution seems to give an even distribution or 
ordered combinations, I don't know what algorithm (short of enumerating all 
possible solutions and choosing one at random) gives an even distribution 
when the ordering doesn't matter.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Starting an external, independent process from a script

2007-03-13 Thread rishi pathak

You can do something like this:
pid = os.fork()
if pid != 0:
   os.execl("mencoder variables here and its arguments")
else:
   continue
exec will replace the current child process with the given command and as we
are doing fork the command will get executed in a child process.You can also
use os.system there

On 12 Mar 2007 16:13:51 -0700, Henrik Lied <[EMAIL PROTECTED]> wrote:


Hi there!

I'm trying to create a video uploading service (just to learn). The
system is mostly based on Django, but the question I'm looking an
answer for is more related to Python.

So, the user gets to upload a video file. This can either be a mpg,
avi or mp4-file. When the file is saved to its location, I want to
convert it to FLA (Flash Video). I'm currently using Mplayers
Mencoder, and this works great. The Mencoder is retrieved through
running os.system("mencoder variables here")

The problem with this is that the user has to wait until the movie is
done encoding until he can go around with his business. I don't look
upon this as ideal.

So - I want to spawn a new system process. I need some good pointers
on how to do this right.

Any input? :-)

Thanks a lot in advance!

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





--
Regards--
Rishi Pathak
National PARAM Supercomputing Facility
Center for Development of Advanced Computing(C-DAC)
Pune University Campus,Ganesh Khind Road
Pune-Maharastra
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Starting an external, independent process from a script

2007-03-13 Thread Henrik Lied

Unfortunately, that didn't work either.
The output is empty, I don't get a message, and I definitely don't get a
converted file.

2007/3/13, rishi pathak <[EMAIL PROTECTED]>:


You can do something like this:
pid = os.fork()
if pid != 0:
os.execl("mencoder variables here and its arguments")
else:
continue
exec will replace the current child process with the given command and as
we are doing fork the command will get executed in a child process.You can
also use os.system there

On 12 Mar 2007 16:13:51 -0700, Henrik Lied <[EMAIL PROTECTED] > wrote:
>
> Hi there!
>
> I'm trying to create a video uploading service (just to learn). The
> system is mostly based on Django, but the question I'm looking an
> answer for is more related to Python.
>
> So, the user gets to upload a video file. This can either be a mpg,
> avi or mp4-file. When the file is saved to its location, I want to
> convert it to FLA (Flash Video). I'm currently using Mplayers
> Mencoder, and this works great. The Mencoder is retrieved through
> running os.system("mencoder variables here")
>
> The problem with this is that the user has to wait until the movie is
> done encoding until he can go around with his business. I don't look
> upon this as ideal.
>
> So - I want to spawn a new system process. I need some good pointers
> on how to do this right.
>
> Any input? :-)
>
> Thanks a lot in advance!
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>



--
Regards--
Rishi Pathak
National PARAM Supercomputing Facility
Center for Development of Advanced Computing(C-DAC)
Pune University Campus,Ganesh Khind Road
Pune-Maharastra





--
Med vennlig hilsen,
Henrik Lied
-- 
http://mail.python.org/mailman/listinfo/python-list

Setting System Date And Time

2007-03-13 Thread Tzury
Is it possible to modify the Systems' Date and Time with python?

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


Re: converting epoch time to string (and vice versa)

2007-03-13 Thread Paul McGuire
On Mar 13, 12:42 am, Astan Chee <[EMAIL PROTECTED]> wrote:
> Hi,
> I have a string in this format "DD/MM/YYY" for example:
> tdate = "18/01/1990"
> and Im trying to convert this to epoch time, can anyone help?
> Im also trying to convert that epoch time to the string format
> previously. Can anyone help this one too?
> Thanks!
> Astan

Read up on time.strftime() (_F_ormats a time to a string of various
styles) and time.strptime() (_P_arses a string of various formats into
a time).

-- Paul

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


Re: Single string print statements on multiple lines.

2007-03-13 Thread Bruno Desthuilliers
Goldfish a écrit :
> http://www.catb.org/~esr/faqs/smart-questions.html
> 
> Don't post homework questions.
> 
Given the way the question was expressed, I don't think this particular 
rule applies here. Obviously, the OP is not trying to cheat (explicitelt 
aknowledging it is homework), and has a good enough understanding of 
what the usual solution is (asking for the escape char in Python).

Now of course the answer is in the FineManual(tm), which implies that 
either the OP failed to read it, or that the FineManual is not so fine - 
but that's another problem.

My 2 cents...






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


Re: Request for a change in the csv module.

2007-03-13 Thread Paulo da Silva
Diez B. Roggisch escreveu:
> Paulo da Silva schrieb:
...

>> That works but it is a pain to use.
> 
> Why? I think it's straightforward.

That is not the point. The problem is to have things generalized.
I have some general purpose tables whose fields format I don't know
in advance.
Internally the numeric values are independent of localization.
Having a table, I don't like the idea of preformating things
before sending them to the csv for exportation. A little more
of programming and there will be no need for csv at all :-)
...
> The same is essentially true for dates as well, btw. How do you want to
> deal with them?

This is a pertinent question I didn't think of. May be csv should handle
data conversions using 'locale'.
It is already automatically converting numbers to text
anyway, but unconditionally using the '.'.
As for the dates the dialect could include a format like -MM-DD
hh:mm:ss. Dates are not always 'locale' only. In pt_PT we use
-MM-DD or YY-MM-DD and sometimes DD-MM-.
One must remember that csv is not part of the language. So, to have
some kind of universality, it must use the specs (in dialect) for
formatting and 'locale' for data conversions.

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


Re: Python in a desktop environment

2007-03-13 Thread Paul Boddie
On 13 Mar, 04:33, Grant Edwards <[EMAIL PROTECTED]> wrote:
> On 2007-03-13, David Cramer <[EMAIL PROTECTED]> wrote:
>
> > and we already have a lot written in C++.

[...]

> I think you're nuts to decide that you need C++ before you've
> tested a Python implementation, but it's your nickle. :)

I'm imagining that the luxury of throwing away a large amount of
existing code just isn't an option.

Paul

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


Re: converting epoch time to string (and vice versa)

2007-03-13 Thread Paul Boddie
On 13 Mar, 06:52, "Amit Khemka" <[EMAIL PROTECTED]> wrote:
> On 3/13/07, Astan Chee <[EMAIL PROTECTED]> wrote:
>
> > I have a string in this format "DD/MM/YYY" for example:
> > tdate = "18/01/1990"
> > and Im trying to convert this to epoch time, can anyone help?
>
> import calendar
> t = map(int,tdate.split('/'))
> epochs = calendar.timegm((t[2], t[1], t[0], 0, 0, 0))

You can also use strptime:

import time
t = time.strptime("18/01/1990", "%d/%m/%Y")
epochs = calendar.timegm(t)

Whilst timegm is a hidden gem in the calendar module, it is actually
based on a library function on certain platforms. I've submitted a
patch to add a platform-independent version to the time module -
requests to add such a function previously led only to documentation
changes, I believe. (I think that many people regard mktime as doing
the work that only timegm actually accomplishes, so it's an important
addition.)

> > Im also trying to convert that epoch time to the string format
> > previously. Can anyone help this one too?
>
> import time
> time.ctime(epochs)

Note that ctime makes a string in a particular format (not the
original one, though) from the local time. It might be better to use
strftime instead:

import time
time.strftime("%d/%m/%Y", epochs)

Paul

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


Re: Request for a change in the csv module.

2007-03-13 Thread Diez B. Roggisch
Paulo da Silva wrote:

> Diez B. Roggisch escreveu:
>> Paulo da Silva schrieb:
> ...
> 
>>> That works but it is a pain to use.
>> 
>> Why? I think it's straightforward.
> 
> That is not the point. The problem is to have things generalized.
> I have some general purpose tables whose fields format I don't know
> in advance.
> Internally the numeric values are independent of localization.
> Having a table, I don't like the idea of preformating things
> before sending them to the csv for exportation. A little more
> of programming and there will be no need for csv at all :-)
> ...

This is simply _not_ true. The details of a proper CSV format are difficult
to get right, which is precisely why the module is there.

>> The same is essentially true for dates as well, btw. How do you want to
>> deal with them?
> 
> This is a pertinent question I didn't think of. May be csv should handle
> data conversions using 'locale'.
> It is already automatically converting numbers to text
> anyway, but unconditionally using the '.'.
> As for the dates the dialect could include a format like -MM-DD
> hh:mm:ss. Dates are not always 'locale' only. In pt_PT we use
> -MM-DD or YY-MM-DD and sometimes DD-MM-.
> One must remember that csv is not part of the language. So, to have
> some kind of universality, it must use the specs (in dialect) for
> formatting and 'locale' for data conversions.

I'm not too convinced. It's so darn easy to convert the values to what one
really needs for the actual use-case. Even for your generic case - all you
need is type-based formatting dispatch.

But if you add that complexity to the writers of the csv-module, you'll end
up with a nasty configuration mechanism for special casing individual
columns, or otherwise the next user comes and says "well, I need to format
dates differently just for this case, how to do so in the csv-module". As
your own example shows. 

The purpose of the module is solely to assist in creating properly formatted
csv content in the sense that it is readable and parsable and results in
strings for column values. Not more, not less (and you seem to
underestimate that task, btw.)

That it does convert non-string-values to strings when writing could be seen
as convenience, or actual bug as it might cause troubles as you perceived
them - but the solution would clearly be to get rid of this functionality,
not enhance it.

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


Re: Request for a change in the csv module.

2007-03-13 Thread skip

Paulo> That is not the point. The problem is to have things generalized.

Well, perhaps.  One of the goals of the csv module was to do things the way
Excel does things.  Ideally, that would include formatting elements with
locale sensitivity.  I've been working on a csv module in Python, so I
decided to try the locale.format() calls in its writerow implementation.  A
number of test cases broke as a result because apparently locale.format
doesn't do its job quite the same way Excel does.  I don't think pushing the
locale-sensitive formatting down into the csv module is going to be a
panacea.

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


most complete xml package for Python?

2007-03-13 Thread metaperl
Without even checking them all out, I'm thinking the Amara XML Toolkit
must be the most feature-packed. The developers are readily available
on IRC for support and they seem to make regular releases.

As a meld3 user, I have been using ElementTree under the hood, but was
dismayed to find out that you can't find elements by attribute and I
am finding it difficult to remove elements.

So I am out shopping for a new friend to grok XML.

Input welcome.

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


Re: number generator

2007-03-13 Thread Dick Moores
At 02:52 AM 3/13/2007, Duncan Booth wrote:
>Dick Moores <[EMAIL PROTECTED]> wrote:
>
> > But let's say there is one more constraint--that for each n of the N
> > positive integers, there must be an equal chance for n to be any of
> > the integers between 1 and M-N+1, inclusive. Thus for M == 50 and N
> >== 5, the generated list of 5 should be as likely to be [1,46,1,1,1]
> > as [10,10,10,10,10] or [14, 2, 7, 1, 26].
>
>I don't think what you wrote actually works. Any combination including a 46
>must also have four 1s, so the digit 1 has to be at least 4 times as likely
>to appear as the digit 46, and probably a lot more likely than that.

Yes, I see you're right. Thanks.

>On the other hand, making sure that each combination occurs equally often
>(as your example might imply) is doable but still leaves the question
>whether the order of the numbers matters: are [1,46,1,1,1] and [1,1,46,1,1]
>the same or different combinations?

If the added constraint is instead that the probability of generating 
a given list of length N be the same as that of generating any other 
list of length N, then I believe my function does the job. Of course, 
[1,46,1,1,1] and [1,1,46,1,1], as Python lists, are distinct. I ran 
this test for M == 8 and N == 4:
==
def sumRndInt(M, N):
 import random
 while True:
 lst = []
 for x in range(N):
 n = random.randint(1,M-N+1)
 lst.append(n)
 if sum(lst) == M:
 return lst

A = []
B = []
for x in range(10):
 lst = sumRndInt(8,4)
 if lst not in A:
 A.append(lst)
 B.append(1)
 else:
 i = A.index(lst)
 B[i] += 1

A.sort()
print A
print B
print len(A), len(B)
===
a typical run produced:
[[1, 1, 1, 5], [1, 1, 2, 4], [1, 1, 3, 3], [1, 1, 4, 2], [1, 1, 5, 
1], [1, 2, 1, 4], [1, 2, 2, 3], [1, 2, 3, 2], [1, 2, 4, 1], [1, 3, 1, 
3], [1, 3, 2, 2], [1, 3, 3, 1], [1, 4, 1, 2], [1, 4, 2, 1], [1, 5, 1, 
1], [2, 1, 1, 4], [2, 1, 2, 3], [2, 1, 3, 2], [2, 1, 4, 1], [2, 2, 1, 
3], [2, 2, 2, 2], [2, 2, 3, 1], [2, 3, 1, 2], [2, 3, 2, 1], [2, 4, 1, 
1], [3, 1, 1, 3], [3, 1, 2, 2], [3, 1, 3, 1], [3, 2, 1, 2], [3, 2, 2, 
1], [3, 3, 1, 1], [4, 1, 1, 2], [4, 1, 2, 1], [4, 2, 1, 1], [5, 1, 1, 1]]

[2929, 2847, 2806, 2873, 2887, 2856, 2854, 2825, 2847, 2926, 2927, 
2816, 2816, 2861, 2919, 2820, 2890, 2848, 2898, 2883, 2820, 2820, 
2829, 2883, 2873, 2874, 2891, 2884, 2837, 2853, 2759, 2761, 2766, 2947, 2875]

35 35

Dick Moores




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


How to capture environment state after running a shell script.

2007-03-13 Thread Gerard Flanagan
Hello,

I have a third party shell script which updates multiple environment
values, and I want to investigate (and ultimately capture to python)
the environment state after the script has run. But running the script
as a child process only sets values for that process, which are lost
after execution.  So I thought I could simply tack on an 'env' command
line to the script input lines as shown below. However, using
subprocess.Popen gives the error shown (even though the docs say that
any file object may be used for stdin), and using popen2 hangs
indefinitely. I think I'm missing something basic, any advice? Or is
there a better approach?

(This is Python 2.4 and a Korn shell script on AIX Unix)

Thanks in advance.

from StringIO import StringIO
from subprocess import Popen
from popen2 import popen2

fname = '/opt/WebSphere/AppServer/bin/setupCmdLine.sh'

buf = StringIO()

f = open(fname, 'r')

try:
f.readline() #ignore shebang
for line in f:
buf.write(line)
finally:
f.close()

buf.write('\nenv\n')

buf.seek(0)

## first method ##
p = Popen('/bin/sh', stdin=buf)
print p.stdout.readlines()

Traceback (most recent call last):
  File "scratch.py", line 36, in ?
p = Popen('/bin/sh', stdin=buf)
  File "/usr/local/lib/python2.4/subprocess.py", line 534, in __init__
(p2cread, p2cwrite,
  File "/usr/local/lib/python2.4/subprocess.py", line 830, in
_get_handles
p2cread = stdin.fileno()
AttributeError: StringIO instance has no attribute 'fileno'

## second method ##
cmdout, cmdin = popen2('/bin/sh')
for line in buf:
cmdin.write(line)

ret = cmdout.readlines()
cmdout.close()
cmdin.close()

print ret

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


[EMAIL PROTECTED]

2007-03-13 Thread thatboatguy
[EMAIL PROTECTED]

Here spider spider spiderr!

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


Re: Python in a desktop environment

2007-03-13 Thread Lou Pecora
In article <[EMAIL PROTECTED]>,
 Grant Edwards <[EMAIL PROTECTED]> wrote:

> > I'm a Python developer, I don't give a rats ass about what
> > people say about C#, Python, or c++, they all have their uses.
> > My main reasoning for considering C++ as the backend is some
> > things (reading memory for example) are much easier to do in
> > C++ than in Python, and we already have a lot written in C++.
^

[cut]

> > Anyways, thanks for everyones feedback, we will most likely go
> > with a combination of Python and C++.
> 
> I think you're nuts to decide that you need C++ before you've
> tested a Python implementation, but it's your nickle. :)

It really sounds like it's the C++ legacy that's driving Mr. Edward's 
decision.  The rest are just arguing points. Which several people have 
jumped at.

-- Lou Pecora  (my views are my own) REMOVE THIS to email me.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: httplib/socket problems reading 404 Not Found response

2007-03-13 Thread Patrick Altman
> Yes, it's a known problem. See this message with a 
> self-response:http://mail.python.org/pipermail/python-list/2006-March/375087.html

Are there plans to include this fix in the standard Python libraries
or must I make the modifications myself (I'm running Python 2.5)?


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


Re: Python in a desktop environment

2007-03-13 Thread Grant Edwards
On 2007-03-13, Dennis Lee Bieber <[EMAIL PROTECTED]> wrote:
> On Mon, 12 Mar 2007 15:45:30 -, Grant Edwards <[EMAIL PROTECTED]>
> declaimed the following in comp.lang.python:
>
>> 
>> IMO, robustness is also a quality of a language.  In language
>> like C and C++, it's difficult to write a program that isn't
>> full of potential crashes and exploits: buffer overflows,
>> broken pointers, memory leaks, etc.  Python eliminates many of
>> those sources of problems, and is therefore a "more robust"
>> language.
>
>   And if one doesn't like the dynamic behavior of Python, there is
> always a visit to comp.lang.ada

Or Modula-3.

-- 
Grant Edwards   grante Yow!  I am KING BOMBA of
  at   Sicily!...I will marry
   visi.comLUCILLE BALL next Friday!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: number generator

2007-03-13 Thread Anton Vredegoor
Dick Moores wrote:

> If the added constraint is instead that the probability of generating 
> a given list of length N be the same as that of generating any other 
> list of length N, then I believe my function does the job. Of course, 
> [1,46,1,1,1] and [1,1,46,1,1], as Python lists, are distinct. I ran 
> this test for M == 8 and N == 4:

Yes, I believe your function is OK. But the 'fencepost' method posted 
earlier in this thread also does this and it's faster AND it's only two 
line of code ...

> A = []
> B = []
> for x in range(10):
>  lst = sumRndInt(8,4)
>  if lst not in A:
>  A.append(lst)
>  B.append(1)
>  else:
>  i = A.index(lst)
>  B[i] += 1
> 
> A.sort()

Doesn't sorting break the correspondence between A and B? Also, a more 
pythonic way to count would be to convert the lst into a tuple and then 
do something with a dictionary. Dictionaries have faster lookup. For 
example:

T = tuple(lst)
D[T] = D.get(T,0) + 1

in the loop in order to count the occurrences.

I'm totally fascinated with this stuff myself so it's a bit hard to 
guess whether someone still is interested, but anyway, here are some 
further explorations involving partitions. The code prints the number of 
distinct permutations for each partition.

from operator import mul

def part(m,n,r):
 L = [0]*n
 while m:
 x =  pn(m-1,n-1)
 if r < x:
 L[n-1] += 1
 m -= 1
 n -= 1
 else:
 for i in range(n):
 L[i] += 1
 r -= x
 m -= n
 return L

def memoize(fn):
 cache = {}
 def proxy(*args):
 try: return cache[args]
 except KeyError: return cache.setdefault(args, fn(*args))
 return proxy

@memoize
def pn(m,n):
 if mhttp://mail.python.org/mailman/listinfo/python-list


Re: number generator

2007-03-13 Thread Duncan Booth
Dick Moores <[EMAIL PROTECTED]> wrote:

>>On the other hand, making sure that each combination occurs equally
>>often (as your example might imply) is doable but still leaves the
>>question whether the order of the numbers matters: are [1,46,1,1,1]
>>and [1,1,46,1,1] the same or different combinations?
> 
> If the added constraint is instead that the probability of generating 
> a given list of length N be the same as that of generating any other 
> list of length N, then I believe my function does the job.

I believe you are correct about the distribution. Unfortunately the 
running time for sumRndInt seems to go up exponentially as it gets stuck 
in that while loop desperately trying to find a random sequence that 
fits. 

C>timeit.py -s"from test import sumRndInt" "sumRndInt(50,4)"
100 loops, best of 3: 5.23 msec per loop

C>timeit.py -s"from test import sumRndInt" "sumRndInt(50,5)"
10 loops, best of 3: 21.8 msec per loop

C>timeit.py -s"from test import sumRndInt" "sumRndInt(50,6)"
10 loops, best of 3: 108 msec per loop

C>timeit.py -s"from test import sumRndInt" "sumRndInt(50,7)"
10 loops, best of 3: 861 msec per loop

C>timeit.py -s"from test import sumRndInt" "sumRndInt(50,40)"
... still waiting ...

By comparison, the algorithm using sorted(sample(...)) finishes quickly 
for all input values and also gives a flat distribution:

C>timeit.py -s"from partition import partition" "partition(50,4,1)"
10 loops, best of 3: 20.2 usec per loop

C>timeit.py -s"from partition import partition" "partition(50,5,1)"
1 loops, best of 3: 23 usec per loop

C>timeit.py -s"from partition import partition" "partition(50,6,1)"
1 loops, best of 3: 25.2 usec per loop

C>timeit.py -s"from partition import partition" "partition(50,7,1)"
1 loops, best of 3: 29.6 usec per loop

C>timeit.py -s"from partition import partition" "partition(50,40,1)"
1 loops, best of 3: 100 usec per loop
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: most complete xml package for Python?

2007-03-13 Thread Gerard Flanagan
On Mar 13, 1:43 pm, "metaperl" <[EMAIL PROTECTED]> wrote:
> Without even checking them all out, I'm thinking the Amara XML Toolkit
> must be the most feature-packed. The developers are readily available
> on IRC for support and they seem to make regular releases.
>
> As a meld3 user, I have been using ElementTree under the hood, but was
> dismayed to find out that you can't find elements by attribute and I
> am finding it difficult to remove elements.

Hardly in competition with Amara or lxml, but I wrote this extension
to ElementTree which handles attributes to a limited extent:

http://gflanagan.net/site/python/utils/elementfilter/

(Be aware that parts of the filter string are 'eval-ed')

Gerard


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


Re: glob.glob output

2007-03-13 Thread Hitesh
On Mar 12, 4:33 pm, Bruno Desthuilliers
<[EMAIL PROTECTED]> wrote:
> Hitesh a écrit :
>
> > import string
> > import os
>
> > f = open ("c:\\servername.txt", 'r')
> > linelist = f.read()
>
> > lineLog = string.split(linelist, '\n')
> > lineLog = lineLog [:-1]
> > #print lineLog
> > for l in lineLog:
> > path1 = "" + l + "\\server*\\*\\xtRec*"
> > glob.glob(path1)
>
> And ? What are you doing then with return value of glob.glob ?
>
> BTW, seems like an arbitrarily overcomplicated way to do:
>
> from glob import glob
> source = open(r"c:\\servername.txt", 'r')
> try:
>for line in source:
>  if line.strip():
>found = glob(r"\\%s\server*\*\xtRec*" % line)
>print "\n".join(found)
> finally:
>source.close()
>
> > When I run above from command line python, It prints the output of
> > glob.glob
> > but when I run it as a script, it does not print
> > anything
>
> Not without an explicit print statement. This behaviour is useful in the
> interactive python shell, but would be really annoying in normal use.
>
> > I know that there are files like xtRec* inside those
> > folders.. and glob.glob does spits the path if run from python command
> > line.
>
> > I tried something like this but did not work:
> > for l in lineLog:
> > path1 = "" + l + "\\server*\\*\\xtRec*"
> > xtRec = glob.glob(path1)
> > print xtRec
>
> > No results...
>
> With the same source file, on the same filesystem ? Unless your xtRec*
> files have been deleted between both tests you should have something here.
>
> > xtRec = []
> > for l in lineLog:
> > path1 = "" + l + "\\server*\\*\\xtRec*"
> > xtrec = glob.glob(path1)
>
> You're rebinding xtRec each turn. This is probably not what you want.


Thank you for your reply.
>From the return value I am trying to figure out whether the file
xtRec* exist or not.
I am newbie so exuse my ignorance... still learning.
Somehow when I tried your solution, it takes 10mins to scan 200 plus
servers but when I tried my code, it takes less then 2 mins.
This is a puzzle for me, I gotta figure it out.

hj


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


CD insert/eject detection

2007-03-13 Thread Mark Bryan Yu
Hi,

I'm trying to make a Audio CD ripper using python.

is there a way (library, module, etc) to detect when a CD was inserted
or ejected?

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


Re: glob.glob output

2007-03-13 Thread Bruno Desthuilliers
Hitesh a écrit :
> On Mar 12, 4:33 pm, Bruno Desthuilliers
> <[EMAIL PROTECTED]> wrote:
>> Hitesh a écrit :
>>
(snip)
> Thank you for your reply.
> From the return value I am trying to figure out whether the file
> xtRec* exist or not.

Yes, I had understood this !-)

What I wanted to point out was the fact you were discarding this value.

> I am newbie so exuse my ignorance... still learning.

Been here, done that... Don't worry. We're all still learning.

> Somehow when I tried your solution, it takes 10mins to scan 200 plus
> servers but when I tried my code,

Which one ? The original one, or the one where you first store glob 
results in a list ?

> it takes less then 2 mins.
> This is a puzzle for me, I gotta figure it out.

i/o are usually expansive, so the difference may comes from the repeated 
print. Also, I'm doing a bit of formatting, which is not your case.

FWIW, my own snippet was just an example of the idiomatic way to read a 
text file line by line. Doing TheRightThing(tm) for your actual problem 
is your responsability !-)
-- 
http://mail.python.org/mailman/listinfo/python-list


i can`t get python working on the command line (linux)

2007-03-13 Thread Mark

Hey,

first of all: sorry for the 100% n00b question
i`m brand new to python and i seem to start off with the biggest problem of
all.. not even getting python to work.
i`m running Fedora core 7 test 2 and all the python based applications are
working fine (like pirut, pipet, and some other yum related tools)

but when i try to run this script:

#!/usr/bin/python
#
# python script tel.py
# gevonden door Jan Mooij 24 september 2000
#
from sys import *
from string import *

# Create an empty dictionary.
count = {}

for line in open(argv[1], 'r').readlines():
   for word in split(line):
   if count.has_key(word):
   count[word] = count[word] + 1
   else:
   count[word] = 1
words = count.keys()
words.sort()
for word in words:
   print "%15s\t%10d" % (word, count[word])


and i`ve put it in tel.py (just the same as in the sample) than chmod
it to 777 (just to make sure it isn`t a permission issue) and than i
run it with: ./tel.py
now this is the error that i get:

Traceback (most recent call last):
 File "./tel.py", line 12, in 
   for line in open(argv[1], 'r').readlines():
IndexError: list index out of range

also i`m not even getting the most simple sample code to work.. "Hello World".
everything works fine when i first enter the python console by typing
python. than i have the  >>> things
than print "Hello World" gives me the expected result but that`s not
what i want.. i want to do it from a file..

the solution is probable extremely simple but i have no idea as a
complete n00b in python. i do have alot php experience.
hope someone could help me out with this.

o and any function that i use in python gives me "command not found:
print/whatever function i use"
(probable just a simple yum install command that i need to do to get
this working.. just try to figure that out with no python knowledge)

Thanx alot in favor.
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Eureka moments in Python

2007-03-13 Thread Brett g Porter
Steven D'Aprano wrote:
> I'd be interested in hearing people's stories of Eureka moments in Python,
> moments where you suddenly realise that some task which seemed like it
> would be hard work was easy with Python.

Mine was definitely when I was first working with the xmlrpc module, and 
I was puzzled to no end how it was that I was able to make a call to a 
method of an object when that method didn't exist. All the talk about 
Python being a dynamic language had bounced off of me until that moment, 
when I walked through the __getattr__ method in the debugger and was 
enlightened.

Not surprisingly, that was also the moment when C++ started feeling like 
a straightjacket to me...

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


Re: CD insert/eject detection

2007-03-13 Thread Larry Bates
Mark Bryan Yu wrote:
> Hi,
> 
> I'm trying to make a Audio CD ripper using python.
> 
> is there a way (library, module, etc) to detect when a CD was inserted
> or ejected?
> 
That is going to be OS dependent, so please share with us
what OS you are on?

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


Re: CD insert/eject detection

2007-03-13 Thread Mark Bryan Yu
On Mar 13, 11:07 am, Larry Bates <[EMAIL PROTECTED]> wrote:
> Mark Bryan Yu wrote:
> > Hi,
>
> > I'm trying to make a Audio CD ripper using python.
>
> > is there a way (library, module, etc) to detect when a CD was inserted
> > or ejected?
>
> That is going to be OS dependent, so please share with us
> what OS you are on?
>
> -Larry

Linux. I guess that means i need to make a C/C++ module extension to
do such task.

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


Re: number generator

2007-03-13 Thread Dick Moores
At 06:59 AM 3/13/2007, Anton Vredegoor wrote:
>Dick Moores wrote:
>
> > If the added constraint is instead that the probability of generating
> > a given list of length N be the same as that of generating any other
> > list of length N, then I believe my function does the job. Of course,
> > [1,46,1,1,1] and [1,1,46,1,1], as Python lists, are distinct. I ran
> > this test for M == 8 and N == 4:
>
>Yes, I believe your function is OK. But the 'fencepost' method posted
>earlier in this thread also does this and it's faster AND it's only two
>line of code ...

Yes, I tested that after posting mine. Paul Rubin's fencepost method 
is about 14 times faster than mine for the same M == 8 and N == 4!  :(

> > A = []
> > B = []
> > for x in range(10):
> >  lst = sumRndInt(8,4)
> >  if lst not in A:
> >  A.append(lst)
> >  B.append(1)
> >  else:
> >  i = A.index(lst)
> >  B[i] += 1
> >
> > A.sort()
>
>Doesn't sorting break the correspondence between A and B?

Yes, but I thought that it would be easier to see that all the 
permutations are represented. It seemed clear enough that with larger 
num, all counts would approach num/35..

>  Also, a more
>pythonic way to count would be to convert the lst into a tuple and then
>do something with a dictionary. Dictionaries have faster lookup. For
>example:
>
>T = tuple(lst)
>D[T] = D.get(T,0) + 1
>
>in the loop in order to count the occurrences.

Sorry, I don't understand this. Could you spell it out for me by 
rewriting my above test to use it? Thanks!

Dick Moores


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


Re: help developing an editor to view openoffice files.

2007-03-13 Thread Ken Starks
krishnakant Mane wrote:
> hello,
> right now I am involved on doing a very important accessibility work.
> as many people may or may not know that I am a visually handicap
> person and work a lot on accessibility.  the main issue at hand is to
> create an accessible editor for open office.
> there are a lot of things remaining on that front.
> so right now I am trying to find out a temporary work around by
> creating a simple accessible editor (with wxpython) for viewing and
> editing open office files.
> I know there must be python libraries that can open/ save .odt files
> because it is an open standard any ways.
> but I am trying to work out a kind of a program where those files can
> also be displayed in a text area with all the formatting.
> probably one way of doing it is to use some thing like a rich text
> editor and allow the file to be converted to rtf from odt for viewing
> and back again to odt when the user wishes to save it.
> another way I find is to actually find out if there is a odt text box
> that can display these files as they are.
> viewing the contents of the files in an editable way is most important.
> any suggestions?
> regards.
> Krishnakant.

There is an O'Reilly Book about hacking the Open Office Format, and
it is available free on line in both html and pdf.

Open office files are a variation on 'Zipped' archives and
many unzip tools can be used to open them, apart from ones
that insist on a .zip extension. These include python tools.

The one 'case study' in the book that uses python is actually for
a spreadsheet, but that makes little difference to the
'unzipping' part.  You can find it at:

http://books.evc-cit.info/odbook/ch05.html#modify-spreadsheet-section

Once you have the raw XML you should be able to convert it to any one of
many more accessible XML formats, for screen readers, brail
printers and so on. I don't know much about them, but hopefully you
do!

Don't re-invent the wheel! You will find quite a few ways on the Open
Office Wiki for converting the format to other things. You can also
daisy-tail the XSLT files; for example use one to convert to xhtml and
a second that converts xhtml to text.

Example (Display write files in the 'Firefox' browser).
http://wiki.services.openoffice.org/wiki/Firefox_ODFReader_extension


Don't forget that Open Office already has PDF export facilities, and
Acrobat reader already has some accessibility ability for simple 
documents (i.e single column, 'start at the beginning, keep going until
you get to the end, and then stop'). For adding structure to other PDF 
files you would need Acrobat Professional or software that can export 
'tagged' PDFs.

The case-study code is:

import xml.dom
import xml.dom.ext
import xml.dom.minidom
import xml.parsers.expat
import sys
import od_number
from zipfile import *
from StringIO import *

if (len(sys.argv) == 4):

 #   Open an existing OpenDocument file
 #
 inFile = ZipFile( sys.argv[1] )

 #   ...and a brand new output file
 #
 outFile = ZipFile( sys.argv[2], "w", ZIP_DEFLATED );

 getParameters( sys.argv[3] )

 #
 #   modify all appropriate currency styles
 #
 fixCurrency( "styles.xml" )
 fixCurrency( "content.xml" )

 #
 #   copy the manifest
 #
 copyManifest( )

 inFile.close
 outFile.close
else:
 print "Usage: " + sys.argv[0] + " inputfile outputfile parameterfile"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Best place for a function?

2007-03-13 Thread Inyeol Lee
On Sun, Mar 11, 2007 at 06:36:02PM +0100, Bruno Desthuilliers wrote:
> Inyeol Lee a �crit :
> > On Wed, Mar 07, 2007 at 05:27:04PM -0500, Sergio Correia wrote:
> > 
> >>I'm writing a class, where one of the methods is kinda complex. The
> >>method uses a function which I know for certain will not be used
> >>anywhere else. This function does not require anything from self, only
> >>the args passed by the method.
> >>
> >>Where should I put the function?
> > 
> > 
> > Use staticmethod. It's a normal function with class namespace.
> 
> What do you think the OP will gain from making a simple helper function 
> a staticmethod ? Apart from extra lookup time ?

Namespace.
Plz check this old thread. It explains some usage of staticmethod.
  http://mail.python.org/pipermail/python-list/2003-February/190258.html

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

Re: glob.glob output

2007-03-13 Thread Hitesh
On Mar 13, 11:00 am, Bruno Desthuilliers  wrote:
> Hitesh a écrit :
>
> > On Mar 12, 4:33 pm, Bruno Desthuilliers
> > <[EMAIL PROTECTED]> wrote:
> >> Hitesh a écrit :
>
> (snip)
> > Thank you for your reply.
> > From the return value I am trying to figure out whether the file
> > xtRec* exist or not.
>
> Yes, I had understood this !-)
>
> What I wanted to point out was the fact you were discarding this value.
>
> > I am newbie so exuse my ignorance... still learning.
>
> Been here, done that... Don't worry. We're all still learning.
>
> > Somehow when I tried your solution, it takes 10mins to scan 200 plus
> > servers but when I tried my code,
>
> Which one ? The original one, or the one where you first store glob
> results in a list ?
>
> > it takes less then 2 mins.
> > This is a puzzle for me, I gotta figure it out.
>
> i/o are usually expansive, so the difference may comes from the repeated
> print. Also, I'm doing a bit of formatting, which is not your case.
>
> FWIW, my own snippet was just an example of the idiomatic way to read a
> text file line by line. Doing TheRightThing(tm) for your actual problem
> is your responsability !-)

Thank you :-). I understand that now!

hj

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


Re: number generator

2007-03-13 Thread Anton Vredegoor
Dick Moores wrote:

> Paul Rubin's fencepost method is about 14 times faster than mine for
> the same M == 8 and N == 4!  :(

Actually they looked a bit similar after I had mucked a bit with them 
:-) But indeed it's slow.

> Sorry, I don't understand this. Could you spell it out for me by 
> rewriting my above test to use it? Thanks!

OK here you go. I'm copying a modification from something that I used to 
check something else, I hope you recognize the code after my refactoring.

from itertools import islice
import random

def sumRndInt(m,n):
  while 1:
  L = [random.randint(1,m-n+1) for i in xrange(n)]
  if sum(L) == m:
  yield tuple(L)

def fencepost(m,n):
 while 1:
 t = sorted(random.sample(xrange(1,m), n-1))
 yield tuple((j-i) for i,j in zip([0]+t, t+[m]))

def freq(g,k):
 D = {}
 for x in islice(g,k):
 D[x] = D.get(x,0)+1
 return D

def test():
 m = 7
 n = 4
 k = 2
 R = freq(sumRndInt(m,n),k)
 F = freq(fencepost(m,n),k)
 assert sorted(R) == sorted(F)
 for x in sorted(R):
 print x,R[x],F[x]

if __name__=='__main__':
 test()
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: i can`t get python working on the command line (linux)

2007-03-13 Thread Sells, Fred
looks like it is expecting command line agrs that are not there.

put this at the top of your code to see what's going on

import sys
print sys.argv

remembering that the first element printed is sys.argv[0]



-Original Message-
From: [EMAIL PROTECTED]
[mailto:[EMAIL PROTECTED]
Behalf Of Mark
Sent: Tuesday, March 13, 2007 10:04 AM
To: python-list@python.org
Subject: i can`t get python working on the command line (linux)
[html-removed]


Hey,

first of all: sorry for the 100% n00b question
i`m brand new to python and i seem to start off with the biggest problem of
all.. not even getting python to work.
i`m running Fedora core 7 test 2 and all the python based applications are
working fine (like pirut, pipet, and some other yum related tools)

but when i try to run this script:

#!/usr/bin/python
#
# python script tel.py
# gevonden door Jan Mooij 24 september 2000
#
from sys import *
from string import *

 # Create an empty dictionary.
count = {}

for line in open(argv[1], 'r').readlines():
for word in split(line):
if count.has_key(word):
count[word] = count[word] + 1
else:
count[word] = 1
words = count.keys()
words.sort()
for word in words:
print "%15s\t%10d" % (word, count[word])


and i`ve put it in tel.py (just the same as in the sample) than chmod
it to 777 (just to make sure it isn`t a permission issue) and than i
run it with: ./tel.py
now this is the error that i get:

Traceback (most recent call last):
  File "./tel.py", line 12, in 
for line in open(argv[1], 'r').readlines():
IndexError: list index out of range

also i`m not even getting the most simple sample code to work.. "Hello
World".
everything works fine when i first enter the python console by typing
python. than i have the  >>> things
than print "Hello World" gives me the expected result but that`s not
what i want.. i want to do it from a file..

the solution is probable extremely simple but i have no idea as a
complete n00b in python. i do have alot php experience.
hope someone could help me out with this.

o and any function that i use in python gives me "command not found:
print/whatever function i use"
(probable just a simple yum install command that i need to do to get
this working.. just try to figure that out with no python knowledge)

Thanx alot in favor.
-- 
http://mail.python.org/mailman/listinfo/python-list
-- 
http://mail.python.org/mailman/listinfo/python-list


Communicating with a DLL under Linux

2007-03-13 Thread Mikael Olofsson
I am interested in peoples experience with communicating with DLLs under 
Linux.

Situation:

I'm an electrical engineer that finds pleasure in using my soldering 
iron from time to time. I also find programming, preferably in Python, 
entertaining. I wouldn't call myself a programmer, though. Now, I may 
have found a hobby project that could give me the pleasure from both 
those worlds. There's this USB development gadget for sale in my 
favourite electronics store, and I sure would like to have something 
like that connected to my lab computer (a fairly new budget computer 
running Kubuntu 6.06).

The gadget costs about 50 Euros. It's not a lot of money, but I would 
not like to buy the thing if there is a substancial risk that I will not 
be able to make it work on that computer. From what I've read on the 
box, it assumes Windows (a number of versions), it includes a DLL to 
communicate with it, and example code in VB (iirc). For the interested, 
here's the gadget:

http://www.elfa.se/elfa-bin/dyndok.pl?lang=en&vat=0&dok=9001.htm

I have been looking at ctypes, and from what I read, I should be able to 
communicate with a DLL by using ctypes. It even sounds fairly easy, as 
long as I know what the DLL is supposed to do. I expect there to be some 
kind of manual for the DLL included in the box. Are DLLs universal, or 
are there different DLLs for Windows and Linux (I'm not a programmer, 
remember)? If the vendor claims that the DLL is for Windows, is it 
reasonable to assume that it can be made to work under Linux, from 
Python, that is? Or is this perhaps completely out of the question?

So, who is willing share their experiences? Share advice? Is this as 
easy as it sounds to me? Any pitfalls around?

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


Re: struct.pack oddity

2007-03-13 Thread Erik Johnson

"Dave Opstad" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> Is the lack of a struct.error when the byte-order mark is at the start
> of the format intentional? This seems like a bug to me, but maybe
> there's a subtlety here I'm not seeing.

I am by no means any sort of expert on this module, but for what it's
worth, the behaviour is basically the same for my Python 2.4.3 under Cygwin
(except that there is no deprecation warning) and I agree with you: this
seems like a bug to me. Or maybe not technically a bug, but the behaviour
could be improved. I would expect to get the same struct.error in all three
cases:

$ python
Python 2.4.3 (#1, May 18 2006, 07:40:45)
[GCC 3.3.3 (cygwin special)] on cygwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from struct import *
>>> pack('H', 10)
Traceback (most recent call last):
  File "", line 1, in ?
struct.error: short format requires 0<=number<=USHRT_MAX
>>> pack('>H', 10)
'\x86\xa0'
>>> pack('>>

There used to be a form at the bottom left of the main site:
www.python.org for reporting bugs, but that now seems to be used only for
reporting stuff about the web site itself.  The struct module comes from
struct.dll, so I can't see any comments about who wrote or maintains that
module.

Barring anyone else disagreeing with classifying it as a bug, I would
suggest reporting it. Proper procedure for reporting a bug appears to be
covered in section B of the Python Library Reference:
http://docs.python.org/lib/reporting-bugs.html

Hope that helps,
-ej


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


Re: CD insert/eject detection

2007-03-13 Thread Diez B. Roggisch
Mark Bryan Yu wrote:

> On Mar 13, 11:07 am, Larry Bates <[EMAIL PROTECTED]> wrote:
>> Mark Bryan Yu wrote:
>> > Hi,
>>
>> > I'm trying to make a Audio CD ripper using python.
>>
>> > is there a way (library, module, etc) to detect when a CD was inserted
>> > or ejected?
>>
>> That is going to be OS dependent, so please share with us
>> what OS you are on?
>>
>> -Larry
> 
> Linux. I guess that means i need to make a C/C++ module extension to
> do such task.

http://www-128.ibm.com/developerworks/linux/library/l-dbus.html

might be a start.

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


Re: Request for a change in the csv module.

2007-03-13 Thread Paulo da Silva
Diez B. Roggisch escreveu:
> Paulo da Silva wrote:
...

> 
> That it does convert non-string-values to strings when writing could be seen
> as convenience, or actual bug as it might cause troubles as you perceived
> them - but the solution would clearly be to get rid of this functionality,
> not enhance it.


It's just a matter of
personal opinion, and IMO, taking in consideration what other python
modules provide, a csv module should make the appropriate data
conversions. It is simple to implement for most (all?) cases and it will
bring a lot of functionality. You just output things.
In csv output you don't need special data formats. Only the data to the
most available precision. Dates are a very special case, as are the
separators, line terminators, etc.

The python way of exporting this data should be something like:
class MyDialect(Dialect):
...
locale="[EMAIL PROTECTED]"
dateformat="-MM-DD hh:mm:ss"

...
w=csv.writer(f,dialect=MyDialect)
w.writerows(foo)

Frequent tasks should be done by the modules. Not by the users.
And csv is unusable without output formatting. This is particulary true
if, as you said, the csv didn't provide any conversion at all.
So, why force the programmers to repeat the same tedious procedures
whenever they want to use csv, not to talk about the lack of performance
that implies?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Request for a change in the csv module.

2007-03-13 Thread Paulo da Silva
[EMAIL PROTECTED] escreveu:
> Paulo> That is not the point. The problem is to have things generalized.
> 
> Well, perhaps.  One of the goals of the csv module was to do things the way
> Excel does things.

It would be nice because many csv users use it to export files to
spreadsheets and Excel is certainly a reference. But there may be a
difference! One thing is to do things as Excel does and another is
to write data in a way Excel understands. The later, IMO, is not so
complicated.

  Ideally, that would include formatting elements with
> locale sensitivity.  I've been working on a csv module in Python, so I
> decided to try the locale.format() calls in its writerow implementation.  A
> number of test cases broke as a result because apparently locale.format
> doesn't do its job quite the same way Excel does.
locale.format does not need to write the same way Excel does. It just
should convert in a way Excel understands.
Anyway, a csv user needs to do that if it is not provided by csv.

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


Server-side script takes way too long to launch

2007-03-13 Thread Teresa Hardy

I have a webpage calling a python script, using Apache
serverhttp://localhost/cgi-bin/mycode.py?dmn
I am using Firefox, WindowsXP Python 2.4

I can count to 13 from the time I click to the time the browser finds the
path.

The python runs okay when I finally get to it. In the first step it just
launches a Flash file. I benchmarked the time thru the python code and it
isn't the slow part. It's the launch. Forgive me if I am not explaining this
well. I am pretty much teaching myself...fumbling thru the process.

Any suggestions on how to speed up the first step?

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

Re: number generator

2007-03-13 Thread Paul Rubin
"Terry Reedy" <[EMAIL PROTECTED]> writes:
> P(m,n)  has no known exact formula but can be computed 
> inductively rather easily.  The partitions for m and n can be ranked in 
> lexicographic order from 0 to P(m,n)-1.  Given a rank r in that range, one 
> can calculate the particular partition that has that rank.  So a 
> equi-probable random count in the range can be turned into a equi-probable 
> random partition.

I don't see an efficient way to do that, but will try to look sometime
for the book you cited.

Here is a brute force generation approach (not fully tested since
I'm using Python 2.3):

from itertools import imap

# yield all partitions of n having length k, with many duplications
def _partitions(n,k):
if k==0: return
for i in xrange(1,n-k+1):
for p in partitions(n-i, k-1):
yield (i,)+p

def unique_partitions(n,k):
 return sorted(set(tuple(sorted(p)) for p in _partitions(n,k)))

p50_5 = unique_partitions(50,5)
assert len(p50_5) = 2611

Note the use of a generator expression in unique_partitions to
enumerate the non-unique partitions without remembering them all in
memory.  "set" strips out the duplicates and remembers only the unique
ones.  The above takes a few seconds to run on (50,5) on my 1.2 ghz laptop.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Server-side script takes way too long to launch

2007-03-13 Thread Josh Bloom

Teresa, when you call a python script this way, the server needs to load the
python interpreter for each call.

If you need faster execution you should look into having a server process
running already. Something like mod_python for apache or CherryPy will help
you speed this up.

-Josh


On 3/13/07, Teresa Hardy <[EMAIL PROTECTED]> wrote:


I have a webpage calling a python script, using Apache
serverhttp://localhost/cgi-bin/mycode.py?dmn
I am using Firefox, WindowsXP Python 2.4

I can count to 13 from the time I click to the time the browser finds the
path.

The python runs okay when I finally get to it. In the first step it just
launches a Flash file. I benchmarked the time thru the python code and it
isn't the slow part. It's the launch. Forgive me if I am not explaining this
well. I am pretty much teaching myself...fumbling thru the process.

Any suggestions on how to speed up the first step?

Thanks,
Teresa







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

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

Re: Communicating with a DLL under Linux

2007-03-13 Thread Grant Edwards
On 2007-03-13, Mikael Olofsson <[EMAIL PROTECTED]> wrote:

> The gadget costs about 50 Euros. It's not a lot of money, but I would 
> not like to buy the thing if there is a substancial risk that I will not 
> be able to make it work on that computer. From what I've read on the 
> box, it assumes Windows (a number of versions), it includes a DLL to 
> communicate with it, and example code in VB (iirc). For the interested, 
> here's the gadget:
>
> http://www.elfa.se/elfa-bin/dyndok.pl?lang=en&vat=0&dok=9001.htm
>
> I have been looking at ctypes, and from what I read, I should be able to 
> communicate with a DLL by using ctypes.

Only under Windows.

> It even sounds fairly easy, as long as I know what the DLL is
> supposed to do. I expect there to be some kind of manual for
> the DLL included in the box. Are DLLs universal, or are there
> different DLLs for Windows and Linux (I'm not a programmer, 
> remember)?

Yes.  Shared libraries (Called DLLs under Windows) are
different than shared libraries under Linux.

> If the vendor claims that the DLL is for Windows, is it
> reasonable to assume that it can be made to work under Linux

No.

> from Python, that is? Or is this perhaps completely out
> of the question?

It's probably out of the question.

-- 
Grant Edwards   grante Yow!  I am NOT a nut
  at   
   visi.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Server-side script takes way too long to launch

2007-03-13 Thread Jeff McNeil

But even if the server was loading Python on each hit, which it will for
CGI, it shouldn't take "a count to 13", especially on localhost. That to me
is an indication of a further problem.  Does it take that long to load with
each hit, or just the first following a server restart?  What do log
timestamps say from initial hit until last-byte from your Python script?

Might want to validate your Apache configuration and have a look at
httpd.apache.org.  Sounds to me like DNS lookups are enabled or something of
the sort.

Thanks,

Jeff


On 3/13/07, Josh Bloom <[EMAIL PROTECTED]> wrote:


Teresa, when you call a python script this way, the server needs to load
the python interpreter for each call.

If you need faster execution you should look into having a server process
running already. Something like mod_python for apache or CherryPy will help
you speed this up.

-Josh


On 3/13/07, Teresa Hardy < [EMAIL PROTECTED]> wrote:

> I have a webpage calling a python script, using Apache
> serverhttp://localhost/cgi-bin/mycode.py?dmn
> I am using Firefox, WindowsXP Python 2.4
>
> I can count to 13 from the time I click to the time the browser finds
> the path.
>
> The python runs okay when I finally get to it. In the first step it just
> launches a Flash file. I benchmarked the time thru the python code and it
> isn't the slow part. It's the launch. Forgive me if I am not explaining this
> well. I am pretty much teaching myself...fumbling thru the process.
>
> Any suggestions on how to speed up the first step?
>
> Thanks,
> Teresa
>
>
>
>
>
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>


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

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

Re: Communicating with a DLL under Linux

2007-03-13 Thread Bart Ogryczak
On Mar 13, 5:59 pm, Mikael Olofsson <[EMAIL PROTECTED]> wrote:
> If the vendor claims that the DLL is for Windows, is it
> reasonable to assume that it can be made to work under Linux, from
> Python, that is?

No. It's reasonable to assume, that there is no *easy* way to get
Win32's DLL working under unices. There are hackish ways, for example
MPlayer does support Win32's DLL codecs.
Linux/Unix shared libraries have completely different file format
(usually ELF).

http://en.wikipedia.org/wiki/Dynamic-link_library
http://en.wikipedia.org/wiki/Executable_and_Linkable_Format
http://en.wikipedia.org/wiki/Shared_library#Naming

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


Re: Eureka moments in Python

2007-03-13 Thread Dustan
On Mar 13, 10:05 am, Brett g Porter <[EMAIL PROTECTED]> wrote:
> Steven D'Aprano wrote:
> > I'd be interested in hearing people's stories of Eureka moments in Python,
> > moments where you suddenly realise that some task which seemed like it
> > would be hard work was easy with Python.
>
> Mine was definitely when I was first working with the xmlrpc module, and
> I was puzzled to no end how it was that I was able to make a call to a
> method of an object when that method didn't exist. All the talk about
> Python being a dynamic language had bounced off of me until that moment,
> when I walked through the __getattr__ method in the debugger and was
> enlightened.
>
> Not surprisingly, that was also the moment when C++ started feeling like
> a straightjacket to me...

Started? Meaning there was a time when it DIDN'T feel like a
straightjacket? If I were a journalist, this would be all over the
news...

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


Re: Eureka moments in Python

2007-03-13 Thread [EMAIL PROTECTED]
On Mar 13, 2:16 am, Steven D'Aprano <[EMAIL PROTECTED]>
wrote:
> I'd be interested in hearing people's stories of Eureka moments in Python,
> moments where you suddenly realise that some task which seemed like it
> would be hard work was easy with Python.
>

##I have this problem where, given a list of non-zero
##positive integers (sv), I need to calculate threee constants
##x, y, z where
##
##x is 2 raised to the power of the sum of the elements in sv,
##
##y is 3 raised to the power of the count of the elements in sv,
##
##and
##
##z is 3**a*2**A + 3**b*2**B + ... + 3**m*2**M + 3**n*2**N
##
##where a,b,...m,n are 0,1,...len(sv)-2,len(sv)-1 and
##N is the sum of all elements of sv except the last one,
##M is the sum of all elements of sv except the last two,
##...
##B is the sum of all elements of sv except the last len(sv)-1,
##A is the sum of all elements of sv except the last len(sv).
##
##This turned out to be one of those things that's
##easier to code than to describe.
##
##And if you saw my original Excel spreadsheet where I
##developed it, you'd say Eureka too.

def calc_xyz(sv):
x = 2**sum(sv)
y = 3**len(sv)
z = 0
for i in xrange(len(sv)):
z += 3**i * 2**sum(sv[:-(i+1)])
return (x,y,z)

sv = [1,2,3,4]
print calc_xyz(sv)

##(1024, 81, 133)

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


Re: Communicating with a DLL under Linux

2007-03-13 Thread jkn
Hi Mikael
It is probably worth you finding out more about the specific
Hardware that Velleman use for this kit. Depending on the chip
manufacturer, there may be more or less support already available. For
instance, I have recently been communicating with the FTDI USB chips
under windows. There is a PyUSB module which might help you do
something similar, and the FTDI website has quite a lot of
information.

As it turns out, I didn't use PyUSB - for reasons connected with the
version number of Python and annoying things like that (aside - has
anyone got PyUSB compiled for 2.5?). I developed my own pure python
interface to the FTDI chips DLL, using ctypes. So yes, this can be
done. I think you'd be on quite a learning curve for this, from what
you say, but don't let that put you off! Unfortunately I can't share
my code with you, but just knowing that it can be done is sometimes a
help...

FTDI make some evaluation boards for their USB chips and you might
consider going that route... http://www.ftdichip.com BTW. No
connection, just a customer/developer.

HTH
jon N

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


Re: struct.pack oddity

2007-03-13 Thread Larry Bates
Erik Johnson wrote:
> "Dave Opstad" <[EMAIL PROTECTED]> wrote in message
> news:[EMAIL PROTECTED]
>> Is the lack of a struct.error when the byte-order mark is at the start
>> of the format intentional? This seems like a bug to me, but maybe
>> there's a subtlety here I'm not seeing.
> 
> I am by no means any sort of expert on this module, but for what it's
> worth, the behaviour is basically the same for my Python 2.4.3 under Cygwin
> (except that there is no deprecation warning) and I agree with you: this
> seems like a bug to me. Or maybe not technically a bug, but the behaviour
> could be improved. I would expect to get the same struct.error in all three
> cases:
> 
> $ python
> Python 2.4.3 (#1, May 18 2006, 07:40:45)
> [GCC 3.3.3 (cygwin special)] on cygwin
> Type "help", "copyright", "credits" or "license" for more information.
 from struct import *
 pack('H', 10)
> Traceback (most recent call last):
>   File "", line 1, in ?
> struct.error: short format requires 0<=number<=USHRT_MAX
 pack('>H', 10)
> '\x86\xa0'
 pack(' '\xa0\x86'
> 
> There used to be a form at the bottom left of the main site:
> www.python.org for reporting bugs, but that now seems to be used only for
> reporting stuff about the web site itself.  The struct module comes from
> struct.dll, so I can't see any comments about who wrote or maintains that
> module.
> 
> Barring anyone else disagreeing with classifying it as a bug, I would
> suggest reporting it. Proper procedure for reporting a bug appears to be
> covered in section B of the Python Library Reference:
> http://docs.python.org/lib/reporting-bugs.html
> 
> Hope that helps,
> -ej
> 
> 
It looks like you have multiple "issues".

1) You can't put 10 into a half-word.  The limit is 2**16
or 65535. On Python 2.5 I get:

>>> struct.pack('H', 10)
Traceback (most recent call last):
  File "", line 1, in 
  File "C:\Python25\lib\struct.py", line 63, in pack
return o.pack(*args)
error: short format requires 0 <= number <= USHRT_MAX
>>> struct.pack('H', 65535)
'\xff\xff'
>>> struct.pack('>H', 10)
C:\Python25\Lib\struct.py:63: DeprecationWarning: 'H' format requires 0 <=
number <= 65535
  return o.pack(*args)
'\x86\xa0'
>>> struct.pack('>>

On the last try, struct.pack('http://mail.python.org/mailman/listinfo/python-list


Iterating across a filtered list

2007-03-13 Thread Drew
All -

I'm currently writing a toy program as I learn python that acts as a
simple address book. I've run across a situation in my search function
where I want to iterate across a filtered list. My code is working
just fine, but I'm wondering if this is the most "elegant" way to do
this. Essentially, I'm searching the dict self.contacts for a key that
matches the pattern entered by the user. If so, I print the value
associated with that key. A pastie to the method is below, any help/
advice is appreciated:

http://pastie.caboo.se/46647

Side note: I'm learning python after ruby experience. In ruby I would
do something like:

contacts.find_all{|name,contact| name =~ /search/}.each{|name,contact|
puts contact}

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


Re: number generator

2007-03-13 Thread Gabriel Genellina
En Tue, 13 Mar 2007 03:20:49 -0300, Hendrik van Rooyen  
<[EMAIL PROTECTED]> escribió:

> Is it possible to devise a test that can distinguish between sets
> of:
>
> - five random numbers that add to 50, and
> - four random numbers and a fudge number that add to 50?
>
> My stats are way too small and rusty to attempt to answer
> the question, but it seems intuitively a very difficult thing.

You can't have two different sets with four equal numbers - it's not a  
very difficult thing, it's impossible to distinguish because they're  
identical!
Given 4 numbers in the set, the 5th is uniquely determined. By example:  
12, 3, 10, 18 *must* end with 7. The 5th number is not "random". Any  
randomness analysis should include only the first 4 numbers (or any other  
set of 4).
In other words, there are only 4 degrees of freedom. In the fence analogy,  
you only have to choose where to place 4 poles; the 5th is fixed at the  
end.

-- 
Gabriel Genellina

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


Tools for GUI/graphics

2007-03-13 Thread Paulo da Silva
I need to make some data representation.
Basically a major window for a 2D chart,
a scrollable window with some few small 2D
graphics. The rest is a normal form with
buttons, labels and entries.

I thought of doing that using Tkinter+pmw+blt.
But now I'm considering use a web solution.
Is there anything that make this stuff easy?
I'm not searching for professional look. This
is for my personal use and the important is
the data processed and visualized I could get.
I gave a look at cherrypy but from a 1st sight
I couldn't see if it allows for easy graphic
charts - may be with svg ...

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


Re: CD insert/eject detection

2007-03-13 Thread [EMAIL PROTECTED]
I've never used it myself, but pygame (based on SDL - so it should
work for MS Windows, Linux, and Apple OSX) has a CD module with some
potentially useful functions, CD.eject() and CD.get_empty().

http://www.pygame.org/docs/ref/cdrom.html#pygame.cdrom.CD

-sjbrown

On Mar 13, 7:54 am, "Mark Bryan Yu" <[EMAIL PROTECTED]> wrote:
> Hi,
>
> I'm trying to make a Audio CD ripper using python.
>
> is there a way (library, module, etc) to detect when a CD was inserted
> or ejected?


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


Re: Iterating across a filtered list

2007-03-13 Thread Paul Rubin
"Drew" <[EMAIL PROTECTED]> writes:
> I'm currently writing a toy program as I learn python that acts as a
> simple address book. I've run across a situation in my search function
> where I want to iterate across a filtered list. My code is working
> just fine, but I'm wondering if this is the most "elegant" way to do
> this. Essentially, I'm searching the dict self.contacts for a key that
> matches the pattern entered by the user. If so, I print the value
> associated with that key. A pastie to the method is below, any help/
> advice is appreciated:

If I can decipher your Ruby example (I don't know Ruby), I think you
want:

   for name,contact in contacts.iteritems():
  if re.search('search', name):
  print contact

If you just want to filter the dictionary inside an expression, you
can use a generator expression:

  d = ((name,contact) for (name,contact) in contacts.iteritems() \
if re.search('search', name))

  print '\n'.join(d)   # prints items from filtered dict, one per line

Note that d is an iterator, which means it mutates when you step
through it.
-- 
http://mail.python.org/mailman/listinfo/python-list


Setting Up SOAPpy for Python v2.5 on Windows?

2007-03-13 Thread Steve
Hi All,

What are the required version of the SOAPpy, PyXML, fpconst that are
needed to run under the Python 2.5 environment on Windows?

Locations for the downloads?

Thanks!

Steve

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


Re: Iterating across a filtered list

2007-03-13 Thread Drew
On Mar 13, 2:42 pm, Paul Rubin  wrote:
> If I can decipher your Ruby example (I don't know Ruby), I think you
> want:
>
>for name,contact in contacts.iteritems():
>   if re.search('search', name):
>   print contact
>
> If you just want to filter the dictionary inside an expression, you
> can use a generator expression:
>
>   d = ((name,contact) for (name,contact) in contacts.iteritems() \
> if re.search('search', name))
>
>   print '\n'.join(d)   # prints items from filtered dict, one per line
>
> Note that d is an iterator, which means it mutates when you step
> through it.

Paul -

You're exactly on the mark. I guess I was just wondering if your first
example (that is, breaking the if statement away from the iteration)
was preferred rather than initially filtering and then iterating.
However, you're examples make a lot of sense are are quite helpful.

Thanks,
Drew

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


Re: How to capture environment state after running a shell script.

2007-03-13 Thread attn . steven . kuo
On Mar 13, 5:57 am, "Gerard Flanagan" <[EMAIL PROTECTED]> wrote:
> Hello,
>
> I have a third party shell script which updates multiple environment
> values, and I want to investigate (and ultimately capture to python)
> the environment state after the script has run. But running the script
> as a child process only sets values for that process, which are lost
> after execution.  So I thought I could simply tack on an 'env' command
> line to the script input lines as shown below. However, using
> subprocess.Popen gives the error shown (even though the docs say that
> any file object may be used for stdin), and using popen2 hangs
> indefinitely. I think I'm missing something basic, any advice? Or is
> there a better approach?
>

(snipped)

> ## first method ##
> p = Popen('/bin/sh', stdin=buf)
> print p.stdout.readlines()
>
> Traceback (most recent call last):
>   File "scratch.py", line 36, in ?
> p = Popen('/bin/sh', stdin=buf)
>   File "/usr/local/lib/python2.4/subprocess.py", line 534, in __init__
> (p2cread, p2cwrite,
>   File "/usr/local/lib/python2.4/subprocess.py", line 830, in
> _get_handles
> p2cread = stdin.fileno()
> AttributeError: StringIO instance has no attribute 'fileno'
>
> ## second method ##
> cmdout, cmdin = popen2('/bin/sh')
> for line in buf:
> cmdin.write(line)
>
> ret = cmdout.readlines()
> cmdout.close()
> cmdin.close()
>
> print ret



First close the input so that the (sub) process
knows to terminate and flush the output.  Then,
you can read from the output:

import subprocess
import popen2

p = subprocess.Popen(["/bin/sh"], stdin=subprocess.PIPE,
stdout=subprocess.PIPE)

p.stdin.write("env -i FOO=BAR\n")
p.stdin.close()
status = p.wait()
ret = p.stdout.readlines()
p.stdout.close()

print ret

# Or

cmdout, cmdin = popen2.popen2("/bin/sh")
cmdin.write("env -i FOO=BAR\n")
cmdin.close()
ret = cmdout.readlines()
cmdout.close

print ret

--
Hope this helps,
Steven

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


Re: Tools for GUI/graphics

2007-03-13 Thread Larry Bates
Paulo da Silva wrote:
> I need to make some data representation.
> Basically a major window for a 2D chart,
> a scrollable window with some few small 2D
> graphics. The rest is a normal form with
> buttons, labels and entries.
> 
> I thought of doing that using Tkinter+pmw+blt.
> But now I'm considering use a web solution.
> Is there anything that make this stuff easy?
> I'm not searching for professional look. This
> is for my personal use and the important is
> the data processed and visualized I could get.
> I gave a look at cherrypy but from a 1st sight
> I couldn't see if it allows for easy graphic
> charts - may be with svg ...
> 
> Thanks for any suggestions.

You can use ReportLab Graphics to generate the
graphs as .JPG files and display them in a
browser window with simple HTML.

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


Re: Starting an external, independent process from a script

2007-03-13 Thread Gabriel Genellina
On 12 Mar 2007 16:13:51 -0700, Henrik Lied <[EMAIL PROTECTED]> wrote:

>> I'm trying to create a video uploading service (just to learn). The
>> system is mostly based on Django, but the question I'm looking an
>> answer for is more related to Python.

En Tue, 13 Mar 2007 06:57:33 -0300, rishi pathak  
<[EMAIL PROTECTED]> escribió:

> You can do something like this:
> pid = os.fork()

I don't think it's a good idea, the running process is Django, not a  
script.

To the OP: I think the question *is* a Django question. You could launch  
the external process, finish the current request and redirect to another  
location; in that page you set a refresh to itself, and show the current  
status "somehow" depending on how your external process can report its  
progress. The details on how to do that, or even if that way is a good  
approach at all, depend on Django.

-- 
Gabriel Genellina

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


Re: Iterating across a filtered list

2007-03-13 Thread Arnaud Delobelle
On Mar 13, 6:04 pm, "Drew" <[EMAIL PROTECTED]> wrote:
> All -
Hi!

[snip]
> http://pastie.caboo.se/46647

There is no need for such a convoluted list comprehension as you
iterate over it immediately!  It is clearer to put the filtering logic
in the for loop.  Moreover you recalculate the regexp for each element
of the list.  Instead I would do something like this:

def find(search_str, flags=re.IGNORECASE):
print "Contact(s) found:"
search = re.compile(search_str, flags).search
for name, contact in self.contacts.items():
if search(name):
print contact
print

Although I would rather have one function that returns the list of all
found contacts:

def find(search_str, flags=re.IGNORECASE):
search = re.compile(search_str, flags).search
for name, contact in self.contacts.items():
if search(name):
yield contact

And then another one that prints it.

> Side note: I'm learning python after ruby experience. In ruby I would
> do something like:
>
> contacts.find_all{|name,contact| name =~ /search/}.each{|name,contact|
> puts contact}

And that's why you're right to learn Python ;)

HTH

--
Arnaud



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


Re: Iterating across a filtered list

2007-03-13 Thread Paul Rubin
"Drew" <[EMAIL PROTECTED]> writes:
> You're exactly on the mark. I guess I was just wondering if your first
> example (that is, breaking the if statement away from the iteration)
> was preferred rather than initially filtering and then iterating.

I think the multiple statement version is more in Python tradition.
Python is historically an imperative, procedural language with some OO
features.  Iterators like that are a new Python feature and they have
some annoying characteristics, like the way they mutate when you touch
them.  It's usually safest to create and consume them in the same
place, e.g. creating some sequence and passing it through map, filter, etc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Iterating across a filtered list

2007-03-13 Thread Paul Rubin
"Arnaud Delobelle" <[EMAIL PROTECTED]> writes:
> in the for loop.  Moreover you recalculate the regexp for each element
> of the list.

The re library caches the compiled regexp, I think.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: help developing an editor to view openoffice files.

2007-03-13 Thread Colin J. Williams
Ken Starks wrote:
> krishnakant Mane wrote:
>> hello,
>> right now I am involved on doing a very important accessibility work.
>> as many people may or may not know that I am a visually handicap
>> person and work a lot on accessibility.  the main issue at hand is to
>> create an accessible editor for open office.
>> there are a lot of things remaining on that front.
>> so right now I am trying to find out a temporary work around by
>> creating a simple accessible editor (with wxpython) for viewing and
>> editing open office files.
>> I know there must be python libraries that can open/ save .odt files
>> because it is an open standard any ways.
>> but I am trying to work out a kind of a program where those files can
>> also be displayed in a text area with all the formatting.
>> probably one way of doing it is to use some thing like a rich text
>> editor and allow the file to be converted to rtf from odt for viewing
>> and back again to odt when the user wishes to save it.
>> another way I find is to actually find out if there is a odt text box
>> that can display these files as they are.
>> viewing the contents of the files in an editable way is most important.
>> any suggestions?
>> regards.
>> Krishnakant.
> 
> There is an O'Reilly Book about hacking the Open Office Format, and
> it is available free on line in both html and pdf.
More expensive but well reviewed is:
 
http://www.amazon.com/gp/product/customer-reviews/013148205X/ref=cm_cr_dp_pt/103-7133293-6391046?ie=UTF8&n=283155&s=books

Colin W.
> 
> Open office files are a variation on 'Zipped' archives and
> many unzip tools can be used to open them, apart from ones
> that insist on a .zip extension. These include python tools.
> 
> The one 'case study' in the book that uses python is actually for
> a spreadsheet, but that makes little difference to the
> 'unzipping' part.  You can find it at:
> 
> http://books.evc-cit.info/odbook/ch05.html#modify-spreadsheet-section
> 
> Once you have the raw XML you should be able to convert it to any one of
> many more accessible XML formats, for screen readers, brail
> printers and so on. I don't know much about them, but hopefully you
> do!
> 
> Don't re-invent the wheel! You will find quite a few ways on the Open
> Office Wiki for converting the format to other things. You can also
> daisy-tail the XSLT files; for example use one to convert to xhtml and
> a second that converts xhtml to text.
> 
> Example (Display write files in the 'Firefox' browser).
> http://wiki.services.openoffice.org/wiki/Firefox_ODFReader_extension
> 
> 
> Don't forget that Open Office already has PDF export facilities, and
> Acrobat reader already has some accessibility ability for simple 
> documents (i.e single column, 'start at the beginning, keep going until
> you get to the end, and then stop'). For adding structure to other PDF 
> files you would need Acrobat Professional or software that can export 
> 'tagged' PDFs.
> 
> The case-study code is:
> 
> import xml.dom
> import xml.dom.ext
> import xml.dom.minidom
> import xml.parsers.expat
> import sys
> import od_number
> from zipfile import *
> from StringIO import *
> 
> if (len(sys.argv) == 4):
> 
>  #   Open an existing OpenDocument file
>  #
>  inFile = ZipFile( sys.argv[1] )
> 
>  #   ...and a brand new output file
>  #
>  outFile = ZipFile( sys.argv[2], "w", ZIP_DEFLATED );
> 
>  getParameters( sys.argv[3] )
> 
>  #
>  #   modify all appropriate currency styles
>  #
>  fixCurrency( "styles.xml" )
>  fixCurrency( "content.xml" )
> 
>  #
>  #   copy the manifest
>  #
>  copyManifest( )
> 
>  inFile.close
>  outFile.close
> else:
>  print "Usage: " + sys.argv[0] + " inputfile outputfile parameterfile"

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


Re: Setting Up SOAPpy for Python v2.5 on Windows?

2007-03-13 Thread Steven Bethard
Steve wrote:
> What are the required version of the SOAPpy, PyXML, fpconst that are
> needed to run under the Python 2.5 environment on Windows?

If you're not married to SOAPpy, you can use elementsoap which has just 
a single download and works with ElementTree from the 2.5 stdlib:

 http://effbot.org/downloads/#elementsoap


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


ANN: ActivePython 2.5.0.0 is now available

2007-03-13 Thread Trent Mick
I'm happy to announce that ActivePython 2.5.0.0 is now available for download
from:
 http://www.activestate.com/products/activepython/

This is the first release of ActivePython for Python version 2.5. Apologies
for the long delay between core Python 2.5 and this release. The good news is
that part of the reason for this delay was to finally get approval to include
crypto in ActivePython, hence:

Changes in this release include:
- Full OpenSSL support (finally!)
- Update to Python 2.5 (duh)
- [Mac OS X] Universal build (finally!)
- [Windows] Update to PyWin32 build 210
- All the new standard extensions: SQLite, ctypes, ElementTree
- [Linux] Rationalized the build names.
- [Mac OS X] A sane uninstall script

See the release notes for full details:
http://aspn.activestate.com/ASPN/docs/ActivePython/2.5/relnotes.html


What is ActivePython?
-

ActivePython is ActiveState's binary distribution of Python. Builds for
Windows, Mac OS X, Linux, HP-UX and AIX are made freely available.

ActivePython includes the Python core and the many core extensions: zlib and
bzip2 for data compression, the Berkeley DB (bsddb) and SQLite (sqlite3)
database libraries, the Tix GUI widgets for Tkinter, ElementTree for XML
processing, ctypes (on supported platforms) for low-level library access, and
others. The Windows distribution ships with PyWin32 -- a suite of Windows
tools developed by Mark Hammond, including bindings to the Win32 API and
Windows COM. See this page for full details:
http://aspn.activestate.com/ASPN/docs/ActivePython/2.5/whatsincluded.html

As well, ActivePython ships with a wealth of documentation for both new and
experienced Python programmers. In addition to the core Python docs,
ActivePython includes the "What's New in Python" series, "Dive into Python",
the Python FAQs & HOWTOs, and the Python Enhancement Proposals (PEPs).

An online version of the docs can be found here:
 http://aspn.activestate.com/ASPN/docs/ActivePython/2.5/welcome.html

We would welcome any and all feedback to:
 [EMAIL PROTECTED]

Please file bugs against ActivePython at:
 http://bugs.activestate.com/query.cgi?set_product=ActivePython


On what platforms does ActivePython run?


ActivePython includes installers for the following platforms:

- AIX/PowerPC
- HP-UX/PA-RISC
- Linux/x86
- Linux/x86_64: "x86_64" is also known as "AMD64"
- Solaris/SPARC
- Solaris/x86
- Mac OS X
- Windows/x64: "x64" is also known as "AMD64"
- Windows/x86


Extra Bits
--

ActivePython releases also include the following:

- ActivePython25.chm: An MS compiled help collection of the full
   ActivePython documentation set. Linux users of applications such as
   xCHM might find this useful. This package is installed by default on
   Windows.

Extra bits are available from:
 http://downloads.activestate.com/ActivePython/etc/


Thanks, and enjoy!

Trent, Python Tech Lead

--
Trent Mick
trentm at activestate.com

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


Re: Communicating with a DLL under Linux

2007-03-13 Thread John Nagle
Mikael Olofsson wrote:
> I am interested in peoples experience with communicating with DLLs under 
> Linux.
> 
> Situation:
> 
> I'm an electrical engineer that finds pleasure in using my soldering 
> iron from time to time. I also find programming, preferably in Python, 
> entertaining. I wouldn't call myself a programmer, though. Now, I may 
> have found a hobby project that could give me the pleasure from both 
> those worlds. There's this USB development gadget for sale in my 
> favourite electronics store, and I sure would like to have something 
> like that connected to my lab computer (a fairly new budget computer 
> running Kubuntu 6.06).

 Take a look at Wiring:

http://wiring.org.co/

That's an interface board with considerable onboard processing power
and a whole no-cost development environment that runs under Linux
or Windows.  It's intended for artists who want to build projects that need
some computer control.

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


Re: Single string print statements on multiple lines.

2007-03-13 Thread Gabriel Genellina
En Tue, 13 Mar 2007 08:31:17 -0300, Bruno Desthuilliers  
<[EMAIL PROTECTED]> escribió:

> Obviously, the OP is not trying to cheat (explicitelt
> aknowledging it is homework), and has a good enough understanding of
> what the usual solution is (asking for the escape char in Python).
>
> Now of course the answer is in the FineManual(tm), which implies that
> either the OP failed to read it, or that the FineManual is not so fine -
> but that's another problem.

If the FineManual(tm) is the Tutorial, it only explain escape sequences  
minimally, presuming some prior knowledge on the reader. For users with  
previous experience in different languages (like VB or Delphi) using \n is  
rather strange.

-- 
Gabriel Genellina

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


Re: struct.pack oddity

2007-03-13 Thread Dave Opstad
In article <[EMAIL PROTECTED]>,
 Larry Bates <[EMAIL PROTECTED]> wrote:

> 1) You can't put 10 into a half-word.  The limit is 2**16
> or 65535. On Python 2.5 I get:

Yes, I know. I used that example to illustrate the problem. If a value 
does not fit a format then Python should report that consistently, 
independent of whether a byte-order indication is explicit or implicit.

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


Re: httplib/socket problems reading 404 Not Found response

2007-03-13 Thread Gabriel Genellina
En Tue, 13 Mar 2007 10:38:24 -0300, Patrick Altman <[EMAIL PROTECTED]>  
escribió:

>> Yes, it's a known problem. See this message with a  
>> self-response:http://mail.python.org/pipermail/python-list/2006-March/375087.html

> Are there plans to include this fix in the standard Python libraries
> or must I make the modifications myself (I'm running Python 2.5)?

Submit a bug report, if not already done.
http://sourceforge.net/tracker/?group_id=5470

-- 
Gabriel Genellina

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


Getting a service's banner by connect to a port

2007-03-13 Thread mmcgee00
Hi,

Currently, I am trying to get different service banner by connecting
to different ports using python (code below).  The versions I am
working with are python 4.2.1 and fedora core 4.  I am trying to
reproduce a very small piece of nmap, since nmap has to get a port's
banner in order to figure out the version.  However, I haven't been
entirely successful.

***
maxBannerLength = 1024
def probeScan(host, port, probeString):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(6)
try:
s.connect((host, port))
s.send(probeString)
data = s.recv(maxBannerLength)

except socket.timeout:
print "socket.timeout exception"
data = ""
except socket.error, (value, message):
print "socket.error " +  message
data = ""

# Close connection and return banner/data
s.close()
return data

***

First off, the above code works fine for some ports.  I was able to
get the correct banners for some ports, some using the probeString as
an empty string and others as a different probeString.

But I have been having issues with many others.  The one I have tested
most recently was port 515 (services given from nmap on 2 ip addresses
are "printer" and "sdmsvc".  Now, I pass in the variable probeString
to the function as an empty string "", some of the ports (including
515) should give me the banner right away without needing a specific
probeString.  My python program is ending up in the socket.timeout
exception.  I have increased the timeout a couple of times to check if
that may be the problem, but no such luck.  I have been testing my
results from the above program with the results of netcat.  Netcat
gives me the correct banner when I pass it an empty string "".

As far as I have been able to figure out, I just need to connect to a
port, and send it a probeString.  As long as the correct probeString
is sent, the port(s) should give their banner.  I am pulling the
probeStrings from the nmap-service-probes file, which is the file that
nmap keeps its probes.  So, I am confident my probes are correct.

Has anyone ever run into this problem?  Or have suggestions?
I would greatly appreciate any information.

Thanks in advance.

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


Re: Iterating across a filtered list

2007-03-13 Thread Bruno Desthuilliers
Paul Rubin a écrit :
> "Drew" <[EMAIL PROTECTED]> writes:
> 
>>You're exactly on the mark. I guess I was just wondering if your first
>>example (that is, breaking the if statement away from the iteration)
>>was preferred rather than initially filtering and then iterating.
> 
> 
> I think the multiple statement version is more in Python tradition.

I don't know if I qualify as a Python traditionalist, but I'm using 
Python since the 1.5.2 days, and I usually favor list comps or generator 
expressions over old-style loops when it comes to this kind of operations.

> Python is historically an imperative, procedural language with some OO
> features.

Python has had functions as first class objects and (quite-limited-but) 
anonymous functions, map(), filter() and reduce() as builtin funcs at 
least since 1.5.2 (quite some years ago).

>  Iterators like that are a new Python feature

List comps are not that new (2.0 or 2.1 ?):
print "\n".join([contact for name, contact in contacts.items() \
  if search.match(name)])


> and they have
> some annoying characteristics, like the way they mutate when you touch
> them. 

While sequences are iterables, all iterables are not sequences. Know 
what you use, and you'll be fine.

> It's usually safest to create and consume them in the same
> place, e.g. creating some sequence and passing it through map, filter, etc.

Safest ? Why so ?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Iterating across a filtered list

2007-03-13 Thread Arnaud Delobelle
On Mar 13, 7:36 pm, Paul Rubin  wrote:
> "Arnaud Delobelle" <[EMAIL PROTECTED]> writes:
> > in the for loop.  Moreover you recalculate the regexp for each element
> > of the list.
>
> The re library caches the compiled regexp, I think.

That would surprise me.
How can re.search know that string.lower(search) is the same each
time?  Or else there is something that I misunderstand.

Moreover:

In [49]: from timeit import Timer
In [50]: Timer('for i in range(1000): search("abcdefghijk")', 'import
re; search=re.compile("ijk").search').timeit(100)
Out[50]: 0.36964607238769531

In [51]: Timer('for i in range(1000): re.search("ijk",
"abcdefghijk")', 'import re;
search=re.compile("ijk").search').timeit(100)
Out[51]: 1.4777300357818604

--
Arnaud

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


Re: struct.pack oddity

2007-03-13 Thread Dave Opstad
In article <[EMAIL PROTECTED]>,
 "Erik Johnson" <[EMAIL PROTECTED]> wrote:

> Barring anyone else disagreeing with classifying it as a bug, I would
> suggest reporting it. Proper procedure for reporting a bug appears to be
> covered in section B of the Python Library Reference:
> http://docs.python.org/lib/reporting-bugs.html

Thanks for that link. I searched for an existing bug covering this case 
and found 1229380, which specifically lists the case I raised. The bug 
appears to have been closed last June, which confuses me since the bad 
behavior remains in 2.5.

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


Re: ActivePython 2.5.0.0 is now available

2007-03-13 Thread Bror Johansson

"Trent Mick" <[EMAIL PROTECTED]> skrev i meddelandet 
news:[EMAIL PROTECTED]
> I'm happy to announce that ActivePython 2.5.0.0 is now available for 
> download
> from:
> http://www.activestate.com/products/activepython/
>
> This is the first release of ActivePython for Python version 2.5. 
> Apologies
> for the long delay between core Python 2.5 and this release. The good news 
> is
> that part of the reason for this delay was to finally get approval to 
> include
> crypto in ActivePython, hence:

I did notice the download earlier today and I have installed it on five 
Windows-machines (two WinXPPro and three Win2K) and have found one 
consistent error.

Whenever I try Help->Python Manuals from PythonWin I get this errormessage:

"Internal error in help file processing :(2, 
'ShellExecute', 'Det går inte att hitta filen.')

The last few words are swedish (the machine I'm using right here is arunning 
a swedish WinXP) and has this meaning: "It's not possible to find the file".

Is there a remedy for this problem?

Bror J. 


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

Re: Need help with a string plz! (newbie)

2007-03-13 Thread Bruno Desthuilliers
Grant Edwards a écrit :
(snip)
> I don't know if emacs still includes Zippy quotes
> (of if they've been updated), but you used to be able to do
> "esc-X yow" and emacs would show you a random Zippy quote.
> 
It's still there.
-- 
http://mail.python.org/mailman/listinfo/python-list


Calling cpp from python/SWIG

2007-03-13 Thread Frank
Hi,

I have the following problem:

I want to parse an array M1 from python to a cpp function fct which
returns an array M2.

How can I do this best? Is SWIG appropriate or is there something
else?

If someone could give some code example or a link to a page with
examples, that would be great!

Thanks to all!

Frank

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


Re: Iterating across a filtered list

2007-03-13 Thread Paul Rubin
Bruno Desthuilliers <[EMAIL PROTECTED]> writes:
> I don't know if I qualify as a Python traditionalist, but I'm using
> Python since the 1.5.2 days, and I usually favor list comps or
> generator expressions over old-style loops when it comes to this kind
> of operations.

I like genexps when they're nested inside other expressions so they're
consumed as part of the evaluation of the outer expression.  They're a
bit scary when the genexp-created iterator is saved in a variable.

Listcomps are different, they allocate storage for the entire list, so
they're just syntax sugar for a loop.  They have an annoying
misfeature of their

> Python has had functions as first class objects and
> (quite-limited-but) anonymous functions, map(), filter() and reduce()
> as builtin funcs at least since 1.5.2 (quite some years ago).

True, though no iterators so you couldn't easily use those functions
on lazily-evaluated streams like you can now.

> >  Iterators like that are a new Python feature
> List comps are not that new (2.0 or 2.1 ?):
> print "\n".join([contact for name, contact in contacts.items() \
>   if search.match(name)])

Well you could do it that way but it allocates the entire filtered
list in memory.  In this example "\n".join() also builds up a string
in memory, but you could do something different, like run the sequence
through another filter or print out one element at a time, in which
case lazy evaluation can be important (imagine that contacts.iteritems
chugs through a billion row table in an SQL database).

> > It's usually safest to create and consume them in the same
> > place, e.g. creating some sequence and passing it through map, filter, etc.
> Safest ? Why so ?

Just that things can get confusing if you're consuming the iterator in
more than one place.  It can get to be like those old languages where
you had to do your own storage management ;-).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Iterating across a filtered list

2007-03-13 Thread Arnaud Delobelle
On Mar 13, 8:53 pm, Bruno Desthuilliers
<[EMAIL PROTECTED]> wrote:
> Paul Rubin a écrit :

[snip]

> >  Iterators like that are a new Python feature
>
> List comps are not that new (2.0 or 2.1 ?):
> print "\n".join([contact for name, contact in contacts.items() \
>   if search.match(name)])

You can write this, but:
   * it is difficult to argue that it is more readable than Paul's (or
my)  'imperative' version;
   * it has no obvious performance benefit, in fact it creates a list
unnecessarily (I know you could use a generator with recent python).

> > and they have
> > some annoying characteristics, like the way they mutate when you touch
> > them.
>
> While sequences are iterables, all iterables are not sequences. Know
> what you use, and you'll be fine.

...And know when to use for statements :)

--
Arnaud

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


Re: ActivePython 2.5.0.0 is now available

2007-03-13 Thread Trent Mick
Bror Johansson wrote:
> I did notice the download earlier today and I have installed it on five 
> Windows-machines (two WinXPPro and three Win2K) and have found one 
> consistent error.
> 
> Whenever I try Help->Python Manuals from PythonWin I get this errormessage:
> 
> "Internal error in help file processing :(2, 
> 'ShellExecute', 'Det går inte att hitta filen.')
> 
> The last few words are swedish (the machine I'm using right here is arunning 
> a swedish WinXP) and has this meaning: "It's not possible to find the file".
> 
> Is there a remedy for this problem?

http://bugs.activestate.com/show_bug.cgi?id=68029

I don't currently have a work around for it. I should be able to fix this for 
the next release (but don't have a date for that yet). You could CC yourself 
to that bug report to get a notification for when it is fixed, if you like.

Thanks,
Trent

-- 
Trent Mick
trentm at activestate.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Starting Python... some questions

2007-03-13 Thread jezzzz .
All,

thank you for your responses. I learned much and made some modifications in my 
small program. Currently I am attempting to put together a packet that contains 
a Python message (created using struct.pack) and a Scapy message (Ether()). 
Having a packet with combined payload from Python and Scapy doesn't seem to 
work the way I do it: 
ether = scapy.Ether(dst="01:02:03:04:05:06")
payload = ether + payload (where payload is the chassis_id)

I get as error:
  File "lldp.py", line 23, in main
fullpayload = ether + payload
TypeError: unsupported operand type(s) for +: 'Ether' and 'str'

I'm thinking instead to just use Python to create the Ethernet Frame as well 
and then send the packet off. How difficult is this? I could only find 
references online on how to send TCP/UDP packets but no information on how to 
send a packet with a Layer1 and Layer2 only. The ethernet frame should only 
contain a destination MAC, a source MAC and a type (88cc). Any advice on how to 
create such a packet and send it? (if anyone knows of an easy way to use a 
hybrid of Python and Scapy, that's fine by me as well).

Thanks!


class lldp_class:
def __init__(self):
self.chassis_id_tlv = None

def chassis_id(self, subtype, chassis_info):
if subtype == 4:
chassis_data_int = [int(x,16) for x in chassis_info.split(":")] 
   
chassis_data = struct.pack("6B", *chassis_data_int)
subtype_data = struct.pack("!B",subtype)
self.chassis_id_tlv = subtype_data + chassis_data

def main():
p = lldp_class()
p.chassis_id(4, "01:80:C2:00:00:0E")
payload = p.chassis_id_tlv
ether = scapy.Ether(dst="01:02:03:04:05:06")
fullpayload = ether + payload
sendp(fullpayload)

main()






 

Never miss an email again!
Yahoo! Toolbar alerts you the instant new Mail arrives.
http://tools.search.yahoo.com/toolbar/features/mail/
-- 
http://mail.python.org/mailman/listinfo/python-list


help!! *extra* tricky web page to extract data from...

2007-03-13 Thread [EMAIL PROTECTED]
How extract the visible numerical data from this Microsoft financial
web site?

http://tinyurl.com/yw2w4h

If you simply download the HTML file you'll see the data is *not*
embedded in it but loaded from some other file.

Surely if I can see the data in my browser I can grab it somehow right
in a Python script?

Any help greatly appreciated.

Sincerely,

Chris

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


Re: Iterating across a filtered list

2007-03-13 Thread Gabriel Genellina
En Tue, 13 Mar 2007 15:04:50 -0300, Drew <[EMAIL PROTECTED]> escribió:

> I'm currently writing a toy program as I learn python that acts as a
> simple address book. I've run across a situation in my search function
> where I want to iterate across a filtered list. My code is working
> just fine, but I'm wondering if this is the most "elegant" way to do
> this. Essentially, I'm searching the dict self.contacts for a key that
> matches the pattern entered by the user. If so, I print the value
> associated with that key. A pastie to the method is below, any help/
> advice is appreciated:
>
> http://pastie.caboo.se/46647
>
> Side note: I'm learning python after ruby experience. In ruby I would
> do something like:
>
> contacts.find_all{|name,contact| name =~ /search/}.each{|name,contact|
> puts contact}
>

Just a few changes:

def find(self, search):
 search_re = re.compile(search, re.IGNORECASE)
 for result in [self.contacts[name] for name in self.contacts if  
search_re.match(name)]:
 print result

- you can iterate directly over a dictionary keys using: for key in dict
- you can compile a regexp to re-use it in all loops; using re.IGNORECASE,  
you don't need to explicitely convert all to lowercase before comparing
- if all you want to do is to print the results, you can even avoid the  
for loop:

 print '\n'.join('%s' % self.contacts[name] for name in self.contacts  
if search_re.match(name))

-- 
Gabriel Genellina

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


Re: ANN: ActivePython 2.5.0.0 is now available

2007-03-13 Thread Wensui Liu
Is it free of charge?

On 3/13/07, Trent Mick <[EMAIL PROTECTED]> wrote:
> I'm happy to announce that ActivePython 2.5.0.0 is now available for download
> from:
>  http://www.activestate.com/products/activepython/
>
> This is the first release of ActivePython for Python version 2.5. Apologies
> for the long delay between core Python 2.5 and this release. The good news is
> that part of the reason for this delay was to finally get approval to include
> crypto in ActivePython, hence:
>
> Changes in this release include:
> - Full OpenSSL support (finally!)
> - Update to Python 2.5 (duh)
> - [Mac OS X] Universal build (finally!)
> - [Windows] Update to PyWin32 build 210
> - All the new standard extensions: SQLite, ctypes, ElementTree
> - [Linux] Rationalized the build names.
> - [Mac OS X] A sane uninstall script
>
> See the release notes for full details:
> http://aspn.activestate.com/ASPN/docs/ActivePython/2.5/relnotes.html
>
>
> What is ActivePython?
> -
>
> ActivePython is ActiveState's binary distribution of Python. Builds for
> Windows, Mac OS X, Linux, HP-UX and AIX are made freely available.
>
> ActivePython includes the Python core and the many core extensions: zlib and
> bzip2 for data compression, the Berkeley DB (bsddb) and SQLite (sqlite3)
> database libraries, the Tix GUI widgets for Tkinter, ElementTree for XML
> processing, ctypes (on supported platforms) for low-level library access, and
> others. The Windows distribution ships with PyWin32 -- a suite of Windows
> tools developed by Mark Hammond, including bindings to the Win32 API and
> Windows COM. See this page for full details:
> http://aspn.activestate.com/ASPN/docs/ActivePython/2.5/whatsincluded.html
>
> As well, ActivePython ships with a wealth of documentation for both new and
> experienced Python programmers. In addition to the core Python docs,
> ActivePython includes the "What's New in Python" series, "Dive into Python",
> the Python FAQs & HOWTOs, and the Python Enhancement Proposals (PEPs).
>
> An online version of the docs can be found here:
>  http://aspn.activestate.com/ASPN/docs/ActivePython/2.5/welcome.html
>
> We would welcome any and all feedback to:
>  [EMAIL PROTECTED]
>
> Please file bugs against ActivePython at:
>  http://bugs.activestate.com/query.cgi?set_product=ActivePython
>
>
> On what platforms does ActivePython run?
> 
>
> ActivePython includes installers for the following platforms:
>
> - AIX/PowerPC
> - HP-UX/PA-RISC
> - Linux/x86
> - Linux/x86_64: "x86_64" is also known as "AMD64"
> - Solaris/SPARC
> - Solaris/x86
> - Mac OS X
> - Windows/x64: "x64" is also known as "AMD64"
> - Windows/x86
>
>
> Extra Bits
> --
>
> ActivePython releases also include the following:
>
> - ActivePython25.chm: An MS compiled help collection of the full
>ActivePython documentation set. Linux users of applications such as
>xCHM might find this useful. This package is installed by default on
>Windows.
>
> Extra bits are available from:
>  http://downloads.activestate.com/ActivePython/etc/
>
>
> Thanks, and enjoy!
>
> Trent, Python Tech Lead
>
> --
> Trent Mick
> trentm at activestate.com
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>


-- 
WenSui Liu
A lousy statistician who happens to know a little programming
(http://spaces.msn.com/statcompute/blog)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Iterating across a filtered list

2007-03-13 Thread Arnaud Delobelle
On Mar 13, 8:59 pm, "Gabriel Genellina" <[EMAIL PROTECTED]>
wrote:
[snip]
> def find(self, search):
>  search_re = re.compile(search, re.IGNORECASE)
>  for result in [self.contacts[name] for name in self.contacts if  
> search_re.match(name)]:
>  print result

I do not see how

for y in [f(x) for x in L if g(x)]:
do stuff with y

can be preferable to

for x in L:
if g(x):
do stuff with f(x)

What can be the benefit of creating a list by comprehension for the
sole purpose of iterating over it?

--
Arnaud

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


Re: Iterating across a filtered list

2007-03-13 Thread Gabriel Genellina
En Tue, 13 Mar 2007 17:19:53 -0300, Arnaud Delobelle  
<[EMAIL PROTECTED]> escribió:

> On Mar 13, 7:36 pm, Paul Rubin  wrote:
>>
>> The re library caches the compiled regexp, I think.
>
> That would surprise me.
> How can re.search know that string.lower(search) is the same each
> time?  Or else there is something that I misunderstand.

It does.

py> import re
py> x = re.compile("ijk")
py> y = re.compile("ijk")
py> x is y
True

Both, separate calls, returned identical results. You can show the cache:

py> re._cache
{(, '%(?:\\((?P.*?)\\))?(?P[-#0-9  
+*.hlL]*?)[eEfFgGd
iouxXcrs%]', 0): <_sre.SRE_Pattern object at 0x00A786A0>,
  (, 'ijk', 0): <_sre.SRE_Pattern object at 0x00ABB338>}

-- 
Gabriel Genellina

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


Re: ANN: ActivePython 2.5.0.0 is now available

2007-03-13 Thread Trent Mick
Yes.

Wensui Liu wrote:
> Is it free of charge?
> 
> On 3/13/07, Trent Mick <[EMAIL PROTECTED]> wrote:
>>...
>> ActivePython is ActiveState's binary distribution of Python. Builds for
>> Windows, Mac OS X, Linux, HP-UX and AIX are made freely available.
>>...

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


Re: help!! *extra* tricky web page to extract data from...

2007-03-13 Thread Diez B. Roggisch
[EMAIL PROTECTED] schrieb:
> How extract the visible numerical data from this Microsoft financial
> web site?
> 
> http://tinyurl.com/yw2w4h
> 
> If you simply download the HTML file you'll see the data is *not*
> embedded in it but loaded from some other file.
> 
> Surely if I can see the data in my browser I can grab it somehow right
> in a Python script?
> 
> Any help greatly appreciated.

It's an AJAX-site. You have to carefully analyze it and see what 
actually happens in the javascript, then use that. Maybe something like 
the http header plugin for firefox helps you there.

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


Re: help!! *extra* tricky web page to extract data from...

2007-03-13 Thread Max Erickson
"[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote:

> How extract the visible numerical data from this Microsoft
> financial web site?
> 
> http://tinyurl.com/yw2w4h
> 
> If you simply download the HTML file you'll see the data is *not*
> embedded in it but loaded from some other file.
> 
> Surely if I can see the data in my browser I can grab it somehow
> right in a Python script?
> 
> Any help greatly appreciated.
> 
> Sincerely,
> 
> Chris
> 

The url for the data is in an iframe. If you need to scrape the 
original page for some reason(instead of iframe url directly), you can 
use urlparse.urljoin to resolve the relative url.


max

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


Re: using python to visit web sites and print the web sites image to files

2007-03-13 Thread [EMAIL PROTECTED]
> The reason I want to do simulation but not just crawling is : we have
> to check many web pages' front page to see whether it conform to our
> visual standard, e.g, it should put a search box on the top part of
> the page. It's tedious for human work. So I want to 'crawl and save
> the visual presentation of the web site automatically', and check
> these image files later with human eyes.
>
> -Xiong

Hi Xiong,

I have been working on a program to do something very similar to
generate thumbnails of websites.

The code is in IronPython (which may put you off!) and would need
modified or scripted with pywinauto to deal with multiple images.

Let me know if it is of use to you and I will upload it.

Cheers,
Davy

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


Re: Iterating across a filtered list

2007-03-13 Thread Gabriel Genellina
En Tue, 13 Mar 2007 18:16:32 -0300, Arnaud Delobelle  
<[EMAIL PROTECTED]> escribió:

> On Mar 13, 8:59 pm, "Gabriel Genellina" <[EMAIL PROTECTED]>
> wrote:
> [snip]
>> def find(self, search):
>>  search_re = re.compile(search, re.IGNORECASE)
>>  for result in [self.contacts[name] for name in self.contacts if
>> search_re.match(name)]:
>>  print result
>
> I do not see how
>
> for y in [f(x) for x in L if g(x)]:
> do stuff with y
>
> can be preferable to
>
> for x in L:
> if g(x):
> do stuff with f(x)
>
> What can be the benefit of creating a list by comprehension for the
> sole purpose of iterating over it?

No benefit...

-- 
Gabriel Genellina

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


  1   2   >