Re: How to display unicode with the CGI module?

2007-11-26 Thread greg
paul wrote:
 However, this will change in py3k..., 
 what's the new rule of thumb?

In py3k, the str type will be what unicode is now, and there
will be a new type called bytes for holding binary data --
including text in some external encoding. These two types
will not be compatible.

At the lowest level, reading a file will return bytes, which
then have to be decoded to produce a (unicode) str, and a str
will have to be encoded into bytes before being written to a
file.

There will be wrappers for text files that perform the
decoding and encoding automatically, but they will need to
be set up to use a specified encoding if you're dealing
with anything other than ascii. (It may be possible to
set up a system-wide default, I'm not sure.)

So you won't be able to get away with ignoring encoding
issues in py3k. On the plus side, it should all be handled
in a much more consistent and less error-prone way. If
you mistakenly try to use encoded data as though it were
decoded data or vice versa, you'll get a type error.

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


Re: better way to write this function

2007-11-26 Thread Peter Otten
Kelie wrote:

 Hello,
 
 This function does I what I want. But I'm wondering if there is an
 easier/better way. To be honest, I don't have a good understanding of
 what pythonic means yet.
 
 def divide_list(lst, n):
 Divide a list into a number of lists, each with n items. Extra
 items are
ignored, if any.
 cnt = len(lst) / n
 rv =  [[None for i in range(n)] for i in range(cnt)]
 for i in range(cnt):
 for j in range(n):
 rv[i][j] = lst[i * n + j]
 return rv

You can use slicing:

 def chunks(items, n):
... return [items[start:start+n] for n in range(0, len(items)-n+1, n)]
... 
 for i in range(1,10):
... print chunks(range(5), i)
... 
[[0], [1], [2], [3], [4]]
[[0, 1], [2, 3]]
[[0, 1, 2]]
[[0, 1, 2, 3]]
[[0, 1, 2, 3, 4]]
[]
[]
[]
[]

Or build a generator that works with arbitrary iterables:

 from itertools import *
 def chunks(items, n):
... items = iter(items)
... while 1:
... chunk = list(islice(items, n-1))
... chunk.append(items.next())
... yield chunk
... 
 list(chunks(range(5), 2))
[[0, 1], [2, 3]]

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


Re: How to display unicode with the CGI module?

2007-11-26 Thread greg
coldpizza wrote:
 I am always confused as to which one to use: encode() or decode();

In unicode land, an encoding is a method of representing
unicode data in an external format. So you encode unicode
data in order to send it into the outside world, and you
decode it in order to turn it back into unicode data.

It'll be easier to get right in py3k, because bytes will only have
a decode() method and str will only have an encode() method.

 It is funny that encode() and decode() omit the name of the other
 encoding (Unicode ucs2?),

Unicode objects don't *have* an encoding. UCS2 is not an encoding,
it's an internal storage format. You're not supposed to need to know
or care about it, and it could be different between different
Python builds.

 Another wierd thing is that by default Python converts internal
 Unicode to ascii.

It's the safest assumption. Python is refusing the temptation
to guess the encoding of anything outside the range 0-127 if you
don't tell it.

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


Re: basic if stuff- testing ranges

2007-11-26 Thread Peter Otten
Donn Ingle wrote:

 x in range(1,20) ?
 Sure, that's okay, but it has clarity issues, and is calling a func.

and it requires that x is integral (1.0 is in the range, 1.001 is not),
and becomes dog slow when the range gets larger. Not a good idea.

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


Re: better way to write this function

2007-11-26 Thread Chris
On Nov 26, 9:42 am, Kelie [EMAIL PROTECTED] wrote:
 Hello,

 This function does I what I want. But I'm wondering if there is an
 easier/better way. To be honest, I don't have a good understanding of
 what pythonic means yet.

 def divide_list(lst, n):
 Divide a list into a number of lists, each with n items. Extra
 items are
ignored, if any.
 cnt = len(lst) / n
 rv =  [[None for i in range(n)] for i in range(cnt)]
 for i in range(cnt):
 for j in range(n):
 rv[i][j] = lst[i * n + j]
 return rv

 Thanks!

x = ['1', '2', '3', '4', '5', '6', '7', '8']
def divide_list(lst, n):
rv = []
for i in range(int(round((len(lst)/n),0))):
rv.append(lst[i*n:(i+1)*n])
return rv

tmp = divide_list(x, 3)
tmp
[['1', '2', '3'], ['4', '5', '6']]

One way to do it.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Installing modules via setuptools in a script

2007-11-26 Thread Thorsten Kampe
* Ben Finney (Mon, 26 Nov 2007 09:04:51 +1100)
 Thorsten Kampe [EMAIL PROTECTED] writes:
  * Robert Kern (Sat, 24 Nov 2007 16:33:37 -0600)
   Thorsten Kampe wrote:
can anyone give me a short code snippet how to install a missing
module via setuptools (assuming setuptools is already
installed)?!
   
   The recommended way to handle dependencies using setuptools is to
   specify them in the install_requires metadata in the setup()
   function call in your setup.py:
  
  It's just a simple script - no package. So I don't even have a
  setup.py.
 
 The recommended way of installing a simple script that has
 dependencies is to write a setup.py for the simple script, so that you
 can declare its dependencies and have them checked on install.

Yes, I know. But this script is not going to be installed - just run. 
And therefore I'd like to know if it's possible to install missing 
dependencies in the script itself via importing setuptools. Or do I 
have to use subprocess('easy_install')?

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


Re: How to Teach Python Variables

2007-11-26 Thread greg
none wrote:
 IIRC, I once saw an explanation how Python doesn't have variables 
 in the sense that, say, C does, and instead has bindings from names to 
 objects.

If you're talking to C programmers, just tell them that
Python variables always contain pointers. That should
give them the right mental model to build on.

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


Tk 8.5

2007-11-26 Thread Ron Provost
Hello,

According to the tk wiki, the final release of Tcl/Tk is just weeks away (see 
http://wiki.tcl.tk/12753).  Does anyone know if the Tk enhancements will be in 
Python 2.6?  Since I don't use tk but I do use Python and Tkinter (and Tix) 
extensively, I'm excited about these long-awaited changes.

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

Re: better way to write this function

2007-11-26 Thread Paul Rubin
Chris [EMAIL PROTECTED] writes:
 for i in range(int(round((len(lst)/n),0))): ...

Ugh!!!  Not even correct (under future division), besides being ugly.
I think you mean:

   for i in xrange(len(lst) // n): ...

Really though, this grouping function gets reimplemented so often that
it should be built into the stdlib, maybe in itertools.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to Teach Python Variables

2007-11-26 Thread Simon Brunning
On Nov 25, 2007 6:19 PM, @bag.python.org none wrote:
 IIRC, I once saw an explanation how Python doesn't have variables in
 the sense that, say, C does, and instead has bindings from names to
 objects. Does anyone have a link?

Perhaps you mean:

http://effbot.org/zone/python-objects.htm

-- 
Cheers,
Simon B.
[EMAIL PROTECTED]
http://www.brunningonline.net/simon/blog/
GTalk: simon.brunning | MSN: small_values | Yahoo: smallvalues
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: i want to know what is the problem in this code

2007-11-26 Thread Bruno Desthuilliers
nani a écrit :
 i am getting the following error for below code
 
(snip)
  C:\Program Files\Apache Group\Apache2\cgi-bin\hello.py in ()
 7
 8 val = cgi.FieldStorage()
 9 name = val[name].value
(snip)
 
 type 'exceptions.KeyError': 'name'

Obviously there's no 'name' argument in the http request. Remember that 
html forms dont return key/value pairs for empty (not selected / 
whatever) fields.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: better way to write this function

2007-11-26 Thread Chris
On Nov 26, 10:51 am, Paul Rubin http://[EMAIL PROTECTED] wrote:
 Chris [EMAIL PROTECTED] writes:
  for i in range(int(round((len(lst)/n),0))): ...

 Ugh!!!  Not even correct (under future division), besides being ugly.
 I think you mean:

for i in xrange(len(lst) // n): ...

 Really though, this grouping function gets reimplemented so often that
 it should be built into the stdlib, maybe in itertools.

Beauty is in the eye of the beholder, but true... Looks crap :p
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: better way to write this function

2007-11-26 Thread Paul Rudin
Kelie [EMAIL PROTECTED] writes:

 Hello,

 This function does I what I want. But I'm wondering if there is an
 easier/better way. To be honest, I don't have a good understanding of
 what pythonic means yet.

 def divide_list(lst, n):
 Divide a list into a number of lists, each with n items. Extra
 items are
ignored, if any.
 cnt = len(lst) / n
 rv =  [[None for i in range(n)] for i in range(cnt)]
 for i in range(cnt):
 for j in range(n):
 rv[i][j] = lst[i * n + j]
 return rv

 Thanks!

See the last recipe from:
http://docs.python.org/lib/itertools-recipes.html. It's not doing
quite the same thing, but gives an illustration of one way to approach
this sort of thing.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to Teach Python Variables

2007-11-26 Thread Hrvoje Niksic
greg [EMAIL PROTECTED] writes:

 none wrote:
 IIRC, I once saw an explanation how Python doesn't have
 variables in the sense that, say, C does, and instead has bindings
 from names to objects.

 If you're talking to C programmers, just tell them that Python
 variables always contain pointers. That should give them the right
 mental model to build on.

That is a convenient shortcut when it works, but in my experience it
tends to confuse the issue.  The reason is that one of the main uses
of pointers in C is implementing pass-by-reference.  A C programmer
told that Python variables internally hold pointers expects this code:

def func(a):
  a = 10
...
func(x)

to change the value of x.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Installing modules via setuptools in a script

2007-11-26 Thread Robert Kern
Thorsten Kampe wrote:
 * Robert Kern (Sat, 24 Nov 2007 16:33:37 -0600)
 Thorsten Kampe wrote:
 can anyone give me a short code snippet how to install a missing 
 module via setuptools (assuming setuptools is already installed)?!

 Something like this:

 try:
 import missing_module
 except import_error
 import setuptools
 setuptools.whatever.install(missing_module)
 The recommended way to handle dependencies using setuptools is to specify 
 them
 in the install_requires metadata in the setup() function call in your 
 setup.py:
 
 It's just a simple script - no package. So I don't even have a 
 setup.py.
 
 However, if you have special needs that really do require downloading the
 dependency at runtime instead of install-time:

   #
 http://peak.telecommunity.com/DevCenter/PkgResources#workingset-methods-and-attributes

   import pkg_resources
   pkg_resources.resolve('some_package = 1.0')
   pkg_resources.resolve('another_package')

   import some_package
   import another_package
 
 [5] pkg_resources.working_set.resolve('betterprint')
 --
 -
 AttributeErrorTraceback (most recent call 
 last)
 
 F:\program files\python\ipython console in module()
 
 F:\program files\python\lib\site-packages\setuptools-0.6c5-py2.5.egg
 \pkg_resou
 rces.py in resolve(self=pkg_resources.WorkingSet object at 
 0x01457710, requi
 rements=['n', 'i', 'r', 'p', 'r', 'e', 't', 't', 'e', 'b'], env=None, 
 installe
 r=None)
 472 # Ignore cyclic or redundant dependencies
 473 continue
 -- 474 dist = best.get(req.key)
 dist = undefined
 best.get = built-in method get of dict object at 0x016BC660
 req.key = undefined
 475 if dist is None:
 476 # Find the best distribution and add it to the 
 map
 
 AttributeError: 'str' object has no attribute 'key'

My apologies for misleading you. There is no easy way to do this. Here is a
roundabout way which might be suitable for a throwaway hack script. If it's not
a throwaway hack script, then please heed Ben's advice. Alternatively, just
distribute betterprint along with your script and save yourself the headache.


In [1]: import betterprint
---
ImportError   Traceback (most recent call last)

/Users/rkern/ipython console in module()

ImportError: No module named betterprint

In [2]: import pkg_resources

In [3]: from setuptools.dist import Distribution

In [4]:
pkg_resources.working_set.resolve(pkg_resources.parse_requirements('betterprint'),
installer=Distribution().fetch_build_egg)
zip_safe flag not set; analyzing archive contents...

Installed /Users/rkern/betterprint-0.1-py2.5.egg
Out[4]: [betterprint 0.1 (/Users/rkern/betterprint-0.1-py2.5.egg)]

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


Need to call functions/class_methods etc using string ref :How

2007-11-26 Thread Ravi Kumar
Hi,
First of all, since this is my first mail to Python-List, I want to say
Hello world!
After that;
I am stuck in a project. Actually I am writing a module (for testing now),
which takes URL, parses it, finds which modules and then which method to
call or which class to initiate and which string to load.
So far, I have done some basic URL manipulation and validation and extracted
the name of modules in  a dict
{
  'ModuleName-1': None,
  'ModuleName-2': None
  --ETC--
}

Now I want your help about how to call the  function i.e _render() in the
module. I have to iterate it calling all modules/also Class.methods and
assinging the values in dict for each key as modulename.
Means,
just take that moduleName is a string which contains the name of module to
load.
FuncName is the string which contains the name of def function to call
clName is the string which contains the name of the Class, which is to init
and get returned object.

means everything in string.
ALso, if there are multiple methods to do it, if you provide a little
pros/cons and comments, it would really be very nice of you.


Before I came here, I have searched Google, and found a way
hasattr()/getattr(), but that confused me a little and didnt worked for me.
I am missing something I know, so please ENLIGHTEN Me :)


Thanks in advance EVen you read this mail :P

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

Re: basic if stuff- testing ranges

2007-11-26 Thread Donn Ingle
 The output of the following program might help:
Hey, nifty! Thanks Paddy.

\d

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


Re: Need to call functions/class_methods etc using string ref :How

2007-11-26 Thread Donn Ingle
Well, I don't know all the answers, but you can start here:

def boobs(): print Oohh little birds!
b=boobs
eval(b)()
Ohhh little birds!

Naturally, eval is going to run anything... Even code to format your drive.

HTH
\d

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


Re: How to display unicode with the CGI module?

2007-11-26 Thread paul
greg schrieb:
 paul wrote:
 However, this will change in py3k..., 
 what's the new rule of thumb?
[snipp]

 So you won't be able to get away with ignoring encoding
 issues in py3k. On the plus side, it should all be handled
 in a much more consistent and less error-prone way. If
 you mistakenly try to use encoded data as though it were
 decoded data or vice versa, you'll get a type error.
Thanks for your detailed answer. In fact, having encode() only for str 
and decode() for byte will simplify things a lot. I guess implicit 
encode() of str when using print() will stay but having utf-8 as the 
new default encoding will reduce the number of UnicodeError. You'll get 
weird characters instead ;)

cheers
  Paul

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


regex and IGNORECASE

2007-11-26 Thread Yann Le Boulanger
Hi all,

I have a problem with regex , utf-8 chars and IGNORECASE

  re.search(u'é', u'qwért', re.IGNORECASE)
_sre.SRE_Match object at 0x2ed0c100

Here everything is ok.


  re.search(u'É', u'qwért', re.IGNORECASE)

Here that doesn't work. but:
  print u'é'.upper()
É

is it a bug in IGNORECASE option?

Thanks for your help
-- 
Yann
-- 
http://mail.python.org/mailman/listinfo/python-list


C pointer representation in python

2007-11-26 Thread abarun22
Hi
I am new to SWIG and python. I have a problem while trying to call a C
function from Python using SWIG as an interface. The function is
defined as follows.

void* myfunc(TfichierDLR *fichier, char *nom, char *type, char *txt,
char *classe, TicThemeDLR *icTheme, int **num, int *ier)

The last two are output parameters (**num and *ier) and i wonder how
to represent those while calling from python. Especially 'num' being a
double pointer is tricky to handle. Also how can we represent the
return variable which is a null pointer.

I would be extremely pleased to hear any ideas/suggestions in this
regard.

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


Re: regex and IGNORECASE

2007-11-26 Thread John Machin
On Nov 26, 9:53 pm, Yann Le Boulanger [EMAIL PROTECTED] wrote:
 Hi all,

 I have a problem with regex , utf-8 chars and IGNORECASE

   re.search(u'é', u'qwért', re.IGNORECASE)
 _sre.SRE_Match object at 0x2ed0c100

 Here everything is ok.

   re.search(u'É', u'qwért', re.IGNORECASE)

 Here that doesn't work. but:
   print u'é'.upper()
 É

 is it a bug in IGNORECASE option?


... or poor documentation of a not-very-intuitive API?

 re.search(u'\xc9', u'qw\xe9rt', re.IGNORECASE)
 re.search(u'\xc9', u'qw\xe9rt', re.IGNORECASE + re.UNICODE)
_sre.SRE_Match object at 0x00DC14F0

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


[announce] WARPY, Nov. 29, Warsaw, Poland

2007-11-26 Thread Jarek Zgoda
I'm pleased to announce the first WARsaw PYthoneers meeting which will
be held Nov. 29 at 7 p.m. on Politechnika Warszawska, 15/19 Nowowiejska
st., Warsaw, Poland. More information (in Polish) can be found at
http://7thguard.net/news.php?id=5721 and in an announcement made on
pl.comp.lang.python.

See you there!

-- 
Jarek Zgoda
Skype: jzgoda | GTalk: [EMAIL PROTECTED] | voice: +48228430101

We read Knuth so you don't have to. (Tim Peters)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to change current working directory while using pdb within emacs

2007-11-26 Thread du yan ning
On Nov 21, 1:28 pm, Diez B. Roggisch [EMAIL PROTECTED] wrote:
 duyanningwrote:
  I have written a pyhton script that will process data file in current
  working directory.
  My script is in an different directory to data file.
  When I debug this script using pdb within emacs, emacs will change the
  current working directory to the directory which include the script,
  so my script cannot find the data file.

  I think this is the problem of emacs because when I start pdb from
  console directly, it will not change current working directory to the
  one of script being debugged.

 Just issue

 import os
 os.chdir('whatever')

 inside the pdb-session. Unfortunate, but should work.

 Diez

thank you! my friend.
-- 
http://mail.python.org/mailman/listinfo/python-list


Add speller to Python application

2007-11-26 Thread helzer
I need to add spell checking to my Python application (for Windows).
Any ideas on where to start?

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


Re: Add speller to Python application

2007-11-26 Thread Jarek Zgoda
helzer napisał(a):
 I need to add spell checking to my Python application (for Windows).
 Any ideas on where to start?

There is Python2.4 compatible binary of aspell-python available at
http://www.wmula.republika.pl/proj/aspell-python/index-c.html

-- 
Jarek Zgoda
Skype: jzgoda | GTalk: [EMAIL PROTECTED] | voice: +48228430101

We read Knuth so you don't have to. (Tim Peters)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: i want to know what is the problem in this code

2007-11-26 Thread Gerardo Herzig
nani wrote:

i am getting the following error for below code

type 'exceptions.KeyError'   Python 2.5.1: C:\Python25\python.exe
Mon Nov 26 10:13:17 2007

A problem occurred in a Python script. Here is the sequence of
function calls leading up to the error, in the order they occurred.
 C:\Program Files\Apache Group\Apache2\cgi-bin\hello.py in ()
7
8 val = cgi.FieldStorage()
9 name = val[name].value
   10 time_from = val[time_from].value
   11 time_to = val[time_to].value
name undefined, val = FieldStorage(None, None, []), ].value = []
 C:\Python25\lib\cgi.py in __getitem__(self=FieldStorage(None, None,
[]), key='name')
  565 if item.name == key: found.append(item)
  566 if not found:
  567 raise KeyError, key
  568 if len(found) == 1:
  569 return found[0]
builtin KeyError = type 'exceptions.KeyError', key = 'name'

type 'exceptions.KeyError': 'name'



#!C:/Python25/python.exe
import cgi
import cgitb; cgitb.enable()

print Content-Type: text/html
print

val = cgi.FieldStorage()
name = val[name].value
time_from = val[time_from].value
time_to = val[time_to].value
html = 
html

body
h1 Hello %s  from %s to %s /h1
/body

/html

print html%(name, time_from, time_to)






html page is...


html


body

form action=C:/Program Files/Apache Group/Apache2/cgi-bin/
hello.py
table
tr
td Enter your name: /td
td input type=text name=name value= / /td
/tr
 tr
td Time from: /td
td input type=text name=time_from value= / /
td
/tr
  tr
td Time to: /td
td input type=text name=time_to value= / /
td
/tr
tr 
td colspan=2 align=center  input type=submit
value=Click Here / /td
/tr
/table

/form

/body

/html

  

Looks like the text field name is empty when submitin the form, and 
cgi.FieldStorage() -no args- does not build the key/pair for empty 
textfields. You can use the keep_blank_values=1 arg in FieldStorage() if 
you want force the key/pair to be generated anyway.

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


howto write matplotlib backend?

2007-11-26 Thread mihail . udov
Somewhere on http://matplotlib.sourceforge.net or elsewhere I found
some hints how to get started writing a new backend for matplotlib. It
mentioned some almost empty kind of template that you could extend for
your needs.

I cannot find this description again. Would somebody help, please?

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


Re: the annoying, verbose self

2007-11-26 Thread BJörn Lindqvist
On Nov 24, 2007 11:55 AM, jakub silar [EMAIL PROTECTED] wrote:
 Below is my coding standard - I'm lazy, even lazy to persuade
 comutinties into strange (imho) language syntax extensions.


  class Vector:
  def __init__(s, x, y, z):
  s.x = x
  s.y = y
  s.z = z
  def abs(s):
  return math.sqrt(s.x * s.x + s.y * s.y + s.z * s.z)

 Admit that changing habits may be more difficult then to change a
 language syntax.

Yes, indeed. A self-reference prefix like s, T, _ or even my
would be enough characters shorter than self. But self *is* the
convention and just because the language allows you to break it
doesn't mean that it is not horribly wrong to do so. :)


-- 
mvh Björn
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Add speller to Python application

2007-11-26 Thread Shane Geiger
http://pyenchant.sourceforge.net/


helzer wrote:
 I need to add spell checking to my Python application (for Windows).
 Any ideas on where to start?

 Thanks,
 Helzer
   


-- 
Shane Geiger
IT Director
National Council on Economic Education
[EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy

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


Re: Installing modules via setuptools in a script

2007-11-26 Thread Thorsten Kampe
* Robert Kern (Mon, 26 Nov 2007 04:34:17 -0600)
 Thorsten Kampe wrote:
  * Robert Kern (Sat, 24 Nov 2007 16:33:37 -0600)
  Thorsten Kampe wrote:
  can anyone give me a short code snippet how to install a missing 
  module via setuptools (assuming setuptools is already installed)?!
 
  Something like this:
 
  try:
  import missing_module
  except import_error
  import setuptools
  setuptools.whatever.install(missing_module)
  The recommended way to handle dependencies using setuptools is to specify 
  them
  in the install_requires metadata in the setup() function call in your 
  setup.py:
  
  It's just a simple script - no package. So I don't even have a 
  setup.py.
[...]
 My apologies for misleading you. There is no easy way to do this. Here is a
 roundabout way which might be suitable for a throwaway hack script. If it's 
 not
 a throwaway hack script, then please heed Ben's advice. Alternatively, just
 distribute betterprint along with your script and save yourself the headache.
 
 
 In [1]: import betterprint
 ---
 ImportError   Traceback (most recent call last)
 
 /Users/rkern/ipython console in module()
 
 ImportError: No module named betterprint
 
 In [2]: import pkg_resources
 
 In [3]: from setuptools.dist import Distribution
 
 In [4]:
 pkg_resources.working_set.resolve(pkg_resources.parse_requirements('betterprint'),
 installer=Distribution().fetch_build_egg)
 zip_safe flag not set; analyzing archive contents...
 
 Installed /Users/rkern/betterprint-0.1-py2.5.egg
 Out[4]: [betterprint 0.1 (/Users/rkern/betterprint-0.1-py2.5.egg)]

Okay, works for me, thanks. Is there an option to have the downloaded 
module installed into the site-packages directory (and not into the 
current)?

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


Re: Handling Menubars in WXGlade

2007-11-26 Thread kyosohma
On Nov 23, 7:57 am, jatin patni [EMAIL PROTECTED] wrote:
 Hi, I recently started working on WXGlade...

 I found some amount of documentation online

 I am having problems integrating event handlers with MenubarsI
 want each menu item to open a new window with custom made
 controls...but I can't find it anywhere.Writing event handler is
 secondary actually...How can I attach each menu item with a custom
 dialog or another window


Actually, using the handler would be primary, not secondary. Here's
how I would do it. I would bind each menu item to a separate handler
and within the handler I would call instantiate the window or dialog.
For example, below I bind my Save menu item to a handler called
onSave.

self.Bind(wx.EVT_MENU, self.onSave, save_menu_item)

In the handler, I can save the programs input in many different ways.
I could open a Save dialog to allow the user to choose where it gets
saved, for example.



 Sorry for the newbie slangI am new to programming...
 Thanks

 --
 [EMAIL PROTECTED]
 Ph: 91-9953411751http://jatinpatni.co.nr

I would also recommend that you post to the wxPython user's group as
they'll be much better suited to answering wx questions. Here's where
you'd need to go: http://wxpython.org/maillist.php

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


Re: eof

2007-11-26 Thread Boris Borcic
[EMAIL PROTECTED] wrote:
 def xor(a, b):
   return a and not b or b and not a


  from operator import xor
  help(xor)
Help on built-in function xor in module operator:

xor(...)
 xor(a, b) -- Same as a ^ b.

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


Re: Need to call functions/class_methods etc using string ref :How

2007-11-26 Thread J. Clifford Dyer
On Mon, Nov 26, 2007 at 04:07:03PM +0530, Ravi Kumar wrote regarding Need to 
call functions/class_methods etc using string ref :How:
 
Hi,
First of all, since this is my first mail to Python-List, I want to say
Hello world!
After that;
I am stuck in a project. Actually I am writing a module (for testing
now), which takes URL, parses it, finds which modules and then which
method to call or which class to initiate and which string to load.
So far, I have done some basic URL manipulation and validation and
extracted the name of modules in  a dict
{
  'ModuleName-1': None,
  'ModuleName-2': None
  --ETC--
}
Now I want your help about how to call the  function i.e _render() in
the module. I have to iterate it calling all modules/also Class.methods
and assinging the values in dict for each key as modulename.
Means,
just take that moduleName is a string which contains the name of module
to load.
FuncName is the string which contains the name of def function to
call
clName is the string which contains the name of the Class, which is to
init and get returned object.
means everything in string.
ALso, if there are multiple methods to do it, if you provide a little
pros/cons and comments, it would really be very nice of you.
Before I came here, I have searched Google, and found a way
hasattr()/getattr(), but that confused me a little and didnt worked for
me. I am missing something I know, so please ENLIGHTEN Me :)
Thanks in advance EVen you read this mail :P
--
-=Ravi=-

I see someone already showed you eval.  Eval is evil.  Don't use it.  
Especially if the functions are coming to you from a public URL!  

You are on the right track putting the module names in a dictionary.  Now tie 
those dictionary keys to functions.

func = { 'function_a': function_a,
 'function_b': function_b }

now you can call them as follows, with the desired function name extracted from 
the URL into the variable f_request:

if f_request in func:
result = func[f_request]()

This way, users can't call functions you haven't explicitly added to the func 
dictionary.

Cheers,
Cliff


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


Re: basic if stuff- testing ranges

2007-11-26 Thread Erik Jones

On Nov 25, 2007, at 9:49 PM, Donn Ingle wrote:

 if 0  x  20: print within
 That means if x LESS THAN 0 and x  20.
 Oh, bugger. It's tricky.
 So try
 if 0  x  20:
 Thanks. I was flipping signs in my tests, but I guess I flipped  
 both and got
 myself all confused.

 Likely manuals: Tutorial  Reference
 Tutorial: check contents, if statement looks possible, but no luck
 Yes, I got that far.
 Reference: check contents, comparisons looks possible, and
 Thanks again. I find the reference is laid-out in a way that I  
 don't find
 intuitive and every time I look for something I fail. I even grep  
 through
 the folder to get a clue, which shows how poor the index is (to me)!

Then use one of the quick references here: http://rgruet.free.fr/.

Erik Jones

Software Developer | Emma®
[EMAIL PROTECTED]
800.595.4401 or 615.292.5888
615.292.0777 (fax)

Emma helps organizations everywhere communicate  market in style.
Visit us online at http://www.myemma.com


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


Re: eof

2007-11-26 Thread Grant Edwards
On 2007-11-26, Boris Borcic [EMAIL PROTECTED] wrote:
 [EMAIL PROTECTED] wrote:
 def xor(a, b):
  return a and not b or b and not a


  from operator import xor
  help(xor)
 Help on built-in function xor in module operator:

 xor(...)
  xor(a, b) -- Same as a ^ b.

Which isn't the same thing:

--testit.py--
import operator

def xor(a,b):
return a and not b or b and not a

print xor(1,3), operator.xor(1,3)
--testit.py--

$ python testit.py
False 2

The user-defined xor is operates on logical boolean values.
The one in the operator module is a bitwise operator.

-- 
Grant Edwards   grante Yow! My haircut is totally
  at   traditional!
   visi.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Running unmodified CGI scripts persistently under mod_wsgi.

2007-11-26 Thread Jeffrey Froman
Graham Dumpleton wrote:

 The other question is whether there is even a demand for this. Do
 people want to be able to take unmodified Python CGI scripts and try
 to run them persistently in this way, or would they be better off
 converting them to proper WSGI applications.

I would personally be interested in such an adapter. While recently
considering whether to re-write a standalone mod_python application as CGI
or WSGI, I was scared off by this paragraph from PEP333:

-
Note: although we refer to it as an application object, this should not be
construed to mean that application developers will use WSGI as a web
programming API! It is assumed that application developers will continue to
use existing, high-level framework services to develop their applications.
WSGI is a tool for framework and server developers, and is not intended to
directly support application developers.
-

Do you have any thoughts about this warning? I'd much rather have the
performance of mod_wsgi for my application, so if you can provide any
mollifying views about WSGI's suitability for standalone applications my
first choice would be to use WSGI directly.

Regardless of its appropriateness for new applications, a CGI/WSGI adapter
would still be useful for third-party CGI scripts that I have no interest
in rewriting myself, as well as for the interim period during which my own
CGI applications are being rewritten. It would be advantageous for the
hosting company I work for, for example, to be able to boast that your
python CGI scripts run faster on our mod_wsgi-enabled servers.


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


Re: basic if stuff- testing ranges

2007-11-26 Thread Erik Jones
On Nov 26, 2007, at 2:29 AM, Peter Otten wrote:

 Donn Ingle wrote:

 x in range(1,20) ?
 Sure, that's okay, but it has clarity issues, and is calling a func.

 and it requires that x is integral (1.0 is in the range, 1.001 is  
 not),
 and becomes dog slow when the range gets larger. Not a good idea.

That is because range() is not a range in the abstract sense (i.e.  
simply defining bounds that can be tested for set membership) but are  
used to create lists (or, in the case of xrange(), successive values)  
between the bounds given in the params.  So, saying x in range(1,20)  
is not asking if x is between 1 and 20 but, rather, if x is a member  
of the values genereated by the range function with params 1 and 20.   
So, yes, using range()

Erik Jones

Software Developer | Emma®
[EMAIL PROTECTED]
800.595.4401 or 615.292.5888
615.292.0777 (fax)

Emma helps organizations everywhere communicate  market in style.
Visit us online at http://www.myemma.com


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


Re: Code Management

2007-11-26 Thread Sergio Correia
Bluebird:

If you are using python 2.5, relative imports are no longer an issue:
http://docs.python.org/whatsnew/pep-328.html

That problem solved, what you sometimes want is to change the version
of your package. I just change the text in the PTH file, to point to
another version, and voilá (no need to move files around or to mess
with the code in the package itself). Probably you can write a script
that changes the PTH file from python itself.

Albert:

Thanks, that looks useful.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: eof

2007-11-26 Thread ZeD
Grant Edwards wrote:

 The user-defined xor is operates on logical boolean values.
 The one in the operator module is a bitwise operator.

def xor(a, b):
return bool(a) ^ bool(b)

seems more explicit to me.
maybe, to make more explicit (too much, onestly...)

from operator import xor as bitwise_xor

def logical_xor(a, b):
return bitwise_xor(bool(a), bool(b))

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


Re: Need to call functions/class_methods etc using string ref :How

2007-11-26 Thread Donn Ingle
 I see someone already showed you eval.  Eval is evil.  Don't use it. 
 Especially if the functions are coming to you from a public URL!
Yes, I suggested to him (by email) this:

thisinstance =  SomeObject.__class__.__dict__
Then you have a list of strings that may be function names, so:
for f in yourlist:
 if f in thisinstance: eval(f)(params)

Which would vet the functions too.


\d

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

Re: mod_python

2007-11-26 Thread Aaron Watters
On Nov 24, 1:19 am, Vernon Wenberg III [EMAIL PROTECTED] wrote:
 Why do I receive a File not found error on a perfect good and simple
 script but properly receive errors when I deliberately add errors in the
 script? The file is there, it just doesn't do anything.

 Any help would be appreciated.

I'm guessing the file is okay, but something involving naming
is wrong.  Check the error log file(s).  It may show that
mod_py is looking inside the module and not finding the right
function/method.  As others have said, some sample code would
help us help you...
  -- Aaron Watters

===
http://www.xfeedme.com/nucular/pydistro.py/go?FREETEXT=generate+muck
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: better way to write this function

2007-11-26 Thread Kelie
On Nov 25, 10:51 pm, Paul Rubin http://[EMAIL PROTECTED] wrote:
 Really though, this grouping function gets reimplemented so often that
 it should be built into the stdlib, maybe in itertools.

thanks Paul.
itertools? that was actually the first module i checked.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Installing modules via setuptools in a script

2007-11-26 Thread Robert Kern
Thorsten Kampe wrote:
 * Robert Kern (Mon, 26 Nov 2007 04:34:17 -0600)
 Thorsten Kampe wrote:
 * Robert Kern (Sat, 24 Nov 2007 16:33:37 -0600)
 Thorsten Kampe wrote:
 can anyone give me a short code snippet how to install a missing 
 module via setuptools (assuming setuptools is already installed)?!

 Something like this:

 try:
 import missing_module
 except import_error
 import setuptools
 setuptools.whatever.install(missing_module)
 The recommended way to handle dependencies using setuptools is to specify 
 them
 in the install_requires metadata in the setup() function call in your 
 setup.py:
 It's just a simple script - no package. So I don't even have a 
 setup.py.
 [...]
 My apologies for misleading you. There is no easy way to do this. Here is a
 roundabout way which might be suitable for a throwaway hack script. If it's 
 not
 a throwaway hack script, then please heed Ben's advice. Alternatively, just
 distribute betterprint along with your script and save yourself the headache.


 In [1]: import betterprint
 ---
 ImportError   Traceback (most recent call last)

 /Users/rkern/ipython console in module()

 ImportError: No module named betterprint

 In [2]: import pkg_resources

 In [3]: from setuptools.dist import Distribution

 In [4]:
 pkg_resources.working_set.resolve(pkg_resources.parse_requirements('betterprint'),
 installer=Distribution().fetch_build_egg)
 zip_safe flag not set; analyzing archive contents...

 Installed /Users/rkern/betterprint-0.1-py2.5.egg
 Out[4]: [betterprint 0.1 (/Users/rkern/betterprint-0.1-py2.5.egg)]
 
 Okay, works for me, thanks. Is there an option to have the downloaded 
 module installed into the site-packages directory (and not into the 
 current)?

No. This is a hack. If you need things installed properly, use a setup.py.

-- 
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: better way to write this function

2007-11-26 Thread Kelie
On Nov 25, 11:24 pm, Paul Rudin [EMAIL PROTECTED] wrote:
 See the last recipe from:http://docs.python.org/lib/itertools-recipes.html. 
 It's not doing
 quite the same thing, but gives an illustration of one way to approach
 this sort of thing.

Thanks for the link!


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


How to write Regular Expression for recursive matching?

2007-11-26 Thread lisong
Hi All,

I have problem to split a string like this:

'abc.defg.hij.klmnop'

and I want to get all substrings with only one '.' in mid. so the
output I expect is :

'abc.defg', 'defg.hij', 'hij.klmnop'

a simple regular expression '\w+.\w' will only return:
'abc.defg', 'hij.klmnop'

is there a way to get 'defg.hij' using regular expression?

Thanks,

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


Re: eof

2007-11-26 Thread Boris Borcic
ZeD wrote:
 Grant Edwards wrote:
 
 The user-defined xor is operates on logical boolean values.
 The one in the operator module is a bitwise operator.
 
 def xor(a, b):
 return bool(a) ^ bool(b)
 
 seems more explicit to me.
 maybe, to make more explicit (too much, onestly...)
 
 from operator import xor as bitwise_xor
 
 def logical_xor(a, b):
 return bitwise_xor(bool(a), bool(b))
 

I'd prefer   bool(a)!=bool(b)

or even  bool(a) is not bool(b)

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


Re: better way to write this function

2007-11-26 Thread Chris Mellon
On Nov 26, 2007 3:24 AM, Paul Rudin [EMAIL PROTECTED] wrote:
 Kelie [EMAIL PROTECTED] writes:

  Hello,
 
  This function does I what I want. But I'm wondering if there is an
  easier/better way. To be honest, I don't have a good understanding of
  what pythonic means yet.
 
  def divide_list(lst, n):
  Divide a list into a number of lists, each with n items. Extra
  items are
 ignored, if any.
  cnt = len(lst) / n
  rv =  [[None for i in range(n)] for i in range(cnt)]
  for i in range(cnt):
  for j in range(n):
  rv[i][j] = lst[i * n + j]
  return rv
 
  Thanks!

 See the last recipe from:
 http://docs.python.org/lib/itertools-recipes.html. It's not doing
 quite the same thing, but gives an illustration of one way to approach
 this sort of thing.

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


The one in the sample consumes the entire sequence up front, too. It's
trivial to write a fully generator based one (and only slightly more
work to implement an iterator that doesn't rely on generators, if you
want to avoid the slight performance hit), but there's a few subtle
issues and I too think that we really should have a good one ready for
use in itertools. Maybe I should write a patch.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: win32serviceutil won't start

2007-11-26 Thread kyosohma
On Nov 25, 5:11 pm, Nikola Skoric [EMAIL PROTECTED] wrote:
 Dana Sun, 25 Nov 2007 13:52:35 -0800 (PST),
 [EMAIL PROTECTED] [EMAIL PROTECTED] kaze:

  Looks like Microsoft thinks you mis-spelled it.

 http://www.microsoft.com/technet/prodtechnol/windows2000serv/reskit/w...

  I would check and see if that service is installed on your PC. You can
  go to Start -- Run and type services.msc

  Scroll through there and see if your service is listed. You might
  check to see if you can enable/disable it via that console as well.

 Seems like I misunderstood Windows services (I'm porting UNIX daemon
 to Windows so I'm thinking in UNIX terms). I didn't know I have to
 _install_ a service before I _start_ it. How do I install a service?

 --
 Now the storm has passed over me
 I'm left to drift on a dead calm sea
 And watch her forever through the cracks in the beams
 Nailed across the doorways of the bedrooms of my dreams

Sorry I didn't reply sooner. If you're creating a service based on a
Python file, check out the following links in addition to the book
Wolfgang mentioned:

http://agiletesting.blogspot.com/2005/09/running-python-script-as-windows.html
http://www.thescripts.com/forum/thread595660.html
http://essiene.blogspot.com/2005/04/python-windows-services.html

That should get you started. Hope it helps!

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


Re: How to write Regular Expression for recursive matching?

2007-11-26 Thread Paul McGuire
On Nov 26, 10:40 am, lisong [EMAIL PROTECTED] wrote:
 Hi All,

 I have problem to split a string like this:

 'abc.defg.hij.klmnop'

 and I want to get all substrings with only one '.' in mid. so the
 output I expect is :

 'abc.defg', 'defg.hij', 'hij.klmnop'

 a simple regular expression '\w+.\w' will only return:
 'abc.defg', 'hij.klmnop'

 is there a way to get 'defg.hij' using regular expression?

 Thanks,

Why are you using regular expressions?  Use the split method defined
for strings:

 'abc.defg.hij.klmnop'.split('.')
['abc', 'defg', 'hij', 'klmnop']

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


spawning a process with subprocess

2007-11-26 Thread bhunter
Hi,

I've used subprocess with 2.4 several times to execute a process, wait
for it to finish, and then look at its output.  Now I want to spawn
the process separately, later check to see if it's finished, and if it
is look at its output.  I may want to send a signal at some point to
kill the process.  This seems straightforward, but it doesn't seem to
be working.

Here's my test case:

import subprocess, time

cmd = cat somefile
thread = subprocess.Popen(args=cmd.split(), shell=True,
stdout=subprocess.PIPE, stdin=subprocess.PIPE,
stderr=subprocess.STDOUT, close_fds=True)

while(1):
  time.sleep(1)
  if(thread.returncode):
 break
  else:
 print thread.returncode

print returncode = , thread.returncode
for line in thread.stdout:
   print stdout:\t,line


This will just print the returncode of None forever until I Ctrl-C it.

Of course, the program works fine if I call thread.communicate(), but
since this waits for the process to finish, that's not what I want.

Any help would be appreciated.

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


Re: How to write Regular Expression for recursive matching?

2007-11-26 Thread Diez B. Roggisch
lisong wrote:

 Hi All,
 
 I have problem to split a string like this:
 
 'abc.defg.hij.klmnop'
 
 and I want to get all substrings with only one '.' in mid. so the
 output I expect is :
 
 'abc.defg', 'defg.hij', 'hij.klmnop'
 
 a simple regular expression '\w+.\w' will only return:
 'abc.defg', 'hij.klmnop'
 
 is there a way to get 'defg.hij' using regular expression?

Nope. Regular expressions can't get back in their input-stream, at least not
for such stuff.

The problem at hand is easily solved using

s = 'abc.defg.hij.klmnop'

pairs = [..join(v) for v in zip(s.split(.)[:-1], s.split(.)[1:])]

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


Re: spawning a process with subprocess

2007-11-26 Thread kyosohma
On Nov 26, 10:54 am, bhunter [EMAIL PROTECTED] wrote:
 Hi,

 I've used subprocess with 2.4 several times to execute a process, wait
 for it to finish, and then look at its output.  Now I want to spawn
 the process separately, later check to see if it's finished, and if it
 is look at its output.  I may want to send a signal at some point to
 kill the process.  This seems straightforward, but it doesn't seem to
 be working.

 Here's my test case:

 import subprocess, time

 cmd = cat somefile
 thread = subprocess.Popen(args=cmd.split(), shell=True,
 stdout=subprocess.PIPE, stdin=subprocess.PIPE,
 stderr=subprocess.STDOUT, close_fds=True)

 while(1):
   time.sleep(1)
   if(thread.returncode):
  break
   else:
  print thread.returncode

 print returncode = , thread.returncode
 for line in thread.stdout:
print stdout:\t,line

 This will just print the returncode of None forever until I Ctrl-C it.

 Of course, the program works fine if I call thread.communicate(), but
 since this waits for the process to finish, that's not what I want.

 Any help would be appreciated.

I've read that this sort of thing can be a pain. I'm sure someone will
post and have other views though. I have had some success using
Python's threading module though. There's a pretty good walkthrough
here (it uses wxPython in its example):

http://wiki.wxpython.org/LongRunningTasks

Other places of interest include:

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/491281
http://uucode.com/texts/pylongopgui/pyguiapp.html
http://sayspy.blogspot.com/2007/11/idea-for-process-concurrency.html

If I were doing something like this, I would have the process write
it's output to a file and periodically check to see if the file has
data.

Hopefully someone with more knowledge will come along soon.

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


Re: Should proxy objects lie about their class name?

2007-11-26 Thread John J. Lee
[EMAIL PROTECTED] (John J. Lee) writes:

 Not much to add to the subject line.  I mean something like this:

 ProxyClass.__name__ = ProxiedClass.__name__


 I've been told that this is common practice.  Is it?  Would this
 surprise you if you ran into it in a debugging session?

Does nobody have an opinion on this?  Pull your socks up, c.l.py!

insert reference to argument sketch here


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


Re: better way to write this function

2007-11-26 Thread Paul McGuire
On Nov 26, 1:42 am, Kelie [EMAIL PROTECTED] wrote:
 Hello,

 This function does I what I want. But I'm wondering if there is an
 easier/better way. To be honest, I don't have a good understanding of
 what pythonic means yet.

 def divide_list(lst, n):
 Divide a list into a number of lists, each with n items. Extra
 items are
ignored, if any.
 cnt = len(lst) / n
 rv =  [[None for i in range(n)] for i in range(cnt)]
 for i in range(cnt):
 for j in range(n):
 rv[i][j] = lst[i * n + j]
 return rv

 Thanks!

 lst = list(ABCDE)
 for j in range(1,6):
... print j,':',[lst[i:i+j] for i in xrange(0,len(lst),j)]
...
1 : [['A'], ['B'], ['C'], ['D'], ['E']]
2 : [['A', 'B'], ['C', 'D'], ['E']]
3 : [['A', 'B', 'C'], ['D', 'E']]
4 : [['A', 'B', 'C', 'D'], ['E']]
5 : [['A', 'B', 'C', 'D', 'E']]

Or if you want to discard the uneven leftovers:

 for j in range(1,6):
... print j,':',[lst[i:i+j] for i in xrange(0,len(lst),j) if i
+j=len(lst)]
...
1 : [['A'], ['B'], ['C'], ['D'], ['E']]
2 : [['A', 'B'], ['C', 'D']]
3 : [['A', 'B', 'C']]
4 : [['A', 'B', 'C', 'D']]
5 : [['A', 'B', 'C', 'D', 'E']]

Or define a lambda:

 chunksWithLeftovers = lambda lst,n: [lst[i:i+n] for i in 
 xrange(0,len(lst),n)]
 chunksWithoutLeftovers = lambda lst,n: [lst[i:i+n] for i in 
 xrange(0,len(lst),n) if i+n=len(lst)]
 chunksWithLeftovers(lst,2)
[['A', 'B'], ['C', 'D'], ['E']]
 chunksWithoutLeftovers(lst,2)
[['A', 'B'], ['C', 'D']]


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


Re: How to write Regular Expression for recursive matching?

2007-11-26 Thread Paul McGuire
On Nov 26, 10:51 am, Paul McGuire [EMAIL PROTECTED] wrote:
 On Nov 26, 10:40 am, lisong [EMAIL PROTECTED] wrote:





  Hi All,

  I have problem to split a string like this:

  'abc.defg.hij.klmnop'

  and I want to get all substrings with only one '.' in mid. so the
  output I expect is :

  'abc.defg', 'defg.hij', 'hij.klmnop'

  a simple regular expression '\w+.\w' will only return:
  'abc.defg', 'hij.klmnop'

  is there a way to get 'defg.hij' using regular expression?

  Thanks,

 Why are you using regular expressions?  Use the split method defined
 for strings:

  'abc.defg.hij.klmnop'.split('.')

 ['abc', 'defg', 'hij', 'klmnop']

 -- Paul- Hide quoted text -

 - Show quoted text -

Sorry, misread your post - Diez Roggisch has the right answer.

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


Re: How to write Regular Expression for recursive matching?

2007-11-26 Thread Boris Borcic
lisong wrote:
 Hi All,
 
 I have problem to split a string like this:
 
 'abc.defg.hij.klmnop'
 
 and I want to get all substrings with only one '.' in mid. so the
 output I expect is :
 
 'abc.defg', 'defg.hij', 'hij.klmnop'
 
 a simple regular expression '\w+.\w' will only return:
 'abc.defg', 'hij.klmnop'
 
 is there a way to get 'defg.hij' using regular expression?
 
 Thanks,
 

Do you need it to be a regular expression ?

  def f(s) :
ws = s.split('.')
return map('.'.join,zip(ws,ws[1:]))

  f('abc.defg.hij.klmnop')
['abc.defg', 'defg.hij', 'hij.klmnop']

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


Re: How to write Regular Expression for recursive matching?

2007-11-26 Thread J. Clifford Dyer
On Mon, Nov 26, 2007 at 06:04:54PM +0100, Diez B. Roggisch wrote regarding Re: 
How to write Regular Expression for recursive matching?:
 
 lisong wrote:
 
  Hi All,
  
  I have problem to split a string like this:
  
  'abc.defg.hij.klmnop'
  
  and I want to get all substrings with only one '.' in mid. so the
  output I expect is :
  
  'abc.defg', 'defg.hij', 'hij.klmnop'
  
  a simple regular expression '\w+.\w' will only return:
  'abc.defg', 'hij.klmnop'
  
  is there a way to get 'defg.hij' using regular expression?
 
 Nope. Regular expressions can't get back in their input-stream, at least not
 for such stuff.
 
 The problem at hand is easily solved using
 
 s = 'abc.defg.hij.klmnop'
 
 pairs = [..join(v) for v in zip(s.split(.)[:-1], s.split(.)[1:])]
 

which is veritably perlesque in its elegance and simplicity!

A slightly more verbose version.

l = s.split('.')
pairs = []
for x in xrange(len(l)-1):
pairs.append('.'.join(l[x:x+2]))

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


Re: spawning a process with subprocess

2007-11-26 Thread bhunter
 I've read that this sort of thing can be a pain. I'm sure someone will
 post and have other views though. I have had some success using
 Python's threading module though. There's a pretty good walkthrough
 here (it uses wxPython in its example):

 http://wiki.wxpython.org/LongRunningTasks

 Other places of interest include:

 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/491281http://uucode.com/texts/pylongopgui/pyguiapp.htmlhttp://sayspy.blogspot.com/2007/11/idea-for-process-concurrency.html

 If I were doing something like this, I would have the process write
 it's output to a file and periodically check to see if the file has
 data.

 Hopefully someone with more knowledge will come along soon.

 Mike

Darn.  Is threading the only way to do it?  I was hoping not to have
to avoid that.  Would have thought that there might be a way for
subprocess to handle this automatically.

Thanks for your help,
Brian
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to write Regular Expression for recursive matching?

2007-11-26 Thread lisong
On Nov 26, 12:34 pm, J. Clifford Dyer [EMAIL PROTECTED] wrote:
 On Mon, Nov 26, 2007 at 06:04:54PM +0100, Diez B. Roggisch wrote regarding 
 Re: How to write Regular Expression for recursive matching?:





  lisong wrote:

   Hi All,

   I have problem to split a string like this:

   'abc.defg.hij.klmnop'

   and I want to get all substrings with only one '.' in mid. so the
   output I expect is :

   'abc.defg', 'defg.hij', 'hij.klmnop'

   a simple regular expression '\w+.\w' will only return:
   'abc.defg', 'hij.klmnop'

   is there a way to get 'defg.hij' using regular expression?

  Nope. Regular expressions can't get back in their input-stream, at least not
  for such stuff.

  The problem at hand is easily solved using

  s = 'abc.defg.hij.klmnop'

  pairs = [..join(v) for v in zip(s.split(.)[:-1], s.split(.)[1:])]

 which is veritably perlesque in its elegance and simplicity!

 A slightly more verbose version.

 l = s.split('.')
 pairs = []
 for x in xrange(len(l)-1):
 pairs.append('.'.join(l[x:x+2]))

 Cheers,
 Cliff

Thank u all for your kindly reply, I agree, RE is not necessary here.

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


Re: Tk 8.5

2007-11-26 Thread James Matthews
I also cannot wait!

On Nov 24, 2007 4:12 PM, Ron Provost [EMAIL PROTECTED] wrote:

  Hello,

 According to the tk wiki, the final release of Tcl/Tk is just weeks away
 (see http://wiki.tcl.tk/12753).  Does anyone know if the Tk enhancements
 will be in Python 2.6?  Since I don't use tk but I do use Python and
 Tkinter (and Tix) extensively, I'm excited about these long-awaited changes.

 Thanks,
 Ron


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




-- 
http://search.goldwatches.com/?Search=Movado+Watches
http://www.jewelerslounge.com
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: spawning a process with subprocess

2007-11-26 Thread kyosohma
On Nov 26, 12:27 pm, bhunter [EMAIL PROTECTED] wrote:
  I've read that this sort of thing can be a pain. I'm sure someone will
  post and have other views though. I have had some success using
  Python's threading module though. There's a pretty good walkthrough
  here (it uses wxPython in its example):

 http://wiki.wxpython.org/LongRunningTasks

  Other places of interest include:

 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/491281http://...

  If I were doing something like this, I would have the process write
  it's output to a file and periodically check to see if the file has
  data.

  Hopefully someone with more knowledge will come along soon.

  Mike

 Darn.  Is threading the only way to do it?  I was hoping not to have
 to avoid that.  Would have thought that there might be a way for
 subprocess to handle this automatically.

 Thanks for your help,
 Brian

This is just the way I do it...as I said, there are probably some
other people in the group who will have other opinions. By the way,
your statement I was hoping not to have to avoid that means that you
hoped to use threading...which I think is contradictory to what you
meant.

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


Re: spawning a process with subprocess

2007-11-26 Thread Diez B. Roggisch
bhunter schrieb:
 Hi,
 
 I've used subprocess with 2.4 several times to execute a process, wait
 for it to finish, and then look at its output.  Now I want to spawn
 the process separately, later check to see if it's finished, and if it
 is look at its output.  I may want to send a signal at some point to
 kill the process.  This seems straightforward, but it doesn't seem to
 be working.
 
 Here's my test case:
 
 import subprocess, time
 
 cmd = cat somefile
 thread = subprocess.Popen(args=cmd.split(), shell=True,
 stdout=subprocess.PIPE, stdin=subprocess.PIPE,
 stderr=subprocess.STDOUT, close_fds=True)
 
 while(1):
   time.sleep(1)
   if(thread.returncode):
  break
   else:
  print thread.returncode
 
 print returncode = , thread.returncode
 for line in thread.stdout:
print stdout:\t,line
 
 
 This will just print the returncode of None forever until I Ctrl-C it.
 
 Of course, the program works fine if I call thread.communicate(), but
 since this waits for the process to finish, that's not what I want.
 
 Any help would be appreciated.

I have difficulties understanding what you are after here. To me it 
looks as if everything works as expected. I mean you periodically check 
on the liveness of the thread - which is what you describe above. All 
you are missing IMHO is the actual work in this program.

So

while True:
 if do_work():
 if thread.returncode:
 break
 else:
 thread.kill()

This assumes that your do_work()-method communicates the wish to end the 
sub-process using it's returnvalue.

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


Re: Should proxy objects lie about their class name?

2007-11-26 Thread Diez B. Roggisch
John J. Lee schrieb:
 [EMAIL PROTECTED] (John J. Lee) writes:
 
 Not much to add to the subject line.  I mean something like this:

 ProxyClass.__name__ = ProxiedClass.__name__


 I've been told that this is common practice.  Is it?  Would this
 surprise you if you ran into it in a debugging session?
 
 Does nobody have an opinion on this?  Pull your socks up, c.l.py!
 
 insert reference to argument sketch here

I've written quite a few proxies, but none of them did that. IMHO this 
is similar to using isinstance overeagerly: it works against the 
duck-typing principle to guard code by requiring certain base-classes, 
instead of just relying on protocol. The same applies here.

There might be of course cases where you have code lying around that 
does do some distinctions based on the class-name (I'm certainly I've 
seen such stuff once or tiwce, but always regarded it a WTF). Then doing 
as you do above might help in getting things work.

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


Re: Need to call functions/class_methods etc using string ref :How

2007-11-26 Thread Bruno Desthuilliers
Donn Ingle a écrit :
I see someone already showed you eval.  Eval is evil.  Don't use it. 
Especially if the functions are coming to you from a public URL!
 
 Yes, I suggested to him (by email) this:
 
 thisinstance =  SomeObject.__class__.__dict__
 Then you have a list of strings that may be function names, so:

This will only get attributes defined in SomeObject.__class__ - not the 
one defined in the parent classes. Nor methods dynamically bound to a 
specific instance.

 for f in yourlist:
  if f in thisinstance: eval(f)(params)
 
 Which would vet the functions too.

You *still* don't need eval here.

target = module or any other objet here
for funcname in funclist:
   func = getattr(target, funcname, None)
   if callable(func):
 func(*args, **kwargs)


I've almost never had a real use case for eval (or exec) in 7 years.
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: better way to write this function

2007-11-26 Thread Paul Hankin
On Nov 26, 7:42 am, Kelie [EMAIL PROTECTED] wrote:
 Hello,

 This function does I what I want. But I'm wondering if there is an
 easier/better way. To be honest, I don't have a good understanding of
 what pythonic means yet.

 def divide_list(lst, n):
 Divide a list into a number of lists, each with n items. Extra
 items are
ignored, if any.
 cnt = len(lst) / n
 rv =  [[None for i in range(n)] for i in range(cnt)]
 for i in range(cnt):
 for j in range(n):
 rv[i][j] = lst[i * n + j]
 return rv

 Thanks!

Here's a terrible way to do it:

def divide_list(lst, n):
return zip(*[lst[i::n] for i in range(n)])

[It produces a list of tuples rather than a list of lists, but it
usually won't matter].

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


Re: the annoying, verbose self

2007-11-26 Thread Bruno Desthuilliers
Ton van Vliet a écrit :
 On 24 Nov 2007 13:56:37 GMT, Marc 'BlackJack' Rintsch [EMAIL PROTECTED]
 wrote:
(snip)
So::

   def meth(self):
   using self:
   tmp = raw_input('Enter age: ')
   age = int(tmp)

becomes::

   def meth(self):
   using self:
   self.tmp = self.raw_input('Enter age: ')
   self.age = self.int(tmp)

Binding `tmp` unnecessarily to the object and trying to get `raw_input()`
and `int()` from the object.  Ouch.  :-)
 
 
 Absolutely.
 
 However, I was more thinking in terms of attributes only

Too bad : in Python, everything's an object, so 'methods' are attributes 
too.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: the annoying, verbose self

2007-11-26 Thread Bruno Desthuilliers
samwyse a écrit :
(snip)
 
 Besides Pascal, Visual Basic also offers a 'with' statement that
 behaves almost in this way.  That in itself should be an indication
 that the whole thing is a bad idea.  ;-)

FWIW, Javascript has it too - and it's considered a BadPractice(tm) to 
use it...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: the annoying, verbose self

2007-11-26 Thread Bruno Desthuilliers
Ton van Vliet a écrit :
 On 24 Nov 2007 16:07:18 GMT, Duncan Booth
 [EMAIL PROTECTED] wrote:
 
 
Ton van Vliet [EMAIL PROTECTED] wrote:


It would boil down to choice: explicit/speed vs implicit/readability

No, it would boil down to explicit+speed+readability+maintainability vs 
implicit+error prone.
 
 
 It would not be a full fledged *implicit*, but only used in small
 areas where many self's are coming together, and possibly clutter
 readability (a subjective classification anyhow) and even could
 degrade (code) maintainability.
 
 
In which case explicitely making local aliases is not too much work, and 
way more readable.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to Teach Python Variables

2007-11-26 Thread [EMAIL PROTECTED]
Hrvoje Niksic wrote:
 greg [EMAIL PROTECTED] writes:

  none wrote:
  IIRC, I once saw an explanation how Python doesn't have
  variables in the sense that, say, C does, and instead has bindings
  from names to objects.
 

IMHO, this is nonsense.  All that variables are (in any language) are
bindings for names.  Pretending python does anything novel with
regard to variables is confusing and, ultimately, simply results in
a redefinition of terms programmers are already familiar with.  I
mean, it's kind of like saying my computer is not a computer but is
actually a device that follows input directions.  Of course that
description may be true (and I may even use it to explain to students
*what* a computer is), but it is no less a computer for it.

  If you're talking to C programmers, just tell them that Python
  variables always contain pointers. That should give them the right
  mental model to build on.

 That is a convenient shortcut when it works, but in my experience it
 tends to confuse the issue.  The reason is that one of the main uses
 of pointers in C is implementing pass-by-reference.  A C programmer
 told that Python variables internally hold pointers expects this code:


I think most C programmers are smart enough to figure out the supposed
differences, with only a little additional explanation on the part of
the instructor.  Python's variable model is practically identical to
that of Java, after all, and I don't recall any discussion of
cataclysmic proportions over the differences between C pointers and
Java references.  There are differences (or more accurately
points of emphasis), but of the sort that take a paragraph or two of
explanation/clarification -- not a completely new model.

 def func(a):
   a = 10
 ...
 func(x)

 to change the value of x.

Depends on how you implement the C equivalent.  The most direct
translation, IMHO, is the following:

  void func(int *a){
a = 10; //Of course this is nonsense, but it illustrates the
point.  Just because a is a pointer
 //does not mean that a is not rebound when it is
assigned to.  Oh wait!  Did I use
 //the word rebound when talking about a *C*
variable? ;-)
//*a = 10; //I'm guessing this is what *you* had in mind, but it
is very different
  }

  int main(int argc, char **argv){
int x = 5;
func(x);
printf(x is: %i\n, x);
return 0;
  }

Which prints:
  x is: 5

In this case, both the C and Python code have the same result.

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


Re: the annoying, verbose self

2007-11-26 Thread Bruno Desthuilliers
Patrick Mullen a écrit :
(snip)
 Still an unnecessary lookup on tmp though :)  And it would be useless
 to use it for one assignment, the idea is to eliminate all the typing
 with this:
 
 self.var1 = 5
 self.var2 = a value
 self.var3 = stuff
 self.var4 = [2,54,7,7]
 self.var5 = dingaling
 self.var6 = 6.4
 self.var7 = 1
 self.var8 = False
 self.var9 = True

self.__dict__.update(dict(var1=5, var2=a value, var3 = stuff, etc))

Someone else ? Or are we done with this DeadHorse ?
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: the annoying, verbose self

2007-11-26 Thread Bruno Desthuilliers
samwyse a écrit :
(snip)
 
 Actually, the chained dots are solving a completely different problem,
 that of refactoring a collection of functions that use global vars
 into a class.

Using globals to maintain state between functions being bad practice in 
most cases, I don't see any reason to encourage it by providing some 
builtin support.


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


Re: spawning a process with subprocess

2007-11-26 Thread bhunter

 This is just the way I do it...as I said, there are probably some
 other people in the group who will have other opinions. By the way,
 your statement I was hoping not to have to avoid that means that you
 hoped to use threading...which I think is contradictory to what you
 meant.

 Mike

That was a typo.  I was hoping to avoid that is what it should
read.  Proof once again: never type while holding a baby. :)

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


Re: better way to write this function

2007-11-26 Thread Peter Otten
Peter Otten wrote:

 def chunks(items, n):
 ... return [items[start:start+n] for n in range(0, len(items)-n+1, n)]

Ouch, this should be 

def chunks(items, n):
return [items[start:start+n] for start in range(0, len(items)-n+1, n)]
 
Peter
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: spawning a process with subprocess

2007-11-26 Thread bhunter
On Nov 26, 1:50 pm, Diez B. Roggisch [EMAIL PROTECTED] wrote:
 bhunter schrieb:



  Hi,

  I've used subprocess with 2.4 several times to execute a process, wait
  for it to finish, and then look at its output.  Now I want to spawn
  the process separately, later check to see if it's finished, and if it
  is look at its output.  I may want to send a signal at some point to
  kill the process.  This seems straightforward, but it doesn't seem to
  be working.

  Here's my test case:

  import subprocess, time

  cmd = cat somefile
  thread = subprocess.Popen(args=cmd.split(), shell=True,
  stdout=subprocess.PIPE, stdin=subprocess.PIPE,
  stderr=subprocess.STDOUT, close_fds=True)

  while(1):
time.sleep(1)
if(thread.returncode):
   break
else:
   print thread.returncode

  print returncode = , thread.returncode
  for line in thread.stdout:
 print stdout:\t,line

  This will just print the returncode of None forever until I Ctrl-C it.

  Of course, the program works fine if I call thread.communicate(), but
  since this waits for the process to finish, that's not what I want.

  Any help would be appreciated.

 I have difficulties understanding what you are after here. To me it
 looks as if everything works as expected. I mean you periodically check
 on the liveness of the thread - which is what you describe above. All
 you are missing IMHO is the actual work in this program.

 So

 while True:
  if do_work():
  if thread.returncode:
  break
  else:
  thread.kill()

 This assumes that your do_work()-method communicates the wish to end the
 sub-process using it's returnvalue.

 Diez

If the subprocess had finished, I expect that the returncode will not
be None, and the loop would break.  The process hasn't actually
started.  I know this because while this simple testcase just cats a
file, the real case submits a simulation job.  This job never starts
until after I ctrl-c the program.

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


Best ways of managing text encodings in source/regexes?

2007-11-26 Thread tinkerbarbet
Hi

I've read around quite a bit about Unicode and python's support for
it, and I'm still unclear about how it all fits together in certain
scenarios.  Can anyone help clarify?

* When I say # -*- coding: utf-8 -*- and confirm my IDE is saving
the source file as UTF-8, do I still need to prefix all the strings
constructed in the source with u as in myStr = ublah, even when
those strings contain only ASCII or ISO-8859-1 chars?  (It would be a
bother for me to do this for the complete source I'm working on, where
I rarely need chars outside the ISO-8859-1 range.)

* Will python figure it out if I use different encodings in different
modules -- say a main source file which is # -*- coding: utf-8 -*-
and an imported module which doesn't say this (for which python will
presumably use a default encoding)?  This seems inevitable given that
standard library modules such as re don't declare an encoding,
presumably because in that case I don't see any non-ASCII chars in the
source.

* If I want to use a Unicode char in a regex -- say an en-dash, U+2013
-- in an ASCII- or ISO-8859-1-encoded source file, can I say

myASCIIRegex = re.compile('[A-Z]')
myUniRegex = re.compile(u'\u2013') # en-dash

then read the source file into a unicode string with codecs.read(),
then expect re to match against the unicode string using either of
those regexes if the string contains the relevant chars?  Or do I need
to do make all my regex patterns unicode strings, with u?

I've been trying to understand this for a while so any clarification
would be a great help.

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


Re: How to Teach Python Variables

2007-11-26 Thread Chris Mellon
On Nov 26, 2007 1:21 PM, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote:
 Hrvoje Niksic wrote:
  greg [EMAIL PROTECTED] writes:
 
   none wrote:
   IIRC, I once saw an explanation how Python doesn't have
   variables in the sense that, say, C does, and instead has bindings
   from names to objects.
  

 IMHO, this is nonsense.  All that variables are (in any language) are
 bindings for names.  Pretending python does anything novel with
 regard to variables is confusing and, ultimately, simply results in
 a redefinition of terms programmers are already familiar with.  I
 mean, it's kind of like saying my computer is not a computer but is
 actually a device that follows input directions.  Of course that
 description may be true (and I may even use it to explain to students
 *what* a computer is), but it is no less a computer for it.


Long real-life experience that people with previous programming
experience, especially C programmers, have a great deal of trouble
with this concept. Python variables do not work the way they do in
other languages, where variables are compile-time bindings for memory
locations. Even Java references aren't the same (there's no such thing
as a null reference in Python, for example).

   If you're talking to C programmers, just tell them that Python
   variables always contain pointers. That should give them the right
   mental model to build on.
 
  That is a convenient shortcut when it works, but in my experience it
  tends to confuse the issue.  The reason is that one of the main uses
  of pointers in C is implementing pass-by-reference.  A C programmer
  told that Python variables internally hold pointers expects this code:
 

 I think most C programmers are smart enough to figure out the supposed
 differences, with only a little additional explanation on the part of
 the instructor.  Python's variable model is practically identical to
 that of Java, after all, and I don't recall any discussion of
 cataclysmic proportions over the differences between C pointers and
 Java references.  There are differences (or more accurately
 points of emphasis), but of the sort that take a paragraph or two of
 explanation/clarification -- not a completely new model.


C programmers, when told that Python works like this almost *always*
get this wrong, because they want to pretend that Python is C-like
pass by reference and it isn't.

The very first thing they want to do is to get at the pointer
underneath the object so they can simulate C style pass by reference
with ints. It takes a lot of bandwidth (both mental and electronic)
before they get that there is no underlying pointer and they can't do
this.

The second thing they want to do is to intercept rebinding actions,
like you might do in C++ with operator overloads. If you explain it to
them in these terms, it is not clear (and will not be, until you use
other terms) that rebinding a name (assignment) and mutating an object
are fundamentally different operations.

I see these questions on a daily basis in #python and somewhat less
frequently in c.l.p. Your assertion that C programmers will just get
it if it's explained in those terms is simply not borne out by real
world results.

One thing that C programmers *do* get, at least the smarter ones, is
explaining it in terms of the actual implementation - that there are
PyObject structs that are not exposed, that they are refcounted, and
that name/object bindings are entries in various hash tables. Saying
it's just like a pointer isn't generally sufficient, because it's
not like a pointer, and it gives them totally the wrong model to work
with.


  def func(a):
a = 10
  ...
  func(x)
 
  to change the value of x.

 Depends on how you implement the C equivalent.  The most direct
 translation, IMHO, is the following:

   void func(int *a){
 a = 10; //Of course this is nonsense, but it illustrates the
 point.  Just because a is a pointer
  //does not mean that a is not rebound when it is
 assigned to.  Oh wait!  Did I use
  //the word rebound when talking about a *C*
 variable? ;-)
 //*a = 10; //I'm guessing this is what *you* had in mind, but it
 is very different
   }


The very first thing a C programmer will want to do when seeing this
snippet is ask how to do the later operation in Python. If you tell
them they can't, they will then think of python variables as like
pointers, except for special cases which is wrong. If you use Python
semantics to explain it, in terms of names and bindings, they'll see
that it's not at all like pointers, that assignment operations are
totally consistent (assignment is name binding, not mutation) and that
immutable objects are immutable by virtue of not having mutating
methods, not because of compiler magic.

The only special cases which then need to be explained are augmented
assignment and object attribute assignment, which are easily (and
correctly) explained as being syntactic sugar for mutate + rebind and
a 

gnosis XML objectify

2007-11-26 Thread Wang, Harry
The gnosis xml libs should not be version specific, but when I try to use 
Python 2.5, I am getting not well formed (invalid token) errors. 

Harry

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


Re: C pointer representation in python

2007-11-26 Thread Terry Reedy

[EMAIL PROTECTED] wrote in message 
news:[EMAIL PROTECTED]
| Hi
| I am new to SWIG and python. I have a problem while trying to call a C
| function from Python using SWIG as an interface.

Did you consider using the ctypes module?
(It is new in the stdlib for 2.5, I believe.)
Some consider it easier to use than swig. 



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


Re: spawning a process with subprocess

2007-11-26 Thread Diez B. Roggisch
bhunter schrieb:
 On Nov 26, 1:50 pm, Diez B. Roggisch [EMAIL PROTECTED] wrote:
 bhunter schrieb:



 Hi,
 I've used subprocess with 2.4 several times to execute a process, wait
 for it to finish, and then look at its output.  Now I want to spawn
 the process separately, later check to see if it's finished, and if it
 is look at its output.  I may want to send a signal at some point to
 kill the process.  This seems straightforward, but it doesn't seem to
 be working.
 Here's my test case:
 import subprocess, time
 cmd = cat somefile
 thread = subprocess.Popen(args=cmd.split(), shell=True,
 stdout=subprocess.PIPE, stdin=subprocess.PIPE,
 stderr=subprocess.STDOUT, close_fds=True)
 while(1):
   time.sleep(1)
   if(thread.returncode):
  break
   else:
  print thread.returncode
 print returncode = , thread.returncode
 for line in thread.stdout:
print stdout:\t,line
 This will just print the returncode of None forever until I Ctrl-C it.
 Of course, the program works fine if I call thread.communicate(), but
 since this waits for the process to finish, that's not what I want.
 Any help would be appreciated.
 I have difficulties understanding what you are after here. To me it
 looks as if everything works as expected. I mean you periodically check
 on the liveness of the thread - which is what you describe above. All
 you are missing IMHO is the actual work in this program.

 So

 while True:
  if do_work():
  if thread.returncode:
  break
  else:
  thread.kill()

 This assumes that your do_work()-method communicates the wish to end the
 sub-process using it's returnvalue.

 Diez
 
 If the subprocess had finished, I expect that the returncode will not
 be None, and the loop would break.  The process hasn't actually
 started.  I know this because while this simple testcase just cats a
 file, the real case submits a simulation job.  This job never starts
 until after I ctrl-c the program.

I don't know what the reason is for that, but I've just today worked 
with code that exactly uses subprocess as advertised - spawning a 
process which runs while the main process occasionally checks inside the 
child's logfiles for certain state changes.

What might be though is that you need to consume the subprocesses stdout 
in your program - because otherwise it will buffer until a certain 
amount (usually 4 or 16k) and then halt.



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


Re: Need to call functions/class_methods etc using string ref :How

2007-11-26 Thread Donn Ingle
 target = module or any other objet here
 for funcname in funclist:
 func = getattr(target, funcname, None)
 if callable(func):
 func(*args, **kwargs)
Nice. 'callable' is new to me. Live and learn :)

\d

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


Re: gnosis XML objectify

2007-11-26 Thread kyosohma
On Nov 26, 1:46 pm, Wang, Harry [EMAIL PROTECTED] wrote:
 The gnosis xml libs should not be version specific, but when I try to use 
 Python 2.5, I am getting not well formed (invalid token) errors.

 Harry

When does this happen? When you import the module? When you pass it
some xml? Do you have a full traceback?

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


Re: gnosis XML objectify

2007-11-26 Thread Sébastien Boisgérault
On Nov 26, 8:46 pm, Wang, Harry [EMAIL PROTECTED] wrote:
 The gnosis xml libs should not be version specific, but when I try to use 
 Python 2.5, I am getting not well formed (invalid token) errors.

 Harry

Could you show us a simple example that exhibits this behavior
please ?

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


RE: gnosis XML objectify

2007-11-26 Thread Wang, Harry
Full Traceback enclosed:
 
Test Suite Started @ 2007-11-26 11:34:46.617000
Traceback (most recent call last):
  File C:\UDR2\UDRxmlGateway.py, line 370, in module
ParseAll()
  File C:\UDR2\UDRxmlGateway.py, line 286, in ParseAll
py_obj = gnosis.xml.objectify.XML_Objectify(InputFile).make_instance()
  File C:\python25\Lib\site-packages\gnosis\xml\objectify\_objectify.py, line 
160, in make_instance
o = self.ParseFile(self._fh)
  File C:\python25\Lib\site-packages\gnosis\xml\objectify\_objectify.py, line 
190, in ParseFile
self._myparser.ParseFile(file)
xml.parsers.expat.ExpatError: not well-formed (invalid token): line 68, column 0
 
Harry C. Wang
Sr. Test Engineer (Automation)
AOL Mobile
Phone 206 - 268 - 7502
temporary e-mail: [EMAIL PROTECTED] 
Personal e-mail: [EMAIL PROTECTED] 



From: [EMAIL PROTECTED] on behalf of [EMAIL PROTECTED]
Sent: Mon 11/26/2007 12:19 PM
To: python-list@python.org
Subject: Re: gnosis XML objectify



On Nov 26, 1:46 pm, Wang, Harry [EMAIL PROTECTED] wrote:
 The gnosis xml libs should not be version specific, but when I try to use 
 Python 2.5, I am getting not well formed (invalid token) errors.

 Harry

When does this happen? When you import the module? When you pass it
some xml? Do you have a full traceback?

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


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


Re: Need to call functions/class_methods etc using string ref :How

2007-11-26 Thread Bruno Desthuilliers
Donn Ingle a écrit :
target = module or any other objet here
for funcname in funclist:
func = getattr(target, funcname, None)
if callable(func):
func(*args, **kwargs)
 
 Nice. 'callable' is new to me.

What about getattr, then ?-)

And FWIW, callable will disappear in py3k... (anyway, you can just test 
if the object has a __call__ method).
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: gnosis XML objectify

2007-11-26 Thread Wang, Harry
I can't tell where in the XML file it throws the error.
 
Here is the snippet of the Python code:
def ParseAll():
py_obj = gnosis.xml.objectify.XML_Objectify(InputFile).make_instance()

Harry C. Wang
Sr. Test Engineer (Automation)
AOL Mobile
Phone 206 - 268 - 7502
temporary e-mail: [EMAIL PROTECTED] 
Personal e-mail: [EMAIL PROTECTED] 



From: [EMAIL PROTECTED] on behalf of Sébastien Boisgérault
Sent: Mon 11/26/2007 12:21 PM
To: python-list@python.org
Subject: Re: gnosis XML objectify



On Nov 26, 8:46 pm, Wang, Harry [EMAIL PROTECTED] wrote:
 The gnosis xml libs should not be version specific, but when I try to use 
 Python 2.5, I am getting not well formed (invalid token) errors.

 Harry

Could you show us a simple example that exhibits this behavior
please ?

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


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


Re: the annoying, verbose self

2007-11-26 Thread Ton van Vliet
On Mon, 26 Nov 2007 20:14:50 +0100, Bruno Desthuilliers
[EMAIL PROTECTED] wrote:

 However, I was more thinking in terms of attributes only

Too bad : in Python, everything's an object, so 'methods' are attributes 
too.

Right, but I'm sure *you* know a way to distinguish between them (I'm
just a beginner ;-)

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


Re: gnosis XML objectify

2007-11-26 Thread kyosohma
On Nov 26, 2:33 pm, Wang, Harry [EMAIL PROTECTED] wrote:
 Full Traceback enclosed:

 Test Suite Started @ 2007-11-26 11:34:46.617000
 Traceback (most recent call last):
   File C:\UDR2\UDRxmlGateway.py, line 370, in module
 ParseAll()
   File C:\UDR2\UDRxmlGateway.py, line 286, in ParseAll
 py_obj = gnosis.xml.objectify.XML_Objectify(InputFile).make_instance()
   File C:\python25\Lib\site-packages\gnosis\xml\objectify\_objectify.py, 
 line 160, in make_instance
 o = self.ParseFile(self._fh)
   File C:\python25\Lib\site-packages\gnosis\xml\objectify\_objectify.py, 
 line 190, in ParseFile
 self._myparser.ParseFile(file)
 xml.parsers.expat.ExpatError: not well-formed (invalid token): line 68, 
 column 0

 Harry C. Wang
 Sr. Test Engineer (Automation)
 AOL Mobile
 Phone 206 - 268 - 7502
 temporary e-mail: [EMAIL PROTECTED]
 Personal e-mail: [EMAIL PROTECTED]

 

 From: [EMAIL PROTECTED] on behalf of [EMAIL PROTECTED]
 Sent: Mon 11/26/2007 12:19 PM
 To: [EMAIL PROTECTED]
 Subject: Re: gnosis XML objectify

 On Nov 26, 1:46 pm, Wang, Harry [EMAIL PROTECTED] wrote:

  The gnosis xml libs should not be version specific, but when I try to use 
  Python 2.5, I am getting not well formed (invalid token) errors.

  Harry

 When does this happen? When you import the module? When you pass it
 some xml? Do you have a full traceback?

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

Googling the error seems to indicate that the problem may be an
encoding issue. Check the following threads:

http://www.mail-archive.com/[EMAIL PROTECTED]/msg00787.html
http://article.gmane.org/gmane.comp.python.devel/90093
http://mail.python.org/pipermail/python-list/2007-July/450288.html

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


gnosis XML objectify

2007-11-26 Thread Wang, Harry
Problem solved.   
 
I left out a right closing tag () in the XML, but I am having another 
problem. 
 
Harry C. Wang
Sr. Test Engineer (Automation)
AOL Mobile
Phone 206 - 268 - 7502
temporary e-mail: [EMAIL PROTECTED] 
Personal e-mail: [EMAIL PROTECTED] 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: spawning a process with subprocess

2007-11-26 Thread bhunter
On Nov 26, 3:05 pm, Diez B. Roggisch [EMAIL PROTECTED] wrote:
 bhunter schrieb:



  On Nov 26, 1:50 pm, Diez B. Roggisch [EMAIL PROTECTED] wrote:
  bhunter schrieb:

  Hi,
  I've used subprocess with 2.4 several times to execute a process, wait
  for it to finish, and then look at its output.  Now I want to spawn
  the process separately, later check to see if it's finished, and if it
  is look at its output.  I may want to send a signal at some point to
  kill the process.  This seems straightforward, but it doesn't seem to
  be working.
  Here's my test case:
  import subprocess, time
  cmd = cat somefile
  thread = subprocess.Popen(args=cmd.split(), shell=True,
  stdout=subprocess.PIPE, stdin=subprocess.PIPE,
  stderr=subprocess.STDOUT, close_fds=True)
  while(1):
time.sleep(1)
if(thread.returncode):
   break
else:
   print thread.returncode
  print returncode = , thread.returncode
  for line in thread.stdout:
 print stdout:\t,line
  This will just print the returncode of None forever until I Ctrl-C it.
  Of course, the program works fine if I call thread.communicate(), but
  since this waits for the process to finish, that's not what I want.
  Any help would be appreciated.
  I have difficulties understanding what you are after here. To me it
  looks as if everything works as expected. I mean you periodically check
  on the liveness of the thread - which is what you describe above. All
  you are missing IMHO is the actual work in this program.

  So

  while True:
   if do_work():
   if thread.returncode:
   break
   else:
   thread.kill()

  This assumes that your do_work()-method communicates the wish to end the
  sub-process using it's returnvalue.

  Diez

  If the subprocess had finished, I expect that the returncode will not
  be None, and the loop would break.  The process hasn't actually
  started.  I know this because while this simple testcase just cats a
  file, the real case submits a simulation job.  This job never starts
  until after I ctrl-c the program.

 I don't know what the reason is for that, but I've just today worked
 with code that exactly uses subprocess as advertised - spawning a
 process which runs while the main process occasionally checks inside the
 child's logfiles for certain state changes.

 What might be though is that you need to consume the subprocesses stdout
 in your program - because otherwise it will buffer until a certain
 amount (usually 4 or 16k) and then halt.

 Diez

It works?  You mean there are place on earth where it really does
this?  Excellent!

Still doesn't work for me, though.  I first tried changing bufsize to
-1, then 0, then a very large number greater than the number of bytes
in this file (just to be sure).  None seemed to have any affect.

Then I modified the code to this:

cmd = cat /nfs/dv1/bhunter/o52a/verif/gmx/rgx.cc
args = cmd.split()
thread = subprocess.Popen(args=args, shell=True,
stdout=subprocess.PIPE, stdin=subprocess.PIPE,
stderr=subprocess.STDOUT, close_fds=True, bufsize=30)

lines = []

try:
   while(1):
  time.sleep(1)
  if(thread.returncode):
 break
  else:
 print thread.returncode
  lines.extend(thread.stdout.readlines())
except KeyboardInterrupt:
   print lines

print returncode = , thread.returncode
for line in thread.stdout:
   print stdout:\t,line


This one hangs after the first print of returncode None.  Then, I ctrl-
C it and find that the lines array is empty.

It's my guess that the process is waiting for some input, even though
'cat'  clearly does not require anything from stdin.  But if I put a
communicate() after Popen and a few other tweaks, then everything
works as expected--but of course not as desired.

Still confused.

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


Re: basic if stuff- testing ranges

2007-11-26 Thread John Machin
On Nov 27, 3:01 am, Erik Jones [EMAIL PROTECTED] wrote:
 On Nov 25, 2007, at 9:49 PM, Donn Ingle wrote:



  if 0  x  20: print within
  That means if x LESS THAN 0 and x  20.
  Oh, bugger. It's tricky.
  So try
  if 0  x  20:
  Thanks. I was flipping signs in my tests, but I guess I flipped
  both and got
  myself all confused.

  Likely manuals: Tutorial  Reference
  Tutorial: check contents, if statement looks possible, but no luck
  Yes, I got that far.
  Reference: check contents, comparisons looks possible, and
  Thanks again. I find the reference is laid-out in a way that I
  don't find
  intuitive and every time I look for something I fail. I even grep
  through
  the folder to get a clue, which shows how poor the index is (to me)!

 Then use one of the quick references here:http://rgruet.free.fr/.


Generally excellent references, but X  Y  Z  W has expected
meaning, unlike C is not much help to people who have not been
exposed to similar notation (e.g. 0 = angle  2 * pi) in other
disciplines and/or know C merely as a member of the same set as X, Y,
Z and W.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: the annoying, verbose self

2007-11-26 Thread Colin J. Williams
Bruno Desthuilliers wrote:
[snip]
 Too bad : in Python, everything's an object, so 'methods' are attributes 
 too.

What do you see as a problem here? 
Surely it gives useful flexibility.

Colin W.

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


Re: better way to write this function

2007-11-26 Thread Arnaud Delobelle
On Nov 26, 8:19 am, Peter Otten [EMAIL PROTECTED] wrote:
[...]

 Or build a generator that works with arbitrary iterables:

  from itertools import *
  def chunks(items, n):

 ... items = iter(items)
 ... while 1:
 ... chunk = list(islice(items, n-1))
 ... chunk.append(items.next())
 ... yield chunk
 ... list(chunks(range(5), 2))

 [[0, 1], [2, 3]]

 Peter

I was about to send this before I saw your post :)
Well here it is anyway...
Using the fact that StopIteration exceptions fall through list
comprehensions (as opposed to islices):

def chunks(iterable, size):
next = iter(iterable).next
while True:
yield [next() for i in xrange(size)]

--
Arnaud

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


Installing Python 3000

2007-11-26 Thread André
Sorry about the simple question ...

I'd like to install Python 3000 on my computers (Mac, and possibly
Windows), without messing up the existing versions.  So far, I've
always relied on using .msi on Windows and .dmg on the Mac.

From the Python site, I read (different version, but still...):

Unpack the archive with tar -zxvf Python-2.4.4.tgz ... Change to the
Python-2.4.4 directory and run the ./configure, make, make
install commands to compile and install Python.

The step that gets me worried is the make install one... I don't
want it to take over as default.  I would like to be able to invoke it
by typing python3k ... from anywhere and have it work - while still
having python invoke the default 2.5 version.

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


Re: How to Teach Python Variables

2007-11-26 Thread jkn
On Nov 25, 10:36 pm, Ben Finney [EMAIL PROTECTED]
wrote:

 In addition to the good answers you've had already, I highly recommend
 David Goodger's Code like a Pythonista page
 URL:http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html,
 which contains a very good cardboard boxes versus paper tags analogy
 of the topic you're asking about.


or even Ben's own version of this, which I liked:

URL:http://groups.google.com/group/comp.lang.python/browse_frm/thread/
56e7d62bf66a435c/ab62283cde9e4c63#ab62283cde9e4c63

J^n
-- 
http://mail.python.org/mailman/listinfo/python-list


fork/exec with input redirection

2007-11-26 Thread Dan Upton
I have a Python script that does a fork/exec, so the parent process
can get the child's PID and monitor /proc/PID/stat (on a CentOS
system).  Most of my processes' command lines are straightforward
enough to do this with, but I have a handful that use  on the command
line, eg

./gobmk_base.linux_x86 --quiet --mode gtp  13x13.tst

The only thing I could really think of to try was

   os.execv(./gobmk_base.linux_x86, [./gobmk_base.linux_x86,
--quiet, --mode, gtp, , 13x13.tst])

but this apparently doesn't work.  Is there some other way to
accomplish what I'm going for?

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


Re: Installing Python 3000

2007-11-26 Thread Peter Otten
André wrote:

 The step that gets me worried is the make install one... I don't want it
 to take over as default.  I would like to be able to invoke it by typing
 python3k ... from anywhere and have it work - while still having
 python invoke the default 2.5 version.

You want

make altinstall

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

Re: fork/exec with input redirection

2007-11-26 Thread Erik Jones
On Nov 26, 2007, at 3:58 PM, Dan Upton wrote:

 I have a Python script that does a fork/exec, so the parent process
 can get the child's PID and monitor /proc/PID/stat (on a CentOS
 system).  Most of my processes' command lines are straightforward
 enough to do this with, but I have a handful that use  on the command
 line, eg

 ./gobmk_base.linux_x86 --quiet --mode gtp  13x13.tst

 The only thing I could really think of to try was

os.execv(./gobmk_base.linux_x86, [./gobmk_base.linux_x86,
 --quiet, --mode, gtp, , 13x13.tst])

 but this apparently doesn't work.  Is there some other way to
 accomplish what I'm going for?

Read up on the docs for the subprocess module.

Erik Jones

Software Developer | Emma®
[EMAIL PROTECTED]
800.595.4401 or 615.292.5888
615.292.0777 (fax)

Emma helps organizations everywhere communicate  market in style.
Visit us online at http://www.myemma.com


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


Re: Installing Python 3000

2007-11-26 Thread Martin v. Löwis
 I'd like to install Python 3000 on my computers (Mac, and possibly
 Windows), without messing up the existing versions.  So far, I've
 always relied on using .msi on Windows and .dmg on the Mac.
 
 From the Python site, I read (different version, but still...):
 
 Unpack the archive with tar -zxvf Python-2.4.4.tgz ... Change to the
 Python-2.4.4 directory and run the ./configure, make, make
 install commands to compile and install Python.
 
 The step that gets me worried is the make install one... I don't
 want it to take over as default.  I would like to be able to invoke it
 by typing python3k ... from anywhere and have it work - while still
 having python invoke the default 2.5 version.

I recommend that you then do use the prebuilt binaries, at least
where available, i.e.

http://www.python.org/download/releases/3.0/

For OSX, I recommend to use a different --prefix for installing,
e.g. /usr/local/py3k. All files then go into that directory, and
nothing else lives in it. To invoke it, you give
/usr/local/py3k/bin/python; if you want to make a python3k link someone
in your path - that would be your choice.

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


Re: How to Teach Python Variables

2007-11-26 Thread Steven D'Aprano
On Mon, 26 Nov 2007 21:37:19 +1300, greg wrote:

 none wrote:
 IIRC, I once saw an explanation how Python doesn't have variables
 in the sense that, say, C does, and instead has bindings from names to
 objects.
 
 If you're talking to C programmers, just tell them that Python variables
 always contain pointers. That should give them the right mental model to
 build on.

Until they wonder why this doesn't work.


x = 1  # x points to 1
y = x
assert x is y  # confirm y points to the same memory location as x
x += 1
assert y == 2  # so naturally y should be incremented as well



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


  1   2   >