Re: Is there conversion method to convert pyunicodeobject to pybyteobject?

2010-05-19 Thread MathanK
Got it worked with the following change.

PyUnicodeObject *p = ...whatever...;

char* tmp = (char *)p;
PyObject* arg = PyBytes_FromString (tmp); 

function( (PyBytesObject*) arg); 


>From : MathanK
To : "python-list" 
Date : Sat, 15 May 2010 02:50:22 -1200
Subject : Is there conversion method to convert pyunicodeobject to pybyteobject?

Hi All,

A variable whose data type is PyUnicodeObject is to be assigned to varioable of 
PyBytesObject type 

example :
void function( (PyBytesObject* byte){} 
PyUnicodeObject *p = ...whatever...; 
function( (PyBytesObject*)p); 

compiled and got a Bus Error.

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


Re: Global variables for python applications

2010-05-19 Thread TomF

On 2010-05-16 12:27:21 -0700, christian schulze said:


On 16 Mai, 20:20, James Mills  wrote:

On Mon, May 17, 2010 at 4:00 AM, Krister Svanlund

 wrote:

On Sun, May 16, 2010 at 7:50 PM, AON LAZIO  wrote:

   How can I set up global variables for the entire python applications?
Like I can call and set this variables in any .py files.
   Think of it as a global variable in a single .py file but thisis for the
entire application.



First: Do NOT use global variables, it is bad practice and will
eventually give you loads of s**t.



But if you want to create global variables in python I do believe it
is possible to specify them in a .py file and then simply import it as
a module in your application. If you change one value in a module the
change will be available in all places you imported that module in.


The only place global variables are considered somewhat "acceptable"
are as constants in a module shared as a static value.

Anything else should be an object that you share. Don't get into the
habit of using global variables!

--james


Exactly! Python's OOP is awesome. Use it. Global vars used as anything
but constants is bad practice. It isn't that much work to implement
that.


Let's say you have a bunch of globals, one of which is a verbose flag.  
If I understand the difference, using a module gbls.py:

# in gbls.py
verbose = False
# elsewhere:
import gbls
gbls.verbose = True

Using a class:

# In the main module:
class gbls(object):
def __init__(self, verbose=False):
self.verbose = verbose

my_globals = gbls.gbls(verbose=True)
...
some_function(my_globals, ...)


If this is what you have in mind, I'm not really seeing how one is good 
practice and the other is bad.  The OOP method is more verbose (no pun 
intended) and I don't see how I'm any less likely to shoot myself in 
the foot with it.


-Tom


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


Re: help need to write a python spell checker

2010-05-19 Thread CM
I love how he just copied and pasted the assignment without any other
remarks.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Regular expression

2010-05-19 Thread Anthra Norell

Back9 wrote:

 Hi,

I have a string like this:
0x340x5A0x9B0xBA
I want to extract 0x from the string but the first one.

How I can use re for this case?

The string size will vary.

TIA

  

Unless the use of a regular expression is a requirement I'd do it like this:

'0x%s' % s.split ('x', 1)[1].replace ('x', '')

Frederic

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


Re: Classes and threading

2010-05-19 Thread Adam W.
On May 19, 12:04 am, Erik Max Francis  wrote:
> Adam W. wrote:
> > I thought I knew how classes worked, but this code sample is making my
> > second guess myself:
>
> > import threading
>
> > class nThread(threading.Thread):
> >     def __init__(self):
> >         threading.Thread.__init__(self)
>
> >     def run(self,args):
> >         print self.name
> >         print self.args
>
> > pants = nThread(args=('fruit'),name='charlie')
> > pants.start()
>
> > Traceback (most recent call last):
> >   File "C:\Users\Adam\Desktop\PyTiVo\task_master.py", line 13, in
> > 
> >     pants = nThread(args=('fruit'),name='charlie')
> > TypeError: __init__() got an unexpected keyword argument 'args'
>
> > Shouldn't __init__ still handle these (as per
> >http://docs.python.org/library/threading.html#thread-objects), even
> > if its subclassed?  I thought this was the whole idea of inheritance
> > and overdriving.
>
> You've overridden the __init__ method to _not_ take any arguments, and
> explicitly call its parent constructor not passing anything.  So it
> shouldn't be a wonder that it won't accept any arguments.
>
> If you don't intend to override the constructor in the parent class,
> simply don't define it.

Hummm, so lets say I wanted it pass all the variables to the parent
constructor, how would I do that?  I wouldn't have to list every
variable it could possible receive would I?

This is like the opposite behavior I remember.  When working with PyQt
GUI classes, I swear I just sub classed the few things I wanted to
change, and everything else would refer back to the parent...

What I really just want to do is pass run() some args, which is what I
assumed the default __init__'s args was for, but I give it args
without sub classing __init__ and it has no idea what to do with
them.  I subclass __init__ to take args, and I break everything else?
Is this really how this is supposed to work?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: another question about classes and subclassing

2010-05-19 Thread Gregory Ewing

Alex Hall wrote:


Sorry, top-posting is a habit on some other lists I am on, and
sometimes it follows me to lists where in-line posting is the way to
do it.


Which list you're on shouldn't matter. You should cultivate
the habit of always quoting selectively and minimally, on
any list. It may take you a little longer to write your
reply that way, but it will make your posts a lot easier
for everyone else to read and understand.

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


Re: Pointers on packaging python programs for installation on multiple platforms?

2010-05-19 Thread Tim Golden

On 19/05/2010 03:05, gobnat wrote:

I am trying to release my first python program.  I would like to be
able to create a download which will automatically do stuff like add
menu items (eg for KDE, GNOME and Windows).  Is there anywhere which
explains how to do this?


Speaking from the Windows perspective (although the same probably
applies elsewhere): this is the kind of thing which installer
generators handle for you. If you wrap your installer using
NSIS [1] or Wix [2] or whatever other installer-generator,
that will include options to add menu items. (Caveat: this
is informed hearsay; I've never actually used either of those
in earnest).

If you *want* to do it yourself then, on Windows, you basically want
to create folders and shortcuts within the user's Start Menu shell
folder. It's not too hard even from scratch; my winshell module might
help a little, too. [3]

TJG

[1] http://nsis.sourceforge.net/Main_Page
[2] http://wix.sourceforge.net/
[3]http://timgolden.me.uk/python/winshell.html
--
http://mail.python.org/mailman/listinfo/python-list


Re: another question about classes and subclassing

2010-05-19 Thread Gregory Ewing

Alex Hall wrote:

So by calling submarine(craft) I am bringing
in all of craft's attribs (subclassing)? Or does calling craft's
__init__ method do that instead?


By making Submarine a subclass of Craft, you are inheriting
any methods, or other class attributes, defined in the
classes themselves.

Instance attributes are a little different -- they only
come into existence when you assign to them, which is
usually done for the first time in the __init__ method.
Each instance has its own dictionary that holds the
values of its instance attributes, and it's just a
flat namespace -- there is no real distinction between
an instance attribute of a class or a subclass.
Any "inheritance" of instance attributes is just a
consequence of one __init__ method calling another.

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


Re: another question about classes and subclassing

2010-05-19 Thread Gregory Ewing

Dave Angel wrote:

Inside the __init__() method of Submarine, simply call the __init__() 
method of Craft, with appropriate parameters.


To elaborate on that a little, it looks like this:

  class Craft:

def __init__(self, position):
  self.position = position


  class Submarine(Craft):

def __init__(self, position, depth):
  Craft.__init__(self, position)
  self.depth = depth

Note the explicit 'self' passed to the __init__ method
of Craft. This is necessary because you are calling the
method's underlying function directly, bypassing the
magic which normally inserts 'self' automatically.

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


Re: Classes and threading

2010-05-19 Thread Duncan Booth
"Adam W."  wrote:

>> If you don't intend to override the constructor in the parent class,
>> simply don't define it.
> 
> Hummm, so lets say I wanted it pass all the variables to the parent
> constructor, how would I do that?  I wouldn't have to list every
> variable it could possible receive would I?
> 
No, you just have to handle them the way you would for any function that 
accepts arguments that it doesn't know in advance:

class nThread(threading.Thread):
def __init__(self, *args, **kw):
threading.Thread.__init__(self, *args, **kw)

If you want to add your own additional arguments then name them explicitly  
and don't pass them through:

class nThread(threading.Thread):
def __init__(self, myarg1, mayarg2, *args, **kw):
threading.Thread.__init__(self, *args, **kw)


-- 
Duncan Booth http://kupuguy.blogspot.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Classes and threading

2010-05-19 Thread Gregory Ewing

Erik Max Francis wrote:

Adam W. wrote:


class nThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)


If you don't intend to override the constructor in the parent class, 
simply don't define it.


Or if you do need to override it for some reason, you
need to accept the extra args and pass them on:

  class nThread(threading.Thread):

  def __init__(self, *args, **kwds):
  threading.Thread.__init__(self, *args, **kwds)
  # your other stuff here

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


Re: Classes and threading

2010-05-19 Thread Adam W.
On May 19, 4:30 am, Gregory Ewing  wrote:
> Or if you do need to override it for some reason, you
> need to accept the extra args and pass them on:
>
>    class nThread(threading.Thread):
>
>        def __init__(self, *args, **kwds):
>            threading.Thread.__init__(self, *args, **kwds)
>            # your other stuff here
>
Amazing, I've never seen *args used before outside of documentation, I
didn't think it was "real" :P  One problem down, still looking for why
printing inside a thread crashes IDLE.

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


Reading data from a Microsoft Access 2003 database

2010-05-19 Thread Jimoid
Hi All,

I use Ubuntu 64 bit and need to develop a programme (ideally in
Python) to work on data that is contained in a Microsoft Access 2003
database. I do not need to modify the database, simply read a few
columns of data from some tables.

Google hasn't been able to offer me a suitable solution to this
problem, and although there are some references to this problem in the
archives of this group, they are mainly very old and I wonder if there
is anything more recent that members could suggest to me?

Python would be my language of choice, however if someone has any
other suggestions then I'm open to ideas.

TIA,

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


Re: Classes and threading

2010-05-19 Thread Christian Heimes

Or if you do need to override it for some reason, you
need to accept the extra args and pass them on:

class nThread(threading.Thread):

def __init__(self, *args, **kwds):
threading.Thread.__init__(self, *args, **kwds)
# your other stuff here


Since Thread is a new style class, this should read:

class NThread(threading.thread):
def __init__(self, *args, **kwargs):
super(NThread, self).__init__(*args, **kwargs)

Christian

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


Re: Reading data from a Microsoft Access 2003 database

2010-05-19 Thread Simon Brunning
On 19 May 2010 10:28:15 UTC+1, Jimoid  wrote:
> I use Ubuntu 64 bit and need to develop a programme (ideally in
> Python) to work on data that is contained in a Microsoft Access 2003
> database. I do not need to modify the database, simply read a few
> columns of data from some tables.

mxODBC might well be what you are looking for,

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


remove elements incrementally from a list

2010-05-19 Thread Javier Montoya
Dear all,

I've a list of float numbers and I would like to delete incrementally
a set of elements in a given range of indexes, sth. like:

for j in range(beginIndex, endIndex+1):
   print ("remove [%d] => val: %g" % (j, myList[j]))
   del myList[j]

However, since I'm iterating over the same list, the indexes (range)
are not valid any more for the new list.
Does anybody has some suggestions on how to delete the elements
properly?

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


Re: remove elements incrementally from a list

2010-05-19 Thread superpollo

Javier Montoya ha scritto:

Dear all,

I've a list of float numbers and I would like to delete incrementally
a set of elements in a given range of indexes, sth. like:

for j in range(beginIndex, endIndex+1):
   print ("remove [%d] => val: %g" % (j, myList[j]))
   del myList[j]

However, since I'm iterating over the same list, the indexes (range)
are not valid any more for the new list.
Does anybody has some suggestions on how to delete the elements
properly?


clone the list, and then loop over the copy while deleting from the original

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


multiprocessing module - could it use google protocol buffers?

2010-05-19 Thread zLuke
Does it make sense to be able to substitute the pickling action in the
multiprocessing module with google protocol buffers instead?  If so,
has anyone thought how to do it?  I wanted some operation more compact/
faster than pickling for ipc of data.

Also, has anyone built any wrappers for the multiprocessing module
that gives a simple pp flavor kind of construct?

Curious,
zLuke
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: remove elements incrementally from a list

2010-05-19 Thread Mark Lawrence

On 19/05/2010 11:53, Javier Montoya wrote:

Dear all,

I've a list of float numbers and I would like to delete incrementally
a set of elements in a given range of indexes, sth. like:

for j in range(beginIndex, endIndex+1):
print ("remove [%d] =>  val: %g" % (j, myList[j]))
del myList[j]

However, since I'm iterating over the same list, the indexes (range)
are not valid any more for the new list.
Does anybody has some suggestions on how to delete the elements
properly?

Best wishes


You can delete the lot in one hit using a slice, see section 5.2 here
http://docs.python.org/tutorial/datastructures.html

Regards.

Mark Lawrence

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


RE: Reading data from a Microsoft Access 2003 database

2010-05-19 Thread Ahmed, Shakir

-Original Message-
From: [email protected]
[mailto:[email protected]] On Behalf Of
Simon Brunning
Sent: Wednesday, May 19, 2010 6:13 AM
To: python-list
Subject: Re: Reading data from a Microsoft Access 2003 database

On 19 May 2010 10:28:15 UTC+1, Jimoid  wrote:
> I use Ubuntu 64 bit and need to develop a programme (ideally in
> Python) to work on data that is contained in a Microsoft Access 2003
> database. I do not need to modify the database, simply read a few
> columns of data from some tables.

mxODBC might well be what you are looking for,

-- 
Cheers,
Simon B.
-- 

Or you can use pyodbc
DBfile = '/path/*.mdb
conn = pyodbc.connect('DRIVER={Microsoft Access Driver
(*.mdb)};DBQ='+DBfile, autocommit=True)
cursor = conn.cursor()

Thanks
Shakir

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


Re: Reading data from a Microsoft Access 2003 database

2010-05-19 Thread Les Schaffer

Jimoid wrote:


I use Ubuntu 64 bit and need to develop a programme (ideally in
Python) to work on data that is contained in a Microsoft Access 2003
database. I do not need to modify the database, simply read a few
columns of data from some tables.


this worked like a charm for me:

http://code.activestate.com/recipes/528868-extraction-and-manipulation-class-for-microsoft-ac/

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


Re: Reading data from a Microsoft Access 2003 database

2010-05-19 Thread Adam Tauno Williams
On Wed, 2010-05-19 at 08:05 -0400, Les Schaffer wrote:
> Jimoid wrote:
> 
> > I use Ubuntu 64 bit and need to develop a programme (ideally in
> > Python) to work on data that is contained in a Microsoft Access 2003
> > database. I do not need to modify the database, simply read a few
> > columns of data from some tables.
> 
> this worked like a charm for me:
> http://code.activestate.com/recipes/528868-extraction-and-manipulation-class-for-microsoft-ac/

The OP: "I use Ubuntu 64 bit"

Does something that contains "import win32com.client" work on anything
other than Windows?
-- 
Adam Tauno Williams  LPIC-1, Novell CLA

OpenGroupware, Cyrus IMAPd, Postfix, OpenLDAP, Samba

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


Re: Reading data from a Microsoft Access 2003 database

2010-05-19 Thread Adam Tauno Williams
On Wed, 2010-05-19 at 02:28 -0700, Jimoid wrote:
> Hi All,
> I use Ubuntu 64 bit and need to develop a programme (ideally in
> Python) to work on data that is contained in a Microsoft Access 2003
> database. I do not need to modify the database, simply read a few
> columns of data from some tables.
> Google hasn't been able to offer me a suitable solution to this

Google is a poor way to look for such things.  It is better to go to
Freshmeat / SourceForge or PyPI directly.

Try 

mdbtools is your best bet unless you are willing to pay for the EasySoft
drivers.  I've had mixed success with mdbtools;  if all you need to do
is extract data their ODBC driver will probably work.

If you are willing to use Jython (Python on the JVM) you have a *lot*
more options for this kind of thing.

> problem, and although there are some references to this problem in the
> archives of this group, they are mainly very old and I wonder if there
> is anything more recent that members could suggest to me?
> Python would be my language of choice, however if someone has any
> other suggestions then I'm open to ideas.
-- 
Adam Tauno Williams  LPIC-1, Novell CLA

OpenGroupware, Cyrus IMAPd, Postfix, OpenLDAP, Samba

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


Re: abc don't play well with private method

2010-05-19 Thread mouadino
Hello, and thank you for ALL the informations.

i think i was reading the wrong documents :)

For my use of ABC, i wanted to implement a plugin interface with the
ABC, in first i define a Base class (ABC) that other class
inherit(implement)
so that they can be interfaced as plugins.

but i did have some confusing about the privates method .

thank you all again.

Khalil_ibn_Ahmad (http://en.wikipedia.org/wiki/Khalil_ibn_Ahmad)
sayed :
They are 4 kind of man :
  the one that know that he don't know, this is a ignorant so teach
him
  the one that know that he know, this is a savant so take from him
the knowledge
  the one that don't know that he know, this one has forget so remind
him
  the one that don't know that he don't know , this is a fool


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


Re: remove elements incrementally from a list

2010-05-19 Thread Steven W. Orr

On 5/19/2010 6:53 AM, Javier Montoya wrote:


I've a list of float numbers and I would like to delete incrementally
a set of elements in a given range of indexes, sth. like:

for j in range(beginIndex, endIndex+1):
print ("remove [%d] =>  val: %g" % (j, myList[j]))
del myList[j]

However, since I'm iterating over the same list, the indexes (range)
are not valid any more for the new list.
Does anybody has some suggestions on how to delete the elements
properly?


How about using numpy?

to_be_deleted is an array of indexes to be deleted from myList. You seem to 
already have that list created but your list is contiguous. Just in case it 
isn't, you can say stuff like:


to_be_deleted = numpy.where( myList > allowed_or_something )
myList = numpy.delete( myList, to_be_deleted )


--
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: Reading data from a Microsoft Access 2003 database

2010-05-19 Thread Les Schaffer

Adam Tauno Williams wrote:


The OP: "I use Ubuntu 64 bit"


woops, my bad ...
--
http://mail.python.org/mailman/listinfo/python-list


Re: remove elements incrementally from a list

2010-05-19 Thread Steven D'Aprano
On Wed, 19 May 2010 03:53:44 -0700, Javier Montoya wrote:

> Dear all,
> 
> I've a list of float numbers and I would like to delete incrementally a
> set of elements in a given range of indexes, sth. like:
> 
> for j in range(beginIndex, endIndex+1):
>print ("remove [%d] => val: %g" % (j, myList[j])) del myList[j]
> 
> However, since I'm iterating over the same list, the indexes (range) are
> not valid any more for the new list. Does anybody has some suggestions
> on how to delete the elements properly?


Just delete the slice:

del myList[beginIndex:endIndex+1]

For small lists where you are deleting small chunks, this is the 
simplest, most straight-forward way.


Alternatively, create a new list excluding the bits you would have 
deleted, and assign it in place:

myList[:] = myList[:beginIndex] + myList[endIndex+1:]

Note carefully that you aren't just re-binding the name "myList", but 
assigning to the slice myList[:].

Then there is the old-fashioned way: iterate over the list backwards, 
deleting from the end towards the front.

for j in range(endIndex, beginIndex-1, -1):
del myList[j]


If your list is HUGE and you have very little memory, this is probably 
the least worst way. It might be slow, but it will work.

Finally, we have this:

myList[beginIndex:] = myList[endIndex+1:]



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


View Html/ py code in a zip as HTML/text ? ( for phone )

2010-05-19 Thread Jake b
I'm trying to figure out the best way to view python snippets /
smaller files on the itouch/iPhone.
I'm reading a new projects docs, but it's not easy to view the zip.

It can't view zip files. Say I want to read pyglet examples, I need
unzip at least one file and serve that. If it is text/HTML/py , then
view in pastebin.

Is there a trick to do this? Or maybe for certain sites. I thought I
had seen a way google did it to a zip not hosted on google code, but
can't find it.

1) is there existing web app to do this?
2) if not, I am on wifi, with apache mod-wsgi python enabled, so I
could use that?

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


Python Script for Website Mirroring

2010-05-19 Thread Kevin Rea
Hello Folks:

Can you please point me to a decent Python script(s) that I could customize
to do automatic Website mirroring?

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


Re: Global variables for python applications

2010-05-19 Thread Steven D'Aprano
On Wed, 19 May 2010 00:16:56 -0700, TomF wrote:

> Let's say you have a bunch of globals, one of which is a verbose flag.
> If I understand the difference, using a module gbls.py: 
>
> # in gbls.py
> verbose = False
> # elsewhere:
> import gbls
> gbls.verbose = True
> 
> Using a class:
> 
> # In the main module:
> class gbls(object):
>   def __init__(self, verbose=False):
>   self.verbose = verbose
> 
> my_globals = gbls.gbls(verbose=True)
> ...
> some_function(my_globals, ...)
> 
> 
> If this is what you have in mind, I'm not really seeing how one is good
> practice and the other is bad.  The OOP method is more verbose (no pun
> intended) and I don't see how I'm any less likely to shoot myself in the
> foot with it.

Exactly! Both are considered harmful. Best is to avoid the use of globals 
if possible, not to disguise them by wrapping them in a class.

The second case (using a class) is slightly less harmful, because you can 
set up multiple global namespaces and do this:

some_function(my_globals, ...)
some_function(other_globals, ...)

which at least allows you to replace the globals on demand, but it is 
still somewhat of a code-smell. Best is to find a way of doing without 
them. (Note that global constants and functions are usually fine.)

Unfortunately, it's rarely possible to do entirely without global 
settings, except in trivial applications. But what you can do is use 
Python's dynamic programming to reduce the need to keep globals hanging 
around:


# Untested.
def verbose_print(arg, level, verbosity=1):
if level <= verbosity:
print arg

def my_function(arg):
my_print(arg, level=2)
return arg.upper()

if __name__ == '__main__':
if '--verbose' in sys.argv:
my_print = functools.partial(verbose_print, verbosity=2)
elif '--quiet' in sys.argv:
my_print = functools.partial(verbose_print, verbosity=0)

my_function("hello world")


Note that although there is no verbosity global setting, every function 
that calls my_print will do the right thing (unless I've got the test 
backwards...), and if a function needs to override the implicit verbosity 
setting, it can just call verbose_print directly.


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


Delete files from FTP Server older then 7 days. Using ftputil and ftplib.

2010-05-19 Thread pilgrim773
Hello I am new to Python programming. I need a write a script which
will delete files from a FTP server after they have reached a certain
age, like 7 days for example. I have prepared this code below, but I
get an error message:
The system cannot find the path specified: '/test123/*.*' Probably
someone can help me further? Thank you in advance!

import os, time, ftputil
from ftplib import FTP

ftp = FTP('127.0.0.1')
print "Automated FTP Maintainance"
print 'Logging in.'
ftp.login('admin', 'admin')

# This is the directory that we want to go to
directory = 'test123'
print 'Changing to:' + directory
ftp.cwd(directory)
files = ftp.retrlines('LIST')
print 'List of Files:' + files
# ftp.remove('LIST')

#---
now = time.time()
for f in os.listdir(directory):
if os.stat(f).st_mtime < now - 7 * 86400:
if os.directory.isfile(f):
   os.remove(os.directory.join(directory, f))
#except:
#exit ("Cannot delete files")
#---

print 'Closing FTP connection'
ftp.close()

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


Re: __str__ for each function in a class

2010-05-19 Thread Terry Reedy

On 5/19/2010 1:14 AM, Vincent Davis wrote:


I am sure this is easy but I am not sure how to do it and google was
failing me.
Lets say I have a class() with an def x() and def y() and I want
print(class.x) and (class.y) to have custom prints (__str__) how do I do
this
For example
class C(object):
 def __init__(self, new):
 self.letter = dict(a=1,b=2,c=3, amin=np.amin)
 self.new = new
 self._x = None
 self._Y = None

 @property
 def x(self):
"""I'm the 'x' property."""
 self._x = self.new
 return self._x

 @property
 def y(self):
"""I'm the 'x' property."""
 self._y = self.new*-1
 return self._y

...
 >>> print(class.x)


'class' is a keyword, so this is a syntax error.
Did you mean C.x?


x


In any case, the printing of an object ob is controlled by 
type(ob).__str__ and type(ob).__repr__, so you can only control the 
printing of instances of custom type. You cannot replace methods of 
builtin classes.


Terry Jan Reedy

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


Re: __str__ for each function in a class

2010-05-19 Thread Xavier Ho
On 5/19/2010 1:14 AM, Vincent Davis wrote:

> class C(object):
>> def __init__(self, new):
>> self.letter = dict(a=1,b=2,c=3, amin=np.amin)
>> self.new = new
>> self._x = None
>> self._Y = None
>>
>> @property
>> def x(self):
>> """I'm the 'x' property."""
>> self._x = self.new
>> return self._x
>>
>
I just wanted to point out that your

self._x = self.new

does not give you a new object. Instead, _x is assigned a reference that
points to this object called 'new', which is passed in during the class
initialisation. I think your variable naming needs some improvement to
show/correct your understanding.

Also, you can just use `x` and `y` for the variable names; you don't need
the underscore. If you want to use a pseudo-private variable, use __x
(double prefix underscore) instead.

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


Re: help need to write a python spell checker

2010-05-19 Thread Terry Reedy

On 5/19/2010 3:17 AM, CM wrote:

I love how he just copied and pasted the assignment without any other
remarks.


Yeah, that way he did not mess it up ;-).



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


Re: remove elements incrementally from a list

2010-05-19 Thread Javier Montoya
On May 19, 4:06 pm, Steven D'Aprano  wrote:
> On Wed, 19 May 2010 03:53:44 -0700, Javier Montoya wrote:
> > Dear all,
>
> > I've a list of float numbers and I would like to delete incrementally a
> > set of elements in a given range of indexes, sth. like:
>
> > for j in range(beginIndex, endIndex+1):
> >    print ("remove [%d] => val: %g" % (j, myList[j])) del myList[j]
>
> > However, since I'm iterating over the same list, the indexes (range) are
> > not valid any more for the new list. Does anybody has some suggestions
> > on how to delete the elements properly?
>
> Just delete the slice:
>
> del myList[beginIndex:endIndex+1]
>
> For small lists where you are deleting small chunks, this is the
> simplest, most straight-forward way.
>
> Alternatively, create a new list excluding the bits you would have
> deleted, and assign it in place:
>
> myList[:] = myList[:beginIndex] + myList[endIndex+1:]
>
> Note carefully that you aren't just re-binding the name "myList", but
> assigning to the slice myList[:].
>
> Then there is the old-fashioned way: iterate over the list backwards,
> deleting from the end towards the front.
>
> for j in range(endIndex, beginIndex-1, -1):
>     del myList[j]
>
> If your list is HUGE and you have very little memory, this is probably
> the least worst way. It might be slow, but it will work.
>
> Finally, we have this:
>
> myList[beginIndex:] = myList[endIndex+1:]
>
> --
> Steven

Hi guys,

A big thanks to everybody, it's amazing!

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


Re: Delete files from FTP Server older then 7 days. Using ftputil and ftplib.

2010-05-19 Thread MRAB

pilgrim773 wrote:

Hello I am new to Python programming. I need a write a script which
will delete files from a FTP server after they have reached a certain
age, like 7 days for example. I have prepared this code below, but I
get an error message:
The system cannot find the path specified: '/test123/*.*' Probably
someone can help me further? Thank you in advance!

import os, time, ftputil
from ftplib import FTP

ftp = FTP('127.0.0.1')
print "Automated FTP Maintainance"
print 'Logging in.'
ftp.login('admin', 'admin')

# This is the directory that we want to go to
directory = 'test123'
print 'Changing to:' + directory
ftp.cwd(directory)
files = ftp.retrlines('LIST')
print 'List of Files:' + files
# ftp.remove('LIST')


It's better to pass the full filename instead of changing the directory
because it means that you don't need to keep track of which directory
you're currently in, for example:

files = ftp.retrlines(directory + '/LIST')


#---
now = time.time()
for f in os.listdir(directory):
if os.stat(f).st_mtime < now - 7 * 86400:
if os.directory.isfile(f):
   os.remove(os.directory.join(directory, f))


The os module works with _local_ files, not the remote files on a
server.

You can list the files and get info about them like this:

reply = []
ftp.retrlines("LIST " + directory, reply.append)

'reply' will be a list of lines, one per file, which you can then parse.
It shouldn't be too difficult to write a function to hide the messy
details. :-)


#except:
#exit ("Cannot delete files")


Bare excepts are almost always a very bad idea.


#---

print 'Closing FTP connection'
ftp.close()



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


abc for generators?

2010-05-19 Thread Alan Franzoni
Hello,
I was looking for an ABC for generators in python. While there's a
types.GeneratorType type object - which can't be used directly  and it's
not an abc - and many collections-related ABCs in the collections
module, there's no way to say a user-defined class as a generator, even
though it could expose the very same interface as a builtin, yield-based
generator.

I think it would be pretty useful.

comments?


-- 
Alan Franzoni
contact me at pub...@[mysurname].eu
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Discover PyH

2010-05-19 Thread Michel Claveau - MVP
Bonsoir ! 

La démarche me semble intéressante.
Je testerai le module quand j'aurai un peu de temps.

@-salutations
-- 
Michel Claveau 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What's the matter with docs.python.org?

2010-05-19 Thread Christian Mertes
by kjon 2010-03-24T16:40:21+00:00. 
> In Philip Semanchuk writes:
> >On Mar 24, 2010, at 12:05 PM, kj wrote:
> >> In the last couple of weeks, docs.python.org has been down repeatedly
> >> (like right now). Has anyone else noticed this?
> >http://downforeveryoneorjustme.com/docs.python.org
> Very handy. Thanks!
> ~K

Hey kjon,

I just found your mail in the archives because I've been experiencing the
same weird problems and I couldn't believe they wouldn't fix their server
for such a long time. I'd like to know what downforeveryoneorjustme.com does
because it's so lightning fast. Pinging the server? Works for me. Looking for
port 80? It's open. Connecting to it and getting a web page? That's where things
start to get interesting:

> $ telnet docs.python.org 80
> Trying 2001:888:2000:d::a2...
> Trying 82.94.164.162...
> Connected to docs.python.org.
> Escape character is '^]'.
> GET / HTTP/1.0
> 
> 
> 
> Connection closed by foreign host.

... after a really long time. The server wouldn't serve me. Opera reports a
network error right away though, not waiting for a timeout. And the best part:
Chrome and Firefox just get me the website. Wireshark reveals that both latter
browsers get a "304 Not Modified" response and then do a lot of weird stuff 
involving
DNS as well as HTTP to finally deliver a web page. Opera does no such thing but 
only
sends a request to 2001:888:2000:d::a2. Yeah, right, that's an IPv6 address.
I really don't understand the details of what's going on here but chances are
that you also use Opera, kjon and those who replied to you didn't?

I reported docs.python.org as a broken page to the Opera devs but I'm also 
Ccing this
mail to the server admin because this seems to be a more complex problem than 
just
a broken (if at all) web browser.

Best regards,

Christian



signature.asc
Description: This is a digitally signed message part
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What's the matter with docs.python.org?

2010-05-19 Thread member thudfoo
On Wed, May 19, 2010 at 9:23 AM, Christian Mertes
 wrote:
> by kjon 2010-03-24T16:40:21+00:00.
>> In Philip Semanchuk writes:
>> >On Mar 24, 2010, at 12:05 PM, kj wrote:
>> >> In the last couple of weeks, docs.python.org has been down repeatedly
>> >> (like right now). Has anyone else noticed this?
>> >http://downforeveryoneorjustme.com/docs.python.org
>> Very handy. Thanks!
>> ~K
>
> Hey kjon,
>
> I just found your mail in the archives because I've been experiencing the
> same weird problems and I couldn't believe they wouldn't fix their server
> for such a long time. I'd like to know what downforeveryoneorjustme.com does
> because it's so lightning fast. Pinging the server? Works for me. Looking for
> port 80? It's open. Connecting to it and getting a web page? That's where 
> things
> start to get interesting:
>
>> $ telnet docs.python.org 80
>> Trying 2001:888:2000:d::a2...
>> Trying 82.94.164.162...
>> Connected to docs.python.org.
>> Escape character is '^]'.
>> GET / HTTP/1.0
>>
>>
>>
>> Connection closed by foreign host.
>
> ... after a really long time. The server wouldn't serve me. Opera reports a
> network error right away though, not waiting for a timeout. And the best part:
> Chrome and Firefox just get me the website. Wireshark reveals that both latter
> browsers get a "304 Not Modified" response and then do a lot of weird stuff 
> involving
> DNS as well as HTTP to finally deliver a web page. Opera does no such thing 
> but only
> sends a request to 2001:888:2000:d::a2. Yeah, right, that's an IPv6 address.
> I really don't understand the details of what's going on here but chances are
> that you also use Opera, kjon and those who replied to you didn't?
>
> I reported docs.python.org as a broken page to the Opera devs but I'm also 
> Ccing this
> mail to the server admin because this seems to be a more complex problem than 
> just
> a broken (if at all) web browser.
>
> Best regards,
>
>        Christian
>

Worked for me:

~/isos2burn> telnet docs.python.org 80
Trying 82.94.164.162...
Connected to docs.python.org.
Escape character is '^]'.
GET/HTTP/1.0


302 Found

Found
The document has moved http://www.python.org";>here.

Apache/2.2.9 (Debian) DAV/2 SVN/1.5.1 mod_ssl/2.2.9
OpenSSL/0.9.8g mod_wsgi/2.5 Python/2.5.2 Server at dinsdale.python.org
Port 80

Connection closed by foreign host.
~/isos2burn> date
Wed May 19 09:49:11 PDT 2010
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to determine subprocess.Popen() failed when shell=True

2010-05-19 Thread python
For the archives - solution posted at
http://stackoverflow.com/questions/2861548/how-to-determine-subprocess-popen-failed-when-shelltrue

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


Re: how to cause a request for a missing class attribute cause its calculation

2010-05-19 Thread John Posner

On 5/18/2010 4:54 PM, Chris Rebert wrote:





Suggested reading: http://docs.python.org/library/functions.html#property


I've placed a revision to this official *property* documentation at:

  http://wiki.python.org/moin/AlternativeDescriptionOfProperty

There's also a gentle (I hope) intro to the *property* feature on the Wiki:

  http://wiki.python.org/moin/ComputedAttributesUsingPropertyObjects

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


ipython question

2010-05-19 Thread superpollo

In [39]: def f():
   : return 42
   :

In [40]: %psource f
No source found for f

In [41]:

i expected to see the source...
--
http://mail.python.org/mailman/listinfo/python-list


Re: Access to comp.lang.python

2010-05-19 Thread cjw

On 18-May-10 19:27 PM, Tim Chase wrote:

On 05/15/2010 05:34 PM, cjw wrote:

It seems that messages are coming from a number of sources, such as
gmane and google groups.

The problem is that many messages seem to get unlinked from their
threads.

I use Thunderbird 3.0.5 and wonder whether the problem lies with the
merge process, the server or my reader.


While others have told you about using gmane or other sources (direct
email, etc), I haven't seen anything fly by regarding the "unlinked from
their threads" portion of your question. Thunderbird 2.0 -> 3.0 changed
the default value for mail.strict_threading from False to True. Pulling
up the config editor (essentially the about:config, buried in the
options->advanced stuff, I think; or perhaps I have the "about:config"
plugin to do that) allows you to toggle this value back to "True". This
setting controls whether threads are defined *only* by the mail header
(strict=True), or whether TB also tries to guess based on the Subject
header (strict=False).

Toggle it (and perhaps restart TB?) and see if that helps rectify the
threading. There are a lot of folks here on c.l.p that use broken
newsreaders that don't correctly set news/threading headers.

-tkc




Thanks, mine is already set to "true".

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


Re: another question about classes and subclassing

2010-05-19 Thread cjw

On 18-May-10 17:51 PM, Alex Hall wrote:

Hi again all,
More about classes. I am still looking into my battleship game, and I
will have several different craft. All craft have common attribs
(position, alive, and so on) but each craft may be a surface ship,
submarine, or airplane. All three are craft, but a submarine can be
submerged or not, which does not apply to a surface ship or a plane,
while a plane can be airborne or not, which is not applicable to the
other two. Is there any advantage to creating a craft class:

class craft():
  #has attribs common to any and all craft
#end class

then doing something like:

class submarine(craft):
  #sub-specific attribs
#end class

How would I create a submarine, and then get at the craft-level
attribs? Come to think of it, how would I pass anything to the craft
constructor (position and alive, for example) when creating a new
submarine object? Am I even doing this right to make submarine a
subclass of craft? Thanks.


Looks OK to me.

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


Re: abc for generators?

2010-05-19 Thread Carl Banks
On May 19, 8:42 am, Alan Franzoni 
wrote:
> Hello,
> I was looking for an ABC for generators in python. While there's a
> types.GeneratorType type object - which can't be used directly  and it's
> not an abc - and many collections-related ABCs in the collections
> module, there's no way to say a user-defined class as a generator, even
> though it could expose the very same interface as a builtin, yield-based
> generator.
>
> I think it would be pretty useful.
>
> comments?

collections.Iterator


You don't actually need abc's to write custom iterators, BTW, the
following is an iterator for instance.

class Noise:
def __iter__(self):
return self
def __next__(self):
return random.random()


which is equivalent to the generator


def Noise():
while True:
yield random.random()


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


Best XML python package to learn for Ubuntu Linux ?

2010-05-19 Thread Robert Somerville

Hi;

I am about to get my feet wet with Python XML, there appears to be many 
libraries ... can someone recommend

a good package to use on Ubuntu ???


regards;
Robert Somerville
--
http://mail.python.org/mailman/listinfo/python-list


Re: Best XML python package to learn for Ubuntu Linux ?

2010-05-19 Thread Philip Semanchuk


On May 19, 2010, at 1:54 PM, Robert Somerville wrote:


Hi;

I am about to get my feet wet with Python XML, there appears to be  
many libraries ... can someone recommend

a good package to use on Ubuntu ???


Hi Robert,
xml.etree.ElementTree is in the Python standard library as of version  
2.5. It was a popular 3rd party package even before it became part of  
the standard library, so a lot of code uses it. It's a good place to  
start.


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


Re: What's the matter with docs.python.org?

2010-05-19 Thread Christian Mertes
On Mi, 2010-05-19 at 09:54 -0700, member thudfoo wrote:

> Worked for me:
> 
> ~/isos2burn> telnet docs.python.org 80
> Trying 82.94.164.162...
> Connected to docs.python.org.
> Escape character is '^]'.
> GET/HTTP/1.0
> 
> 
> 302 Found
> 
> Found
> The document has moved http://www.python.org";>here.
> 
> Apache/2.2.9 (Debian) DAV/2 SVN/1.5.1 mod_ssl/2.2.9
> OpenSSL/0.9.8g mod_wsgi/2.5 Python/2.5.2 Server at dinsdale.python.org
> Port 80
> 

Interesting. You did read the content you got though, didn't you?

Regards,

Christian


signature.asc
Description: This is a digitally signed message part
-- 
http://mail.python.org/mailman/listinfo/python-list


how to preserve hex value

2010-05-19 Thread Back9
Hi,

When converting a hex value, I'd like to preserve the decimal
position.
For example, 0x0A is converted to 0A not just A in string.

How do I do this?

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


Re: Delete files from FTP Server older then 7 days. Using ftputil and ftplib.

2010-05-19 Thread Giampaolo Rodolà
2010/5/19 pilgrim773 :
> Hello I am new to Python programming. I need a write a script which
> will delete files from a FTP server after they have reached a certain
> age, like 7 days for example. I have prepared this code below, but I
> get an error message:
> The system cannot find the path specified: '/test123/*.*' Probably
> someone can help me further? Thank you in advance!
>
> import os, time, ftputil
> from ftplib import FTP
>
> ftp = FTP('127.0.0.1')
> print "Automated FTP Maintainance"
> print 'Logging in.'
> ftp.login('admin', 'admin')
>
> # This is the directory that we want to go to
> directory = 'test123'
> print 'Changing to:' + directory
> ftp.cwd(directory)
> files = ftp.retrlines('LIST')
> print 'List of Files:' + files
> # ftp.remove('LIST')
>
> #---
> now = time.time()
> for f in os.listdir(directory):
>if os.stat(f).st_mtime < now - 7 * 86400:
>if os.directory.isfile(f):
>   os.remove(os.directory.join(directory, f))
> #except:
>#exit ("Cannot delete files")
> #---
>
> print 'Closing FTP connection'
> ftp.close()
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>

Instead of parsing the LIST response you can use MDTM command instead
(if the server supports it) which returns a standardized time-like
response for every file (ftp.sendcmd('MDTM filename')).

Alternatively you can do as you're doing now but using MLSD instead of
LIST (again, the server must support it).
MLSD returns something like this:

type=file;size=156;perm=r;modify=20071029155301;unique=801cd2; music.mp3
type=dir;size=0;perm=el;modify=20071127230206;unique=801e33; ebooks
type=file;size=211;perm=r;modify=20071103093626;unique=801e32; module.py

This would also be a lot cheaper in terms of data exchanged between
client and server and hence faster as you proceed "per-directory"
instead of "per-file in every directory".
Note that if the server is RFC-compliant both MDTM and MLSD times are
expressed as GMT times so an extra conversion to your local time may
be necessary.

Hope this helps,


--- Giampaolo
http://code.google.com/p/pyftpdlib
http://code.google.com/p/psutil
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to preserve hex value

2010-05-19 Thread member thudfoo
On Wed, May 19, 2010 at 11:38 AM, Back9  wrote:
> Hi,
>
> When converting a hex value, I'd like to preserve the decimal
> position.
> For example, 0x0A is converted to 0A not just A in string.
>
> How do I do this?
>
> TIA
> --
> http://mail.python.org/mailman/listinfo/python-list
>
|109> '%02X' % 10
<109> '0A'
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to preserve hex value

2010-05-19 Thread J. Cliff Dyer
On Wed, 2010-05-19 at 11:38 -0700, Back9 wrote:
> Hi,
> 
> When converting a hex value, I'd like to preserve the decimal
> position.
> For example, 0x0A is converted to 0A not just A in string.
> 
> How do I do this?
> 
> TIA

I'm not sure I understand what your use case is, but generally speaking,
it is better to treat hex values as integers (which they are) than as
string (which they are not).  0x0a is an integer value of ten.  There is
no change of decimal position gained by prepending a zero digit.  It
means exactly the same thing.  If you know how large a chunk is, you can
multiply (or bit-shift) and add to get the behavior you're looking for.

def concat(byte1, byte2):
return (byte1 << 8) + byte2

>>> hex(concat(0x43, 0x0a))
0x430a

One common use case is when using hex notation to represent sequences of
bytes.  In this case, you may want to work with a byte string instead.
To concatenate your numbers this way, convert each number to a byte
using chr(x) (Python 2.x)

To print it as hex, do something like this:  

def bytestring_to_hex(s):
return '0x + ''.join('%02x' % ord(x) for x in s) 

However, if you need an arbitrary number of zeros preserved, you're out
of luck.  They are semantically meaningless in python.  (Is semantically
meaningless redundant?)

Cheers,
Cliff



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


function that counts...

2010-05-19 Thread superpollo

... how many positive integers less than n have digits that sum up to m:

In [197]: def prttn(m, n):
tot = 0
for i in range(n):
s = str(i)
sum = 0
for j in range(len(s)):
sum += int(s[j])
if sum == m:
tot += 1
return tot
   .:

In [207]: prttn(25, 1)
Out[207]: 348

any suggestion for pythonizin' it?

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


Re: ipython question

2010-05-19 Thread Robert Kern

On 5/19/10 12:11 PM, superpollo wrote:

In [39]: def f():
: return 42
:

In [40]: %psource f
No source found for f

In [41]:

i expected to see the source...


You will want to ask IPython questions on the IPython mailing list:

  http://mail.scipy.org/mailman/listinfo/ipython-user

The reason you do not get the source is because there is no file that contains 
functions defined in the interactive interpreter. %psource uses the inspect 
module, and the inspect module explicitly only looks in real files using the 
linecache module. IPython could be modified to inject fake files into the 
linecache, but that's a chunk of work. I am sure they would be happy to 
incorporate a patch if you were to provide it to them.


--
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: function that counts...

2010-05-19 Thread Jerry Hill
On Wed, May 19, 2010 at 3:58 PM, superpollo  wrote:
> ... how many positive integers less than n have digits that sum up to m:
...
> any suggestion for pythonizin' it?

This is how I would do it:

def prttn(m, n):
"""How many positive integers less than n have digits that sum up to m"""
total = 0
for testval in range(n):
sumofdigits = sum(int(char) for char in str(testval))
if sumofdigits == m:
total += 1
return total

I added a docstring to the function, saying what it does, and what the
arguments are supposed to represent.  I also moved the
convert-to-string-and-sum-the-digits logic into a single generator
expression that's passed to the builtin sum function.  Oh, and I tried
to use slightly more expressive variable names.

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


Re: ipython question

2010-05-19 Thread superpollo

Robert Kern ha scritto:

On 5/19/10 12:11 PM, superpollo wrote:

In [39]: def f():
: return 42
:

In [40]: %psource f
No source found for f

In [41]:

i expected to see the source...


You will want to ask IPython questions on the IPython mailing list:

  http://mail.scipy.org/mailman/listinfo/ipython-user

The reason you do not get the source is because there is no file that 
contains functions defined in the interactive interpreter. %psource uses 
the inspect module, and the inspect module explicitly only looks in real 
files


but still:

In [218]: def f():
   .: return 42
   .:

In [219]: %save tmp.py 218
File `tmp.py` exists. Overwrite (y/[N])? y
The following commands were written to file `tmp.py`:
def f():
return 42


In [220]: !cat tmp.py
def f():
return 42

In [221]: %psource f
No source found for f
--
http://mail.python.org/mailman/listinfo/python-list


Re: ipython question

2010-05-19 Thread superpollo

superpollo ha scritto:

Robert Kern ha scritto:

On 5/19/10 12:11 PM, superpollo wrote:

In [39]: def f():
: return 42
:

In [40]: %psource f
No source found for f

In [41]:

i expected to see the source...


You will want to ask IPython questions on the IPython mailing list:

  http://mail.scipy.org/mailman/listinfo/ipython-user

The reason you do not get the source is because there is no file that 
contains functions defined in the interactive interpreter. %psource 
uses the inspect module, and the inspect module explicitly only looks 
in real files


but still:

In [218]: def f():
   .: return 42
   .:

In [219]: %save tmp.py 218
File `tmp.py` exists. Overwrite (y/[N])? y
The following commands were written to file `tmp.py`:
def f():
return 42


In [220]: !cat tmp.py
def f():
return 42

In [221]: %psource f
No source found for f


maybe i got it:

In [230]: import tmp

In [231]: %psource tmp.f
def f():
return 42


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


Re: ipython question

2010-05-19 Thread Robert Kern

On 5/19/10 3:10 PM, superpollo wrote:

Robert Kern ha scritto:

On 5/19/10 12:11 PM, superpollo wrote:

In [39]: def f():
: return 42
:

In [40]: %psource f
No source found for f

In [41]:

i expected to see the source...


You will want to ask IPython questions on the IPython mailing list:

http://mail.scipy.org/mailman/listinfo/ipython-user

The reason you do not get the source is because there is no file that
contains functions defined in the interactive interpreter. %psource
uses the inspect module, and the inspect module explicitly only looks
in real files


but still:

In [218]: def f():
.: return 42
.:

In [219]: %save tmp.py 218
File `tmp.py` exists. Overwrite (y/[N])? y
The following commands were written to file `tmp.py`:
def f():
return 42


In [220]: !cat tmp.py
def f():
return 42

In [221]: %psource f
No source found for f


So? The function object f knows nothing about the file tmp.py. If you were to 
import tmp and then ask for %psource tmp.f, it should work.


--
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: function that counts...

2010-05-19 Thread René 'Necoro' Neumann
Am 19.05.2010 21:58, schrieb superpollo:
> ... how many positive integers less than n have digits that sum up to m:
> 
> In [197]: def prttn(m, n):
> tot = 0
> for i in range(n):
> s = str(i)
> sum = 0
> for j in range(len(s)):
> sum += int(s[j])
> if sum == m:
> tot += 1
> return tot
>.:
> 
> In [207]: prttn(25, 1)
> Out[207]: 348
> 
> any suggestion for pythonizin' it?
> 
> bye

An idea would be:

>>> def prttn(m, n):
... return sum(1 for x in range(n) if sum(map(int, str(x))) == m)

A small oneliner :)

(I first had "return len([x for x in ...])" but the above avoids
creating an intermediate list)

- René



signature.asc
Description: OpenPGP digital signature
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: function that counts...

2010-05-19 Thread superpollo

Jerry Hill ha scritto:

On Wed, May 19, 2010 at 3:58 PM, superpollo  wrote:

... how many positive integers less than n have digits that sum up to m:

...

any suggestion for pythonizin' it?


This is how I would do it:

def prttn(m, n):
"""How many positive integers less than n have digits that sum up to m"""
total = 0
for testval in range(n):
sumofdigits = sum(int(char) for char in str(testval))


this line gives me this:

TypeError: 'int' object is not callable

is it some new feature in >2.5 ?


if sumofdigits == m:
total += 1
return total

I added a docstring to the function, saying what it does, and what the
arguments are supposed to represent.  I also moved the
convert-to-string-and-sum-the-digits logic into a single generator
expression that's passed to the builtin sum function.  Oh, and I tried
to use slightly more expressive variable names.


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


Re: function that counts...

2010-05-19 Thread superpollo

René 'Necoro' Neumann ha scritto:

Am 19.05.2010 21:58, schrieb superpollo:

... how many positive integers less than n have digits that sum up to m:

In [197]: def prttn(m, n):
tot = 0
for i in range(n):
s = str(i)
sum = 0
for j in range(len(s)):
sum += int(s[j])
if sum == m:
tot += 1
return tot
   .:

In [207]: prttn(25, 1)
Out[207]: 348

any suggestion for pythonizin' it?

bye


An idea would be:


def prttn(m, n):

... return sum(1 for x in range(n) if sum(map(int, str(x))) == m)


TypeError: 'int' object is not callable

on 2.5.4



A small oneliner :)

(I first had "return len([x for x in ...])" but the above avoids
creating an intermediate list)

- René


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


Re: Installing Lightweight Python

2010-05-19 Thread News123


Nima Mohammadi wrote:
> Well, I tried to run Python with -v option. It seems that python26.zip
> is partially loaded but can't be used, because zlib is "unavailable".
This is normal.
the zip library itself cannot be zipped, as it is needed to unzip and
extract th other libs.

> 
> n...@nima-desktop:~/py$ ./bin/python -v
> Could not find platform independent libraries 
> Could not find platform dependent libraries 
> Consider setting $PYTHONHOME to [:]
> # installing zipimport hook
> import zipimport # builtin
> # installed zipimport hook
> # zipimport: found 2509 names in /home/nima/py/lib/python26.zip
> # zipimport: zlib UNAVAILABLE
> 'import site' failed; traceback:
> zipimport.ZipImportError: can't decompress data; zlib not available
> # zipimport: zlib UNAVAILABLE
> 
> Python 2.6.5 (r265:79063, May 17 2010, 18:36:54)
> [GCC 4.4.3] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
 import sys
 sys.path
> ['', '/home/nima/py/lib/python26.zip', '/home/nima/py/lib/python2.6/',
> '/home/nima/py/lib/python2.6/plat-linux2', '/home/nima/py/lib/
> python2.6/lib-tk', '/home/nima/py/lib/python2.6/lib-old', '/home/nima/
> py/lib/lib-dynload']
> 
> 
> --
> Yours sincerely,
> Nima Mohammadi
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: function that counts...

2010-05-19 Thread Jerry Hill
On Wed, May 19, 2010 at 4:25 PM, superpollo  wrote:
> Jerry Hill ha scritto:
>>        sumofdigits = sum(int(char) for char in str(testval))
>
> this line gives me this:
>
> TypeError: 'int' object is not callable
>
> is it some new feature in >2.5 ?

No, sum() has been a builtin since Python 2.3.  Based on your first
post, you have probably shadowed the builtin "sum" function by
assigning an integer to a variable named "sum".

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


Re: function that counts...

2010-05-19 Thread Mark Dickinson
On May 19, 9:30 pm, superpollo  wrote:
> René 'Necoro' Neumann ha scritto:
> > An idea would be:
>
>  def prttn(m, n):
> > ...        return sum(1 for x in range(n) if sum(map(int, str(x))) == m)
>
> TypeError: 'int' object is not callable
>
> on 2.5.4

The TypeError is almost certainly because you've created a integer
'sum' variable in your script/interpreter session, hiding the built-in
sum function.

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


Re: function that counts...

2010-05-19 Thread superpollo

Jerry Hill ha scritto:

On Wed, May 19, 2010 at 4:25 PM, superpollo  wrote:

Jerry Hill ha scritto:

   sumofdigits = sum(int(char) for char in str(testval))

this line gives me this:

TypeError: 'int' object is not callable

is it some new feature in >2.5 ?


No, sum() has been a builtin since Python 2.3.  Based on your first
post, you have probably shadowed the builtin "sum" function by
assigning an integer to a variable named "sum".


o my... thanks!

In [266]: del(sum)

In [267]: def prttn2(m, n):
"""How many positive integers less than n have digits that sum up 
to m"""

total = 0
for testval in range(n):
sumofdigits = sum(int(char) for char in str(testval))
if sumofdigits == m:
total += 1
return total
   .:

In [275]: def prttn3(m, n):
return sum(1 for x in range(n) if sum(map(int, str(x))) == m)
   .:

In [277]: prttn(25, 1)
Out[277]: 348

In [278]: prttn2(25, 1)
Out[278]: 348

In [279]: prttn3(25, 1)
Out[279]: 348

ok, bye!
--
http://mail.python.org/mailman/listinfo/python-list


Re: function that counts...

2010-05-19 Thread superpollo

Mark Dickinson ha scritto:

On May 19, 9:30 pm, superpollo  wrote:

René 'Necoro' Neumann ha scritto:

An idea would be:

def prttn(m, n):

...return sum(1 for x in range(n) if sum(map(int, str(x))) == m)

TypeError: 'int' object is not callable

on 2.5.4


The TypeError is almost certainly because you've created a integer
'sum' variable in your script/interpreter session, hiding the built-in
sum function.


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


Re: function that counts...

2010-05-19 Thread René 'Necoro' Neumann
Am 19.05.2010 22:58, schrieb superpollo:
> 
> In [277]: prttn(25, 1)
> Out[277]: 348
> 
> In [278]: prttn2(25, 1)
> Out[278]: 348
> 
> In [279]: prttn3(25, 1)
> Out[279]: 348
> 
> ok, bye!

Just because I was curios:

nec...@zakarumiy ~ % python -m timeit "import test; test.prttn(25,1)"
10 loops, best of 3: 108 msec per loop

nec...@zakarumiy ~ % python -m timeit "import test; test.prttn2(25,1)"
10 loops, best of 3: 157 msec per loop

nec...@zakarumiy ~ % python -m timeit "import test; test.prttn3(25,1)"
10 loops, best of 3: 137 msec per loop

Note: This is probably not representative ... just a quick check to get
a raw feeling.

- René



signature.asc
Description: OpenPGP digital signature
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: abc for generators?

2010-05-19 Thread Alan Franzoni
On 5/19/10 7:24 PM, Carl Banks wrote:
> collections.Iterator

That would just support the next() method. But enhanced generators
interface - supporting coroutines as well - include send(), throw() and
close().


-- 
Alan Franzoni
contact me at pub...@[mysurname].eu
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: function that counts...

2010-05-19 Thread Steven D'Aprano
On Wed, 19 May 2010 22:58:22 +0200, superpollo wrote:

> In [266]: del(sum)


del is a statement, not a function, so the brackets are pointless. This 
is like writing:

x = (1)

instead of

x = 1

`del sum` is all you need.



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


Re: function that counts...

2010-05-19 Thread Steven D'Aprano
On Wed, 19 May 2010 21:58:04 +0200, superpollo wrote:

> ... how many positive integers less than n have digits that sum up to m:
> 
> In [197]: def prttn(m, n):

Does the name "prttn" mean anything? I'm afraid I keep reading it as a 
mispelling of "print n".


[...]
>  s = str(i)
>  sum = 0
>  for j in range(len(s)):
>  sum += int(s[j])

Rather than iterating over an index j = 0, 1, 2, ... and then fetching 
the jth character of the string, you can iterate over the characters 
directly. So the inner loop is better written:

for c in s:
sum += int(c)




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


struct

2010-05-19 Thread Back9
Can anyone explain the difference between f and d in struct unpack?
When using them, some data work in either one not both.
To me it seems to be same,

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


Re: struct

2010-05-19 Thread Gary Herron

On 05/19/2010 02:53 PM, Back9 wrote:

Can anyone explain the difference between f and d in struct unpack?
When using them, some data work in either one not both.
To me it seems to be same,

TIA
   


'f' is single precision float (32 bits), and
'd'  is a double precision float (64 bits)

Gary Herron

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


compile() error

2010-05-19 Thread Iuri
>>> compile("for i in [1,2,3]:\n pass\n#end\n", "test_file.py", "exec")
 at 0x266a378, file "test_file.py", line 1>
>>> compile("for i in [1,2,3]:\n pass\n#end", "test_file.py", "exec")
Traceback (most recent call last):
File "", line 1, in 
File "", line 2, in cptest
File "test_file.py", line 3
#end
^
SyntaxError: invalid syntax

I guess these commands explain the problem.

Any ideas about what is happening?

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


Re: compile() error

2010-05-19 Thread Benjamin Peterson
Iuri  gmail.com> writes:
> Any ideas about what is happening?

Until Python 2.7/3.2, compile() does't like sources which don't end in a 
newline.



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


Re: Python Script for Website Mirroring

2010-05-19 Thread Vincent Davis
Probably need a little more info to help. Are you running both sites, are
there database involved?
If it is a simple site you could just transfer with ftp and have the script
updated any urls.

Vincent

On Wed, May 19, 2010 at 8:21 AM, Kevin Rea  wrote:

>  Hello Folks:
>
> Can you please point me to a decent Python script(s) that I could customize
> to do automatic Website mirroring?
>
> Thanks Much!
> Kevin
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>
  *Vincent Davis
720-301-3003 *
[email protected]
 my blog  |
LinkedIn
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: compile() error

2010-05-19 Thread Iuri
Thanks, Benjamin.

I used Python 2.6 to these tests.

[]s
iuri


On Wed, May 19, 2010 at 7:31 PM, Benjamin Peterson wrote:

> Iuri  gmail.com> writes:
> > Any ideas about what is happening?
>
> Until Python 2.7/3.2, compile() does't like sources which don't end in a
> newline.
>
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Script for Website Mirroring

2010-05-19 Thread Christian Mertes
On Mi, 2010-05-19 at 16:35 -0600, Vincent Davis wrote:
> If it is a simple site you could just transfer with ftp

Or rsync -a or wget -m ... like tools that were specifically made for
this task. 

Therefore something like subprocess.call(["rsync", "-az", "-e", "ssh",
"--delete", source, target]) should be part of your Python script I
guess ;)

Regards,

Christian



signature.asc
Description: This is a digitally signed message part
-- 
http://mail.python.org/mailman/listinfo/python-list


client server console app with cmd library

2010-05-19 Thread [email protected]
Hi to all,
i need some hints about a console application i' m trying.
I want to make it act as a client and as a server at a same time.
And since it is a console application i' m using cmd library.
I want something that works like asterisk. while working with my app
i want to listen for incoming requests, that they appear automatically
at my console.
Any design considerations?
Do i have to use threads?
Please i want your advice.
Any examples somewhere?

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


Re: What's the matter with docs.python.org?

2010-05-19 Thread Rhodri James
On Wed, 19 May 2010 17:23:18 +0100, Christian Mertes  
 wrote:


I reported docs.python.org as a broken page to the Opera devs but I'm  
also Ccing this
mail to the server admin because this seems to be a more complex problem  
than just

a broken (if at all) web browser.


It's been working fine for me, using Opera on Window and Ubuntu, for the
last week or so.

--
Rhodri James *-* Wildebeeste Herder to the Masses
--
http://mail.python.org/mailman/listinfo/python-list


Re: Classes and threading

2010-05-19 Thread Aahz
In article ,
Christian Heimes   wrote:
>>
>> class nThread(threading.Thread):
>> def __init__(self, *args, **kwds):
>> threading.Thread.__init__(self, *args, **kwds)
>> # your other stuff here
>
>Since Thread is a new style class, this should read:
>
>class NThread(threading.thread):
> def __init__(self, *args, **kwargs):
> super(NThread, self).__init__(*args, **kwargs)

"Should" is too strong.  There are plenty of reasons for wanting to avoid
the mess of super().
-- 
Aahz ([email protected])   <*> http://www.pythoncraft.com/

f u cn rd ths, u cn gt a gd jb n nx prgrmmng.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What's the matter with docs.python.org?

2010-05-19 Thread Aahz
In article ,
Christian Mertes   wrote:
>
> $ telnet docs.python.org 80
> Trying 2001:888:2000:d::a2...
> Trying 82.94.164.162...
> Connected to docs.python.org.
> Escape character is '^]'.

IPv6 has sometimes been problematical -- try disabling it.  Also, I
think you need to pass the host HTTP header to access docs.python.org
-- 
Aahz ([email protected])   <*> http://www.pythoncraft.com/

f u cn rd ths, u cn gt a gd jb n nx prgrmmng.
-- 
http://mail.python.org/mailman/listinfo/python-list


KaPy -- Karlsruhe Python User Group meeting, 2010-05-21, 19:00

2010-05-19 Thread Jürgen Erhard
The Karlsruhe Python User Group (KaPy) meets again.

Friday, 2010-04-16 (May 21st) at 19:00 (7pm) in the rooms of Entropia
eV (the local affiliate of the
CCC).  See http://entropia.de/wiki/Anfahrt on how to get there.

For your calendars: meetings are held monthly, on the 3rd Friday.

Bye, J

PS: Sorry for the late announcement.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: abc for generators?

2010-05-19 Thread Carl Banks
On May 19, 2:27 pm, Alan Franzoni 
wrote:
> On 5/19/10 7:24 PM, Carl Banks wrote:
>
> > collections.Iterator
>
> That would just support the next() method. But enhanced generators
> interface - supporting coroutines as well - include send(), throw() and
> close().

Hmm, don't know.

Maybe you could contribute one, it sounds like a rather
unobjectionable idea likely to be accepted into Python.


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


Re: ipython question

2010-05-19 Thread Terry Reedy

On 5/19/2010 4:14 PM, superpollo wrote:


In [219]: %save tmp.py 218
File `tmp.py` exists. Overwrite (y/[N])? y
The following commands were written to file `tmp.py`:
def f():
return 42


In [220]: !cat tmp.py
def f():
return 42

In [221]: %psource f
No source found for f


maybe i got it:

In [230]: import tmp

In [231]: %psource tmp.f
def f():
return 42


I use IDLE, write functions and other code as desired in a temp file to 
begin with, hit F5, and the window with source stays around until closef 
it and the file until deleted.



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


Re: compile() error

2010-05-19 Thread Steven D'Aprano
On Wed, 19 May 2010 22:31:31 +, Benjamin Peterson wrote:

> Iuri  gmail.com> writes:
>> Any ideas about what is happening?
> 
> Until Python 2.7/3.2, compile() does't like sources which don't end in a
> newline.


Are you sure about that?


>>> x = compile("print __import__('sys').version, 'see ma, no newline'", 
"", "single")
>>> exec x
2.5 (r25:51908, Nov  6 2007, 16:54:01)
[GCC 4.1.2 20070925 (Red Hat 4.1.2-27)] see ma, no newline


The original post isn't showing up for me, so I don't know the full 
context, but it seems to me that compile can deal with the lack of 
newline.


>>> x = compile("""import sys
... print sys.version
... print 'see ma, still no final newline!'""", "", "exec")
>>> exec x
2.5 (r25:51908, Nov  6 2007, 16:54:01)
[GCC 4.1.2 20070925 (Red Hat 4.1.2-27)]
see ma, still no final newline!




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


links button gone from python.org

2010-05-19 Thread [email protected]
 I noticed that that the link to that section is gone.  The page
seems to be there when I use the url that is stored on my computer.
Unrelated but I will mention that It is sad to see that dr dobs python
newsletter has vanished, I enjoyed reading that from time to time.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: compile() error

2010-05-19 Thread Iuri
Steven, it works fine to some cases.

I have problem only when last line is a comment and before it I have an
indentation. It is a specific case, and it is not a common case.

>>> compile("for i in [1,2,3]:\n pass\n#end", "test_file.py", "exec")

What I understanded about Benjamin's answer is compile() without a new line
at the end has an indetermined behaviour, so in some cases it works.

Iuri de Silvio

On Wed, May 19, 2010 at 9:52 PM, Steven D'Aprano <
[email protected]> wrote:

> On Wed, 19 May 2010 22:31:31 +, Benjamin Peterson wrote:
>
> > Iuri  gmail.com> writes:
> >> Any ideas about what is happening?
> >
> > Until Python 2.7/3.2, compile() does't like sources which don't end in a
> > newline.
>
>
> Are you sure about that?
>
>
> >>> x = compile("print __import__('sys').version, 'see ma, no newline'",
> "", "single")
> >>> exec x
> 2.5 (r25:51908, Nov  6 2007, 16:54:01)
> [GCC 4.1.2 20070925 (Red Hat 4.1.2-27)] see ma, no newline
>
>
> The original post isn't showing up for me, so I don't know the full
> context, but it seems to me that compile can deal with the lack of
> newline.
>
>
> >>> x = compile("""import sys
> ... print sys.version
> ... print 'see ma, still no final newline!'""", "", "exec")
> >>> exec x
> 2.5 (r25:51908, Nov  6 2007, 16:54:01)
> [GCC 4.1.2 20070925 (Red Hat 4.1.2-27)]
> see ma, still no final newline!
>
>
>
>
> --
> Steven
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: compile() error

2010-05-19 Thread Jerry Hill
On Wed, May 19, 2010 at 8:52 PM, Steven D'Aprano
 wrote:
> On Wed, 19 May 2010 22:31:31 +, Benjamin Peterson wrote:
>> Iuri  gmail.com> writes:
>>> Any ideas about what is happening?
>>
>> Until Python 2.7/3.2, compile() does't like sources which don't end in a
>> newline.

It appears to be this bug: http://bugs.python.org/issue1184112 which
is still open.  Maybe a fix got checked in without the bug being
closed?  I don't have 2.7 or 3.2 here to test with.

> The original post isn't showing up for me, so I don't know the full
> context, but it seems to me that compile can deal with the lack of
> newline.

The original example was:
compile("for i in [1,2,3]:\n pass\n#end", "test_file.py", "exec")

Bug 1184112 is only triggered with an indented block followed by a
comment with no newline following the comment.

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


Fwd: question on logging module - solved

2010-05-19 Thread frank zhu
FYI.

-- Forwarded message --
From: Cameron Simpson 
Date: Wed, May 19, 2010 at 6:18 PM
Subject: Re: question on logging module
To: frank zhu 


On 19May2010 11:55, frank zhu  wrote:
| Thanks Cameron. That was the problem. I copied the sample code and named
it
| logging.py. which was bad.

You might want to post this info to the list to save follow-on
discussion.

One way to check that what you want actually happened is like this:

 [/Users/cameron]g4*> python
 Python 2.6.5 (r265:79063, May 17 2010, 14:44:07)
 [GCC 4.0.1 (Apple Inc. build 5493)] on darwin
  Type "help", "copyright", "credits" or "license" for more information.
 >>> import logging
  >>> sorted(logging.__dict__.keys())

which will report the names in what you imported.

Cheers,
--
Cameron Simpson  DoD#743
http://www.cskk.ezoshosting.com/cs/
-- 
http://mail.python.org/mailman/listinfo/python-list


Display file names in Tkinter Listbox

2010-05-19 Thread Rick
Hello,

My first attenpt at a simple  python Tkinter application. I wanted to
see how to load file names into a listbox from a menu. This is what I
got until the part of displaying the file names in a listbox, which I
could not figfure out how to do?

Any help would be appreciated. Trying to do this as simple as possible
to understand.

The "print fileNames" does work but how to display it in listbox?

from Tkinter import *
from tkFileDialog   import askopenfilenames

class MyCode:
   def __init__(self):
  root = Tk()
  
  menubar = Menu(root)
  filemenu = Menu(menubar)
  
  lbox = Listbox(root, width=50).pack()
  
  menubar.add_cascade(label='File', menu=filemenu)
  filemenu.add_command(label='New Project')
  filemenu.add_command(label='Load Files...', command=self.OnLoad)
  

  filemenu.add_command(label='Exit', command=root.quit)
  
  root.config(menu=menubar)
  
  root.mainloop()
  
  
   def OnLoad(self):
  fileNames = askopenfilenames(filetypes=[('Split Files', '*')])
  print fileNames

  
myApp = MyCode()
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: function that counts...

2010-05-19 Thread Richard Thomas
For this kind of problem you should avoid all that stringification. I
find it best to deal with sequences of digits of a fixed length and go
from there. For example:

def count1(m, n, cache={}):
"""Number of digit sequences of length `n` summing to `m`."""
if n < 0 or m < 0:
return 0
elif n == 0:
return int(m == 0)
elif (m, n) in cache:
return cache[m, n]
# This is an optimisation using the combinatoric choose function.
#elif m < 10:
#result = choose(n + m - 1, n - 1)
else:
result = 0
for digit in xrange(min(10, m + 1)):
result += count1(m - digit, n - 1)
cache[m, n] = result
return result

Notice the caching of results. With this we can compute the required
thing quite easily:

def count2(m, n):
"""Number of numbers less than `n` whose digits sum to `m`."""
result = 0
digits = map(int, str(n))
length = len(digits)
for idx, digit in enumerate(digits):
for seq_digit in xrange(digit):
seq_limit = m - seq_digit
seq_length = length - idx - 1
result += count1(seq_limit, seq_length)
m -= digit
return result

Essentially we move through the number left to right, choose digits
less than the digit in the number and count digit sequences to fill
the remainder. Then fix the actual digit and step forward.

An approach like this avoids the relatively slow stringification
process and makes decent use of caching and iteration (both easy and
efficient in Python).

In [1]: count2(25, 1)
Out[1]: 348

In [2]: timeit count2(25, 1)
10 loops, best of 3: 12.6 us per loop
-- 
http://mail.python.org/mailman/listinfo/python-list


Newbie Alert: subprocess.call

2010-05-19 Thread Carbon
I am new to Python and am trying to write a GUI wrapper script in python 
2.5 to get username and passwords from Linux users to send as options to 
run an app on a 2X terminal server. I came across the easygui module and 
its multpasswordbox function, which made popping a dialog box and storing 
the usernames very painless. 

However, subprocess.call as implemented below doesn't work. For some 
reason the "-s ts.mycompany.org:80" parameter is being interpreted 
differently by the application when sent from the python script than it 
does when sent from the BASH script below. The :80 is the default port so 
it isn't technically required, but the script doesn't work without it 
either.

Any ideas where I should look? Is subprocess.call the best way to do what 
I want? Any advice would be most appreciated.


Here's the broken bit:

print "Reply was:", fieldValues
print "Reply was:", fieldValues[0], fieldValues[1]

subprocess.call(["/opt/2X/Client/bin/appserverclient", "-u fieldValues
[0]", "-p fieldValues[1]", "-s ts.mycompany.org:80", "-d corp", "-S 
local", "-c 16", "-e 0xF", "-l 0x0409", "-a #1"])


Output:

m...@work:~/bin$ ./demo2.py 
Reply was: ['MyUsername', 'MyPassword']
Reply was: MyUsername MyPassword

ERROR in CTcpConnector:  ts.mycompany.org: unable to resolve host
Error 7: TCP/IP connection: unable to resolve host.


This BASH script runs correctly:
m...@work:~/bin$ cat 2xconnect
#!/bin/bash

USER=$1
PASS=$2

/opt/2X/Client/bin/appserverclient \
-u "$USER" \
-p "$PASS" \
-s ts.mycompany.org:80 \
-d corp \
-S local \
-c 16 \
-e 0xF \
-l 0x0409 \
-m 2G \
-a "#1" 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie Alert: subprocess.call

2010-05-19 Thread Patrick Maupin
On May 19, 9:27 pm, Carbon  wrote:
> I am new to Python and am trying to write a GUI wrapper script in python
> 2.5 to get username and passwords from Linux users to send as options to
> run an app on a 2X terminal server. I came across the easygui module and
> its multpasswordbox function, which made popping a dialog box and storing
> the usernames very painless.
>
> However, subprocess.call as implemented below doesn't work. For some
> reason the "-s ts.mycompany.org:80" parameter is being interpreted
> differently by the application when sent from the python script than it
> does when sent from the BASH script below. The :80 is the default port so
> it isn't technically required, but the script doesn't work without it
> either.
>
> Any ideas where I should look? Is subprocess.call the best way to do what
> I want? Any advice would be most appreciated.
>
> Here's the broken bit:
>
> print "Reply was:", fieldValues
> print "Reply was:", fieldValues[0], fieldValues[1]
>
> subprocess.call(["/opt/2X/Client/bin/appserverclient", "-u fieldValues
> [0]", "-p fieldValues[1]", "-s ts.mycompany.org:80", "-d corp", "-S
> local", "-c 16", "-e 0xF", "-l 0x0409", "-a #1"])
>
> Output:
>
> m...@work:~/bin$ ./demo2.py
> Reply was: ['MyUsername', 'MyPassword']
> Reply was: MyUsername MyPassword
>
> ERROR in CTcpConnector:  ts.mycompany.org: unable to resolve host
> Error 7: TCP/IP connection: unable to resolve host.
>
> This BASH script runs correctly:
> m...@work:~/bin$ cat 2xconnect
> #!/bin/bash
>
> USER=$1
> PASS=$2
>
> /opt/2X/Client/bin/appserverclient \
> -u "$USER" \
> -p "$PASS" \
> -s ts.mycompany.org:80 \
> -d corp \
> -S local \
> -c 16 \
> -e 0xF \
> -l 0x0409 \
> -m 2G \
> -a "#1"

I think, for example, instead of "-d corp", you want "-d" and "corp"
in your list.

I usually make a string like I would pass to bash, and then
do .split() on it to get the list.  This works fine unless you need
embedded spaces anywhere.

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


Re: Newbie Alert: subprocess.call

2010-05-19 Thread Ben Finney
Patrick Maupin  writes:

> On May 19, 9:27 pm, Carbon  wrote:
> > subprocess.call(["/opt/2X/Client/bin/appserverclient", "-u
> > fieldValues [0]", "-p fieldValues[1]", "-s ts.mycompany.org:80", "-d
> > corp", "-S local", "-c 16", "-e 0xF", "-l 0x0409", "-a #1"])

As Patrick says, you need to give the arguments to the command as
the shell would pass them. That means option arguments separate from
value arguments, etc.

> I think, for example, instead of "-d corp", you want "-d" and "corp"
> in your list.

Right.

> I usually make a string like I would pass to bash, and then do
> .split() on it to get the list. This works fine unless you need
> embedded spaces anywhere.

Better is to use ‘shlex.split’ to split the string as a shell parser
would do http://docs.python.org/library/shlex#shlex.split>.

-- 
 \  “Not using Microsoft products is like being a non-smoker 40 or |
  `\ 50 years ago: You can choose not to smoke, yourself, but it's |
_o__)   hard to avoid second-hand smoke.” —Michael Tiemann |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


How to unescape a raw string?

2010-05-19 Thread python
How can I unescape a raw string so that it behaves as a non-raw
string?

For example, if I read the string "\n\t A B C\" D E F \xa0
\u1234" from a text file, how can I convert (unescape?) this
string so that \n, \t, \", \x, and \u get converted to a newline,
tab, double quote, hex encoded and unicode encoded chars?

I know I can do this explictly via a series of .replace()
methods, but certainly there must be a built-in way to do this on
a generic basis?

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


Re: Newbie Alert: subprocess.call

2010-05-19 Thread Chris Rebert
On Wed, May 19, 2010 at 7:27 PM, Carbon  wrote:
> I am new to Python and am trying to write a GUI wrapper script in python
> 2.5 to get username and passwords from Linux users to send as options to
> run an app on a 2X terminal server. I came across the easygui module and
> its multpasswordbox function, which made popping a dialog box and storing
> the usernames very painless.
>
> However, subprocess.call as implemented below doesn't work. For some
> reason the "-s ts.mycompany.org:80" parameter is being interpreted
> differently by the application when sent from the python script than it
> does when sent from the BASH script below. The :80 is the default port so
> it isn't technically required, but the script doesn't work without it
> either.
>
> Any ideas where I should look? Is subprocess.call the best way to do what
> I want? Any advice would be most appreciated.
>
>
> Here's the broken bit:
>
> print "Reply was:", fieldValues
> print "Reply was:", fieldValues[0], fieldValues[1]
>
> subprocess.call(["/opt/2X/Client/bin/appserverclient", "-u fieldValues
> [0]", "-p fieldValues[1]", "-s ts.mycompany.org:80", "-d corp", "-S
> local", "-c 16", "-e 0xF", "-l 0x0409", "-a #1"])

RTFineM (http://docs.python.org/library/subprocess.html#subprocess.Popen
). Verbatim quote, emphasis mine:

>>> command_line = raw_input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print args
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt',
'-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
***Note in particular that options (such as -input) and arguments
(such as eggs.txt) that are separated by whitespace in the shell go in
separate list elements***, while arguments that need quoting or
backslash escaping when used in the shell (such as filenames
containing spaces or the echo command shown above) are single list
elements.

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


Re: How to unescape a raw string?

2010-05-19 Thread Chris Rebert
On Wed, May 19, 2010 at 8:34 PM,   wrote:
> How can I unescape a raw string so that it behaves as a non-raw string?

That's not what the notion of raw strings in Python technically means,
but anyway...

> For example, if I read the string "\n\t A B C\" D E F \xa0 \u1234"

I'll assume you're quoting the file contents itself verbatim here,
rather than a Python string literal (which would require doubling up
on the backslashes).

> from a
> text file, how can I convert (unescape?) this string so that \n, \t, \", \x,
> and \u get converted to a newline, tab, double quote, hex encoded and
> unicode encoded chars?
>
> I know I can do this explictly via a series of .replace() methods, but
> certainly there must be a built-in way to do this on a generic basis?

new_string = your_string.decode('string_escape')

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


Re: function that counts...

2010-05-19 Thread John Posner

On 5/19/2010 5:51 PM, Steven D'Aprano wrote:

On Wed, 19 May 2010 21:58:04 +0200, superpollo wrote:


Rather than iterating over an index j = 0, 1, 2, ... and then fetching
the jth character of the string, you can iterate over the characters
directly. So the inner loop is better written:

for c in s:
 sum += int(c)



Or, as a one-liner (and not shadowing the built-in *sum* function):

  mysum = sum(map(int, str(i)))

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


Best practice for string substition with gettext

2010-05-19 Thread python
Looking for best practice advice on what string substitution
technique to use when using gettext(). Or do all techniques apply
equally?

I can think of at least 3 string techniques:

1. Classic "%" based formatting:

"My name is %(name)s" % locals()

2. .format() based formatting:

"My name is {name}".format( locals() )

3. string.Template.safe_substitute()

import string
template = string.Template( "My name is ${name}" )
template.safe_substitute( locals() )

The advantage of the string.Template technique is that a
translated string with with an incorrectly spelled variable
reference can still yield a usable string value while the other
techniques unconditionally raise an exception. The downside of
the string.Template technique appears to be the inability for one
to customize how a variable is formatted (padding, justification,
width, etc).

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


  1   2   >