RE: Putting asterisks around text

2009-02-11 Thread Barak, Ron
[http://www.emofaces.com/en/emoticons/t/thumbs-up-emoticon.gif]

-Original Message-
From: D'Arcy J.M. Cain [mailto:da...@druid.net]
Sent: Monday, February 09, 2009 20:21
To: todp...@hotmail.com
Cc: python-list@python.org
Subject: Re: Putting asterisks around text

On Mon, 9 Feb 2009 10:09:26 -0800
"todp...@hotmail.com"  wrote:
> I'm trying to write a program that puts asterisks around the input text using 
> while loop.
> I can do this without using while loop, but how can you do that using
> while loop?Example:Enter a string: Hello world***Hello
> world***

while understand_problem is False:
study("textbook")

complete("homework")

if want_help is True:
study("http://www.catb.org/~esr/faqs/smart-questions.html";)

--
D'Arcy J.M. Cain  |  Democracy is three wolves
http://www.druid.net/darcy/|  and a sheep voting on
+1 416 425 1212 (DoD#0082)(eNTP)   |  what's for dinner.

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


Re: getopt

2009-02-11 Thread John Machin
On Feb 11, 5:46 pm, Matthew Sacks  wrote:
> I didn't realize that the no-value arguments, -b, -h, etc are required?

required sense 1: the 2nd arg of the function is required; if there
are to be no short options, the 2nd arg should be an empty string.

required sense 2: you are required to specify *all* short options that
you will accept, whether they are no-value or value options; otherwise
you would have to do your own checking for unacceptable options

> This seems to make things a bit more difficult considering unless I
> use the GNU style getopt all arguments are required to be passed?

What does "all arguments are required to be passed" mean? The user is
not required to supply an arg corresponding to any option. Options are
optional!

GNU? Change getopt.getopt to getopt.gnu_getopt and you still get an
exception like "GetoptError: option -b not recognized" if -b is not
defined in the 2nd arg of [gnu_]getopt. AFAICT the GNU difference is
only the documented different treatment of an arg string like "-a1 -b
bvalue stray -c -d" ... non-Gnu treats -c and -d the same as stray.

> I will have a look at what you have posted here and report my results.

Just bear in mind that it was written under the assumption that you
weren't plannning to use short options at all; your examples left lack
for want.

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


Re: Escaping my own chroot...

2009-02-11 Thread Christian Heimes
Dennis Lee Bieber schrieb:
>   That's the whole purpose of chroot()... As far as the process is
> concerned, the chroot() path is now the top of the file system, so there
> is no where above it you can get to...

Yes, you can get with some hacks.

> chroot() is meant for cases where one may be running a server or such
> that should not permit any outside hacks from reaching above its level.
> Typically one creates a minimal environment of just those commands and
> programs needed by users of the server -- you remove anything that
> offers privileged ability.
> 
> chdir() would be used to change the current directory of the process, so
> any spawned commands would operate in the new directory by default

chroot() must not be understood as a security mechanism like BSD's jail.
   A process can still access resources outside the chroot. Unless the
process drops it's root privileges with setuid() ASAP the process can
escape the chroot'ed environment, too.

chroot() can help with increasing security but it's not bullet proof. By
the way it's a bad idea to mount proc and sys inside a chroot ...

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


Re: Avoiding argument checking in recursive calls

2009-02-11 Thread Aaron Brady
On Feb 10, 7:58 pm, Steven D'Aprano
 wrote:
> I sometimes write recursive functions like this simple factorial:
>
> def fact(n):
>     if n < 0: raise ValueError
>     if n = 0: return 1
>     return fact(n-1)*n
>
> At the risk of premature optimization, I wonder if there is an idiom for
> avoiding the unnecessary test for n <= 0 in the subsequent recursive
> calls? For the sake of the argument, let's pretend the test is expensive
> and I have a good reason for wanting to avoid it on subsequent calls :)
>
> I've done this:
>
> def _fact(n):
>     if n = 0: return 1
>     return _fact(n-1)*n
>
> def fact(n):
>     if n < 0: raise ValueError
>     return _fact(n)
>
> but that's ugly. What else can I do?
>
> --
> Steven

Build a list of function calls, and just replace the base case with a
terminating call.

>>> def f( n ):
... def rec( i ):
... return i* funcs[ i- 1 ]( i- 1 )
... def base( i ):
... return 1
... funcs= [ rec ]* n
... funcs[ 0 ]= base
... return rec( n )
...
>>> f( 5 )
120
>>> f( 6 )
720
>>> f( 1 )
1
--
http://mail.python.org/mailman/listinfo/python-list


Re: python3 tutorial for newbie

2009-02-11 Thread Ken

"Gabriel Genellina"  wrote in message 
news:mailman.9312.1234332608.3487.python-l...@python.org...
> En Tue, 10 Feb 2009 16:22:36 -0200, Gary Wood  
> escribió:
>
>> Can someone recommend a good tutorial for Python 3, ideally that has 
>> tasks or assignments at the end of each chapter.
>
> I don't know of any specifically targetted to Python 3, except the 
> official one at http://www.python.org/doc/3.0/
>
> For the most part, any Python tutorial should be fine. Perhaps the only 
> visible change (at the tutorial level) is that "print" became a function:
>
> # 2.x syntax:
> print "Hello", "world!"
>
> # 3.x syntax:
> print("Hello", "world!")
>
> That said, Python 3.0 is so recent that isn't widely used yet, and many 
> third party libraries aren't available for 3.0 at this moment. This 
> certainly will change in the future, but in the meantime, perhaps you 
> should stick to Python 2.6 for a while.
>
> -- 
> Gabriel Genellina

Several links here:

http://wiki.python.org/moin/Python3.0Tutorials
> 


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


Re: import wx works interactive but not from script

2009-02-11 Thread jefm
ok, sorry for the long wait.
I tried this on both my work (XP) and home PC (Vista64) and they are
both consistent.

I had both Python2.6 and Python 3.0 installed.
wxPython didn't like that.
As soon as I uninstalled Python3.0, my wxPython started running again.
Must be some kind of registry thing.

Thanks for the suggestion.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Avoiding argument checking in recursive calls

2009-02-11 Thread Terry Reedy



Steven D'Aprano  writes:

def fact(n):
if n < 0: raise ValueError
if n = 0: return 1
return fact(n-1)*n 

At the risk of premature optimization, I wonder if there is an idiom for 
avoiding the unnecessary test for n <= 0 in the subsequent recursive 
calls?


Reverse the test order

def fact(n):
if n > 0: return fact(n-1)*n
if n == 0: return 1
raise ValueError

You must test recursive versus terminal case every call in any case.
Nearly always, the first test passes and second is not done.
You only test n==0 once, either to terminate or raise exception.
This works for any integral value and catches non-integral values. 
(There is some delay for that, but only bad calls are penalized.)


Terry Jan Reedy

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


Re: Avoiding argument checking in recursive calls

2009-02-11 Thread Jervis Whitley
> You've merely replaced the 'test n<0' with 'not check' at the expense
> of an additional parameter that has to be passed each time (and the
> additional test 'n<0' for the first iteration).
> --
> http://mail.python.org/mailman/listinfo/python-list
>
I think you have missed the point. The OP stated that n<0 could stand
for an expensive
operation, this replaces an expensive check every time with a cheaper
one every time.

I like the idea of the interface that was in the original post.

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


Re: Avoiding argument checking in recursive calls

2009-02-11 Thread Jervis Whitley
>
> You've merely replaced the 'test n<0' with 'not check' at the expense
> of an additional parameter that has to be passed each time (and the
> additional test 'n<0' for the first iteration).
> --
> http://mail.python.org/mailman/listinfo/python-list
>

I think you have missed the point. The OP stated that n<0 could stand
for an expensive
operation, this replaces an expensive check every time with a cheaper
one every time.

I like the idea of the interface that was in the original post.

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


Re: zlib interface semi-broken

2009-02-11 Thread Scott David Daniels

Travis wrote:

On Tue, Feb 10, 2009 at 01:36:21PM -0800, Scott David Daniels wrote:

 I personally would like it and bz2 to get closer to each other...


Well, I like this idea; perhaps this is a good time to discuss the
equivalent of some "abstract base classes", or "interfaces", for
compression.

As I see it, the fundamental abstractions are the stream-oriented
de/compression routines.  Given those, one should easily be able to
implement one-shot de/compression of strings.  In fact, that is the
way that zlib is implemented; the base functions are the
stream-oriented ones and there is a layer on top of convenience
functions that do one-shot compression and decompression.


There are a couple of things here to think about.  I've wanted to
do some low-level (C-coded) search w/o bothering to create strings
until a match.  I've no idea how to push this down in, but I may be
looking for a nice low-level spot to fit.  Characteristics for that
could be read-only access to small expansion parts w/o copying them
out.  Also, in case of a match, a (relatively quick) way to mark points
as we proceed and a (possibly slower) way to resrore from one or
more marked points.

Also, another programmer wants to parallelize _large_ bzip file
expansion by expanding independent blocks in separate threads (we
know how to find safe start points).  To get such code to work, we
need to find big chunks of computation, and (at least optionally)
surround them with GIL release points.


So what I suggest is a common framework of three APIs; a sequential
compression/decompression API for streams, a layer (potentially
generic) on top of those for strings/buffers, and a third API for
file-like access.  Presumably the file-like access can be implemented
on top of the sequential API as well.

If we have to be able to start from arbitrary points in bzip files, they
have one nasty characteristic: they are bit-serial, and we'll need to
start them at arbitrary _bit_ points (not simply byte boundaries).

One structure I have used for searching is a result iterator fed by
a source iterator, so rather than a read w/ inconvenient boundaries
the input side of the thing calls the 'next' method of the provided
source.


... I would rather see a pythonic interface to the libraries than a

> simple-as-can-be wrapper around the C functions
I'm on board with you here.


My further suggestion is that we start with the sequential
de/compression, since it seems like a fundamental primitive.
De/compressing strings will be trivial, and the file-like interface is
already described by Python.

Well, to be explicit, are we talking about Decompresion and Compression
simultaneously or do we want to start with one of them first?


2) The de/compression object has routines for reading de/compressed
data and states such as end-of-stream or resynchronization points as
exceptions, much like the file class can throw EOFError.  My problem
with this is that client code has to be cognizant of the possible
exceptions that might be thrown, and so one cannot easily add new
exceptions should the need arise.  For example, if we add an exception
to indicate a possible resynchronization point, client code may not
be capable of handling it as a non-fatal exception.


Seems like we may want to say things like, "synchronization points are
too be silently ignored."

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


best way to serve wsgi with multiple processes

2009-02-11 Thread Robin
Hi,

I am building some computational web services using soaplib. This
creates a WSGI application.

However, since some of these services are computationally intensive,
and may be long running, I was looking for a way to use multiple
processes. I thought about using multiprocessing.Process manually in
the service, but I was a bit worried about how that might interact
with a threaded server (I was hoping the thread serving that request
could just wait until the child is finished). Also it would be good to
keep the services as simple as possible so it's easier for people to
write them.

I have at the moment the following WSGI structure:
TransLogger(URLMap(URLParser(soaplib objects)))
although presumably, due to the beauty of WSGI, this shouldn't matter.

As I've found with all web-related Python stuff, I'm overwhelmed by
the choice and number of alternatives. I've so far been using cherrypy
and ajp-wsgi for my testing, but am aware of Spawning, twisted etc.
What would be the simplest [quickest to setup and fewest details of
the server required - ideally with a simple example] and most reliable
[this will eventually be 'in production' as part of a large scientific
project] way to host this sort of WSGI with a process-per-request
style?

Thanks!

Robin

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


Re: Avoiding argument checking in recursive calls

2009-02-11 Thread andrew cooke
Terry Reedy wrote:
> Reverse the test order
>
> def fact(n):
>  if n > 0: return fact(n-1)*n
>  if n == 0: return 1
>  raise ValueError

sweet!  but is this generally possible?  ie: did you think this up for
this question or is it an idiom that you find yourself using often?

andrew

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


Re: ANN: Python 2.6 Quick Reference available

2009-02-11 Thread Thorsten Kampe
* Richard Gruet (Tue, 10 Feb 2009 20:38:24 +0100)
> The Python 2.6 Quick Reference is available in HTML and PDF formats at
> http://rgruet.free.fr/#QuickRef.

THANK YOU!

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


urllib2.Request:: http Request sending successfully, but Response contains in valid data.

2009-02-11 Thread nRk
Hi

I am trying to send Data to a website through "http" using
"urllib.request" library using the bellow code.
Response status code contains. 200 (OK) but Response contains
nothing...

With same data When I test using C# it working fine.. Response
having.. some data in xml format.
But I am using below python code i am getting response only "".

Is there any in my code..

 req  = urllib2.Request(url) // url is valid url
 req.add_header('Authorization','AuthSub token="x"')
 req.add_header('Content-Type','application/atom+xml')
 req.data=data  // data is having valid xml data
 r = urllib2.urlopen(req)

print(r.code) // output 200
print(r.msg) // output OK
print(r.read()) //
--
http://mail.python.org/mailman/listinfo/python-list


Re: Distributing simple tasks

2009-02-11 Thread Piet van Oostrum
Noam Aigerman wrote:
> Hi,
> 
> Suppose I have an array of functions which I execute in threads (each
> thread get a slice of the array, iterates over it and executes each
> function in it’s slice one after the other). Now I want to distribute
> these tasks between two machines, i.e give each machine half of the
> slices and let it run them in threads as described above. Is there an
> easy way, or an article on this matter you can point me to?

Have a look at MapReduce (google for MapReduce Python).
-- 
Piet van Oostrum 
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: p...@vanoostrum.org
--
http://mail.python.org/mailman/listinfo/python-list


Re: zlib interface semi-broken

2009-02-11 Thread Paul Rubin
Scott David Daniels  writes:
> Seems like we may want to say things like, "synchronization points are
> too be silently ignored."

That would completely break some useful possible applications, so should
be avoided.
--
http://mail.python.org/mailman/listinfo/python-list


Re: generator object or 'send' method?

2009-02-11 Thread greg

Aaron Brady wrote:


It would receive the 'send' from a different point in control
flow than its usual 'next'.  Should it repeat a value if it receives a
'send'?


No. This requirement clearly indicates that send() is
the wrong tool for the job.

I would use a class with a generator as a method, e.g.

  class Multiples:

m = 1

def set_multiplier(self, m):
  self.m = m

def generate(self, limit):
  for i in xrange(limit):
yield i * self.m

  g = Multiples()
  for x in g.generate(10):
print x
if x == 3:
  g.set_multiplier(42)

produces

0
1
2
3
168
210
252
294
336
378

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


Unexpected string behaviour: txt = 'this' ' works'

2009-02-11 Thread c d saunter
I did a double take when debugging an error the other day.  My
problem was missing out a comma when building a list of strings.

Much to my surprise the offending code still executed to cause
problems later on:

>>> txt = 'this', 'works'
>>> print txt
('this', 'works')
# As expected
>>> txt = 'this' 'works'
>>> print txt
thisworks
# Eh?

I have never seen this behaviour before, but it works in Python 2.2.1
and 2.5.4 so I guess it's meant to be there.  I assume it is a feature
of the compiler.

Any thoughts?
Regards
Chris



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


ANN: SuPy for Python 2.5 on Windows

2009-02-11 Thread Greg Ewing

SuPy 1.0 - Windows
--

A Windows build for Python 2.5 is now available.

   http://www.cosc.canterbury.ac.nz/greg.ewing/SuPy/

What is SuPy?
-

SuPy is a plugin for the Sketchup 3D modelling application
that lets you script it in Python.

This is a first version and is highly experimental. Let me
know if it works for you and whether you have any problems.

--
Greg Ewing
greg.ew...@canterbury.ac.nz
--
http://mail.python.org/mailman/listinfo/python-list


Re: Unexpected string behaviour: txt = 'this' ' works'

2009-02-11 Thread Quentin Gallet-Gilles
*Literal* string concatenation has always been a part of Python :
http://docs.python.org/reference/lexical_analysis.html#string-literal-concatenation


On Wed, Feb 11, 2009 at 12:06 PM, c d saunter <
christopher.saun...@durham.ac.uk> wrote:

> I did a double take when debugging an error the other day.  My
> problem was missing out a comma when building a list of strings.
>
> Much to my surprise the offending code still executed to cause
> problems later on:
>
> >>> txt = 'this', 'works'
> >>> print txt
> ('this', 'works')
> # As expected
> >>> txt = 'this' 'works'
> >>> print txt
> thisworks
> # Eh?
>
> I have never seen this behaviour before, but it works in Python 2.2.1
> and 2.5.4 so I guess it's meant to be there.  I assume it is a feature
> of the compiler.
>
> Any thoughts?
> Regards
> Chris
>
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: python is great

2009-02-11 Thread greg

python is great.


No.

Python is VERY GREAT !!!


All right now, everyone...

  Every Python's sacred, every Python's great,
  If any Python's wasted, Guido gets irate!

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


Re: Unexpected string behaviour: txt = 'this' ' works'

2009-02-11 Thread Bruno Desthuilliers

c d saunter a écrit :

I did a double take when debugging an error the other day.  My
problem was missing out a comma when building a list of strings.

Much to my surprise the offending code still executed to cause
problems later on:


txt = 'this', 'works'
print txt

('this', 'works')
# As expected

txt = 'this' 'works'
print txt

thisworks
# Eh?

I have never seen this behaviour before, but it works in Python 2.2.1
and 2.5.4 so I guess it's meant to be there.  I assume it is a feature
of the compiler.

Any thoughts?


http://docs.python.org/reference/lexical_analysis.html#string-literal-concatenation
--
http://mail.python.org/mailman/listinfo/python-list


Re: Unexpected string behaviour: txt = 'this' ' works'

2009-02-11 Thread c d saunter
Bruno Desthuilliers (bruno.42.desthuilli...@websiteburo.invalid) wrote:
: c d saunter a écrit :
: > I did a double take when debugging an error the other day.  My
: > problem was missing out a comma when building a list of strings.
: > 
: > Much to my surprise the offending code still executed to cause
: > problems later on:
: > 
:  txt = 'this', 'works'
:  print txt
: > ('this', 'works')
: > # As expected
:  txt = 'this' 'works'
:  print txt
: > thisworks
: > # Eh?
: >
: > I have never seen this behaviour before, but it works in Python 2.2.1
: > and 2.5.4 so I guess it's meant to be there.  I assume it is a feature
: > of the compiler.
: > 
: > Any thoughts?

: 
http://docs.python.org/reference/lexical_analysis.html#string-literal-concatenation

Ahh.  Thanks.

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


Re: best way to serve wsgi with multiple processes

2009-02-11 Thread Robin Becker

Robin wrote:

Hi,

I am building some computational web services using soaplib. This
creates a WSGI application.

However, since some of these services are computationally intensive,
and may be long running, I was looking for a way to use multiple
processes. I thought about using multiprocessing.Process manually in
the service, but I was a bit worried about how that might interact
with a threaded server (I was hoping the thread serving that request
could just wait until the child is finished). Also it would be good to
keep the services as simple as possible so it's easier for people to
write them.

I have at the moment the following WSGI structure:
TransLogger(URLMap(URLParser(soaplib objects)))
although presumably, due to the beauty of WSGI, this shouldn't matter.

As I've found with all web-related Python stuff, I'm overwhelmed by
the choice and number of alternatives. I've so far been using cherrypy
and ajp-wsgi for my testing, but am aware of Spawning, twisted etc.
What would be the simplest [quickest to setup and fewest details of
the server required - ideally with a simple example] and most reliable
[this will eventually be 'in production' as part of a large scientific
project] way to host this sort of WSGI with a process-per-request
style?

..


We've used forked fastcgi (flup) with success as that decouples the wsgi process 
(in our case django) from the main server (in our case apache). Our reasons for 
doing that were to allow the backend to use modern pythons without having to 
upgrade the server (which is required if using say mod_python). The wsgi process 
runs as an ordinary user which eases some tasks.


A disadvantage of our scheme is that long running processes may cause problems 
eg timeouts. In practice since there are no guarantees for how long an http 
connection will hold up (because of proxies etc etc) we decided to work around 
this problem. Basically long running jobs go into a task queue on the server and 
the response is used to reconnect to the long running job peridically for status 
querying/results etc etc.

--
Robin Becker

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


Re: Unexpected string behaviour: txt = 'this' ' works'

2009-02-11 Thread bearophileHUGS
christopher.saun...@durham.ac.uk (c d saunter):

>I assume it is a feature of the compiler.<

Yes it's a bug-prone antifeature that's probably a relic from C that
doesn't have a concatenation operator among strings as Python does
(+). So in Python it saves you to use + at the cost of possible bugs.

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


Re: cannot install

2009-02-11 Thread Benjamin Kaplan
2009/2/11 administrator 

> I tried as admin with Python-3.0 in my home directory but no success yet.
> Is there another help?
>
> Macintosh:~ admin$ export
> PATH=/opt/local/bin:/opt/local/sbin:/Developer/usr/bin:$PATH
> Macintosh:~ admin$ echo $PATH
>
> /opt/local/bin:/opt/local/sbin:/Developer/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Users/admin:/usr/local/bin:/usr/X11/bin
> Macintosh:~ admin$ cd ~/Python-3.0
> Macintosh:Python-3.0 admin$ pwd
> /Users/admin/Python-3.0
> Macintosh:Python-3.0 admin$ sudo ./configure --enable-framework
> checking for --with-universal-archs... 32-bit
> checking MACHDEP... darwin
> checking machine type as reported by uname -m... i386
> checking for --without-gcc... no
> checking for gcc... gcc
> checking for C compiler default output file name...
> *configure: error: C compiler cannot create executables*
> See `config.log' for more details.
> Macintosh:Python-3.0 admin$
>



What does config.log say?


>
>
> Regards, Vladimir Zupka
>
> On 10.2.2009, at 14:35, Benjamin Kaplan wrote:
>
>
>
> On Tue, Feb 10, 2009 at 4:07 AM, Vladimír Župka  wrote:
>
>> I tried this:
>> PATH=$PATH:/Developer/usr/bin
>> echo $PATH
>> cd /Python-3.0
>> ./configure --enable-framework
>> make
>> sudo make install
>>
>> and the result is:
>>
>> Macintosh:~ vzupka$ /Users/vzupka/Desktop/Python.sh ; exit;
>>
>> /Library/Frameworks/Python.framework/Versions/Current/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin:/Developer/usr/bin
>> checking for --with-universal-archs... 32-bit
>> checking MACHDEP... darwin
>> checking machine type as reported by uname -m... i386
>> checking for --without-gcc... no
>> checking for gcc... gcc
>> checking for C compiler default output file name...
>> *configure: error: C compiler cannot create executables*
>> *See `config.log' for more details.*
>> make: *** No targets specified and no makefile found.  Stop.
>>
>> WARNING: Improper use of the sudo command could lead to data loss
>> or the deletion of important system files. Please double-check your
>> typing when using sudo. Type "man sudo" for more information.
>>
>> To proceed, enter your password, or type Ctrl-C to abort.
>>
>> Password:
>> logout
>>
>> [Process completed]
>>
>> What is wrong with C compiler? Where do I find the 'config.log'?
>>
>
>
> config.log should be in Python-3.0. I believe that you have a permissions
> problem. ./configure needs to generate the makefiles that tell the compiler
> what to do and then the make command will create the executables. Since
> you're not in your home directory, you (as a standard user) don't have
> permission to write to that directory. Either move Python-3.0 to somewhere
> that you have write permissions or use sudo for the whole script.
>
>
>
> Vladimir Zupka
>>
>> On 9.2.2009, at 16:56, Benjamin Kaplan wrote:
>>
>>
>>
>> On Mon, Feb 9, 2009 at 9:05 AM, Vladimír Župka  wrote:
>>
>>> I have Mac OS X Leopard 10.5.6 and I downloaded and unpacked Python 3.0
>>> into a folder (/Library/Frameworks/Python.framework) and ran commands:
>>>
>>> cd /Library/Frameworks/Python.framework/Python-3.0
>>> python setup.py install
>>>
>>> and got the message reporting a syntax error:
>>>
>>> Macintosh:~ vzupka$ /bin/csh
>>> [Macintosh:~] vzupka% cd /Library/Frameworks/Python.framework/Python-3.0
>>> [Macintosh:Frameworks/Python.framework/Python-3.0] vzupka% python
>>> setup.py install
>>>   File "setup.py", line 232
>>> except (CCompilerError, DistutilsError) as why:
>>>  ^
>>> SyntaxError: invalid syntax
>>> [Macintosh:Frameworks/Python.framework/Python-3.0] vzupka%
>>>
>>>
>>>
>>
>> You can't use setup.py because the python 2.5 on your system (or 2.6 if
>> you installed it) is incompatible with Python 3 modules. You need to compile
>> Python 3 yourself. It will then automatically call setup.py to create all
>> the extension modules.
>>
>> Just unpack the tarball anywhere and use the following commands  Python 3
>> is automatically installed as python3.0, so you don't need to worry about
>> overwriting the default python on the system.
>>
>> ./configure --enable-framework
>> make
>> sudo make install
>>
>> more complete instructions are in the Mac/README file, except substitute
>> "Python 3.0" everywhere it says "MacPython 2.6". You will probably need to
>> install a whole bunch of packages to compile it. configure will tell you
>> about them. MacPorts (www.macports.org) and fink (www.finkproject.org)
>> provide an easy way to get them.
>>
>>
>>> Regards,
>>>  Vladimír Župka
>>> vzu...@volny.cz
>>>
>>>
>>>
>>>
>>>
>>>
>>> --
>>> http://mail.python.org/mailman/listinfo/python-list
>>>
>>>
>>
>>  Vladimír Župka
>> vzu...@volny.cz
>>
>>
>>
>>
>>
>>
>
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: best way to serve wsgi with multiple processes

2009-02-11 Thread Robin
On Feb 11, 12:10 pm, Robin Becker  wrote:
> We've used forked fastcgi (flup) with success as that decouples the wsgi 
> process
> (in our case django) from the main server (in our case apache). Our reasons 
> for
> doing that were to allow the backend to use modern pythons without having to
> upgrade the server (which is required if using say mod_python). The wsgi 
> process
> runs as an ordinary user which eases some tasks.

Yes - I've done something very similar with ajp-wsgi (from the author
of flup; and which incidently performs very well works really nicely)
to go from apache -> wsgi. But the issue I'm asking about here is to
have multiple WSGI processes - ie to allow concurrent execution of
more than one web service at the time (since these are long running
computational soap web services). ajp-wsgi embeds a single python
interpreter so multiple running services would be effected by the GIL
- I imagine flup is similar (a single process on the python side).

So I'm not worried about decoupling from the web server - I'm happy to
use pure python server (which I guess is easier to setup) - but I want
the web server to dispatch requests to different processes running the
wsgi app. I've looked at Spawning, but couldn't get it to work and it
seems a little bit 'beta' for my taste (doesn't exit cleanly, leaves
worker processes running etc.)

Cheers

Robin



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


Re: optparse versus getopt

2009-02-11 Thread Pete Forman
Robert Kern  writes:

>> is there some way i can force the import based on the the absolute
>> path to the module?
>
 > Better would be for you to copy the optparse.py module onto your
 > Jython's import path. I'm not particularly familiar with the details
 > of Jython, so you will need to consult with the Jython documentation
 > unless if a Jython expert can jump in here. Here is one message
 > describing this procedure:
>
 >   http://osdir.com/ml/lang.jython.user/2004-01/msg00086.html

Here are notes from some of my code which can run on Jython.  You
might also like to check out Jython 2.5 which is in beta.

  Jython 2.2 needs optparse.py and textwrap.py.  These can be copied
  from Python 2.3 or Optik 1.4.1 or later.  May also need gettext.py
  and locale.py.

-- 
Pete Forman-./\.-  Disclaimer: This post is originated
WesternGeco  -./\.-   by myself and does not represent
pete.for...@westerngeco.com-./\.-   the opinion of Schlumberger or
http://petef.22web.net   -./\.-   WesternGeco.
--
http://mail.python.org/mailman/listinfo/python-list


Re: getopt index out of range

2009-02-11 Thread Steve Holden
Matthew Sacks wrote:
> Hi List,
> I am getting an index out of range error when trying to parse with getopt.
> Probably something simple. Any suggestions are appreciated
> 
> optlist, args = getopt.getopt(sys.argv[1:], 'h', ['connectPassword=',
> 'adminServerURL=', 'action=', 'targets=', 'appDir='])
> 
> 
> #Assign Opts
> connectPassword = optlist[0][1]
> adminServerURL = optlist[1][1]
> action = optlist[2][1]
> targets = optlist[3][1]
> appDir = optlist[4][1]
> 
> #this statement never gets executed
> print "Args: " + connectPassword + " " + adminServerURL + " " + action
> + " " + targets + " " + appDir
> 
>   File "/home/msacks/untitled4.py", line 23, in ?
> IndexError: index out of range: 0
> 
It might help a little if you made it more obvious which was line 23 ...

The real problem, though, is a misunderstanding of what getopt.getopt()
returns. The (option, value) pairs are only returned for options found
in the command line, so you can't guarantee there'll be four.

Set your values to defaults, then adjust for those for which an option
is found in the list, as in the "typical usage" example in the Fine Manual.

regards
 Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

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


Re: Functional schmunctional...

2009-02-11 Thread Steve Holden
Terry Reedy wrote:
> r0g wrote:
> 
>>
>> def inet2ip(n):
>>   p = (n/16777216)
>>   q = ((n-(p*16777216))/65536)
>>   r = ((n-((p*16777216)+(q*65536)))/256)
>>   s = ((n-((p*16777216)+(q*65536)+(r*256
>>   return str(p)+"."+str(q)+"."+str(r)+"."+str(s)
> 
> Beyond what other wrote:
> To future-proof code, use // instead of / for integer division.
> To get both quotient and remainder, use divmod(num,den)
> For future reading (and generalization) documenting magic constants helps.
> 
> In 3.0:
> 
> def inet2ip(n):
>   p = (n//16777216)
>   q = ((n-(p*16777216))//65536)
>   r = ((n-((p*16777216)+(q*65536)))//256)
>   s = ((n-((p*16777216)+(q*65536)+(r*256
>   return str(p)+"."+str(q)+"."+str(r)+"."+str(s)
> 
> def inet2ip2(n):
> p,n=divmod(n,16777216) # 1<<24
> q,n=divmod(n,65536) # 1<<16
> r,s=divmod(n,256) # 1<<8
> return str(p)+"."+str(q)+"."+str(r)+"."+str(s)
> 
> print(inet2ip(10), inet2ip2(10))
> 

> 59.154.202.0 59.154.202.0
> 
Jeez, doesn't anyone read the fine manual any more? I hope this was just
an academic exercise.

>>> socket.inet_ntoa(struct.pack("!l", 10))
'59.154.202.0'
>>>

Holden's rule: when it looks simple enough to be worth including in the
standard library it may well already *be* in the standard library.

regards
 Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

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


Re: getopt index out of range

2009-02-11 Thread MRAB

Steve Holden wrote:

Matthew Sacks wrote:

Hi List,
I am getting an index out of range error when trying to parse with getopt.
Probably something simple. Any suggestions are appreciated

optlist, args = getopt.getopt(sys.argv[1:], 'h', ['connectPassword=',
'adminServerURL=', 'action=', 'targets=', 'appDir='])


#Assign Opts
connectPassword = optlist[0][1]
adminServerURL = optlist[1][1]
action = optlist[2][1]
targets = optlist[3][1]
appDir = optlist[4][1]

#this statement never gets executed
print "Args: " + connectPassword + " " + adminServerURL + " " + action
+ " " + targets + " " + appDir

  File "/home/msacks/untitled4.py", line 23, in ?
IndexError: index out of range: 0


It might help a little if you made it more obvious which was line 23 ...


It a guess I'd say it was:

connectPassword = optlist[0][1]

because the traceback says the index is 0 and there's only one line with 
a 0 in it!



The real problem, though, is a misunderstanding of what getopt.getopt()
returns. The (option, value) pairs are only returned for options found
in the command line, so you can't guarantee there'll be four.

Set your values to defaults, then adjust for those for which an option
is found in the list, as in the "typical usage" example in the Fine Manual.


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


Re: best way to serve wsgi with multiple processes

2009-02-11 Thread Robin
On Feb 11, 1:28 pm, Robin  wrote:
> On Feb 11, 12:10 pm, Robin Becker  wrote:
>
> > We've used forked fastcgi (flup) with success as that decouples the wsgi 
> > process
> > (in our case django) from the main server (in our case apache). Our reasons 
> > for
> > doing that were to allow the backend to use modern pythons without having to
> > upgrade the server (which is required if using say mod_python). The wsgi 
> > process
> > runs as an ordinary user which eases some tasks.

I'm sorry - I originally missed the worked 'forked' and hence the
whole point of your message I think.

I looked at flup before but had forgotten about the forked version.
Having revisited it I think the forked version does keep a process
pool so each request is processed by a seperate process, which is
exactly what I wanted.

Cheers

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


Pycon 2009 Hotel?

2009-02-11 Thread jay graves
I'm attending Pycon this year and for the first time I have to pay for
myself.  (All training/conference budgets have been zeroed out at my
company.)

I would like to take the cheaper option by staying at the Crowne Plaza
but as I understand it, the part of the conference I'll be attending
will be held at the Hyatt Regency.  I don't mind the walk but I also
don't want to miss out on the open spaces in the evening.

Is anyone else similarly on the fence?  I'd like to save $130 ((153 -
100) * 3) but since I'm not staying for the sprints and alot of my
enjoyment of the conference is the open spaces.


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


Re: best way to serve wsgi with multiple processes

2009-02-11 Thread Diez B. Roggisch
Robin wrote:

> On Feb 11, 1:28 pm, Robin  wrote:
>> On Feb 11, 12:10 pm, Robin Becker  wrote:
>>
>> > We've used forked fastcgi (flup) with success as that decouples the
>> > wsgi process (in our case django) from the main server (in our case
>> > apache). Our reasons for doing that were to allow the backend to use
>> > modern pythons without having to upgrade the server (which is required
>> > if using say mod_python). The wsgi process runs as an ordinary user
>> > which eases some tasks.
> 
> I'm sorry - I originally missed the worked 'forked' and hence the
> whole point of your message I think.
> 
> I looked at flup before but had forgotten about the forked version.
> Having revisited it I think the forked version does keep a process
> pool so each request is processed by a seperate process, which is
> exactly what I wanted.

You can have that with mod_wsgi & daemon mode as well, with presumably less
setup hassle.

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


Re: Pycon 2009 Hotel?

2009-02-11 Thread jay graves
On Feb 11, 9:13 am, jay graves  wrote:
> I'm attending Pycon this year and for the first time I have to pay for
> myself.  (All training/conference budgets have been zeroed out at my
> company.)
>
> I would like to take the cheaper option by staying at the Crowne Plaza
> but as I understand it, the part of the conference I'll be attending
> will be held at the Hyatt Regency.  I don't mind the walk but I also
> don't want to miss out on the open spaces in the evening.
>
> Is anyone else similarly on the fence?  I'd like to save $130 ((153 -
> 100) * 3) but since I'm not staying for the sprints and alot of my
> enjoyment of the conference is the open spaces.

(Sorry. i hit 'Send' too quickly.)

I'm wondering if I'm being 'penny-wise and pound-foolish'?  I'd hate
to spend all that money to get there and then not enjoy it because I
was at the 'other' hotel.

...
Jay Graves


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


Re: Functional schmunctional...

2009-02-11 Thread Michele Simionato
On Feb 10, 9:28 pm, r0g  wrote:
> def ip2inet(a):
>   li = a.split('.')
>   assert len(li) == 4 or len(li) == 6
>   return reduce(add,[int(li[e])*(256**((len(li)-1)-e)) for e in
> xrange(0,len(li))])

Aagh! Notice that functional programming is not about filter, map,
reduce and other unreadable constructs: it is much more about avoiding
mutation.

Your problem has been already solved by using the standard library;
however, if you want to know more about functional programming, I
could as well advertise my own series of "Adventures of a Pythonista
in Schemeland" which is facing exactly that topic right now:

http://www.artima.com/weblogs/viewpost.jsp?thread=248953
--
http://mail.python.org/mailman/listinfo/python-list


Re: Escaping my own chroot...

2009-02-11 Thread Nick Craig-Wood
r0g  wrote:
>  I'm writing a linux remastering script in python where I need to chroot
>  into a folder, run some system commands and then come out and do some
>  tidying up, un-mounting proc & sys etc.
> 
>  I got in there with os.chroot() and I tried using that to get back out
>  but that didn't work so... is my script trapped in there forever now or
>  is there an un-hacky way to escape?

No!

>  If it is an OS restriction rather than my ignorance of python is there a
>  canonical way of dealing with it? Should I maybe fork a process, have it
>  do the chroot and wait for it to terminate before continuing?

That is the only way...

However this is a solved problem if you use schroot (which works very
well in my experience)

  http://packages.debian.org/sid/schroot
  http://www.debian-administration.org/articles/566

There are definitely debian, ubuntu and centos packages for it if you
look!

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


SOAP client

2009-02-11 Thread mk
Hi,

I'm trying to consume a SOAP web service using Python.  So far I have
found two libraries: SOAPpy and ZSI.  Both of them rely on PyXML which
is no longer maintained (and there is no build for 64bit Windows and
the setup.py doesn't seem to know how to build it on Windows).  Is
there a live SOAP library for Python?  I'm sort of surprised that a
common standard like SOAP is not more actively supported in Python.
I'm probably missing something?

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


[no subject]

2009-02-11 Thread João Rabelo

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


Re: best way to serve wsgi with multiple processes

2009-02-11 Thread Robin Becker

Robin wrote:
..


Yes - I've done something very similar with ajp-wsgi (from the author
of flup; and which incidently performs very well works really nicely)
to go from apache -> wsgi. But the issue I'm asking about here is to
have multiple WSGI processes - ie to allow concurrent execution of
more than one web service at the time (since these are long running
computational soap web services). ajp-wsgi embeds a single python
interpreter so multiple running services would be effected by the GIL
- I imagine flup is similar (a single process on the python side).

So I'm not worried about decoupling from the web server - I'm happy to
use pure python server (which I guess is easier to setup) - but I want
the web server to dispatch requests to different processes running the
wsgi app. I've looked at Spawning, but couldn't get it to work and it
seems a little bit 'beta' for my taste (doesn't exit cleanly, leaves
worker processes running etc.)


well the flup server for fast cgi supports forking if the server is declared as 
an external process in apache. Then the top level of the flup process handles 
each request and passes it off to a forked worker. I cannot recall exactly, but 
I believe that apache mod_fastcgi does the right thing when it comes to 
internally declared fastcgi handlers. For apache at least I think the threading 
issues are handled properly.


I think the preforkserver.py code handles all the threading issues for you 
(assuming it's not win32).

--
Robin Becker

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


Re: urllib2.Request:: http Request sending successfully, but Response contains in valid data.

2009-02-11 Thread Tino Wildenhain

Hi,

nRk wrote:

Hi

I am trying to send Data to a website through "http" using
"urllib.request" library using the bellow code.
Response status code contains. 200 (OK) but Response contains
nothing...

With same data When I test using C# it working fine.. Response
having.. some data in xml format.
But I am using below python code i am getting response only "".


This does not mean you are doing it identical to C# here, doesn't it?
Also you might be looking at the defaults in the calls within C#
and some weird expectations on server side.

Also you are requesting XML by sending a payload of XML data,
so you need to make sure you actually use POST and not GET.

I'd start by watching your working application with
strace or wireshark and compare with the data to and fro
from your python application.

Also I believe there should be example code for reading
RSS feeds from python.



Is there any in my code..

 req  = urllib2.Request(url) // url is valid url
 req.add_header('Authorization','AuthSub token="x"')
 req.add_header('Content-Type','application/atom+xml')
 req.data=data  // data is having valid xml data
 r = urllib2.urlopen(req)



print(r.code) // output 200
print(r.msg) // output OK
print(r.read()) //


Regards
Tino




smime.p7s
Description: S/MIME Cryptographic Signature
--
http://mail.python.org/mailman/listinfo/python-list


Re: best way to serve wsgi with multiple processes

2009-02-11 Thread M.-A. Lemburg
On 2009-02-11 16:16, Diez B. Roggisch wrote:
> Robin wrote:
> 
>> On Feb 11, 1:28 pm, Robin  wrote:
>>> On Feb 11, 12:10 pm, Robin Becker  wrote:
>>>
 We've used forked fastcgi (flup) with success as that decouples the
 wsgi process (in our case django) from the main server (in our case
 apache). Our reasons for doing that were to allow the backend to use
 modern pythons without having to upgrade the server (which is required
 if using say mod_python). The wsgi process runs as an ordinary user
 which eases some tasks.
>> I'm sorry - I originally missed the worked 'forked' and hence the
>> whole point of your message I think.
>>
>> I looked at flup before but had forgotten about the forked version.
>> Having revisited it I think the forked version does keep a process
>> pool so each request is processed by a seperate process, which is
>> exactly what I wanted.
> 
> You can have that with mod_wsgi & daemon mode as well, with presumably less
> setup hassle.

Another option that works well on Unix and even Windows is SCGI
which deals with the forking and piping of data for you:

http://www.mems-exchange.org/software/scgi/
http://python.ca/scgi/

Lighttpd even ships with a mod_scgi module built-in.

More on the protocol used by SCGI (basically net-strings):

http://python.ca/scgi/protocol.txt

Unlike FastCGI, it's very easy to setup.

Since SCGI provides standard CGI on the Python side, it's easy to
wrap this up as WSGI interface (using e.g. the code from PEP 333).

-- 
Marc-Andre Lemburg
eGenix.com

Professional Python Services directly from the Source  (#1, Feb 11 2009)
>>> Python/Zope Consulting and Support ...http://www.egenix.com/
>>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/
>>> mxODBC, mxDateTime, mxTextTools ...http://python.egenix.com/


::: Try our new mxODBC.Connect Python Database Interface for free ! 


   eGenix.com Software, Skills and Services GmbH  Pastor-Loeh-Str.48
D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg
   Registered at Amtsgericht Duesseldorf: HRB 46611
   http://www.egenix.com/company/contact/
--
http://mail.python.org/mailman/listinfo/python-list


access to MS Access password-protected database?

2009-02-11 Thread Ken McDonald
Can anyone direct me towards a code snippet showing how to use Python  
to insert data into a password-protected MS Access database? My google  
searches have been uninformative for dbs that are password-protected.


Thanks,
Ken

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


Re: access to MS Access password-protected database?

2009-02-11 Thread Tim Golden

Ken McDonald wrote:
Can anyone direct me towards a code snippet showing how to use Python to 
insert data into a password-protected MS Access database? My google 
searches have been uninformative for dbs that are password-protected.


Caveat: I've never done it and I have no Access db to hand,
but in a spirit of being helpful...

According to this snippet:

http://www.vb-helper.com/howto_ado_use_access_password.html

it can be done via ADO. You can either roll your own, or you
can use the adodbapi module from the pywin32 extensions.

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


Re: Process crash with no reason

2009-02-11 Thread gil . shinar
On Feb 8, 5:31 pm, Stephen Hansen  wrote:
> > Thanks a lot and sorry for the late response. My main suspect is the
> > CherryPy.
> > I'm still investigating it.
>
> You're asking for advice but not listening to what people are saying
> here -- why is CherryPy on the top of your list?
>
> What version of CherryPy is it? 1 or 2?
>
> If its 2, then its pure python and there's a really, really low chance
> that its provoking a hard crash w/o a traceback printing before it
> dies out. A hard crash which isn't printing an error message is
> possible in pure Python I suppose, but I've never seen it. A "Bus
> error" for example will kill the interpreter before it can do any
> error handling. But I've only ever seen that when interfacing with
> third party libraries.
>
> If its 1, there is some C so you can bump it up ... and for that I'd
> probably attempt to run the application in a console or with stdout
> manually redirected instead of relying on the logging alone, to see if
> anything useful gets put out.. like "Bus error", at the time it exits.
>
> But why do you keep discarding the Sybase module?
>
> Its most definitely *not* written in python. What Philip and Tim were
> trying to tell you is you are *not* using "python's functions to run
> sybase sql commands"
>
> The Sybase module is a python wrapper around code written in C module
> which is interfacing with a third party library to talk to Sybase. Are
> you at the latest version of Sybase(0.39 if its the same module I'm
> aware of?) How about the library underneath it? FreeTDS or Sybase ASE
> (whatever that is) or whatever else is being used? A bug in /any/ of
> those C layers (notice its *multiple* layers) could propagate up and
> provoke a hard crash that Python doesn't catch. So if you look into
> those versions perhaps one has a new release that fixes bugs.
>
> --S

Hi,

After farther investigation and some help from other developers, we
got to the conclusion that the python process does not crash but the
program exits because cherrypy freezes and the python program has
nothing to do when the web service is not responding. My cherrypy
version is 3.0.1
Can any of you help me with cherrypy or should I ask in cherrypy
group?

Thanks

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


Re: best way to serve wsgi with multiple processes

2009-02-11 Thread Robin
On Feb 11, 3:46 pm, Robin Becker  wrote:
> well the flup server for fast cgi supports forking if the server is declared 
> as
> an external process in apache. Then the top level of the flup process handles
> each request and passes it off to a forked worker. I cannot recall exactly, 
> but
> I believe that apache mod_fastcgi does the right thing when it comes to
> internally declared fastcgi handlers. For apache at least I think the 
> threading
> issues are handled properly.
>
> I think the preforkserver.py code handles all the threading issues for you
> (assuming it's not win32).

Thanks - I think if I go the flup route I would use AJP though - since
its very easy to setup with apache (1 proxy line) and mod_ajp comes as
standard. And then everything is very much seperated from the apache
process.

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


Re: SOAP client

2009-02-11 Thread Robin
On Feb 11, 3:33 pm, mk  wrote:
> Hi,
>
> I'm trying to consume a SOAP web service using Python.  So far I have
> found two libraries: SOAPpy and ZSI.  Both of them rely on PyXML which
> is no longer maintained (and there is no build for 64bit Windows and
> the setup.py doesn't seem to know how to build it on Windows).  Is
> there a live SOAP library for Python?  I'm sort of surprised that a
> common standard like SOAP is not more actively supported in Python.
> I'm probably missing something?
>
> Thanks,
> m

For consuming services, I've found suds to be the best client:
https://fedorahosted.org/suds/

For creating them, I've been using soaplib:
http://trac.optio.webfactional.com/

HTH,

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


Re: Pycon 2009 Hotel?

2009-02-11 Thread Mike Driscoll
On Feb 11, 9:17 am, jay graves  wrote:
> On Feb 11, 9:13 am, jay graves  wrote:
>
> > I'm attending Pycon this year and for the first time I have to pay for
> > myself.  (All training/conference budgets have been zeroed out at my
> > company.)
>
> > I would like to take the cheaper option by staying at the Crowne Plaza
> > but as I understand it, the part of the conference I'll be attending
> > will be held at the Hyatt Regency.  I don't mind the walk but I also
> > don't want to miss out on the open spaces in the evening.
>
> > Is anyone else similarly on the fence?  I'd like to save $130 ((153 -
> > 100) * 3) but since I'm not staying for the sprints and alot of my
> > enjoyment of the conference is the open spaces.
>
> (Sorry. i hit 'Send' too quickly.)
>
> I'm wondering if I'm being 'penny-wise and pound-foolish'?  I'd hate
> to spend all that money to get there and then not enjoy it because I
> was at the 'other' hotel.
>
> ...
> Jay Graves

As I understand it, the hotels are connected via a skywalk, so I don't
think it will be a big deal either way. It just means a little extra
walking.

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


Who's on First, IDLE or pythonWin? Dialog Problem?

2009-02-11 Thread W. eWatson

My program in IDLE bombed with:
==
Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Python25\lib\lib-tk\Tkinter.py", line 1403, in __call__
return self.func(*args)
  File 
"C:\Sandia_Meteors\New_Sentinel_Development\Sentuser_Utilities_Related\sentuser\sentuserNC25-Dev4.py", 
line 552, in OperationalSettings

dialog = OperationalSettingsDialog( self.master, set_loc_dict )
  File 
"C:\Sandia_Meteors\New_Sentinel_Development\Sentuser_Utilities_Related\sentuser\sentuserNC25-Dev4.py", 
line 81, in __init__

tkSimpleDialog.Dialog.__init__(self, parent)
  File "C:\Python25\lib\lib-tk\tkSimpleDialog.py", line 69, in __init__
self.wait_visibility() # window needs to be visible for the grab
  File "C:\Python25\lib\lib-tk\Tkinter.py", line 415, in wait_visibility
self.tk.call('tkwait', 'visibility', window._w)
TclError: window ".34672232" was deleted before its visibility changed
===
It runs fine in pythonWin performing the same entry operation. Open a menu, 
 select an item to open a dialog, select a select button in the dialog, 
press OK to leave the dialog. Boom, as above.


(This does not mean pythonWin doesn't have problems of its own. ) If I just 
execute the code (double click on the py file, the console shows no 
problems. IDLE is unhappy.


Another side to this is that I use WinMerge to find differences between my 
last saved copy and the current copy. I found the current copy had two lines 
where a abc.get() was changed to abc.get. This was undoubtedly from briefly 
using the pyWin editor, when I mis-hit some keys. Yet pyWin had no trouble 
executing the program. My guess is that while briefly editing there, I hit 
some odd combination of keys that produced, perhaps, an invisible character 
that pyWin ignores.


Not the 34672232 window is a dialog that I closed by pressing OK. I would 
again guess, that, if there is a problem, it occurs in the code that 
destroys the dialog.



--
   W. eWatson

 (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time)
  Obz Site:  39° 15' 7" N, 121° 2' 32" W, 2700 feet

Web Page: 

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


Re: best way to serve wsgi with multiple processes

2009-02-11 Thread Robin Becker

Robin wrote:

On Feb 11, 3:46 pm, Robin Becker  wrote:

well the flup server for fast cgi supports forking if the server is declared as
an external process in apache. Then the top level of the flup process handles
each request and passes it off to a forked worker. I cannot recall exactly, but
I believe that apache mod_fastcgi does the right thing when it comes to
internally declared fastcgi handlers. For apache at least I think the threading
issues are handled properly.

I think the preforkserver.py code handles all the threading issues for you
(assuming it's not win32).


Thanks - I think if I go the flup route I would use AJP though - since
its very easy to setup with apache (1 proxy line) and mod_ajp comes as
standard. And then everything is very much seperated from the apache
process.

...

that's right and very easy to control. The only problem I recall is that the 
socket needs to be made readable by www. You can do that with a sudo chown or by 
setting up the mask at the ajp server start.

--
Robin Becker

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


Re: Escaping my own chroot...

2009-02-11 Thread Jean-Paul Calderone

On Wed, 11 Feb 2009 09:31:56 -0600, Nick Craig-Wood  wrote:

r0g  wrote:

 I'm writing a linux remastering script in python where I need to chroot
 into a folder, run some system commands and then come out and do some
 tidying up, un-mounting proc & sys etc.

 I got in there with os.chroot() and I tried using that to get back out
 but that didn't work so... is my script trapped in there forever now or
 is there an un-hacky way to escape?


No!



If you still have root in the chroot (and you need root to get in there, so
it's not implausible that you will), then you can get out.  Googling for
"escape chroot" turns up lots of hits.  This page contains a fairly simple,
explicit description of how to get out of a chroot:

  http://www.bpfh.net/simes/computing/chroot-break.html

See the bulleted list in the "Breaking chroot()" section.  Since you also
control the process before the chroot happens, breaking out is even simpler
in your case (just open / before you chroot in the first place).  forking
before doing the chroot may still be a good idea, but it's not the only
solution.

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


Re: Who's on First, IDLE or pythonWin? Dialog Problem?

2009-02-11 Thread Mike Driscoll
On Feb 11, 10:28 am, "W. eWatson"  wrote:
> My program in IDLE bombed with:
> ==
> Exception in Tkinter callback
> Traceback (most recent call last):
>    File "C:\Python25\lib\lib-tk\Tkinter.py", line 1403, in __call__
>      return self.func(*args)
>    File
> "C:\Sandia_Meteors\New_Sentinel_Development\Sentuser_Utilities_Related\sentuser\sentuserNC25-Dev4.py",
> line 552, in OperationalSettings
>      dialog = OperationalSettingsDialog( self.master, set_loc_dict )
>    File
> "C:\Sandia_Meteors\New_Sentinel_Development\Sentuser_Utilities_Related\sentuser\sentuserNC25-Dev4.py",
> line 81, in __init__
>      tkSimpleDialog.Dialog.__init__(self, parent)
>    File "C:\Python25\lib\lib-tk\tkSimpleDialog.py", line 69, in __init__
>      self.wait_visibility() # window needs to be visible for the grab
>    File "C:\Python25\lib\lib-tk\Tkinter.py", line 415, in wait_visibility
>      self.tk.call('tkwait', 'visibility', window._w)
> TclError: window ".34672232" was deleted before its visibility changed
> ===
> It runs fine in pythonWin performing the same entry operation. Open a menu,
>   select an item to open a dialog, select a select button in the dialog,
> press OK to leave the dialog. Boom, as above.
>
> (This does not mean pythonWin doesn't have problems of its own. ) If I just
> execute the code (double click on the py file, the console shows no
> problems. IDLE is unhappy.
>
> Another side to this is that I use WinMerge to find differences between my
> last saved copy and the current copy. I found the current copy had two lines
> where a abc.get() was changed to abc.get. This was undoubtedly from briefly
> using the pyWin editor, when I mis-hit some keys. Yet pyWin had no trouble
> executing the program. My guess is that while briefly editing there, I hit
> some odd combination of keys that produced, perhaps, an invisible character
> that pyWin ignores.
>
> Not the 34672232 window is a dialog that I closed by pressing OK. I would
> again guess, that, if there is a problem, it occurs in the code that
> destroys the dialog.
>
> --
>                                 W. eWatson
>
>               (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time)
>                Obz Site:  39° 15' 7" N, 121° 2' 32" W, 2700 feet
>
>                      Web Page: 

You don't really say what your code does or if it uses a GUI toolkit
and if so, which one. But my guess is that you are using some kind of
GUI and its GUI and IDLE's are clashing somehow. I see this sort of
thing with some of my wxPython programs from time to time, although
IDLE usually just crashes with no error message.

I would recommend using the command line or something that can open it
in a completely separate process, such as Wingware's IDE.

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


Re: Who's on First, IDLE or pythonWin? Dialog Problem?

2009-02-11 Thread Steve Holden
W. eWatson wrote:
> My program in IDLE bombed with:
> ==
> Exception in Tkinter callback
> Traceback (most recent call last):
>   File "C:\Python25\lib\lib-tk\Tkinter.py", line 1403, in __call__
> return self.func(*args)
>   File
> "C:\Sandia_Meteors\New_Sentinel_Development\Sentuser_Utilities_Related\sentuser\sentuserNC25-Dev4.py",
> line 552, in OperationalSettings
> dialog = OperationalSettingsDialog( self.master, set_loc_dict )
>   File
> "C:\Sandia_Meteors\New_Sentinel_Development\Sentuser_Utilities_Related\sentuser\sentuserNC25-Dev4.py",
> line 81, in __init__
> tkSimpleDialog.Dialog.__init__(self, parent)
>   File "C:\Python25\lib\lib-tk\tkSimpleDialog.py", line 69, in __init__
> self.wait_visibility() # window needs to be visible for the grab
>   File "C:\Python25\lib\lib-tk\Tkinter.py", line 415, in wait_visibility
> self.tk.call('tkwait', 'visibility', window._w)
> TclError: window ".34672232" was deleted before its visibility changed
> ===
> It runs fine in pythonWin performing the same entry operation. Open a
> menu,  select an item to open a dialog, select a select button in the
> dialog, press OK to leave the dialog. Boom, as above.
> 
> (This does not mean pythonWin doesn't have problems of its own. ) If I
> just execute the code (double click on the py file, the console shows no
> problems. IDLE is unhappy.
> 
> Another side to this is that I use WinMerge to find differences between
> my last saved copy and the current copy. I found the current copy had
> two lines where a abc.get() was changed to abc.get. This was undoubtedly
> from briefly using the pyWin editor, when I mis-hit some keys. Yet pyWin
> had no trouble executing the program. My guess is that while briefly
> editing there, I hit some odd combination of keys that produced,
> perhaps, an invisible character that pyWin ignores.
> 
> Not the 34672232 window is a dialog that I closed by pressing OK. I
> would again guess, that, if there is a problem, it occurs in the code
> that destroys the dialog.
> 
> 
Well you have to remember that you are trying to run a windowed GUI
under the control of another windows GUI, so it isn't surprising that
you hit trouble.

With IDLE the issue will be that IDLE already created a main window
before your program started running. With PythonWin you are using two
different toolkits, so it isn't really surprising that breaks down -
there will be two entirely separate main loops competing with each other.

regards
 Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

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


Could you recommend job schedulling solution?

2009-02-11 Thread redbaron
I've sinlge 8-way node dedicated for executing long running tasks. To
be able to execute multiple tasks on this node it shoud  spawn each
task in another process. At the same time it should accept network
connection with new tasks without blocking of client and put it on job
queue.

What is "task" ? Executing just ordinary python function will be
enough. If solution contain some client library which allow easy task
submit it will be great.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Iterable Ctypes Struct

2009-02-11 Thread mark . seagoe
On Feb 10, 9:52 pm, "Gabriel Genellina" 
wrote:
> En Wed, 11 Feb 2009 00:31:26 -0200,  escribió:
>
> > I like the ability to access elements of a struct such as with ctypes
> > Structure:
>  myStruct.elementName1
> > 4
>
> > What I like about it is there are no quotes needed.
>
> > What I don't like about it is that it's not iterable:
>  for n in myStruct:  <== gives error
>     print n
>
> > I don't want to force the end user to have preknowledge of the element
> > names.
>
> Note that those names are available as the _fields_ class attribute
>
> > Has anyone subclassed ctypes Structure based class to be iterable?
> > Before a noob starts trying to do this, is it possible?  How to
> > approach it?
>
> The easiest way would be to define __getitem__ accepting index 0, 1, 2...  
> until the last defined field.
> Seehttp://docs.python.org/reference/datamodel.html#object.__getitem__
>
> 
>  from ctypes import Structure
>
> class IterableStructure(Structure):
>    def __getitem__(self, i):
>      if not isinstance(i, int):
>        raise TypeError('subindices must be integers: %r' % i)
>      return getattr(self, self._fields_[i][0])
>
> 
>
> This was tested as much as you see here:
>
> py> from ctypes import c_int
> py>
> py> class POINT(IterableStructure):
> ...     _fields_ = [("x", c_int),
> ...                 ("y", c_int)]
> ...
> py> point = POINT(10, 20)
> py> print point.x, point.y
> 10 20
> py> for field in point:
> ...   print field
> ...
> 10
> 20
> py> print list(point)
> [10, 20]
>
> --
> Gabriel Genellina

Thanks very much, Gabriel.  This is very good start for me.
This works for predefined class.  How about a situation where the
fields are added dynamically (as from reading in from an xml file).
For example, if I were to now add another element:

>>> point.z = 30
>>> print list(point)
[10, 20]
>>> dir(point)
['__class__', '__ctypes_from_outparam__', '__delattr__', '__
dict__', '__doc__', '__getattribute__', '__getitem__', '__ha
sh__', '__init__', '__module__', '__new__', '__reduce__', '_
_reduce_ex__', '__repr__', '__setattr__', '__str__', '__weak
ref__', '_b_base_', '_b_needsfree_', '_fields_', '_objects',
 'x', 'y', 'z']

I don't know why the iterator (where ever it is) didn't get
incremented.  Thanks for any insight.

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


Re: generator object or 'send' method?

2009-02-11 Thread Aaron Brady
On Feb 11, 4:41 am, greg  wrote:
> Aaron Brady wrote:
> > It would receive the 'send' from a different point in control
> > flow than its usual 'next'.  Should it repeat a value if it receives a
> > 'send'?
>
> No. This requirement clearly indicates that send() is
> the wrong tool for the job.
>
> I would use a class with a generator as a method, e.g.
>
>    class Multiples:
>
>      m = 1
>
>      def set_multiplier(self, m):
>        self.m = m
>
>      def generate(self, limit):
>        for i in xrange(limit):
>          yield i * self.m
>
>    g = Multiples()
>    for x in g.generate(10):
>      print x
>      if x == 3:
>        g.set_multiplier(42)
>
> produces
>
> 0
> 1
> 2
> 3
> 168
> 210
> 252
> 294
> 336
> 378
>
> --
> Greg

Alright, but you don't have to go so far as to create an entire
class.  It's alright to use a formula.  Here's a way to add a
dictionary to a generator instance.

def gen_dict( fun ):
def inner( *ar, **kw ):
self.gen= fun( self, *ar, **kw )
return self
class GenWrapper:
def __iter__( self ): return self
def __next__( self, *ar, **kw ): return self.gen.__next__
( *ar, **kw )
self= GenWrapper()
return inner

It's a shame that you can't set 'self.__next__= self.gen.__next__'.
It costs an entire level of call depth.  On the other hand, I'm not
sure a pure delegate class is possible.

The decorator just puts the generator object in a 'gen' attribute, and
adds itself to the '__init__' argument list.  So the generator has a
'self' argument, which is of type 'instance', and allows dynamic
attributes.

@gen_dict
def jumper( self, N= 1, K= 1 ):
self.N, self.K= N, K
while 1:
yield self.N
self.N+= self.K

j= jumper()
print( next( j ) )
j.K= 4
print( next( j ) )

It might need some touch-ups to run in Python 2.  Neat mix.  It's a
cool hybrid between Terry's and Greg's idea, and a bare generator.
Unfortunately, if you want 'self' to have any methods, you'll probably
need a class... though maybe it could inherit from 'GenWrapper'.  What
do you think?

P.S.  Here's a slightly simpler version.

def gen_dict( fun ):
class GenWrapper:
def __init__( self, *ar, **kw ):
self.gen= fun( self, *ar, **kw )
def __iter__( self ): return self
def __next__( self, *ar, **kw ): return self.gen.__next__
( *ar, **kw )
return GenWrapper

P.P.S.  Simpler, but a line longer.

class GenWrapper:
def __init__( self, fun ):
self.fun= fun
def __call__( self, *ar, **kw ):
self.gen= self.fun( self, *ar, **kw )
return self
def __iter__( self ): return self
def __next__( self, *ar, **kw ): return self.gen.__next__( *ar,
**kw )
--
http://mail.python.org/mailman/listinfo/python-list


RE: Could you recommend job schedulling solution?

2009-02-11 Thread bruce
hi...

not sure exactly what you're looking for, but "condor" has a robust job
scheduling architecture for dealing with grid/distributed setups over
multiple systems..

give us more information, and there might be other suggestions!


-Original Message-
From: python-list-bounces+bedouglas=earthlink@python.org
[mailto:python-list-bounces+bedouglas=earthlink@python.org]on Behalf
Of redbaron
Sent: Wednesday, February 11, 2009 9:01 AM
To: python-list@python.org
Subject: Could you recommend job schedulling solution?


I've sinlge 8-way node dedicated for executing long running tasks. To
be able to execute multiple tasks on this node it shoud  spawn each
task in another process. At the same time it should accept network
connection with new tasks without blocking of client and put it on job
queue.

What is "task" ? Executing just ordinary python function will be
enough. If solution contain some client library which allow easy task
submit it will be great.
--
http://mail.python.org/mailman/listinfo/python-list

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


Re: access to MS Access password-protected database?

2009-02-11 Thread imageguy
On Feb 11, 10:43 am, Ken McDonald 
wrote:
> Can anyone direct me towards a code snippet showing how to use Python  
> to insert data into a password-protected MS Access database? My google  
> searches have been uninformative for dbs that are password-protected.
>
> Thanks,
> Ken

You post is a little vague on specifics
- do you actually have access to the db ?
- can you open it with access ?
- can you currently read records using python ?

I am assuming you don't have access to the db through python, once you
do the rest is straight forward.

I use DSN-less connections.  This link below is quite helpful
http://www.carlprothman.net/Default.aspx?tabid=90#ODBCDriverForAccess

If you aren't using the adodbapi (part of the pywin32 package), you
need to do something like this, assuming you access db is MS-Access
2000 and above.


import win32com
cnx = win32com.client.Dispatch('ADODB.connection')

parms = {}
parms['driver'] = '{Microsoft Access Driver (*.mdb)}'
parms['dbase'] = path_to_mdb
parms['sys_mdw'] = path_to_workgroup_security
parms['uid'] = userid_defined_in_mdw
parhs['pwd'] = pwd_for_uid_in_mdw

cnxtr = 'Driver=%(driver)s; DBQ=%(dbase)s; SYSTEMDB=%(sys_mdw)s; UID=%
(uid)s; PWD=%(pwd)s; ' % parms
cnx.ConnectionString = cnxstr
cnx.Open()


once you have an ADO Connection, execute SQL directly on the
connection like this

cnx.Execute('INSERT INTO tablename (col1, col2) VALUES ('val1,
val2);')

Or alternatively you should create RecordSets and manipulate these.

IF you need help understanding ADO I would recommend;
http://www.w3schools.com/ado/default.asp

The examples are translateable to Python.
You create recordsets via;
rs = win32com.client.Dispatch('ADO.RecordSet')


If you don't have/weren't given the passwords to the DB, but you do
have access to the workgroup file ('*.MDW') file that stores the uid/
pwds and permission, then there are several third party tools that
will recover these for you. Google is your friend.

If you don't have access to the original .mdw ... well, I can't help
you and I don't think anyone can.

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


Re: SOAP client

2009-02-11 Thread JBW
On Wed, 11 Feb 2009 07:33:29 -0800, mk wrote:

> I'm trying to consume a SOAP web service using Python.

Suds (ibid) -- accept no substitute!
--
http://mail.python.org/mailman/listinfo/python-list


Re: Iterable Ctypes Struct

2009-02-11 Thread mark . seagoe
On Feb 11, 9:01 am, mark.sea...@gmail.com wrote:
> On Feb 10, 9:52 pm, "Gabriel Genellina" 
> wrote:
>
>
>
>
>
> > En Wed, 11 Feb 2009 00:31:26 -0200,  escribió:
>
> > > I like the ability to access elements of a struct such as with ctypes
> > > Structure:
> >  myStruct.elementName1
> > > 4
>
> > > What I like about it is there are no quotes needed.
>
> > > What I don't like about it is that it's not iterable:
> >  for n in myStruct:  <== gives error
> >     print n
>
> > > I don't want to force the end user to have preknowledge of the element
> > > names.
>
> > Note that those names are available as the _fields_ class attribute
>
> > > Has anyone subclassed ctypes Structure based class to be iterable?
> > > Before a noob starts trying to do this, is it possible?  How to
> > > approach it?
>
> > The easiest way would be to define __getitem__ accepting index 0, 1, 2...  
> > until the last defined field.
> > Seehttp://docs.python.org/reference/datamodel.html#object.__getitem__
>
> > 
> >  from ctypes import Structure
>
> > class IterableStructure(Structure):
> >    def __getitem__(self, i):
> >      if not isinstance(i, int):
> >        raise TypeError('subindices must be integers: %r' % i)
> >      return getattr(self, self._fields_[i][0])
>
> > 
>
> > This was tested as much as you see here:
>
> > py> from ctypes import c_int
> > py>
> > py> class POINT(IterableStructure):
> > ...     _fields_ = [("x", c_int),
> > ...                 ("y", c_int)]
> > ...
> > py> point = POINT(10, 20)
> > py> print point.x, point.y
> > 10 20
> > py> for field in point:
> > ...   print field
> > ...
> > 10
> > 20
> > py> print list(point)
> > [10, 20]
>
> > --
> > Gabriel Genellina
>
> Thanks very much, Gabriel.  This is very good start for me.
> This works for predefined class.  How about a situation where the
> fields are added dynamically (as from reading in from an xml file).
> For example, if I were to now add another element:
>
> >>> point.z = 30
> >>> print list(point)
> [10, 20]
> >>> dir(point)
>
> ['__class__', '__ctypes_from_outparam__', '__delattr__', '__
> dict__', '__doc__', '__getattribute__', '__getitem__', '__ha
> sh__', '__init__', '__module__', '__new__', '__reduce__', '_
> _reduce_ex__', '__repr__', '__setattr__', '__str__', '__weak
> ref__', '_b_base_', '_b_needsfree_', '_fields_', '_objects',
>  'x', 'y', 'z']
>
> I don't know why the iterator (where ever it is) didn't get
> incremented.  Thanks for any insight.
>
> Mark- Hide quoted text -
>
> - Show quoted text -

I tinkered with it and think I have viable solution.
I need to append a new member to _fields_ before writing it,
then it seems to work.

>>> p._fields_.append(('z', c_int))
>>> point.z = 30
>>> print 'List:', list(p)
List: [10, 20, 30]

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


Unicode issue on Windows cmd line

2009-02-11 Thread jeffg
Having issue on Windows cmd.
> Python.exe
>>>a = u'\xf0'
>>>print a

This gives a unicode error.

Works fine in IDLE, PythonWin, and my Macbook but I need to run this
from a windows batch.

Character should look like this "ð".

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


Re: Iterable Ctypes Struct

2009-02-11 Thread mark . seagoe
In last post, I mixed code w/ 'p' and 'point'.  Should be:

>>> point._fields_.append(('z', c_int))
>>> point.z = 30
>>> print 'List:', list(point)

List: [10, 20, 30]
--
http://mail.python.org/mailman/listinfo/python-list


Re: Could you recommend job schedulling solution?

2009-02-11 Thread redbaron
On 11 фев, 20:26, "bruce"  wrote:
> hi...
>
> not sure exactly what you're looking for, but "condor" has a robust job
> scheduling architecture for dealing with grid/distributed setups over
> multiple systems..
>
> give us more information, and there might be other suggestions!

Condor, Globus or any other grid system looks like serious overkill
for me. I need some sort of job manager, which accepts jobs from
clients as pickled python functions and queues/executes them. Client
side should be able to ask status of submitted job, their return
value, ask to cancel job etc.
--
http://mail.python.org/mailman/listinfo/python-list


Re: getopt index out of range

2009-02-11 Thread Matthew Sacks
>because the traceback says the index is 0 and there's only one line with a 0 
>in it!
Indeed. Thank you.


On Wed, Feb 11, 2009 at 7:11 AM, MRAB  wrote:
> Steve Holden wrote:
>>
>> Matthew Sacks wrote:
>>>
>>> Hi List,
>>> I am getting an index out of range error when trying to parse with
>>> getopt.
>>> Probably something simple. Any suggestions are appreciated
>>>
>>> optlist, args = getopt.getopt(sys.argv[1:], 'h', ['connectPassword=',
>>> 'adminServerURL=', 'action=', 'targets=', 'appDir='])
>>>
>>>
>>> #Assign Opts
>>> connectPassword = optlist[0][1]
>>> adminServerURL = optlist[1][1]
>>> action = optlist[2][1]
>>> targets = optlist[3][1]
>>> appDir = optlist[4][1]
>>>
>>> #this statement never gets executed
>>> print "Args: " + connectPassword + " " + adminServerURL + " " + action
>>> + " " + targets + " " + appDir
>>>
>>>  File "/home/msacks/untitled4.py", line 23, in ?
>>> IndexError: index out of range: 0
>>>
>> It might help a little if you made it more obvious which was line 23 ...
>>
> It a guess I'd say it was:
>
>connectPassword = optlist[0][1]
>
> because the traceback says the index is 0 and there's only one line with a 0
> in it!
>
>> The real problem, though, is a misunderstanding of what getopt.getopt()
>> returns. The (option, value) pairs are only returned for options found
>> in the command line, so you can't guarantee there'll be four.
>>
>> Set your values to defaults, then adjust for those for which an option
>> is found in the list, as in the "typical usage" example in the Fine
>> Manual.
>>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: Functional schmunctional...

2009-02-11 Thread wolfram . hinderer
On 10 Feb., 21:28, r0g  wrote:

> def inet2ip(n, l=[], c=4):
>   if c==0: return ".".join(l)
>   p = 256**( c-1 )
>   l.append( str(n/p) )
>   return inet2ip( n-(n/p)*p, l, c-1 )

> The results for 1
> iterations of each were as follows...
>
> 0.113744974136 seconds for old INET->IP method
> 27.744112 seconds for new INET->IP method
>
> :-/

That's probably because your new function is broken:

>>> def inet2ip(n, l=[], c=4):
  if c==0: return ".".join(l)
  p = 256**( c-1 )
  l.append( str(n/p) )
  return inet2ip( n-(n/p)*p, l, c-1 )

>>> inet2ip(0)
'0.0.0.0'
>>> inet2ip(0)
'0.0.0.0.0.0.0.0'
>>> inet2ip(0)
'0.0.0.0.0.0.0.0.0.0.0.0'

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


Re: zlib interface semi-broken

2009-02-11 Thread Scott David Daniels

Paul Rubin wrote:

Scott David Daniels  writes:

Seems like we may want to say things like, "synchronization points are
too be silently ignored."


That would completely break some useful possible applications, so should
be avoided.

No, I mean that we, _the_users_of_the_interface_, may want to say, 
That is, I'd like that behavior as an option.

-Scott David Daniels
scott.dani...@acm.org

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


Re: zlib interface semi-broken

2009-02-11 Thread Scott David Daniels

Paul Rubin wrote:

Scott David Daniels  writes:

I suspect that is why such an interface never came up (If
you can clone states, then you can say: "compress this, then use the
resultant state to compress/decompress others." 


The zlib C interface supports something like that.  It is just not
exported to the python application.  It should be.

Right, we are gathering ideas we'd like to see available to the Python
programmer in the new zlib / bz2 agglomeration that we are thinking of
building / proposing.

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


Re: zlib interface semi-broken

2009-02-11 Thread Scott David Daniels

Scott David Daniels wrote:

... I've wanted to do some low-level (C-coded) search w/o bothering
to create strings until a match

Here's a more common use case: signature gathering on the contents.

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


Re: Unicode issue on Windows cmd line

2009-02-11 Thread Albert Hopkins
On Wed, 2009-02-11 at 10:35 -0800, jeffg wrote:
> Having issue on Windows cmd.
> > Python.exe
> >>>a = u'\xf0'
> >>>print a
> 
> This gives a unicode error.
> 
> Works fine in IDLE, PythonWin, and my Macbook but I need to run this
> from a windows batch.
> 
> Character should look like this "ð".
> 
> Please help!

You forgot to paste the error.


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


Re: Who's on First, IDLE or pythonWin? Dialog Problem?

2009-02-11 Thread W. eWatson

Mike Driscoll wrote:

On Feb 11, 10:28 am, "W. eWatson"  wrote:

My program in IDLE bombed with:
==
Exception in Tkinter callback
Traceback (most recent call last):
   File "C:\Python25\lib\lib-tk\Tkinter.py", line 1403, in __call__
 return self.func(*args)
   File
"C:\Sandia_Meteors\New_Sentinel_Development\Sentuser_Utilities_Related\sentuser\sentuserNC25-Dev4.py",
line 552, in OperationalSettings
 dialog = OperationalSettingsDialog( self.master, set_loc_dict )
   File
"C:\Sandia_Meteors\New_Sentinel_Development\Sentuser_Utilities_Related\sentuser\sentuserNC25-Dev4.py",
line 81, in __init__
 tkSimpleDialog.Dialog.__init__(self, parent)
   File "C:\Python25\lib\lib-tk\tkSimpleDialog.py", line 69, in __init__
 self.wait_visibility() # window needs to be visible for the grab
   File "C:\Python25\lib\lib-tk\Tkinter.py", line 415, in wait_visibility
 self.tk.call('tkwait', 'visibility', window._w)
TclError: window ".34672232" was deleted before its visibility changed
===
It runs fine in pythonWin performing the same entry operation. Open a menu,
  select an item to open a dialog, select a select button in the dialog,
press OK to leave the dialog. Boom, as above.

(This does not mean pythonWin doesn't have problems of its own. ) If I just
execute the code (double click on the py file, the console shows no
problems. IDLE is unhappy.

Another side to this is that I use WinMerge to find differences between my
last saved copy and the current copy. I found the current copy had two lines
where a abc.get() was changed to abc.get. This was undoubtedly from briefly
using the pyWin editor, when I mis-hit some keys. Yet pyWin had no trouble
executing the program. My guess is that while briefly editing there, I hit
some odd combination of keys that produced, perhaps, an invisible character
that pyWin ignores.

Note the 34672232 window is a dialog that I closed by pressing OK. I would
again guess, that, if there is a problem, it occurs in the code that
destroys the dialog.




You don't really say what your code does or if it uses a GUI toolkit
and if so, which one. But my guess is that you are using some kind of
GUI and its GUI and IDLE's are clashing somehow. I see this sort of
thing with some of my wxPython programs from time to time, although
IDLE usually just crashes with no error message.

I would recommend using the command line or something that can open it
in a completely separate process, such as Wingware's IDE.

Mike
Tkinter. Isn't just clicking on the py file enough to side step either of 
the two? I did it and it worked fine. The code is for a GUI that has five or 
 so menus on the main window bar, and manipulates video that is downloaded 
to it from a video camera. The problem occurs in a dialog in which a user 
enters configuration values, like the time to start/stop the camera. As soon 
as I press OK on the dialog the program dies as above. It wasn't doing that 
at all for days despite some heavy editing. A WinMerge shows its quite 
faithful to it's last working predecessor. That's how I found the get problem.


--
   W. eWatson

 (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time)
  Obz Site:  39° 15' 7" N, 121° 2' 32" W, 2700 feet

Web Page: 

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


Re: Who's on First, IDLE or pythonWin? Dialog Problem?

2009-02-11 Thread W. eWatson

Steve Holden wrote:

W. eWatson wrote:

My program in IDLE bombed with:
==
Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Python25\lib\lib-tk\Tkinter.py", line 1403, in __call__
return self.func(*args)
  File
"C:\Sandia_Meteors\New_Sentinel_Development\Sentuser_Utilities_Related\sentuser\sentuserNC25-Dev4.py",
line 552, in OperationalSettings
dialog = OperationalSettingsDialog( self.master, set_loc_dict )
  File
"C:\Sandia_Meteors\New_Sentinel_Development\Sentuser_Utilities_Related\sentuser\sentuserNC25-Dev4.py",
line 81, in __init__
tkSimpleDialog.Dialog.__init__(self, parent)
  File "C:\Python25\lib\lib-tk\tkSimpleDialog.py", line 69, in __init__
self.wait_visibility() # window needs to be visible for the grab
  File "C:\Python25\lib\lib-tk\Tkinter.py", line 415, in wait_visibility
self.tk.call('tkwait', 'visibility', window._w)
TclError: window ".34672232" was deleted before its visibility changed
===
It runs fine in pythonWin performing the same entry operation. Open a
menu,  select an item to open a dialog, select a select button in the
dialog, press OK to leave the dialog. Boom, as above.

(This does not mean pythonWin doesn't have problems of its own. ) If I
just execute the code (double click on the py file, the console shows no
problems. IDLE is unhappy.

Another side to this is that I use WinMerge to find differences between
my last saved copy and the current copy. I found the current copy had
two lines where a abc.get() was changed to abc.get. This was undoubtedly
from briefly using the pyWin editor, when I mis-hit some keys. Yet pyWin
had no trouble executing the program. My guess is that while briefly
editing there, I hit some odd combination of keys that produced,
perhaps, an invisible character that pyWin ignores.

Not the 34672232 window is a dialog that I closed by pressing OK. I
would again guess, that, if there is a problem, it occurs in the code
that destroys the dialog.



Well you have to remember that you are trying to run a windowed GUI
under the control of another windows GUI, so it isn't surprising that
you hit trouble.

With IDLE the issue will be that IDLE already created a main window
before your program started running. With PythonWin you are using two
different toolkits, so it isn't really surprising that breaks down -
there will be two entirely separate main loops competing with each other.

regards
 Steve

Not quite. I take down IDLE when I run pyWin, and vice versa.

--
   W. eWatson

 (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time)
  Obz Site:  39° 15' 7" N, 121° 2' 32" W, 2700 feet

Web Page: 

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


Re: Replace unknow string varible in file.

2009-02-11 Thread namire
Thanks to Vlastimil Brom for his example and r0g for his helpful
attitude and hyperlinks I was able to made program do what was
needed.  Terry the comments in the html are not important I was just
saying that if I could cover the undesired strings in html comment
tags then they would not should up on a web browser viewing the file,
lucky I get then erased also so the comments is not needed.  I anyone
wants I can post a pastebin the the full code that uses the regex's.
--
http://mail.python.org/mailman/listinfo/python-list


openOffic, windows, and Python 2.5

2009-02-11 Thread John Fabiani
Hi,
OpenOffice 3 on windows uses python 2.3.x (I have no idea why).  Does anyone
know where I can get whatever is needed to get python 2.5 working.  I don't
want to learn how recompile openoffice because it has a steep learning
curve and is just to much when I can just use M$ word.

BTW using the openSUSE update to install openOffice3 uses my installed
python.  

Maybe someone has already done the compile and is willing to share?

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


Re: Who's on First, IDLE or pythonWin? Dialog Problem?

2009-02-11 Thread Steve Holden
W. eWatson wrote:
> Steve Holden wrote:
>> W. eWatson wrote:
>>> My program in IDLE bombed with:
>>> ==
>>> Exception in Tkinter callback
>>> Traceback (most recent call last):
>>>   File "C:\Python25\lib\lib-tk\Tkinter.py", line 1403, in __call__
>>> return self.func(*args)
>>>   File
>>> "C:\Sandia_Meteors\New_Sentinel_Development\Sentuser_Utilities_Related\sentuser\sentuserNC25-Dev4.py",
>>>
>>> line 552, in OperationalSettings
>>> dialog = OperationalSettingsDialog( self.master, set_loc_dict )
>>>   File
>>> "C:\Sandia_Meteors\New_Sentinel_Development\Sentuser_Utilities_Related\sentuser\sentuserNC25-Dev4.py",
>>>
>>> line 81, in __init__
>>> tkSimpleDialog.Dialog.__init__(self, parent)
>>>   File "C:\Python25\lib\lib-tk\tkSimpleDialog.py", line 69, in __init__
>>> self.wait_visibility() # window needs to be visible for the grab
>>>   File "C:\Python25\lib\lib-tk\Tkinter.py", line 415, in wait_visibility
>>> self.tk.call('tkwait', 'visibility', window._w)
>>> TclError: window ".34672232" was deleted before its visibility changed
>>> ===
>>> It runs fine in pythonWin performing the same entry operation. Open a
>>> menu,  select an item to open a dialog, select a select button in the
>>> dialog, press OK to leave the dialog. Boom, as above.
>>>
>>> (This does not mean pythonWin doesn't have problems of its own. ) If I
>>> just execute the code (double click on the py file, the console shows no
>>> problems. IDLE is unhappy.
>>>
>>> Another side to this is that I use WinMerge to find differences between
>>> my last saved copy and the current copy. I found the current copy had
>>> two lines where a abc.get() was changed to abc.get. This was undoubtedly
>>> from briefly using the pyWin editor, when I mis-hit some keys. Yet pyWin
>>> had no trouble executing the program. My guess is that while briefly
>>> editing there, I hit some odd combination of keys that produced,
>>> perhaps, an invisible character that pyWin ignores.
>>>
>>> Not the 34672232 window is a dialog that I closed by pressing OK. I
>>> would again guess, that, if there is a problem, it occurs in the code
>>> that destroys the dialog.
>>>
>>>
>> Well you have to remember that you are trying to run a windowed GUI
>> under the control of another windows GUI, so it isn't surprising that
>> you hit trouble.
>>
>> With IDLE the issue will be that IDLE already created a main window
>> before your program started running. With PythonWin you are using two
>> different toolkits, so it isn't really surprising that breaks down -
>> there will be two entirely separate main loops competing with each other.
>>
> Not quite. I take down IDLE when I run pyWin, and vice versa.
> 
The two separate loops being PyWin (which uses MFC) and your program
(which uses Tkinter). You just can't mix GUIs in the same process like
that, sorry.

regards
 Stedve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

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


Re: Unicode issue on Windows cmd line

2009-02-11 Thread jeffg
On Feb 11, 2:35 pm, Albert Hopkins  wrote:
> On Wed, 2009-02-11 at 10:35 -0800, jeffg wrote:
> > Having issue on Windows cmd.
> > > Python.exe
> > >>>a = u'\xf0'
> > >>>print a
>
> > This gives a unicode error.
>
> > Works fine in IDLE, PythonWin, and my Macbook but I need to run this
> > from a windows batch.
>
> > Character should look like this "ð".
>
> > Please help!
>
> You forgot to paste the error.

The error looks like this:
File "
File "C:\python25\lib\encodings\cp437.py", line 12, in encode
  return codecs.charmap_encode(input,errors,encoding_map)
UnicodeEncodeError: 'charmap' codec can't encode character u'\xf0' in
position 0
: character maps to 


Running Python 2.5.4 on Windows XP
--
http://mail.python.org/mailman/listinfo/python-list


Re: re.sub and named groups

2009-02-11 Thread Shawn Milochik
>
> Book recommendation: _Mastering Regular Expressions_, Jeffrey Friedl
> --
> Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

I wholeheartedly second this! The third edition is out now.
--
http://mail.python.org/mailman/listinfo/python-list


hpw to convert a linux python script ?

2009-02-11 Thread Stef Mientki

hello,

I've a python script, written for some Linux version,
now I want to run it under windows.
It complains of not finding files in
 /usr/share/tinybldLin/  
where  is the directory where the script is located and started from.

As there are a whole lot of these lines, in a whole lot of files,
I wonder if there's a simple trick to point
 /usr/share/tinybldLin/
to my directory ?


thanks,
Stef
--
http://mail.python.org/mailman/listinfo/python-list


Re: zlib interface semi-broken

2009-02-11 Thread Paul Rubin
Scott David Daniels  writes:
> >> Seems like we may want to say things like, "synchronization points are
> >> too be silently ignored."
> No, I mean that we, _the_users_of_the_interface_, may want to say, 
> That is, I'd like that behavior as an option.

I don't see any reason to want that (rather than letting the application
handle it) but I'll take your word for it.
--
http://mail.python.org/mailman/listinfo/python-list


Re: best way to serve wsgi with multiple processes

2009-02-11 Thread Graham Dumpleton
On Feb 11, 8:50 pm, Robin  wrote:
> Hi,
>
> I am building some computational web services using soaplib. This
> creates a WSGI application.
>
> However, since some of these services are computationally intensive,
> and may be long running, I was looking for a way to use multiple
> processes. I thought about using multiprocessing.Process manually in
> the service, but I was a bit worried about how that might interact
> with a threaded server (I was hoping the thread serving that request
> could just wait until the child is finished). Also it would be good to
> keep the services as simple as possible so it's easier for people to
> write them.
>
> I have at the moment the following WSGI structure:
> TransLogger(URLMap(URLParser(soaplib objects)))
> although presumably, due to the beauty of WSGI, this shouldn't matter.
>
> As I've found with all web-related Python stuff, I'm overwhelmed by
> the choice and number of alternatives. I've so far been using cherrypy
> and ajp-wsgi for my testing, but am aware of Spawning, twisted etc.
> What would be the simplest [quickest to setup and fewest details of
> the server required - ideally with a simple example] and most reliable
> [this will eventually be 'in production' as part of a large scientific
> project] way to host this sort of WSGI with a process-per-request
> style?

In this sort of situation one wouldn't normally do the work in the
main web server, but have a separarte long running daemon process
embedding mini web server that understands XML-RPC. The main web
server would then make XML-RPC requests against the backend daemon
process, which would use threading and or queueing to handle the
requests.

If the work is indeed long running, the backend process would normally
just acknowledge the request and not wait. The web page would return
and it would be up to user to then somehow occassionally poll web
server, manually or by AJAX, to see how progres is going. That is,
further XML-RPC requests from main server to backend daemon process
asking about progress.

I do't believe the suggestions about fastcgi/scgi/ajp/flup or mod_wsgi
are really appropriate as you don't want this done in web server
processes as then you are at mercy of web server processes being
killed or dying when part way through something. Some of these systems
will do this if requests take too long. Thus better to offload real
work to another process.

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


Re: Could you recommend job schedulling solution?

2009-02-11 Thread Martin
Hi,

2009/2/11 redbaron :
> should accept network
> connection with new tasks without blocking of client and put it on job
> queue.
>
> What is "task" ? Executing just ordinary python function will be
> enough. If solution contain some client library which allow easy task
> submit it will be great.

I think parallel python will take of that for you
(http://www.parallelpython.com/)

-- 
http://soup.alt.delete.co.at
http://www.xing.com/profile/Martin_Marcher
http://www.linkedin.com/in/martinmarcher

You are not free to read this message,
by doing so, you have violated my licence
and are required to urinate publicly. Thank you.

Please avoid sending me Word or PowerPoint attachments.
See http://www.gnu.org/philosophy/no-word-attachments.html
--
http://mail.python.org/mailman/listinfo/python-list


Re: Unicode issue on Windows cmd line

2009-02-11 Thread Benjamin Kaplan
On Wed, Feb 11, 2009 at 2:50 PM, jeffg  wrote:

> On Feb 11, 2:35 pm, Albert Hopkins  wrote:
> > On Wed, 2009-02-11 at 10:35 -0800, jeffg wrote:
> > > Having issue on Windows cmd.
> > > > Python.exe
> > > >>>a = u'\xf0'
> > > >>>print a
> >
> > > This gives a unicode error.
> >
> > > Works fine in IDLE, PythonWin, and my Macbook but I need to run this
> > > from a windows batch.
> >
> > > Character should look like this "ð".
> >
> > > Please help!
> >
> > You forgot to paste the error.
>
> The error looks like this:
>File "
>File "C:\python25\lib\encodings\cp437.py", line 12, in encode
>  return codecs.charmap_encode(input,errors,encoding_map)
> UnicodeEncodeError: 'charmap' codec can't encode character u'\xf0' in
> position 0
> : character maps to 
>
>
> Running Python 2.5.4 on Windows XP



That isn't a python problem, it's a Windows problem. For "compatibility
reasons", Microsoft never added Unicode support to cmd.  When you do print
u'', python tries to convert the characters to the console encoding (the
really old cp437, not even the Windows standard cp1252), it messes up.
AFAIK, you'll have to use the chcp command to switch to an encoding that has
the character and then print u'\xf0'.encode(the_encoding) to get it to
display. There isn't any way around it- we've tried.


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


Re: Unexpected string behaviour: txt = 'this' ' works'

2009-02-11 Thread Jason
On Feb 11, 5:16 am, bearophileh...@lycos.com wrote:
> christopher.saun...@durham.ac.uk (c d saunter):
>
> >I assume it is a feature of the compiler.<
>
> Yes it's a bug-prone antifeature that's probably a relic from C that
> doesn't have a concatenation operator among strings as Python does
> (+). So in Python it saves you to use + at the cost of possible bugs.
>
> Bye,
> bearophile

I've used this feature in C and Python when I want to wrap strings
without having a newlines in the strings... grouping the whole bunch
with a set of parenthesis to make the concatenation explicit.
Admittedly, I wouldn't be broken up if this feature became deprecated,
as

It does do a minor optimization in Python and most C compilers.  The
two string constants are concatenated when the code is parsed, rather
than when the code is executed.

>>> from dis import dis
>>> def f():
...   return 'This is '  'an example.'
...
>>> dis(f)
  2   0 LOAD_CONST   1 ('This is an example.')
  3 RETURN_VALUE
>>>

It's such a minor optimization, that you probably wouldn't see any
effect on your program.

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


Re: Unicode issue on Windows cmd line

2009-02-11 Thread Karen Tracey
On Wed, Feb 11, 2009 at 2:50 PM, jeffg  wrote:

> On Feb 11, 2:35 pm, Albert Hopkins  wrote:
> > On Wed, 2009-02-11 at 10:35 -0800, jeffg wrote:
> > > Having issue on Windows cmd.
> > > > Python.exe
> > > >>>a = u'\xf0'
> > > >>>print a
> >
> > > This gives a unicode error.
> >
> > > Works fine in IDLE, PythonWin, and my Macbook but I need to run this
> > > from a windows batch.
> >
> > > Character should look like this "ð".
> >
> > > Please help!
> >
> > You forgot to paste the error.
>
> The error looks like this:
>File "
>File "C:\python25\lib\encodings\cp437.py", line 12, in encode
>  return codecs.charmap_encode(input,errors,encoding_map)
> UnicodeEncodeError: 'charmap' codec can't encode character u'\xf0' in
> position 0
> : character maps to 
>
>
> Running Python 2.5.4 on Windows XP
>

First, you may need to change your command prompt Properties->Font to use
Lucida Console rather than raster fonts.  Then you'll need to change the
code page using chcp to something that has a mapping for the character you
want. E.g.:

D:\>chcp
Active code page: 437

D:\>python
Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit (Intel)]
on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> a = u'\xf0'
>>> print a
Traceback (most recent call last):
  File "", line 1, in 
  File "D:\bin\Python2.5.2\lib\encodings\cp437.py", line 12, in encode
return codecs.charmap_encode(input,errors,encoding_map)
UnicodeEncodeError: 'charmap' codec can't encode character u'\xf0' in
position 0: character maps to 
>>> quit()

D:\>chcp 1252
Active code page: 1252

D:\>python
Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit (Intel)]
on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> a = u'\xf0'
>>> print a
ð
>>> quit()

D:\>

(Just changing the code page works to avoid the UnicodeEncodeError, but with
raster fonts that character displays as thee horizontal bars.)

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


Re: access to MS Access password-protected database?

2009-02-11 Thread Kenneth McDonald

Sorry for the vagueness.

I do have access to the file and can open it using Access. I haven't  
yet done anything involving Python and Access (or Python and Win  
interfacing, for that matter.)


Thanks,
Ken


On Feb 11, 2009, at 12:01 PM, imageguy wrote:


On Feb 11, 10:43 am, Ken McDonald 
wrote:

Can anyone direct me towards a code snippet showing how to use Python
to insert data into a password-protected MS Access database? My  
google

searches have been uninformative for dbs that are password-protected.

Thanks,
Ken


You post is a little vague on specifics
- do you actually have access to the db ?
- can you open it with access ?
- can you currently read records using python ?

I am assuming you don't have access to the db through python, once you
do the rest is straight forward.

I use DSN-less connections.  This link below is quite helpful
http://www.carlprothman.net/Default.aspx?tabid=90#ODBCDriverForAccess

If you aren't using the adodbapi (part of the pywin32 package), you
need to do something like this, assuming you access db is MS-Access
2000 and above.


import win32com
cnx = win32com.client.Dispatch('ADODB.connection')

parms = {}
parms['driver'] = '{Microsoft Access Driver (*.mdb)}'
parms['dbase'] = path_to_mdb
parms['sys_mdw'] = path_to_workgroup_security
parms['uid'] = userid_defined_in_mdw
parhs['pwd'] = pwd_for_uid_in_mdw

cnxtr = 'Driver=%(driver)s; DBQ=%(dbase)s; SYSTEMDB=%(sys_mdw)s; UID=%
(uid)s; PWD=%(pwd)s; ' % parms
cnx.ConnectionString = cnxstr
cnx.Open()


once you have an ADO Connection, execute SQL directly on the
connection like this

cnx.Execute('INSERT INTO tablename (col1, col2) VALUES ('val1,
val2);')

Or alternatively you should create RecordSets and manipulate these.

IF you need help understanding ADO I would recommend;
http://www.w3schools.com/ado/default.asp

The examples are translateable to Python.
You create recordsets via;
rs = win32com.client.Dispatch('ADO.RecordSet')


If you don't have/weren't given the passwords to the DB, but you do
have access to the workgroup file ('*.MDW') file that stores the uid/
pwds and permission, then there are several third party tools that
will recover these for you. Google is your friend.

If you don't have access to the original .mdw ... well, I can't help
you and I don't think anyone can.

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


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


Clearing the keyboard buffer (wxPython)

2009-02-11 Thread MarcusD

Platform: MSW (XP) Python 2.5 wxPython 2.8
Topic: Clear Keyboard buffer

Hi,
I hope I am not off topic asking a wxpython question.
I'm writing a Score counter for Dart games. The software
shows graphical output on a Canvas and accepts keyboard
input (no buttons, no widgest). A stripped version looks
like that:

self.Bind(wx.EVT_CHAR,OnKeyEvent)
.
.
#--
def OnKeyEvent(self, event):
  k =event.GetKeyCode()
  try:
z=chr(k)
  except:
return
  if (z in ["0","1","2","3","4","5","6","7","8","9",.."\r"..]:
self.keystr +=z
score=self.CalculateScore(self.keystr)
self.DisplayScore(score)
.
.
  if z== "\r" #enter
self.SayScore(score)
self.NextPlayer()
#--
def SayScore(self,number):
  if number > 100:
a=os.path.join(self.wavpath,"100.wav")
b=os.path.join(self.wavpath,"%i.wav"%(number-100))
  else:
a=os.path.join(self.wavpath,"%i.wav"%(number))
b=""
  sound1 = wx.Sound(a)
  sound2 = wx.Sound(b)
  sound1.Play(wx.SOUND_SYNC)
  if b:
sound2.HurryupandPlay(wx.SOUND_SYNC)
#--

The problem is, that during the voice output all keystrokes
are buffered somewhere and are processed when SayScore is
finished. So I have to clear the keyboard buffer at the end
of SayScore. Something like:

  evt=MagicFetchPendingKeyEventFunction()
  while evt:
evt=MagicFetchPendingKeyEventFunction()

I was thinking about threading (maybe using delayedresults), but
this might be a little oversized for my problem.
Playing the sound ASYNC doesn't work here.

Any ideas?
Thanks in advance
Marcus


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


Re: best way to serve wsgi with multiple processes

2009-02-11 Thread alex goretoy
GAE (Google App Engine) uses WSGI for webapps. You don't have to overhead of
managing a server and all it's services this way as well. Just manage dns
entries. Although, there are limitations depending on your project needs of
what libs you need to use.

appengine.google.com

-Alex Goretoy
http://www.goretoy.com



On Wed, Feb 11, 2009 at 1:59 PM, Graham Dumpleton <
graham.dumple...@gmail.com> wrote:

> On Feb 11, 8:50 pm, Robin  wrote:
> > Hi,
> >
> > I am building some computational web services using soaplib. This
> > creates a WSGI application.
> >
> > However, since some of these services are computationally intensive,
> > and may be long running, I was looking for a way to use multiple
> > processes. I thought about using multiprocessing.Process manually in
> > the service, but I was a bit worried about how that might interact
> > with a threaded server (I was hoping the thread serving that request
> > could just wait until the child is finished). Also it would be good to
> > keep the services as simple as possible so it's easier for people to
> > write them.
> >
> > I have at the moment the following WSGI structure:
> > TransLogger(URLMap(URLParser(soaplib objects)))
> > although presumably, due to the beauty of WSGI, this shouldn't matter.
> >
> > As I've found with all web-related Python stuff, I'm overwhelmed by
> > the choice and number of alternatives. I've so far been using cherrypy
> > and ajp-wsgi for my testing, but am aware of Spawning, twisted etc.
> > What would be the simplest [quickest to setup and fewest details of
> > the server required - ideally with a simple example] and most reliable
> > [this will eventually be 'in production' as part of a large scientific
> > project] way to host this sort of WSGI with a process-per-request
> > style?
>
> In this sort of situation one wouldn't normally do the work in the
> main web server, but have a separarte long running daemon process
> embedding mini web server that understands XML-RPC. The main web
> server would then make XML-RPC requests against the backend daemon
> process, which would use threading and or queueing to handle the
> requests.
>
> If the work is indeed long running, the backend process would normally
> just acknowledge the request and not wait. The web page would return
> and it would be up to user to then somehow occassionally poll web
> server, manually or by AJAX, to see how progres is going. That is,
> further XML-RPC requests from main server to backend daemon process
> asking about progress.
>
> I do't believe the suggestions about fastcgi/scgi/ajp/flup or mod_wsgi
> are really appropriate as you don't want this done in web server
> processes as then you are at mercy of web server processes being
> killed or dying when part way through something. Some of these systems
> will do this if requests take too long. Thus better to offload real
> work to another process.
>
> Graham
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: hpw to convert a linux python script ?

2009-02-11 Thread Alec Schueler
On Feb 11, 7:58 pm, Stef Mientki  wrote:
> As there are a whole lot of these lines, in a whole lot of files,
> I wonder if there's a simple trick to point
>   /usr/share/tinybldLin/
> to my directory ?
>
> thanks,
> Stef

Find and replace?
--
http://mail.python.org/mailman/listinfo/python-list


Re: hpw to convert a linux python script ?

2009-02-11 Thread Stef Mientki

Alec Schueler wrote:

On Feb 11, 7:58 pm, Stef Mientki  wrote:
  

As there are a whole lot of these lines, in a whole lot of files,
I wonder if there's a simple trick to point
  /usr/share/tinybldLin/
to my directory ?

thanks,
Stef



Find and replace?
  

well I was thinking of a more elegant way,
so the scripts remains, or better become multi-platform.

anyway thanks,
Stef

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


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


Re: Clearing the keyboard buffer (wxPython)

2009-02-11 Thread Mike Driscoll
On Feb 11, 2:28 pm, "MarcusD"  wrote:
> Platform: MSW (XP) Python 2.5 wxPython 2.8
> Topic: Clear Keyboard buffer
>
> Hi,
> I hope I am not off topic asking a wxpython question.
> I'm writing a Score counter for Dart games. The software
> shows graphical output on a Canvas and accepts keyboard
> input (no buttons, no widgest). A stripped version looks
> like that:
>
> self.Bind(wx.EVT_CHAR,OnKeyEvent)
> .
> .
> #--
>     def OnKeyEvent(self, event):
>       k =event.GetKeyCode()
>       try:
>         z=chr(k)
>       except:
>         return
>       if (z in ["0","1","2","3","4","5","6","7","8","9",.."\r"..]:
>         self.keystr +=z
>         score=self.CalculateScore(self.keystr)
>         self.DisplayScore(score)
>         .
>         .
>       if z== "\r" #enter
>         self.SayScore(score)
>         self.NextPlayer()
> #--
>     def SayScore(self,number):
>       if number > 100:
>         a=os.path.join(self.wavpath,"100.wav")
>         b=os.path.join(self.wavpath,"%i.wav"%(number-100))
>       else:
>         a=os.path.join(self.wavpath,"%i.wav"%(number))
>         b=""
>       sound1 = wx.Sound(a)
>       sound2 = wx.Sound(b)
>       sound1.Play(wx.SOUND_SYNC)
>       if b:
>         sound2.HurryupandPlay(wx.SOUND_SYNC)
> #--
>
> The problem is, that during the voice output all keystrokes
> are buffered somewhere and are processed when SayScore is
> finished. So I have to clear the keyboard buffer at the end
> of SayScore. Something like:
>
>   evt=MagicFetchPendingKeyEventFunction()
>   while evt:
>     evt=MagicFetchPendingKeyEventFunction()
>
> I was thinking about threading (maybe using delayedresults), but
> this might be a little oversized for my problem.
> Playing the sound ASYNC doesn't work here.
>
> Any ideas?
> Thanks in advance
> Marcus
It's fine to post here with wxPython questions, but I would recommend
the official wxPython mailing list in most cases as it has lots of
experienced users and developers on it: http://wxpython.org/maillist.php

I've never done this sort of thing with wxPython, but you may be able
to use wx.Yield somehow. There are various tips and tricks in the wiki
about working around long running processes that block the GUI's
mainloop here:

http://wiki.wxpython.org/LongRunningTasks

Other than that, I would recommend doing this with pygame or pyglet as
they might be easier to use for this use-case. Here are their sites:

http://www.pyglet.org/
http://www.pygame.org/news.html

HTH

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


Re: Clearing the keyboard buffer (wxPython)

2009-02-11 Thread MarcusD
Whow. Thanks for the fast and comprehensive answer. To be honest I would 
have posted to wxpython.org but the server seems to be down for the last 
couple of days.

I'll check this wx.Yield thing that I never heard of. And let's see what 
else we get here.
Thanks again
marcus 


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


Re: Unicode issue on Windows cmd line

2009-02-11 Thread Martin v. Löwis
> Having issue on Windows cmd.
>> Python.exe
 a = u'\xf0'
 print a
> 
> This gives a unicode error.
> 
> Works fine in IDLE, PythonWin, and my Macbook but I need to run this
> from a windows batch.
> 
> Character should look like this "ð".
> 
> Please help!

Well, your terminal just cannot display this character by default; you
need to use a different terminal program, or reconfigure your terminal.

For example, do

chcp 1252

and select Lucida Console as the terminal font, then try again.

Of course, this will cause *different* characters to become
non-displayable.

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


Re: Unexpected string behaviour: txt = 'this' ' works'

2009-02-11 Thread bearophileHUGS
Jason:
> It's such a minor optimization, that you probably wouldn't see any
> effect on your program.

>>> from dis import dis
>>> def f():
...  return 'This is ' + 'an example.'
...
>>> dis(f)
  2   0 LOAD_CONST   3 ('This is an example.')
  3 RETURN_VALUE

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


Re: hpw to convert a linux python script ?

2009-02-11 Thread rdmurray
Stef Mientki  wrote:
> Alec Schueler wrote:
> > On Feb 11, 7:58 pm, Stef Mientki  wrote:
> >   
> >> As there are a whole lot of these lines, in a whole lot of files,
> >> I wonder if there's a simple trick to point
> >>   /usr/share/tinybldLin/
> >> to my directory ?
> >>
> >> thanks,
> >> Stef
> >> 
> >
> > Find and replace?
> >   
> well I was thinking of a more elegant way,
> so the scripts remains, or better become multi-platform.
> 
> anyway thanks,

Well, you'll have to rewrite the script so that it doesn't make
assumptions about path names, and we can't help you with that without
seeing some of the script code.  There _might_ be easy fixes, but if the
path is hardcoded in many places in the script...then you will just have
to go through and un-hard-code it.

--RDM

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


Re: hpw to convert a linux python script ?

2009-02-11 Thread Benjamin Kaplan
On Wed, Feb 11, 2009 at 3:48 PM, Stef Mientki wrote:

> Alec Schueler wrote:
>
>> On Feb 11, 7:58 pm, Stef Mientki  wrote:
>>
>>
>>> As there are a whole lot of these lines, in a whole lot of files,
>>> I wonder if there's a simple trick to point
>>>  /usr/share/tinybldLin/
>>> to my directory ?
>>>
>>> thanks,
>>> Stef
>>>
>>>
>>
>> Find and replace?
>>
>>
> well I was thinking of a more elegant way,
> so the scripts remains, or better become multi-platform.



That's the problem with using external files- unless you can get to the file
by some combination of os and os.path functions, you're pretty much stuck
checking os.name and/or sys.platform and choosing filenames based on that.
--
http://mail.python.org/mailman/listinfo/python-list


Re: re.sub and named groups

2009-02-11 Thread Paul McGuire
On Feb 4, 10:51 am, "Emanuele D'Arrigo"  wrote:
> Hi everybody,
>
> I'm having a ball with the power of regular expression

Don't forget the ball you can have with the power of ordinary Python
strings, string methods, and string interpolation!

originalString = "spam:%(first)s ham:%(second)s"
print originalString % { "first" : "foo" , "second" : "" }

prints

spam:foo ham:

with far fewer surprises and false steps.  (Note: Py3K supports this
same feature, but with different interpolation syntax, which I have
not learned yet.)

Book recommendation: Text Processing in Python, by David Mertz (free
online - http://gnosis.cx/TPiP/), in which David advises against
dragging out the RE heavy artillery until you've at least thought
about using ordinary string methods.

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


Re: Clearing the keyboard buffer (wxPython)

2009-02-11 Thread Mike Driscoll
On Feb 11, 2:54 pm, "MarcusD"  wrote:
> Whow. Thanks for the fast and comprehensive answer. To be honest I would
> have posted to wxpython.org but the server seems to be down for the last
> couple of days.
>
> I'll check this wx.Yield thing that I never heard of. And let's see what
> else we get here.
> Thanks again
> marcus

Is it? I wondered why I had suddenly stopped getting emails from them,
but my company recently had some email config changes that blocked a
ton of stuff and I just figured that was part of the problem.
Hopefully Robin Dunn can put the smack down on his web hosts...

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


Re: Unicode issue on Windows cmd line

2009-02-11 Thread Benjamin Kaplan
On Wed, Feb 11, 2009 at 3:57 PM, "Martin v. Löwis" wrote:

> > Having issue on Windows cmd.
> >> Python.exe
>  a = u'\xf0'
>  print a
> >
> > This gives a unicode error.
> >
> > Works fine in IDLE, PythonWin, and my Macbook but I need to run this
> > from a windows batch.
> >
> > Character should look like this "ð".
> >
> > Please help!
>
> Well, your terminal just cannot display this character by default; you
> need to use a different terminal program, or reconfigure your terminal.
>
> For example, do
>
> chcp 1252
>
> and select Lucida Console as the terminal font, then try again.
>
> Of course, this will cause *different* characters to become
> non-displayable.


Well,

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


Re: Unicode issue on Windows cmd line

2009-02-11 Thread Benjamin Kaplan
On Wed, Feb 11, 2009 at 4:10 PM, Benjamin Kaplan
wrote:

>
>
> On Wed, Feb 11, 2009 at 3:57 PM, "Martin v. Löwis" wrote:
>
>> > Having issue on Windows cmd.
>> >> Python.exe
>>  a = u'\xf0'
>>  print a
>> >
>> > This gives a unicode error.
>> >
>> > Works fine in IDLE, PythonWin, and my Macbook but I need to run this
>> > from a windows batch.
>> >
>> > Character should look like this "ð".
>> >
>> > Please help!
>>
>> Well, your terminal just cannot display this character by default; you
>> need to use a different terminal program, or reconfigure your terminal.
>>
>> For example, do
>>
>> chcp 1252
>>
>> and select Lucida Console as the terminal font, then try again.
>>
>> Of course, this will cause *different* characters to become
>> non-displayable.
>
>
> Well,
>

Whoops. Didn't mean to hit send there. I was going to say, you can't have
everything when Microsoft is only willing to break the programs that average
people are going to use on a daily basis. I mean, why would they do
something nice for the international community at the expense of breaking
some 20 year old batch scripts? Those were the only things that still worked
when Vista first came out.



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


Re: Avoiding argument checking in recursive calls

2009-02-11 Thread Terry Reedy

andrew cooke wrote:

Terry Reedy wrote:

Reverse the test order

def fact(n):
 if n > 0: return fact(n-1)*n
 if n == 0: return 1
 raise ValueError


sweet!  but is this generally possible?


I believe so, for some meaning of 'generally'.

> ie: did you think this up for

this question or is it an idiom that you find yourself using often?


It is an idiom I developed for an algorithm book-in-progress that will 
include  detailed comparisons of 'body' recursive (my term for 'not tail 
recursive", such as fact() above), tail recursive, and iterative 
versions of algorithms.


Here are written-for-didactic-purposes tail and iterative versions of 
fact that are computationally equivalent to the above in that they 
compute the same expression, (...((1*1)*2)**n), without commutative 
or associative transformation, and raise the same error (expanded).


def fact_tail(n, i=0, res=1):
if i < n: return fact_tail(n, i+1, res*(i+1))
if i == n: return res
raise ValueError("Input negative or non-integral")

def fact_iter(n, i=0, res=1):
while i < n: i,res = i+1, res*(i+1)
if i == n: return res
raise ValueError("Input negative or non-integral")

My original reason for writing the tail recursion in the same reversed 
order was to make the conversion to iteration as obvious as possible. 
But I them noticed that it also made possible 'test once for bad input 
without a separate function."


Terry Jan Reedy

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


Re: hpw to convert a linux python script ?

2009-02-11 Thread John Machin
On Feb 12, 7:48 am, Stef Mientki  wrote:
> Alec Schueler wrote:
> > On Feb 11, 7:58 pm, Stef Mientki  wrote:
>
> >> As there are a whole lot of these lines, in a whole lot of files,
> >> I wonder if there's a simple trick to point
> >>   /usr/share/tinybldLin/
> >> to my directory ?
>
> >> thanks,
> >> Stef
>
> > Find and replace?
>
> well I was thinking of a more elegant way,
> so the scripts remains, or better become multi-platform.

Your current setup is not even single-platform portable ... consider
the scenario where some Linux admin wants your gear to live in some
directory other than /usr/share/tinybldLin/

The standard technique for ensuring that kind of portability involves:
1. Find the directory in which your script lives. Inspect sys.argv[0],
use some os.path.some_functionality() to extract the directory, name
it (say) home_base.
2. When you want to open a data file in the script's directory, do
this:
   the_path = os.path.join(home_base, 'stef1.dat')
   f = open(the_path, .)

NOTE: Use os.path.join() instead of some DIY technique; it knows
better than you what the path separator is on the OS it's being run
on. In fact, read the whole of the os.path manual carefully before you
jump in to changing your code.

If you prefer to have the data files in (say) .../script_locn/data
instead of .../script_locn, the adjustment should be obvious.

Unfortunately, you are still going to need use find and replace to fix
your script. Code in haste, repent at leisure :-)

HTH,
John



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


  1   2   >