Re: Python-URL! - weekly Python news and links (Nov 17)

2008-11-19 Thread Daniel Fetchinson
>> > One of the reasons I would like to formulate a good
>> > model of an object's value and type is so that I could
>> > try to offer something better.  Responses like yours
>> > are significantly demotivating.
>>
>> And yet you argue when people try to explain to you that objects don't
>> *have* values, objects *are* values. Objects have attributes, which are
>> references to other values. One of an object's attributes is its type.
> [...]
>
> Steve, since Gabriel does not want to go for the
> record in this thread :-), I posted my response as
> a reply to your most recent message in the "Official
> definition of call-by-value..." thread.
> --
> http://mail.python.org/mailman/listinfo/python-list

And this thread has a good chance of becoming the "Longest and Most
Boring Python-URL Weekly Python News and Links Thread".

Cheers,
Daniel

-- 
Psss, psss, put it down! - http://www.cafepress.com/putitdown
--
http://mail.python.org/mailman/listinfo/python-list


Re: python vs smalltalk 80

2008-11-19 Thread Erik Max Francis

Lawrence D'Oliveiro wrote:


gavino wrote:


which is nicer?


If I were to lock you and INTERCAL in a room until only one is left alive, who 
do you think would survive?


The rest of us.

--
Erik Max Francis && [EMAIL PROTECTED] && http://www.alcyone.com/max/
 San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis
  The work of many cannot be done alone.
   -- (a Bemba proverb)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Official definition of call-by-value (Re: Finding the instance reference...)

2008-11-19 Thread Antoon Pardon
On 2008-11-19, greg <[EMAIL PROTECTED]> wrote:
> Antoon Pardon wrote:
>> Call by value is officially defined in terms of assignment in
>> a context where assignments means copying and in a definition
>> of a specifix language.
>> 
>> You can't lift this part out of the definition of algol 60
>> and say it applies equally well in languages with different
>> assignment semantics.
>
> But many other language designers, of both static and
> dynamic languages, have done just that.
> I'm not saying it *has* to be interpreted that way,
> just that it *is* very often interpreted that way.
> So you can't claim that it's not common usage.

You are changing your argument. In a follow up you
made the point that call by value should be as it
was intended by the writers of the algol 60 report.

Now your falling back to how it is often interpreted.
It is very well possible that it is often interpreted
contrary to how it was intended. And since this
interpretation just as often results in misunderstandings
I don't think it is a usefull interpretation.

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


Re: Will MySQLdb, the Python shim, be supported for Python 2.6 or 3.x?

2008-11-19 Thread Tino Wildenhain

Hi,

Dennis Lee Bieber wrote:
...



I'm not any heavy user -- but if it means anything... I finally
converted my home machine from 2.4 to 2.5 only a few months ago! (My
work machine is still running 2.4).


Converted? You can install and run more then one Python version in
parallel. (Of course only one is "the default" but you can use as
many as you want explicitely)
...


smime.p7s
Description: S/MIME Cryptographic Signature
--
http://mail.python.org/mailman/listinfo/python-list


Re: regular expressions ... slow

2008-11-19 Thread Kay Schluehr
On 18 Nov., 18:47, Stefan Behnel <[EMAIL PROTECTED]> wrote:
> Kay Schluehr wrote:
> > All of this is prototyped in Python and it is still work in progress.
> > As long as development has not reached a stable state I refuse to
> > rebuild the system in an optimized C version.
>
> And rightfully so:
>
> 1) the approach is algorithmically better, so it may even beat the current
> C implementation by design.
>
> 2) switching languages before finishing and benchmarking the prototype is a
> premature optimisation. It wouldn't be the first prototype going into
> production.
>
> 3) even before considering a reimplementation, you should throw it into
> Cython to translate it into C code, and then benchmark that.
>
> Stefan

I fully agree and in fact the Trail parser generator contains a single
extension module called cyTrail which is written in Cython - it's not
just a trivial recompilation of Python in Cython but it uses all kinds
of cdefs.

There is just a difference between optimizing existing code using the
best techniques available and writing code from scratch for speed. I
consider this as a different, subsequent project ( call it cTrail )
and I want to have more fine control than being possible with Cython -
actually I do want to understand the code in a simple language as C. I
have to idea what the code does, generated by Cython. There are entire
layers that can be stripped off when not dealing with Python types and
dynamic memory allocation.

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


Re: Python bytecode STORE_NAME

2008-11-19 Thread Peter Otten
[EMAIL PROTECTED] wrote:

> As part of some research I am doing a Python Virtual Machine in Java,
> and the exact semantics of the STORE_NAME bytecode is unclear to be,
> so I was hoping somebody here could clarify it.
> The STORE_NAME bytecode is supposed to set a value for a name in the
> current scope. However, the following piece of code:
> 
> def hello(who):
> print "Hello", who
> return hello(who)
> print "Say:"
> hello("World")
> 
> Results in this bytecode for the top level:
> 1, LOAD_CONST, 1
> 4, MAKE_FUNCTION, 0
> 7, STORE_NAME, 0
> 10, LOAD_CONST, 2
> 13, PRINT_ITEM, None
> 14, PRINT_NEWLINE, None
> 15, LOAD_NAME, 0
> 18, LOAD_CONST, 3
> 21, CALL_FUNCTION, 1
> 24, POP_TOP, None
> 25, LOAD_CONST, 0
> 28, RETURN_VALUE, None
> 
> And this bytecode for the hello function:
> 1, LOAD_CONST, 1
> 4, PRINT_ITEM, None
> 5, LOAD_FAST, 0
> 8, PRINT_ITEM, None
> 9, PRINT_NEWLINE, None
> 10, LOAD_GLOBAL, 1
> 13, LOAD_FAST, 0
> 16, CALL_FUNCTION, 1
> 19, RETURN_VALUE, None
> 20, LOAD_CONST, 0
> 23, RETURN_VALUE, None
> 
> The first column are the byte numbers, and the last column contains
> the arguments to the byte codes if they take any.
> 
> The function is stored using STORE_NAME with offset 0 in the module
> scope, but it is loaded from inside the hello method using LOAD_GLOBAL
> with offset 1. My questions are: Does STORE_NAME add things to the
> global scope when used top level? And why is the offset different?

Every code object has its own co_names attribute (a tuple). The arguments
are offsets into that tuple.

Using Python 2.5 I can't reproduce your example, I get 0 offsets in both
cases. Here's a simpler one:

>>> import dis
>>> def f():
... x
... y
...
>>> def g():
... y
...
>>> dis.dis(f)
  2   0 LOAD_GLOBAL  0 (x)
  3 POP_TOP

  3   4 LOAD_GLOBAL  1 (y)
  7 POP_TOP
  8 LOAD_CONST   0 (None)
 11 RETURN_VALUE
>>> dis.dis(g)
  2   0 LOAD_GLOBAL  0 (y)
  3 POP_TOP
  4 LOAD_CONST   0 (None)
  7 RETURN_VALUE
>>> f.func_code.co_names
('x', 'y')
>>> g.func_code.co_names
('y',)

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


Re: compressed serialization module

2008-11-19 Thread Nick Craig-Wood
greg <[EMAIL PROTECTED]> wrote:
>  Nick Craig-Wood wrote:
> > (Note that basic pickle protocol is likely to be more compressible
> > than the binary version!)
> 
>  Although the binary version may be more compact to
>  start with. It would be interesting to compare the
>  two and see which one wins.

It is very data dependent of course, but in this case the binary
version wins...

However there is exactly the same amount of information in the text
pickle and the binary pickle, so in theory a perfect compressor will
compress each to exactly the same size ;-)

>>> import os
>>> import bz2
>>> import pickle
>>> L = range(100)
>>> f = bz2.BZ2File("z.dat", "wb")
>>> pickle.dump(L, f)
>>> f.close()
>>> os.path.getsize("z.dat")
1055197L
>>> f = bz2.BZ2File("z1.dat", "wb")
>>> pickle.dump(L, f, -1)
>>> f.close()
>>> os.path.getsize("z1.dat")
524741L
>>>

Practical considerations might be that bz2 is quite CPU expensive.  It
also has quite a large overhead

eg

>>> len("a".encode("bz2"))
37

So if you are compressing lots of small things, zip is a better
protocol

>>> len("a".encode("zip"))
9

It is also much faster!

-- 
Nick Craig-Wood <[EMAIL PROTECTED]> -- http://www.craig-wood.com/nick
--
http://mail.python.org/mailman/listinfo/python-list


Re: Sieve of Zakiya

2008-11-19 Thread Mark Dickinson
On Nov 19, 5:16 am, jzakiya <[EMAIL PROTECTED]> wrote:
[Lots of stuff snipped]
> My SoZ mathematical analysis shows why its algorithmically faster than
> both the SoA & SoE, to explain its demonstrated computational
> superiority. Again, hopefully professional mathematicians will become
> interested in some of the features and characteristics I've found in
> the method's elements, and do a better and more thorough analysis of
> what's going on than I'm able to do presently.

This is getting off-topic for comp.lang.python.  I suggest you
take it to sci.math.

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


Possible bug in Tkinter for Python 2.6

2008-11-19 Thread Eric Brunel

Hello all,

I'm trying out Python 2.6 and I found what might be a bug in the Tkinter  
module. How can I report it?


The possible bug is a traceback when trying to delete a menu item in a  
menu where no items have associated commands.


For example:
--
from Tkinter import *

root = Tk()

mb = Menu(root)
root.configure(menu=mb)

fm = Menu(mb)
mb.add_cascade(label='File', menu=fm)

fm.add_command(label='Open')
fm.add_command(label='Quit')

def remove_menu_item():
  fm.delete(1)

Button(root, text='Remove menu item',  
command=remove_menu_item).pack(padx=12, pady=24)


root.mainloop()
--

Clicking on the button should remove the 'Open' item in the 'File' menu,  
but ends up in a traceback:
  File "/opt/Python2.6+Tk8.5/bin/Linux/lib/python2.6/lib-tk/Tkinter.py",  
line 1410, in __call__

return self.func(*args)
  File "menu.py", line 15, in remove_menu_item
fm.delete(1)
  File "/opt/Python2.6+Tk8.5/bin/Linux/lib/python2.6/lib-tk/Tkinter.py",  
line 2670, in delete

if c in self._tclCommands:

It just seems the _tclCommands attribute on menus is initialized to None  
and never changed if none of the items actually have a command.


Thanks!
--
python -c "print ''.join([chr(154 - ord(c)) for c in  
'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])"

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


Re: Possible bug in Tkinter for Python 2.6

2008-11-19 Thread Jeremiah Dodds
On Wed, Nov 19, 2008 at 4:57 AM, Eric Brunel <[EMAIL PROTECTED]> wrote:

> Hello all,
>
> I'm trying out Python 2.6 and I found what might be a bug in the Tkinter
> module. How can I report it?
>
> The possible bug is a traceback when trying to delete a menu item in a menu
> where no items have associated commands.
>
> For example:
> --
> from Tkinter import *
>
> root = Tk()
>
> mb = Menu(root)
> root.configure(menu=mb)
>
> fm = Menu(mb)
> mb.add_cascade(label='File', menu=fm)
>
> fm.add_command(label='Open')
> fm.add_command(label='Quit')
>
> def remove_menu_item():
>  fm.delete(1)
>
> Button(root, text='Remove menu item',
> command=remove_menu_item).pack(padx=12, pady=24)
>
> root.mainloop()
> --
>
> Clicking on the button should remove the 'Open' item in the 'File' menu,
> but ends up in a traceback:
>  File "/opt/Python2.6+Tk8.5/bin/Linux/lib/python2.6/lib-tk/Tkinter.py",
> line 1410, in __call__
>return self.func(*args)
>  File "menu.py", line 15, in remove_menu_item
>fm.delete(1)
>  File "/opt/Python2.6+Tk8.5/bin/Linux/lib/python2.6/lib-tk/Tkinter.py",
> line 2670, in delete
>if c in self._tclCommands:
>
> It just seems the _tclCommands attribute on menus is initialized to None
> and never changed if none of the items actually have a command.
>
> Thanks!
> --
> python -c "print ''.join([chr(154 - ord(c)) for c in
> 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])"
> --
> http://mail.python.org/mailman/listinfo/python-list
>


I can confirm this behavior in 2.6: Full traceback (as Eric's is missing the
last line)

Exception in Tkinter callback
Traceback (most recent call last):
  File "/usr/local/lib/python2.6/lib-tk/Tkinter.py", line 1410, in __call__
return self.func(*args)
  File "", line 2, in remove_menu_item
  File "/usr/local/lib/python2.6/lib-tk/Tkinter.py", line 2670, in delete
if c in self._tclCommands:
TypeError: argument of type 'NoneType' is not iterable


The example code works "as expected" under 2.5.

I don't know enough about Tkinter to know whether or not this is actually a
bug, or intended behavior, but it certainly strikes me as being a bug.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Non blocking socket server and storage engine

2008-11-19 Thread Lawrence D'Oliveiro
kdeveloper wrote:

> The server needs to run at least three threads:

Get it working without threading first.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Non blocking socket server and storage engine

2008-11-19 Thread kdeveloper
On Nov 19, 10:51 am, Lawrence D'Oliveiro <[EMAIL PROTECTED]
central.gen.new_zealand> wrote:
> kdeveloper wrote:
> > The server needs to run at least three threads:
>
> Get it working without threading first.

Lawrence, I was following article [1] when building my code.
So I guess it should be ok. At the moment
I have only two threads running:
a. receiving packages and storing to queue,
b. getting packet from the queue and storing in DB.

Regards,
Krzysztof


[1] http://www.ibm.com/developerworks/aix/library/au-threadingpython/index.html
--
http://mail.python.org/mailman/listinfo/python-list


Re: sorting list of complex numbers

2008-11-19 Thread Hrvoje Niksic
Terry Reedy <[EMAIL PROTECTED]> writes:

> Do your tuple destructuring in the first statement in your body and
> nothing will break.

Unless you were using a lambda, which is quite useful as argument to
"sort".
--
http://mail.python.org/mailman/listinfo/python-list


Re: Non blocking socket server and storage engine

2008-11-19 Thread kdeveloper
On Nov 19, 10:57 am, "Chris Rebert" <[EMAIL PROTECTED]> wrote:

> Quoting from Wikipedia (http://en.wikipedia.org/wiki/User_Datagram_Protocol):
> "UDP does not guarantee reliability or ordering in the way that TCP
> does. Datagrams may arrive out of order, ***appear duplicated***, or
> go missing without notice."

I agree with that. But the amount of possible duplcates shouldn't be
so huge.

What about using different storing engine? Any suggestions?

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


Re: Problem with sqlite3 cursor and imbricated for loop

2008-11-19 Thread jhermann
c.execute("select * from stocks")
for s in list(c):
   print s[0]
   c.execute("select * from stocks where price<20")
   for sp in c:
  print '  '+sp[0]
c.close()

The simple addition of list() should do away with the dependency on
mysql's implementation, since it forces the instant fetch of all data.
Whether that is better than to use a 2nd cursor is probably a matter
of taste.

Using "*" in selects is always bad, though. ;)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python 3.0 - is this true?

2008-11-19 Thread Duncan Grisby
In article <[EMAIL PROTECTED]>,
Martin v. Löwis <[EMAIL PROTECTED]> wrote:

>> The sorting is in a performance-critical part of the system, so the
>> overhead of evaluating a key function is not insignificant.
>
>Can you easily produce an example? It doesn't have to be real data,
>but should have the structure (typewise) of the real data. I would
>like to perform some measurements. For example, I could imagine that
>
>l = []
>for i in range(1000):
>  x = random.randint(0,100)
>  if x < 4: l.append(None)
>  else: l.append(x)
>
>might adequately model your problem.

Sorry for the delay in replying. Yes, that's not far off. Most of the
time the lists contain strings, though. A better approximation might
be to read lines from a file and randomly replace them with Nones:

l = []
for line in open("bigfile.txt"):
x = random.randint(0,100)
if x < 4: l.append(None)
else: l.append(line)

And maybe once in a while you end up with something not dissimilar to:

l = []
for line in open("bigfile.txt"):
x = random.randint(0,100)
if x < 4: l.append(None)
elif x < 5: l.append([line,line])
else: l.append(line)

In that kind of case it doesn't really matter what happens to list
items in the sort order, but it's important it doesn't fail to sort
the ones that are strings.

Cheers,

Duncan.

-- 
 -- Duncan Grisby --
  -- [EMAIL PROTECTED] --
   -- http://www.grisby.org --
--
http://mail.python.org/mailman/listinfo/python-list


Re: Identifying unicode punctuation characters with Python regex

2008-11-19 Thread jhermann
> >>> P=P.replace('\\','').replace(']','\\]')   # escape both of them.

re.escape() does this w/o any assumptions by your code about the regex
implementation.
--
http://mail.python.org/mailman/listinfo/python-list


Re: unittest exits

2008-11-19 Thread jhermann
On 13 Nov., 20:20, "Chris Rebert" <[EMAIL PROTECTED]> wrote:
> try:
>     unittest.main()
> except SystemExit:
>     pass

You most probably want this instead:

try:
unittest.main()
except SystemExit, exc:
# only exit if tests failed
if exc.code:
raise
--
http://mail.python.org/mailman/listinfo/python-list


Re: Non blocking socket server and storage engine

2008-11-19 Thread Chris Rebert
On Wed, Nov 19, 2008 at 2:36 AM, kdeveloper
<[EMAIL PROTECTED]> wrote:
> Hello Pythonists,
>
> I am building a non blocking socket server for incomming UDP packets.
> The server needs to run at least three threads:
> 1. getting data and pushing to "some" storage (at the moment I use
> queue),
> 2. acknowledge the package received
> 3. retrieve the information from the storage and insert it in DB.
>
> The problem I have is that when I use queue it stores more packets in
> the queue than it actually receives. An example: sent 99 UDP packets
> and queue stored 600-750 entries (?) Why? I have no idea. I have
> impression that I still do not understand completely how does the
> queue work in python.

No, I believe rather you don't completely understand UDP.

Quoting from Wikipedia (http://en.wikipedia.org/wiki/User_Datagram_Protocol):
"UDP does not guarantee reliability or ordering in the way that TCP
does. Datagrams may arrive out of order, ***appear duplicated***, or
go missing without notice."

I think that might at least partially account for your duplicate entries.

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com

>
> Another issue is that I want the server to run very rupidly. The
> server needs to get at least 100 packets per second, and the same
> amount of acknowledges has to be sent back.
>
> The questions are:
> 1. What is the best storage engine for Python and multithreading
> server?
> 2. Can I use queue for such problem?
> 3. How does actually queue work in Python? (I know how it should work
> generally, but somehow it doesn't work as I expect)
>
> Any hints & helps? Would be very grateful
>
> Cheers
> K
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: Programming exercises/challenges

2008-11-19 Thread Jeremiah Dodds
On Wed, Nov 19, 2008 at 7:12 AM, Mr. SpOOn <[EMAIL PROTECTED]> wrote:

> On Wed, Nov 19, 2008 at 2:39 AM, Mensanator <[EMAIL PROTECTED]> wrote:
>
>  What
> requisites should have the host to run python code?
>
> Thanks and sorry for the meddling.
> --
> http://mail.python.org/mailman/listinfo/python-list
>

If the host is linux-based (possibly if not, I don't have much experience
otherwise, so I can't say), and allows ssh access, you should be able to
write and run python code for a web service or site. How difficult it will
be to do, and what you need to do to make your app publicly accessible, will
depend on the hosts TOS. It's definitely accomplishable with the vast
majority of hosts.

Personally, I prefer a host that gives me root on a box (or virtual
machine). I've had a great time with slicehost (http://slicehost.com).
However, going this route means that you'll have to learn quite a bit on the
sys-admin side. Slicehost has great articles written on various things, and
there's plenty of resources on the web (and in man pages) about what you
need to do to configure and secure a webserver, but it's still a lot of
learning. It is, however, stuff that you'll probably want to get familiar
with eventually anyhow, if you're writing web-facing python (or any other
language!).

There are a few hosts that specialize in, or explicitly offer python
hosting, http://wiki.python.org/moin/PythonHosting has an overview of them.
--
http://mail.python.org/mailman/listinfo/python-list


Inheriting frozenset gives bug if i overwrite __repr__ method

2008-11-19 Thread srinivasan srinivas
Hi,
I am getting an error while executing the following snippet. If i comment out 
method __repr__ , it works fine.

class fs(frozenset):
    def __new__(cls, *data):
    data = sorted(data)
    self = frozenset.__new__(cls, data)
    self.__data = data
    return self

    def __repr__(self):
    return "%s(%r)" % (self.__class__.__name__, self.__data)

a1 = fs(1,2,3)
a2 = fs(3,4,5)
print a1.difference(a2)

Error:
    return "%s(%r)" % (self.__class__.__name__, self.__data)
AttributeError: 'fs' object has no attribute '_fs__data'

Please help me in fixing this.

Thanks,
Srini



  Add more friends to your messenger and enjoy! Go to 
http://messenger.yahoo.com/invite/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Programming exercises/challenges

2008-11-19 Thread greg
On Nov 18, 6:39 pm, [EMAIL PROTECTED] wrote:
> Hi guys,
>
> I'm learning Python by teaching myself, and after going through several
> tutorials I feel like I've learned the basics. Since I'm not taking a
> class or anything, I've been doing challenges/programs to reinforce the
> material and improve my skills. I started out with stuff like "Guess my
> number" games, hangman, etc. and moved on to making poker and card
> games to work with classes. For GUIs I created games like minesweeper,
> and a GUI stock portfolio tracker. I am out of ideas and am looking for
> programming projects, challenges, or programs that have helped you'll
> learn. I'm working on the project Euler problems, but I find that they
> don't really help my programming skills; they are more math focused.
> Suggestions? What has been useful or interesting to you? I'd also
> welcome sources of textbook type problems, because the ones provided in
> tutorials tend to be repetitive.
>
> Thanks,
> Ben

You night look at "Useless Python" (you'll have to Google for the
site).  It has tons of problems from trivial to complex.
--greg
--
http://mail.python.org/mailman/listinfo/python-list


Re: Programming exercises/challenges

2008-11-19 Thread Jeremiah Dodds
On Wed, Nov 19, 2008 at 7:44 AM, Mr. SpOOn <[EMAIL PROTECTED]> wrote:

> On Wed, Nov 19, 2008 at 1:35 PM, Jeremiah Dodds
> <[EMAIL PROTECTED]> wrote:
> >
> > Personally, I prefer a host that gives me root on a box (or virtual
> > machine). I've had a great time with slicehost (http://slicehost.com).
>
> Yes, I knew about slicehost, but it is expensive for what I need to
> do, that is just experimentin a bit.
>
> > There are a few hosts that specialize in, or explicitly offer python
> > hosting, http://wiki.python.org/moin/PythonHosting has an overview of
> them.
>
> Thanks for the link, seems useful.
>

If you need to do it on the extremely cheap, you can host on your own
machine on a port other than 80, make sure your router / firewall is
forwarding the port to your machine, and use dyndns (http://dyndns.com) to
give yourself a domain name. CherryPy (http://cherrypy.org) makes the python
side of hosting a simple service or app quite painless. I use this method to
host a little app for downloading Ubuntu packages and their dependencies as
a tarfile on my personal machine.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Programming exercises/challenges

2008-11-19 Thread Mr . SpOOn
On Wed, Nov 19, 2008 at 1:50 PM, Jeremiah Dodds
<[EMAIL PROTECTED]> wrote:
> If you need to do it on the extremely cheap, you can host on your own
> machine on a port other than 80, make sure your router / firewall is
> forwarding the port to your machine, and use dyndns (http://dyndns.com) to
> give yourself a domain name. CherryPy (http://cherrypy.org) makes the python
> side of hosting a simple service or app quite painless. I use this method to
> host a little app for downloading Ubuntu packages and their dependencies as
> a tarfile on my personal machine.

Thanks, I'll try.

To turn back in topic, there is the python challenge:
http://www.pythonchallenge.com/
I started it when I was learning Python, but since the beginning it is
not as simple as they say on the site. It maybe stimulating.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Possible bug in Tkinter for Python 2.6

2008-11-19 Thread Anton Vredegoor
On Wed, 19 Nov 2008 10:57:53 +0100
"Eric Brunel" <[EMAIL PROTECTED]> wrote:

> I'm trying out Python 2.6 and I found what might be a bug in the
> Tkinter module. How can I report it?

maybe here:
http://bugs.python.org/issue3774
 
> The possible bug is a traceback when trying to delete a menu item in
> a menu where no items have associated commands.

[...]

> It just seems the _tclCommands attribute on menus is initialized to
> None and never changed if none of the items actually have a command

I ran into the same issue after I downloaded PysolFC-1.1 . I actually
uploaded a patch for PysolFC for it for Python26 on Ubuntu and forgot
all about it, thinking it could be some API change. Thanks for nailing
down the problem a bit more and asking the questions here. It helped me
to discover the bug reporting facility. According to the link above
this bug is already reported and fixed, but it's nice to know anyway.

Now for some really strange bug that still breaks PysolFC-1.1 on windows
for me with Python26 ... (Python25 not affected):



  File "c:\python26\lib\lib-tk\Tkinter.py", line 1202, in configure
return self._configure('configure', cnf, kw)
  File "c:\python26\lib\lib-tk\Tkinter.py", line 1193, in _configure
self.tk.call(_flatten((self._w, cmd)) + self._options(cnf))
_tkinter.TclError: image "pyimage237" doesn't exist

I suspect there has been some upgrade or new compilation of tcl
that causes this behavior.

A.


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


Re: Programming exercises/challenges

2008-11-19 Thread Mr . SpOOn
On Wed, Nov 19, 2008 at 1:35 PM, Jeremiah Dodds
<[EMAIL PROTECTED]> wrote:
>
> Personally, I prefer a host that gives me root on a box (or virtual
> machine). I've had a great time with slicehost (http://slicehost.com).

Yes, I knew about slicehost, but it is expensive for what I need to
do, that is just experimentin a bit.

> There are a few hosts that specialize in, or explicitly offer python
> hosting, http://wiki.python.org/moin/PythonHosting has an overview of them.

Thanks for the link, seems useful.
--
http://mail.python.org/mailman/listinfo/python-list


Re: compressed serialization module

2008-11-19 Thread Tino Wildenhain

Hi,

greg wrote:

Mark wrote:

Thanks guys.  This is for serializing to disk.  I was hoping to not
have to use too many intermediate steps


You should be able to use a gzip.GzipFile
or bz2.BZ2File and pickle straight into it.



also:

import codecs

out=codecs.open("picklefile.bz2",mode="wb",encoding="bz2")

pickle.dump(obj,out,pickle.pickle.HIGHEST_PROTOCOL)
out.close()

should work (and has far less code :-)

Regards
Tino


smime.p7s
Description: S/MIME Cryptographic Signature
--
http://mail.python.org/mailman/listinfo/python-list


Re: regular expressions ... slow

2008-11-19 Thread Lawrence D'Oliveiro
Uwe Schmitt wrote:

> Are there any plans  to speed up Pythons regular expression module ?
> Or
> is the example in this artricle too far from reality ???


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


Getting fractional part from a float without using string operations

2008-11-19 Thread srinivasan srinivas
Thanks,
Srini


  Add more friends to your messenger and enjoy! Go to 
http://messenger.yahoo.com/invite/
--
http://mail.python.org/mailman/listinfo/python-list


Non blocking socket server and storage engine

2008-11-19 Thread kdeveloper
Hello Pythonists,

I am building a non blocking socket server for incomming UDP packets.
The server needs to run at least three threads:
1. getting data and pushing to "some" storage (at the moment I use
queue),
2. acknowledge the package received
3. retrieve the information from the storage and insert it in DB.

The problem I have is that when I use queue it stores more packets in
the queue than it actually receives. An example: sent 99 UDP packets
and queue stored 600-750 entries (?) Why? I have no idea. I have
impression that I still do not understand completely how does the
queue work in python.

Another issue is that I want the server to run very rupidly. The
server needs to get at least 100 packets per second, and the same
amount of acknowledges has to be sent back.

The questions are:
1. What is the best storage engine for Python and multithreading
server?
2. Can I use queue for such problem?
3. How does actually queue work in Python? (I know how it should work
generally, but somehow it doesn't work as I expect)

Any hints & helps? Would be very grateful

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


Re: Getting fractional part from a float without using string operations

2008-11-19 Thread Jeremiah Dodds
On Wed, Nov 19, 2008 at 8:35 AM, srinivasan srinivas <
[EMAIL PROTECTED]> wrote:

> Thanks,
> Srini
>
>
>  Add more friends to your messenger and enjoy! Go to
> http://messenger.yahoo.com/invite/
> --
> http://mail.python.org/mailman/listinfo/python-list
>

x = 2.99340584
y = abs(int(x) - x)
y
0.99340584

Is that what you wanted?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Optional parameter object re-used when instantiating multiple objects

2008-11-19 Thread Rick Giuly
Thanks to all for your replies

All things considered, I vote for evaluating the arguments at runtime
(each time the function is called). Good reasons for this have already
been mentioned so I won't repeat them. A programming language is a
user interface of sorts. (Pretty much all languages are logical so
"correctness" is not what I'm meaning to discuss - I'm thinking about
usability.) Python provides, for the most part, an *excellent* user
interface to the programmer. Why not make it even "better" by
evaluating the arguments each time the function is called? It will be
harder to change the language 10 years from now, so why not change it
now?

(By "better" I mean that over many years of time programmers will be
more productive because the language will be learned a bit faster with
a fewer surprises - and still retain its power.)

-Rick

On Nov 16, 10:28 pm, "Chris Rebert" <[EMAIL PROTECTED]> wrote:
> For the Nth time this year that this has come up, I'll point out yet
> again that this issue has already been discussed to death before:
>
> [Python-ideas] proto-PEP: Fixing Non-constant Default 
> Argumentshttp://mail.python.org/pipermail/python-ideas/2007-January/000121.html
>
> [Python-3000] pre-PEP: Default Argument 
> Expressionshttp://mail.python.org/pipermail/python-3000/2007-February/005704.html
>
> Result: Evaluating the arguments at runtime rather than
> definition-time was deemed too magical; the backward compatibility
> issues make changes unlikely; it's hard to find an acceptable syntax.
>
> But hey, if some people want to have another go at it, best of luck.
>
> Cheers,
> Chris
> --
> Follow the path of the Iguana...http://rebertia.com
>
> On Sun, Nov 16, 2008 at 8:11 PM, alex23 <[EMAIL PROTECTED]> wrote:
> > On Nov 17, 12:27 pm, Steve Holden <[EMAIL PROTECTED]> wrote:
> >> If multiple statements are needed to perform the
> >> argument initialization, how would you then propose the problem should
> >> be solved?
>
> > Why, with another function of course!
>
> > def f(x, y=`f_arg_computation(x)`): ...
>
> > Or my personal favourite:
>
> > def f(x, **`f_arg_computation(x)`): ...
>
> > Seriously, though, I agree with Steve; the function body -is- the
> > place for computation to occur.
> > --
> >http://mail.python.org/mailman/listinfo/python-list

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


Re: Getting fractional part from a float without using string operations

2008-11-19 Thread John Machin
On Nov 20, 12:35 am, srinivasan srinivas <[EMAIL PROTECTED]>
wrote:


| >>> import math
| >>> num = 123.4567
| >>> math.modf(num)
| (0.456699789, 123.0)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Avoiding local variable declarations?

2008-11-19 Thread Mark Wooding
greg <[EMAIL PROTECTED]> wrote:

> I've only ever seen "identity element" in English mathematics.
> "Neutral element" sounds like something my car's gearbox
> might have...

I've encountered both.  I think `neutral element' is more common when
dealing with the possibility that it might not be unique (in the way
that identity elements are in groups, rings and fields), but that might
just be my misconception.

-- [mdw]
--
http://mail.python.org/mailman/listinfo/python-list


Re: Getting fractional part from a float without using string operations

2008-11-19 Thread srinivasan srinivas
Yes. But it didn't give only the expected decimals.
For ex:
>>> a = 1.23
>>> abs(int(a) -a)
0.22998

I would like to get the result '0.23' only.

Thanks,
Srini





From: Jeremiah Dodds <[EMAIL PROTECTED]>
To: python-list@python.org
Sent: Wednesday, 19 November, 2008 7:14:17 PM
Subject: Re: Getting fractional part from a float without using string 
operations




On Wed, Nov 19, 2008 at 8:35 AM, srinivasan srinivas <[EMAIL PROTECTED]> wrote:

Thanks,
Srini


     Add more friends to your messenger and enjoy! Go to 
http://messenger.yahoo.com/invite/
--
http://mail.python.org/mailman/listinfo/python-list

x = 2.99340584
y = abs(int(x) - x)
y
0.99340584

Is that what you wanted?



  Get perfect Email ID for your Resume. Grab now 
http://in.promos.yahoo.com/address--
http://mail.python.org/mailman/listinfo/python-list


Re: file tell in a for-loop

2008-11-19 Thread Tim Chase

Magdoll wrote:

I was trying to map various locations in a file to a dictionary. At
first I read through the file using a for-loop, but tell() gave back
weird results, so I switched to while, then it worked.

The for-loop version was something like:
d = {}
for line in f:
 if line.startswith('>'): d[line] = f.tell()

And the while version was:
d = {}
while 1:
line = f.readline()
if len(line) == 0: break
if line.startswith('>'): d[line] = f.tell()


In the for-loop version, f.tell() would sometimes return the same
result multiple times consecutively, even though the for-loop
apparently progressed the file descriptor. I don't have a clue why
this happened, but I switched to while loop and then it worked.

Does anyone have any ideas as to why this is so?


I suspect that at least the iterator version uses internal 
buffering, so the tell() call returns the current buffer 
read-location, not the current read location.  I've also had 
problems with tell() returning bogus results while reading 
through large non-binary files (in this case about a 530 meg 
text-file) once the file-offset passed some point I wasn't able 
to identify.  It may have to do with newline translation as this 
was python2.4 on Win32.  Switching to "b"inary mode resolved the 
issue for me.


I created the following generator to make my life a little easier:

  def offset_iter(fp):
assert 'b' in fp.mode.lower(), \
  "offset_iter must have a binary file"
while True:
  addr = fp.tell()
  line = fp.readline()
  if not line: break
  yield (addr, line.rstrip('\n\r'))

That way, I can just use

  f = file('foo.txt', 'b')
  for offset, line in offset_iter(f):
if line.startswith('>'): d[line] = offset

This bookmarks the *beginning* (I think your code notes the 
*end*) of each line that starts with ">"


-tkc





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


Re: Getting fractional part from a float without using string operations

2008-11-19 Thread MRAB
On Nov 19, 1:44 pm, John Machin <[EMAIL PROTECTED]> wrote:
> On Nov 20, 12:35 am, srinivasan srinivas <[EMAIL PROTECTED]>
> wrote:
> 
>
> | >>> import math
> | >>> num = 123.4567
> | >>> math.modf(num)
> | (0.456699789, 123.0)

def frac(n):
return n - int(n)
--
http://mail.python.org/mailman/listinfo/python-list


Re: wildcard match with list.index()

2008-11-19 Thread Sion Arrowsmith
jeff  <[EMAIL PROTECTED]> wrote:
 list
>[['a', [], []], ['b', [1, 2], []], ['c', [3, 4], [5, 6]]]
 list.index(['b',[],[]])
>
>ie, would like to match the second element in the list with something
>where i just know 'b' is the first element, but have no idea what the
>other elements will be:
>
>Traceback (most recent call last):
>  File "", line 1, in 
>ValueError: list.index(x): x not in list
 list.index(['b',[1,2],[]])
>1

If you really want to do that:

py> lst.index([x for x in lst if x[0] == 'b'][0])

(Oh, yeah, don't shadow the builtin "list".)

What I suspect would be far more useful is a better data structure:

py> dct = dict((x[0], x[1:]) for x in lst)
py> dct['b']>>> dct['b']
[[1, 2], []]

Dealing with the case of more than one entry identified by 'b' is
left as a problem to someone who knows what the data actually is.

-- 
\S -- [EMAIL PROTECTED] -- http://www.chaos.org.uk/~sion/
   "Frankly I have no feelings towards penguins one way or the other"
-- Arthur C. Clarke
   her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump
--
http://mail.python.org/mailman/listinfo/python-list


Re: Programming exercises/challenges

2008-11-19 Thread Mr . SpOOn
On Wed, Nov 19, 2008 at 2:39 AM, Mensanator <[EMAIL PROTECTED]> wrote:
> Another hobby I have is tracking movie box-office receipts
> (where you can make interesting graphs comparing Titanic
> to Harry Potter or how well the various sequels do, if Pierce
> Brosnan saved the James Bond franchise, what can you say about
> Daniel Craig?). Lots of potential database problems there.
> Not to mention automating the data collection from the Internet
> Movie Database by writing a web page scraper than can grab
> six months worth of data in a single session (you probably
> wouldn't need this if you cough up a subscription fee for
> professional access, but I'm not THAT serious about it).

This is really interesting. What would one need to do such a thing?
The only program web related I did in Python was generating a rss feed
from a local newspaper static site, using BeautifulSoup. But I never
put it on an online host. I'm not even sure if I could run. What
requisites should have the host to run python code?

Thanks and sorry for the meddling.
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to deal with globals during refactoring classes into separate files.

2008-11-19 Thread r0g
r0g wrote:
> Hi There,
> 
> I'm refactoring some old code that uses global variables and was
> originally written in one big flat file with a view to nicening it up
> and then extending it. The problem I have though is when I move the


Hi Chris / Gabriel,

Thanks v.much, that's really helped my understanding of this and my
refactoring is now proceeding apace :-)

Cheers,

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


Re: Exception difference 2.4 ==> 2.5

2008-11-19 Thread D'Arcy J.M. Cain
On Wed, 19 Nov 2008 01:57:37 -0500
Ross Ridge <[EMAIL PROTECTED]> wrote:
> D'Arcy J.M. Cain <[EMAIL PROTECTED]> wrote:
> >Under Python 2.4 this works fine.  If an exception is raised in the
> >looked up method it gets handled by this code just fine.  Under 2.5,
> >however, the exception is not caught here.  It's as if there was no
> >try/except here at all.
> 
> Python 2.5 changed the exception hierarchy a bit.  The Exception class
> is no longer at the root and now inheirits from BaseException.  If the
> exception being thrown was KeyboardInterrupt or SystemExit then it won't
> be caught by your code.

Yes, I was aware of that but the error not being caught is
RuntimeError.  I also tried a bare "except" just to be sure but same
behaviour.

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


Re: Inheriting frozenset gives bug if i overwrite __repr__ method

2008-11-19 Thread Mark Dickinson
On Nov 19, 12:39 pm, srinivasan srinivas <[EMAIL PROTECTED]>
wrote:
> a1 = fs(1,2,3)
> a2 = fs(3,4,5)
> print a1.difference(a2)
>
> Error:
>     return "%s(%r)" % (self.__class__.__name__, self.__data)
> AttributeError: 'fs' object has no attribute '_fs__data'

I guess you need to implement the difference method in your
subclass.

It's a little odd that an operation on subclasses of frozenset returns
an instance of the subclass, rather than simply a frozenset. Most
other
Python types don't work that way.  Compare and contrast:

Python 2.5.1 (r251:54863, Jan 17 2008, 19:35:17)
[GCC 4.0.1 (Apple Inc. build 5465)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> class myint(int): pass
...
>>> a = myint(3)
>>> b = myint(5)
>>> c = a+b
>>> c
8
>>> type(c)

>>> class fs(frozenset): pass
...
>>> a = fs([1, 2, 3])
>>> b = fs([3, 4, 5])
>>> c = a - b
>>> c
fs([1, 2])
>>> type(c)

>>>

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


Re: Getting fractional part from a float without using string operations

2008-11-19 Thread Tino Wildenhain

srinivasan srinivas wrote:

Yes. But it didn't give only the expected decimals.
For ex:
 >>> a = 1.23
 >>> abs(int(a) -a)
0.22998
 
I would like to get the result '0.23' only.


well, thats what get stored internally - there
is no way around it if you are using floating
point numbers:

>>> 0.23
0.23001

but str() handles the rounding correctly:

>>> print 0.23
0.23

>>> print abs(int(a) -a)
0.23

See also http://en.wikipedia.org/wiki/Floating_point
for the problems with FP figures.

Regards
Tino


smime.p7s
Description: S/MIME Cryptographic Signature
--
http://mail.python.org/mailman/listinfo/python-list


Re: how to acces the block inside of a context manager as sourcecode

2008-11-19 Thread Daniel
Hi Aaron,

let me give you the reason for the context manager:
I am driving handware with a python script, basically a data acquisition
program which looks like this:


with dataStore('measurement1.dat') as d:
magnet.setField(0)
r1=doExperiment(voltage=0.345, current=0.346, temperature=33)
magnet.setField(1)
r2=doExperiment(voltage=0.32423, current=0.3654, temperature=45)
d.append(r2-r1)

the script does the measuring and the context manager stores the result
(r1 and r2), at the end the result is printed.

The source code serves as the documentation (it contains many parameters
that need to be well documented), so I print the source code, cut it out
and glue it into my lab notebook.
Now I want to automate this process, i.e. the dataStore should print the
sourcecode.

Daniel

> There isn't a solution in the general case, because strings can be
> executed.  However, 'inspect.currentframe()' and
> 'inspect.getsourcelines(object)' can handle some cases, and your idea
> is (I believe) how getsourcelines works itself.  You can probably do
> it without a context manager, e.g. 'print_next_lines( 5 )' or
> 'print_prior_lines( 2 )', dedenting as needed.
--
http://mail.python.org/mailman/listinfo/python-list


More elegant way to try running a function X times?

2008-11-19 Thread Gilles Ganault
Hello

As a newbie, it's pretty likely that there's a smarter way to do this,
so I'd like to check with the experts:

I need to try calling a function 5 times. If successful, move on; If
not, print an error message, and exit the program:

=
success = None

for i in range(5):
#Try to fetch public IP
success = CheckIP()
if success:
break

if not success:
print "Exiting."
sys.exit()
=

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


Re: More elegant way to try running a function X times?

2008-11-19 Thread Tim Chase

I need to try calling a function 5 times. If successful, move on; If
not, print an error message, and exit the program:

success = None
for i in range(5):
#Try to fetch public IP
success = CheckIP()
if success:
break
if not success:
print "Exiting."
sys.exit()


Though a bit of an abuse, you can use

  if not any(CheckIP() for _ in range(5)):
print "Exiting"
sys.exit()

(this assumes Python2.5, but the any() function is easily 
recreated per the docs at [1]; and also assumes the generator 
creation of 2.4, so this isn't as useful in 2.3 and below)


Alternatively, you can use the for/else structure:

  for i in range(5):
if CheckIP():
  break
  else:
print "Exiting"
sys.exit()

-tkc

[1]
http://www.python.org/doc/2.5.2/lib/built-in-funcs.html#l2h-10





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


Re: Programming exercises/challenges

2008-11-19 Thread Philip Semanchuk


On Nov 19, 2008, at 7:12 AM, Mr.SpOOn wrote:

On Wed, Nov 19, 2008 at 2:39 AM, Mensanator <[EMAIL PROTECTED]>  
wrote:

Another hobby I have is tracking movie box-office receipts
(where you can make interesting graphs comparing Titanic
to Harry Potter or how well the various sequels do, if Pierce
Brosnan saved the James Bond franchise, what can you say about
Daniel Craig?). Lots of potential database problems there.
Not to mention automating the data collection from the Internet
Movie Database by writing a web page scraper than can grab
six months worth of data in a single session (you probably
wouldn't need this if you cough up a subscription fee for
professional access, but I'm not THAT serious about it).


This is really interesting. What would one need to do such a thing?
The only program web related I did in Python was generating a rss feed
from a local newspaper static site, using BeautifulSoup. But I never
put it on an online host. I'm not even sure if I could run. What
requisites should have the host to run python code?


I'm not sure why you'd need to host the Python code anywhere other  
than your home computer. If you wanted to pull thousands of pages from  
a site like that, you'd need to respect their robots.txt file. Don't  
forget to look for a crawl-delay specification. Even if they don't  
specify one, you shouldn't let your bot hammer their servers at full  
speed -- give it a delay, let it run in the background, it might take  
you three days versus an hour to collect the data you need but that's  
not too big of deal in the service of good manners, is it?


You might also want to change the user-agent string that you send out.  
Some sites serve up different content to bots than to browsers.


You could even use wget to scrape the site instead of rolling your own  
bot if you're more interested in the data manipulation aspect of the  
project than the bot writing.


Enjoy
Philip

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


Re: More elegant way to try running a function X times?

2008-11-19 Thread Sion Arrowsmith
Gilles Ganault  <[EMAIL PROTECTED]> wrote:
>As a newbie, it's pretty likely that there's a smarter way to do this,
>so I'd like to check with the experts:
>
>I need to try calling a function 5 times. If successful, move on; If
>not, print an error message, and exit the program:
>
>=
>success = None
>
>for i in range(5):
>   #Try to fetch public IP
>   success = CheckIP()
>   if success:
>   break
>
>if not success:
>   print "Exiting."
>   sys.exit()
>=

for i in range(5):
if CheckIP():
break
else:
print "Exiting."
sys.exit()

Note very carefully that the "else" goes with the "for" and not the "if".

-- 
\S -- [EMAIL PROTECTED] -- http://www.chaos.org.uk/~sion/
   "Frankly I have no feelings towards penguins one way or the other"
-- Arthur C. Clarke
   her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump
--
http://mail.python.org/mailman/listinfo/python-list


Re: More elegant way to try running a function X times?

2008-11-19 Thread Nicholas Ferenc Fabry


On Nov 19, 2008, at 09:09, Gilles Ganault wrote:


Hello

As a newbie, it's pretty likely that there's a smarter way to do this,
so I'd like to check with the experts:

I need to try calling a function 5 times. If successful, move on; If
not, print an error message, and exit the program:

=
success = None

for i in range(5):
#Try to fetch public IP
success = CheckIP()
if success:
break

if not success:
print "Exiting."
sys.exit()
=



A little simpler:

for i in range(5):
if CheckIP():
break
else:
print "Exiting."
sys.exit()

The else part will only fire if the for finishes without breaking.   
Hope this helps a bit...



Nick Fabry











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


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


wxPython BoxSizer

2008-11-19 Thread Jamie McQuay
Simple question, i just can't make it work.

I need to center a StaticText component in its parent (Panel).  I want
to do this with BoxSizer(s).

if i use:
box = wx.BoxSizer(wx.VERTICAL)   #or wx.HORIZONTAL
box.Add(myText,0,wx.ALIGN_CENTER)
parentPanel.Sizer = box

i can get it to center either vertically or horizontally, but not both
(i.e. the center).  I've tried myText.CenterOnParent but i need to
handle to Size event to move the text when the panel is resized and i
don't want to have to do this.

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


Re: Python bytecode STORE_NAME

2008-11-19 Thread schwarz
On 19 Nov., 10:14, Peter Otten <[EMAIL PROTECTED]> wrote:
>
> Every code object has its own co_names attribute (a tuple). The arguments
> are offsets into that tuple.
>
> Using Python 2.5 I can't reproduce your example, I get 0 offsets in both
> cases. Here's a simpler one:
>
> >>> import dis
> >>> def f():
>
> ...     x
> ...     y
> ...>>> def g():
>
> ...     y
> ...>>> dis.dis(f)
>
>   2           0 LOAD_GLOBAL              0 (x)
>               3 POP_TOP
>
>   3           4 LOAD_GLOBAL              1 (y)
>               7 POP_TOP
>               8 LOAD_CONST               0 (None)
>              11 RETURN_VALUE>>> dis.dis(g)
>
>   2           0 LOAD_GLOBAL              0 (y)
>               3 POP_TOP
>               4 LOAD_CONST               0 (None)
>               7 RETURN_VALUE>>> f.func_code.co_names
> ('x', 'y')
> >>> g.func_code.co_names
>
> ('y',)
>
> Peter

Ok, thanks a lot. That helped me understand the offsets. Your
disassembly misses the code in the global scope that creates the two
methods from the code objects. That code looks like this for your
example (dis won't give you this. I use a modified version of the
byteplay disassembler which can disassemble a module without loading
it):
1, LOAD_CONST, 1 //Loads the code object for function f
4, MAKE_FUNCTION, 0 //Creates a function from the code object
7, STORE_NAME, 0 //Stores it as 'f' using STORE_NAME
10, LOAD_CONST, 2 //Loads the code object for function g
13, MAKE_FUNCTION, 0 //Creates the function
16, STORE_NAME, 1 //Stores it as 'g' using STORE_NAME
19, LOAD_CONST, 0 //Loads None
22, RETURN_VALUE, None //Exists the program with status None

The two last bytecodes are there because I didn't use the interactive
mode. I guess I narrowed down my other question to whether the
semantics are that stuff saved using STORE_NAME in the global scope
can be loaded everywhere else using LOAD_GLOBAL. What baffled me was
that there is actually a STORE_GLOBAL byte code.
--
http://mail.python.org/mailman/listinfo/python-list


Re: More elegant way to try running a function X times?

2008-11-19 Thread Gilles Ganault
On 19 Nov 2008 14:37:06 + (GMT), Sion Arrowsmith
<[EMAIL PROTECTED]> wrote:
>Note very carefully that the "else" goes with the "for" and not the "if".

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


Re: redirecting stdout/err to mysql table

2008-11-19 Thread pruebauno
On Nov 18, 2:07 pm, n00b <[EMAIL PROTECTED]> wrote:
> greetings,
>
> i need to log to the db directly and wrote a little script to do so.
> since i'm pretty new to python,
> i was wondering if a) you could review the enclosed code and b)
> provide suggestions to harden to code to turn it into a more general,
> broadly reusable class.
>
> thank you very much.
>
> import sys
> import MySQLdb
>
> class DBLogger(object):
> def __init__(self):
> self.db_name = 'xxx'
> self.db_host = '127.0.0.1'
> self.db_table = 'yyy'
> self.db_uname = 'root'
> self.db_passwd = ''
> self.db_port = 3306
> self.db = None
> self.cur = None
> self.sql = 'INSERT INTO %s' %self.db_table + ' VALUES(null, NOW
> (), %s)'
>
> def openDb(self):
> try:
> self.db = MySQLdb.connect(host = self.db_host,
> user = self.db_uname,
> passwd = self.db_passwd,
> db = self.db_name,
> )
>
> self.cur = self.db.cursor()
> return self.db, self.cur
> except Exception, e:
> sys.stdout = sys.__stdout__
> sys.stderr = sys.__stderr__
> print e[0], e[1]
> sys.exit(1)
>
> def closeDb(self):
>self.cur.close()
>self.db.close()
>
> def write(self, string):
> s = string.strip('\n')
> if not s=='':
> self.openDb()
> self.cur.execute(self.sql, (s))
> self.db.commit()
> self.closeDb()
>
> dbl = DBLogger()
> sys.stdout = dbl
> sys.stderr = dbl
> #a = 'test string'
> #dbl.write(a)
>
> print 'a b c '
> sys.stdout = sys.__stdout__
> sys.stderr = sys.__stderr__
>
> thanks again for your time

Looks good to me.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Optional parameter object re-used when instantiating multiple objects

2008-11-19 Thread George Sakkis
On Nov 19, 8:41 am, Rick Giuly <[EMAIL PROTECTED]> wrote:

> Python provides, for the most part, an *excellent* user
> interface to the programmer. Why not make it even "better"
> by evaluating the arguments each time the function is called?
> It will be harder to change the language 10 years from now,
> so why not change it now?

You probably messed up with your time machine; "now" is 2008, not
1991 ;-)

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


Why is try...except in my code not working (gzip/text files) ?

2008-11-19 Thread Barak, Ron
Hi,

I need to read a file that is either a gzip or a text file (on both *nix and 
Windows).
Since I didn't find a way to determine a file type, I thought of using the 
following:

import gzip

FILE = "../dpm/save_state-ssp8400-F0023209_080723-110131/top.1"
#FILE = "../dpm/save_state-ssp8400-F0023209_080723-110131/var/log/sac.log.0.gz"

try:
file = gzip.GzipFile(FILE, "r")
except IOError:
file = open(FILE, "r")

print file.read()


Strangely, when FILE is a gzip file, all is fine.
But, when FILE is a text file (as in the above code), I get the following:

$ python ./gzip_try.py
Traceback (most recent call last):
  File "./gzip_try.py", line 11, in 
print file.read()
  File "c:\Python25\lib\gzip.py", line 220, in read
self._read(readsize)
  File "c:\Python25\lib\gzip.py", line 263, in _read
self._read_gzip_header()
  File "c:\Python25\lib\gzip.py", line 164, in _read_gzip_header
raise IOError, 'Not a gzipped file'
IOError: Not a gzipped file

Can you explain why the try...except in my code does not work ?
Or, back to my original problem: how do I deal with a file whether it's a text 
file or a gzip file ?

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


Python image library issue: domain users cannot save files?

2008-11-19 Thread [EMAIL PROTECTED]
Hi,
Has anyone try to use PIL in a windows domain environment? I am having
a permission issue. If I am a domain user, even I have the permission
to write a folder, when I tried to do simple things like Image.open
("foo.tif").save("bar.tif"), i am getting exception IOError ("0",
"Error"). I tried to set os.umask(0) before I saved the file but the
same exception threw. But If I am the same domain user with local
admin permission on a windows box, I have no problem with the same
script. Does anyone ever have the same situation and know a work
around for this? Thanks.

Best,

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


XML -> Tab-delimited text file (using lxml)

2008-11-19 Thread Gibson
I'm attempting to do the following:
A) Read/scan/iterate/etc. through a semi-large XML file (about 135 mb)
B) Grab specific fields and output to a tab-delimited text file

The only problem I'm having is that the tab-delimited text file
requires a different order of values than which appear in the XML
file. Example below.


   
  
  
  
   
   
  
  
  
   
   
  
  
  
   


(Note: The last item "3456cdef" shows the description value as being
before the name, where as in previous items, it comes after. This is
to simulate the XML data with which I am working.)
And the tab-delimited text file should appear as follows: (tabs are as
2 spaces, for the sake of readability here)

(ID,name,description,image)
1234abcd  My Wonderful Product 1  My Wonderful Product 1 is a
wonderful product, indeed.  image.jpg
2345bcde  My Wonderful Product 2  My Wonderful Product 2 is a
wonderful product, indeed.  image2.jpg
3456cdef  My Wonderful Product 3  My Wonderful Product 3 is a
wonderful product, indeed.  image3.jpg

Currently, I'm working with the lxml library for iteration and
parsing, though this is proving to be a bit of a challenge for data
that needs to be reorganized (such as mine). Sample below.

''' Start code '''

from lxml import etree

def main():
  # Far too much room would be taken up if I were to paste my
  # real code here, so I will give a smaller example of what
  # I'm doing. Also, I do realize this is a very naive way to do
  # what it is I'm trying to accomplish... besides the fact
  # that it doesn't work as intended in the first place.

  out = open('output.txt','w')
  cat = etree.parse('catalog.xml')
  for el in cat.iter():
# Search for the first item, make a new line for it
# and output the ID
if el.tag == "Item":
  out.write("\n%s\t" % (el.attrib['ID']))
elif el.tag == "ItemVal":
  if el.attrib['ValueID'] == "name":
out.write("%s\t" % (el.attrib['value']))
  elif el.attrib['ValueID'] == "description":
out.write("%s\t" % (el.attrib['value']))
  elif el.attrib['ValueID'] == "image":
out.write("%s\t" % (el.attrib['value']))
  out.close()

if __name__ == '__main__': main()

''' End code '''

I now realize that etree.iter() is meant to be used in an entirely
different fashion, but my brain is stuck on this naive way of coding.
If someone could give me a push in any correct direction I would be
most grateful.
--
http://mail.python.org/mailman/listinfo/python-list


Re: redirecting stdout/err to mysql table

2008-11-19 Thread Aleksandar Radulovic
On Tue, Nov 18, 2008 at 7:07 PM, n00b <[EMAIL PROTECTED]> wrote:
> greetings,
>
> i need to log to the db directly and wrote a little script to do so.
> since i'm pretty new to python,
> i was wondering if a) you could review the enclosed code and b)
> provide suggestions to harden to code to turn it into a more general,
> broadly reusable class.

First of all, your code is not quite pythonic and it will also open the
connection to the database *every* time you log. That can be quite
expensive and generally is not advisable. Plus it may block your code.

I suggest checking out (already existing) logging module in Python
distribution and extend the BaseHandler to implement the logging to
a database.

I highly recommend implementing pooling of connections to the DB
(ie. by simply using SqlAlchemy instead of direct MySQLDb module).



-- 
a lex 13 x
http://www.a13x.info
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python bytecode STORE_NAME

2008-11-19 Thread Peter Otten
[EMAIL PROTECTED] wrote:

> On 19 Nov., 10:14, Peter Otten <[EMAIL PROTECTED]> wrote:
>>
>> Every code object has its own co_names attribute (a tuple). The arguments
>> are offsets into that tuple.
>>
>> Using Python 2.5 I can't reproduce your example, I get 0 offsets in both
>> cases. Here's a simpler one:
>>
>> >>> import dis
>> >>> def f():
>>
>> ...     x
>> ...     y
>> ...>>> def g():
>>
>> ...     y
>> ...>>> dis.dis(f)
>>
>> 2           0 LOAD_GLOBAL              0 (x)
>> 3 POP_TOP
>>
>> 3           4 LOAD_GLOBAL              1 (y)
>> 7 POP_TOP
>> 8 LOAD_CONST               0 (None)
>> 11 RETURN_VALUE>>> dis.dis(g)
>>
>> 2           0 LOAD_GLOBAL              0 (y)
>> 3 POP_TOP
>> 4 LOAD_CONST               0 (None)
>> 7 RETURN_VALUE>>> f.func_code.co_names
>> ('x', 'y')
>> >>> g.func_code.co_names
>>
>> ('y',)
>>
>> Peter
> 
> Ok, thanks a lot. That helped me understand the offsets. Your
> disassembly misses the code in the global scope that creates the two
> methods from the code objects. That code looks like this for your
> example (dis won't give you this. I use a modified version of the
> byteplay disassembler which can disassemble a module without loading
> it):
> 1, LOAD_CONST, 1 //Loads the code object for function f
> 4, MAKE_FUNCTION, 0 //Creates a function from the code object
> 7, STORE_NAME, 0 //Stores it as 'f' using STORE_NAME
> 10, LOAD_CONST, 2 //Loads the code object for function g
> 13, MAKE_FUNCTION, 0 //Creates the function
> 16, STORE_NAME, 1 //Stores it as 'g' using STORE_NAME
> 19, LOAD_CONST, 0 //Loads None
> 22, RETURN_VALUE, None //Exists the program with status None

You can get it with standard tools, too:

$ cat tmp.py
def f():
x
y

def g():
x
$ python -c'import tmp'
$ python
Python 2.5.1 (r251:54863, Jul 31 2008, 23:17:43)
[GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import marshal
>>> module = marshal.loads(open("tmp.pyc").read()[8:])
>>> import dis
>>> dis.dis(module)
  1   0 LOAD_CONST   0 ()
  3 MAKE_FUNCTION0
  6 STORE_NAME   0 (f)

  5   9 LOAD_CONST   1 ()
 12 MAKE_FUNCTION0
 15 STORE_NAME   1 (g)
 18 LOAD_CONST   2 (None)
 21 RETURN_VALUE

I just didn't deem it relevant.

> The two last bytecodes are there because I didn't use the interactive
> mode. I guess I narrowed down my other question to whether the
> semantics are that stuff saved using STORE_NAME in the global scope
> can be loaded everywhere else using LOAD_GLOBAL. What baffled me was
> that there is actually a STORE_GLOBAL byte code.

If you are really interested in the subtleties you have to dive into the
source. After a quick look into

http://svn.python.org/view/python/trunk/Python/ceval.c?rev=63675&view=markup

I think STORE_NAME works with the module startup code because global and
local namespace are identical. Within a function (with distinct global and
local namespaces) you'd have to use STORE_GLOBAL.

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


Re: XML -> Tab-delimited text file (using lxml)

2008-11-19 Thread Stefan Behnel
Gibson wrote:
> I'm attempting to do the following:
> A) Read/scan/iterate/etc. through a semi-large XML file (about 135 mb)
> B) Grab specific fields and output to a tab-delimited text file
> [...]
>   out = open('output.txt','w')
>   cat = etree.parse('catalog.xml')

Use iterparse() instead of parsing the file into memory completely.

untested:

for _, item in etree.iterparse('catalog.xml', tag='Item'):
# do some cleanup to save memory
previous_item = item.getprevious()
while previous_item is not None:
 previous_item.getparent().remove(previous_item)
 previous_item = item.getprevious()

# now read the data
id = item.get('ID')
collect = {}
for child in item:
if child.tag != 'ItemVal': continue
collect[child.get('ValueId')] = child.get('value')

print "%s\t%s\t%s\t%s" % ((id,) + tuple(
collect[key] for key in ['name','description','image']))

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


Re: More elegant way to try running a function X times?

2008-11-19 Thread George Sakkis
On Nov 19, 10:21 am, Gilles Ganault <[EMAIL PROTECTED]> wrote:

> On 19 Nov 2008 14:37:06 + (GMT), Sion Arrowsmith
>
> <[EMAIL PROTECTED]> wrote:
> >Note very carefully that the "else" goes with the "for" and not the "if".
>
> Thanks guys.

And if you end up doing this for several different functions, you can
factor it out with the following decorator:

class MaxRetriesExceededError(Exception):
pass

def retry(n):
def decorator(f):
def wrapper(*args, **kwds):
for i in xrange(n):
r = f(*args, **kwds)
if r: return r
raise MaxRetriesExceededError
return wrapper
return decorator

If the number of retries is fixed and known at "compile" time, you can
use the standard decorator syntax:

@retry(5)
def CheckIP():
   ...

If not, just decorate it explicitly at runtime:

def CheckIP():
  ...

n = int(raw_input('Give number of retries:'))
CheckIP = retry(n)(CheckIP)


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


Re: python vs smalltalk 80

2008-11-19 Thread Grant Edwards
On 2008-11-19, gavino <[EMAIL PROTECTED]> wrote:
> python vs smalltalk 80
>
> which is nicer?

Yes.

-- 
Grant Edwards   grante Yow! ... I want to perform
  at   cranial activities with
   visi.comTuesday Weld!!
--
http://mail.python.org/mailman/listinfo/python-list


Re: Official definition of call-by-value (Re: Finding the instance reference...)

2008-11-19 Thread Terry Reedy

Steven D'Aprano wrote:

On Tue, 18 Nov 2008 15:55:10 -0500, Terry Reedy wrote:



To me, that distortion of his (and my) point is silly.  0 partipipates
in numerous integer operations, whereas None participates in no NoneType
operations.  (Neither has attributes.)  And that is the difference he is
pointing at.


Why do you care about built-in NoneType operations?


Because class-specific operations are what make one class, and instances 
thereof, different from another.  If you don't care about that, fine, 
but stop ridiculing those who do.  Why do you oppose people 
investigating specific differences?


> Why don't we count the infinite number of useful operations
> we can do to None that merely happen to not be built-in to the type?

Everything one can do with None is due to its status as a Python object.


We can convert None to a bool: bool(None)
We can append it to a list: alist.append(None)
We can convert it to a string: str(None), repr(None)
(In Python 2.6) We can ask how many bytes the None object uses.
We can ask the garbage collector how many objects refer to it: 
gc.get_referrers
We can count how many words have been written debating whether or not 
None is a value.


and so forth. These operations aren't methods on NoneType but that is not 
of any importance. The richness or poverty of methods in a class is 
irrelevant.


To you, but not to me.

It is useful and convenient to have "null values" like None, but it isn't 
useful to say that None is not a value.


I never said that.  I said that it has no attributes (other than 
__class__) and no private data.  In other words, no content, no state. 
It is an empty object, just like objects()s, and similar in that to 
empty collections.


Terry Jan Reedy

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


Re: Inheriting frozenset gives bug if i overwrite __repr__ method

2008-11-19 Thread Gabriel Genellina
En Wed, 19 Nov 2008 11:56:28 -0200, Mark Dickinson <[EMAIL PROTECTED]>  
escribió:



On Nov 19, 12:39 pm, srinivasan srinivas <[EMAIL PROTECTED]>
wrote:

a1 = fs(1,2,3)
a2 = fs(3,4,5)
print a1.difference(a2)

Error:
    return "%s(%r)" % (self.__class__.__name__, self.__data)
AttributeError: 'fs' object has no attribute '_fs__data'


I guess you need to implement the difference method in your
subclass.

It's a little odd that an operation on subclasses of frozenset returns
an instance of the subclass, rather than simply a frozenset. Most
other
Python types don't work that way.  Compare and contrast:


Yep; looks like a bug in the set/frozenset implementation. Usually builtin  
types don't return subclasses because they don't know how the constructor  
should be called - it is indeed the case here, as the OP has changed  
frozenset.__new__ signature. Even if fs.__new__ were called its arguments  
would be wrong.
The bug is not that the subclass constructor is skipped, but that  
a1.difference(a2) returns a subclass instead of a frozenset instance.
(set and frozenset are unrelated types but share a lot of their  
implementation by using generic algorithms, and it's the generic part the  
culprit here)


--
Gabriel Genellina

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


Re: Exception difference 2.4 ==> 2.5

2008-11-19 Thread D'Arcy J.M. Cain
On Tue, 18 Nov 2008 22:33:35 -0800
"Chris Rebert" <[EMAIL PROTECTED]> wrote:
> What happens under Python 2.6?

Interesting.  I installed 2.6 and tried it.  My unit test still failed
but for a different reason that I will have to investigate but the
exceptions were handled correctly.  Does this suggest something to you?

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


Re: python vs smalltalk 80

2008-11-19 Thread Jason Scheirer
On Nov 18, 10:53 pm, gavino <[EMAIL PROTECTED]> wrote:
> python vs smalltalk 80
>
> which is nicer?

I thought this was comp.lang.colorforth. WHAT IS GOING ON?
--
http://mail.python.org/mailman/listinfo/python-list


Re: sorting list of complex numbers

2008-11-19 Thread Terry Reedy

Hrvoje Niksic wrote:

Terry Reedy <[EMAIL PROTECTED]> writes:


Do your tuple destructuring in the first statement in your body and
nothing will break.


Unless you were using a lambda, which is quite useful as argument to
"sort".


So write a separate def statement.
If you do not want to do that, don't run with 3.0.

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


Re: Getting fractional part from a float without using string operations

2008-11-19 Thread Blind Anagram
"MRAB" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]

On Nov 19, 1:44 pm, John Machin <[EMAIL PROTECTED]> wrote:

On Nov 20, 12:35 am, srinivasan srinivas <[EMAIL PROTECTED]>
wrote:


| >>> import math
| >>> num = 123.4567
| >>> math.modf(num)
| (0.456699789, 123.0)


def frac(n):
   return n - int(n)


n % 1.0

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


broken setuptools dependencies

2008-11-19 Thread Mac
I just tried to set up a Windows box as a client talking to a MySQL
database on Linux using Python.  So I installed the most recent
version of Python (2.6) and then I tried to add the MySQLdb module.
There wasn't any binary pre-built for Python 2.6 on Windows (or any
other OS), so I pulled down the tarball, unpacked it, and ran setup.py
install.  That blew up because it couldn't find the version of
setuptools that it needed on the cheeseshop.python.org server.

I have to say that I find all the different packaging installation
options more than a little confusing (wasn't Perl supposed to be the
language that gave you more ways to do something than you really
wanted?), and I find myself wondering why the standard distribution of
Python doesn't come with everything you need to install a third-party
package.  That would come closer to the "batteries included" paradigm
the community likes to advertise.

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


Re: Python 3.0 - is this true?

2008-11-19 Thread Terry Reedy

Duncan Grisby wrote:



Sorry for the delay in replying. Yes, that's not far off. Most of the
time the lists contain strings, though. A better approximation might
be to read lines from a file and randomly replace them with Nones:

l = []
for line in open("bigfile.txt"):
x = random.randint(0,100)
if x < 4: l.append(None)
else: l.append(line)


So use '' or '\0' instead of None for null lines.  Or replace None for 
the sort.



And maybe once in a while you end up with something not dissimilar to:

l = []
for line in open("bigfile.txt"):
x = random.randint(0,100)
if x < 4: l.append(None)
elif x < 5: l.append([line,line])
else: l.append(line)

In that kind of case it doesn't really matter what happens to list
items in the sort order, but it's important it doesn't fail to sort
the ones that are strings.


Replace the sublists with a coded string, such as '\0'+line.
If sorting is time (and space) critical, you want a straight string sort 
without key *or* cmp function.


tjr

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


Re: file tell in a for-loop

2008-11-19 Thread Magdoll
Gotcha. Thanks!

Magdoll

On Nov 19, 2:57 am, Tim Chase <[EMAIL PROTECTED]> wrote:
> Magdoll wrote:
> > I was trying to map various locations in a file to a dictionary. At
> > first I read through the file using a for-loop, buttell() gave back
> > weird results, so I switched to while, then it worked.
>
> > The for-loop version was something like:
> >                 d = {}
> >                 for line in f:
> >                          if line.startswith('>'): d[line] = f.tell()
>
> > And the while version was:
> >                 d = {}
> >                 while 1:
> >                         line = f.readline()
> >                         if len(line) == 0: break
> >                         if line.startswith('>'): d[line] = f.tell()
>
> > In the for-loop version, f.tell() would sometimes return the same
> > result multiple times consecutively, even though the for-loop
> > apparently progressed the file descriptor. I don't have a clue why
> > this happened, but I switched to while loop and then it worked.
>
> > Does anyone have any ideas as to why this is so?
>
> I suspect that at least the iterator version uses internal
> buffering, so thetell() call returns the current buffer
> read-location, not the current read location.  I've also had
> problems withtell() returning bogus results while reading
> through large non-binary files (in this case about a 530 meg
> text-file) once the file-offset passed some point I wasn't able
> to identify.  It may have to do with newline translation as this
> was python2.4 on Win32.  Switching to "b"inary mode resolved the
> issue for me.
>
> I created the following generator to make my life a little easier:
>
>    def offset_iter(fp):
>      assert 'b' in fp.mode.lower(), \
>        "offset_iter must have a binary file"
>      while True:
>        addr = fp.tell()
>        line = fp.readline()
>        if not line: break
>        yield (addr, line.rstrip('\n\r'))
>
> That way, I can just use
>
>    f = file('foo.txt', 'b')
>    for offset, line in offset_iter(f):
>      if line.startswith('>'): d[line] = offset
>
> This bookmarks the *beginning* (I think your code notes the
> *end*) of each line that starts with ">"
>
> -tkc

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


Re: python vs smalltalk 80

2008-11-19 Thread Pierre-Alain Dorange
gavino <[EMAIL PROTECTED]> wrote:

> python vs smalltalk 80
> 
> which is nicer?

1st clue : Python got less letters in its name.
2nd clue : 80 is the year of the release of Alan Vega/Martin Rev album
3rd clue : Smalltalk began with an S, but Python with a P

-- 
Pierre-Alain Dorange

Ce message est sous licence Creative Commons "by-nc-sa-2.0"

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


Re: zope vs openACS

2008-11-19 Thread [EMAIL PROTECTED]
On Nov 19, 1:50 am, gavino <[EMAIL PROTECTED]> wrote:
> what is nicer about each?

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


Re: Inheriting frozenset gives bug if i overwrite __repr__ method

2008-11-19 Thread Terry Reedy

srinivasan srinivas wrote:

Hi,
I am getting an error while executing the following snippet. If i comment out 
method __repr__ , it works fine.

class fs(frozenset):
def __new__(cls, *data):
data = sorted(data)
self = frozenset.__new__(cls, data)
self.__data = data
return self

def __repr__(self):
return "%s(%r)" % (self.__class__.__name__, self.__data)

a1 = fs(1,2,3)
a2 = fs(3,4,5)
print a1.difference(a2)

Error:
return "%s(%r)" % (self.__class__.__name__, self.__data)
AttributeError: 'fs' object has no attribute '_fs__data'

Please help me in fixing this.


When posting problems like this, please include the Python version.
If you ran this with 2.6, please run the following:

x = frozenset('abc')
y = frozenset('bcd')
z = x.difference(y)
print(id(x) != id(z))

This should print (True), but if 2.6 has a bug for frozenset similar one 
it has for bytearrays, it will print (False) and that would explain your 
error.


tjr

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


Re: sorting list of complex numbers

2008-11-19 Thread Hrvoje Niksic
Terry Reedy <[EMAIL PROTECTED]> writes:

> Hrvoje Niksic wrote:
>> Terry Reedy <[EMAIL PROTECTED]> writes:
>>
>>> Do your tuple destructuring in the first statement in your body and
>>> nothing will break.
>>
>> Unless you were using a lambda, which is quite useful as argument to
>> "sort".
>
> So write a separate def statement.

That is a valid possibility, but loses the succinctness of a short
lambda.  Some uses of lambda+unpacking can also be replaced by
operator.itemgetter.

> If you do not want to do that, don't run with 3.0.

Tuple unpacking in parameters is a useful feature, but hardly reason
enough to abandon the future of the language.
--
http://mail.python.org/mailman/listinfo/python-list


Re: wxPython BoxSizer

2008-11-19 Thread Mike Driscoll
Hi Jamie,

On Nov 19, 9:16 am, Jamie McQuay <[EMAIL PROTECTED]> wrote:
> Simple question, i just can't make it work.
>
> I need to center a StaticText component in its parent (Panel).  I want
> to do this with BoxSizer(s).
>
> if i use:
> box = wx.BoxSizer(wx.VERTICAL)   #or wx.HORIZONTAL
> box.Add(myText,0,wx.ALIGN_CENTER)
> parentPanel.Sizer = box
>
> i can get it to center either vertically or horizontally, but not both
> (i.e. the center).  I've tried myText.CenterOnParent but i need to
> handle to Size event to move the text when the panel is resized and i
> don't want to have to do this.
>
> thanks,
> Jamie

Try the style=wx.CENTER like this:

box.Add(myText,0,wx.CENTER)

FYI: There's a great wxPython mailing list too. Check it out here:
http://wxpython.org/maillist.php

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


Re: Programming exercises/challenges

2008-11-19 Thread Mr . SpOOn
On Wed, Nov 19, 2008 at 3:41 PM, Philip Semanchuk <[EMAIL PROTECTED]> wrote:
> I'm not sure why you'd need to host the Python code anywhere other than your
> home computer. If you wanted to pull thousands of pages from a site like
> that, you'd need to respect their robots.txt file. Don't forget to look for
> a crawl-delay specification. Even if they don't specify one, you shouldn't
> let your bot hammer their servers at full speed -- give it a delay, let it
> run in the background, it might take you three days versus an hour to
> collect the data you need but that's not too big of deal in the service of
> good manners, is it?

Mmm, I didn't really mean the possibility to just host the code, but
to run. I mean, like server side code, so that my programs keep
running and updating, in my case, the RSS feed, without the need for
me to be online and run it.
--
http://mail.python.org/mailman/listinfo/python-list


Re: PEP 324 error

2008-11-19 Thread Terry Reedy

Andrew wrote:

It appears PEP 324 is missing the part about check_call():

http://www.python.org/dev/peps/pep-0324/ ...

...


In the docstring of subprocess in python 2.5:

...


I don't know if check_call is going to be deprecated, but there still
appears to be a missing function. I'm not sure if this is the correct
way to report errors, but I think it's prudent to keep the
documentation comprehensive.


Comments about the text of a PEP should be directed to the PEP author, 
whose is the one who would edit it.


The definitive documentation of the subprocess module is, as usual, its 
section in the Library manual, as well as the docstring.  Those two 
should be in sync.  PEPs are design and development documents and are 
usually not revised once approved and implemented.


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


python template: may help at starting a new script

2008-11-19 Thread Stephane Bulot
Hello,

I've created a python script template that I've been using for a while, but
that I improved recently.
This script is a class that you can inherit into your main class. In the
source package, you have a main template, a thread template, and two example
files.

If you are interested in this project, you can go to the
http://www.bulot.org/wiki/doku.php?id=projects:python:pytemplate and let me
know your feedbacks. If you use it, tell me how to improve, what to add,
what is wrong, what is good.
For your information, this script has not been tested on windows. Feel free
to patch it and give me your patches. I will introduce them into my project.

You will get some news on http://www.bulot.org .

Regards.

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


Re: wxPython BoxSizer

2008-11-19 Thread Jamie McQuay

>
> Try the style=wx.CENTER like this:
>
> box.Add(myText,0,wx.CENTER)

tried but i still get the same result.  The text is either at the top
of the panel (centered) or in the middle (on the left side).  If i
manually call CenterOnParent when the panel is resized it goes to the
center but i want to get the sizers to work correctly for this.

>
> FYI: There's a great wxPython mailing list too. Check it out 
> here:http://wxpython.org/maillist.php

thanks, i will take a look.

Jamie

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


Re: XML -> Tab-delimited text file (using lxml)

2008-11-19 Thread Gibson
On Nov 19, 11:03 am, Stefan Behnel <[EMAIL PROTECTED]> wrote:
>
> Use iterparse() instead of parsing the file into memory completely.
>
> *stuff*
>
> Stefan

That worked wonders. Thanks a lot, Stefan.

So, iterparse() uses an iterate -> parse method instead of parse() and
iter()'s parse -> iterate method (if that makes any sense)?
--
http://mail.python.org/mailman/listinfo/python-list


Re: python vs smalltalk 80

2008-11-19 Thread George Sakkis
On Nov 19, 1:53 am, gavino <[EMAIL PROTECTED]> wrote:

> python vs smalltalk 80
>
> which is nicer?

Dunno but there's an interesting talk about this: 
http://www.youtube.com/watch?v=oHg5SJYRHA0

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


Re: Inheriting frozenset gives bug if i overwrite __repr__ method

2008-11-19 Thread Mark Dickinson
On Nov 19, 4:23 pm, "Gabriel Genellina" <[EMAIL PROTECTED]>
wrote:
> Yep; looks like a bug in the set/frozenset implementation.

Thanks!  I was about to report this to bugs.python.org, but it
looks as though Raymond's been at the time machine again:

http://bugs.python.org/issue1721812

It's fixed in 3.0; backporting the fix to 2.x was deemed too risky.

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


Quick nested loop syntax?

2008-11-19 Thread Johannes Bauer
Hi group,

if I remember correctly, wasn't there a way to quickly iterate through
nested loops? Something like

a = { "a", "b", "c" }
b = { 4, 9, 13}
for (x, y) in someoperator(a, b):
print(x, y)

which would print all tuples of
"a", 4
"a", 9
"a", 13
"b", 4
"b", 9
"b", 13
"c", 4
"c", 9
"c", 13

(not nececssarily in that order, of course).

Thanks,
Johannes

-- 
"Meine Gegenklage gegen dich lautet dann auf bewusste Verlogenheit,
verlästerung von Gott, Bibel und mir und bewusster Blasphemie."
 -- Prophet und Visionär Hans Joss aka HJP in de.sci.physik
 <[EMAIL PROTECTED]>
--
http://mail.python.org/mailman/listinfo/python-list


Re: Possible bug in Tkinter for Python 2.6

2008-11-19 Thread Terry Reedy

Anton Vredegoor wrote:

On Wed, 19 Nov 2008 10:57:53 +0100
"Eric Brunel" <[EMAIL PROTECTED]> wrote:


I'm trying out Python 2.6 and I found what might be a bug in the
Tkinter module. How can I report it?


maybe here:
http://bugs.python.org/issue3774


The fix will be in 2.6.1, which might be in December.

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


wxPython Crashes with basic example

2008-11-19 Thread Samuel Morhaim
Hi, I am trying to run the basic wxpython example as seen here
http://www.zetcode.com/wxpython/firststeps/ and everytime i run it, it
crashes python/wxpython .. meaning it doesnt close gracefully.
The error I get is

Problem signature:
  Problem Event Name: APPCRASH
  Application Name: pythonw.exe
  Application Version: 0.0.0.0
  Application Timestamp: 48e49638
  Fault Module Name: comctl32.dll_unloaded
  Fault Module Version: 0.0.0.0
  Fault Module Timestamp: 4791a629
  Exception Code: c005
  Exception Offset: 72b35a6e
  OS Version: 6.0.6001.2.1.0.256.1
  Locale ID: 1033
  Additional Information 1: fd00
  Additional Information 2: ea6f5fe8924aaa756324d57f87834160
  Additional Information 3: fd00
  Additional Information 4: ea6f5fe8924aaa756324d57f87834160

Read our privacy statement:
  http://go.microsoft.com/fwlink/?linkid=50163&clcid=0x0409



Any ideas? it is just a basic example..   running python 2.6, wxpython,
executing via IDLE or eric or any other..

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


Re: Quick nested loop syntax?

2008-11-19 Thread Mark Dickinson
On Nov 19, 5:48 pm, Johannes Bauer <[EMAIL PROTECTED]> wrote:
> Hi group,
>
> if I remember correctly, wasn't there a way to quickly iterate through
> nested loops? Something like

Python 2.6 has itertools.product:

http://docs.python.org/library/itertools.html#itertools.product

If you don't have Python 2.6 available, then the documentation
above also contains (almost) equivalent Python code that might
work for you.

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


Re: Finding the instance reference of an object

2008-11-19 Thread Douglas Alan
greg <[EMAIL PROTECTED]> writes:

> Steven D'Aprano wrote:

>> At least some sections of the Java community seem to prefer a
>> misleading and confusing use of the word "value" over clarity and
>> simplicity, but I for one do not agree with them.

> I don't see anything inherently confusing or misleading
> about it. Confusion only arises when some people jump up
> and say that it's wrong to use the terms that way, because
> it might cause confusion...

Personally, I find this whole debate kind of silly, as it is based on
a completely fallacious either/or dichotomy.

(1) It is unarguably true that Python and Java use a type of
call-by-value.  This follows from the standard definition of
call-by-value, and common usage in, for example, the Scheme and
Java communities, etc.

(2) It is also unarguably true that saying that Python or Java use
"call-by-value", and saying nothing more is going to be profoundly
confusing to anyone who is learning these languages.

It's like the difference between

   Q. What is a giraffe?

   A. A giraffe is a type of animal.

and

   Q. What is Greg?

   A. Greg is a type of animal.

In both cases, the answers are strictly correct, but in the second
case, the answer is also deeply misleading.

Q. How do we generally solve this problem when speaking?

A. We invent more specific terms and then generally stick to the more
specific terms when the more general terms would be misleading.

I.e.,

   Q. What is Greg?

   A. Greg is a human being.

and

   Q. What type of calling semantics do Python and Java use?

   A. Call-by-sharing.

I assert that anyone who does not understand all of the above, is
helping to spread confusion.

|>oug
--
http://mail.python.org/mailman/listinfo/python-list


Re: Quick nested loop syntax?

2008-11-19 Thread Terry Reedy

Johannes Bauer wrote:

Hi group,

if I remember correctly, wasn't there a way to quickly iterate through
nested loops? Something like

a = { "a", "b", "c" }
b = { 4, 9, 13}
for (x, y) in someoperator(a, b):
print(x, y)


from itertools import product
a = { "a", "b", "c" }
b = { 4, 9, 13}
for (x, y) in product(a, b):
print(x, y)

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


Re: wxPython BoxSizer

2008-11-19 Thread Jamie McQuay

>
> > FYI: There's a great wxPython mailing list too. Check it out 
> > here:http://wxpython.org/maillist.php
>
> thanks, i will take a look.

Here is the answer i got from the mailing list (and it works)

Try adding a spacer on both sides of text.

i.e)
box.AddStretchSpacer()
box.Add(myText, 0, wx.ALIGN_CENTER)
box.AddStretchSpacer()

jamie

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


Re: Finding the instance reference of an object

2008-11-19 Thread Joe Strout

On Nov 19, 2008, at 11:05 AM, Douglas Alan wrote:


Personally, I find this whole debate kind of silly, as it is based on
a completely fallacious either/or dichotomy.

(1) It is unarguably true that Python and Java use a type of
   call-by-value.  This follows from the standard definition of
   call-by-value, and common usage in, for example, the Scheme and
   Java communities, etc.


True.


(2) It is also unarguably true that saying that Python or Java use
   "call-by-value", and saying nothing more is going to be profoundly
   confusing to anyone who is learning these languages.


Perhaps (unless they've already learned this from one of the other  
languages).



Q. How do we generally solve this problem when speaking?

A. We invent more specific terms and then generally stick to the more
specific terms when the more general terms would be misleading.

I.e.,

  Q. What is Greg?

  A. Greg is a human being.

and

  Q. What type of calling semantics do Python and Java use?

  A. Call-by-sharing.


Fair enough, but if the questioner then says "WTF is call-by-sharing,"  
we should answer "call-by-sharing is the term we prefer for call-by- 
value in the case where the value is an object reference (as is always  
the case in Python)."



I assert that anyone who does not understand all of the above, is
helping to spread confusion.


I agree.

Best,
- Joe

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


Re: Quick nested loop syntax?

2008-11-19 Thread Vlastimil Brom
2008/11/19 Johannes Bauer <[EMAIL PROTECTED]>

> Hi group,
>
> if I remember correctly, wasn't there a way to quickly iterate through
> nested loops? Something like
>
> a = { "a", "b", "c" }
> b = { 4, 9, 13}
> for (x, y) in someoperator(a, b):
>print(x, y)
>
> which would print all tuples of
> "a", 4
> "a", 9
> "a", 13
> "b", 4
> "b", 9
> "b", 13
> "c", 4
> "c", 9
> "c", 13
>
> (not nececssarily in that order, of course).
>
> Thanks,
> Johannes
>
> --
>
If you are running the code in python 3, as suggested by the use of the set
literals, the mentioned itertools.product() is probably the straightforward
way.
Another possibility could be a nested generator expression (here using lists
- preserving the order):
>>> a = ["a", "b", "c"]
>>> b = [4, 9, 13]
>>> for item in ((ax, bx) for ax in a for bx in b): print item
...
('a', 4)
('a', 9)
('a', 13)
('b', 4)
('b', 9)
('b', 13)
('c', 4)
('c', 9)
('c', 13)
>>>
regards
   vbr
--
http://mail.python.org/mailman/listinfo/python-list


Re: wxPython BoxSizer

2008-11-19 Thread Mike Driscoll
On Nov 19, 12:22 pm, Jamie McQuay <[EMAIL PROTECTED]> wrote:
> > > FYI: There's a great wxPython mailing list too. Check it out 
> > > here:http://wxpython.org/maillist.php
>
> > thanks, i will take a look.
>
> Here is the answer i got from the mailing list (and it works)
>
> Try adding a spacer on both sides of text.
>
> i.e)
> box.AddStretchSpacer()
> box.Add(myText, 0, wx.ALIGN_CENTER)
> box.AddStretchSpacer()
>
> jamie

Yeah...I saw that on the wx list. I either had forgotten about that
method or never knew it existed. The wx.CENTER style should have
worked. Robin Dunn might explain it later. You can learn a lot from
the guys (and girls) on that list though.

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


Re: wxPython Crashes with basic example

2008-11-19 Thread Benjamin Kaplan
On Wed, Nov 19, 2008 at 12:51 PM, Samuel Morhaim
<[EMAIL PROTECTED]>wrote:

> Hi, I am trying to run the basic wxpython example as seen here
> http://www.zetcode.com/wxpython/firststeps/ and everytime i run it, it
> crashes python/wxpython .. meaning it doesnt close gracefully.
> The error I get is
>
> Problem signature:
>   Problem Event Name: APPCRASH
>   Application Name: pythonw.exe
>   Application Version: 0.0.0.0
>   Application Timestamp: 48e49638
>   Fault Module Name: comctl32.dll_unloaded
>   Fault Module Version: 0.0.0.0
>   Fault Module Timestamp: 4791a629
>   Exception Code: c005
>   Exception Offset: 72b35a6e
>   OS Version: 6.0.6001.2.1.0.256.1
>   Locale ID: 1033
>   Additional Information 1: fd00
>   Additional Information 2: ea6f5fe8924aaa756324d57f87834160
>   Additional Information 3: fd00
>   Additional Information 4: ea6f5fe8924aaa756324d57f87834160
>
> Read our privacy statement:
>   http://go.microsoft.com/fwlink/?linkid=50163&clcid=0x0409
>
>
>
> Any ideas? it is just a basic example..   running python 2.6, wxpython,
> executing via IDLE or eric or any other..
>


I don't have any idea what caused your problem since I don't use Windows,
but you shouldn't run wxPython apps from IDLE because of conflicting event
loops. I think you might also have problems with Eric. Try running the
script from the command line and see if that solves your problem.
--
http://mail.python.org/mailman/listinfo/python-list


GzipFile as a Context manager

2008-11-19 Thread Mikolai Fajer
Is there a reason that the gzip.GzipFile class does not have __enter__
and __exit__ methods that mimic those of the file object?  I expected
the following to work but it doesn't:

import gzip
with gzip.open('temp.gz', 'w') as fhandle:
gzip.write('Hello world.')

If there is no reason to avoid this behavior should I submit a bug
report and a subsequent patch?  Thanks!

-- 

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


Re: Avoiding local variable declarations?

2008-11-19 Thread Arnaud Delobelle
greg <[EMAIL PROTECTED]> writes:

> Arnaud Delobelle wrote:
>
>> Neutral element is correct.  But maybe its use is limited to
>> mathematicians in the english-speaking word.
>
> I've only ever seen "identity element" in English mathematics.
> "Neutral element" sounds like something my car's gearbox
> might have...

I was an academic mathematician for several years (although not a very
good one) and I can assure you that 'neutral element' is correct and
understood. 'Unit element' is another common synonym.

Unfortunately I can't find a reference in one of the few books in
English that I have at home.  Lang's "Algebra" does not seem to use the
term and it's the only undergraduate book I've got.  Wikipedia and other
internet sources cite 'neutral element' as a synonym to 'identity
element'.

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


calling python scripts as a sub-process

2008-11-19 Thread Catherine Moroney
I have one script (Match1) that calls a Fortran executable as a 
sub-process, and I want to write another script (Match4) that

spawns off several instances of Match1 in parallel and then waits
until they all finish running.  The only way I can think of doing this
is to call it as a sub-process, rather than directly.

I'm able to get Match1 working correctly in isolation, using the
subprocess.Popen command, but calling an instance of Match1 as a
subprocess spawned from Match4 isn't working.

The command (stored as an array of strings) that I'm executing is:

['python ../src_python/Match1.py ', 
'--file_ref=MISR_AM1_GRP_ELLIPSOID_GM_P228_O003571_BF_F03_0024.hdf ', 
'--file_cmp=MISR_AM1_GRP_ELLIPSOID_GM_P228_O003571_DF_F03_0024.hdf ', 
'--block_start=62 ', '--block_end=62 ', '--istep=16 ', "--chmetric='M2' 
", "--use_textid='true '"]


and I'm calling it as:

sub1 = subprocess.Popen(command)

I get the error below.  Does anybody know what this error refers
to and what I'm doing wrong?  Is it even allowable to call another
script as a sub-process rather than calling it directly?

 File "../src_python/Match4.py", line 24, in RunMatch4
sub1 = subprocess.Popen(command1)
  File "/usr/lib64/python2.5/subprocess.py", line 593, in __init__
errread, errwrite)
  File "/usr/lib64/python2.5/subprocess.py", line 1051, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory

Thanks for any help,

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


Re: Programming exercises/challenges

2008-11-19 Thread Stef Mientki

hi Ben,

[EMAIL PROTECTED] wrote:

Hi guys,

I'm learning Python by teaching myself, and after going through 
several tutorials I feel like I've learned the basics. Since I'm not 
taking a class or anything, I've been doing challenges/programs to 
reinforce the material and improve my skills. I started out with stuff 
like "Guess my number" games, hangman, etc. and moved on to making 
poker and card games to work with classes. For GUIs I created games 
like minesweeper, and a GUI stock portfolio tracker. I am out of ideas 
and am looking for programming projects, challenges, or programs that 
have helped you'll learn. I'm working on the project Euler problems, 
but I find that they don't really help my programming skills; they are 
more math focused. Suggestions? What has been useful or interesting to 
you? I'd also welcome sources of textbook type problems, because the 
ones provided in tutorials tend to be repetitive.


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


I'm working on an open source alternative for MatLab / LabView (math 
again ;-)

and there's still a lot to do
- (re-)design of the core engine (multi thread ?)
- implementation of webkit under wxPython
- integration of Scintilla and rpdb2
- Vpython integration under Linux / Mac (Windows works)
- something like Okular, but then platform independant
- integrating of data acquisition hardware, soundcard, National 
Instruments AD-converters, ...

here is a somewhat older version of my notes
 http://mientki.ruhosting.nl/data_www/pylab_works/pw_manual.pdf
all separate notes until now can be seen under the paragraph PyLab works 
here

 http://pic.flappie.nl


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


Re: calling python scripts as a sub-process

2008-11-19 Thread Philip Semanchuk


On Nov 19, 2008, at 2:03 PM, Catherine Moroney wrote:


The command (stored as an array of strings) that I'm executing is:

['python ../src_python/Match1.py ', '-- 
file_ref=MISR_AM1_GRP_ELLIPSOID_GM_P228_O003571_BF_F03_0024.hdf ',  
'--file_cmp=MISR_AM1_GRP_ELLIPSOID_GM_P228_O003571_DF_F03_0024.hdf  
', '--block_start=62 ', '--block_end=62 ', '--istep=16 ', "-- 
chmetric='M2' ", "--use_textid='true '"]




[snip]



I get the error below.  Does anybody know what this error refers
to and what I'm doing wrong?  Is it even allowable to call another
script as a sub-process rather than calling it directly?

File "../src_python/Match4.py", line 24, in RunMatch4
   sub1 = subprocess.Popen(command1)
 File "/usr/lib64/python2.5/subprocess.py", line 593, in __init__
   errread, errwrite)
 File "/usr/lib64/python2.5/subprocess.py", line 1051, in  
_execute_child

   raise child_exception
OSError: [Errno 2] No such file or directory


Try supplying a fully-qualified path to your script, e.g.:
['python /home/catherine/src_python/Match1.py ', '-- 
file_ref=MISR_AM1_GRP_ELLIPSOID_GM_P228_O003571_BF_F03_0024.hdf ', '-- 
file_cmp=MISR_AM1_GRP_ELLIPSOID_GM_P228_O003571_DF_F03_0024.hdf ', '-- 
block_start=62 ', '--block_end=62 ', '--istep=16 ', "--chmetric='M2'  
", "--use_textid='true '"]




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


Re: calling python scripts as a sub-process

2008-11-19 Thread Dan Upton
On Wed, Nov 19, 2008 at 2:13 PM, Philip Semanchuk <[EMAIL PROTECTED]> wrote:
>
> On Nov 19, 2008, at 2:03 PM, Catherine Moroney wrote:
>
>> The command (stored as an array of strings) that I'm executing is:
>>
>> ['python ../src_python/Match1.py ',
>> '--file_ref=MISR_AM1_GRP_ELLIPSOID_GM_P228_O003571_BF_F03_0024.hdf ',
>> '--file_cmp=MISR_AM1_GRP_ELLIPSOID_GM_P228_O003571_DF_F03_0024.hdf ',
>> '--block_start=62 ', '--block_end=62 ', '--istep=16 ', "--chmetric='M2' ",
>> "--use_textid='true '"]
>>
>
> [snip]
>
>>
>> I get the error below.  Does anybody know what this error refers
>> to and what I'm doing wrong?  Is it even allowable to call another
>> script as a sub-process rather than calling it directly?
>>
>> File "../src_python/Match4.py", line 24, in RunMatch4
>>   sub1 = subprocess.Popen(command1)
>>  File "/usr/lib64/python2.5/subprocess.py", line 593, in __init__
>>   errread, errwrite)
>>  File "/usr/lib64/python2.5/subprocess.py", line 1051, in _execute_child
>>   raise child_exception
>> OSError: [Errno 2] No such file or directory
>
> Try supplying a fully-qualified path to your script, e.g.:
> ['python /home/catherine/src_python/Match1.py ',
> '--file_ref=MISR_AM1_GRP_ELLIPSOID_GM_P228_O003571_BF_F03_0024.hdf ',
> '--file_cmp=MISR_AM1_GRP_ELLIPSOID_GM_P228_O003571_DF_F03_0024.hdf ',
> '--block_start=62 ', '--block_end=62 ', '--istep=16 ', "--chmetric='M2' ",
> "--use_textid='true '"]

I think when I came across this error, I added shell=True, e.g.

sub1 = subprocess.Popen(command, shell=True)
--
http://mail.python.org/mailman/listinfo/python-list


  1   2   >