ANN: warehouse Objects in SQLite : y_serial module

2009-09-11 Thread code43
Module download at SourceForge http://yserial.sourceforge.net

Serialization + persistance :: in a few lines of code, compress and
annotate Python objects into SQLite; then later retrieve them
chronologically by keywords without any SQL. Most useful standard
module for a database to store schema-less data.

The module is instructive in the way it unifies the standard
batteries: sqlite3 (as of Python v2.5), zlib (for compression), and
cPickle (for serializing objects).

If your Python program requires data persistance, then y_serial is a
module which should be worth importing. All objects are warehoused in
a single database file in the most compressed form possible. Tables
are used to differentiate projects. Steps for insertion, organization
by annotation, and finally retrieval are amazingly simple...

y_serial.py module :: warehouse Python objects with SQLite
http://yserial.sourceforge.net

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

Support the Python Software Foundation:
http://www.python.org/psf/donations/


Re: New Tkinter windows don't get focus on OS X

2009-09-11 Thread Hendrik van Rooyen
On Thursday 10 September 2009 18:19:09 Joshua Bronson wrote:

 True, but it'll still be a lot less painful for me to test my app if I
 can get it to steal focus
 when launched from the command line. If anyone knows how to do this in
 Tkinter, help would be much appreciated.


look for widget.focus_force()
and look for widget.grab_set_global()

Yahoo for:   Shipman Tkinter new mexico tech
for a nice manual, if you do not have it yet.

HTH - Hendrik


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


Why can't I run this test class?

2009-09-11 Thread Kermit Mei
Dear all,
I'm a newbie for python, and I write a program to test how to
implement a class:

#!/usr/bin/env
python   

class Test:
'My Test class'
def __init__(self):
self.arg1 = 1

def first(self):
return self.arg1

t1 = Test

print t1.first()


#

But when I run it, some errors take:

$ ./Test.py 
Traceback (most recent call last):
  File ./Test.py, line 13, in module
print t1.first()
TypeError: unbound method first() must be called with Test instance as
first argument (got nothing instead)

What I want is as the following c++ code do:

class Test
{
public:
Test()
:arg1(1)
{/*Do nothing*/}

int first() const
{ return arg1; }
protected:
int arg1;
};

void main(void)
{
Test t1;
std::cout  t1.first;
}


Hope your help.
Thanks

Kermit


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


Re: Why can't I run this test class?

2009-09-11 Thread Chris Rebert
On Fri, Sep 11, 2009 at 12:30 AM, Kermit Mei kermit@gmail.com wrote:
 Dear all,
    I'm a newbie for python, and I write a program to test how to
 implement a class:

 #!/usr/bin/env
 python

 class Test:
    'My Test class'
    def __init__(self):
        self.arg1 = 1

    def first(self):
        return self.arg1

 t1 = Test

You missed the parentheses to call the constructor. That line should be:

t1 = Test()

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


Re: Why can't I run this test class?

2009-09-11 Thread Donn
On Friday 11 September 2009 09:30:42 Kermit Mei wrote:
Do this:
class Test(object):

 t1 = Test
And this:
t1 = Test()
That makes an instance and runs the __init__

\d
-- 
home: http://otherwise.relics.co.za/
2D vector animation : https://savannah.nongnu.org/projects/things/
Font manager : https://savannah.nongnu.org/projects/fontypython/
-- 
http://mail.python.org/mailman/listinfo/python-list


Getting error while importing Sybase Module in Python

2009-09-11 Thread gopalmore007
Hi,

I have solaris 10 x86 installed. I have installed Sybase module 0.39
on Python2.5.
While importing Sybase module. I m getting bellow error.Please
suggest.

 python
Python 2.5.1 (r251:54863, May 16 2007, 19:39:00)
[GCC 3.4.6] on sunos5
Type help, copyright, credits or license for more information.
 import Sybase
Traceback (most recent call last):
  File stdin, line 1, in module
  File build/bdist.solaris-2.10-i86pc/egg/Sybase.py, line 11, in
module
  File build/bdist.solaris-2.10-i86pc/egg/sybasect.py, line 7, in
module
  File build/bdist.solaris-2.10-i86pc/egg/sybasect.py, line 6, in
__bootstrap__
ImportError: ld.so.1: python: fatal: relocation error: file /.python-
eggs/python_sybase-0.39-py2.5-solaris-2.10-i86pc.egg-tmp/sybasect.so:
symbol blk_bind: referenced symbol not found


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


Re: Why can't I run this test class?

2009-09-11 Thread Kermit Mei
On Fri, 2009-09-11 at 00:33 -0700, Chris Rebert wrote:
 On Fri, Sep 11, 2009 at 12:30 AM, Kermit Mei kermit@gmail.com wrote:
  Dear all,
 I'm a newbie for python, and I write a program to test how to
  implement a class:
 
  #!/usr/bin/env
  python
 
  class Test:
 'My Test class'
 def __init__(self):
 self.arg1 = 1
 
 def first(self):
 return self.arg1
 
  t1 = Test
 
 You missed the parentheses to call the constructor. That line should be:
 
 t1 = Test()
 
 Cheers,
 Chris


Yes, that can run. But If I put the following code into Test.py :
#!/usr/bin/env python   |
|
class Test: |
'My Test class' |
def __init__(self): |
self.arg1 = 1   |
|
def first(self):|
return self.arg1|
|
def setFirst(self,value = 5):   |
self.arg1 = value   

But when I want to run it as a module, something also be wrong:

$ python
Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41) 
[GCC 4.3.3] on linux2
Type help, copyright, credits or license for more information.
 import Test
 t1 = Test()
Traceback (most recent call last):
  File stdin, line 1, in module
TypeError: 'module' object is not callable
 

Thanks

Kermit


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


Re: Why can't I run this test class?

2009-09-11 Thread Chris Rebert
On Fri, Sep 11, 2009 at 12:40 AM, Kermit Mei kermit@gmail.com wrote:
 On Fri, 2009-09-11 at 00:33 -0700, Chris Rebert wrote:
 On Fri, Sep 11, 2009 at 12:30 AM, Kermit Mei kermit@gmail.com wrote:
  Dear all,
     I'm a newbie for python, and I write a program to test how to
  implement a class:
 
  #!/usr/bin/env
  python
 
  class Test:
     'My Test class'
     def __init__(self):
         self.arg1 = 1
 
     def first(self):
         return self.arg1
 
  t1 = Test

 You missed the parentheses to call the constructor. That line should be:

 t1 = Test()

 Cheers,
 Chris


 Yes, that can run. But If I put the following code into Test.py :
 #!/usr/bin/env python                                               |
                                                                    |
 class Test:                                                         |
    'My Test class'                                                 |
    def __init__(self):                                             |
        self.arg1 = 1                                               |
                                                                    |
    def first(self):                                                |
        return self.arg1                                            |
                                                                    |
    def setFirst(self,value = 5):                                   |
        self.arg1 = value

 But when I want to run it as a module, something also be wrong:

 $ python
 Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41)
 [GCC 4.3.3] on linux2
 Type help, copyright, credits or license for more information.
 import Test
 t1 = Test()
 Traceback (most recent call last):
  File stdin, line 1, in module
 TypeError: 'module' object is not callable

You've imported the module `Test`, whose name is determined by the
filename (Test.py).
To access the class of the same name (`Test`) that is defined in the
module, you need to use the dot operator:

 import Test
 t1 = Test.Test()

You should probably use different names for the module/file and the
class to avoid confusion.
Unlike Java, Python does not observe a direct correspondence between
filenames and classes.

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


Re: New Tkinter windows don't get focus on OS X

2009-09-11 Thread eb303
On Sep 11, 9:14 am, Hendrik van Rooyen hend...@microcorp.co.za
wrote:
 On Thursday 10 September 2009 18:19:09 Joshua Bronson wrote:

  True, but it'll still be a lot less painful for me to test my app if I
  can get it to steal focus
  when launched from the command line. If anyone knows how to do this in
  Tkinter, help would be much appreciated.

 look for widget.focus_force()
 and look for widget.grab_set_global()

Doesn't work. BTW, forcing the focus or setting the grab globally are
usually considered very annoying and I don't know any windowing system
or window manager honouring those.

For the OP: the problem comes from the tcl/tk level. Running a tcl
script just opening a window from the terminal shows the same
behaviour. You might want to forward the question to the tcl guys.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why can't I run this test class?

2009-09-11 Thread Kermit Mei
On Fri, 2009-09-11 at 00:43 -0700, Chris Rebert wrote:
 On Fri, Sep 11, 2009 at 12:40 AM, Kermit Mei kermit@gmail.com wrote:
  On Fri, 2009-09-11 at 00:33 -0700, Chris Rebert wrote:
  On Fri, Sep 11, 2009 at 12:30 AM, Kermit Mei kermit@gmail.com wrote:
   Dear all,
  I'm a newbie for python, and I write a program to test how to
   implement a class:
  
   #!/usr/bin/env
   python
  
   class Test:
  'My Test class'
  def __init__(self):
  self.arg1 = 1
  
  def first(self):
  return self.arg1
  
   t1 = Test
 
  You missed the parentheses to call the constructor. That line should be:
 
  t1 = Test()
 
  Cheers,
  Chris
 
 
  Yes, that can run. But If I put the following code into Test.py :
  #!/usr/bin/env python   |
 |
  class Test: |
 'My Test class' |
 def __init__(self): |
 self.arg1 = 1   |
 |
 def first(self):|
 return self.arg1|
 |
 def setFirst(self,value = 5):   |
 self.arg1 = value
 
  But when I want to run it as a module, something also be wrong:
 
  $ python
  Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41)
  [GCC 4.3.3] on linux2
  Type help, copyright, credits or license for more information.
  import Test
  t1 = Test()
  Traceback (most recent call last):
   File stdin, line 1, in module
  TypeError: 'module' object is not callable
 
 You've imported the module `Test`, whose name is determined by the
 filename (Test.py).
 To access the class of the same name (`Test`) that is defined in the
 module, you need to use the dot operator:
 
  import Test
  t1 = Test.Test()
 
 You should probably use different names for the module/file and the
 class to avoid confusion.
 Unlike Java, Python does not observe a direct correspondence between
 filenames and classes.
 
 Cheers,
 Chris
 --

Oh, yep! 
Thanks, Cheers.

Can you tell me how can I write __init__.py for modules:

I have a directory like this:
$ tree
.
`-- main
|-- MyTestModules
|   |-- Test1.py
|   `-- Test2.py
`-- main.py

2 directories, 3 files


In main.py, I want to run the following code:

#!/usr/bin/env python

import MyTestModules

t1 = Test1()
t2 = Test2()

print t1.first()
print t2.first()

###
The classes Test1 and Test2 just be similar with the Test that I showed
before. To run main.py correct, how can I orgnize the code under
directory MyTestModules. (May need a __init__.py file under
MyTestModules, but I don't know how to write it)


Thank you,very much!
Regards
Kermit





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


Re: Q on explicitly calling file.close

2009-09-11 Thread Gabriel Genellina
En Thu, 10 Sep 2009 08:26:16 -0300, David C. Ullrich  
dullr...@sprynet.com escribió:

On Wed, 9 Sep 2009 15:13:49 -0700 (PDT), r rt8...@gmail.com wrote:

On Sep 9, 4:19 pm, Charles Yeomans char...@declaresub.com wrote:



I removed the except block because I prefer exceptions to error codes.


how will the caller know an exception has occurred? What if logic
depends on the validation that a file *had* or *had not* been written
too, huh?

Oh I see! But what happens if the filename does not exist? What then?
open will blow chucks thats what! Here is a version for our paranoid-
schizophrenic-sadomasochist out there...


Well first, we agree that putting the open() in the try part of a
try-finally is wrong. try-finally is supposed to ensure that
_allocated_ resources are cleaned up.

What you do below may work. But it's essentially throwing
out exception handling and using error codes instead. There
are plenty of reasons why exceptions are preferred. The
standard thing is this:

def UseResource(rname):
  r = get(rname)
  try:
r.use()
  finally
r.cleanup()


And it is so widely used that it got its own syntax (the with statement)  
and library support (contextlib, for creating custom context managers). In  
any decent version of Python this idiom becomes:


with get(rname) as r:
  r.use

assuming get(rname) returns a suitable object (that defines __enter__ and  
__exit__)



def egor_read_file(fname, mode='rb'):
   print 'yes, master'
   try:
f = open(fname, mode=mode)
   except IOError:
   return (0, 'But, the file no open master!')

   try:
   s = f.read()
   except NameError:
   return (0, 'the file still no open master!')

   try:
   f.close()
   except:
   print 'That file sure is tricky master!

   return (s, 'Whew! here is the file contents, master')


What's above seems simpler. More important, if you do
it this way then you _always_ have to check the return
value of egor_read_file and take appropriate action -
complicates the code everywhere the function is called
as well as making the function more complicated.
Doing it as in UseResource() above you don't need
to worry about whether UseResource() failed
_except_ in situations where you're certain that
that's the right level to catch the error.


That's the standard argument showing why structured exceptions are a Good  
Thing. I'd say everyone should be aware of that, giving the ample usage of  
exceptions in Python, but looks like people requires a reminder from time  
to time.


--
Gabriel Genellina

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


Re: New Tkinter windows don't get focus on OS X

2009-09-11 Thread Hendrik van Rooyen
On Friday 11 September 2009 09:53:56 eb303 wrote:
 On Sep 11, 9:14 am, Hendrik van Rooyen hend...@microcorp.co.za
 wrote:

  look for widget.focus_force()
  and look for widget.grab_set_global()

 Doesn't work. BTW, forcing the focus or setting the grab globally are
 usually considered very annoying and I don't know any windowing system
 or window manager honouring those.

I have to confess I have never used the stuff - just remembered seeing it in 
the manual and pointed it out.

What does it do?

- Hendrik

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


Re: Question about unpickling dict subclass with custom __setstate__

2009-09-11 Thread Gabriel Genellina
En Thu, 10 Sep 2009 20:09:34 -0300, Matthew Wilson m...@tplus1.com  
escribió:



I subclassed the dict class and added a __setstate__ method because I
want to add some extra steps when I unpickle these entities.  This is a
toy example of what I am doing:

class Entity(dict):

def __setstate__(self, d):

log.debug(blah...)

Based on my experiments, the data in d *IS NOT* the data stored in my
instances when I do stuff like:

e = Entity()
e['a'] = 1

Instead, the stuff in d is the data stored when I do stuff like:

e.fibityfoo = 99


Yes. The dict contents are pickled directly; __getstate__ and __setstate__  
are related to the instance attributes (fibityfoo), not its contents  
(a-1).

Try defining __reduce__ or __reduce_ex__ instead.


Is there anything I have to do to make sure that my real dictionary data
is correctly reloaded during the unpickle phase?  In other words, should
I run super(Entity, self).__setstate__(d) or something like that?


That doesn't work, dict.__setstate__ doesn't even exist.

--
Gabriel Genellina

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


Re: New Tkinter windows don't get focus on OS X

2009-09-11 Thread eb303
On Sep 11, 10:40 am, Hendrik van Rooyen hend...@microcorp.co.za
wrote:
 On Friday 11 September 2009 09:53:56 eb303 wrote:

  On Sep 11, 9:14 am, Hendrik van Rooyen hend...@microcorp.co.za
  wrote:
   look for widget.focus_force()
   and look for widget.grab_set_global()

  Doesn't work. BTW, forcing the focus or setting the grab globally are
  usually considered very annoying and I don't know any windowing system
  or window manager honouring those.

 I have to confess I have never used the stuff - just remembered seeing it in
 the manual and pointed it out.

 What does it do?

At tcl level, focus_force() and grab_set_global() are translated as
options to the equivalents of focus_set() and grab_set() [1][2]. If
these are not honoured, the options are simply ignored. That's what
seems to happen on Mac OS X. So focus_force() does the same as
focus_set(), and grab_set_global() the same as grab_set(). No use for
the OP's problem...

[1] http://www.tcl.tk/man/tcl8.5/TkCmd/focus.htm
[2] http://www.tcl.tk/man/tcl8.5/TkCmd/grab.htm
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python server locks up

2009-09-11 Thread sturlamolden
On 9 Sep, 22:28, Zac Burns zac...@gmail.com wrote:

 Theories:
    Python is resizing the large dictionary
    Python is garbage collecting

Python uses reference counting, not a generational GC like Java. A
Python object is  destroyed when the refcount drops to 0. The GC only
collects cyclic references. If you create none, there are no GC delays
(you can in fact safely turn the GC off). Python does not share Java's
nasty habit of having long GC delays.

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


How can I use my modules here?

2009-09-11 Thread Kermit Mei
Hello community!

I write a modules for testing, and my code is like this(under Linux):


$ tree
.
|-- MyTestModules
|   |-- Test1.py
|   |-- Test2.py
|   `-- __init__.py
`-- main.py

1 directory, 4 files

$ find . -name '*.py' -print0|xargs -0 cat

 main.py Begin ##
#!/usr/bin/env python

from MyTestModules import Test1,Test2

t1 = Test1()
t2 = Test2()

print t1.first()
print t2.first()
 main.py  End ###

#Test1.py Begin ##
#!/usr/bin/env python

class Test1:
def first(self):
return self.arg1

#Test1.py End 

#Test1.py Begin ##
#!/usr/bin/env python

class Test2:
def first(self):
return self.arg1

#Test1.py End 

## __init__.py Begin 
#!/usr/bin/env python

## __init__.py End 


When I run the main.py, the following error takes:

$ ./main.py 
from: can't read /var/mail/MyTestModules
./main.py: line 7: syntax error near unexpected token `('
./main.py: line 7: `t1 = Test1()'




Waiting for your help.
Thanks.

Best Regards

Kermit Mei





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


Re: How can I use my modules here?

2009-09-11 Thread Chris Rebert
On Fri, Sep 11, 2009 at 2:24 AM, Kermit Mei kermit@gmail.com wrote:
 Hello community!

 I write a modules for testing, and my code is like this(under Linux):


 $ tree
 .
 |-- MyTestModules
 |   |-- Test1.py
 |   |-- Test2.py
 |   `-- __init__.py
 `-- main.py

 1 directory, 4 files

 $ find . -name '*.py' -print0|xargs -0 cat

  main.py Begin ##
 #!/usr/bin/env python

 from MyTestModules import Test1,Test2

 t1 = Test1()
 t2 = Test2()

 print t1.first()
 print t2.first()
  main.py  End ###

 #Test1.py Begin ##
 #!/usr/bin/env python

 class Test1:
    def first(self):
        return self.arg1

 #Test1.py End 

 #Test1.py Begin ##
 #!/usr/bin/env python

 class Test2:
    def first(self):
        return self.arg1

 #Test1.py End 

 ## __init__.py Begin 
 #!/usr/bin/env python

 ## __init__.py End 


 When I run the main.py, the following error takes:

 $ ./main.py
 from: can't read /var/mail/MyTestModules
 ./main.py: line 7: syntax error near unexpected token `('
 ./main.py: line 7: `t1 = Test1()'

For some reason, your Python program is being executed by bash as if
it were a shell script, which it's not.
No idea what the cause is though.

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


Re: Accessing objects at runtime.

2009-09-11 Thread Gary Duzan
In article 228b-379d-4fe4-956b-cf803541a...@37g2000yqm.googlegroups.com,
jacopo  jacopo.pe...@gmail.com wrote:
I have a  system comprising many objects cooperating with each others.
(For the time being, everything is running on the same machine, in the
same process but things might change in the future). The system starts
a infinite loop which keeps triggering operations from the
instantiated objects.

I would like to find a way to inspect the objects at run time.  In
other words I would like to check certain attributes in order to
understand in which status the object is. This of course without
having to stop the system and resume it after the checking is
finished.

   You might consider running a BaseHTTPServer in a separate thread
which has references to your objects of interest and exporting the
data through a web interface. Using a RESTful approach for mapping
URLs to objects within your system, a basic export of the data can
be as simple as printing out HTML strings with interpolated data.
(I recently did this in a couple hundred lines of code for a small
example handling a few resource types.) Fancier solutions could
pull in any of the freely available template engines or other web
framework pieces.  When you move to different processes and/or
machines, the access method can remain the same by varying the port
and/or hostname in the URL.

   Good luck...

Gary Duzan
Motorola HNM


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


Re: Why can't I run this test class?

2009-09-11 Thread Ulrich Eckhardt
Kermit Mei wrote:
 #!/usr/bin/env
 python
 
 class Test:
 'My Test class'
 def __init__(self):
 self.arg1 = 1
 
 def first(self):
 return self.arg1
 
 t1 = Test

't1' is now an alternative name for 'Test'. What you wanted instead was to
instantiate 'Test', which you do with this syntax:

 t1 = Test()


 print t1.first()

't1.first' or 'Test.first' is a function that takes a single argument (by
convention, that should be an instance of 'Test'). However, no such
instance is provided:

 TypeError: unbound method first() must be called with Test instance as
 first argument (got nothing instead)


Note that you can invoke the 'first' function in two ways:

  t1.first()
  Test.first(t1)


Uli

-- 
Sator Laser GmbH
Geschäftsführer: Thorsten Föcking, Amtsgericht Hamburg HR B62 932

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


Re: Rapid GUI Programming with Python and Qt source code

2009-09-11 Thread Steven Woody
On Thu, Sep 10, 2009 at 10:18 PM, David Boddie dbod...@trolltech.comwrote:

 On Thursday 10 September 2009, Steven Woody wrote:
  On Wed, Sep 9, 2009 at 9:33 PM, David Boddie dbod...@trolltech.com
 wrote:

   See this page for the links:
  
http://www.qtrac.eu/pyqtbook.html
 
  but the URL is not reachable from here.  is there another URL? thanks.

 Can't you access anything from qtrac.eu from where you are? Here are two
 links to archives for the Python 2.6 versions of the examples:

 http://www.qtrac.eu/pyqtbook26.tar.gz
 http://www.qtrac.eu/pyqtbook26.zip

 If you can't reach those, maybe Mark will send you the examples directly.

 David


Hi, Mark  David
I don't know the reason, but from here the site www.qtrac.eu is totally
unreachable.  So, would you please send me a file directly?

Thanks you very much!


-- 
Life is the only flaw in an otherwise perfect nonexistence
   -- Schopenhauer

narke
public key at http://subkeys.pgp.net:11371 (narkewo...@gmail.com)
-- 
http://mail.python.org/mailman/listinfo/python-list


Python 3.1 csv with gzip

2009-09-11 Thread dryfish
Python 3.1.1 doesn't seem to be happy with the use of gzip.open with
csv.reader.

Using this:

import gzip, csv, sys

data = csv.reader(gzip.open(sys.argv[1]))
for row in data:
print(row)

Will give this:

Traceback (most recent call last):
  File ./a.py, line 6, in module
for row in data:
_csv.Error: iterator should return strings, not bytes (did you open
the file in text mode?)

My work around is:

import gzip, csv, sys

def gziptext(filename):
for line in gzip.open(filename):
yield str(line, 'ascii')

data = csv.reader(gziptext(sys.argv[1]))
for row in data:
print(row)

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


Re: How can I use my modules here?

2009-09-11 Thread Albert Hopkins
On Fri, 2009-09-11 at 02:29 -0700, Chris Rebert wrote:
 For some reason, your Python program is being executed by bash as if
 it were a shell script, which it's not.
 No idea what the cause is though.

Because the first 2 bytes of the file need to be #!/path/to/interpreter,
the OP has:

 main.py Begin ##

This won't work.

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


Re: Why can't I run this test class?

2009-09-11 Thread Benjamin Kaplan
On Fri, Sep 11, 2009 at 4:01 AM, Kermit Mei kermit@gmail.com wrote:

 On Fri, 2009-09-11 at 00:43 -0700, Chris Rebert wrote:
  On Fri, Sep 11, 2009 at 12:40 AM, Kermit Mei kermit@gmail.com
 wrote:
   On Fri, 2009-09-11 at 00:33 -0700, Chris Rebert wrote:
   On Fri, Sep 11, 2009 at 12:30 AM, Kermit Mei kermit@gmail.com
 wrote:
Dear all,
   I'm a newbie for python, and I write a program to test how to
implement a class:
   
#!/usr/bin/env
python
   
class Test:
   'My Test class'
   def __init__(self):
   self.arg1 = 1
   
   def first(self):
   return self.arg1
   
t1 = Test
  
   You missed the parentheses to call the constructor. That line should
 be:
  
   t1 = Test()
  
   Cheers,
   Chris
  
  
   Yes, that can run. But If I put the following code into Test.py :
   #!/usr/bin/env python
 |
  |
   class Test: |
  'My Test class' |
  def __init__(self): |
  self.arg1 = 1   |
  |
  def first(self):|
  return self.arg1|
  |
  def setFirst(self,value = 5):   |
  self.arg1 = value
  
   But when I want to run it as a module, something also be wrong:
  
   $ python
   Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41)
   [GCC 4.3.3] on linux2
   Type help, copyright, credits or license for more information.
   import Test
   t1 = Test()
   Traceback (most recent call last):
File stdin, line 1, in module
   TypeError: 'module' object is not callable
 
  You've imported the module `Test`, whose name is determined by the
  filename (Test.py).
  To access the class of the same name (`Test`) that is defined in the
  module, you need to use the dot operator:
 
   import Test
   t1 = Test.Test()
 
  You should probably use different names for the module/file and the
  class to avoid confusion.
  Unlike Java, Python does not observe a direct correspondence between
  filenames and classes.
 
  Cheers,
  Chris
  --

 Oh, yep!
 Thanks, Cheers.

 Can you tell me how can I write __init__.py for modules:

 I have a directory like this:
 $ tree
 .
 `-- main
|-- MyTestModules
|   |-- Test1.py
|   `-- Test2.py
`-- main.py

 2 directories, 3 files


 In main.py, I want to run the following code:

 #!/usr/bin/env python

 import MyTestModules

 t1 = Test1()
 t2 = Test2()

 print t1.first()
 print t2.first()

 ###
 The classes Test1 and Test2 just be similar with the Test that I showed
 before. To run main.py correct, how can I orgnize the code under
 directory MyTestModules. (May need a __init__.py file under
 MyTestModules, but I don't know how to write it)


 Thank you,very much!
 Regards
 Kermit


Just make a blank file called __init__.py in MyTestModules. That's all you
need. Then, in main.py, you need to either do

import MyImportModules.Test1
t1 = MyImportModules.Test1.Test1()

or

from MyImportModules.Test1 import Test1
t1 = Test1()

Unlike C++ and Java, an import in Python does not make the other module's
stuff available in the local namespace. You only have the one extra name
(the name of the module) and everything else is stored in there. If you want
to add the new module's stuff to the local namespace, you have to do the
from ... import  This is also why you shouldn't make a separate file
for every class. You could put both Test1 and Test2 into a file called
test.py (module names in Python are usually lowercase) and then do from
MyImportModules.test import Test1, Test2





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

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


Re: How can I use my modules here?

2009-09-11 Thread Kermit Mei
On Fri, 2009-09-11 at 07:48 -0400, Albert Hopkins wrote:
 On Fri, 2009-09-11 at 02:29 -0700, Chris Rebert wrote:
  For some reason, your Python program is being executed by bash as if
  it were a shell script, which it's not.
  No idea what the cause is though.
 
 Because the first 2 bytes of the file need to be #!/path/to/interpreter,
 the OP has:
 
  main.py Begin ##
 
 This won't work.

Yep, Thanks!

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


Download and save a picture - urllib

2009-09-11 Thread mattia
Hi all, in order to download an image. In order to correctly retrieve the 
image I need to set the referer and handle cookies.

opener = urllib.request.build_opener(urllib.request.HTTPRedirectHandler
(), urllib.request.HTTPCookieProcessor())
urllib.request.install_opener(opener)
req = urllib.request.Request(http://myurl/image.jpg;)
req.add_header(Referer, http://myulr/referer.jsp;)
r = urllib.request.urlopen(req)
with open(image.jpg, w ) as fd:
print(r.read(), file=fd)

I'm not able to correctly save the image. In fact it seems that it it 
saved in hex format. Any suggestion?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Help with cumulative sum

2009-09-11 Thread Giacomo Boffi
Maggie la.f...@gmail.com writes:

 [...]
 else:
print 'The loop is finito'

do you know of it.comp.lang.python?

-- 
Sarebbe essere un atto di pieta'. 
Contro i miei principi.-- whip,  in IFMdI
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: IDE for python similar to visual basic

2009-09-11 Thread Nobody
On Mon, 07 Sep 2009 23:56:17 +, Albert van der Horst wrote:

The main advantage of a GUI builder is that it helps prevent you from
hard-coding the GUI into the program. You could get the same effect by
coding a UIL/XRC/etc file manually, but a GUI builder tends to force it.
 
 A GUI builder results in hard coding the GUI. The code only resides
 elsewhere.

Data (e.g. a UIL or XRC file) isn't code.

But hard-coding is more a question of whether you can realistically
change the data without changing the code. If the code craps out due to
minor changes to the data, there isn't much advantage of having a separate
data file.

Creating a GUI programmatically is almost always the wrong approach. It
tends to be adopted due to a path of least resistance, rather than any
affirmative reason.
 
 In view of the above this is not quite the correct way to put it.
 
 What I resent is that it leads to a non-professional attitude
 of the graphical part. Programming is over, lets now kludge
 some screens together. No. The graphics part has to be carefully
 designed, carefully tested, and carefully written, even if it
 is using a graphical tool. So, yes please, *do* create a GUI
 programmatically.

My view is that the program should provide functionality without
unnecessarily dictating the way in which that functionality is used.
Essentially, it's an issue of loose coupling.

The interface really should be configurable by the user according to their
needs. The code doesn't need to *know* the position or dimensions of
a widget, or its label or colour or spacing, let alone dictate them.

In most cases, the code shouldn't even get to dictate that specific
widgets even exist. Rather, it should provide actions which can
be bound to buttons, menu items and/or accelerators as the user chooses.

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


Re: IDE for python similar to visual basic

2009-09-11 Thread Nobody
On Mon, 07 Sep 2009 18:04:40 -0700, r wrote:

 It also allows the GUI to be edited by without requiring any programming
 knowledge. This eliminates the need for the GUI designer to be familiar
 with the programming language used (or any programming language), and
 allows customisation by end users.
 
 and this is why M$ interfaces suck eggs! This whole let's just slap
 together something that works even if kludgy attitude begets the
 horrible UI's of which i speak. Are you saying that programmers have
 no ability to design elegant UI's? Or are you saying GUI's are not
 *that* important?

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.


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


Re: IDE for python similar to visual basic

2009-09-11 Thread r
On Sep 11, 7:08 am, Nobody nob...@nowhere.com wrote:
(snip)
 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? Sounds like somebody failed to get input
from their users at design time. Or somebody has the inability to
relate to their end users. However i know some out there like the
styles and skins crap, which is a different animal altogether than
what you speak of.

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!!

Only qualified persons should fix cars, same for software!

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


ANN: warehouse Objects in SQLite : y_serial module

2009-09-11 Thread code43
Module download at SourceForge http://yserial.sourceforge.net

Serialization + persistance :: in a few lines of code, compress and
annotate Python objects into SQLite; then later retrieve them
chronologically by keywords without any SQL. Most useful standard
module for a database to store schema-less data.

The module is instructive in the way it unifies the standard
batteries: sqlite3 (as of Python v2.5), zlib (for compression), and
cPickle (for serializing objects).

If your Python program requires data persistance, then y_serial is a
module which should be worth importing. All objects are warehoused in
a single database file in the most compressed form possible. Tables
are used to differentiate projects. Steps for insertion, organization
by annotation, and finally retrieval are amazingly simple...

y_serial.py module :: warehouse Python objects with SQLite
http://yserial.sourceforge.net

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


Re: IDE for python similar to visual basic

2009-09-11 Thread Brendon Wickham


 The interface really should be configurable by the user according to their
 needs. The code doesn't need to *know* the position or dimensions of
 a widget, or its label or colour or spacing, let alone dictate them.


Perhaps...but the user needs a framework in order to understand the
functions they find themselves in charge of once they've initiated a
program. As the designer, the programmer is best placed to provide
that framework, because they know, or they should know, what it is
(something I don't think can be taken for granted). Therefore,
fundamental decisions about the UI should be left to the programmer.
If customisation is possible, all well and good, but it should not be
the main goal of a UI. Usability principles should be.

 In most cases, the code shouldn't even get to dictate that specific
 widgets even exist. Rather, it should provide actions which can
 be bound to buttons, menu items and/or accelerators as the user chooses.


That would be an API.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: An assessment of the Unicode standard

2009-09-11 Thread r
On Sep 10, 8:43 pm, Jan Claeys use...@janc.be wrote:

 Maybe we should use a language that has a Turing-complete grammar, so
 that even computers can understand  speak it easily?

Interesting, i do find some things more easily explainable using code,
however, code losses the ability to describe abstract ideas and such.
But you have piqued my interest...?

--
def get_enlightened():
  import webbrowser
  webbrowser.open('http://jjsenlightenments.blogspot.com/')
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: IDE for python similar to visual basic

2009-09-11 Thread David Smith
r wrote:
 On Sep 11, 7:08 am, Nobody nob...@nowhere.com wrote:
 (snip)
 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? Sounds like somebody failed to get input
 from their users at design time. Or somebody has the inability to
 relate to their end users. However i know some out there like the
 styles and skins crap, which is a different animal altogether than
 what you speak of.
 
 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!!
 
 Only qualified persons should fix cars, same for software!
 

Speaking for backyard mechanics everywhere, I sometimes want the
screwdriver. :-)

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


Re: Python 3.1 csv with gzip

2009-09-11 Thread Stefan Behnel
dryfish wrote:
 Python 3.1.1 doesn't seem to be happy with the use of gzip.open with
 csv.reader.
 
 Using this:
 
 import gzip, csv, sys
 
 data = csv.reader(gzip.open(sys.argv[1]))
 for row in data:
 print(row)
 
 Will give this:
 
 Traceback (most recent call last):
   File ./a.py, line 6, in module
 for row in data:
 _csv.Error: iterator should return strings, not bytes (did you open
 the file in text mode?)

See codecs.EncodedFile().

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


Execution order

2009-09-11 Thread DarkBlue
Here is some code from a pyqt4.5.4  application on python 2.6

def findData(self):

  self.ui.label.setText('Processing... ')

  # here we do something which takes a few seconds
  self.refreshGrid()



The problem is that the text in the self.ui.label  is only changed
on screen after the self.refreshGrid() has finished executing
rather than before.

How do I achieve the expected result ?

Thanks
Db



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


Iterating Through Dictionary of Lists

2009-09-11 Thread JB
I have created a small program that generates a project tree from a
dictionary. The dictionary is of key/value pairs where each key is a
directory, and each value is a list. The list have unique values
corresponding to the key, which is a directory where each value in the
list becomes a subdirectory.

The question that I have is how to do this process if one of the
unique values in the list is itself a dict. For example, in the
projdir dict below, suppose the Analysis value in the list
corresponding to the Engineering key was itself a dict and was
assigned {'Analysis' : 'Simulink'} for example.

Thanks.
James


#-
# DEFINE Root Dir  Path, Sch Numbers
#-
sch_names = ['AED500','AED600']
dir_main  = Z:\\ABC_PROJ\\
dir_sub   = PCB_MDX\\
rootdir   = dir_main + dir_sub
#-
# DEFINE Directory Tree for Project
#-
projdir =  {'Project':  ['Schedule', 'Specifications',
'Procedures'],
'Schematics_PCB' :  ['SCH','BOM','ASSY'],
'Drawings'   :  ['System', 'Board', 'Packaging_3D'],
'Engineering':  ['Analysis', 'Reports', 'Design Reviews']}
#-
# DEFINE Debug Status
#-
debug = True
#-
# Print Directory Path (Helper Func)
#-
def print_path(z,suffix):
print z
print z + suffix
#-
# Make a Directory Project Tree
#-
def make_tree_with_debug(proj,sch,root):
counter = 0
print The dictionary was found to have the following: \n

#-
# Iterate over items in the dictionary, creating tuples of key/value
pairs

#-
for key, values in proj.iteritems():
counter = counter + 1
print Key # + str(counter) +  is   + ' + key + \'
print For this key, the values are  + str(values)
print Thus, the results of generating directories for this key/
values combo are: \n
#-
# Iterate over the invidividual unique values in the list
# that is associated with each key in the dict
#-
for unique in values:
prefix = root + key +  \\ + unique
suffix = \\Previous \n
if key == 'Schematics_PCB':
print unique
for item in sch:
z = prefix + \\ + item
print_path(z,suffix)
else:
#if unique.haskeys():
#   print unique.key
z = prefix
print_path(z,suffix)


make_tree_with_debug(projdir,sch_names,rootdir)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: IDE for python similar to visual basic

2009-09-11 Thread Kevin Walzer

On 8/30/09 1:48 PM, r wrote:



Hello qwenbsp;rty,

I remember my first days with GUI programming and thinking to myself;
how on earth can i write GUI code without a MS style GUI builder? Not
to long after that i was coding up some pretty spectacular GUI's from
nothing more than source code and loving it.

[Warning: the following is only opinion!]
I think a point and click GUI builder (although some may disagree) is
actually detrimental to your programming skills. The ability to
visualize the GUI only from the source code as you read it, is as
important to a programmer as site reading sheet music is to a
musician. And I like to program with the training wheels off.


Whether done in code or with a visual tool, good, effective GUI design 
is not easy. However you get there is up to you. In my case (using 
Tkinter), I've found that it's faster and better to write the code by 
hand. Code in the text editor, the terminal for testing: simple and 
easy. Adding another tool to the mix just makes things more complicated. 
:-) Some may find it's easier to use a GUI builder, and if that's the 
case, some good ones have been recommended.


shameless plug
In case anyone thinks the words Tkinter and good, effective GUI 
design shouldn't be in the same paragraph, please see 
http://www.codebykevin.com/phynchronicity.html...

/shameless plug

--
Kevin Walzer
Code by Kevin
http://www.codebykevin.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: Execution order

2009-09-11 Thread Diez B. Roggisch
DarkBlue wrote:

 Here is some code from a pyqt4.5.4  application on python 2.6
 
 def findData(self):
 
   self.ui.label.setText('Processing... ')
 
   # here we do something which takes a few seconds
   self.refreshGrid()
 
 
 
 The problem is that the text in the self.ui.label  is only changed
 on screen after the self.refreshGrid() has finished executing
 rather than before.
 
 How do I achieve the expected result ?

You can make Qt process all pending events once, via
QCoreApplication.processEvents.

This should trigger the redraw.

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


Re: Iterating Through Dictionary of Lists

2009-09-11 Thread Stefan Behnel
JB wrote:
 I have created a small program that generates a project tree from a
 dictionary. The dictionary is of key/value pairs where each key is a
 directory, and each value is a list. The list have unique values
 corresponding to the key, which is a directory where each value in the
 list becomes a subdirectory.
 
 The question that I have is how to do this process if one of the
 unique values in the list is itself a dict. For example, in the
 projdir dict below, suppose the Analysis value in the list
 corresponding to the Engineering key was itself a dict and was
 assigned {'Analysis' : 'Simulink'} for example.

You might want to read up on recursion, i.e. a function calling itself.

You can find out if something is a dict like this:

isinstance(x, dict)

or, if you know it really is a dict and not a subtype:

type(x) is dict

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


Re: Some issue with easy_install and PIL/Imaging

2009-09-11 Thread Chris Withers

Klein Stéphane wrote:

Resume :
1. first question : why PIL package in pypi don't work ?


Because Fred Lundh have his package distributions unfortunate names that 
setuptools doesn't like...



2. second question : when I add PIL dependence in my setup.py and I do
   python setup.py develop, I've this error :
   error: Could not find required distribution Imaging.
   Why ?


See above.


Now, I add --find-links parameter to easy_install :


If you google harder, you'll find there are packagings of PIL that do 
work with setuptools...


Chris

--
Simplistix - Content Management, Batch Processing  Python Consulting
   - http://www.simplistix.co.uk
--
http://mail.python.org/mailman/listinfo/python-list


Re: Execution order

2009-09-11 Thread DarkBlue
On Sep 11, 9:34 pm, Diez B. Roggisch de...@nospam.web.de wrote:
 DarkBlue wrote:
  Here is some code from a pyqt4.5.4  application on python 2.6

  def findData(self):

        self.ui.label.setText('Processing... ')

        # here we do something which takes a few seconds
        self.refreshGrid()

  The problem is that the text in the self.ui.label  is only changed
  on screen after the self.refreshGrid() has finished executing
  rather than before.

  How do I achieve the expected result ?

 You can make Qt process all pending events once, via
 QCoreApplication.processEvents.

 This should trigger the redraw.

 Diez

Thanks ! That helped. :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: urlopen error (11001, 'getaddrinfo failed')

2009-09-11 Thread Chris Withers

open...@hushmail.com wrote:

fs = cgi.FieldStorage()
url = fs.getvalue('url', http://www.openlayers.org;)
try:


insert a print url here...


y = urllib2.urlopen(url)
print y.read()


This script produces the urlopen error (11001, 'getaddrinfo 
failed'). 


This is a name lookup failing, whatever you're ending up with in url is 
either incorrect or the dns config of the server it's pointing at is 
incorrect...


Chris

--
Simplistix - Content Management, Batch Processing  Python Consulting
   - http://www.simplistix.co.uk
--
http://mail.python.org/mailman/listinfo/python-list


Re: HTTP POST File without cURL

2009-09-11 Thread John Giotta
Is there a verbose feature for urllib2.urlopen?

Here is my python snippet for posted the file:

req = urllib2.Request(url='https://%s%s' % (host, selector),
data=open('test.zip', 'rb').read())
req.add_header('content-type', 'application/zip')
req.add_header('Authorization', 'Basic %s' % self.auth)
#req.add_header('content-length', str(len(body)))
print req.headers
u = urllib2.urlopen(req)
-- 
http://mail.python.org/mailman/listinfo/python-list


Podcast catcher in Python

2009-09-11 Thread Chuck
Hi all,

I would like to code a simple podcast catcher in Python merely as an
exercise in internet programming.  I am a CS student and new to
Python, but understand Java fairly well.  I understand how to connect
to a server with urlopen, but then I don't understand how to download
the mp3, or whatever, podcast?  Do I need to somehow parse the XML
document?  I really don't know.  Any ideas?

Thanks!

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


Re: Podcast catcher in Python

2009-09-11 Thread Chuck
Also, if anyone could recommend some books that cover this type of
programming, I would greatly appreciate it.

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


Use python to execute a windows program

2009-09-11 Thread Doran, Harold
Dear list:

My question is conceptual at the moment.

Current problem:

I have a windows-based program that reads in a file and from that file
generates data that is saved to a file.

The way we do this now is a person sits in front of their machine and
proceeds as follows:

1) Open windows program
2) Click file - open which opens a dialog box
3) Locate the file (which is a text file) click on it and let the
program run.

This would be no problem if we did this for a small number of files.
But, we repeat this process for a few hundred files. So, the human is
sitting in front of the machine repeating this process for days until we
have all data generated.

Question:

Is it possible to write a python script that would automate this process
such that it could interact with the windows program, loop through all
of the text files in a directory rather than the human repeating this
process for days.

I have sued python quite a bit to parse XML and text files, but I have
never used it such that it would interact with a program designed to
work in windows. So, I'm not sure if such a problem is conceptually
possible.

I wish I could provide minimal commented code, but I am not sure where
to even start with this problem other than to first ask if it is
conceptually possible.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Use python to execute a windows program

2009-09-11 Thread Simon Brunning
2009/9/11 Doran, Harold hdo...@air.org:
 The way we do this now is a person sits in front of their machine and
 proceeds as follows:

 1) Open windows program
 2) Click file - open which opens a dialog box
 3) Locate the file (which is a text file) click on it and let the
 program run.

It might very well be possible, depending upon how the program you
want to automate has been written.

First, make sure, absolutely sure, that's there's no proper
automation option available - a command line version, COM automation,
that kind of thing. These approaches are very much easier than GUI
automation.

If none of these options are available, http://pywinauto.openqa.org/
is probably what you need.

-- 
Cheers,
Simon B.
-- 
http://mail.python.org/mailman/listinfo/python-list


how to return value from button clicked by python

2009-09-11 Thread chen tao
Hi,
 I have several buttons, I want to realize: when I click first
button, the button will call a function, and the function should
return some parameter value, because I need this value for the other
buttons.
I tried the button.invoke() function, it almost got it...however,
I only want it returns value when the button clicked, but because the
program is in the class _ini_ function, so it always runs once before
I click the button...
Any one can give me some suggestions?
My scripts is like this:
def call1():

 return para

def app():
...
class GUI():
  def __init__(self,parent = None):
 
 B1 = Button(self.master, text ='browse...', command = call1)
 B1.grid(row=len(self.user_input_index),column = 3,sticky=W)
 print self.B1.invoke()
 call2 = lambda: app(self.B1.invoke())
 B2 = Button(self.master, text ='browse...',command = call2)
-- 
http://mail.python.org/mailman/listinfo/python-list


Message box always appears on 2nd monitor

2009-09-11 Thread ed

No matter what I do, the MessageBox always appears on the 2nd monitor.
I've forced all the other widgets to monitor 1.
I thought that creating a class and forcing the position would help, but 
it hasn't.


I'm using Ubuntu Jaunty, python 2.6.

Any ideas what I can do to force widgets to a specific monitor?

Thank you.

class ConnectErrorMsgBox( wx.Frame ):
def __init__( self ):
wx.Frame.__init__(self,None, -1, '', pos=(0,0) )
self.SetPosition( (0, 0) )
wx.MessageBox(message='Connect Error',
 caption='Status',
 style=wx.OK | wx.ICON_EXCLAMATION| wx.CENTER,
 x=0, y=0)
--
http://mail.python.org/mailman/listinfo/python-list


Re: [Guppy-pe-list] An iteration idiom (Was: Re: loading files containing multiple dumps)

2009-09-11 Thread Chris Withers

Sverker Nilsson wrote:

If you just use heap(), and only want total memory not relative to a
reference point, you can just use hpy() directly. So rather than:

CASE 1:

h=hpy()
h.heap().dump(...)
#other code, the data internal to h is still around
h.heap().dump(...)

you'd do:

CASE 2:

hpy().heap().dump(...)
#other code. No data from Heapy is hanging around
hpy().heap().dump(...)

The difference is that in case 1, the second call to heap() could reuse
the internal data in h, 


But that internal data would have to hang around, right? (which might, 
in itself, cause memory problems?)



whereas in case 2, it would have to be recreated
which would take longer time. (The data would be such things as the
dictionary owner map.)


How long is longer? Do you have any metrics that would help make good 
decisions about when to keep a hpy() instance around and when it's best 
to save memory?



Do you mean we should actually _remove_ features to create a new
standalone system?

Absolutely, why provide more than is used or needed?


How should we understand this? Should we have to support 2 or more
systems depending on what functionality you happen to need? Or do
you mean most functionality is actually _never_ used by
_anybody_ (and will not be in the future)? That would be quite gross
wouldn't it.


I'm saying have one project and dump all the excess stuff that no-one 
but you uses ;-)


Or, maybe easier, have a core, separate, package that just has the 
essentials in a simply, clean fashion and then another package that 
builds on this to add all the other stuff...



It also gives as an alternative, If this is not possible, a string of
the form ...some useful description... should be returned

The __repr__ I use don't have the enclosing , granted, maybe I missed
this or it wasn't in the docs in 2005 or I didn't think it was important
(still don't) but was that really what the complain was about?


No, it was about the fact that when I do repr(something_from_heapy) I 
get a shedload of text.



I thought it was more useful to actually get information of what was
contained in the object directly at the prompt, than try to show how to
recreate it which wasn't possible anyway.


Agreed, but I think the stuff you currently have in __repr__ would be 
better placed in its own method:


 heap()
IdentitySet object at 0x containing 10 items
 _.show()
... all the current __repr__ output

That should have another name... I don't know what a partition or 
equivalence order are in the contexts you're using them, but I do know 
that hijacking __getitem__ for this is wrong.


Opinions may differ, I'd say one can in principle never 'know' if such a
thing is 'right' or 'wrong', but that gets us into philosophical territory. 
Anyway...


I would bet that if you asked 100 experienced python programmers, most 
of them would tell you that what you're doing with __getitem__ is wrong, 
some might even say evil ;-)



To get a tutorial provided by someone who did not seem to share your
conviction about indexing, but seemed to regard the way Heapy does it natural
(although has other valid complaints, though it is somewhat outdated i.e.
wrt 64 bit) see:

http://www.pkgcore.org/trac/pkgcore/doc/dev-notes/heapy.rst


This link has become broken recently, but I don't remember reading the 
author's comments as liking the indexing stuff...


Chris

--
Simplistix - Content Management, Batch Processing  Python Consulting
   - http://www.simplistix.co.uk
--
http://mail.python.org/mailman/listinfo/python-list


Re: Podcast catcher in Python

2009-09-11 Thread Falcolas
On Sep 11, 8:20 am, Chuck galois...@gmail.com wrote:
 Hi all,

 I would like to code a simple podcast catcher in Python merely as an
 exercise in internet programming.  I am a CS student and new to
 Python, but understand Java fairly well.  I understand how to connect
 to a server with urlopen, but then I don't understand how to download
 the mp3, or whatever, podcast?  Do I need to somehow parse the XML
 document?  I really don't know.  Any ideas?

 Thanks!

 Chuck

You will first have to download the RSS XML file, then parse that file
for the URL for the audio file itself. Something like eTree will help
immensely in this part. You'll also have to keep track of what you've
already downloaded.

I'd recommend taking a look at the RSS XML yourself, so you know what
it is you have to parse out, and where to find it. From there, it
should be fairly easy to come up with the proper query to pull it
automatically out of the XML.

As a kindness to the provider, I would recommend a fairly lengthy
sleep between GETs, particularly if you want to scrape their back
catalog.

Unfortunately, I no longer have the script I created to do just such a
thing in the past, but the process is rather straightforward, once you
know where to look.

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


Re: Multiple inheritance - How to call method_x in InheritedBaseB from method_x in InheritedBaseA?

2009-09-11 Thread Scott David Daniels

The Music Guy wrote:
...


def main():
...

class MyMixin(object):

This is a mistake.  If Mixins inherit from CommonBase as well, no
order of class definition can catch you out.
If it doesn't, you can get yourself in trouble.


def method_x(self, a, b, c):
super(MyMixin, self).method_x(a, b, c)
print MyMixin.method_x(%s, %s, %s, %s) % (repr(self),
repr(a), repr(b), repr(c))

class CommonBase(object):
def method_x(self, a, b, c):
print CommonBase.method_x(%s, %s, %s, %s) % (repr(self),
repr(a), repr(b), repr(c))

class BaseA(CommonBase):
...


Redoing this example for small prints:

def main():
for n, class_ in enumerate(
(BaseA, BaseB, BaseC,
 FooV, FooW, FooX, FooY, FooZ,
 BarW, BarX, BarY, BarZ)):
instance = class_()
instance.method_x(n, n * '-', hex(n*13))
print

class CommonBase(object):
def method_x(self, a, b, c):
# really, %r is the way to go.
print CommonBase.method_x(%r, %r, %r, %r) % (self, a, b, c)

def __repr__(self):
# Just so we have a more compact repr
return '%s.%s' % (self.__class__.__name__, id(self))

class Mixin(CommonBase):
def method_x(self, a, b, c):
super(Mixin, self).method_x(a, b, c)
print Mixin,

class MyMixin(CommonBase):
def method_x(self, a, b, c):
super(MyMixin, self).method_x(a, b, c)
print MyMixin,

class BaseA(CommonBase):
def method_x(self, a, b, c):
super(BaseA, self).method_x(a, b, c)
print BaseA,

class BaseB(CommonBase):
def method_x(self, a, b, c):
super(BaseB, self).method_x(a, b, c)
print BaseB,

class BaseC(CommonBase):
pass

class FooV(Mixin, BaseA):
def method_x(self, a, b, c):
super(FooV, self).method_x(a, b, c)
print FooV,

class FooW(Mixin, MyMixin, BaseA):
def method_x(self, a, b, c):
super(FooW, self).method_x(a, b, c)
print FooW,

class FooX(MyMixin, BaseA):
def method_x(self, a, b, c):
super(FooX, self).method_x(a, b, c)
print FooX,

class FooY(MyMixin, BaseB):
pass

class FooZ(MyMixin, BaseC):
def method_x(self, a, b, c):
super(FooZ, self).method_x(a, b, c)
print FooZ,

class BarW(Mixin, BaseA, MyMixin):
def method_x(self, a, b, c):
super(BarW, self).method_x(a, b, c)
print BarW,

class BarX(BaseA, MyMixin):
def method_x(self, a, b, c):
super(BarX, self).method_x(a, b, c)
print BarX,

class BarY(BaseB, MyMixin):
def method_x(self, a, b, c):
super(BarY, self).method_x(a, b, c)
print BarY,

class BarZ(BaseB, Mixin):
def method_x(self, a, b, c):
super(BarZ, self).method_x(a, b, c)
print BarZ,


 main() # prints
CommonBase.method_x(BaseA.18591280, 0, '', '0x0')
BaseA
...
CommonBase.method_x(FooZ.18478384, 7, '---', '0x5b')
MyMixin FooZ
CommonBase.method_x(BarW.18480592, 8, '', '0x68')
MyMixin BaseA Mixin BarW
...


If you make of Mixin and MyMixin inherit from object you get:

CommonBase.method_x(BaseA.18613328, 0, '', '0x0')
BaseA
...
CommonBase.method_x(FooZ.18480592, 7, '---', '0x5b')
MyMixin FooZ
CommonBase.method_x(BarW.18591280, 8, '', '0x68')
BaseA Mixin BarW
...

Note that in the BarW case (with object), not all mixins are called.

--Scott David Daniels
scott.dani...@acm.org
--
http://mail.python.org/mailman/listinfo/python-list


Re: How can I use my modules here?

2009-09-11 Thread Diez B. Roggisch
Chris Rebert wrote:

 On Fri, Sep 11, 2009 at 2:24 AM, Kermit Mei kermit@gmail.com wrote:
 Hello community!

 I write a modules for testing, and my code is like this(under Linux):


 $ tree
 .
 |-- MyTestModules
 | |-- Test1.py
 | |-- Test2.py
 | `-- __init__.py
 `-- main.py

 1 directory, 4 files

 $ find . -name '*.py' -print0|xargs -0 cat

  main.py Begin ##
 #!/usr/bin/env python

 from MyTestModules import Test1,Test2

 t1 = Test1()
 t2 = Test2()

 print t1.first()
 print t2.first()
  main.py  End ###

 #Test1.py Begin ##
 #!/usr/bin/env python

 class Test1:
 def first(self):
 return self.arg1

 #Test1.py End 

 #Test1.py Begin ##
 #!/usr/bin/env python

 class Test2:
 def first(self):
 return self.arg1

 #Test1.py End 

 ## __init__.py Begin 
 #!/usr/bin/env python

 ## __init__.py End 


 When I run the main.py, the following error takes:

 $ ./main.py
 from: can't read /var/mail/MyTestModules
 ./main.py: line 7: syntax error near unexpected token `('
 ./main.py: line 7: `t1 = Test1()'
 
 For some reason, your Python program is being executed by bash as if
 it were a shell script, which it's not.
 No idea what the cause is though.

The first comment line must go - it must be the shebang instead.

http://en.wikipedia.org/wiki/Shebang_(Unix)


Diez

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


string interpolation mystery in Python 2.6

2009-09-11 Thread Alan G Isaac

MYSTERY: how can %s%error be different from %s%str(error) in Python 2.6?

APOLOGY: I tried to strip this down, but could not find a simple way to
reproduce the problem.  This way works, however.  (There is a discussion on
the docutils-develop list.)  Although there are several steps, we are talking
about less than 5 minutes to document the puzzle.  Please use the specific
revision (or earlier) in the directions, as later revisions implement a
work around.

1. Check out revision 6121 from docutils
http://docutils.sourceforge.net/docs/dev/repository.html

2. Install docutils under Python 2.6

3. Process the file below [1]_ using the rst2html.py script
(found in Python26/Scripts on Windows platforms)

4. Note the IOError::

temp.rst:: (SEVERE/4) Problems with include directive path:
IOError: (2, 'No such file or directory').
Exiting due to level-4 (SEVERE) system message.

5. Make the following change and *no other* changes:
In docutils/parsers/rst/directives/misc.py (line 66-67) change ::

raise self.severe('Problems with %s directive path:\n%s: %s.'
  % (self.name, error.__class__.__name__, error))

to ::

raise self.severe('Problems with %s directive path:\n%s: %s.'
  % (self.name, error.__class__.__name__, 
str(error)))

6. Process the same file the same way. Note the change in the IOError::

temp.rst:: (SEVERE/4) Problems with include directive path:
IOError: [Errno 2] No such file or directory: 'doesnotexist.rst'.
Exiting due to level-4 (SEVERE) system message.

7. Try this again in Python 2.5.  The correct (filename reported) error report
is produced both times.  So this is a Python 2.6 change.


Clues?  Bug or feature?

I'm going to hazard a guess that there was an undocumented (in What's New) 
change
to the __unicode__ method of BaseException.

Thanks,
Alan Isaac

.. [1] Following is the rst file to process:


Test


This is just a test.

.. include:: doesnotexist.rst

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


Re: Use python to execute a windows program

2009-09-11 Thread Alan G Isaac

Does the Windows application offer a COM interface?
http://oreilly.com/catalog/pythonwin32/chapter/ch12.html
http://sourceforge.net/projects/pywin32/

Alan Isaac

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


Re: Message box always appears on 2nd monitor

2009-09-11 Thread Sean DiZazzo
On Sep 11, 8:27 am, ed e...@nospam.net wrote:
 No matter what I do, the MessageBox always appears on the 2nd monitor.
 I've forced all the other widgets to monitor 1.
 I thought that creating a class and forcing the position would help, but
 it hasn't.

 I'm using Ubuntu Jaunty, python 2.6.

 Any ideas what I can do to force widgets to a specific monitor?

 Thank you.

 class ConnectErrorMsgBox( wx.Frame ):
      def __init__( self ):
          wx.Frame.__init__(self,None, -1, '', pos=(0,0) )
          self.SetPosition( (0, 0) )
          wx.MessageBox(message='Connect Error',
                       caption='Status',
                       style=wx.OK | wx.ICON_EXCLAMATION| wx.CENTER,
                       x=0, y=0)

Did you try making the message box a child of whatever window called
it?  ie.  Pass in the parent= attribute.

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


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

2009-09-11 Thread joy99
Dear Group,

I am trying to download the following files,
a) lxml,
b) numpy,
c) scipy, and
d) django.

I am trying to include them in C\python26\Lib

But they are giving error report, as I am trying to use them by
importing.

I am using IDLE as GUI, my OS is WinXP SP2, and my Python version 2.6.

If any one suggest what is the problem, I am doing?

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


RE: Use python to execute a windows program

2009-09-11 Thread Doran, Harold
I am working with this now. I'm toying with the examples to test out a
few things and learn how this works. I've made some modifications such
that I have the following working (below). This does nothing more than
open a program.

I have commented out the portion

#app.AM.MenuSelect(File-Open Database)

When it is uncommented, the program fails. However, when I tinker with
this MenuSelect() for, say, Notepad, this presents no problem and
behaves as expected. For example, the following works with notepad:

app.Notepad.MenuSelect(Help-Help Topics)

At the risk of sounding too silly, how do I know what to place after
app.??.MenuSelect? I've tried this with a few programs and the name I
use in place of ?? Doesn't seem to work.




import time
import sys

try:
from pywinauto import application
except ImportError:
import os.path
pywinauto_path = os.path.abspath(__file__)
pywinauto_path = os.path.split(os.path.split(pywinauto_path)[0])[0]
import sys
sys.path.append(pywinauto_path)
from pywinauto import application


def AM():

app = application.Application()

try:
app.start_(   # connect_(path =
urC:\Program Files\American Institutes for
Research\AMBeta\AM.exe)
except application.ProcessNotFoundError:
print You must first start Windows Media \
Player before running this script
sys.exit()

 #app.AM.MenuSelect(File-Open Database)
 

def Main():
start = time.time()

AM()

if __name__ == __main__:
Main() 

 -Original Message-
 From: simon.brunn...@gmail.com 
 [mailto:simon.brunn...@gmail.com] On Behalf Of Simon Brunning
 Sent: Friday, September 11, 2009 11:02 AM
 To: Doran, Harold
 Cc: python-list@python.org
 Subject: Re: Use python to execute a windows program
 
 2009/9/11 Doran, Harold hdo...@air.org:
  The way we do this now is a person sits in front of their 
 machine and 
  proceeds as follows:
 
  1) Open windows program
  2) Click file - open which opens a dialog box
  3) Locate the file (which is a text file) click on it and let the 
  program run.
 
 It might very well be possible, depending upon how the 
 program you want to automate has been written.
 
 First, make sure, absolutely sure, that's there's no proper
 automation option available - a command line version, COM 
 automation, that kind of thing. These approaches are very 
 much easier than GUI automation.
 
 If none of these options are available, 
 http://pywinauto.openqa.org/ is probably what you need.
 
 --
 Cheers,
 Simon B.
 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Different results for request() vs putrequest()

2009-09-11 Thread John Gordon
In h7pdan$5i...@reader1.panix.com John Gordon gor...@panix.com writes:

 According to the documentation, these two sections of code should be
 equivalent:

   conn = httplib.HTTPSConnection(host)
   conn.putrequest(POST, url)
   conn.putheader(Proxy-Authorization, myProxy)
   conn.putheader(Content-Length, %d % len(body))
   conn.endheaders()
   conn.send(body)

 vs

   headers = { Proxy-Authorization: myProxy }
   conn = httplib.HTTPSConnection(host)
   conn.request(POST, url, body, headers)

 And yet they are not.  The first section works, but I get an
 HTTP/1.1 401 Unauthorized error from the second.

To follow up my own post, this was happening because of a trailing
newline in myProxy, put there by base64.encodestring().

The newline made the server stop processing any subsequent headers.

-- 
John Gordon   A is for Amy, who fell down the stairs
gor...@panix.com  B is for Basil, assaulted by bears
-- Edward Gorey, The Gashlycrumb Tinies

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


Re: Unexpected 411 error response using httplib

2009-09-11 Thread John Gordon
In h7h963$4a...@reader1.panix.com John Gordon gor...@panix.com writes:

 As you can see, I am including the call to putheader() for Content-Length,
 and the debugging output confirms that the header is present in the outgoing
 message.

 So why am I getting a 411 Length Required error?

To follow up my own post, this was happening because of a trailing
newline in auth, put there by base64.encodestring().

The newline made the server stop processing any subsequent headers.

-- 
John Gordon   A is for Amy, who fell down the stairs
gor...@panix.com  B is for Basil, assaulted by bears
-- Edward Gorey, The Gashlycrumb Tinies

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


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

2009-09-11 Thread Diez B. Roggisch

joy99 schrieb:

Dear Group,

I am trying to download the following files,
a) lxml,
b) numpy,
c) scipy, and
d) django.

I am trying to include them in C\python26\Lib

But they are giving error report, as I am trying to use them by
importing.


What is an error report? Unless you get more specific here, nobody 
will be able to help you.


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


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

2009-09-11 Thread Robert Kern

On 2009-09-11 11:39 AM, joy99 wrote:

Dear Group,

I am trying to download the following files,
a) lxml,
b) numpy,
c) scipy, and
d) django.

I am trying to include them in C\python26\Lib

But they are giving error report, as I am trying to use them by
importing.

I am using IDLE as GUI, my OS is WinXP SP2, and my Python version 2.6.

If any one suggest what is the problem, I am doing?


Exactly what steps are you doing? Are you following the detailed installation 
instructions for each package? You cannot just download the packages and drop 
them into Lib. Exactly what errors are you seeing? Please copy-and-paste 
complete error messages; do not paraphrase.


Do one package at a time, and write to each package's mailing list if you need 
help installing that package.


--
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: urlopen error (11001, 'getaddrinfo failed')

2009-09-11 Thread opengis
Thank you for the response.  I have been using 
urllib2.urlopen(http://www.openlayers.org;), so I can rule out the 
url being incorrect.  Since my original question I can add the 
following:

1. I am not using a proxy to connect to the internet
2. I added these lines to the script:
 ...
 proxy_support = urllib2.ProxyHandler({})
 opener = urllib2.build_opener(proxy_support)
 urllib2.install_opener(opener)
 ...
   I believe this tells python not to look for a proxy server.
3. I have added http://www.openlayers.org and its ip to my windows 
hosts file
4. socket.gethostbyname produces the same 11001 error as 
urllib2.urlopen

You are spot-on suggesting a dns issue.  It seems like python 
cannot resolve hostnames when it is running in Tomcat 6.  Here is 
my Tomcat cgi config from web.xml:

servlet
servlet-namecgi/servlet-name
servlet-classorg.apache.catalina.servlets.CGIServlet/servlet-
class
init-param
param-namedebug/param-name
param-value0/param-value
/init-param
init-param
param-namecgiPathPrefix/param-name
param-valueWEB-INF/cgi/param-value
/init-param
init-param
param-nameexecutable/param-name
param-valueC:/Program 
Files/Python25/python.exe/param-value
/init-param
init-param
param-namepassShellEnviroment/param-name
param-valuetrue/param-value
/init-param
load-on-startup5/load-on-startup
/servlet

servlet-mapping
servlet-namecgi/servlet-name
url-pattern/cgi-bin/*/url-pattern
/servlet-mapping

The hostnames consistently resolve in Apache Server with the same 
script, so I don't think my dns config is wrong.  I don't have a 
local firewall, but could my network firewall be blocking python 
from takin care of business?  Can anyone share their experience or 
a link on running python in Tomcat?  

thanks again,
josh

On Fri, 11 Sep 2009 08:54:20 -0500 Chris Withers 
ch...@simplistix.co.uk wrote:
open...@hushmail.com wrote:
 fs = cgi.FieldStorage()
 url = fs.getvalue('url', http://www.openlayers.org;)
 try:

insert a print url here...

 y = urllib2.urlopen(url)
 print y.read()

 This script produces the urlopen error (11001, 'getaddrinfo 
 failed'). 

This is a name lookup failing, whatever you're ending up with in 
url is 
either incorrect or the dns config of the server it's pointing at 
is 
incorrect...

Chris

-- 
Simplistix - Content Management, Batch Processing  Python 
Consulting
- http://www.simplistix.co.uk

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


Re: [Guppy-pe-list] An iteration idiom (Was: Re: loading files containing multiple dumps)

2009-09-11 Thread Ethan Furman

Chris Withers wrote:

Sverker Nilsson wrote:


The __repr__ I use don't have the enclosing , granted, maybe I missed
this or it wasn't in the docs in 2005 or I didn't think it was important
(still don't) but was that really what the complain was about?



No, it was about the fact that when I do repr(something_from_heapy) I 
get a shedload of text.



I thought it was more useful to actually get information of what was
contained in the object directly at the prompt, than try to show how to
recreate it which wasn't possible anyway.



Agreed, but I think the stuff you currently have in __repr__ would be 
better placed in its own method:


  heap()
IdentitySet object at 0x containing 10 items


For what it's worth, the container class I wrote recently to hold dbf 
rows is along the lines of Chris' suggestion; output is similar to this:


DbfList(97 records)

or, if a description was provided at list creation time:

DbfList(State of Oregon - 97 records)

basically, a short description of what's in the container, instead of 97 
screens of gibberish (even usefull information is gibberish after 97 
screenfulls of it!-)


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


Re: Turn-based game - experimental economics

2009-09-11 Thread Paolo Crosetto
In data sabato 05 settembre 2009 21:47:41, Dennis Lee Bieber ha scritto:

 Much better to just send the token TO the active client (which is
 responsible for returning it at the end of its turn processing) 

Dennis,

I am finally getting my head round this problem. I do have a further question, 
though.

I am using XMLRPC as server. It is quite convenient since it handles all low-
level network stuff for me. On the other hand, though, it seems I cannot make 
the server actually _send_ anything to the clients; it just sits there and 
waits for calls.
This is rather inconvenient for me, as every time I need to send the clients 
some information (eg, the state of the game) I have to formulate the problem 
as a specific call from each client. This can indeed be done quite easily, but 
the end result is a staggering amount of calls to the server, and high cpu 
usage - this might as well slow down the network in the lab, I guess.

If you look at the pseudocode you sent me - and I implemented - you see, on 
the clients side, where the -- are, that a call to update is made over 
and over again.

-=-=-=-=-=- Display

connect to game
ACTIVE = False
while True:
get game data--- *
update console display  --- *
ACTIVE = game data == active token
if ACTIVE:
get user input
if user input == EndTurn:
ACTIVE = False
send user input
if user input == QUIT:
break
disconnect from game


Is there any way of telling XMLRPC 'send this and this to all clients 
connected'?
Or should I use another server-side technology? I have no much experience in 
writing network programs - this is my first - and I'd rather not go into 
complicated stuff.

Thanks!
-- 
Paolo Crosetto
-
PhD Student in Economics
DEAS - Department of Economics - University of Milan
-
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python server locks up

2009-09-11 Thread Paul Rubin
sturlamolden sturlamol...@yahoo.no writes:
 Python uses reference counting, not a generational GC like Java. A
 Python object is  destroyed when the refcount drops to 0. The GC only
 collects cyclic references. If you create none, there are no GC delays
 (you can in fact safely turn the GC off). Python does not share Java's
 nasty habit of having long GC delays.

If you drop the last reference to a large object (say a billion item
dictionary), then Python can pause for quite a long time freeing
all the constituents of that object.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Podcast catcher in Python

2009-09-11 Thread Chuck
On Sep 11, 10:30 am, Falcolas garri...@gmail.com wrote:
 On Sep 11, 8:20 am, Chuck galois...@gmail.com wrote:

  Hi all,

  I would like to code a simple podcast catcher in Python merely as an
  exercise in internet programming.  I am a CS student and new to
  Python, but understand Java fairly well.  I understand how to connect
  to a server with urlopen, but then I don't understand how to download
  the mp3, or whatever, podcast?  Do I need to somehow parse the XML
  document?  I really don't know.  Any ideas?

  Thanks!

  Chuck

 You will first have to download the RSS XML file, then parse that file
 for the URL for the audio file itself. Something like eTree will help
 immensely in this part. You'll also have to keep track of what you've
 already downloaded.

 I'd recommend taking a look at the RSS XML yourself, so you know what
 it is you have to parse out, and where to find it. From there, it
 should be fairly easy to come up with the proper query to pull it
 automatically out of the XML.

 As a kindness to the provider, I would recommend a fairly lengthy
 sleep between GETs, particularly if you want to scrape their back
 catalog.

 Unfortunately, I no longer have the script I created to do just such a
 thing in the past, but the process is rather straightforward, once you
 know where to look.

 ~G

Thanks!  I will see what I can do.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python server locks up

2009-09-11 Thread Terry Reedy

sturlamolden wrote:

On 9 Sep, 22:28, Zac Burns zac...@gmail.com wrote:


Theories:
   Python is resizing the large dictionary
   Python is garbage collecting


Python uses reference counting, not a generational GC like Java.


The CPython implementation, that is. Jython, built on top of Java, uses 
Java's GC.  Ditto for IronPython implementation. PyPY may allow some choice.


 A

Python object is  destroyed when the refcount drops to 0. The GC only
collects cyclic references. If you create none, there are no GC delays
(you can in fact safely turn the GC off). Python does not share Java's
nasty habit of having long GC delays.



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


Creating a local variable scope.

2009-09-11 Thread Johan Grönqvist

Hi All,

I find several places in my code where I would like to have a variable
scope that is smaller than the enclosing function/class/module definition.

One representative example would look like:

--
spam = { ... }
eggs = { ... }

ham = (a[eggs], b[spam])
--

The essence is that for readability, I want spam and eggs in separate
definitions, but for clarity, I would like to express the fact that they
are local to the definition of ham, i.e., they are not used outside of
 the definition of ham.

The language reference at
http://docs.python.org/reference/executionmodel.html says that The
following are blocks: a module, a function body, and a class
definition. (all other cases seem to refer to dynamic execution using
eval() or similar). Python 3 and 2.6 seem to have identical scope rules.

In the other languages I have used I can either use braces (C and
descendants) or use let-bindings (SML, Haskell etc.) to form local scopes.

Are there suggestions or conventions to maximize readability for these
cases in python? (Execution time is not important in the cases I
currently consider.)


Regards

Johan



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


Re: Creating a local variable scope.

2009-09-11 Thread Neal Becker
Johan Grönqvist wrote:

 Hi All,
 
 I find several places in my code where I would like to have a variable
 scope that is smaller than the enclosing function/class/module definition.
 
 One representative example would look like:
 
 --
 spam = { ... }
 eggs = { ... }
 
 ham = (a[eggs], b[spam])
 --
 
 The essence is that for readability, I want spam and eggs in separate
 definitions, but for clarity, I would like to express the fact that they
 are local to the definition of ham, i.e., they are not used outside of
   the definition of ham.
 
 The language reference at
 http://docs.python.org/reference/executionmodel.html says that The
 following are blocks: a module, a function body, and a class
 definition. (all other cases seem to refer to dynamic execution using
 eval() or similar). Python 3 and 2.6 seem to have identical scope rules.
 
 In the other languages I have used I can either use braces (C and
 descendants) or use let-bindings (SML, Haskell etc.) to form local scopes.
 
 Are there suggestions or conventions to maximize readability for these
 cases in python? (Execution time is not important in the cases I
 currently consider.)
 
I'd like this also.

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


Re: how to return value from button clicked by python

2009-09-11 Thread r
On Sep 11, 10:19 am, chen tao ct19850...@gmail.com wrote:
(snip)
     I tried the button.invoke() function, it almost got it...however,
 I only want it returns value when the button clicked, but because the
 program is in the class _ini_ function, so it always runs once before
 I click the button...

so don't call the function in the __init__ method OR just write a
def...?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Podcast catcher in Python

2009-09-11 Thread Chuck
On Sep 11, 12:56 pm, Chuck galois...@gmail.com wrote:
 On Sep 11, 10:30 am, Falcolas garri...@gmail.com wrote:





  On Sep 11, 8:20 am, Chuck galois...@gmail.com wrote:

   Hi all,

   I would like to code a simple podcast catcher in Python merely as an
   exercise in internet programming.  I am a CS student and new to
   Python, but understand Java fairly well.  I understand how to connect
   to a server with urlopen, but then I don't understand how to download
   the mp3, or whatever, podcast?  Do I need to somehow parse the XML
   document?  I really don't know.  Any ideas?

   Thanks!

   Chuck

  You will first have to download the RSS XML file, then parse that file
  for the URL for the audio file itself. Something like eTree will help
  immensely in this part. You'll also have to keep track of what you've
  already downloaded.

  I'd recommend taking a look at the RSS XML yourself, so you know what
  it is you have to parse out, and where to find it. From there, it
  should be fairly easy to come up with the proper query to pull it
  automatically out of the XML.

  As a kindness to the provider, I would recommend a fairly lengthy
  sleep between GETs, particularly if you want to scrape their back
  catalog.

  Unfortunately, I no longer have the script I created to do just such a
  thing in the past, but the process is rather straightforward, once you
  know where to look.

  ~G

 Thanks!  I will see what I can do.- Hide quoted text -

 - Show quoted text -

I am not sure how eTree fits in.  Is that eTree.org?
-- 
http://mail.python.org/mailman/listinfo/python-list


Python C/API Problem

2009-09-11 Thread Gianfranco Murador
Hi to all python fans,
i'm trying to run this C source file:
[code]

#include Python.h
#include structmember.h
#include compile.h
#include dirent.h
#include node.h


int main(int argc, char *argv[]) {
Py_Initialize();

struct _node *node = PyParser_SimpleParseString(from time import
time,ctime\n
print 'Today 
is',ctime(time())\n,0);
if(node == NULL)
{
printf(Errore nel parsing);
}else{
PyNode_Compile(node, ./prova.pyc);
PyNode_Free(node);
}

Py_Finalize();
return 0;
}

[/code]

I compile the file without errors, but when i launch the executable i
have a Segmentation Fault. I'm using the shared library of python
2.5.2 under linux.. Any ideas? It's clear that i do some mistakes, but
where?
Thanks.
greetings, G.

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


Where find regexs needed to build lexical analyzer for Python source code?

2009-09-11 Thread Chris Seberino
I'd like to build a lexer aka lexical analyzer aka tokenizer for
Python source code as a learning exercise.

Where can I find the regexs that define the tokens of Python source?
(I am aware of tokenizer.py but I was hoping there was a web page w/ a
list somewhere.)

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


Re: Podcast catcher in Python

2009-09-11 Thread Chuck
On Sep 11, 1:09 pm, Chuck galois...@gmail.com wrote:
 On Sep 11, 12:56 pm, Chuck galois...@gmail.com wrote:





  On Sep 11, 10:30 am, Falcolas garri...@gmail.com wrote:

   On Sep 11, 8:20 am, Chuck galois...@gmail.com wrote:

Hi all,

I would like to code a simple podcast catcher in Python merely as an
exercise in internet programming.  I am a CS student and new to
Python, but understand Java fairly well.  I understand how to connect
to a server with urlopen, but then I don't understand how to download
the mp3, or whatever, podcast?  Do I need to somehow parse the XML
document?  I really don't know.  Any ideas?

Thanks!

Chuck

   You will first have to download the RSS XML file, then parse that file
   for the URL for the audio file itself. Something like eTree will help
   immensely in this part. You'll also have to keep track of what you've
   already downloaded.

   I'd recommend taking a look at the RSS XML yourself, so you know what
   it is you have to parse out, and where to find it. From there, it
   should be fairly easy to come up with the proper query to pull it
   automatically out of the XML.

   As a kindness to the provider, I would recommend a fairly lengthy
   sleep between GETs, particularly if you want to scrape their back
   catalog.

   Unfortunately, I no longer have the script I created to do just such a
   thing in the past, but the process is rather straightforward, once you
   know where to look.

   ~G

  Thanks!  I will see what I can do.- Hide quoted text -

  - Show quoted text -

 I am not sure how eTree fits in.  Is that eTree.org?- Hide quoted text -

 - Show quoted text -

Can I just use x.read() to download the mp3 file and use x.write() to
write it to a file?  Or, do I have to worry about encoding/decoding
etc...?  I am under the impression that I can just read the mp3 and
write to a file, then play it in a media player.  Is this too
simplified?
-- 
http://mail.python.org/mailman/listinfo/python-list


Mapping in python? Transforming shapefile so that basemap can read them?

2009-09-11 Thread C Barr Leigh
I'm trying to get started with plotting maps in python. I need to read
shape files (.shp) and make maps. There seem to be many efforts but
none is complete? I'm looking for suggestions and troubleshooting.

The basemap package is obviously at an impressive stage and comes with
some data:
http://www.scipy.org/Cookbook/Matplotlib/Maps

but it cannot read shapefiles when their coordinates are not in
geographic projection. min are in a lambert, so the readshapefile
fails.

Apparently there is a utility that can convert a .shp file to lat/lon
coordinates, but it fails for me. “You can convert the shapefile to
geographic - coordinates using the shpproj utility from the shapelib
tools - (http://shapelib.maptools.org/shapelib-tools.html)
 For me, this gives:
“unable to process projection, exiting...”

Has anyone overcome these problems?

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


Re: Creating a local variable scope.

2009-09-11 Thread Patrick Sabin

Johan Grönqvist schrieb:

Hi All,

I find several places in my code where I would like to have a variable
scope that is smaller than the enclosing function/class/module definition.

One representative example would look like:

--
spam = { ... }
eggs = { ... }

ham = (a[eggs], b[spam])
--

The essence is that for readability, I want spam and eggs in separate
definitions, but for clarity, I would like to express the fact that they
are local to the definition of ham, i.e., they are not used outside of
 the definition of ham.

The language reference at
http://docs.python.org/reference/executionmodel.html says that The
following are blocks: a module, a function body, and a class
definition. (all other cases seem to refer to dynamic execution using
eval() or similar). Python 3 and 2.6 seem to have identical scope rules.

In the other languages I have used I can either use braces (C and
descendants) or use let-bindings (SML, Haskell etc.) to form local scopes.

Are there suggestions or conventions to maximize readability for these
cases in python? (Execution time is not important in the cases I
currently consider.)


Regards

Johan


I think it is not possible to realize something like braces in C or 
let-bindings in python. But here are some Ideas to work around this problem:


1) If you define all this in the global namespace you could remove your 
temporary variables afterwards, e.g.


spam = 1
ham = (spam,)
del globals()['spam']

This only works for the global namespace and not for the local! I 
wouldn't recommend it.


2) create a method, which initializes ham

def make_ham():
spam = {...}
egg = {...}
return (egg, spam)

ham = make_ham()

This makes it easier to reuse ham in other situations and wouldn't 
expose spam or egg.


3) Make a class for your ham data structure

If ham is so complex that you have to split it up, it may makes sense to 
create a class for it. Of course this would need refactoring of the 
code, but it's more readable and extensible than packing your data in 
tuples, lists or dictionaries.


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


Re: Creating a local variable scope.

2009-09-11 Thread Daniel Stutzbach
2009/9/11 Johan Grönqvist johan.gronqv...@gmail.com

 I find several places in my code where I would like to have a variable
 scope that is smaller than the enclosing function/class/module definition.


For what it's worth, there was a relevant proposal on the python-ideas list
a few months back:

http://mail.python.org/pipermail/python-ideas/2009-July/005114.html
http://mail.python.org/pipermail/python-ideas/2009-July/005114.html%20

--
Daniel Stutzbach, Ph.D.
President, Stutzbach Enterprises, LLC http://stutzbachenterprises.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Dataflow programming in Python

2009-09-11 Thread Anh Hai Trinh
Hello all,

I just want to share with you something that I've worked on recently.
It is a library which implements streams -- generalized iterators with
a pipelining mechanism and lazy-evaluation to enable data-flow
programming in Python.

The idea is to be able to take the output of a function that turn an
iterable into another iterable and plug that as the input of another
such function. While you can already do some of this using function
composition, this package provides an elegant notation for it by
overloading the '' operator.

To give a simple example of string processing, here we grep the lines
matching some regex, strip them and accumulate to a list:

 import re
 result = open('log').xreadlines()  filter(re.compile('[Pp]attern').search) 
  mapmethod('strip')  list

This approach focuses the programming on processing streams of data,
step by step. A pipeline usually starts with a generator, or anything
iterable, then passes through a number of processors. Multiple streams
can be branched and combined. Finally, the output is fed to an
accumulator, which can be any function of one iterable argument.

Another advantage is that the values are lazily computed, i.e. only
when the accumulator needs to have it.

Homepage:
http://trinhhaianh.com/stream.py/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Use python to execute a windows program

2009-09-11 Thread Jerry Hill
On Fri, Sep 11, 2009 at 12:46 PM, Doran, Harold hdo...@air.org wrote:
 I am working with this now. I'm toying with the examples to test out a
 few things and learn how this works. I've made some modifications such
 that I have the following working (below). This does nothing more than
 open a program.

 I have commented out the portion

 #app.AM.MenuSelect(File-Open Database)

 When it is uncommented, the program fails. However, when I tinker with
 this MenuSelect() for, say, Notepad, this presents no problem and
 behaves as expected. For example, the following works with notepad:

 app.Notepad.MenuSelect(Help-Help Topics)

 At the risk of sounding too silly, how do I know what to place after
 app.??.MenuSelect? I've tried this with a few programs and the name I
 use in place of ?? Doesn't seem to work.

I'm not very familiar with pywinauto myself, but a quick look through
the docs says that the application looks for a window or dialog with a
similar name to what you put there.  So, what does the title bar of
the window opened by AM.exe say?  You should use a name that is
similar to the title of the window you're trying to control.

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


Problem with queues and gobject event loop

2009-09-11 Thread Roman Kapl
Why does not this snipplet work?
-
from job import JobQueue
import Queue
import threading
import gobject
q=JobQueue()
def worker():
print Worker waiting
q.get()
print Got job!

if __name__ == __main__:
t = threading.Thread(target=worker)
t.start()
q.put(1)
loop = gobject.MainLoop()
loop.run()
-
It blocks indefinitely on the q.get() in the worker thread. When I
remove the the gobject main loop call, the code works fine and worker
thread gets to the print Got job! statement. This is just simplified
example to show the weird behaviour, otherwise I am trying to receive
messages via DBus and schedule jobs for another thread(I am a DBus
server). So is it a bug, my mistake or just simply queues can't be
used in combination with gobject main loop? Can I use dbus without
main loop(since I really don't need it, but I couldn't find any
example how to get rid of it.

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


RE: Use python to execute a windows program

2009-09-11 Thread Doran, Harold
Thanks, Jerry. Tried that, as well as various other possible names to no
avail. 

 -Original Message-
 From: python-list-bounces+hdoran=air@python.org 
 [mailto:python-list-bounces+hdoran=air@python.org] On 
 Behalf Of Jerry Hill
 Sent: Friday, September 11, 2009 3:09 PM
 To: python-list@python.org
 Subject: Re: Use python to execute a windows program
 
 On Fri, Sep 11, 2009 at 12:46 PM, Doran, Harold 
 hdo...@air.org wrote:
  I am working with this now. I'm toying with the examples to 
 test out a 
  few things and learn how this works. I've made some 
 modifications such 
  that I have the following working (below). This does 
 nothing more than 
  open a program.
 
  I have commented out the portion
 
  #app.AM.MenuSelect(File-Open Database)
 
  When it is uncommented, the program fails. However, when I 
 tinker with 
  this MenuSelect() for, say, Notepad, this presents no problem and 
  behaves as expected. For example, the following works with notepad:
 
  app.Notepad.MenuSelect(Help-Help Topics)
 
  At the risk of sounding too silly, how do I know what to 
 place after 
  app.??.MenuSelect? I've tried this with a few programs and 
 the name I 
  use in place of ?? Doesn't seem to work.
 
 I'm not very familiar with pywinauto myself, but a quick look 
 through the docs says that the application looks for a window 
 or dialog with a similar name to what you put there.  So, 
 what does the title bar of the window opened by AM.exe say?  
 You should use a name that is similar to the title of the 
 window you're trying to control.
 
 --
 Jerry
 --
 http://mail.python.org/mailman/listinfo/python-list
 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Creating a local variable scope.

2009-09-11 Thread Ethan Furman

Patrick Sabin wrote:

Johan Grönqvist schrieb:


Hi All,

I find several places in my code where I would like to have a variable
scope that is smaller than the enclosing function/class/module 
definition.


One representative example would look like:

--
spam = { ... }
eggs = { ... }

ham = (a[eggs], b[spam])
--


[snip]

1) If you define all this in the global namespace you could remove your 
temporary variables afterwards, e.g.


spam = 1
ham = (spam,)
del globals()['spam']


Why use globals()?  You could just say

del spam

and be done with it.

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


Re: Extracting patterns after matching a regex

2009-09-11 Thread Mart.
On Sep 9, 4:58 pm, Al Fansome al_fans...@hotmail.com wrote:
 Mart. wrote:
  On Sep 8, 4:33 pm, MRAB pyt...@mrabarnett.plus.com wrote:
 Mart. wrote:
  On Sep 8, 3:53 pm, MRAB pyt...@mrabarnett.plus.com wrote:
 Mart. wrote:
  On Sep 8, 3:14 pm, Andreas Tawn andreas.t...@ubisoft.com wrote:
  Hi,
  I need to extract a string after a matching a regular expression. 
  For
  example I have the string...
  s = FTPHOST: e4ftl01u.ecs.nasa.gov
  and once I match FTPHOST I would like to extract
  e4ftl01u.ecs.nasa.gov. I am not sure as to the best approach to 
  the
  problem, I had been trying to match the string using something like
  this:
  m = re.findall(rFTPHOST, s)
  But I couldn't then work out how to return the 
  e4ftl01u.ecs.nasa.gov
  part. Perhaps I need to find the string and then split it? I had 
  some
  help with a similar problem, but now I don't seem to be able to
  transfer that to this problem!
  Thanks in advance for the help,
  Martin
  No need for regex.
  s = FTPHOST: e4ftl01u.ecs.nasa.gov
  If FTPHOST in s:
      return s[9:]
  Cheers,
  Drea
  Sorry perhaps I didn't make it clear enough, so apologies. I only
  presented the example  s = FTPHOST: e4ftl01u.ecs.nasa.gov as I
  thought this easily encompassed the problem. The solution presented
  works fine for this i.e. re.search(r'FTPHOST: (.*)',s).group(1). But
  when I used this on the actual file I am trying to parse I realised it
  is slightly more complicated as this also pulls out other information,
  for example it prints
  e4ftl01u.ecs.nasa.gov\r\n', 'FTPDIR: /PullDir/0301872638CySfQB\r\n',
  'Ftp Pull Download Links: \r\n', 'ftp://e4ftl01u.ecs.nasa.gov/PullDir/
  0301872638CySfQB\r\n', 'Down load ZIP file of packaged order:\r\n',
  etc. So I need to find a way to stop it before the \r
  slicing the string wouldn't work in this scenario as I can envisage a
  situation where the string lenght increases and I would prefer not to
  keep having to change the string.
  If, as Terry suggested, you do have a tuple of strings and the first 
  element has FTPHOST, then s[0].split(:)[1].strip() will work.
  It is an email which contains information before and after the main
  section I am interested in, namely...
  FINISHED: 09/07/2009 08:42:31
  MEDIATYPE: FtpPull
  MEDIAFORMAT: FILEFORMAT
  FTPHOST: e4ftl01u.ecs.nasa.gov
  FTPDIR: /PullDir/0301872638CySfQB
  Ftp Pull Download Links:
 ftp://e4ftl01u.ecs.nasa.gov/PullDir/0301872638CySfQB
  Down load ZIP file of packaged order:
 ftp://e4ftl01u.ecs.nasa.gov/PullDir/0301872638CySfQB.zip
  FTPEXPR: 09/12/2009 08:42:31
  MEDIA 1 of 1
  MEDIAID:
  I have been doing this to turn the email into a string
  email = sys.argv[1]
  f = open(email, 'r')
  s = str(f.readlines())
  To me that seems a strange thing to do. You could just read the entire
  file as a string:
       f = open(email, 'r')
       s = f.read()
  so FTPHOST isn't the first element, it is just part of a larger
  string. When I turn the email into a string it looks like...
  'FINISHED: 09/07/2009 08:42:31\r\n', '\r\n', 'MEDIATYPE: FtpPull\r\n',
  'MEDIAFORMAT: FILEFORMAT\r\n', 'FTPHOST: e4ftl01u.ecs.nasa.gov\r\n',
  'FTPDIR: /PullDir/0301872638CySfQB\r\n', 'Ftp Pull Download Links: \r
  \n', 'ftp://e4ftl01u.ecs.nasa.gov/PullDir/0301872638CySfQB\r\n', 'Down
  load ZIP file of packaged order:\r\n',
  So not sure splitting it like you suggested works in this case.
  Within the file are a list of files, e.g.
  TOTAL FILES: 2
             FILENAME: MOD13A2.A2007033.h17v08.005.2007101023605.hdf
             FILESIZE: 11028908
             FILENAME: MOD13A2.A2007033.h17v08.005.2007101023605.hdf.xml
             FILESIZE: 18975
  and what i want to do is get the ftp address from the file and collect
  these files to pull down from the web e.g.
  MOD13A2.A2007033.h17v08.005.2007101023605.hdf
  MOD13A2.A2007033.h17v08.005.2007101023605.hdf.xml
  Thus far I have
  #!/usr/bin/env python
  import sys
  import re
  import urllib
  email = sys.argv[1]
  f = open(email, 'r')
  s = str(f.readlines())
  m = re.findall(rMOD\.\.h..v..\.005\..\
  \, s)
  ftphost = re.search(r'FTPHOST: (.*?)\\r',s).group(1)
  ftpdir  = re.search(r'FTPDIR: (.*?)\\r',s).group(1)
  url = 'ftp://' + ftphost + ftpdir
  for i in xrange(len(m)):
     print i, ':', len(m)
     file1 = m[i][:-4]               # remove xml bit.
     file2 = m[i]
     urllib.urlretrieve(url, file1)
     urllib.urlretrieve(url, file2)
  which works, clearly my match for the MOD13A2* files isn't ideal I
  guess, but they will always occupt those dimensions, so it should
  work. Any suggestions on how to improve this are appreciated.
  Suppose the file contains your example text above. Using 'readlines'
  returns a list of the lines:

    f = open(email, 'r')
    lines = f.readlines()
    lines
  ['TOTAL FILES: 2\n', '\t\tFILENAME:
  MOD13A2.A2007033.h17v08.005.2007101023605.hdf\n', '\t\tFILESIZE:
  11028908\n', '\n', '\t\tFILENAME:
  

Re: Use python to execute a windows program

2009-09-11 Thread Jerry Hill
On Fri, Sep 11, 2009 at 3:31 PM, Doran, Harold hdo...@air.org wrote:
 Thanks, Jerry. Tried that, as well as various other possible names to no
 avail.

You'll need to dig into the documentation then, probably starting in
one of these two places:
http://pywinauto.openqa.org/howto.html
http://pywinauto.openqa.org/module-pywinauto.application.html

The howto says that once you've started your application, calling
app.windows_() will return a list of visible, enabled, top level
windows of the application.  Try printing those and seeing if any of
them look like the window you want.  Or maybe try app.top_window_()
which tries to guess which window might be the main window of your
application.

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


Re: Python C/API Problem

2009-09-11 Thread Philip Semanchuk


On Sep 11, 2009, at 2:10 PM, Gianfranco Murador wrote:


Hi to all python fans,
i'm trying to run this C source file:
[code]

#include Python.h
#include structmember.h
#include compile.h
#include dirent.h
#include node.h


int main(int argc, char *argv[]) {
Py_Initialize();

struct _node *node = PyParser_SimpleParseString(from time import
time,ctime\n
print 'Today 
is',ctime(time())\n,0);
if(node == NULL)
{
printf(Errore nel parsing);
}else{
PyNode_Compile(node, ./prova.pyc);
PyNode_Free(node);
}

Py_Finalize();
return 0;
}

[/code]

I compile the file without errors, but when i launch the executable i
have a Segmentation Fault. I'm using the shared library of python
2.5.2 under linux.. Any ideas? It's clear that i do some mistakes, but
where?


Hi G,
With some basic debugging you should at least be able to figure out on  
which line the segfault happens. Have you done that?



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


Re: Creating a local variable scope.

2009-09-11 Thread Terry Reedy

Johan Grönqvist wrote:

Hi All,

I find several places in my code where I would like to have a variable
scope that is smaller than the enclosing function/class/module definition.

One representative example would look like:

--
spam = { ... }
eggs = { ... }

ham = (a[eggs], b[spam])
--

The essence is that for readability, I want spam and eggs in separate
definitions, but for clarity, I would like to express the fact that they
are local to the definition of ham, i.e., they are not used outside of
 the definition of ham.


delete spam, eggs

rather effectively says that the reader can also forget the bindings.
Execution time is minimal since no object is gc'ed.

This works with function locals also:

 def f():
i=1; del i; print (i)


 f()
Traceback (most recent call last):
  File pyshell#6, line 1, in module
f()
  File pyshell#5, line 2, in f
i=1; del i; print (i)
UnboundLocalError: local variable 'i' referenced before assignment

However, since probably a majority of non-function bindings are rather 
local, I do not see that this really improved readability.


Within a module intended to be imported, using _spam, _eggs would signal 
that they are only inted for local use. Delete if you want to enforce that.



The language reference at
http://docs.python.org/reference/executionmodel.html says that The
following are blocks: a module, a function body, and a class
definition. (all other cases seem to refer to dynamic execution using
eval() or similar). Python 3 and 2.6 seem to have identical scope rules.


Not exactly. In 3.0, comprehensions define a new scope by virtue of 
being implicit function bodies.



In the other languages I have used I can either use braces (C and
descendants) or use let-bindings (SML, Haskell etc.) to form local scopes.


I consider that simplicity of Python scoping to be a major feature; it 
is one of the reasons I use it.


tjr


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


Writing a thread-safe class

2009-09-11 Thread Timothy Madden

Hello

I would like to write a class with methods that can be accessed by many 
threads at the same time.


For this I have a lock attribute in my class obtained with 
threading.Lock(), in the constructor, and every method begins by 
acquiring the lock and ends by releasing it


My problem is that the lock is still an attribute of the class, and the 
very expression self.lock in the statement self.lock.acquire() is 
performed before locking, thus not being thread-safe.


If I am correct self is a dictionary of object attributes, and if 
another thread has the lock and creates a new attribute, or deletes one, 
in the same time with my lookup for self.lock, than the lookup is 
compromised.


How do people create thread-safe classes in python ?

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


Re: Unicode - and MIMEType - Good friday fun.

2009-09-11 Thread MRAB

rh0dium wrote:

Hi Geniuses,

Can anyone please show me the way..  I don't understand why this
doesn't work...


# encoding: utf-8
from email.MIMEText import MIMEText

msg = MIMEText(hi)
msg.set_charset('utf-8')
print msg.as_string()

a = 'Ho\xcc\x82tel Ste\xcc\x81phane '
b = unicode(a, utf-8)

print b

msg = MIMEText(b)
msg.set_charset('utf-8')
print msg.as_string()

It should right??


'b' is Unicode, but you're telling 'msg' that it's UTF-8, which it
isn't. Try giving 'msg' the UTF-8 string:

 msg = MIMEText(a)
 msg.set_charset('utf-8')
 print msg.as_string()
MIME-Version: 1.0
Content-Transfer-Encoding: 8bit
Content-Type: text/plain; charset=utf-8

Hôtel Stéphane
--
http://mail.python.org/mailman/listinfo/python-list


Re: [Distutils] uses for setup.cfg and extracting data from it

2009-09-11 Thread P.J. Eby

At 08:14 AM 9/12/2009 +1000, Ben Finney wrote:
Specifically, I want to programmatically access the metadata that is 
held in the arguments to the ‘distutils.setup()’ call. Without, 
as you say, executing any Distutils command. I am not aware of any 
‘distutils’ public functions that can do that, and reading 
URL:http://docs.python.org/distutils/ again doesn't enlighten me. 
Would you be more specific about what these functions are?


http://docs.python.org/distutils/apiref.html#module-distutils.core - 
specifically the run_setup() function.  (It appears the docs do not 
have link anchors for individual functions, alas.)


distutils.core.run_setup(setup.py, [], init) will return you an 
initialized Distribution object from running the setup script, 
without parsing any configuration files or executing any 
commands.  You could use config or commandline instead of init 
if you wanted those pieces of processing to be done as well - i.e. if 
you wanted to be sure any setup.cfg options were processed.


This will work with a sufficiently well-behaved setup.py; setup 
scripts that try to do build or install steps outside of any 
distutils command may produce side-effects when run.  (Which is why 
setuptools always runs setup scripts in a loose sandbox that detects 
when a script tries to modify the filesystem outside the setup directory.)


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


Re: Creating a local variable scope.

2009-09-11 Thread Steven D'Aprano
On Fri, 11 Sep 2009 19:36:14 +0200, Johan Grönqvist wrote:

 Hi All,
 
 I find several places in my code where I would like to have a variable
 scope that is smaller than the enclosing function/class/module
 definition.
...
 The essence is that for readability, I want spam and eggs in separate
 definitions, but for clarity, I would like to express the fact that they
 are local to the definition of ham, i.e., they are not used outside of
   the definition of ham.

Personally, I don't think your use-case is the least bit convincing, and 
I think that introducing a new scope would hurt readability and clarity 
rather than help it, but if you really want this, there are a couple of 
approaches:

(1) Use comments to give your intention.

spam = 'abc'  # Used only in definition of ham.
eggs = 'def'  # Likewise.
ham = (a[eggs], b[spam])


(2) Delete the local names afterwards.

spam = 'abc'
eggs = 'def'
ham = (a[eggs], b[spam])
del spam, eggs


(3) Create an inner function, then call that.

def outer(*args):
a = parrot()
b = spanish_inquistion()
def inner():
spam = 'abc'
eggs = 'def'
return a[eggs], b[spam]
ham = inner()
return do_something_with(ham)


(4) Create a do nothing context manager allowing you to visually indent 
the block, but otherwise have no effect:

class do_nothing:
def __enter__(self):
pass
def __exit__(self, type, value, traceback):
pass

ham = ()
with do_nothing() as imaginary_local_scope:
spam = 'abc'
eggs = 'def'
ham = a[eggs], b[spam]
del spam, eggs, imaginary_local_scope


I think the fourth is an abomination and I only mention it for completion.

My personal opinion is that if you really need a local scope inside a 
function, the function is doing too much and should be split up.


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


Re: Podcast catcher in Python

2009-09-11 Thread Chris Rebert
On Fri, Sep 11, 2009 at 11:09 AM, Chuck galois...@gmail.com wrote:
 On Sep 11, 12:56 pm, Chuck galois...@gmail.com wrote:
 On Sep 11, 10:30 am, Falcolas garri...@gmail.com wrote:
  On Sep 11, 8:20 am, Chuck galois...@gmail.com wrote:

   Hi all,

   I would like to code a simple podcast catcher in Python merely as an
   exercise in internet programming.  I am a CS student and new to
   Python, but understand Java fairly well.  I understand how to connect
   to a server with urlopen, but then I don't understand how to download
   the mp3, or whatever, podcast?  Do I need to somehow parse the XML
   document?  I really don't know.  Any ideas?

   Thanks!

   Chuck

  You will first have to download the RSS XML file, then parse that file
  for the URL for the audio file itself. Something like eTree will help
  immensely in this part. You'll also have to keep track of what you've
  already downloaded.

  I'd recommend taking a look at the RSS XML yourself, so you know what
  it is you have to parse out, and where to find it. From there, it
  should be fairly easy to come up with the proper query to pull it
  automatically out of the XML.

  As a kindness to the provider, I would recommend a fairly lengthy
  sleep between GETs, particularly if you want to scrape their back
  catalog.

  Unfortunately, I no longer have the script I created to do just such a
  thing in the past, but the process is rather straightforward, once you
  know where to look.

 I am not sure how eTree fits in.  Is that eTree.org?

No, he's referring to the `xml.etree.elementtree` standard module:
http://docs.python.org/library/xml.etree.elementtree.html#module-xml.etree.ElementTree

Although since you're dealing with feeds, you might be able to use
Universal Feed Parser, which is specifically for RSS/Atom:
http://www.feedparser.org/

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


Re: Writing a thread-safe class

2009-09-11 Thread Carl Banks
On Sep 11, 4:26 pm, Timothy Madden terminato...@gmail.com wrote:
 Hello

 I would like to write a class with methods that can be accessed by many
 threads at the same time.

 For this I have a lock attribute in my class obtained with
 threading.Lock(), in the constructor, and every method begins by
 acquiring the lock and ends by releasing it

 My problem is that the lock is still an attribute of the class, and the
 very expression self.lock in the statement self.lock.acquire() is
 performed before locking, thus not being thread-safe.

 If I am correct self is a dictionary of object attributes, and if
 another thread has the lock and creates a new attribute, or deletes one,
 in the same time with my lookup for self.lock, than the lookup is
 compromised.

You are not correct.  Dictionary operation (like getting and setting
items) are atomic and limited to one thread at a time, thus thread-
safe.

(In fact, in CPython only one thread can execute Python code at a
time, in most cases.  This is called the Global Interpreter Lock, or
GIL.  If you search this newsgroup for information you will find a LOT
of discission about it.  Other Python implementations such as Jython
may not use the GIL, but I am quite sure dictionary access is thread-
safe on those platforms also.)


 How do people create thread-safe classes in python ?

I think exactly the way you are doing it.  (Some people might use
threading.RLock instead as a minor safety measure, but threading.Lock
will suffice.)


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


Re: string interpolation mystery in Python 2.6

2009-09-11 Thread Steven D'Aprano
On Fri, 11 Sep 2009 15:19:05 -0700, Chris Rebert wrote:

 On Fri, Sep 11, 2009 at 3:12 PM, Alan G Isaac alan.is...@gmail.com
 wrote:
 Michael Foord came up with a much simpler illustration.  With Python
 2.6::

[snip]

 Sounds like IOError or one of its ancestors defines both __str__() and
 __unicode__ () special methods but has them produce different output.


That's what it looks like to me too, which I wouldn't call either a bug 
or a feature. I don't think Python makes any promises regarding exception 
messages. 

However, I must admit I'm perplexed why the original example is calling 
__unicode__() in the first place! Given the line:

raise self.severe('Problems with %s directive path:\n%s: %s.'
% (self.name, error.__class__.__name__, error))

it looks to me like it should be calling error.__str__() not 
error.__unicode(). Making the suggested edit:

raise self.severe('Problems with %s directive path:\n%s: %s.'
% (self.name, error.__class__.__name__, str(error)))

should have no effect. But it (apparently) does. This brings us back to 
Alan's original question:

MYSTERY: how can %s%error be different from %s%str(error) in Python 
2.6?



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


Re: Unicode - and MIMEType - Good friday fun.

2009-09-11 Thread Rami Chowdhury

b = unicode(a, utf-8)


[snip]


msg = MIMEText(b)


I believe this is the problem line -- the MIMEText constructor takes  
encoded strings rather than unicode objects. Try:


msg = MIMEText(a)

Or, alternatively

msg = MIMEText(b.encode('utf-8'))

On Fri, 11 Sep 2009 16:33:42 -0700, rh0dium steven.kl...@gmail.com wrote:


Hi Geniuses,

Can anyone please show me the way..  I don't understand why this
doesn't work...


# encoding: utf-8
from email.MIMEText import MIMEText

msg = MIMEText(hi)
msg.set_charset('utf-8')
print msg.as_string()

a = 'Ho\xcc\x82tel Ste\xcc\x81phane '
b = unicode(a, utf-8)

print b

msg = MIMEText(b)
msg.set_charset('utf-8')
print msg.as_string()

It should right??

Thanks!




--
Rami Chowdhury
Never attribute to malice that which can be attributed to stupidity --  
Hanlon's Razor

408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Unicode - and MIMEType - Good friday fun.

2009-09-11 Thread bouncy...@gmail.com
How do you suppose it should workand how is it working? what about the 
outpout difference?

--
Sent via Cricket Mobile Email

--Original Message--
From: rh0dium steven.kl...@gmail.com
To: python-list@python.org
Date: Fri, 11 Sep 2009 04:33:42 PM -0700
Subject: Unicode - and MIMEType - Good friday fun.

Hi Geniuses,

Can anyone please show me the way..  I don't understand why this
doesn't work...


# encoding: utf-8
from email.MIMEText import MIMEText

msg = MIMEText(hi)
msg.set_charset('utf-8')
print msg.as_string()

a = 'Ho\xcc\x82tel Ste\xcc\x81phane '
b = unicode(a, utf-8)

print b

msg = MIMEText(b)
msg.set_charset('utf-8')
print msg.as_string()

It should right??

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

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


Re: Podcast catcher in Python

2009-09-11 Thread Chuck
On Sep 11, 8:32 pm, Chris Rebert c...@rebertia.com wrote:
 On Fri, Sep 11, 2009 at 11:09 AM, Chuck galois...@gmail.com wrote:
  On Sep 11, 12:56 pm, Chuck galois...@gmail.com wrote:
  On Sep 11, 10:30 am, Falcolas garri...@gmail.com wrote:
   On Sep 11, 8:20 am, Chuck galois...@gmail.com wrote:

Hi all,

I would like to code a simple podcast catcher in Python merely as an
exercise in internet programming.  I am a CS student and new to
Python, but understand Java fairly well.  I understand how to connect
to a server with urlopen, but then I don't understand how to download
the mp3, or whatever, podcast?  Do I need to somehow parse the XML
document?  I really don't know.  Any ideas?

Thanks!

Chuck

   You will first have to download the RSS XML file, then parse that file
   for the URL for the audio file itself. Something like eTree will help
   immensely in this part. You'll also have to keep track of what you've
   already downloaded.

   I'd recommend taking a look at the RSS XML yourself, so you know what
   it is you have to parse out, and where to find it. From there, it
   should be fairly easy to come up with the proper query to pull it
   automatically out of the XML.

   As a kindness to the provider, I would recommend a fairly lengthy
   sleep between GETs, particularly if you want to scrape their back
   catalog.

   Unfortunately, I no longer have the script I created to do just such a
   thing in the past, but the process is rather straightforward, once you
   know where to look.

  I am not sure how eTree fits in.  Is that eTree.org?

 No, he's referring to the `xml.etree.elementtree` standard 
 module:http://docs.python.org/library/xml.etree.elementtree.html#module-xml

 Although since you're dealing with feeds, you might be able to use
 Universal Feed Parser, which is specifically for 
 RSS/Atom:http://www.feedparser.org/

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

Brilliant!  I will give that a try.
Cheers!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Creating a local variable scope.

2009-09-11 Thread Bearophile
Steven D'Aprano:

 (3) Create an inner function, then call that.

Several people after someone gives this anwer.


 My personal opinion is that if you really need a local scope inside a 
 function, the function is doing too much and should be split up.

I agree. And a way to split a function is to define an inner function,
that's one of their main purposes. No need to add other things to the
language as the OP suggests.

Bye,
bearophile
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Podcast catcher in Python

2009-09-11 Thread Chuck
On Sep 11, 9:07 pm, Chuck galois...@gmail.com wrote:
 On Sep 11, 8:32 pm, Chris Rebert c...@rebertia.com wrote:





  On Fri, Sep 11, 2009 at 11:09 AM, Chuck galois...@gmail.com wrote:
   On Sep 11, 12:56 pm, Chuck galois...@gmail.com wrote:
   On Sep 11, 10:30 am, Falcolas garri...@gmail.com wrote:
On Sep 11, 8:20 am, Chuck galois...@gmail.com wrote:

 Hi all,

 I would like to code a simple podcast catcher in Python merely as an
 exercise in internet programming.  I am a CS student and new to
 Python, but understand Java fairly well.  I understand how to connect
 to a server with urlopen, but then I don't understand how to download
 the mp3, or whatever, podcast?  Do I need to somehow parse the XML
 document?  I really don't know.  Any ideas?

 Thanks!

 Chuck

You will first have to download the RSS XML file, then parse that file
for the URL for the audio file itself. Something like eTree will help
immensely in this part. You'll also have to keep track of what you've
already downloaded.

I'd recommend taking a look at the RSS XML yourself, so you know what
it is you have to parse out, and where to find it. From there, it
should be fairly easy to come up with the proper query to pull it
automatically out of the XML.

As a kindness to the provider, I would recommend a fairly lengthy
sleep between GETs, particularly if you want to scrape their back
catalog.

Unfortunately, I no longer have the script I created to do just such a
thing in the past, but the process is rather straightforward, once you
know where to look.

   I am not sure how eTree fits in.  Is that eTree.org?

  No, he's referring to the `xml.etree.elementtree` standard 
  module:http://docs.python.org/library/xml.etree.elementtree.html#module-xml

  Although since you're dealing with feeds, you might be able to use
  Universal Feed Parser, which is specifically for 
  RSS/Atom:http://www.feedparser.org/

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

 Brilliant!  I will give that a try.
 Cheers!

Does anyone know how I should read/download the mp3 file, and how I
should write/save it so that I can play it on a media player such as
Windoze media player?  Excuse my ignorance, but I am a complete noob
at this.  I downloaded the mp3, and I got a ton of hex, I think, but
it could've been unicode.
-- 
http://mail.python.org/mailman/listinfo/python-list


[issue6873] posix_lchown: possible overflow of uid, gid

2009-09-11 Thread Martin v . Löwis

Martin v. Löwis mar...@v.loewis.de added the comment:

I think the new patch is still incorrect. You now pass long variables into 
the i argument parser. Also, I would expect that compilers prefer to see 
an explicit cast from long to uid_t, in case it's a truncating cast.

Can you try your patch on a system where all this is an actual problem?

--

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue6873
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



  1   2   >