Re: ImageFont family mojibake

2009-09-13 Thread Lie Ryan

Donn wrote:

On Saturday 12 September 2009 17:30:19 garabik-
news-2005...@kassiopeia.juls.savba.sk wrote:

apt-get install unicode
unicode 0100..

Nice tip, thanks.

if you see a lot of accented letters (and not squares or question marks), 
you can be sure
I see the accented chars -- so now I am more certain that the problem is in 
the font.family function. Something deep in the C code...


\d


Try testing with some of the supported encodings like:

print f.font.family.decode('utf-8')

try some of these encodings: 
http://docs.python.org/library/codecs.html#standard-encodings


The brute force should work if the font's name is encoded in one of the 
supported codecs; and if wx does not do something like 
f.[en|de]code(errors='replace').


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


Re: Which version of python I should use if I just start programming in python?

2009-09-13 Thread Kegan
I have just started using 2.6 (upgrade from 2.5). All my web
applications' code (using Django), work without any changes.
-- 
http://mail.python.org/mailman/listinfo/python-list


run exe on different computer

2009-09-13 Thread daved170
Hi everybody,
I'm building a small python program that run a service (exe file) on
my servers.
I don't want to use remote desktop and it's siblings.

I would like to have some information on how to run an exe on a
different computer and if there a way to check if that exe is still
alive.

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


Re: run exe on different computer

2009-09-13 Thread rootkit

Il 13/09/09 09.43, daved170 ha scritto:


Hi everybody,
I'm building a small python program that run a service (exe file) on
my servers.
I don't want to use remote desktop and it's siblings.

I would like to have some information on how to run an exe on a
different computer and if there a way to check if that exe is still
alive.


assuming windows as your target, look at this:
http://timgolden.me.uk/python/wmi.html

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


Re: Finite state machine in python

2009-09-13 Thread Banibrata Dutta
For simplistic FSMs, if you want to avoid hand-coding all the transitions,
actions etc., you could consider something like Libero (
http://www.cs.vu.nl/~eliens/documents/libero/lrintr.htm), although the last
I checked Libero didn't generate Python yet (but I believe there might be
similar options available with Python, though haven't come accross
anything). Machine generated FSMs can be suboptimal for many cases though.

On Sun, Sep 13, 2009 at 10:28 AM, CTO  wrote:

> On Sep 12, 4:39 pm, Peng Yu  wrote:
> > Hi,
> >
> > I have see some discussion on the implementation of finite state
> > machine in python. Can somebody point to me the best way in implenting
> > an FSM in python?
> >
> > http://code.activestate.com/recipes/146262/
> >
> > Regards,
> > Peng
>
> I wrote an example of how to do it using Graphine a while back.
> Probably not the most efficient in the world, but pretty easy
> to read, and it allows you to add and remove states and transitions
> easily.
>
> URL: http://gitorious.org/graphine/pages/GraphineForPythonistas
>
> Geremy Condra
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
regards,
Banibrata
http://www.linkedin.com/in/bdutta
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: CPU usage while reading a named pipe

2009-09-13 Thread Nick Craig-Wood
Miguel P  wrote:
>  On Sep 12, 2:54 pm, Ned Deily  wrote:
> > In article
> > ,
> >  Miguel P  wrote:
> > > I've been working on parsing (tailing) a named pipe which is the
> > > syslog output of the traffic for a rather busy haproxy instance. It's
> > > a fair bit of traffic (upto 3k hits/s per server), but I am finding
> > > that simply tailing the file  in python, without any processing, is
> > > taking up 15% of a CPU core. In contrast HAProxy takes 25% and syslogd
> > > takes 5% with the same load. `cat < /named.pipe` takes 0-2%
> >
> > > Am I just doing things horribly wrong or is this normal?
> >
> > > Here is my code:
> >
> > > from collections import deque
> > > import io, sys
> >
> > > WATCHED_PIPE = '/var/log/haproxy.pipe'
> >
> > > if __name__ == '__main__':
> > >     try:
> > >         log_pool = deque([],1)
> > >         fd = io.open(WATCHED_PIPE)
> > >         for line in fd:
> > >             log_pool.append(line)
> > >     except KeyboardInterrupt:
> > >         sys.exit()
> >
> > > Deque appends are O(1) so that's not it. And I am using 2.6's io
> > > module because it's supposed to handle named pipes better. I have
> > > commented the deque appending line and it still takes about the same
> > > CPU.
> >
> > Be aware that the io module in Python 2.6 is written in Python and was
> > viewed as a prototype.  In the current svn trunk, what will be Python
> > 2.7 has a much faster C implementation of the io module backported from
> > Python 3.1.
> 
>  Aha, I will test with trunk and see if the performance is better, if
>  so I'll use 2.6 in production until 2.7 comes out. I will report back
>  when I have made the tests.

Why don't you try just using the builtin open() with bufsize
parameter set big?

Something like this (tested with named pipes).  Tweak BUFFERSIZE and
SLEEP_INTERVAL for maximum performance!


import time

BUFFERSIZE = 1024*1024
SLEEP_INTERVAL = 0.1

def tail(path):
fd = open(path)
buf =  ""
while True:
buf += fd.read(BUFFERSIZE)
if buf:
lines = buf.splitlines(True)
for line in lines[:-1]:
yield line
buf = lines[-1]
if buf.endswith("\n"):
yield buf
buf = ""
else:
time.sleep(SLEEP_INTERVAL)


def main(path):
for line in tail(path):
print "%r:%r" % (len(line), line)

if __name__ == "__main__":
import sys
main(sys.argv[1])


-- 
Nick Craig-Wood  -- http://www.craig-wood.com/nick
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: is there a "strawberry python"?

2009-09-13 Thread Thorsten Kampe
* Daniel Fetchinson (Sat, 12 Sep 2009 12:54:03 -0700)
> 
> > the reason I like strawberry perl is that I don't need to have admin right
> > to install it. i can just unzip it and start the game.
> > i am wondering if there is something similar in python community.
> >
> > any insight will be appreciated!
> 
> As far as I remember there are python installations on USB sticks
> which you can run without any privileges.
> 
> http://www.portablepython.com/

Any Python runs without privileges. For some actions (like installing 
new packages) you need to have the appropriate keys in HKCU. But this is 
not required to run Python.

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


Re: Finite state machine in python

2009-09-13 Thread Hendrik van Rooyen
On Saturday 12 September 2009 22:39:10 Peng Yu wrote:
> Hi,
>
> I have see some discussion on the implementation of finite state
> machine in python. Can somebody point to me the best way in implenting
> an FSM in python?
>
> http://code.activestate.com/recipes/146262/

You can go a long way with a far simpler model than the one in that recipe:

1) Define a routine for every state.
2) Have every state do the following:
 (i) Run the code to make the side effects like outputs happen.
(ii) Scan the conditions for the state transitions relevant to this state.
  (Only the arrows leaving this state on the state diagram.)
(iii) Return the next state (either the same or a different state).

3) The main loop of a long running machine then looks like this:

next_state = start_state()

while True:
next_state = next_state()
time.sleep(step_time)   # if needed

This simple model is surprisingly powerful, and it can be expanded to run a 
bundle of such machines in parallel very easily, by keeping a list of 
next_states and continuously cycling through and updating the list.

You do not even need a dispatch dictionary.

This is about the simplest model for making FSMs that I know of.
Not sure if it is the "best" - best for what?.

- Hendrik

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


Re: How to define a function with an empty body?

2009-09-13 Thread Hendrik van Rooyen
On Sunday 13 September 2009 05:37:01 Peng Yu wrote:
> Hi,
>
> I want to define a function without anything in it body. In C++, I can
> do something like the following because I can use "{}" to denote an
> empty function body. Since python use indentation, I am not sure how
> to do it. Can somebody let me know how to do it in python?

def rubbish_do_nothing():
 pass

- Hendrik

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


Re: run exe on different computer

2009-09-13 Thread Dave Angel

daved170 wrote:

Hi everybody,
I'm building a small python program that run a service (exe file) on
my servers.
I don't want to use remote desktop and it's siblings.

I would like to have some information on how to run an exe on a
different computer and if there a way to check if that exe is still
alive.

Thanks
Dave

  
On a question like this, you really need to supply much more information 
on your constraints.  You could start by saying these servers are 
running Windows Server 2003.  And that they're on a domain (rather than 
a workgroup).  And that you're trying to access them from another 
machine within the same local domain, not over the internet.  And that 
your local machine is on the same domain, and has an account with admin 
privileges for all the desired servers.  And that you are allowed to do 
a one-time install (of something) on each server prior to this 
particular need.  And that each server already has Python version 2.5 
installed, and the IT department won't allow you to install any later 
version.


Then once you have an environment, you need to specify just what kind of 
program you want to run on those servers.  Is it an EXE program?  Or is 
it Python, with a particular script?  Does it really need to be a 
*service*, which has a particular set of constraints, and should be 
installed, and started/stopped using the service manager.  Do you want 
this program to restart whenever the servers are restarted?


One solution that should work for nearly every Windows topology might be 
to go to each server, run the scheduler task, and specify a new batch 
file to be run upon boot.  This batch file can check a specified 
(shared) directory for a python script, and if found, run it.  If not 
found, sleep for 60 seconds or so, then repeat.  Note that it's a good 
idea to put a five minute delay at the very beginning, in case the 
script needs to be deleted at the next boot.  Sometimes a bug requires 
surgery, and it's good to have enough time to do it.


Now, to control those servers from another machine, copy an appropriate 
script into the prearranged directory.  Within a minute, it'll be 
running, and it can post whatever results it likes in another accessible 
directory.



Whether this is a "safe" thing to do is a separate question.  Generally 
an IT department likes to have some control over just what programs run 
on their servers, and for good reason.



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


Re: IDE for python similar to visual basic

2009-09-13 Thread Nobody
On Fri, 11 Sep 2009 05:27:59 -0700, r wrote:

>> I'm saying that the user understands their workflow and environment better
>> than the application's programmers. The user should be able to decide
>> which menu items are shown and where, which buttons are shown and where,
>> etc. The code doesn't need to know this level of detail, let alone dictate
>> it.
> 
> I completely disagree with this idea of user "customization" of the
> GUI. Sounds more like adolescent accessorizing to me. How is changing
> the location of a button, or entry, or whatever, actually going to
> make workflow more easier?

For a start, removing any buttons which the user won't be needing
eliminates the risk of them clicking on them by accident.

Beyond that, there is an advantage to placing buttons (etc) in similar
locations to other applications which the user uses (or was using prior
to migrating).

In some cases, the reduction in mouse motion which can be obtained by
placing specific buttons close together can make significant difference.

Sometimes those buttons aren't all part of the same application (I know of
people who place the Windows taskbar at the top of the screen simply
because it's closer to most applications' toolbar and menubar). If you
have two windows side-by-side, there's a benefit to having the left-hand
window's controls running down its right-hand edge and vice-versa, so both
sets of controls are all in one cluster.

For mouse-centric applications, keyboard shortcuts aren't always
a solution; particularly for left-handed users, as shortcuts are normally
optimised for right-handed users (i.e. common shortcuts use the LHS of the
keyboard, on the assumption that the right hand is on the mouse).

> Sounds like "somebody" failed to get input
> from their users at design time. Or "somebody" has the inability to
> relate to their end users.

You're assuming that there is some "right" answer which is appropriate for
all users. There isn't.

> Would a mechanic give you a screw driver so you could adjust the fuel/
> air ratio yourself? If he did i would never take my car back again!
> Just reeks of incompetence!!

If the manufacturer took your approach, there wouldn't be any screw. Just
a fixed setting for all climates and altitudes, urban and rural, flat
and hilly.

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


Distributing Python environment

2009-09-13 Thread Ecir Hana
Hello,
I have an app which I would like to extend with Python. I I saw how to
embed the interpreter into C. If I bundle my app with the Python lib
(say, python26.dll) I can PyRun_SimpleString() some code. My question
is, how do I bundle the rest of the libraries (site, os, elementtree,
random, ...)? Is it possible to make one huge (ok, not so huge) .zip
blob containing all of the libraries? And what happens if some user
has Python already installed? Which libraries get loaded first? Is it
possible to alter this order? I mean, first check for local Python
install and if the user doesn't have Python installation use the
bundled one?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: run exe on different computer

2009-09-13 Thread daved170
On Sep 13, 2:17 pm, Dave Angel  wrote:
> daved170 wrote:
> > Hi everybody,
> > I'm building a small python program that run a service (exe file) on
> > my servers.
> > I don't want to use remote desktop and it's siblings.
>
> > I would like to have some information on how to run an exe on a
> > different computer and if there a way to check if that exe is still
> > alive.
>
> > Thanks
> > Dave
>
> On a question like this, you really need to supply much more information
> on your constraints.  You could start by saying these servers are
> running Windows Server 2003.  And that they're on a domain (rather than
> a workgroup).  And that you're trying to access them from another
> machine within the same local domain, not over the internet.  And that
> your local machine is on the same domain, and has an account with admin
> privileges for all the desired servers.  And that you are allowed to do
> a one-time install (of something) on each server prior to this
> particular need.  And that each server already has Python version 2.5
> installed, and the IT department won't allow you to install any later
> version.
>
> Then once you have an environment, you need to specify just what kind of
> program you want to run on those servers.  Is it an EXE program?  Or is
> it Python, with a particular script?  Does it really need to be a
> *service*, which has a particular set of constraints, and should be
> installed, and started/stopped using the service manager.  Do you want
> this program to restart whenever the servers are restarted?
>
> One solution that should work for nearly every Windows topology might be
> to go to each server, run the scheduler task, and specify a new batch
> file to be run upon boot.  This batch file can check a specified
> (shared) directory for a python script, and if found, run it.  If not
> found, sleep for 60 seconds or so, then repeat.  Note that it's a good
> idea to put a five minute delay at the very beginning, in case the
> script needs to be deleted at the next boot.  Sometimes a bug requires
> surgery, and it's good to have enough time to do it.
>
> Now, to control those servers from another machine, copy an appropriate
> script into the prearranged directory.  Within a minute, it'll be
> running, and it can post whatever results it likes in another accessible
> directory.
>
> Whether this is a "safe" thing to do is a separate question.  Generally
> an IT department likes to have some control over just what programs run
> on their servers, and for good reason.
>
> DaveA

Hi DaveA
Thanks for your answer. I'll try to clearify myself.
For now I'm trying to do that on client & server that are win XP. They
both on the same domain (maybe in the future they'll be runinig on the
web). I have admin user on both my computers.
I have both an exe and a python app that I'd like to control from my
client.
Insted of logging to my Server I would like to write a python app at
my client that allows me to control both that exe and my Server-python-
app. I don't want to use the schedualer because I would like to
control it from my client.
I can install whatever I'll like on both of the computers. they are
mine and I have full access for them.
I hope I clearify myself and if there are more solutions I'll be happy
to be noted.
Thans
DaveD :)
-- 
http://mail.python.org/mailman/listinfo/python-list


PyQT child forms

2009-09-13 Thread daved170
Hi everybody,
I'm building my GUI app with PyQT and i'm quite new with it.
I looked for example for managing a form and a child form.
My goal is to run the main form and a certain button will open a child
form. Whenever the child form will be open the main form will be
disabled until the child form is closed.
Moreover I would like to know how to pass data from the child form to
the main form.
Thank you very much
DaveD
-- 
http://mail.python.org/mailman/listinfo/python-list


Python and 3d

2009-09-13 Thread azrael
Has anyone any exipience with python and 3d.

I mean, is there a module to deal with popular 3d formats like 3ds, or
vrml. is it possible to import into python opengl models and then use
it in application for GUI purposes like through WX. I know that WX
supports OpenGL but how to import models from file.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Which version of python I should use if I just start programming in python?

2009-09-13 Thread Steven D'Aprano
On Sat, 12 Sep 2009 20:25:47 -0700, Kee Nethery wrote:

> I would prefer to be in 3.x because all the inconsistencies of how you
> do things in 2.x make it harder than it needs to be to learn the
> language.
> 
> People who have been coding in 2.x for along time don't notice how the
> syntax is wonky in places. Their fingers type the right stuff. As a
> newbie I assume that everything works the same way and I am frequently
> surprised.

What inconsistencies surprise you?



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


Re: How to define a function with an empty body?

2009-09-13 Thread Christian Heimes
Peng Yu schrieb:
> Hi,
> 
> I want to define a function without anything in it body. In C++, I can
> do something like the following because I can use "{}" to denote an
> empty function body. Since python use indentation, I am not sure how
> to do it. Can somebody let me know how to do it in python?

Python has two possibilities to create an empty function. The others
already told you aber the pass statement. The other way is a function
with a doc string

def func():
"""No op function
"""

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


Re: How to define a function with an empty body?

2009-09-13 Thread Albert Hopkins
On Sat, 2009-09-12 at 22:37 -0500, Peng Yu wrote:
> Hi,
> 
> I want to define a function without anything in it body. In C++, I can
> do something like the following because I can use "{}" to denote an
> empty function body. Since python use indentation, I am not sure how
> to do it. Can somebody let me know how to do it in python?
> 
> void f() {
> }
> 

Surprised no one has mentioned this yet, but since it's a function, and
in python all functions return values (whether explicitly or implicitly,
a simple "return" works and, to me, does much more to inform the reader
that "this function does nothing".

def f():
return


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


Array of objects lost in unpickling

2009-09-13 Thread Bahadir
Hi,

I have a class:

class second:
a = None
b = None

class first:
array = []

I populate the array in first class with instances of second, then
save by:

shelve = shelve.open(),
shelve["first"] = myfirst
shelve.close()

When I reopen the shelve from another script, the first class is
there, but array has no elements. If I reopen the shelve in the same
script right after shelve.close(), the elements are there.

Also there are no errors printed out.

Any idea why the array of instances are lost?

Thanks,

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


Re: Array of objects lost in unpickling

2009-09-13 Thread Jon Clements
On 13 Sep, 15:19, Bahadir  wrote:
> Hi,
>
> I have a class:
>
> class second:
>     a = None
>     b = None
>
> class first:
>     array = []
>
> I populate the array in first class with instances of second, then
> save by:
>
> shelve = shelve.open(),
> shelve["first"] = myfirst
> shelve.close()
>
> When I reopen the shelve from another script, the first class is
> there, but array has no elements. If I reopen the shelve in the same
> script right after shelve.close(), the elements are there.
>
> Also there are no errors printed out.
>
> Any idea why the array of instances are lost?
>
> Thanks,
>
> Bahadir

You most likely want 'array' to be an instance level and not class
level attribute.

class first(object):
def __init__(self):
self.array = []

myfirst = first()
myfirst.array.append(23423)

etc...

hth,
Jon.

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


Re: Array of objects lost in unpickling

2009-09-13 Thread Christian Heimes
Bahadir wrote:
> Also there are no errors printed out.
> 
> Any idea why the array of instances are lost?
> 

The pickle protocol doesn't pickle class attributes by default, only
instance variables. You list called 'array' is a class variable -- it's
bound to the class not your instance.

By the way it's called a list in Python, not array.

Christian

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


Re: Array of objects lost in unpickling

2009-09-13 Thread Bahadir
On Sep 13, 5:48 pm, Jon Clements  wrote:
> On 13 Sep, 15:19, Bahadir  wrote:
>
>
>
> > Hi,
>
> > I have a class:
>
> > class second:
> >     a = None
> >     b = None
>
> > class first:
> >     array = []
>
> > I populate the array in first class with instances of second, then
> > save by:
>
> > shelve = shelve.open(),
> > shelve["first"] = myfirst
> > shelve.close()
>
> > When I reopen the shelve from another script, the first class is
> > there, but array has no elements. If I reopen the shelve in the same
> > script right after shelve.close(), the elements are there.
>
> > Also there are no errors printed out.
>
> > Any idea why the array of instances are lost?
>
> > Thanks,
>
> > Bahadir
>
> You most likely want 'array' to be an instance level and not class
> level attribute.
>
> class first(object):
>     def __init__(self):
>         self.array = []
>
> myfirst = first()
> myfirst.array.append(23423)
>
> etc...
>
> hth,
> Jon.

Hmm, OK. New to python. Got it. Thanks a lot!

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


Re: How to define a function with an empty body?

2009-09-13 Thread David
Il Sat, 12 Sep 2009 22:37:01 -0500, Peng Yu ha scritto:

> Hi,
> 
> I want to define a function without anything in it body. 
[...]

I usually define void functions as:

def myfunction():
raise NotImplementedError("You forgot to implement me!")


so I keep safe from leaving orphaned functions all over my code.
-- 
http://mail.python.org/mailman/listinfo/python-list


compiling python 3

2009-09-13 Thread Rustom Mody
Just managed to compile python3 on debian lenny
I get (among other things)

7 skips unexpected on linux2:
test_dbm_ndbm test_bz2 test_ttk_guionly test_tcl test_tk
test_ttk_textonly test_dbm_gnu
Any ideas what dev packages I need to add?

Also emacs python-mode is not set for python3 it looks I get the foll when I
try to load a file into python in emacs

Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'execfile' is not defined
>>>
-- 
http://mail.python.org/mailman/listinfo/python-list


Python strict mode?

2009-09-13 Thread Peng Yu
Hi,

Is there is a way to make python check the variables just as the
strict mode in perl. Would somebody let me know what is the python
equivalent to the perl strict mode?

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


Re: Python and 3d

2009-09-13 Thread TerryP
Importing models from a file, obviously always raises the question,
what kind of model formats :-P.

You should probably take a look at something like Python-Ogre or
Pygame for a starting point. Doing raw OpenGL is a bit more tricky and
even more dependent on format.


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


Re: Python and 3d

2009-09-13 Thread Mike C. Fletcher
azrael wrote:
> Has anyone any exipience with python and 3d.
>
> I mean, is there a module to deal with popular 3d formats like 3ds, or
> vrml. is it possible to import into python opengl models and then use
> it in application for GUI purposes like through WX. I know that WX
> supports OpenGL but how to import models from file.
>   
http://www.vrplumber.com/py3d.py

There's a few older projects to load 3DS files, but I don't think any of
them is currently PyOpenGL 3.x compatible.  OpenGLContext loads VRML97
files (with SimpleParse installed).  Pyglet, OpenGLContext and Ian
Mallet's game engine all load .obj models (I believe Ian's engine is the
most advanced there).  Pivy should load VRML files as well, and has a
very powerful engine (COIN) under the covers (OpenGLContext is more of a
demo/testing system).  The big engines (Ogre, Soya, OpenSceneGraph,
Crystal Space, etc) should all have content loaders, though I haven't
played with them enough to be able to say what formats they support.

HTH,
Mike

-- 

  Mike C. Fletcher
  Designer, VR Plumber, Coder
  http://www.vrplumber.com
  http://blog.vrplumber.com

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


Re: compiling python 3

2009-09-13 Thread Christian Heimes
Rustom Mody wrote:
> Just managed to compile python3 on debian lenny
> I get (among other things)
> 
> 7 skips unexpected on linux2:
> test_dbm_ndbm test_bz2 test_ttk_guionly test_tcl test_tk
> test_ttk_textonly test_dbm_gnu
> Any ideas what dev packages I need to add?

"apt-get build-dep python2.5" should install all required build
dependencies. Have fun!

Christian

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


AttributeError: 'NoneType' object has no attribute 'get_text'

2009-09-13 Thread Raji Seetharaman
Hi all,
i did a small gui addressbook application using pygtk, python, mysql db. It
was successful.
I tried the same application with glade. But i ended up with errors.
I desgined the code as follows.
1.It has one main window and four child dialogs.
2.In the main window, i have to fill in the text entry widget & if i press
'add', the data will get inserted into the database.This works fine.
3. If showdialog button is clicked, a child dialog appears, where i have to
enter old entry to update.
4. To update, i again use the main window, where i get the following error
  Traceback (most recent call last):
  File "addressbookglade.py", line 63, in update
self.ssn = self.wTree.get_widget("ssn"). get_text()
AttributeError: 'NoneType' object has no attribute 'get_text'

Also i already set the name in properties window.  It works fine for add
option. But not for update option.
Im using the same window for both add and update.

The code is available here http://pastebin.com/m28a4747e
The glade xml file is here http://pastebin.com/m1af61a29
The screenshot of my glade windows are here
http://www.flickr.com/photos/raji_me/?saved=1
 It works fine for add option. But not for update option. Im using the same
window for both add and update.

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


Re: Python and 3d

2009-09-13 Thread Ian Mallett
On Sun, Sep 13, 2009 at 9:29 AM, Mike C. Fletcher wrote:

> There's a few older projects to load 3DS files, but I don't think any of
> them is currently PyOpenGL 3.x compatible.

I would be interested in making them 3.x compatible.   Where are they?  I've
wanted .3ds support for a while...

> OpenGLContext loads VRML97
> files (with SimpleParse installed).  Pyglet, OpenGLContext and Ian
> Mallet's game engine all load .obj models (I believe Ian's engine is the
> most advanced there).

"Mallett" :-)
My .obj loader is actually a version of
http://www.pygame.org/wiki/OBJFileLoader?parent=CookBook, which is
excellent, tweaked to return the actual data (for VBOs, texture object
modification, etc.) and provide stuff like signed tangents for various
effects.  Likewise cannibalizing existing .3ds code would be nice...  I also
have a loader for .raw objects, but that was far simpler.  Like a LOT
simpler.  I can help you with getting stuff set up if that's what you were
asking (I didn't receive the original email, so)
Ian
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: First release of pyfsevents

2009-09-13 Thread Aahz
In article <04180ce5-4cc0-43a4-b26a-b7a4fe826...@g23g2000yqh.googlegroups.com>,
IngoognI   wrote:
>On Sep 8, 6:19=A0am, a...@pythoncraft.com (Aahz) wrote:
>>
>> There's no direct equivalent to Linux inotify [...]
>
>pnotify ?

Thanks!  I'll look into that.
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

"It's 106 miles to Chicago.  We have a full tank of gas, a half-pack of
cigarettes, it's dark, and we're wearing sunglasses."  "Hit it."
-- 
http://mail.python.org/mailman/listinfo/python-list


Is there a similar mailing list about django?

2009-09-13 Thread Joel Goldstick
I'm learning python and django more or less concurrently.  I've googled 
to find a similar list like this for django.  Help?


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


Re: AttributeError: 'NoneType' object has no attribute 'get_text'

2009-09-13 Thread MRAB

Raji Seetharaman wrote:

Hi all,
i did a small gui addressbook application using pygtk, python, mysql db. 
It was successful.

I tried the same application with glade. But i ended up with errors.
I desgined the code as follows.
1.It has one main window and four child dialogs.
2.In the main window, i have to fill in the text entry widget & if i 
press 'add', the data will get inserted into the database.This works fine.
3. If showdialog button is clicked, a child dialog appears, where i have 
to enter old entry to update.

4. To update, i again use the main window, where i get the following error
  Traceback (most recent call last):
  File "addressbookglade.py", line 63, in update
self.ssn = self.wTree.get_widget("ssn").
get_text()
AttributeError: 'NoneType' object has no attribute 'get_text'

Also i already set the name in properties window.  It works fine for add 
option. But not for update option.

Im using the same window for both add and update.

The code is available here http://pastebin.com/m28a4747e
The glade xml file is here http://pastebin.com/m1af61a29
The screenshot of my glade windows are here 
http://www.flickr.com/photos/raji_me/?saved=1
 It works fine for add option. But not for update option. Im using the 
same window for both add and update.



You're using instance attributes a lot where I think local variables
would be better, eg "self.ssn" instead of just "ssn".

In the '__init__' method you have:

self.wTree = gtk.glade.XML(self.gladefile,"mainWindow")

and then in the 'view' method you have:

self.wTree = gtk.glade.XML(self.gladefile,"viewdialog")

In both the 'add' and 'update' methods you have:

self.ssn = self.wTree.get_widget("ssn").get_text()

so I suspect that the following is happening:

1. __init__ makes self.wTree refer to 'mainWindow';

2. You click on the Add button, the 'add' method is called, and the 
"self.ssn = " line looks for the "ssn" widget in 'mainWindow';


3. You click on the OK(?) button and view what's just been added;

4. The 'view' method makes self.wTree refer to 'viewdialog';

5. You click on the Update button, the 'update' method is called, and 
the "self.ssn = " line looks for the "ssn" widget in 'viewdialog'.

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


including constants

2009-09-13 Thread Nikola Skoric
Hi there,

I have a simple problem and I know how to solve it :-D, but I suspect that
there is a standard solution which is more elegant.

So, here is my problem: I have django app versioned with svn and I
test my trunk on two different machines (one with mysql, another with
sqlite3). How do I remove database-definition constants from my
settings.py and put them in a separate file which wouldn't be
maintained by svn? (did I really hear somebody call that kind of file
"unversioned file" or did I make that up?) I suppose I could make a
trivial module with database info, import it and then assign my
constants with data from that module, but that looks so unelegant to
me. What's the standard way of doing this?

Thanks in advance.

-- 
"Now the storm has passed over me
I'm left to drift on a dead calm sea
And watch her forever through the cracks in the beams
Nailed across the doorways of the bedrooms of my dreams"
-- 
http://mail.python.org/mailman/listinfo/python-list


QTableWidgetItem-list

2009-09-13 Thread Helvin
Hi,

Could not find anything on this online, except the documentation,
which does not explain how to work with a QTableWidgetItem-list. How
do I get out what QWidgetTable.finditems found?

I have a string that I want to find in my table. I want to locate the
row it's in, then delete the row.
My code:

foundList = 
table_points.findItems(str(picked_node),
QtCore.Qt.MatchExactly)
inRow = 
self.ui.table_points.column(foundList)  # trying to
locate the row, but this does not work

where,
table_points: my table
picked_node:  an integer value I want to locate in table_points


Help MUCH appreciated!
Helvin
Newbie
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: QTableWidgetItem-list

2009-09-13 Thread Helvin
On Sep 14, 7:18 am, Helvin  wrote:
> Hi,
>
> Could not find anything on this online, except the documentation,
> which does not explain how to work with a QTableWidgetItem-list. How
> do I get out what QWidgetTable.finditems found?
>
> I have a string that I want to find in my table. I want to locate the
> row it's in, then delete the row.
> My code:
>
>                                         foundList = 
> table_points.findItems(str(picked_node),
> QtCore.Qt.MatchExactly)
>                                         inRow = 
> self.ui.table_points.column(foundList)  # trying to
> locate the row, but this does not work
>
> where,
>     table_points: my table
>     picked_node:  an integer value I want to locate in table_points
>
> Help MUCH appreciated!
> Helvin
> Newbie

Sorry, forgot to mention I am using PyQT.

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


Python and 3d

2009-09-13 Thread Ryniek90

>
> azrael wrote:
>   
>> Has anyone any exipience with python and 3d.
>>
>> I mean, is there a module to deal with popular 3d formats like 3ds, or
>> vrml. is it possible to import into python opengl models and then use
>> it in application for GUI purposes like through WX. I know that WX
>> supports OpenGL but how to import models from file.
>>   
>> 
> http://www.vrplumber.com/py3d.py
>
> There's a few older projects to load 3DS files, but I don't think any of
> them is currently PyOpenGL 3.x compatible.  OpenGLContext loads VRML97
> files (with SimpleParse installed).  Pyglet, OpenGLContext and Ian
> Mallet's game engine all load .obj models (I believe Ian's engine is the
> most advanced there).  Pivy should load VRML files as well, and has a
> very powerful engine (COIN) under the covers (OpenGLContext is more of a
> demo/testing system).  The big engines (Ogre, Soya, OpenSceneGraph,
> Crystal Space, etc) should all have content loaders, though I haven't
> played with them enough to be able to say what formats they support.
>
> HTH,
> Mike
>
>   

Maybe check out:

- Panda3D ( http://www.panda3d.org/ ),
- PyGame ( http://www.pygame.org/news.html ),
- PyKyra ( http://www.alobbs.com/pykyra ),
- PyOpenGL ( http://pyopengl.sourceforge.net/ ),

or

Blender ( http://www.blender.org/ ).

All above deserve attention.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: including constants

2009-09-13 Thread Andreas Waldenburger
On Sun, 13 Sep 2009 18:44:25 + (UTC) Nikola Skoric
 wrote:

> Hi there,
> 
> I have a simple problem and I know how to solve it :-D, but I suspect
> that there is a standard solution which is more elegant.
> 
> So, here is my problem: I have django app versioned with svn and I
> test my trunk on two different machines (one with mysql, another with
> sqlite3). How do I remove database-definition constants from my
> settings.py and put them in a separate file which wouldn't be
> maintained by svn? (did I really hear somebody call that kind of file
> "unversioned file" or did I make that up?) I suppose I could make a
> trivial module with database info, import it and then assign my
> constants with data from that module, but that looks so unelegant to
> me. What's the standard way of doing this?
> 
> Thanks in advance.
> 

The basic principle seems alright, but since you're talking about
configuration, you could use the ConfigParser module from the stdlib to
create real configuration files. That's what I would do for any
reasonably sized project.

/W

-- 
INVALID? DE!

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


Re: Python strict mode?

2009-09-13 Thread Andreas Waldenburger
On Sun, 13 Sep 2009 09:25:50 -0700 (PDT) Peng Yu 
wrote:

> Is there is a way to make python check the variables just as the
> strict mode in perl.
Short answer: No.

Long answer: I'm guessing you want Python to complain when assigning to
a variable that has not been declared before. Since Python has no
declarations, you're plain out of luck.


> Would somebody let me know what is the python equivalent to the
> perl strict mode?
> 
I don't know about any equivalents (but I wouldn't be surprised if
there were libraries for that somewhere).

You could write a class with a custom __setattr__() method that checks
for valid attribute names for that class (a list of strings given to
it's __init__() method). That way you could form several restricted
"namespaces" for variables simply as different instances of that class.

But in my opinion, it isn't worth it. You still don't get compile time
errors, which is probably the main reason to use strict mode.

Can you describe why you (think you) need this? Maybe there is a
more pythonic approach.

/W

-- 
INVALID? DE!

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


Re: Is there a similar mailing list about django?

2009-09-13 Thread Andreas Waldenburger
On Sun, 13 Sep 2009 14:17:42 -0400 Joel Goldstick
 wrote:

> I'm learning python and django more or less concurrently.  I've
> googled to find a similar list like this for django.  Help?
> 
Didn't like http://groups-beta.google.com/group/django-users ?

(Second hit for "django mailing list", but I know Google results vary
from country to country, so you might not have seen it.)

/W

-- 
INVALID? DE!

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


Re: Is there a similar mailing list about django?

2009-09-13 Thread Albert Hopkins
On Sun, 2009-09-13 at 21:27 +0200, Andreas Waldenburger wrote:
> Didn't like http://groups-beta.google.com/group/django-users ?
> 
> (Second hit for "django mailing list", but I know Google results vary
> from country to country, so you might not have seen it.)

Or, better yet, go to Django's web site (djangoproject.org) and click on
"Community" at the top of the page.

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


IRC bot

2009-09-13 Thread Someone Something
I"m trying to write an IRC bot just for fun (in python of course). Here's my
current code:

  1 #!/usr/local/bin/python
  2 import time
  3 import socket
  4
  5 def message (x, channel,s):
  6 y="PRIVMSG"+" "+ channel+" :"+x
  7 s.send(y);
  8 host="irc.freenode.net";
  9 port=6667;
 10 size=1024;
 11 channel="#dhaivatrocks";
 12 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM);
 13 s.connect((host,port));
 14 s.send("NICK PoincareBot");
 15 s.send("USER  PoincareBot 8 *  : Paul Mutton");
 16 time.sleep(5);
 17 s.send("JOIN #dhaivatrocks");
 18 s.send(PRIVMSG #dhaivatrocks :Hello everybody!
 19 while True:
 20 pass;
 21
What I don't understand is that it doesn't display any messages or show a
new message login on my IRC client. What's wrong with my code?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python strict mode?

2009-09-13 Thread Patrick Sabin

 > You could write a class with a custom __setattr__() method that checks

for valid attribute names for that class (a list of strings given to
it's __init__() method). That way you could form several restricted
"namespaces" for variables simply as different instances of that class.



This can be easier accomplished using __slots__, e.g.:

>>> class X(object):
... __slots__ = ['a']


But in my opinion, it isn't worth it. You still don't get compile time
errors, which is probably the main reason to use strict mode.


I agree.

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


numpy NaN, not surviving pickle/unpickle?

2009-09-13 Thread John Ladasky
Hi folks,

I am aware that numpy has its own discussion group, which is hosted at
gmane.  Unfortunately, I can't seem to get in to gmane today.

In any case, I'm not sure whether I have a problem with numpy, or with
my understanding of the Python pickle module, so I'm posting here.

I am pickling numpy.ndarray objects to disk which are of type "float",
but which may include NaN in some cells.  When I unpickle these
objects and then test for the presence of NaN, the test fails.  Here's
a minimal sample program, and its output:


=== program 


## numpy nan pickle test.py

import pickle
from numpy import *

print "\n\nNaN equivalency tests:\n"
x, y = nan, NaN  # Capitalization reality check
print "x =", x, ", y =", y
print "x is nan:", x is nan
print "y is NaN:", y is NaN
print "x is y:", x is y

A0 = array([[1.2, nan], [3.4, 5.6]])
print "\n\nPickling and saving this array to disk:\n\n", A0
f0 = open("test array pickle.py", "w")
pickle.dump(A0, f0)
f0.close()
print "\nArray saved to disk."

f1 = open("test array pickle.py", "r")
A1 = pickle.load(f1)
f1.close()
print "\n\nThe array reloaded from the disk is:\n\n", A1
print "\narray[0,1] =", A1[0,1]
print "array[0,1] is nan:", A1[0,1] is nan, "\n\n"


=== output 


NaN equivalency tests:

x = nan , y = nan
x is nan: True
y is NaN: True
x is y: True


Pickling and saving this array to disk:

[[ 1.2  NaN]
 [ 3.4  5.6]]

Array saved to disk.


The array reloaded from the disk is:

[[ 1.2  NaN]
 [ 3.4  5.6]]

array[0,1] = nan
array[0,1] is nan: False





The last line of my output is unexpected.  I've printed the contents
of the cell in the array, and it says that it contains "nan".  But
when I try the same equivalency test that I tried in the first few
lines of the program (with unpickled objects), this time it says that
my test object isn't "nan".

I thought that Python was supposed to make values and even objects
portable?


Obligatory version information:

Numpy: 1.0.4
Python: 2.5.2
OS: Ubuntu Linux 8.04


Thanks for any help!

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


Re: IRC bot

2009-09-13 Thread Someone Something
Anyone?

On Sun, Sep 13, 2009 at 3:58 PM, Someone Something wrote:

> I"m trying to write an IRC bot just for fun (in python of course). Here's
> my current code:
>
>   1 #!/usr/local/bin/python
>   2 import time
>   3 import socket
>   4
>   5 def message (x, channel,s):
>   6 y="PRIVMSG"+" "+ channel+" :"+x
>   7 s.send(y);
>   8 host="irc.freenode.net";
>   9 port=6667;
>  10 size=1024;
>  11 channel="#dhaivatrocks";
>  12 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM);
>  13 s.connect((host,port));
>  14 s.send("NICK PoincareBot");
>  15 s.send("USER  PoincareBot 8 *  : Paul Mutton");
>  16 time.sleep(5);
>  17 s.send("JOIN #dhaivatrocks");
>  18 s.send(PRIVMSG #dhaivatrocks :Hello everybody!
>  19 while True:
>  20 pass;
>  21
> What I don't understand is that it doesn't display any messages or show a
> new message login on my IRC client. What's wrong with my code?
>
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: numpy NaN, not surviving pickle/unpickle?

2009-09-13 Thread Robert Kern

John Ladasky wrote:

Hi folks,

I am aware that numpy has its own discussion group, which is hosted at
gmane.  Unfortunately, I can't seem to get in to gmane today.


It is not hosted at GMane. It just has a GMane mirror.

  http://www.scipy.org/Mailing_Lists


In any case, I'm not sure whether I have a problem with numpy, or with
my understanding of the Python pickle module, so I'm posting here.

I am pickling numpy.ndarray objects to disk which are of type "float",
but which may include NaN in some cells.  When I unpickle these
objects and then test for the presence of NaN, the test fails.


The problem is that you are trying to use "is" to compare by Python object 
identity. Except for dtype=object arrays, the object identities of the 
individual elements that you extract from numpy arrays are never guaranteed. 
Usually, they will always be different. You need to use numpy.isnan() to 
determine whether an object is a NaN.


--
Robert Kern

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

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


Re: IRC bot

2009-09-13 Thread MRAB

Someone Something wrote:
I"m trying to write an IRC bot just for fun (in python of course). 
Here's my current code:


  1 #!/usr/local/bin/python
  2 import time
  3 import socket
  4
  5 def message (x, channel,s):
  6 y="PRIVMSG"+" "+ channel+" :"+x
  7 s.send(y);
  8 host="irc.freenode.net ";
  9 port=6667;
 10 size=1024;
 11 channel="#dhaivatrocks";
 12 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM);
 13 s.connect((host,port));
 14 s.send("NICK PoincareBot");
 15 s.send("USER  PoincareBot 8 *  : Paul Mutton");
 16 time.sleep(5);
 17 s.send("JOIN #dhaivatrocks");
 18 s.send(PRIVMSG #dhaivatrocks :Hello everybody!
 19 while True:
 20 pass;
 21
What I don't understand is that it doesn't display any messages or show 
a new message login on my IRC client. What's wrong with my code? 


You probably need to put some sort of line ending on what you send, eg
"\n" or "\r\n". Also, it's better to use 'sendall' insetad of 'send'.

BTW, you don't need to put a semicolon on the end of the lines.
--
http://mail.python.org/mailman/listinfo/python-list


Re: IRC bot

2009-09-13 Thread Someone Something
Thanks a lot!

On Sun, Sep 13, 2009 at 4:29 PM, MRAB  wrote:

> Someone Something wrote:
>
>> I"m trying to write an IRC bot just for fun (in python of course). Here's
>> my current code:
>>
>>  1 #!/usr/local/bin/python
>>  2 import time
>>  3 import socket
>>  4
>>  5 def message (x, channel,s):
>>  6 y="PRIVMSG"+" "+ channel+" :"+x
>>  7 s.send(y);
>>  8 host="irc.freenode.net ";
>>  9 port=6667;
>>  10 size=1024;
>>  11 channel="#dhaivatrocks";
>>  12 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM);
>>  13 s.connect((host,port));
>>  14 s.send("NICK PoincareBot");
>>  15 s.send("USER  PoincareBot 8 *  : Paul Mutton");
>>  16 time.sleep(5);
>>  17 s.send("JOIN #dhaivatrocks");
>>  18 s.send(PRIVMSG #dhaivatrocks :Hello everybody!
>>  19 while True:
>>  20 pass;
>>  21
>> What I don't understand is that it doesn't display any messages or show a
>> new message login on my IRC client. What's wrong with my code?
>>
> You probably need to put some sort of line ending on what you send, eg
> "\n" or "\r\n". Also, it's better to use 'sendall' insetad of 'send'.
>
> BTW, you don't need to put a semicolon on the end of the lines.
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Which version of python I should use if I just start programming in python?

2009-09-13 Thread Peng Yu
On Sun, Sep 13, 2009 at 12:27 AM, John Nagle  wrote:
> Kee Nethery wrote:
>>
>> I am in 2.x because the IDE I am using does not support stepping through
>> my code when in 3.x. As soon as the IDE I use supports debugging in 3.x, I'm
>> moving up to 3.x.
>>
>> I would prefer to be in 3.x because all the inconsistencies of how you do
>> things in 2.x make it harder than it needs to be to learn the language.
>
>   So would I.  But the infrastructure isn't there yet.  Realistically,
> 2.5 is the "production stable" version of CPython.  Almost all important
> modules work with CPython 2.5.  Some work with 2.6.  3.x support remains
> spotty.  Give it a year.  Or two.
>
>   I've tried using 3.1, but had to back down.

What are the differences between 2.5 and 2.6?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is there a similar mailing list about django?

2009-09-13 Thread Tim Chase

Joel Goldstick wrote:
I'm learning python and django more or less concurrently.  I've googled 
to find a similar list like this for django.  Help?


There's a Django Users mailing list over on Google Groups.

  http://groups.google.com/group/django-users

You want Django *Users* for folks that use Django to write 
applications, not Django *Developers* which is the mailing list 
for the dev team that produces Django.


-tkc



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


Re: Which version of python I should use if I just start programming in python?

2009-09-13 Thread Andreas Waldenburger
On Sun, 13 Sep 2009 15:52:44 -0500 Peng Yu  wrote:

> On Sun, Sep 13, 2009 at 12:27 AM, John Nagle 
> wrote:
> What are the differences between 2.5 and 2.6?

http://docs.python.org/dev/whatsnew/2.6.html

/W

-- 
INVALID? DE!

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


Re: Is there a similar mailing list about django?

2009-09-13 Thread Andreas Waldenburger
On Sun, 13 Sep 2009 15:54:07 -0400 Albert Hopkins
 wrote:

> On Sun, 2009-09-13 at 21:27 +0200, Andreas Waldenburger wrote:
> > Didn't like http://groups-beta.google.com/group/django-users ?
> > 
> > (Second hit for "django mailing list", but I know Google results
> > vary from country to country, so you might not have seen it.)
> 
> Or, better yet, go to Django's web site (djangoproject.org) and click
> on "Community" at the top of the page.
> 
Hehe, that was the first Google hit. :)

Well, anyway ...
/W

-- 
INVALID? DE!

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


Re: Python strict mode?

2009-09-13 Thread Terry Reedy

Peng Yu wrote:

Hi,

Is there is a way to make python check the variables just as the
strict mode in perl. Would somebody let me know what is the python
equivalent to the perl strict mode?


3rd party code checkers like pylint, pychecker.

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


ANN: Python FTP Server library (pyftpdlib) 0.5.2 released

2009-09-13 Thread Giampaolo Rodola'
Hi,
I'm pleased to announce release 0.5.2 of Python FTP Server library
(pyftpdlib).
http://code.google.com/p/pyftpdlib

=== About ===

Python FTP server library provides a high-level portable interface to
easily write asynchronous FTP servers with Python.
pyftpdlib is currently the most complete RFC-959 FTP server
implementation available for Python programming language.
It is used in projects like Google Chromium and Bazaar and included in
Linux Fedora and FreeBSD package repositories.


=== Changes ===

This new version is mainly a bugfix release, including some important
security-related patches.
Aside from fixing those bugs, it includes the following enhancements:

* A new ThrottledDTPHandler class is available. With this you can
limit the speed for downloads and uploads affecting the data channel.
Take a look at the throttled_ftpd.py script which shows an example
usage:
http://code.google.com/p/pyftpdlib/source/browse/trunk/demo/throttled_ftpd.py

* A new unix_daemon.py script has been included in the demo directory
(contributed by Michele Petrazzo).

A complete list of changes including enhancements and bug fixes is
available here:
http://code.google.com/p/pyftpdlib/wiki/ReleaseNotes05


=== More links ===

* Source tarball: http://pyftpdlib.googlecode.com/files/pyftpdlib-0.5.2.tar.gz
* Online docs: http://code.google.com/p/pyftpdlib/wiki/Tutorial
* FAQs: http://code.google.com/p/pyftpdlib/wiki/FAQ
* RFCs compliance paper: http://code.google.com/p/pyftpdlib/wiki/RFCsCompliance
* Issue tracker: http://code.google.com/p/pyftpdlib/issues/list
* Mailing list: http://groups.google.com/group/pyftpdlib


Thanks,

--- Giampaolo Rodola' < g.rodola [at] gmail [dot] com >
http://code.google.com/p/pyftpdlib/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python strict mode?

2009-09-13 Thread Ben Finney
Peng Yu  writes:

> Is there is a way to make python check the variables just as the
> strict mode in perl. Would somebody let me know what is the python
> equivalent to the perl strict mode?

There isn't one, because Python doesn't have the same concept of “unsafe
constructs”; in Python, we think more carefully about adding such
constructs to the language in the first place :-) and use a process like
Python 2 → Python 3 to remove them.

You're specifically asking about variables, so I assume you mean the
‘strict vars’ mode to chack variable usage against variable
declarations. Python doesn't have those declarations, and doesn't really
have “variables” as you might think of them either. So no, there's no
such thing in Python.

You will probably be interested in static code checkers such as pyflakes
http://pypi.python.org/pypi/pyflakes> which is small and simple, or
pylint http://pypi.python.org/pypi/pylint> which is comprehensive
and very customisable.

-- 
 \   “It ain't so much the things we don't know that get us in |
  `\trouble. It's the things we know that ain't so.” —Artemus Ward |
_o__) (1834–1867), U.S. journalist |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Odd/Weird errors with FTPLib

2009-09-13 Thread Bakes
I am using a simple python script to download my logfiles. This is on
a while loop, the logfile grows rapidly, so it is necessary for python
to start downloading the new script as soon as it has finished the
old.

It works fine (for about 20 minutes), then crashes. I have removed a
couple of excepts, and have narrowed the error down to a 'error_perm:
550 logfile.log: The data is invalid.' error.

Does anyone know what the problem might be regarding this, and what I
might do to fix it?

It's really irritating to have it break every so often, and at the
moment, I have no chance in which to fix the error.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Odd/Weird errors with FTPLib

2009-09-13 Thread Chris Rebert
On Sun, Sep 13, 2009 at 2:34 PM, Bakes  wrote:
> I am using a simple python script to download my logfiles. This is on
> a while loop, the logfile grows rapidly, so it is necessary for python
> to start downloading the new script as soon as it has finished the
> old.
>
> It works fine (for about 20 minutes), then crashes. I have removed a
> couple of excepts, and have narrowed the error down to a 'error_perm:
> 550 logfile.log: The data is invalid.' error.
>
> Does anyone know what the problem might be regarding this, and what I
> might do to fix it?

Including an actual code snippet and the full error traceback would help a lot.

According to http://en.wikipedia.org/wiki/List_of_FTP_server_return_codes ,
error code 550 translates to:
"Requested action not taken. File unavailable (e.g., file not found,
no access)."

Does the logfile get rotated or something, thus causing it to briefly not exist?

It might also help if you explain how your logfile system works.

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


Re: Odd/Weird errors with FTPLib

2009-09-13 Thread Bakes
On 13 Sep, 22:41, Chris Rebert  wrote:
> On Sun, Sep 13, 2009 at 2:34 PM, Bakes  wrote:
> > I am using a simple python script to download my logfiles. This is on
> > a while loop, the logfile grows rapidly, so it is necessary for python
> > to start downloading the new script as soon as it has finished the
> > old.
>
> > It works fine (for about 20 minutes), then crashes. I have removed a
> > couple of excepts, and have narrowed the error down to a 'error_perm:
> > 550 logfile.log: The data is invalid.' error.
>
> > Does anyone know what the problem might be regarding this, and what I
> > might do to fix it?
>
> Including an actual code snippet and the full error traceback would help a 
> lot.
>
> According tohttp://en.wikipedia.org/wiki/List_of_FTP_server_return_codes,
> error code 550 translates to:
> "Requested action not taken. File unavailable (e.g., file not found,
> no access)."
>
> Does the logfile get rotated or something, thus causing it to briefly not 
> exist?
>
> It might also help if you explain how your logfile system works.
>
> Cheers,
> Chris
> --http://blog.rebertia.com

It's a cod4 gameserver logfile, being downloaded for a python bot to
parse.

The logfile is downloaded using this try/except while loop.


while True:
try:
if ftp == False:
self.debug('FTP connection not active, attempting to
(re)connect')
ftp = self.ftpconnect()
size=os.path.getsize('games_mp.log')
ftp.retrbinary('RETR ' + os.path.basename(self.ftpconfig
['path']), handleDownload, rest=size)
if self.console._paused:
self.console.unpause()
except:
print error
self.debug('Lost connection to server, pausing until
updated properly, Sleeping 10 seconds')
self.console.pause()
try:
ftp.close()
self.debug('FTP Connection Closed')
except:
self.debug('FTP does not appear to be open, so not
closed')
ftp = False
time.sleep(10)


I can only assume that occasionally, the logfile is being written to
by the gameserver at the same time that it's downloading.
If this was the case, do you think a try: download except: sleep
900msec then download loop would work?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Which version of python I should use if I just start programming in python?

2009-09-13 Thread Peng Yu
On Sun, Sep 13, 2009 at 4:01 PM, Andreas Waldenburger
 wrote:
> On Sun, 13 Sep 2009 15:52:44 -0500 Peng Yu  wrote:
>
>> On Sun, Sep 13, 2009 at 12:27 AM, John Nagle 
>> wrote:
>> What are the differences between 2.5 and 2.6?
>
> http://docs.python.org/dev/whatsnew/2.6.html

Are all packages available in 2.5 also available in 2.6?

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


Re: Python and 3d

2009-09-13 Thread Carl Banks
On Sep 13, 9:29 am, "Mike C. Fletcher"  wrote:
> azrael wrote:
> > Has anyone any exipience with python and 3d.
>
> > I mean, is there a module to deal with popular 3d formats like 3ds, or
> > vrml. is it possible to import into python opengl models and then use
> > it in application for GUI purposes like through WX. I know that WX
> > supports OpenGL but how to import models from file.
>
> http://www.vrplumber.com/py3d.py
>
> There's a few older projects to load 3DS files, but I don't think any of
> them is currently PyOpenGL 3.x compatible.

Dice3DS works fine with PyOpenGL 3.x.


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


Why indentation is use to denote block of code?

2009-09-13 Thread Peng Yu
Hi,

I want to understand why python use indentation to denote block of
code. What are the advantages of it? Is there a style in python to
denote a block of code the same as that of C++ (with '{}')?

One disadvantage of using indentation to denote a block of code is
that the runtime to automatically indent a python code would be about
a few times more than the runtime to automatically indent a C++ code
of the same length (both are in vim).

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


Re: Why indentation is use to denote block of code?

2009-09-13 Thread Chris Rebert
On Sun, Sep 13, 2009 at 3:12 PM, Peng Yu  wrote:
> Hi,
>
> I want to understand why python use indentation to denote block of
> code. What are the advantages of it?

See the FAQ:
http://www.python.org/doc/faq/general/#why-does-python-use-indentation-for-grouping-of-statements

> Is there a style in python to
> denote a block of code the same as that of C++ (with '{}')?

No.

> One disadvantage of using indentation to denote a block of code is
> that the runtime to automatically indent a python code would be about
> a few times more than the runtime to automatically indent a C++ code
> of the same length (both are in vim).

In fact it's pretty much impossible to automatically indent Python
code that has had its indentation removed; it's impossible to know for
sure where the dedents should occur.

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


Re: Why indentation is use to denote block of code?

2009-09-13 Thread Sean DiZazzo
On Sep 13, 3:12 pm, Peng Yu  wrote:
> Hi,
>
> I want to understand why python use indentation to denote block of
> code. What are the advantages of it? Is there a style in python to
> denote a block of code the same as that of C++ (with '{}')?
>
> One disadvantage of using indentation to denote a block of code is
> that the runtime to automatically indent a python code would be about
> a few times more than the runtime to automatically indent a C++ code
> of the same length (both are in vim).
>
> Regards,
> Peng

Try this:

from __future__ import braces

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


Re: numpy NaN, not surviving pickle/unpickle?

2009-09-13 Thread John Ladasky
Hi Robert,

Thanks for the quick reply.

On Sep 13, 1:22 pm, Robert Kern  wrote:

> The problem is that you are trying to use "is" to compare by Python object
> identity. Except for dtype=object arrays, the object identities of the
> individual elements that you extract from numpy arrays are never guaranteed.
> Usually, they will always be different. You need to use numpy.isnan() to
> determine whether an object is a NaN.

OK, so there's a dedicated function in numpy to handle this.  Thanks!

I tried "x is NaN" after noting the obvious, that any equality or
inequality test involving NaN will return False.

In my leisure time, I would like to dig deeper into the issue of why
object identities are not guaranteed for elements in numpy arrays...
with elements of type "float", at least, I thought this would be
trivial.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Which version of python I should use if I just start programming in python?

2009-09-13 Thread Andreas Waldenburger
On Sun, 13 Sep 2009 17:04:25 -0500 Peng Yu  wrote:

> On Sun, Sep 13, 2009 at 4:01 PM, Andreas Waldenburger
>  wrote:
> > On Sun, 13 Sep 2009 15:52:44 -0500 Peng Yu 
> > wrote:
> >
> >> On Sun, Sep 13, 2009 at 12:27 AM, John Nagle 
> >> wrote:
> >> What are the differences between 2.5 and 2.6?
> >
> > http://docs.python.org/dev/whatsnew/2.6.html
> 
> Are all packages available in 2.5 also available in 2.6?
> 
If the release notes don't say otherwise, then yes.

The general rule is this: *Only* Python 3 breaks backwards
compatibility. If it works in Python 2.n then it will work unmodified
in Python 2.(n+1).

Please note that I'm talking about the *standard library* and the
language itself, of course. Usually newer versions are not as widely
supported as older ones as far as third party modules go.

/W

-- 
INVALID? DE!

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


Re: Why indentation is use to denote block of code?

2009-09-13 Thread Sean DiZazzo
On Sep 13, 3:12 pm, Peng Yu  wrote:
> Hi,
>
> I want to understand why python use indentation to denote block of
> code. What are the advantages of it? Is there a style in python to
> denote a block of code the same as that of C++ (with '{}')?
>
> One disadvantage of using indentation to denote a block of code is
> that the runtime to automatically indent a python code would be about
> a few times more than the runtime to automatically indent a C++ code
> of the same length (both are in vim).
>
> Regards,
> Peng

Looking at your other post regarding "strict mode", I have to
comment.  I think you are looking for a different language.  What you
are hoping to change about the language are some of the major things
that make it a joy to program for me.  Braces, static typing, no
indentation... What's next?  Would you like semicolons?

I suggest you spend some time just programming it the way it was made
to be programmed, and quit trying to turn it into Perl or any other
language.  If after a week or two, you don't like it, then move on.
And save us the complaints.

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


Re: Is there a similar mailing list about django?

2009-09-13 Thread Joel Goldstick

Andreas Waldenburger wrote:

On Sun, 13 Sep 2009 15:54:07 -0400 Albert Hopkins
 wrote:


On Sun, 2009-09-13 at 21:27 +0200, Andreas Waldenburger wrote:

Didn't like http://groups-beta.google.com/group/django-users ?

(Second hit for "django mailing list", but I know Google results
vary from country to country, so you might not have seen it.)

Or, better yet, go to Django's web site (djangoproject.org) and click
on "Community" at the top of the page.


Hehe, that was the first Google hit. :)

Well, anyway ...
/W

Thanks.. I saw the google group, but I was hoping for a list that I can 
read in my thunderbird client.  Thanks all for the good pointers

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


Re: Odd/Weird errors with FTPLib

2009-09-13 Thread MRAB

Bakes wrote:

On 13 Sep, 22:41, Chris Rebert  wrote:

On Sun, Sep 13, 2009 at 2:34 PM, Bakes  wrote:

I am using a simple python script to download my logfiles. This is on
a while loop, the logfile grows rapidly, so it is necessary for python
to start downloading the new script as soon as it has finished the
old.
It works fine (for about 20 minutes), then crashes. I have removed a
couple of excepts, and have narrowed the error down to a 'error_perm:
550 logfile.log: The data is invalid.' error.
Does anyone know what the problem might be regarding this, and what I
might do to fix it?

Including an actual code snippet and the full error traceback would help a lot.

According tohttp://en.wikipedia.org/wiki/List_of_FTP_server_return_codes,
error code 550 translates to:
"Requested action not taken. File unavailable (e.g., file not found,
no access)."

Does the logfile get rotated or something, thus causing it to briefly not exist?

It might also help if you explain how your logfile system works.

Cheers,
Chris
--http://blog.rebertia.com


It's a cod4 gameserver logfile, being downloaded for a python bot to
parse.

The logfile is downloaded using this try/except while loop.


while True:
try:
if ftp == False:
self.debug('FTP connection not active, attempting to 
(re)connect')
ftp = self.ftpconnect()
size=os.path.getsize('games_mp.log')
ftp.retrbinary('RETR ' + os.path.basename(self.ftpconfig ['path']), 
handleDownload, rest=size)
if self.console._paused:
self.console.unpause()
except:
print error
self.debug('Lost connection to server, pausing until updated 
properly, Sleeping 10 seconds')
self.console.pause()
try:
ftp.close()
self.debug('FTP Connection Closed')
except:
self.debug('FTP does not appear to be open, so not closed')
ftp = False
time.sleep(10)


I can only assume that occasionally, the logfile is being written to
by the gameserver at the same time that it's downloading.
If this was the case, do you think a try: download except: sleep
900msec then download loop would work?


Bare excepts are almost always a bad idea because they'll catch _all_
exceptions, both those you expect could happen and those you don't.
Catch only those you expect.

For example, if the file 'games_mp.log' doesn't exist then 
os.path.getsize('games_mp.log') will raise an exception, and if you

forgot to import the os module then that will raise a NameError
exception.

Anyway, I can't see how you leave the loop; I'd expect something like a
'break' statement.

And as a matter of style, I'd prefer None to False to indicate when
there's no FTP connection (and "if not ftp" instead of "if ftp ==
False").
--
http://mail.python.org/mailman/listinfo/python-list


Re: Why indentation is use to denote block of code?

2009-09-13 Thread Grant Edwards
On 2009-09-13, Peng Yu  wrote:

> One disadvantage of using indentation to denote a block of code is
> that the runtime to automatically indent a python code would be about
> a few times more than the runtime to automatically indent a C++ code
> of the same length (both are in vim).

Talking about "automatically indenting Python" makes no sense.

It would be the equivalent of removing all the braces "{}" from
C code and then talking about automatically inserting them in
the proper places.  If you had a program that could do that,
you might as sell just have it generate all of the source code
for you from scratch.

In C, indentation is just a redundant visual clue for the
reader.  It is needed because people are really awful at
parsing block delimiters and if/then/else/while sematics
visually.

In python the indentation _is_ the block delimiters, which
means that the block structures perceived by the reader via
indentation _always_ matches the block structure seen by the
compiler.  That's not true in C, and it causes all sorts of
bugs when the structure perceived by the reader (via
indenation) doesn't match that perceived by the compiler (via
braces).


-- 
Grant Edwards   grante Yow! If I had a Q-TIP, I
  at   could prevent th' collapse
   visi.comof NEGOTIATIONS!!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: numpy NaN, not surviving pickle/unpickle?

2009-09-13 Thread Christian Heimes
John Ladasky wrote:
> OK, so there's a dedicated function in numpy to handle this.  Thanks!
> 
> I tried "x is NaN" after noting the obvious, that any equality or
> inequality test involving NaN will return False.
> 
> In my leisure time, I would like to dig deeper into the issue of why
> object identities are not guaranteed for elements in numpy arrays...
> with elements of type "float", at least, I thought this would be
> trivial.

You mustn't use "is" on numbers ever. It might work under some special
circumstances but in general it doesn't do what you expect. NaN isn't a
singleton in Python. Python's float type uses IEEE 754 double precision
numbers internally. The double type has much more than billions of NaN
values (IIRC 2**53). isnan() is the only reliable way to detect NaNs. "x
!= x" is a hack that works on most platforms, too.

Christian

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


Re: numpy NaN, not surviving pickle/unpickle?

2009-09-13 Thread Robert Kern

John Ladasky wrote:


In my leisure time, I would like to dig deeper into the issue of why
object identities are not guaranteed for elements in numpy arrays...
with elements of type "float", at least, I thought this would be
trivial.


Why do you think that? We would have to keep a reference around to every scalar 
object that gets created and check against that cache whenever someone accesses 
an element in order to reuse the previously created object. That slows element 
access down for essentially no benefit.


--
Robert Kern

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

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


Re: Why indentation is use to denote block of code?

2009-09-13 Thread r
On Sep 13, 5:12 pm, Peng Yu  wrote:
> Hi,
>
> I want to understand why python use indentation to denote block of
> code. What are the advantages of it? Is there a style in python to
> denote a block of code the same as that of C++ (with '{}')?

Easy! because Python is simplistic programming bliss!

Indenting code makes the blocks easier to read and forcing this on
Python programmers is a good thing. And as a side effect "dedent" can
be used to find the end of a block. Some languages still use block
ending notations like the redundant "end". I think they do this from
an inability to break from old habits and fear of change.

You will find Python to be a revolutionary language that does not
confine itself to closed minded archaic redundancies and asinine
design flaws. Pythons simplistic syntax, elegant coding structure, and
beautifully intelligent design, encompass the traits that every twenty
first century language should aspire to be.

Right now you can think of yourself as the poor Neo, completely
oblivious of the matrix(C) that blinds you to reality. You can think
of Python as Morpheus, the one who shall open your eyes to the
atrocities of C and other evil languages of who's names i shall not
utter here. This should enlighten you a bit...

http://tiny.cc/TheBlindingMatrixOfC
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: numpy NaN, not surviving pickle/unpickle?

2009-09-13 Thread Carl Banks
On Sep 13, 3:18 pm, John Ladasky  wrote:
> In my leisure time, I would like to dig deeper into the issue of why
> object identities are not guaranteed for elements in numpy arrays...
> with elements of type "float", at least, I thought this would be
> trivial.

Unlike Python lists, numpy arrays don't store objects.  It stores the
underlying number, not the object containing the number.  So whenever
you get a value from a numpy array, Python (usually) has to create a
new object for it.


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


Re: Why indentation is use to denote block of code?

2009-09-13 Thread Steven D'Aprano
On Sun, 13 Sep 2009 15:15:40 -0700, Chris Rebert wrote:

> In fact it's pretty much impossible to automatically indent Python code
> that has had its indentation removed; it's impossible to know for sure
> where the dedents should occur.


Just like most other syntactic elements -- if you remove all the return 
statements from Python code, or dot operators, it's impossible to 
automatically add them back in.

The only difference is that some (badly written?) applications mangle 
leading whitespace, but very few feel free to remove other text on a whim.

I don't recall actually using a mail client or newsreader that removes 
leading whitespace when posting, but I've occasionally seen posts from 
others with all indentation removed, so presumably such badly-behaved 
applications do exist.


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


Re: Is there a similar mailing list about django?

2009-09-13 Thread Andreas Waldenburger
On Sun, 13 Sep 2009 18:46:44 -0400 Joel Goldstick
 wrote:

> Thanks.. I saw the google group, but I was hoping for a list that I
> can read in my thunderbird client.  Thanks all for the good pointers

Huh? Django-Users is a mailing list. That's what Google-Groups is
(among a Usenet portal): A collection of mailing lists. And those work
in Thunderbird, I vouch for that.

/W

-- 
INVALID? DE!

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


Re: Is there a similar mailing list about django?

2009-09-13 Thread Andreas Waldenburger
On Mon, 14 Sep 2009 01:24:49 +0200 Andreas Waldenburger
 wrote:

> (among a Usenet portal)

Damn those late hours. What I meant was "amongst other things such as a
Usenet portal".

/W

-- 
INVALID? DE!

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


Re: Is there a similar mailing list about django?

2009-09-13 Thread Albert Hopkins
On Sun, 2009-09-13 at 18:46 -0400, Joel Goldstick wrote:
> Thanks.. I saw the google group, but I was hoping for a list that I
> can 
> read in my thunderbird client.  Thanks all for the good pointers

And if you simply go to the Django web site and click on "Community"
there is a form where you can subscribe to the Django mailing lists and
read them in your precious little Thunderbird client.

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


Re: Python strict mode?

2009-09-13 Thread Carl Banks
On Sep 13, 9:25 am, Peng Yu  wrote:
> Is there is a way to make python check the variables just as the
> strict mode in perl. Would somebody let me know what is the python
> equivalent to the perl strict mode?


I don't recommend using it, but see this post:

http://groups.google.com/group/comp.lang.python/msg/290e4617c3a97f6f?hl=en


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


Re: numpy NaN, not surviving pickle/unpickle?

2009-09-13 Thread Steven D'Aprano
On Sun, 13 Sep 2009 17:58:14 -0500, Robert Kern wrote:

> John Ladasky wrote:
> 
>> In my leisure time, I would like to dig deeper into the issue of why
>> object identities are not guaranteed for elements in numpy arrays...
>> with elements of type "float", at least, I thought this would be
>> trivial.
> 
> Why do you think that? We would have to keep a reference around to every
> scalar object that gets created and check against that cache whenever
> someone accesses an element in order to reuse the previously created
> object. That slows element access down for essentially no benefit.


Exactly -- there are 2**53 distinct floats on most IEEE systems, the vast 
majority of which might as well be "random". What's the point of caching 
numbers like 2.5209481723210079? Chances are it will never come up again 
in a calculation.

There may be something to be said for caching "common" floats, like pi, 
small integers (0.0, 1.0, 2.0, ...), 0.5, 0.25 and similar, but I doubt 
the memory savings would be worth the extra complexity.

You can do your own caching: pass every calculation result through the 
following:

_cache = {}
def cache(f):
"""Cache and return float f."""
if f in _cache:
return _cache[f]
_cache[f] = f
return f




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


Re: How to define a function with an empty body?

2009-09-13 Thread Steven D'Aprano
On Sun, 13 Sep 2009 15:30:52 +0200, Christian Heimes wrote:

> Peng Yu schrieb:
>> Hi,
>> 
>> I want to define a function without anything in it body. In C++, I can
>> do something like the following because I can use "{}" to denote an
>> empty function body. Since python use indentation, I am not sure how to
>> do it. Can somebody let me know how to do it in python?
> 
> Python has two possibilities to create an empty function. The others
> already told you aber the pass statement. The other way is a function
> with a doc string
> 
> def func():
> """No op function
> """


There are more than just two possibilities. Here are three trivial 
variations on the same technique:

def func():
return

def func():
return None

lambda: None


and two slightly more complex variations:

new.function(compile("", "", "exec"), {})

# given some existing function f:
type(f)(compile("", "", "exec"), {})



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


Re: run exe on different computer

2009-09-13 Thread Dave Angel

daved170 wrote:

On Sep 13, 2:17 pm, Dave Angel  wrote:
  

daved170 wrote:


Hi everybody,
I'm building a small python program that run a service (exe file) on
my servers.
I don't want to use remote desktop and it's siblings.
  
I would like to have some information on how to run an exe on a

different computer and if there a way to check if that exe is still
alive.
  
Thanks

Dave
  

On a question like this, you really need to supply much more information
on your constraints.  You could start by saying these servers are
running Windows Server 2003.  And that they're on a domain (rather than
a workgroup).  And that you're trying to access them from another
machine within the same local domain, not over the internet.  And that
your local machine is on the same domain, and has an account with admin
privileges for all the desired servers.  And that you are allowed to do
a one-time install (of something) on each server prior to this
particular need.  And that each server already has Python version 2.5
installed, and the IT department won't allow you to install any later
version.

Then once you have an environment, you need to specify just what kind of
program you want to run on those servers.  Is it an EXE program?  Or is
it Python, with a particular script?  Does it really need to be a
*service*, which has a particular set of constraints, and should be
installed, and started/stopped using the service manager.  Do you want
this program to restart whenever the servers are restarted?

One solution that should work for nearly every Windows topology might be
to go to each server, run the scheduler task, and specify a new batch
file to be run upon boot.  This batch file can check a specified
(shared) directory for a python script, and if found, run it.  If not
found, sleep for 60 seconds or so, then repeat.  Note that it's a good
idea to put a five minute delay at the very beginning, in case the
script needs to be deleted at the next boot.  Sometimes a bug requires
surgery, and it's good to have enough time to do it.

Now, to control those servers from another machine, copy an appropriate
script into the prearranged directory.  Within a minute, it'll be
running, and it can post whatever results it likes in another accessible
directory.

Whether this is a "safe" thing to do is a separate question.  Generally
an IT department likes to have some control over just what programs run
on their servers, and for good reason.

DaveA



Hi DaveA
Thanks for your answer. I'll try to clearify myself.
For now I'm trying to do that on client & server that are win XP. They
both on the same domain (maybe in the future they'll be runinig on the
web). I have admin user on both my computers.
I have both an exe and a python app that I'd like to control from my
client.
Insted of logging to my Server I would like to write a python app at
my client that allows me to control both that exe and my Server-python-
app. I don't want to use the schedualer because I would like to
control it from my client.
I can install whatever I'll like on both of the computers. they are
mine and I have full access for them.
I hope I clearify myself and if there are more solutions I'll be happy
to be noted.
Thans
DaveD :)

  
If you only have those two machines, you aren't on a NT domain, you've 
got a workgroup.  A Windows domain is hosted by a server OS, and XP can 
only be a client on a domain.  Without being on an NT domain, security 
is much sloppier.  In some ways that makes things easier, but you may 
hit a brick wall if you need more than one kind of simultaneous access 
to another machine.


Is this EXE file you want to run on the server something out of your 
control, or could you customize that as well?  Because if you can, then 
the distinction between that and your server-python program is probably 
unimportant.  Call the programs you might want to run:   X1, X2, X3.


In order to run X1 on that server without opening a console (or remote 
desktop, or whatever) on it, you will have to have something else 
already running which is willing to be a proxy on your behalf.  You then 
communicate with that program to tell it what to run, and when.  I 
suggested a batch file for that program, call it S.  It could just as 
easily have been a python script, but there's no advantage that I can 
see.  The idea is to make sure that S is always running (which is why 
you put it into the scheduler;  it'll be restarted whenever the machine 
is booted).


Anyway, the idea is that S is a very lightweight program, and it can 
launch any possible Xn.  And the only question is how you want the 
client to talk to S.  If S is a fancier program, you might use sockets, 
or whatever, but on a local system, the file system works pretty well.  
And a batch file is about as lightweight as you can get;  the only 
external program it needs is "sleep.exe".


It's quite possible that DCOM (for example) includes something that acts 
like S, but when I was work

Re: numpy NaN, not surviving pickle/unpickle?

2009-09-13 Thread John Ladasky
On Sep 13, 4:17 pm, Carl Banks  wrote:
> On Sep 13, 3:18 pm, John Ladasky  wrote:
>
> > In my leisure time, I would like to dig deeper into the issue of why
> > object identities are not guaranteed for elements in numpy arrays...
> > with elements of type "float", at least, I thought this would be
> > trivial.
>
> Unlike Python lists, numpy arrays don't store objects.  

That would be the crux of it, I think.  I've gotten so used to the
behavior of Python lists that I now have to unlearn it!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why indentation is use to denote block of code?

2009-09-13 Thread AggieDan04
On Sep 13, 6:27 pm, Steven D'Aprano  wrote:
> On Sun, 13 Sep 2009 15:15:40 -0700, Chris Rebert wrote:
> > In fact it's pretty much impossible to automatically indent Python code
> > that has had its indentation removed; it's impossible to know for sure
> > where the dedents should occur.
>
> Just like most other syntactic elements -- if you remove all the return
> statements from Python code, or dot operators, it's impossible to
> automatically add them back in.
>
> The only difference is that some (badly written?) applications mangle
> leading whitespace, but very few feel free to remove other text on a whim.
>
> I don't recall actually using a mail client or newsreader that removes
> leading whitespace when posting, but I've occasionally seen posts from
> others with all indentation removed, so presumably such badly-behaved
> applications do exist.

I haven't seen it in a mail client, but it's very common in internet
forums.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: run exe on different computer

2009-09-13 Thread Sean DiZazzo
On Sep 13, 4:57 pm, Dave Angel  wrote:
> daved170 wrote:
> > On Sep 13, 2:17 pm, Dave Angel  wrote:
>
> >> daved170 wrote:
>
> >>> Hi everybody,
> >>> I'm building a small python program that run a service (exe file) on
> >>> my servers.
> >>> I don't want to use remote desktop and it's siblings.
>
> >>> I would like to have some information on how to run an exe on a
> >>> different computer and if there a way to check if that exe is still
> >>> alive.
>
> >>> Thanks
> >>> Dave
>
> >> On a question like this, you really need to supply much more information
> >> on your constraints.  You could start by saying these servers are
> >> running Windows Server 2003.  And that they're on a domain (rather than
> >> a workgroup).  And that you're trying to access them from another
> >> machine within the same local domain, not over the internet.  And that
> >> your local machine is on the same domain, and has an account with admin
> >> privileges for all the desired servers.  And that you are allowed to do
> >> a one-time install (of something) on each server prior to this
> >> particular need.  And that each server already has Python version 2.5
> >> installed, and the IT department won't allow you to install any later
> >> version.
>
> >> Then once you have an environment, you need to specify just what kind of
> >> program you want to run on those servers.  Is it an EXE program?  Or is
> >> it Python, with a particular script?  Does it really need to be a
> >> *service*, which has a particular set of constraints, and should be
> >> installed, and started/stopped using the service manager.  Do you want
> >> this program to restart whenever the servers are restarted?
>
> >> One solution that should work for nearly every Windows topology might be
> >> to go to each server, run the scheduler task, and specify a new batch
> >> file to be run upon boot.  This batch file can check a specified
> >> (shared) directory for a python script, and if found, run it.  If not
> >> found, sleep for 60 seconds or so, then repeat.  Note that it's a good
> >> idea to put a five minute delay at the very beginning, in case the
> >> script needs to be deleted at the next boot.  Sometimes a bug requires
> >> surgery, and it's good to have enough time to do it.
>
> >> Now, to control those servers from another machine, copy an appropriate
> >> script into the prearranged directory.  Within a minute, it'll be
> >> running, and it can post whatever results it likes in another accessible
> >> directory.
>
> >> Whether this is a "safe" thing to do is a separate question.  Generally
> >> an IT department likes to have some control over just what programs run
> >> on their servers, and for good reason.
>
> >> DaveA
>
> > Hi DaveA
> > Thanks for your answer. I'll try to clearify myself.
> > For now I'm trying to do that on client & server that are win XP. They
> > both on the same domain (maybe in the future they'll be runinig on the
> > web). I have admin user on both my computers.
> > I have both an exe and a python app that I'd like to control from my
> > client.
> > Insted of logging to my Server I would like to write a python app at
> > my client that allows me to control both that exe and my Server-python-
> > app. I don't want to use the schedualer because I would like to
> > control it from my client.
> > I can install whatever I'll like on both of the computers. they are
> > mine and I have full access for them.
> > I hope I clearify myself and if there are more solutions I'll be happy
> > to be noted.
> > Thans
> > DaveD :)
>
> If you only have those two machines, you aren't on a NT domain, you've
> got a workgroup.  A Windows domain is hosted by a server OS, and XP can
> only be a client on a domain.  Without being on an NT domain, security
> is much sloppier.  In some ways that makes things easier, but you may
> hit a brick wall if you need more than one kind of simultaneous access
> to another machine.
>
> Is this EXE file you want to run on the server something out of your
> control, or could you customize that as well?  Because if you can, then
> the distinction between that and your server-python program is probably
> unimportant.  Call the programs you might want to run:   X1, X2, X3.
>
> In order to run X1 on that server without opening a console (or remote
> desktop, or whatever) on it, you will have to have something else
> already running which is willing to be a proxy on your behalf.  You then
> communicate with that program to tell it what to run, and when.  I
> suggested a batch file for that program, call it S.  It could just as
> easily have been a python script, but there's no advantage that I can
> see.  The idea is to make sure that S is always running (which is why
> you put it into the scheduler;  it'll be restarted whenever the machine
> is booted).
>
> Anyway, the idea is that S is a very lightweight program, and it can
> launch any possible Xn.  And the only question is how you want the
> client to talk to S.  If

trouble quitting PyQt4 App

2009-09-13 Thread Soumen banerjee
Hi,
Im new to PyQt4 and im having fun using it. but ive run into a bit of
a problem. I cant quit the application.
The application has 2 modules. The gui module(gui.py) and then the
main program(main.py)
heres gui.py:

from PyQt4 import QtCore, QtGui
import sys
from subprocess import Popen
class Ui_MainWindow(object):
   fileinit=False
   paused=True
   quit=False
   filename=""
   def setupUi(self, MainWindow):
   MainWindow.setObjectName("MainWindow")
   MainWindow.resize(394, 414)
   self.centralwidget = QtGui.QWidget(MainWindow)
   self.centralwidget.setObjectName("centralwidget")
   self.scrollArea = QtGui.QScrollArea(self.centralwidget)
   self.scrollArea.setGeometry(QtCore.QRect(19, 9, 361, 281))
   self.scrollArea.setWidgetResizable(True)
   self.scrollArea.setObjectName("scrollArea")
   self.scrollAreaWidgetContents = QtGui.QWidget(self.scrollArea)
   self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0,
0, 357, 277))
   
self.scrollAreaWidgetContents.setObjectName("scrollAreaWidgetContents")
   self.textEdit = QtGui.QTextEdit(self.scrollAreaWidgetContents)
   self.textEdit.setGeometry(QtCore.QRect(-7, -6, 371, 291))
   self.textEdit.setObjectName("textEdit")
   self.scrollArea.setWidget(self.scrollAreaWidgetContents)
   self.pushButton = QtGui.QPushButton(self.centralwidget)
   self.pushButton.setGeometry(QtCore.QRect(30, 310, 80, 25))
   self.pushButton.setObjectName("pushButton")
   self.pushButton_2 = QtGui.QPushButton(self.centralwidget)
   self.pushButton_2.setGeometry(QtCore.QRect(139, 310, 91, 25))
   self.pushButton_2.setObjectName("pushButton_2")
   self.pushButton_3 = QtGui.QPushButton(self.centralwidget)
   self.pushButton_3.setGeometry(QtCore.QRect(280, 310, 80, 25))
   self.pushButton_3.setObjectName("pushButton_3")
   MainWindow.setCentralWidget(self.centralwidget)
   self.menubar = QtGui.QMenuBar(MainWindow)
   self.menubar.setGeometry(QtCore.QRect(0, 0, 394, 23))
   self.menubar.setObjectName("menubar")
   MainWindow.setMenuBar(self.menubar)
   self.statusbar = QtGui.QStatusBar(MainWindow)
   self.statusbar.setObjectName("statusbar")
   MainWindow.setStatusBar(self.statusbar)

   self.retranslateUi(MainWindow)
   QtCore.QObject.connect(self.pushButton,
QtCore.SIGNAL("clicked()"), self.Open)
   QtCore.QObject.connect(self.pushButton_2,
QtCore.SIGNAL("clicked()"), self.Pause)
   QtCore.QObject.connect(self.pushButton_3,
QtCore.SIGNAL("clicked()"), self.Quit)
   QtCore.QMetaObject.connectSlotsByName(MainWindow)

   def retranslateUi(self, MainWindow):
   
MainWindow.setWindowTitle(QtGui.QApplication.translate("MainWindow",
"MainWindow", None, QtGui.QApplication.UnicodeUTF8))
   
self.pushButton.setText(QtGui.QApplication.translate("MainWindow",
"Open", None, QtGui.QApplication.UnicodeUTF8))
   
self.pushButton_2.setText(QtGui.QApplication.translate("MainWindow",
"Pause/Resume", None, QtGui.QApplication.UnicodeUTF8))
   
self.pushButton_3.setText(QtGui.QApplication.translate("MainWindow",
"Quit", None, QtGui.QApplication.UnicodeUTF8))
   def Pause(self):
   print "Pause"
   self.paused=not(self.paused)
   def Quit(self):
   self.quit=True
   print "setting quit"
   def Open(self):
   print "Open"
   self.filename=QtGui.QFileDialog.getOpenFileName()
   self.filename=str(self.filename)
   f=open("book.txt","r")
   old=f.read(20)
   f.close()
   f=open(self.filename,'r')
   new=f.read(20)
   f.close()
   if(old!=new):
   Popen('rm log.txt',shell=True)
   f=open("book.txt",'w')
   f.write(new)
   f.close()
   self.fileinit=True
   print "setting fileinit"


and heres the main.py

from PyQt4 import QtCore, QtGui
import sip,gui
import sys
from subprocess import Popen
from threading import Thread
class AppThread(Thread):
   appinit=False
   def run(self):
   app = QtGui.QApplication(sys.argv)
   MainWindow = QtGui.QMainWindow()
   self.ui = gui.Ui_MainWindow()
   self.ui.setupUi(MainWindow)
   MainWindow.show()
   self.appinit=True
   #ui.textEdit.setText(ui.filename)
   sys.exit(app.exec_())
class Speak(Thread):
   def run(self):
   print "starting speaker"
   try:

NameError: name '__main__' is not defined

2009-09-13 Thread Peng Yu
Hi,

I try the following code. I don't quite understand why __main__ is not
defined. Could somebody let me know what I am wrong about it?

Regards,
Peng

$ cat test.py
#!/usr/bin/env python

if __main__ == '__main__' :
  print "Hello World!\n"
$ ./test.py
Traceback (most recent call last):
  File "./test.py", line 3, in 
if __main__ == '__main__' :
NameError: name '__main__' is not defined
-- 
http://mail.python.org/mailman/listinfo/python-list


yet another modifying locals() question

2009-09-13 Thread Ed Anuff
I know that locals() is not supposed to be modifiable under most
circumstances, but I'm trying to solve a situation where I'm
dynamically generating some class attributes and it seemed to be the
best way, so I tried something out that seems to work but I'm not sure
that it's kosher:

>>> def f(l):
...l['b'] = 1
...
>>> class A:
...f(locals())
...
>>> A.b
1

In my code, I'm doing something quite a bit more complex than just
assigning a single attribute, but this is the simplest use case
example.

Is there a reason why this works and is it safe to rely on it or is
there a better approach?  BTW, this works in a program too, it's not
just an artifact of the command line interpreter globals() = locals()
thing.

Thanks

Ed

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


Re: Is there a similar mailing list about django?

2009-09-13 Thread Tim Chase

Thanks.. I saw the google group, but I was hoping for a list
that I can read in my thunderbird client.  Thanks all for the
good pointers



You can subscribe to the google group via email (which is what I 
did previously with TB), or you can subscribe to the mirrored 
copy of it over at gmane.comp.python.django.user on 
news.gmane.org which is how I read it now in TB.


-tkc



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


Re: NameError: name '__main__' is not defined

2009-09-13 Thread Xavier Ho
Try

if __name__ == '__main__'

:],
Xav


On Mon, Sep 14, 2009 at 11:43 AM, Peng Yu  wrote:

> Hi,
>
> I try the following code. I don't quite understand why __main__ is not
> defined. Could somebody let me know what I am wrong about it?
>
> Regards,
> Peng
>
> $ cat test.py
> #!/usr/bin/env python
>
> if __main__ == '__main__' :
>  print "Hello World!\n"
> $ ./test.py
> Traceback (most recent call last):
>  File "./test.py", line 3, in 
>if __main__ == '__main__' :
> NameError: name '__main__' is not defined
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: NameError: name '__main__' is not defined

2009-09-13 Thread André
On Sep 13, 10:43 pm, Peng Yu  wrote:
> Hi,
>
> I try the following code. I don't quite understand why __main__ is not
> defined. Could somebody let me know what I am wrong about it?
>
> Regards,
> Peng
>
> $ cat test.py
> #!/usr/bin/env python
>
> if __main__ == '__main__' :
>   print "Hello World!\n"
> $ ./test.py
> Traceback (most recent call last):
>   File "./test.py", line 3, in 
>     if __main__ == '__main__' :
> NameError: name '__main__' is not defined

You wrote __main__ instead of __name__.  It should have been:

if __name__ == '__main__':
 ...

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


Re: NameError: name '__main__' is not defined

2009-09-13 Thread Sean DiZazzo
On Sep 13, 6:43 pm, Peng Yu  wrote:
> Hi,
>
> I try the following code. I don't quite understand why __main__ is not
> defined. Could somebody let me know what I am wrong about it?
>
> Regards,
> Peng
>
> $ cat test.py
> #!/usr/bin/env python
>
> if __main__ == '__main__' :
>   print "Hello World!\n"
> $ ./test.py
> Traceback (most recent call last):
>   File "./test.py", line 3, in 
>     if __main__ == '__main__' :
> NameError: name '__main__' is not defined

Is this a production program that you are using??

Please show us the point you are trying to make in something more
valuable.

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


Re: NameError: name '__main__' is not defined

2009-09-13 Thread Sean DiZazzo
On Sep 13, 6:43 pm, Peng Yu  wrote:
> Hi,
>
> I try the following code. I don't quite understand why __main__ is not
> defined. Could somebody let me know what I am wrong about it?
>
> Regards,
> Peng
>
> $ cat test.py
> #!/usr/bin/env python
>
> if __main__ == '__main__' :
>   print "Hello World!\n"
> $ ./test.py
> Traceback (most recent call last):
>   File "./test.py", line 3, in 
>     if __main__ == '__main__' :
> NameError: name '__main__' is not defined

erI was just angry.  __main__ doesn't exist because it is not in
your programs scope.

you are looking for:

if __name__ == "__main__":
print "Hello World"

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


Re: Problem with the inclusion of new files like lxml, django, numpy, etc.

2009-09-13 Thread alex23
joy99  wrote:
> What is the problem I am doing?

Following the wrong installation instructions?

The ones you _should_ be following state:

1. Download the latest release from our download page.
2. Untar the downloaded file (e.g. tar xzvf Django-NNN.tar.gz, where
NNN is the version number of the latest release). If you're using
Windows, you can download the command-line tool bsdtar to do this, or
you can use a GUI-based tool such as 7-zip.
3. Change into the directory created in step 2 (e.g. cd Django-NNN).
4. If you're using Linux, Mac OS X or some other flavor of Unix, enter
the command sudo python setup.py install at the shell prompt. If
you're using Windows, start up a command shell with administrator
privileges and run the command setup.py install.

>From 
>http://docs.djangoproject.com/en/dev/topics/install/#installing-official-release

Unpacking a module somewhere _other_ than site-packages and running
setup.py is a fairly common installation pattern with python.
-- 
http://mail.python.org/mailman/listinfo/python-list


Why use "locals()"

2009-09-13 Thread Sean DiZazzo
I have never used a call to "locals()" in my code.  Can you show me a
use case where it is valuable and Pythonic?

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


Re: yet another modifying locals() question

2009-09-13 Thread Steven D'Aprano
On Sun, 13 Sep 2009 18:52:47 -0700, Ed Anuff wrote:

> I know that locals() is not supposed to be modifiable under most
> circumstances, but I'm trying to solve a situation where I'm dynamically
> generating some class attributes and it seemed to be the best way, so I
> tried something out that seems to work but I'm not sure that it's
> kosher:

Given that the docs state not to rely on modifying locals(), I think it 
is safe to say it's NOT kosher. If it works for you, you're lucky, but it 
might stop working in the future.



 def f(l):
> ...l['b'] = 1
> ...
 class A:
> ...f(locals())
> ...
 A.b
> 1

> In my code, I'm doing something quite a bit more complex than just
> assigning a single attribute, but this is the simplest use case example.

If you want to dynamically assign attributes after the class is created, 
setattr() is your friend:


class A:
pass

setattr(A, 'b', 1)  # set a class attribute


With full knowledge of the risks of exec'ing untrusted data, you can use 
exec:

class A:
exec('b = 1')



For advanced use, you can look at class decorators and metaclasses.

def decorator(cls):
# Add a class attribute b to the cls.
cls.b = 1
return cls


@decorator
class A:
pass


The above @ syntax requires Python 2.6 or better, but in older versions 
you can write:

class A:
pass
A = decorator(A)


To make it even more dynamic, write a decorator factory:

def decorator(name):
def inner(cls):
setattr(cls, name, 1)
return cls
return inner

class A:
pass
A = decorator('b')(A)



Metaclasses are left as an exercise for the reader.



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


Re: Why use "locals()"

2009-09-13 Thread Steven D'Aprano
On Sun, 13 Sep 2009 20:06:51 -0700, Sean DiZazzo wrote:

> I have never used a call to "locals()" in my code.  Can you show me a
> use case where it is valuable and Pythonic?

grep is your friend:



$ grep "locals()" /usr/lib/python2.5/*.py
/usr/lib/python2.5/decimal.py:for name, val in locals().items():
/usr/lib/python2.5/doctest.py:return __import__(module, globals(), 
locals(), ["*"])
/usr/lib/python2.5/profile.py:p.runctx('f(m)', globals(), locals())
/usr/lib/python2.5/pydoc.py:docloc = 'Module Docs' % locals()
/usr/lib/python2.5/smtpd.py:mod = __import__(classname[:lastdot], 
globals(), locals(), [""])




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


Re: Why use "locals()"

2009-09-13 Thread Sean DiZazzo
On Sep 13, 8:18 pm, Steven D'Aprano
 wrote:
> On Sun, 13 Sep 2009 20:06:51 -0700, Sean DiZazzo wrote:
> > I have never used a call to "locals()" in my code.  Can you show me a
> > use case where it is valuable and Pythonic?
>
> grep is your friend:
>
> $ grep "locals()" /usr/lib/python2.5/*.py
> /usr/lib/python2.5/decimal.py:        for name, val in locals().items():
> /usr/lib/python2.5/doctest.py:        return __import__(module, globals(), 
> locals(), ["*"])
> /usr/lib/python2.5/profile.py:        p.runctx('f(m)', globals(), locals())
> /usr/lib/python2.5/pydoc.py:            docloc = ' href="%(docloc)s">Module Docs' % locals()
> /usr/lib/python2.5/smtpd.py:        mod = __import__(classname[:lastdot], 
> globals(), locals(), [""])
>
> --
> Steven

That is not a use case.  I still don't understand!

PS.  I know how to use grep.

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


Re: Simple Text Processing

2009-09-13 Thread Tim Roberts
Steven D'Aprano  wrote:

>On Fri, 11 Sep 2009 21:52:36 -0700, Tim Roberts wrote:
>
>> Basically, when you're good with Perl, you start to think of every task
>> in terms of regular expression matches.  When you're good with Python,
>> you start to think of every task in terms of lists and tuples.
>
>Not me -- I think of most such tasks in terms of iterators.

I'm hoping to reach that point eventually...
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


python audio streams?

2009-09-13 Thread konung.nik...@googlemail.com
Hello!

Is there a way to record different audio streams (.asx, .ram, m3u)
with Python? Also, is there a way to convert them "on the fly" ?

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


Re: Why use "locals()"

2009-09-13 Thread Steven D'Aprano
On Sun, 13 Sep 2009 20:26:06 -0700, Sean DiZazzo wrote:

> On Sep 13, 8:18 pm, Steven D'Aprano
>  wrote:
>> On Sun, 13 Sep 2009 20:06:51 -0700, Sean DiZazzo wrote:
>> > I have never used a call to "locals()" in my code.  Can you show me a
>> > use case where it is valuable and Pythonic?
>>
>> grep is your friend:
>>
>> $ grep "locals()" /usr/lib/python2.5/*.py
>> /usr/lib/python2.5/decimal.py:        for name, val in
>> locals().items(): /usr/lib/python2.5/doctest.py:        return
>> __import__(module, globals(), locals(), ["*"])
>> /usr/lib/python2.5/profile.py:        p.runctx('f(m)', globals(),
>> locals()) /usr/lib/python2.5/pydoc.py:            docloc = '> href="%(docloc)s">Module Docs' % locals()
>> /usr/lib/python2.5/smtpd.py:        mod =
>> __import__(classname[:lastdot], globals(), locals(), [""])
>>
>> --
>> Steven
> 
> That is not a use case. I still don't understand!

Look at the source code to find out what they're doing with the 
information they extract from locals(), and why.

For instance, profile should be obvious -- debuggers and profilers often 
need to see the values of local names.

pydoc is using the fairly common idiom of injecting the values of 
variables into a string. Personally, I don't see why it uses this idiom:

docloc = 'something'
docloc = '%(docloc)s' % locals()

instead of this:

docloc = 'something'
docloc = '%s' % docloc

but for more complicated cases, the first idiom is much simpler.

decimal seems to be using locals() to avoid this anti-pattern:


def __init__(self, a, b, c, d, e, f, g, h):
self.a = a
self.b = b
self.c = c
self.d = d
# blah blah blah
self.h = h

and replacing it with:

def __init__(self, a, b, c, d, e, f, g, h):
for name, val in locals().items():
setattr(self, name, val)
del self.self


Another use-case: if you have a tool that documents Python code 
automatically, it needs a way to automatically view the values of local 
names.



> PS.  I know how to use grep.

I'm sure you do. But you didn't think of using grep, which is why I made 
the suggestion that grepping the standard library is a good tool to use 
to search for Pythonic examples of code.

It's not foolproof, e.g. the unittest module is more Java-onic than 
Pythonic, but it's a good start.




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


  1   2   >