Find & Replace hyperlinks in a string

2007-11-26 Thread Nico Grubert
Hi there,

I have a string containing some hyperlinks. I'd like to replace every 
hyperlink with a HTML style link.

Example:

Replace
   'http://www.foo.com/any_url'
with
   'http://www.foo.com/any_url";>http://www.foo.com/any_url'


What's the best way to do this if I have a few hundret strings to check?

Thanks in advance,
Nico
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: better way to write this function

2007-11-26 Thread Peter Otten
Ricardo Aráoz wrote:

> Peter Otten wrote:

>> 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]]
>> []
>> []
>> []
>> []
> 
> 
> This won't work(e.g. you don't define "start", you change the value of n
> through the loop). I guess you meant :
> 
> def chunks(items, n) :
> return [items[i:i+n] for i in range(0, len(items)-n+1, n)]

Indeed; I'm still wondering how I managed to copy'n'paste the version with
the typo together with the demo of the correct one.

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

Re: How to Teach Python "Variables"

2007-11-26 Thread greg
Hrvoje Niksic wrote:
> 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.

He shouldn't expect that, because that's not what the
equivalent code would do in C. To get that effect in C,
you would (among other things) have to write the
call as

   func(&x)

which you can't do, because there is no & operator in
Python.

I would probably use the term "reference", and explain
it by saying that a reference is a pointer to an object.
Also that Python variables always hold references, never
objects; a reference always refers to an entire object,
never a part of an object or another variable; and that
assignment is always reference assignment and never
copies objects.

And illustrate everything with lots of drawings of
boxes and arrows. It's much easier to explain all these
things unambiguously with diagrams than with words
that may not mean the same thing to the listener that
they mean to you.

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


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

2007-11-26 Thread R. Bernstein
duyanning <[EMAIL PROTECTED]> writes:

> 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.
> 
> please help me.
> thank you.

pydb (http://bashdb.sf.net/pydb) has an option to set the current
working directory on invocation. For example, from emacs I can run:

M-x pydb --cd=/tmp --annotate=3 ~/python/hanoi.py 3 

And then when I type 
  import os; os.getcwd()

I get:
  '/tmp'

Inside pydb, there is a "cd" command saving you the trouble of
importing os; the "directory" command can be used to set a search path
for source files. All same as you would do in gdb.

Begin digression ---

The --annotate option listed above, is similar to gdb's annotation
mode. It is a very recent addition and is only in CVS. With annotation
mode turned on, the effect is similar to running gdb (gdb-ui.el) in
Emacs 22.  Emacs internal buffers track the state of local variables,
breakpoints and the stack automatically as the code progresses. If the
variable pydb-many-windows is set to true, the each of these buffers
appear in a frame.

For those of you who don't start pydb initially bug enter via a call
such as set_trace() or debugger() and do this inside an Emacs comint
shell with pydb-tracking turned on, issue "set annotation 3" same as
you would if you were in gdb.

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


Re: spawning a process with subprocess

2007-11-26 Thread MonkeeSage
Hi Brian,

Couple of things. You should use poll() on the Popen instance, and
should check it explicitly against None (since a 0 return code,
meaning exit successfully, will be treated as a false condition the
same as None). Also, in your second example, you block the program
when you call readlines on the pipe, since readlines blocks until it
reaches eof (i.e., until pipe closes stdout, i.e., process is
complete). Oh, and you don't have to split the input to the args
option yourself, you can just pass a string. So, putting it all
together, you want something like:

import subprocess, time

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

while 1:
  time.sleep(1)
  if proc.poll() != None:
break
  else:
print "waiting on child..."

print "returncode =", proc.returncode

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


Re: C pointer representation in python

2007-11-26 Thread abarun22
HI
Thanks for the suggestion and i believe that seems a good idea. But
because of some work related constraints i have to use SWIG for the
moment.
Regards
Arun

Terry Reedy wrote:
> <[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: can any one tell me where to get graphics module in windows?

2007-11-26 Thread Paul McGuire
On Nov 26, 11:49 pm, evilcraft_mj <[EMAIL PROTECTED]> wrote:
> when i type
> from graphics import *
>
> error shown that there is no such module called graphics.
>
> help me find this..

Googling for "python graphics module" turns up this link:
http://mcsp.wartburg.edu/zelle/python/graphics/graphics/index.html

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


can any one tell me where to get graphics module in windows?

2007-11-26 Thread evilcraft_mj
when i type
from graphics import *

error shown that there is no such module called graphics.

help me find this..
-- 
http://mail.python.org/mailman/listinfo/python-list


**********Hi Fashion lovers*********************

2007-11-26 Thread MayaKannaGi
**Hi Fashion lovers*

http://ghjomy.50webs.com/

http://bigchurch.com/go/g914309-pmem

http://indianfriendfinder.com/go/g914309-pmem
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to Teach Python "Variables"

2007-11-26 Thread [EMAIL PROTECTED]
Chris Mellon wrote:
> 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).
>

I myself learned C++ first, then transitioned to Java, then Python.
Once I got the hang of C++ pointers, I personally did not have any
significant difficulties with Java's references, and even less so with
Python's .  Granted that's just my
experience, which doesn't mean others don't have that difficulty, but
that *is* my experience.

Also, to say that "there's no such thing as a null reference in
Python," is, IMHO, another example of nonesense.  Null is a *concept*,
not a particular *value*, and simply means "there's no real value
here."  The fact that Python's null is called "None" does not change
that.  Furthermore, the fact that Python's designers were good enough
to create a "smarter" null than most languages have does not change
that.  None is still a special value that is used to represent the
fact that there is "nothing here".

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

Which is why you need the "points of emphasis"/"caveats".  I never
claimed this is a slam-dunk.

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

Well, Java calls them "references" instead of "pointers", which may
not be a bad idea if only to emphasize that there are, in fact,
differences.  Java seems to have gotten away with explaining these
differences in a pretty concise manner.  I don't see any reason why
Python can't do likewise.

> 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 assume you are talking about overloading "operator =" in C++, but
that only works for non-pointers.  How do you "intercept" rebinding of
a *pointer* in C/C++?

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

Again, I never said C programmers will "just get it."  That's why I
used the phrase "with only a little additional explanation."  Maybe I
misinterpr

Re: Installing Python 3000 on Leopard (Mac OS) fails...

2007-11-26 Thread Martin v. Löwis
> gcc -fno-strict-aliasing -Wno-long-double -no-cpp-precomp -mno-fused-
> madd -DNDEBUG -g -O3 -Wall -Wstrict-prototypes  -I. -I./Include   -
> DPy_BUILD_CORE  -c ./Modules/posixmodule.c -o Modules/posixmodule.o
> ./Modules/posixmodule.c: In function 'posix_setpgrp':
> ./Modules/posixmodule.c:3769: error: too few arguments to function
> 'setpgrp'
> make: *** [Modules/posixmodule.o] Error 1
> 
> Any suggestions?

This is a known bug:

http://bugs.python.org/issue1358

Apparently, Apple has managed to change the header files of Leopard
in a way that breaks building Python, and also managed to break
the autoconf procedure that was designed to deal with the uncertainty
of the setpgrp declaration.

An expert of OSX will need to look into this and propose a solution;
if you think you need to get this working, just remove setpgrp from
posixmodule.

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


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

2007-11-26 Thread George Sakkis
On Nov 26, 2:04 pm, Bruno Desthuilliers

<[EMAIL PROTECTED]> wrote:
> 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__
> > 
>
> 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 = 
> 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.

That's not to say there aren't any. In one project I'm using exec to
parse user provided function bodies from a web interface into real
python functions (the function signatures are auto generated). Of
course it's a secure environment, with trusted users, etc. Although
Python's current support for code generation (source <-> ast <->
bytecode roundtrip) is far from perfect, it's much easier and more
powerful than building from scratch a domain specific toy language,
which might well turn out to be less expressive than necessary for the
given problem domain. I guess Lisp/Scheme would be even more suited
for this task but then again there's a Web framework (TurboGears), an
ORM (SqlAlchemy) an RPC middleware (Pyro) and a dozen more batteries,
both standard and 3rd party. Can't think of anything better than
Python for this project.

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


Re: Installing Python 3000 on Leopard (Mac OS) fails...

2007-11-26 Thread Robin Kåveland Hansen
"=?ISO-8859-1?Q?Andr=E9?=" <[EMAIL PROTECTED]> wrote (Mon, 26 Nov
2007 17:59:21 -0800):

> While I made some progress in trying to install Py3k from source (for
> the first time), it has failed...
> 
> Here are the steps I went through (not necessarily in that order -
> except for those that matter).
> 
> 1. After installing Leopard, install Xcode tools from the dvd - even
> if you had done so with a previous version (they need to be updated -
> trust me :-)
> 
> 2. Download Python 3.0a1
> 
> 3.  Unpack the archive.
> 
> 4. Go to  /usr/local and make a directory "sudo mkdir py3k"   (This is
> probably not needed, but that's what I did).
> 
> 5. From the directory where the Python 3.0a1 was unpacked run
> ./configure --prefix=/usr/local/py3k
> 
> 6. run "make"
> 
> This last step failed with the following error message:
> 
> gcc -fno-strict-aliasing -Wno-long-double -no-cpp-precomp -mno-fused-
> madd -DNDEBUG -g -O3 -Wall -Wstrict-prototypes  -I. -I./Include   -
> DPy_BUILD_CORE  -c ./Modules/posixmodule.c -o Modules/posixmodule.o
> ./Modules/posixmodule.c: In function 'posix_setpgrp':
> ./Modules/posixmodule.c:3769: error: too few arguments to function
> 'setpgrp'
> make: *** [Modules/posixmodule.o] Error 1
> 
> Any suggestions?
> 
> André

The posix-man-page on setpgrp declares the setpgrp prototype as pid_t
setpgrp(void);, which makes this sort of weird I guess.

You could check if it worked to change the relevant function call from
setpgrp() to setpgrp(0, 0)? Just search for posix_setpgrp, and make sure
that the function isn't called with an empty argument list.

Though I believe this is something for the core python developers and not
for me to fix, or even advice in, so if you want to be on the safe side to
ensure no breakage, don't touch it on my advice. 

-- 
regards, 
Robin
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: How can I create customized classes that have similar properties as 'str'?

2007-11-26 Thread Steven D'Aprano
On Sun, 25 Nov 2007 02:42:36 -0800, Licheng Fang wrote:

> I mentioned trigram counting as an illustrative case. In fact, you'll
> often need to define patterns more complex than that, and tens of
> megabytes of text may generate millions of them, and I've observed they
> quickly  ate up the 8G memory of a workstation in a few minutes.
> Manipulating these patterns can be tricky, you can easily waste a lot of
> memory without taking extra care. I just thought if I define my pattern
> class with this 'atom' property, coding efforts could be easier later.

I'm just not getting the same results as you when I try this. I'm finding 
that with no extra effort at all, it just works.

The size of your corpus is not important. Neither is the complexity of 
how you generate the patterns. What's important is the number of patterns
you produce, and "millions" isn't that huge a number, even without 
interning the strings.

Obviously I'm not running your code, but I can build a dict with millions 
of patterns, from hundreds of megabytes of text, on a PC with just 1GB of 
memory and not run into any serious problems.

I've just processed roughly 240MB of random emails, generating n-grams up
to length 5. The emails include binary attachments and HTML etc., so I'm
getting lots of patterns that don't normally exist in natural languages
(e.g. 71 occurrences of 'qqq', and 5 of ''). As I said, my PC has 
only 1GB, and that's being shared with about a dozen other apps (including
such memory hogs as Firefox).

Results? 64939962 patterns found, of which 17031467 are unique. There's 
paging, yes, and my PC runs a little slow when I try to switch from one 
running application to another, but nothing unusable. Opening a dozen 
YouTube videos at once impacts performance worse.

I can't think what you're doing to use up 8GB of RAM for merely 
"millions" of strings, even if you are keeping two, three, ten redundant 
copies. Assuming an average length of twenty bytes per pattern (you said 
trigrams, but I'd rather over-estimate than under), and even assuming 
that only half the 8GB are available to Python, you should be able to 
store something of the order of one hundred million patterns easily:

4 bytes for a pointer plus 20 bytes for the string = 24 bytes

4*1024**3 / 24 = 178,956,970

(This is a ballpark figure. Real Python strings will have additional 
overhead.)

If you're running into problems with merely millions of patterns, then 
you're doing worse by probably two orders of magnitude.

I don't think that the problem lies where you think it does. If you have 
a dict with millions of keys, it doesn't matter how many times each 
pattern exists in the corpus because the key only exists *once* in the 
dict. Duplicate the dict, or generate it from scratch even, and at worse 
you double the memory used by the keys. And probably not even that.

The only thing I can think of that might explain why you're using so much
memory is if you are generating *all* the patterns up front, say in a 
list, before adding them to the dict:

# Generate one massive list of patterns containing many duplicates
patterns = make_patterns(text)
# returns a massive list like ['fre', 'req', 'equ', 'que' ...]
d = {}
for pattern in patterns:
d[pattern] = d.get(pattern, 0) + 1


Notice that the real killer in the above algorithm is that you need 
enough storage, not just for the unique patterns, but for EVERY separate 
occurrence of each pattern. Nothing to do with how dicts operate, and 
everything to do with the algorithm you (hypothetically) are using.

If that's what you're doing, then no wonder you're running out of memory. 
With 200MB of text, you have 209715198 trigrams in your list. The 
pointers alone will take almost a gigabyte, assuming 32-bit pointers.

If this is your approach, interning the strings won't save you. You 
almost certainly should change to a lazy approach, and use a generator to 
make each pattern as needed, then thrown away:

def make_patterns(s, n=3):
"""Yield n-grams."""
if len(s) <= n:
yield s
else:
for i in range(len(s)-n+1):
yield s[i:i+n]

d = {}
fp = open('corpus', 'r')
for line in fp:
for word in line.split():
for pattern in make_patterns(word.strip()):
d[pattern] = d.get(pattern, 0) + 1



Obviously I haven't seen your code and don't actually know what you are 
doing. If my 1GB machine can deal with a dict of 17 million unique keys 
from a corpus of 240MB with no special memory management, your 8GB 
machine should too.



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


Re: Installing Python 3000 on Leopard (Mac OS) fails...

2007-11-26 Thread André
On Nov 26, 9:59 pm, "André" <[EMAIL PROTECTED]> wrote:
> While I made some progress in trying to install Py3k from source (for
> the first time), it has failed...
>
> Here are the steps I went through (not necessarily in that order -
> except for those that matter).
>
> 1. After installing Leopard, install Xcode tools from the dvd - even
> if you had done so with a previous version (they need to be updated -
> trust me :-)
>
> 2. Download Python 3.0a1
>
> 3.  Unpack the archive.
>
> 4. Go to  /usr/local and make a directory "sudo mkdir py3k"   (This is
> probably not needed, but that's what I did).
>
> 5. From the directory where the Python 3.0a1 was unpacked run
> ./configure --prefix=/usr/local/py3k
>
> 6. run "make"
>
> This last step failed with the following error message:
>
> gcc -fno-strict-aliasing -Wno-long-double -no-cpp-precomp -mno-fused-
> madd -DNDEBUG -g -O3 -Wall -Wstrict-prototypes  -I. -I./Include   -
> DPy_BUILD_CORE  -c ./Modules/posixmodule.c -o Modules/posixmodule.o
> ./Modules/posixmodule.c: In function 'posix_setpgrp':
> ./Modules/posixmodule.c:3769: error: too few arguments to function
> 'setpgrp'
> make: *** [Modules/posixmodule.o] Error 1
>
> Any suggestions?
>
> André

I encountered the same error after downloading 'darwinports' (http://
darwinports.com/), installing it and
doing the following:

sudo ./port install python30

This is getting to be frustrating :-(

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


Re: fork/exec with input redirection

2007-11-26 Thread hdante
On Nov 27, 12:09 am, hdante <[EMAIL PROTECTED]> wrote:
> On Nov 26, 7:58 pm, "Dan Upton" <[EMAIL PROTECTED]> 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?
>
> > Thanks,
> > -dan
>
>  IIRC,
>
>  if os.fork() == 0:
>new_stdin = os.open('13x13.tst')
>os.dup2(new_stdin, sys.stdin.fileno())
>os.close(new_stdin)
>os.execv("./gobmk_base.linux_x86", ["./gobmk_base.linux_x886", "--
> quiet", "--mode", "gtp"])

 Maybe a sys.stdin.flush() just to be sure ?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: fork/exec with input redirection

2007-11-26 Thread hdante
On Nov 26, 7:58 pm, "Dan Upton" <[EMAIL PROTECTED]> 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?
>
> Thanks,
> -dan

 IIRC,

 if os.fork() == 0:
   new_stdin = os.open('13x13.tst')
   os.dup2(new_stdin, sys.stdin.fileno())
   os.close(new_stdin)
   os.execv("./gobmk_base.linux_x86", ["./gobmk_base.linux_x886", "--
quiet", "--mode", "gtp"])
-- 
http://mail.python.org/mailman/listinfo/python-list


Installing Python 3000 on Leopard (Mac OS) fails...

2007-11-26 Thread André
While I made some progress in trying to install Py3k from source (for
the first time), it has failed...

Here are the steps I went through (not necessarily in that order -
except for those that matter).

1. After installing Leopard, install Xcode tools from the dvd - even
if you had done so with a previous version (they need to be updated -
trust me :-)

2. Download Python 3.0a1

3.  Unpack the archive.

4. Go to  /usr/local and make a directory "sudo mkdir py3k"   (This is
probably not needed, but that's what I did).

5. From the directory where the Python 3.0a1 was unpacked run
./configure --prefix=/usr/local/py3k

6. run "make"

This last step failed with the following error message:

gcc -fno-strict-aliasing -Wno-long-double -no-cpp-precomp -mno-fused-
madd -DNDEBUG -g -O3 -Wall -Wstrict-prototypes  -I. -I./Include   -
DPy_BUILD_CORE  -c ./Modules/posixmodule.c -o Modules/posixmodule.o
./Modules/posixmodule.c: In function 'posix_setpgrp':
./Modules/posixmodule.c:3769: error: too few arguments to function
'setpgrp'
make: *** [Modules/posixmodule.o] Error 1

Any suggestions?

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


Re: Installing Python 3000

2007-11-26 Thread André
[huge snip]
> 
> This is on a Macbook with Leopard installed.
>
> I tried compiling a simple c program (hello world), something that I
> have not done in *years* and it failed.  It appears as though gcc has
> a problem  :-(
>
> I can create an object file  (via gcc -c hello.c) but not an
> executable...
>

Never mind ... after searching on the Apple forums, I found out that I
needed to reinstall some developers tools from the Leopard dvd.   I'll
post the result (success/failure) later...


> André


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


Re: Installing Python 3000

2007-11-26 Thread André
On Nov 26, 6:18 pm, "Martin v. Löwis" <[EMAIL PROTECTED]> wrote:
> > 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.
>

I tried this but, unfortunately, the "configure" command fails.
Here's what appears to be the relevant info from config.log:
===
configure: failed program was:
| /* confdefs.h.  */
| #define _GNU_SOURCE 1
| #define _NETBSD_SOURCE 1
| #define __BSD_VISIBLE 1
| #define _BSD_SOURCE 1
| #define _BSD_TYPES 1
| /* end confdefs.h.  */
|
| int
| main ()
| {
|
|   ;
|   return 0;
| }
configure:2647: error: C compiler cannot create executables
See `config.log' for more details.

This is on a Macbook with Leopard installed.

I tried compiling a simple c program (hello world), something that I
have not done in *years* and it failed.  It appears as though gcc has
a problem  :-(

I can create an object file  (via gcc -c hello.c) but not an
executable...


andre-roberges-computer:Downloads andre$ gcc -o hello hello.c
/usr/bin/ld: /usr/lib/gcc/i686-apple-darwin8/4.0.1/../../../
libSystem.dylib unknown flags (type) of section 6
(__TEXT,__dof_plockstat) in load command 0
collect2: ld returned 1 exit status
==


Any help would be appreciated!

André


> HTH,
> Martin

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


Re: Rss Feed Creator

2007-11-26 Thread James Matthews
Is there any where you do not have us tidy?

On Nov 27, 2007 2:03 AM, Shane Geiger <[EMAIL PROTECTED]> wrote:

> I think this is what you need to make the output readable:
>
> tidy -asxml output.xml
>
>
>
>
>
> James Matthews wrote:
> > Thank You Shane,
> >
> > However that is using PyRss2Gen which doesn't put newlines in the XML.
> > So it's a little out of the picture!
> > On Nov 27, 2007 1:57 AM, Shane Geiger < [EMAIL PROTECTED]
> > > wrote:
> >
> > http://www.bigbold.com/snippets/tag/beautifulsoup
> >
> >
> >
> > James Matthews wrote:
> > > Hi,
> > >
> > > I am looking for a library that will create Rss/Atom feeds in
> > python.
> > > It needs to format the XML in a readable format! Does anyone
> > have any
> > > suggestions?
> > >
> > > Thanks James
> > >
> > >
> > > --
> > > http://search.goldwatches.com/?Search=Movado+Watches
> > > http://www.goldwatches.com/coupons
> > > http://www.jewelerslounge.com
> >
> >
> > --
> > 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://search.goldwatches.com/?Search=Movado+Watches
> > http://www.goldwatches.com/coupons
> > http://www.jewelerslounge.com
>
>
> --
> 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://search.goldwatches.com/?Search=Movado+Watches
http://www.jewelerslounge.com
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Rss Feed Creator

2007-11-26 Thread Shane Geiger
I think this is what you need to make the output readable:

tidy -asxml output.xml





James Matthews wrote:
> Thank You Shane,
>
> However that is using PyRss2Gen which doesn't put newlines in the XML.
> So it's a little out of the picture!
> On Nov 27, 2007 1:57 AM, Shane Geiger < [EMAIL PROTECTED]
> > wrote:
>
> http://www.bigbold.com/snippets/tag/beautifulsoup
>
>
>
> James Matthews wrote:
> > Hi,
> >
> > I am looking for a library that will create Rss/Atom feeds in
> python.
> > It needs to format the XML in a readable format! Does anyone
> have any
> > suggestions?
> >
> > Thanks James
> >
> >
> > --
> > http://search.goldwatches.com/?Search=Movado+Watches
> > http://www.goldwatches.com/coupons
> > http://www.jewelerslounge.com
>
>
> --
> 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://search.goldwatches.com/?Search=Movado+Watches
> http://www.goldwatches.com/coupons
> http://www.jewelerslounge.com 


-- 
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: Rss Feed Creator

2007-11-26 Thread James Matthews
Thank You Shane,

However that is using PyRss2Gen which doesn't put newlines in the XML. So
it's a little out of the picture!
On Nov 27, 2007 1:57 AM, Shane Geiger <[EMAIL PROTECTED]> wrote:

> http://www.bigbold.com/snippets/tag/beautifulsoup
>
>
>
> James Matthews wrote:
> > Hi,
> >
> > I am looking for a library that will create Rss/Atom feeds in python.
> > It needs to format the XML in a readable format! Does anyone have any
> > suggestions?
> >
> > Thanks James
> >
> >
> > --
> > http://search.goldwatches.com/?Search=Movado+Watches
> > http://www.goldwatches.com/coupons
> > http://www.jewelerslounge.com
>
>
> --
> 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://search.goldwatches.com/?Search=Movado+Watches
http://www.goldwatches.com/coupons
http://www.jewelerslounge.com
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Rss Feed Creator

2007-11-26 Thread Shane Geiger
http://www.bigbold.com/snippets/tag/beautifulsoup



James Matthews wrote:
> Hi,
>
> I am looking for a library that will create Rss/Atom feeds in python.
> It needs to format the XML in a readable format! Does anyone have any
> suggestions?
>
> Thanks James
>
>
> -- 
> http://search.goldwatches.com/?Search=Movado+Watches
> http://www.goldwatches.com/coupons
> http://www.jewelerslounge.com 


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


Rss Feed Creator

2007-11-26 Thread James Matthews
Hi,

I am looking for a library that will create Rss/Atom feeds in python. It
needs to format the XML in a readable format! Does anyone have any
suggestions?

Thanks James


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

Re: Add speller to Python application

2007-11-26 Thread helzer
Hi Jarek and Shane,

This is just what I need.

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


trouble selling twisted

2007-11-26 Thread sndive
i have a lot of trouble selling twisted a a client lib for network
access
(on embedded platform)
the group i'm a member of wants to write some
unmaintainable threaded blocking junk in c--.
does anyone can give me an idea how many kilobytes extra would it take
to have a pyqt linked in and a running qtreactor?
(qtreactor natirally depends on the qt bindings)

is there an exaample of going thru a passworded proxy
using twisted client classes?
i have trouble understanding how to adapt the proxy example on page 58
in the twisted book to my needs.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: better way to write this function

2007-11-26 Thread Ricardo Aráoz
Peter Otten wrote:
> 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]]
> []
> []
> []
> []


This won't work(e.g. you don't define "start", you change the value of n
through the loop). I guess you meant :

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





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


Re: Should proxy objects lie about their class name?

2007-11-26 Thread Carl Banks
On Nov 20, 3:50 pm, [EMAIL PROTECTED] (John J. Lee) wrote:
> 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?
>
> One very real advantage that I can see is avoiding breaking existing
> doctests.
>
> Thanks in advance for your views


Python 3.0 has a proposal, accepted I believe, to allow classes to
control the behavior of issubclass and ininstance, so there appears to
be tacit support from the language for mimicking the proxied classes
in such ways.

I guess for me it would be a judgment call on based how tight I wanted
the proxy class to be--is it being the class, or is it just standing
in?


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


Re: Best ways of managing text encodings in source/regexes?

2007-11-26 Thread tinkerbarbet
On Nov 27, 12:27 am, "Martin v. Löwis" <[EMAIL PROTECTED]> wrote:
> > * 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 = u"blah", 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.)
>
> Depends on what you want to achieve. If you don't prefix your strings
> with u, they will stay byte string objects, and won't become Unicode
> strings. That should be fine for strings that are pure ASCII; for
> ISO-8859-1 strings, I recommend it is safer to only use Unicode
> objects to represent such strings.
>
> In Py3k, that will change - string literals will automatically be
> Unicode objects.
>
> > * 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)?
>
> Yes, it will. The encoding declaration is per-module.
>
> > * 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""?
>
> It will work fine if the regular expression restricts itself to ASCII,
> and doesn't rely on any of the locale-specific character classes (such
> as \w). If it's beyond ASCII, or does use such escapes, you better make
> it a Unicode expression.
>
> I'm not actually sure what precisely the semantics is when you match
> an expression compiled from a byte string against a Unicode string,
> or vice versa. I believe it operates on the internal representation,
> so \xf6 in a byte string expression matches with \u00f6 in a Unicode
> string; it won't try to convert one into the other.
>
> Regards,
> Martin

Thanks Martin, that's a very helpful response to what I was concerned
might be an overly long query.

Yes, I'd read that in Py3k the distinction between byte strings and
Unicode strings would disappear -- I look forward to that...

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


Re: Best ways of managing text encodings in source/regexes?

2007-11-26 Thread Martin v. Löwis
> * 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 = u"blah", 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.)

Depends on what you want to achieve. If you don't prefix your strings
with u, they will stay byte string objects, and won't become Unicode
strings. That should be fine for strings that are pure ASCII; for
ISO-8859-1 strings, I recommend it is safer to only use Unicode
objects to represent such strings.

In Py3k, that will change - string literals will automatically be
Unicode objects.

> * 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)?

Yes, it will. The encoding declaration is per-module.

> * 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""?

It will work fine if the regular expression restricts itself to ASCII,
and doesn't rely on any of the locale-specific character classes (such
as \w). If it's beyond ASCII, or does use such escapes, you better make
it a Unicode expression.

I'm not actually sure what precisely the semantics is when you match
an expression compiled from a byte string against a Unicode string,
or vice versa. I believe it operates on the internal representation,
so \xf6 in a byte string expression matches with \u00f6 in a Unicode
string; it won't try to convert one into the other.

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


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

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

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

J^n
-- 
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: 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


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


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


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 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: Need to call functions/class_methods etc using string ref :How

2007-11-26 Thread Bruno Desthuilliers
Donn Ingle a écrit :
>>target = 
>>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
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 
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: 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 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: Need to call functions/class_methods etc using string ref :How

2007-11-26 Thread Donn Ingle
> target = 
> 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: 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: 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


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

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 = u"blah", 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: 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


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
>
> 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: 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: 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, ))

Someone else ? Or are we done with this DeadHorse ?
-- 
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
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: 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 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: 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: 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__
> 

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

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




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


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


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


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


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/ in ()
>>
>> 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, 10:51 pm, Paul Rubin  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: 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: 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__

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


  1   2   >