Re: How to do relpath implementation on 2.5

2009-08-09 Thread ryles
On Aug 8, 9:08 pm, Brian Allen Vanderburg II
 wrote:
> I've coded my own 'relpath' implementation for 2.5 (shown below) and I
> want to make sure it follows as closely as it should to 2.6 and later.  
> I've got a question regarding that.  When attempting to convert to a
> relative path and it is not possible for some reason (different drive or
> UNC share), should that be an error or should it return the absolute
> path of the target?  I'm using Debian so I don't have 2.6 available
> right now for testing.

Usually Python source code is easily browsed at:

http://svn.python.org/view/

Unfortunately the server is down right now.

The implementation in 2.6 raises a ValueError exception. Here is the
function from ntpath.py:

def relpath(path, start=curdir):
"""Return a relative version of a path"""

if not path:
raise ValueError("no path specified")
start_list = abspath(start).split(sep)
path_list = abspath(path).split(sep)
if start_list[0].lower() != path_list[0].lower():
unc_path, rest = splitunc(path)
unc_start, rest = splitunc(start)
if bool(unc_path) ^ bool(unc_start):
raise ValueError("Cannot mix UNC and non-UNC paths (%s and
%s)"
%
(path, start))
else:
raise ValueError("path is on drive %s, start on drive %s"
% (path_list[0],
start_list[0]))
# Work out how much of the filepath is shared by start and path.
for i in range(min(len(start_list), len(path_list))):
if start_list[i].lower() != path_list[i].lower():
break
else:
i += 1

rel_list = [pardir] * (len(start_list)-i) + path_list[i:]
if not rel_list:
return curdir
return join(*rel_list)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: unicode() vs. s.decode()

2009-08-09 Thread Jeroen Ruigrok van der Werven
-On [20090808 20:07], Thorsten Kampe (thors...@thorstenkampe.de) wrote:
>In real life people won't even notice whether an application takes one or
>two minutes to complete.

I think you are quite wrong here.

I have worked with optical engineers who needed to calculate grating numbers
for their lenses. If they can have a calculation program that runs in 1
minute instead of 2 they can effectively double their output during the day
(since they run calculations hundreds to thousand times a day to get the
most optimal results with minor tweaks).

I think you are being a bit too easy on hand waving here that mere minute
runtimes are not noticeable.

-- 
Jeroen Ruigrok van der Werven  / asmodai
イェルーン ラウフロック ヴァン デル ウェルヴェン
http://www.in-nomine.org/ | http://www.rangaku.org/ | GPG: 2EAC625B
When we have not what we like, we must like what we have...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why all the __double_underscored_vars__?

2009-08-09 Thread Steven D'Aprano
On Sat, 08 Aug 2009 12:11:19 +, kj wrote:

> In  Chris Rebert
>  writes:
> 
>>The double-underscores indicate that the Python interpreter itself
>>usually is the caller of the method, and as such some level of "magic"
>>may be associated with it. Other languages have you do the equivalent of
>>`def +():` or `def operator +()` to override an operator, the keyword or
>>symbol serving a similar warning that "here be magic".
> 
> In this case, then I hope that some of these __items__ get demoted to a
> more mundane level, so that the notion of "magic" doesn't get
> trivialized by everyday idioms like:
> 
> if __name__ == '__main__':
> # etc

But that is magic, and just because it's magic doesn't mean it's not 
useful every day.

I don't see what's so difficult about telling your students that double 
underscore names have special meaning to the Python interpreter. That 
doesn't mean you're forbidden from using them, or that you have to use 
them, it just means that they have a special meaning to the interpreter, 
and you usually don't call them directly.



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


Re: Python docs disappointing - group effort to hire writers?

2009-08-09 Thread Steven D'Aprano
On Sat, 08 Aug 2009 20:27:49 +0100, Mark Lawrence wrote:

> Further, I have seen many requests here which are nothing really to do
> with Python, say a query about which algorithm to use.  Response "Not
> really a Python question, but try ...".  Put the same question on (say)
> the C ng and you'd be told in no uncertain terms to Foxtrot Oscar.

We're a lot friendlier than the C newsgroup.

Personally, I think knowing the right algorithm to use is as much a part 
of Python programming as knowing whether to call mystring.upper() or 
string.upper(mystring).


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


tracing openurl input and output?

2009-08-09 Thread mh
How can I watch the messages being sent back and for on urllib shttp
requests?  If it were simple http I would just watch the socket traffic
but of course that won't work for https.  Is there a debug flag I can
set that will do this?

context:  I am dealing with a web service bug and I want to tell
the provider exactly what is going back and forth to his server,
eliminating the "maybe there's a bug in your library" chat.

import urllib
params = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})
f = urllib.urlopen("https://example.com/cgi-bin/query";, params)

Many TIA!

-- 
Mark Harrison
Pixar Animation Studios
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: unicode() vs. s.decode()

2009-08-09 Thread Steven D'Aprano
On Sat, 08 Aug 2009 19:00:11 +0200, Thorsten Kampe wrote:

>> I was running it one million times to mitigate influences on the timing
>> by other background processes which is a common technique when
>> benchmarking.
> 
> Err, no. That is what "repeat" is for and it defaults to 3 ("This means
> that other processes running on the same computer may interfere with the
> timing. The best thing to do when accurate timing is necessary is to
> repeat the timing a few times and use the best time. [...] the default
> of 3 repetitions is probably enough in most cases.")


It's useful to look at the timeit module to see what the author(s) think.

Let's start with the repeat() method. In the Timer docstring:

"The repeat() method is a convenience to call timeit() multiple times and 
return a list of results."

and the repeat() method's own docstring:

"This is a convenience function that calls the timeit() repeatedly, 
returning a list of results.  The first argument specifies how many times 
to call timeit(), defaulting to 3; the second argument specifies the 
timer argument, defaulting to one million."

So it's quite obvious that the module author(s), and possibly even Tim 
Peters himself, consider repeat() to be a mere convenience method. 
There's nothing you can do with repeat() that can't be done with the 
timeit() method itself.

Notice that both repeat() and timeit() methods take an argument to 
specify how many times to execute the code snippet. Why not just execute 
it once? The module doesn't say, but the answer is a basic measurement 
technique: if your clock is accurate to (say) a millisecond, and you 
measure a single event as taking a millisecond, then your relative error 
is roughly 100%. But if you time 1000 events, and measure the total time 
as 1 second, the relative error is now 0.1%.

The authors of the timeit module obvious considered this an important 
factor: not only did they allow you to specify the number of times to 
execute the code snippet (defaulting to one million, not to one) but they 
had this to say:

[quote]
Command line usage:
python timeit.py [-n N] [-r N] [-s S] [-t] [-c] [-h] [statement]

Options:
  -n/--number N: how many times to execute 'statement'
 [...]

If -n is not given, a suitable number of loops is calculated by trying
successive powers of 10 until the total time is at least 0.2 seconds.
[end quote]

In other words, when calling the timeit module from the command line, by 
default it will choose a value for n that gives a sufficiently small 
relative error.

It's not an accident that timeit gives you two "count" parameters: the 
number of times to execute the code snippet per timing, and the number of 
timings. They control (partly) for different sources of error.



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


Re: tracing openurl input and output?

2009-08-09 Thread Duncan Booth
m...@pixar.com wrote:

> How can I watch the messages being sent back and for on urllib shttp
> requests?  If it were simple http I would just watch the socket traffic
> but of course that won't work for https.  Is there a debug flag I can
> set that will do this?
> 
> context:  I am dealing with a web service bug and I want to tell
> the provider exactly what is going back and forth to his server,
> eliminating the "maybe there's a bug in your library" chat.
> 
> import urllib
> params = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})
> f = urllib.urlopen("https://example.com/cgi-bin/query";, params)
> 
> Many TIA!
> 
If you are running on Windows then I'd say get hold of a copy of fiddler2 
(http://www.fiddler2.com/fiddler2/) and tell your code to use it as a 
proxy. It does an excellent job of capturing and decoding web traffic and 
even lets you modify packets as they go past. The only thing to watch for 
with https is that your code will see an invalid certificate as of course 
it sees fiddler's own self signed certificate instead of the original.

I'm not sure what Linux or Mac equivalents there might be (though in a 
pinch you can always run your code on one system and Fiddler on a different 
one).
-- 
http://mail.python.org/mailman/listinfo/python-list


String algo

2009-08-09 Thread nipun batra
I will be receiving data serially from another pc,.i can use any sort of
marker between two packets,i will be the person sending data as well after
reading it from some devices.But packet length is not constant.
each packet has this format:
201.535a56.65b4.56c89.565d
another packet could be :
4a5b6c7d
What i need is a program to store variables such as:var_a has value 4,var_b
has value 5,for second string.
I have to read and write data continuosly using serial port.
-- 
http://mail.python.org/mailman/listinfo/python-list


Need help in configuration for TimedRotatingFileHandler

2009-08-09 Thread Lokesh
Hi,

Need help in configure the TimedRotatingFileHandler from configuration
file

I have tried with the below code and ended up with the error, code is
pasted below
Error - IOError: [Errno 2] No such file or directory: 'G:\\lok_sib\
\logs\rotate_test'
[loggers]
keys=root,simpleExample

[handlers]
keys=consoleHandler,timedRotatingFileHandler

[formatters]
keys=simpleFormatter

[logger_root]
level=DEBUG
handlers=consoleHandler

[logger_simpleExample]
level=DEBUG
handlers=timedRotatingFileHandler
qualname=simpleExample
propagate=0

[handler_consoleHandler]
class=StreamHandler
level=DEBUG
formatter=simpleFormatter
args=(sys.stdout,)

[handler_timedRotatingFileHandler]
class=handlers.TimedRotatingFileHandler
level=DEBUG
formatter=simpleFormatter
args=("G:\lok_sib\logs\rotate_test", 'midnight', 1)

[formatter_simpleFormatter]
format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
datefmt='%Y-%m-%d %H:%M:%S'


Thanks or your time
Regards,
Lokesh
-- 
http://mail.python.org/mailman/listinfo/python-list


resume upload wsgi script

2009-08-09 Thread gert
I working on a resume upload script and encountered the following
problems

sql: Could not decode to UTF-8 column 'SUBSTR(picture,?)' with text
'\ufffd\ufff
d\ufffd\ufffd↑!ExifEf1gL6KM7Ij5ae0gL6KM7cH2cH2GI3
Content-Disposition: form-data; name="Filename"

DSC00013.JPG
Ef1

when I dont use SUBSTR or  COALESCE and || it works

def application(environ, response):
range=environ.get('HTTP_RANGE','bytes=0-').replace
('bytes=','').split(',')
offset=[]
for r in range: offset.append(r.split('-'))
db.execute('UPDATE users SET picture=SUBSTR(picture,?) WHERE
uid=?', (offset[0][0],s.UID))

chunk=environ['wsgi.input'].read(int(environ
['CONTENT_LENGTH'])).decode('latin1')
db.execute('UPDATE users SET picture=COALESCE(picture,?)||? WHERE
uid=?', (''.encode('latin1'),chunk.encode('latin1'), s.UID))

#while True:
#  chunk=environ['wsgi.input'].read(8192).decode('latin1')
#  if not chunk: break
#  db.execute("UPDATE users SET picture=COALESCE
(picture,'')||? WHERE uid=?", (chunk, s.UID))

the following is the POST clean up when PUT is not used, does anyone
know how to do this without loading the complete blob into memory ?

db.execute('SELECT picture FROM users WHERE uid=?',(s.UID,))
f=db.fetch()
b=environ['CONTENT_TYPE'].split('boundary=')[1]
p=search(b+r'.*?Content-Type: application/octet-stream\r\n\r\n(.*?)
\r\n--'+b,f[0][0].decode('latin1'),DOTALL).group(1)
db.execute('UPDATE users SET picture=? WHERE uid=?', (p.encode
('latin1'), s.UID))

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


exec("dir()",d)

2009-08-09 Thread Emanuele D'Arrigo
Greetings everybody,

I don't quite understand why if I do this:

>>> d = {}
>>> exec("dir()", d)

1) d is no longer empty
2) the content of d now looks like __builtins__.__dict__ but isn't
quite it d == __builtins__.__dict__ returns false.

Can anybody shed some light?

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


Re: exec("dir()",d)

2009-08-09 Thread Mel
Emanuele D'Arrigo wrote:

> Greetings everybody,
> 
> I don't quite understand why if I do this:
> 
 d = {}
 exec("dir()", d)
> 
> 1) d is no longer empty
> 2) the content of d now looks like __builtins__.__dict__ but isn't
> quite it d == __builtins__.__dict__ returns false.
> 
> Can anybody shed some light?

You should check up on what exec does.  In this case it runs a string 
containing code using dictionary `d` as its global namespace, and so `d` has 
to contain the usual global namespace symbols -- otherwise `dict` can't 
work.  `__builtins__.__dict__ is one of the elements in the global 
namespace, not the namespace itself.  Another example:


Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41) 
[GCC 4.3.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> a=7
>>> d={'b':a}
>>> exec ("print b", d)
7
>>> d
{'__builtins__': {'bytearray': , 'IndexError': , 'all': , 'help': Type 
help() for interactive help, or help(object) for help about object., 'vars': 
, 'SyntaxError': , 
'unicode': , 'UnicodeDecodeError': , 'isinstance': , 'copyright': Copyright (c) 2001-2009 Python Software 
Foundation.
[ ... ]
'AssertionError': , 'classmethod': , 'UnboundLocalError': , 
'NotImplementedError': , 
'AttributeError': , 'OverflowError': }, 'b': 7}
>>> 

To get rid of the name error, you'd need
d={}
d['d'] = d
exec ("dir (d)", d)


Mel.

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


Re: exec("dir()",d)

2009-08-09 Thread Christian Heimes

Emanuele D'Arrigo schrieb:

Greetings everybody,

I don't quite understand why if I do this:


d = {}
exec("dir()", d)


1) d is no longer empty
2) the content of d now looks like __builtins__.__dict__ but isn't
quite it d == __builtins__.__dict__ returns false.

Can anybody shed some light?


RTFM helps ;) http://docs.python.org/reference/simple_stmts.html#exec

As a side effect, an implementation may insert additional keys into the 
dictionaries given besides those corresponding to variable names set by 
the executed code. For example, the current implementation may add a 
reference to the dictionary of the built-in module __builtin__ under the 
key __builtins__ (!).


Christian

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


Re: Serial port access

2009-08-09 Thread Hendrik van Rooyen
On Sunday 09 August 2009 03:20:12 nipun batra wrote:
> On Sun, Aug 9, 2009 at 2:11 AM, Chris Rebert  wrote:
> > On Sat, Aug 8, 2009 at 12:34 PM, nipun batra
> >
> > wrote:
> > > Hi,
> > > How can we access serial port using usb-serial converters,using python
> > > in linux.
> >
> > PySerial might also be an option:
> > http://pyserial.sourceforge.net/index.html
> >
> > Cheers,
> > Chris
> > --
> > http://blog.rebertia.com
>
> pySerial mentions about serial ports but not about usb-serial.Can i do
> something like convert my usb-serial to act as serial port and then use
> pySerial

You can also look in the /dev directory to see which tty is created when you
plug in the usb to serial converter, and use that /dev/ttySx as a file, 
reading and writing to it directly.

You will need this information whatever you do, as you will need to specify
which port to use, to whatever software you choose to use.

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


setting Referer for urllib.urlretrieve

2009-08-09 Thread samwyse
Here's what I have so far:

import urllib

class AppURLopener(urllib.FancyURLopener):
version = "App/1.7"
referrer = None
def __init__(self, *args):
urllib.FancyURLopener.__init__(self, *args)
if self.referrer:
addheader('Referer', self.referrer)

urllib._urlopener = AppURLopener()

Unfortunately, the 'Referer' header potentially varies for each url
that I retrieve, and the way the module is written, I can't change the
calls to __init__ or open. The best idea I've had is to assign a new
value to my class variable just before calling urllib.urlretrieve(),
but that just seems ugly.  Any ideas?  Thanks.

PS for anyone not familiar with the RFCs:  Yes, I'm spelling
"referrer" correctly everywhere in my code.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: resume upload wsgi script

2009-08-09 Thread Diez B. Roggisch

gert schrieb:

I working on a resume upload script and encountered the following
problems

sql: Could not decode to UTF-8 column 'SUBSTR(picture,?)' with text
'\ufffd\ufff
d\ufffd\ufffd↑!ExifEf1gL6KM7Ij5ae0gL6KM7cH2cH2GI3
Content-Disposition: form-data; name="Filename"


You are treating a binary data column as if it were a string. That's 
bogus, you need to use a blob column.


Also I wouldn't combine the uplodaded chunks until the full upload is 
finished - and even then only if I actually need the data.


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


Re: resume upload wsgi script

2009-08-09 Thread gert
On Aug 9, 3:17 pm, "Diez B. Roggisch"  wrote:
> gert schrieb:
>
> > I working on a resume upload script and encountered the following
> > problems
>
> > sql: Could not decode to UTF-8 column 'SUBSTR(picture,?)' with text
> > '\ufffd\ufff
> > d\ufffd\ufffd↑!ExifEf1gL6KM7Ij5ae0gL6KM7cH2cH2GI3
> > Content-Disposition: form-data; name="Filename"
>
> You are treating a binary data column as if it were a string. That's
> bogus, you need to use a blob column.
>
> Also I wouldn't combine the uplodaded chunks until the full upload is
> finished - and even then only if I actually need the data.
>
> Diez

And the best solution would be to use TEXT instead or some sort of
SUBBIN that i do not know of in sqlite ?

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


Re: setting Referer for urllib.urlretrieve

2009-08-09 Thread Steven D'Aprano
On Sun, 09 Aug 2009 06:13:38 -0700, samwyse wrote:

> Here's what I have so far:
> 
> import urllib
> 
> class AppURLopener(urllib.FancyURLopener):
> version = "App/1.7"
> referrer = None
> def __init__(self, *args):
> urllib.FancyURLopener.__init__(self, *args)
> if self.referrer:
> addheader('Referer', self.referrer)
> 
> urllib._urlopener = AppURLopener()
> 
> Unfortunately, the 'Referer' header potentially varies for each url that
> I retrieve, and the way the module is written, I can't change the calls
> to __init__ or open. The best idea I've had is to assign a new value to
> my class variable just before calling urllib.urlretrieve(), but that
> just seems ugly.  Any ideas?  Thanks.

[Aside: an int variable is an int. A str variable is a str. A list 
variable is a list. A class variable is a class. You probably mean a 
class attribute, not a variable. If other languages want to call it a 
variable, or a sausage, that's their problem.]

If you're prepared for a bit of extra work, you could take over all the 
URL handling instead of relying on automatic openers. This will give you 
much finer control, but it will also require more effort on your part. 
The basic idea is, instead of installing openers, and then ask the urllib 
module to handle the connection, you handle the connection yourself:

make a Request object using urllib2.Request
make an Opener object using urllib2.build_opener
call opener.open(request) to connect to the server
deal with the connection (retry, fail or read)

Essentially, you use the Request object instead of a URL, and you would 
add the appropriate referer header to the Request object.

Another approach, perhaps a more minimal change than the above, would be 
something like this:

# untested
class AppURLopener(urllib.FancyURLopener):
version = "App/1.7"
def __init__(self, *args):
urllib.FancyURLopener.__init__(self, *args)
def add_referrer(self, url=None):
if url:
addheader('Referer', url)

urllib._urlopener = AppURLopener()
urllib._urlopener.add_referrer("http://example.com/";)



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


Re: resume upload wsgi script

2009-08-09 Thread Diez B. Roggisch

gert schrieb:

On Aug 9, 3:17 pm, "Diez B. Roggisch"  wrote:

gert schrieb:


I working on a resume upload script and encountered the following
problems
sql: Could not decode to UTF-8 column 'SUBSTR(picture,?)' with text
'\ufffd\ufff
d\ufffd\ufffd↑!ExifEf1gL6KM7Ij5ae0gL6KM7cH2cH2GI3
Content-Disposition: form-data; name="Filename"

You are treating a binary data column as if it were a string. That's
bogus, you need to use a blob column.

Also I wouldn't combine the uplodaded chunks until the full upload is
finished - and even then only if I actually need the data.

Diez


And the best solution would be to use TEXT instead or some sort of
SUBBIN that i do not know of in sqlite ?



No, the best solution would be to use "BLOB", and no SUB*-stuff, but 
instead a 1:n-relation of chunks, that when the upload is finished you 
can easily combine in python to one large blob, storing that in the DB 
again.


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


Re: Need help in configuration for TimedRotatingFileHandler

2009-08-09 Thread Kushal Kumaran
On Sun, Aug 9, 2009 at 5:13 PM, Lokesh wrote:
> Hi,
>
> Need help in configure the TimedRotatingFileHandler from configuration
> file
>
> I have tried with the below code and ended up with the error, code is
> pasted below
> Error - IOError: [Errno 2] No such file or directory: 'G:\\lok_sib\
> \logs\rotate_test'

Does the directory G:\\lok_sib\\logs exist?

> 

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


Re: Need help in configuration for TimedRotatingFileHandler

2009-08-09 Thread Jan Kaliszewski

09-08-2009 Lokesh  wrote:


I have tried with the below code and ended up with the error, code is
pasted below
Error - IOError: [Errno 2] No such file or directory: 'G:\\lok_sib\
\logs\rotate_test'


Note that: '\r' is listed (interpreted by Python as 'carriage return'
special character) and not '\\r' (which would mean '\' char + 'r' char).

Regards,
*j

--
Jan Kaliszewski (zuo) 
--
http://mail.python.org/mailman/listinfo/python-list


Twisted - how to get text for HTTP error responses

2009-08-09 Thread koranthala
Hi,
   I am writing a HTTP client in Twisted. The client contacts the
server, and any errors in the sent messages will be returned back to
the client in 400 message. The reason for failure at the server is
sent as the text in the 400 message. I tried the same using the
browser, and I can see the error text (the text might be like - 'Item
X not found in DB').
   The client is supposed to use this text and calculate the next
messages to be sent to the server. But, I cannot seem to find a
mechanism to get the response text from the errback. I went through
failure.py, but I couldnt find a way to do it.
   Ex:
I send a data to the server as so
d = defer.waitForDeferred(getPage(url, method='POST', headers=hdr,
postdata=form))
yield d
try:
   reply = d.getResult()
   success(reply)
except Error, failure:
   failure(failure)

Now, inside failure method, I was unable to print the text out - say
'Item X not found in DB'.
Is it possible using Twisted? If so, how can it be done?

Thanks in Advance
K

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


Re: Bug or feature: double strings as one

2009-08-09 Thread r
On Aug 8, 12:43 pm, "Jan Kaliszewski"  wrote:
> 08-08-2009 Steven D'Aprano  wrote:
...(snip)
> I use it very often, e.g.:
>
>          afunction('quite long string %s quite long string '
>                    'quite long string quite long string %s '
>                    'quite %s long string quite long string'
>                    % (variable1, variable2, variable3))
>
> It seems nicer to me than:
>
>          afunction(('quite long string %s quite long string '
>                     + 'quite long string quite long string %s '
>                     + 'quite %s long string quite long string')
>                    % (variable1, variable2, variable3))
>
> (Note that multiline-'''-strings are usless in such cases).
>

uhh? A much better way to handle such a problem is like this...

prompt1 = '''
Some people like to use %s
ways of doing things just
so they can support their %s
way of coding
'''

afunction(prompt1 %(var1, var2))

WOW!, that just somehow looks more professional to me? I hate to long
strings in the middle of a code block. Please be smart when writing
code people!!

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


Re: Twisted - how to get text for HTTP error responses

2009-08-09 Thread exarkun

On 03:35 pm, koranth...@gmail.com wrote:

Hi,
  I am writing a HTTP client in Twisted. The client contacts the
server, and any errors in the sent messages will be returned back to
the client in 400 message. The reason for failure at the server is
sent as the text in the 400 message. I tried the same using the
browser, and I can see the error text (the text might be like - 'Item
X not found in DB').
  The client is supposed to use this text and calculate the next
messages to be sent to the server. But, I cannot seem to find a
mechanism to get the response text from the errback. I went through
failure.py, but I couldnt find a way to do it.
  Ex:
I send a data to the server as so
d = defer.waitForDeferred(getPage(url, method='POST', headers=hdr,
postdata=form))
yield d
try:
  reply = d.getResult()
  success(reply)
except Error, failure:
  failure(failure)

Now, inside failure method, I was unable to print the text out - say
'Item X not found in DB'.
Is it possible using Twisted? If so, how can it be done?


The Error instance which the local "failure" is bound to in your example 
above has a number of attributes, one of which is "status" which may be 
what you're looking for.  If not, take a look at its other attributes.


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


Client/Server based on SocketServer and Windows

2009-08-09 Thread Kiki
Hello list,

I've written a small Client/server system.
Basically, i'm expecting something like : The client sends every once
and a while a small data chunk (not more than 50 bytes) the server
receive it and print it.

Here is the server request handler :

class ThreadedTCPRequestHandlerFoo(SocketServer.BaseRequestHandler):

def handle(self):
data = self.request.recv(1024)
cur_thread = threading.currentThread()
response = "%s: %s from Foo" % (cur_thread.getName(),
data)
print response

and this is the client :

def clientPrompt(ip, port, message):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((ip, port))
while(1):
k=raw_input('#>')
sock.send(k)
print "%s\n" % k
if k == 'quit': break
sock.close()

My problem comes from that I can't send data from client more than
once without having the following Winsock error : 10053 Software
caused connection abort.
I have to restart the client each time I want to send a new message.

Could anyboy explain me why ?

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


Re: String algo

2009-08-09 Thread Tim Chase

nipun batra wrote:

I will be receiving data serially from another pc,.i can use any sort of
marker between two packets,i will be the person sending data as well after
reading it from some devices.But packet length is not constant.
each packet has this format:
201.535a56.65b4.56c89.565d
another packet could be :
4a5b6c7d
What i need is a program to store variables such as:var_a has value 4,var_b
has value 5,for second string.
I have to read and write data continuosly using serial port.


Sounds like you want to break apart your string at the 
non-numeric bits, and then create a mapping from them:


>>> import re
>>> s = "201.535a56.65b4.56c89.565d"
>>> r = re.compile(r"(\d+(?:\.\d+)?)([a-z]+)", re.I)
>>> r.findall(s)
[('201.535', 'a'), ('56.65', 'b'), ('4.56', 'c'), ('89.565', 'd')]
>>> d = dict((k,float(v)) for v,k in r.findall(s))
>>> print d['a']
201.535
>>> print d['c']
4.56
>>> print 'z' in d
False
>>> print 'b' in d
True

Adjust the regexp accordingly if there are +/- signs, 
exponentiation, limits on the splitting-characters, etc.



-tkc







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


Re: Bug or feature: double strings as one

2009-08-09 Thread Anny Mous
r wrote:

> On Aug 8, 12:43 pm, "Jan Kaliszewski"  wrote:

>> (Note that multiline-'''-strings are usless in such cases).
>>
> 
> uhh? A much better way to handle such a problem is like this...
> 
> prompt1 = '''
> Some people like to use %s
> ways of doing things just
> so they can support their %s
> way of coding
> '''

Oh wow, you so need to work on your reading comprehension skills! Didn't you
notice Jan's comment that multiline ''' strings are useless??? They add
extra newlines into the string which aren't wanted.

> WOW!, that just somehow looks more professional to me? I hate to long
> strings in the middle of a code block. Please be smart when writing
> code people!!

Because totally failing to pay attention to the requirements is "smart".



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


Re: Bug or feature: double strings as one

2009-08-09 Thread Jan Kaliszewski

09-08-2009 r  wrote:


On Aug 8, 12:43 pm, "Jan Kaliszewski"  wrote:

08-08-2009 Steven D'Aprano  wrote:

...(snip)

I use it very often, e.g.:

         afunction('quite long string %s quite long string '
                   'quite long string quite long string %s '
                   'quite %s long string quite long string'
                   % (variable1, variable2, variable3))

It seems nicer to me than:

         afunction(('quite long string %s quite long string '
                    + 'quite long string quite long string %s '
                    + 'quite %s long string quite long string')
                   % (variable1, variable2, variable3))

(Note that multiline-'''-strings are usless in such cases).



uhh? A much better way to handle such a problem is like this...

prompt1 = '''
Some people like to use %s
ways of doing things just
so they can support their %s
way of coding
'''


Sorry, you are wrong, '''-way would be usefull only if:

* you want to have '\n' in each place where you wrap the
  literal in your code,

and

* you use '''-literal at a module (non-indented) level

  or you need not only '\n'-s but also indentations
 (dependent on indentation of your code),

  or such ugly indentation is ok for you:

  some indentated code...
          prompt = '''quite long string %s quite long string
''' quite long string quite long string %s
''' quite %s long string quite long string
'''
  some indentated code...


That's why I wrote it's "useless in such cases."

Regards,
*j

--
Jan Kaliszewski (zuo) 
--
http://mail.python.org/mailman/listinfo/python-list


Problem with join in__str__() in class (newbie)

2009-08-09 Thread Fencer
Hello, I've written two classes. One class describes experts: experts 
has a unique ID and a name. An expert knows topics and other experts. A 
topic is described by my other class and includes a unique ID and a 
name. Now I have a problem with the __str__ method in my Expert class:


def __str__(self):
output = '%s:%s' % (self.expert_id, self.name)
output += '\nKnown topics: %s' % (', '.join(str(self.topics)))
#   print 'Known experts: '
#   for e in self.known_experts:
#   print '%s:%s' % (e.expert_id, e.name)
return output

self.topics is a list of objects of type Topic.
self.known_experts is a list of objects of type Expert, specifically the 
experts known by the given expert.


When I print an object of type Expert, the output is not what I want. If 
the expert knows only one topic, say polemics, the output is:

e2:Carla
Known topics: t, 5, :, P, o, l, e, m, i, c, s
If the expert knows two topics, say Polemics and The Parthenon, then the 
 output is:

e2:Carla
Known topics: [, <, _, _, m, a, i, n, _, _, ., T, o, p, i, c,  , i, n, 
s, t, a, n, c, e,  , a, t,  , 0, x, 0, 2, 2, 2, D, 0, 8, 0, >, ]


This is not what I want. :) I want the output like this:
e2:Carla
Known topics: t5:Polemics, t6:The Parthenon

Also, notice the code I've commented out. If I can get the join above to 
work (with your help) my next question is how to present the known 
experts in a comma separated list with only expert_id and name? I can't 
use the normal __str__() method (the one I'm writing here) because it 
prints too much information. Does that mean a join is out of the question?


Thanks for any replies!

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


Re: Problem with join in__str__() in class (newbie)

2009-08-09 Thread jon rascal

> def __str__(self):
>      output = '%s:%s' % (self.expert_id, self.name)
>      output += '\nKnown topics: %s' % (', '.join(str(self.topics)))

You're turning your list into a string -- try this:
', '.join([str(x) for x in self.topics])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem with join in__str__() in class (newbie)

2009-08-09 Thread Stephen Hansen
   output += '\nKnown topics: %s' % (', '.join(str(self.topics)))


Your problem is here.

self.topics is a list of topic instances: but you're calling str() on the
list itself to turn the LIST itself into a string. Compare:

>>> x = [1,2,3]
>>> x
[1, 2, 3]
>>> str(x)
'[1, 2, 3]'

Now, after str(self.topics) is done, you have one big string. A string is a
sequence of characters (mostly). Calling ",".join(string) will do just what
you see there-- return a string with a comma between each character.

What you want to do, I assume, is call str() on each item in self.topics,
and join them.

That would be:

output += '\nKnown topics: %s' % ( ','.join(str(item) for item in
self.topics) )

That's a generator expression which will do what you want, I believe.
Provided your topic instances have a __str__ method that returns a string of
the form "t:".

Also, notice the code I've commented out. If I can get the join above to
> work (with your help) my next question is how to present the known experts
> in a comma separated list with only expert_id and name? I can't use the
> normal __str__() method (the one I'm writing here) because it prints too
> much information. Does that mean a join is out of the question?


Honestly, I think you are putting too much into the Expert class's __str__
method. I would make it do basically:

return "%s:%s" % (self.expert_id, self.name)

And then put the __str__ you're working on above in a different method which
does -- more. Call it 'dump' or something. That way you CAN just use the
normal str/__str__ from within this 'dump' and get what you want. str()
should return that object in its stringified form. Another method is a
better way to dump 'that object' and things 'around' it and that it 'knows'.

But if you really must have just str(expert) and have it return the big
chunk of information, your commented code looks about right. You'll have to
use your knowledge of how the internal expert class works instead of relying
on the experts just returning a str() of themselves. That's slightly bad.
But not horrible.

HTH,

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


Re: Problem with join in__str__() in class (newbie)

2009-08-09 Thread Fencer

jon rascal wrote:


You're turning your list into a string -- try this:
', '.join([str(x) for x in self.topics])


Thanks for your quick reply, unfortunately it didn't quite work for me.
Say topics contain two topics: polemics, and the parthenon I get this 
output:

e2:Carla
Known topics: t5:Polemics

only the first topic is printed. If topics only contain a single topic I 
get this error:

Traceback (most recent call last):
  File "C:\Users\fencer\workspace\Find Expert\src\find_expert.py", line 
57, in 

print experts[1]
  File "C:\Users\fencer\workspace\Find Expert\src\find_expert.py", line 
21, in __str__
output += '\nKnown topics: %s' % (', '.join([str(x) for x in 
self.topics]))

TypeError: iteration over non-sequence

What did I do wrong?

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


Re: resume upload wsgi script

2009-08-09 Thread gert
On Aug 9, 4:42 pm, "Diez B. Roggisch"  wrote:
> gert schrieb:
>
>
>
> > On Aug 9, 3:17 pm, "Diez B. Roggisch"  wrote:
> >> gert schrieb:
>
> >>> I working on a resume upload script and encountered the following
> >>> problems
> >>> sql: Could not decode to UTF-8 column 'SUBSTR(picture,?)' with text
> >>> '\ufffd\ufff
> >>> d\ufffd\ufffd↑!ExifEf1gL6KM7Ij5ae0gL6KM7cH2cH2GI3
> >>> Content-Disposition: form-data; name="Filename"
> >> You are treating a binary data column as if it were a string. That's
> >> bogus, you need to use a blob column.
>
> >> Also I wouldn't combine the uplodaded chunks until the full upload is
> >> finished - and even then only if I actually need the data.
>
> >> Diez
>
> > And the best solution would be to use TEXT instead or some sort of
> > SUBBIN that i do not know of in sqlite ?
>
> No, the best solution would be to use "BLOB", and no SUB*-stuff, but
> instead a 1:n-relation of chunks, that when the upload is finished you
> can easily combine in python to one large blob, storing that in the DB
> again.
>
> Diez

so one table of chunks

CREATE TABLE temp (
file_id  VARCHAR(64),
chunK_id  INTEGER,
chunk BLOB,
PRIMARY KEY(file_id,chunk_id)
);

SELECT chunk FROM temp WHERE file_id = 'file'
concatenating result in python
update blob
delete temp

How do I concatenate results that do not fit into memory ?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem with join in__str__() in class (newbie)

2009-08-09 Thread Stephen Hansen
>
> only the first topic is printed. If topics only contain a single topic I
> get this error:
> Traceback (most recent call last):
>  File "C:\Users\fencer\workspace\Find Expert\src\find_expert.py", line 57,
> in 
>print experts[1]
>  File "C:\Users\fencer\workspace\Find Expert\src\find_expert.py", line 21,
> in __str__
>output += '\nKnown topics: %s' % (', '.join([str(x) for x in
> self.topics]))
> TypeError: iteration over non-sequence
>
> What did I do wrong?
>

It looks like, "if topics contains only a single topic", means:

self.topics = MyTopic

was done at some point. What you should do is make self.topics ALWAYS be a
list: even if it's only a list of one item.

So you do

self.topics.append(MyTopic)

when you add that one topic. That way self.topics is always a list.
Sometimes empty, sometimes containing one element, sometimes containing
many.

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


Re: Problem with join in__str__() in class (newbie)

2009-08-09 Thread MRAB

Fencer wrote:

jon rascal wrote:


You're turning your list into a string -- try this:
', '.join([str(x) for x in self.topics])


Thanks for your quick reply, unfortunately it didn't quite work for me.
Say topics contain two topics: polemics, and the parthenon I get this 
output:

e2:Carla
Known topics: t5:Polemics

only the first topic is printed. If topics only contain a single topic I 
get this error:

Traceback (most recent call last):
  File "C:\Users\fencer\workspace\Find Expert\src\find_expert.py", line 
57, in 

print experts[1]
  File "C:\Users\fencer\workspace\Find Expert\src\find_expert.py", line 
21, in __str__
output += '\nKnown topics: %s' % (', '.join([str(x) for x in 
self.topics]))

TypeError: iteration over non-sequence

What did I do wrong?


Try printing self.topics. It should always be a list of topics.
--
http://mail.python.org/mailman/listinfo/python-list


Re: resume upload wsgi script

2009-08-09 Thread Diez B. Roggisch

gert schrieb:

On Aug 9, 4:42 pm, "Diez B. Roggisch"  wrote:

gert schrieb:




On Aug 9, 3:17 pm, "Diez B. Roggisch"  wrote:

gert schrieb:

I working on a resume upload script and encountered the following
problems
sql: Could not decode to UTF-8 column 'SUBSTR(picture,?)' with text
'\ufffd\ufff
d\ufffd\ufffd↑!ExifEf1gL6KM7Ij5ae0gL6KM7cH2cH2GI3
Content-Disposition: form-data; name="Filename"

You are treating a binary data column as if it were a string. That's
bogus, you need to use a blob column.
Also I wouldn't combine the uplodaded chunks until the full upload is
finished - and even then only if I actually need the data.
Diez

And the best solution would be to use TEXT instead or some sort of
SUBBIN that i do not know of in sqlite ?

No, the best solution would be to use "BLOB", and no SUB*-stuff, but
instead a 1:n-relation of chunks, that when the upload is finished you
can easily combine in python to one large blob, storing that in the DB
again.

Diez


so one table of chunks

CREATE TABLE temp (
file_id  VARCHAR(64),
chunK_id  INTEGER,
chunk BLOB,
PRIMARY KEY(file_id,chunk_id)
);

SELECT chunk FROM temp WHERE file_id = 'file'
concatenating result in python
update blob
delete temp

How do I concatenate results that do not fit into memory ?


By writing them into one file? If files were to large for your memory, 
all the substring-stuff wouldn't help either - the sqlite works in the 
same memory as your program...


But how many gigabytes of uploads do you expect?

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


Re: Problem with join in__str__() in class (newbie)

2009-08-09 Thread Fencer

MRAB wrote:

Try printing self.topics. It should always be a list of topics.


Ah, yes, that made me find a bug when I was creating the Expert objects: 
the lists of known topics were not created properly. I should have 
posted more code I suppose! Thanks for the help, this problem has now 
been solved. I guess I can't use a join to print the known experts as I 
described in my first post.


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


Monkeypatching an object to become callable

2009-08-09 Thread Nikolaus Rath
Hi,

I want to monkeypatch an object so that it becomes callable, although
originally it is not meant to be. (Yes, I think I do have a good reason
to do so).

But simply adding a __call__ attribute to the object apparently isn't
enough, and I do not want to touch the class object (since it would
modify all the instances):

>>> class foo(object):
...   pass
... 
>>> t = foo()
>>> def test():
...   print 'bar'
... 
>>> t()
Traceback (most recent call last):
  File "", line 1, in 
TypeError: 'foo' object is not callable
>>> t.__call__ = test
>>> t()
Traceback (most recent call last):
  File "", line 1, in 
TypeError: 'foo' object is not callable
>>> t.__call__()
bar


Is there an additional trick to get it to work?


Best,

   -Nikolaus

-- 
 »Time flies like an arrow, fruit flies like a Banana.«

  PGP fingerprint: 5B93 61F8 4EA2 E279 ABF6  02CF A9AD B7F8 AE4E 425C
-- 
http://mail.python.org/mailman/listinfo/python-list


Unrecognized escape sequences in string literals

2009-08-09 Thread Douglas Alan
A friend of mine is just learning Python, and he's a bit tweaked about
how unrecognized escape sequences are treated in Python. This is from
the Python 3.0 reference manual:

 Unlike Standard C, all unrecognized escape sequences are left in
the string unchanged, i.e.,
 the backslash is left in the string. (This behavior is useful
when debugging: if an escape
 sequence is mistyped, the resulting output is more easily
recognized as broken.) It is also
 important to note that the escape sequences only recognized in
string literals fall into the
 category of unrecognized escapes for bytes literals.

My friend begs to differ with the above. It would be much better for
debugging if Python generated a parsing error for unrecognized escape
sequences, rather than leaving them unchanged. g++ outputs a warning
for such escape sequences, for instance. This is what I would consider
to be the correct behavior. (Actually, I think it should just generate
a fatal parsing error, but a warning is okay too.)

In any case, I think my friend should mellow out a bit, but we both
consider this something of a wart. He's just more wart-phobic than I
am. Is there any way that this behavior can be considered anything
other than a wart? Other than the unconvincing claim that you can use
this "feature" to save you a bit of typing sometimes when you actually
want a backslash to be in your string?

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


Re: Problem with join in__str__() in class (newbie)

2009-08-09 Thread Piet van Oostrum
> Fencer  (F) wrote:

>F> Also, notice the code I've commented out. If I can get the join above to
>F> work (with your help) my next question is how to present the known experts
>F> in a comma separated list with only expert_id and name? I can't use the
>F> normal __str__() method (the one I'm writing here) because it prints too
>F> much information. Does that mean a join is out of the question?

>F> MRAB wrote:
>>> Try printing self.topics. It should always be a list of topics.

>F> Ah, yes, that made me find a bug when I was creating the Expert objects:
>F> the lists of known topics were not created properly. I should have posted
>F> more code I suppose! Thanks for the help, this problem has now been solved.
>F> I guess I can't use a join to print the known experts as I described in my
>F> first post.

Yes, you can. But you need an additional method that gives only the id
and name. Like this:


class Expert:
'''An expert'''
def __init__(self, id, name, topics):
self.expert_id = id
self.name = name
self.topics = topics
self.known_experts = []

def add_expert(self, expert):
self.known_experts.append(expert)

def __str__(self):
output = (self.brief_str() +
  '\nKnown topics: %s' % (', '.join(map(str, self.topics))) +
  ('\nKnown experts: %s' %
   (', '.join(exp.brief_str() for exp in self.known_experts
return output

def brief_str(self):
'''Gives a brief description of the expert: just the id and name.'''
return '%s:%s' % (self.expert_id, self.name)

class Topic:
'''A topic'''
def __init__(self, id, name):
self.topic_id = id
self.name = name

def __str__(self):
return '%s:%s' % (self.topic_id, self.name)

topic1 = Topic('t1', 'Relativity')
topic2 = Topic('t2', 'Math')
topic5 = Topic('t5', 'Polemics')
topic6 = Topic('t6', 'The Parthenon')

expert1 = Expert('e1', 'Albert', [topic1])
expert2 = Expert('e2', 'Leonhard', [topic2])

expert1.add_expert(expert2)

expert5 = Expert('e5', 'Carla', [topic5, topic6])
expert5.add_expert(expert1)
expert5.add_expert(expert2)

for ex in expert1, expert2, expert5:
print ex


(I prefer to use map instead of a list/iterator comprehension in this
particular case. With the known_experts that isn't possible, unless
brief_str is made into a static method)
-- 
Piet van Oostrum 
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: p...@vanoostrum.org
-- 
http://mail.python.org/mailman/listinfo/python-list


Surpressing Warnings

2009-08-09 Thread Victor Subervi
Hi:
I get a ton of warnings like this from a program I run:

Warning (from warnings module):
  File "C:\Python25\read.py", line 67
cursor.execute(sqlKWDrop)
Warning: Unknown table 'judaism_128'

How do I surpress them?
TIA,
Victor
-- 
http://mail.python.org/mailman/listinfo/python-list


[ANNC] pybotwar-0.5

2009-08-09 Thread Lee Harr

pybotwar is a fun and educational game where players
create computer programs to control simulated robots
to compete in a battle arena.

http://pybotwar.googlecode.com/


pybotwar uses pybox2d for the physical simulation,
and uses pygame and pygsear for the visualization.

pybotwar is released under GPLv3.


Changes in pybotwar-0.5:
- added tournament mode
- added explosive shells
- robots are now damaged by colliding with walls or other robots
- added damage sensor
- added gyro sensor
- added configurable cannon reload time
- added robot statistics database
- added time limit for robot startup/ initialization
- health bar changes color below 30% health
- fixed force/ torque possibly going over 100%
- fixed problem with non-integer force/ torque values
- each robot gets its own log file in test mode
- send robot errors to log file
- use optparse for cmd line options


_
More than messages–check out the rest of the Windows Live™.
http://www.microsoft.com/windows/windowslive/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Monkeypatching an object to become callable

2009-08-09 Thread Diez B. Roggisch

Nikolaus Rath schrieb:

Hi,

I want to monkeypatch an object so that it becomes callable, although
originally it is not meant to be. (Yes, I think I do have a good reason
to do so).

But simply adding a __call__ attribute to the object apparently isn't
enough, and I do not want to touch the class object (since it would
modify all the instances):


class foo(object):

...   pass
... 

t = foo()
def test():

...   print 'bar'
... 

t()

Traceback (most recent call last):
  File "", line 1, in 
TypeError: 'foo' object is not callable

t.__call__ = test
t()

Traceback (most recent call last):
  File "", line 1, in 
TypeError: 'foo' object is not callable

t.__call__()

bar


Is there an additional trick to get it to work?


AFAIK special methods are always only evaluated on the class. But this 
works:


class Foo(object):

pass

f = Foo()

def make_callable(f):
class Callable(f.__class__):

def __call__(self):
print "foobar"

f.__class__ = Callable

make_callable(f)
f()

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


Re: Bug or feature: double strings as one

2009-08-09 Thread r
On Aug 9, 12:10 pm, "Jan Kaliszewski"  wrote:
..(snip)
> Sorry, you are wrong, '''-way would be usefull only if:
>
>      * you want to have '\n' in each place where you wrap the
>        literal in your code,
>
> and
>
>      * you use '''-literal at a module (non-indented) level
>
>        or you need not only '\n'-s but also indentations
>           (dependent on indentation of your code),
>
>        or such ugly indentation is ok for you:
>
>            some indentated code...
>            prompt = '''quite long string %s quite long string
> ''' quite long string quite long string %s
> ''' quite %s long string quite long string
> '''
>            some indentated code...
>
> That's why I wrote it's "useless in such cases."

@ Jan & Anny

No, of course putting a multi-line string inside a block does not
solve anything. What i meant for you to do is to declare the string
outside the block or as a module level Constant. i typically declare
all multi-line strings (ig for dialog prompts etc..) right after my
globals at the top of my modules or within an imported module like...

from thisModuleConstants import *


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


Re: unique-ifying a list

2009-08-09 Thread Simon Forman
On Aug 7, 4:53 pm, kj  wrote:
> Suppose that x is some list.  To produce a version of the list with
> duplicate elements removed one could, I suppose, do this:
>
>     x = list(set(x))
>
> but I expect that this will not preserve the original order of
> elements.
>
> I suppose that I could write something like
>
> def uniquify(items):
>     seen = set()
>     ret = []
>     for i in items:
>         if not i in seen:
>             ret.append(i)
>             seen.add(i)
>     return ret
>
> But this seems to me like such a commonly needed operation that I
> find it hard to believe one would need to resort to such self-rolled
> solutions.  Isn't there some more standard (and hopefully more
> efficient, as in "C-coded"/built-in) approach?
>
> TIA!
>
> kynn


Unique items in a list, in the same order as in the list:

x = sorted(set(x), key=x.index)

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


Re: Need help in configuration for TimedRotatingFileHandler

2009-08-09 Thread Dave Angel

Lokesh wrote:

Hi,

Need help in configure the TimedRotatingFileHandler from configuration
file

I have tried with the below code and ended up with the error, code is
pasted below
Error - IOError: [Errno 2] No such file or directory: 'G:\\lok_sib\
\logs\rotate_test'
[loggers]
keys=root,simpleExample

[handlers]
keys=consoleHandler,timedRotatingFileHandler

[formatters]
keys=simpleFormatter

[logger_root]
level=DEBUG
handlers=consoleHandler

[logger_simpleExample]
level=DEBUG
handlers=timedRotatingFileHandler
qualname=simpleExample
propagate=0

[handler_consoleHandler]
class=StreamHandler
level=DEBUG
formatter=simpleFormatter
args=(sys.stdout,)

[handler_timedRotatingFileHandler]
class=handlers.TimedRotatingFileHandler
level=DEBUG
formatter=simpleFormatter
args=("G:\lok_sib\logs\rotate_test", 'midnight', 1)

[formatter_simpleFormatter]
format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
datefmt='%Y-%m-%d %H:%M:%S'


Thanks or your time
Regards,
Lokesh

  
I don't see code there, I see lots of config data, presumably in an .ini 
file.   So I don't know how you're reading it in, and converting it to 
Python variables, but I know where I'd look, based on your error message.


The following line:

args=("G:\lok_sib\logs\rotate_test", 'midnight', 1)

seems to contain a Python string.  But there are unescaped backslashes 
within it.  You can get away with it in two cases, because \l  isn't a 
valid escape sequence.  But in the case of \r, it looks like a newline 
character.


Anyway, all three of those backslashes probably need to be doubled.

args=("G:\\lok_sib\\logs\\rotate_test", 'midnight', 1)

Two other cures that may work, depending on context:   change the backslashes 
to forward slashes, or use a raw string.

But as I said earlier, you don't show in any way what code is interpreting this 
line, so it's all just guesswork.

DaveA

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


Re: Bug or feature: double strings as one

2009-08-09 Thread r

#-- el bueno --#
"hello i am a very long string that\
does not like newlines so please \
escape me, Thank you!"

#-- el malo --#
"hello i am a very long string that"+
"does not like newlines but i have no"+
"idea what to do with myself"

#-- el feo --#
"hello i am a very long string that"
"does not like newlines but i have no"
"idea what to do with myself"


just ideas people!
-- 
http://mail.python.org/mailman/listinfo/python-list


How to find out in which module an instance of a class is created?

2009-08-09 Thread Johannes Janssen

Hi
I like to know in which module an instance of a class was initialized. 
Using __module__ or __name__ within a class only gives me the module in 
which the class was defined not the instance of the class. Is there some 
(simple) way to do this?
For better understanding I'll give an example how I want to use this. 
Okay let's say I've got a module *foo,* in which class A is defined as 
the following:


> class A(object):
> def __init__(self, mod):
> self.mod = mod

In a module called *bar* I do the following:

> import foo
> a = A(__name__)

Then a.mod should be "bar". But I don't like to pass the value of a.mod 
manually rather than having it default to the module the instance a of A 
was created in (here "bar").

Unfortunately something like this ...

> class A(object):
> def __init__(self, mod=__name__):
> self.mod = mod

... won't work. In this case mod would always be "foo".

Kind regards
johannes
--
http://mail.python.org/mailman/listinfo/python-list


Re: resume upload wsgi script

2009-08-09 Thread gert
On Aug 9, 8:25 pm, "Diez B. Roggisch"  wrote:
> gert schrieb:
>
>
>
> > On Aug 9, 4:42 pm, "Diez B. Roggisch"  wrote:
> >> gert schrieb:
>
> >>> On Aug 9, 3:17 pm, "Diez B. Roggisch"  wrote:
>  gert schrieb:
> > I working on a resume upload script and encountered the following
> > problems
> > sql: Could not decode to UTF-8 column 'SUBSTR(picture,?)' with text
> > '\ufffd\ufff
> > d\ufffd\ufffd↑!ExifEf1gL6KM7Ij5ae0gL6KM7cH2cH2GI3
> > Content-Disposition: form-data; name="Filename"
>  You are treating a binary data column as if it were a string. That's
>  bogus, you need to use a blob column.
>  Also I wouldn't combine the uplodaded chunks until the full upload is
>  finished - and even then only if I actually need the data.
>  Diez
> >>> And the best solution would be to use TEXT instead or some sort of
> >>> SUBBIN that i do not know of in sqlite ?
> >> No, the best solution would be to use "BLOB", and no SUB*-stuff, but
> >> instead a 1:n-relation of chunks, that when the upload is finished you
> >> can easily combine in python to one large blob, storing that in the DB
> >> again.
>
> >> Diez
>
> > so one table of chunks
>
> > CREATE TABLE temp (
> >     file_id  VARCHAR(64),
> >     chunK_id  INTEGER,
> >     chunk BLOB,
> >     PRIMARY KEY(file_id,chunk_id)
> > );
>
> > SELECT chunk FROM temp WHERE file_id = 'file'
> > concatenating result in python
> > update blob
> > delete temp
>
> > How do I concatenate results that do not fit into memory ?
>
> By writing them into one file? If files were to large for your memory,
> all the substring-stuff wouldn't help either - the sqlite works in the
> same memory as your program...
>
> But how many gigabytes of uploads do you expect?
>

250KB :)
Its just HTTP1.1 has everything for making ftp like file transfers
possible.
When I write it to a file then I am back at square one because I still
need to load it completely to get it into a blob.
So there is no way to concatenate BLOB's without loading it completely
into memory ?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Monkeypatching an object to become callable

2009-08-09 Thread Carl Banks
On Aug 9, 12:02 pm, Nikolaus Rath  wrote:
> Hi,
>
> I want to monkeypatch an object so that it becomes callable, although
> originally it is not meant to be. (Yes, I think I do have a good reason
> to do so).
>
> But simply adding a __call__ attribute to the object apparently isn't
> enough, and I do not want to touch the class object (since it would
> modify all the instances):


Override the class's __call__, and program it to call a certain method
(say _instancecall) on the object.  Catch AttributeError and raise
TypeError so that it matches the behavior when no __call__ is defined.


def __call__(self,*args,**kwargs):
try:
func = self._instancecall
except AttributeError:
raise TypeError("'%s' object not callable" % self.__class__)
return func(*args,**kwargs)


Note: don't call _instancecall inside the try clause; you don't want
to catch attribute errors raised inside the _instancecall method.

Then set _instancecall on any objects you want to be callable.


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


Re: Surpressing Warnings

2009-08-09 Thread Chris Rebert
On Sun, Aug 9, 2009 at 4:21 PM, Victor Subervi wrote:
> Hi:
> I get a ton of warnings like this from a program I run:
>
> Warning (from warnings module):
>   File "C:\Python25\read.py", line 67
>     cursor.execute(sqlKWDrop)
> Warning: Unknown table 'judaism_128'
>
> How do I surpress them?

import warnings
with warnings.catch_warnings():
warnings.simplefilter("ignore")
cursor.execute(sqlKWDrop)
#repeat for every call that's causing warnings

or to just silence all warnings from anywhere:

import warnings
warnings.simplefilter("ignore")

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


Re: Bug or feature: double strings as one

2009-08-09 Thread Jan Kaliszewski

09-08-2009 o 23:43:14 r  wrote:


#-- el bueno --#
"hello i am a very long string that\
does not like newlines so please \
escape me, Thank you!"


You probably ment: """hello i am... [etc.]

Anyway... You're right that generally it's good idea to define
dialog prompts and such stuff separately rather that to hardcode
it, especially in big projects. Then certainly multiline
string literals are useful (though, if you need to get rid of
newlines, IMHO "el feo" method is more elegant and less error
prone than your "el bueno" [possible invisible space after '\']).

But there are plenty of other situations when it's better
(in practice) to have strings (even long) together with your
code, e.g. log information for debugging, or

Cheers,

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


Re: How to find out in which module an instance of a class is created?

2009-08-09 Thread Christian Heimes

Johannes Janssen wrote:

 > class A(object):
 > def __init__(self, mod=__name__):
 > self.mod = mod

 won't work. In this case mod would always be "foo".


You have to inspect the stack in order to get the module of the caller. 
The implementation of warnings.warn() gives you some examples how to get 
the module name.


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


Re: Does python have the capability for driver development ? Maybe with ShedSkin

2009-08-09 Thread John Nagle

MalC0de wrote:

hello there, I've a question :
I want to know does python have any capability for using Ring0 and
kernel functions for driver and device development stuff .
if there's such a feature it is very good, and if there something for
this kind that you know please refer me to some reference and show me
some snippet .

thanks

- Malc0de


With the CPython interpretive system, it's not likely to work. But
using ShedSkin, which generates hard machine code, it might be possible.
The main problem is that Shed Skin uses a garbage-collected environment,
which few kernels have.

Under QNX, which is a a real message-passing operating system with
all drivers in user space, it should be possible to write a driver in
Python.  There's Python for QNX.  It would probably be too slow to
be useful, though.

I've actually written a handler for Baudot Teletype machines in
Python.  See

https://sourceforge.net/projects/baudotrss/

Those machines are so slow (45.45 baud) that Python isn't the bottleneck.

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


Re: Bug or feature: double strings as one

2009-08-09 Thread MRAB

Jan Kaliszewski wrote:

09-08-2009 o 23:43:14 r  wrote:


#-- el bueno --#
"hello i am a very long string that\
does not like newlines so please \
escape me, Thank you!"


You probably ment: """hello i am... [etc.]

Anyway... You're right that generally it's good idea to define
dialog prompts and such stuff separately rather that to hardcode
it, especially in big projects. Then certainly multiline
string literals are useful (though, if you need to get rid of
newlines, IMHO "el feo" method is more elegant and less error
prone than your "el bueno" [possible invisible space after '\']).

But there are plenty of other situations when it's better
(in practice) to have strings (even long) together with your
code, e.g. log information for debugging, or


Here's an idea that you're probably going to hate: indented strings. :-)

A string prefixed with 'i' would be an 'indented' string. Leading space
and tab characters at the start of the string (just after the quote) or
the start of each line within a multiline string would be ignored.

>>> """Line 1
   Line 2
"""
'Line 1\n   Line 2\n'
>>> i"""Line 1
   Line 2
"""
'Line 1\nLine 2\n'

An additional feature could be to make '\ ' == ' ', perhaps only for
indented strings if you're worried that it could breaking existing code:

>>> i"""Line 1
\   Line 2
"""
'Line 1\n   Line 2\n'

This would save you having to write '\x20'.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Unrecognized escape sequences in string literals

2009-08-09 Thread Steven D'Aprano
On Sun, 09 Aug 2009 12:26:54 -0700, Douglas Alan wrote:

> A friend of mine is just learning Python, and he's a bit tweaked about
> how unrecognized escape sequences are treated in Python.
...
> In any case, I think my friend should mellow out a bit, but we both
> consider this something of a wart. He's just more wart-phobic than I am.
> Is there any way that this behavior can be considered anything other
> than a wart? Other than the unconvincing claim that you can use this
> "feature" to save you a bit of typing sometimes when you actually want a
> backslash to be in your string?

I'd put it this way: a backslash is just an ordinary character, except 
when it needs to be special. So Python's behaviour is "treat backslash as 
a normal character, except for these exceptions" while the behaviour your 
friend wants is "treat a backslash as an error, except for these 
exceptions".

Why should a backslash in a string literal be an error?



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


Re: Monkeypatching an object to become callable

2009-08-09 Thread 7stud
On Aug 9, 1:02 pm, Nikolaus Rath  wrote:
> Hi,
>
> I want to monkeypatch an object so that it becomes callable, although
> originally it is not meant to be. (Yes, I think I do have a good reason
> to do so).
>
> But simply adding a __call__ attribute to the object apparently isn't
> enough, and I do not want to touch the class object (since it would
> modify all the instances):
>
> >>> class foo(object):
>
> ...   pass
> ...>>> t = foo()
> >>> def test():
>
> ...   print 'bar'
> ...>>> t()
>
> Traceback (most recent call last):
>   File "", line 1, in 
> TypeError: 'foo' object is not callable>>> t.__call__ = test
> >>> t()
>
> Traceback (most recent call last):
>   File "", line 1, in 
> TypeError: 'foo' object is not callable>>> t.__call__()
>
> bar
>
> Is there an additional trick to get it to work?
>
> Best,
>
>    -Nikolaus
>
> --
>  »Time flies like an arrow, fruit flies like a Banana.«
>
>   PGP fingerprint: 5B93 61F8 4EA2 E279 ABF6  02CF A9AD B7F8 AE4E 425C


With an old-style class your code will work:

class A:
pass

def test():
print "test"

a = A()
a.__call__ = test

a()

--output:--
test


a2 = A()
a2()

--output:--

a2()
AttributeError: A instance has no __call__ method



Another option is to use the *decorator pattern*.  The decorator
pattern can be used when you want to add additional methods and
attributes to an object, and you don't want to disturb the original
class:

class A(object):
def __init__(self, x):
self.x = x

def sayhi(self):
print "hi"


class Wrapper(object):
def __init__(self, obj, func):
self.obj = obj
self.func = func

def __call__(self, *args):
return self.func(*args)

def __getattr__(self, name):
return object.__getattribute__(self.obj, name)


def test():
print "test"

a = A(10)
w = Wrapper(a, test)
w()
print w.x
w.sayhi()

--output:--
test
10
hi

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


Re: Unrecognized escape sequences in string literals

2009-08-09 Thread Douglas Alan
Steven D'Aprano wrote:

> Why should a backslash in a string literal be an error?

Because in Python, if my friend sees the string "foo\xbar\n", he has
no idea whether the "\x" is an escape sequence, or if it is just the
characters "\x", unless he looks it up in the manual, or tries it out
in the REPL, or what have you. My friend is adamant that it would be
better if he could just look at the string literal and know. He
doesn't want to be bothered to have to store stuff like that in his
head. He wants to be able to figure out programs just by looking at
them, to the maximum degree that that is feasible.

In comparison to Python, in C++, he can just look "foo\xbar\n" and
know that "\x" is a special character. (As long as it compiles without
warnings under g++.)

He's particularly annoyed too, that if he types "foo\xbar" at the
REPL, it echoes back as "foo\\xbar". He finds that to be some sort of
annoying DWIM feature, and if Python is going to have DWIM features,
then it should, for example, figure out what he means by "\" and not
bother him with a syntax error in that case.

Another reason that Python should not behave the way that it does, is
that it pegs Python into a corner where it can't add new escape
sequences in the future, as doing so will break existing code.
Generating a syntax error instead for unknown escape sequences would
allow for future extensions.

Now not to pick on Python unfairly, most other languages have similar
issues with escape sequences. (Except for the Bourne Shell and bash,
where "\x" always just means "x", no matter what character "x" happens
to be.) But I've been telling my friend for years to switch to Python
because of how wonderful and consistent Python is in comparison to
most other languages, and now he seems disappointed and seems to think
that Python is just more of the same.

Of course I think that he's overreacting a bit. My point of view is
that every language has *some* warts; Python just has a bit fewer than
most. It would have been nice, I should think, if this wart had been
"fixed" in Python 3, as I do consider it to be a minor wart.

|>ouglas

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


Re: Unrecognized escape sequences in string literals

2009-08-09 Thread Carl Banks
On Aug 9, 5:06 pm, Steven D'Aprano  wrote:
> On Sun, 09 Aug 2009 12:26:54 -0700, Douglas Alan wrote:
> > A friend of mine is just learning Python, and he's a bit tweaked about
> > how unrecognized escape sequences are treated in Python.
> ...
> > In any case, I think my friend should mellow out a bit, but we both
> > consider this something of a wart. He's just more wart-phobic than I am.
> > Is there any way that this behavior can be considered anything other
> > than a wart? Other than the unconvincing claim that you can use this
> > "feature" to save you a bit of typing sometimes when you actually want a
> > backslash to be in your string?
>
> I'd put it this way: a backslash is just an ordinary character, except
> when it needs to be special. So Python's behaviour is "treat backslash as
> a normal character, except for these exceptions" while the behaviour your
> friend wants is "treat a backslash as an error, except for these
> exceptions".
>
> Why should a backslash in a string literal be an error?

Because the behavior of \ in a string is context-dependent, which
means a reader can't know if \ is a literal character or escape
character without knowing the context, and it means an innocuous
change in context can cause a rather significant change in \.

IOW it's an error-prone mess.  It would be better if Python (like C)
treated \ consistently as an escape character.  (And in raw strings,
consistently as a literal.)

It's kind of a minor issue in terms of overall real-world importance,
but in terms of raw unPythonicness this might be the worst offense the
language makes.


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


Re: pybotwar-0.5

2009-08-09 Thread Mensanator
On Aug 9, 3:26 pm, Lee Harr  wrote:
> pybotwar is a fun and educational game where players
> create computer programs to control simulated robots
> to compete in a battle arena.
>
> http://pybotwar.googlecode.com/

Why is the doc folder empty?

Shouldn't you supply some hint on how the games works
and at least a rudimentary guide to robot design?

What version to you expect that will be in? 1.0? 10.0?

Could you inform us when you have something worth looking
at and not before so we don't have to waste our time?


>
> pybotwar uses pybox2d for the physical simulation,
> and uses pygame and pygsear for the visualization.
>
> pybotwar is released under GPLv3.
>
> Changes in pybotwar-0.5:
>     - added tournament mode
>     - added explosive shells
>     - robots are now damaged by colliding with walls or other robots
>     - added damage sensor
>     - added gyro sensor
>     - added configurable cannon reload time
>     - added robot statistics database
>     - added time limit for robot startup/ initialization
>     - health bar changes color below 30% health
>     - fixed force/ torque possibly going over 100%
>     - fixed problem with non-integer force/ torque values
>     - each robot gets its own log file in test mode
>     - send robot errors to log file
>     - use optparse for cmd line options
>
> _
> More than messages–check out the rest of the Windows 
> Live™.http://www.microsoft.com/windows/windowslive/

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


Re: Unrecognized escape sequences in string literals

2009-08-09 Thread Douglas Alan
On Aug 9, 8:06 pm, Steven D'Aprano wrote:

> while the behaviour your
> friend wants is "treat a backslash as an error, except for these
> exceptions".

Besides, can't all error situations be described as, "treat the error
situation as an error, except for the exception of when the situation
isn't an error"???

The behavior my friend wants isn't any more exceptional than that!

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


Social problems of Python doc [was Re: Python docs disappointing]

2009-08-09 Thread Xah Lee
The prob with python docs is with the python priests.

there are frequent posts about python doc's poor quality, and some
efforts to improve the doc (such as wiki or seggestions), about few
times a year (in so much as i've seen), the typical response is
pissing fight, with python priests to tell them not to start another
wiki, or “you should apply in our church first and formulate a PEP
proposal first or kindly donate or otherwise fuckoff”, and so on.

i've wrote several articles about this issue, total time spend on this
is probably more than 2 months full-time work. See:

• Python Documentation Problems
  http://xahlee.org/perl-python/python_doc_index.html

just about each article above generates a thread of flames.

I also have re-wrote the entire python regex doc in 2005:

• Pyhton Regex Documentation: String Pattern Matching
  http://xahlee.org/perl-python/python_re-write/lib/module-re.html

there are some positive reviews, but most are drawn out by nay-sayers.

I often receive thank you emails for 2 particular articles, which are
most frequently google searched as indicated by my weblog:

• Python Doc Problem Example: gzip
  http://xahlee.org/perl-python/python_doc_gzip.html

• Python Doc Problem Example: sort()
  http://xahlee.org/perl-python/python_doc_sort.html

• Sorting in Python and Perl
  http://xahlee.org/perl-python/sort_list.html

See also:

• Language, Purity, Cult, and Deception
  http://xahlee.org/UnixResource_dir/writ/lang_purity_cult_deception.html

  Xah
∑ http://xahlee.org/

☄

On Jul 31, 1:10 pm, kj  wrote:
> I'm pretty new to Python, and I like a lot overall, but I find the
> documentation for Python rather poor, overall.
>
> I'm sure that Python experts don't have this problem: they have
> internalized some good ways to access the documentation, are
> productive with it, and therefore have lost the ability to see why
> the Python documentations is deficient for beginners.  This explains
> why a suboptimal situation can persist like this: those who are
> most able fix it are also the least able to perceive it.
>
> I've heard similar complaints from other experienced programmers
> who are trying out Python for the first time: poor documentation.
>
> Here is an *entirely typical* example: on some Unix, try
>
> % pydoc urllib
>
> The displayed documentation mention the optional parameter "data"
> in practically every function listed (a few dozen of them).  This
> parameter is not documented *anywhere* on that page.  All that we
> are told is that its default value is always None.
>
> I'm sure that I can find a full description of this parameter if
> I fire up Google, and search online.  In fact, more likely than
> not, I'll find far more documentation than I want.  But my point
> is that a programmer should not need to do this.  The full
> documentation should be readily accessible directly through a few
> keystrokes.
>
> I would love to know how experienced Python programmers quickly
> zero in on the Python documentation they need.
>
> TIA!
>
> kynn

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


reloading the module imported as 'from ... import ...'

2009-08-09 Thread AlF

Hi,

what is the best way to reload the module imported using 'from ... 
import ...'


Is following a way to do so?


>>> from email.charset import Charset
>>> reload(email.charset)
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'email' is not defined
>>>
>>>
>>> import email.charset
>>> reload(email.charset)
Probably it works but I do not like it as I end up with two namespaces 
for the symbol Charset: email.charset.Charset and Charset


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


Re: Social problems of Python doc [was Re: Python docs disappointing]

2009-08-09 Thread David Lyon

Since you're talking about documentation, which is a part of python,
don't you think you should be discussing it on python-dev ?

That's where discussions about the documentation should be held.

haha - I'm just curious to see how long it will for them to
shut the discussion down. 

Before you do that, you should clearly work out in your own mind
how you think things need to improve. It's not good enough just
saying this or that is bad without having specific ideas on what
needs to change.

Good luck fellow sinner and blasphemer...

How dare you suggest that things could be improved...


On Sun, 9 Aug 2009 20:04:43 -0700 (PDT), Xah Lee  wrote:
> The prob with python docs is with the python priests.
> 
> there are frequent posts about python doc's poor quality, and some
> efforts to improve the doc (such as wiki or seggestions), about few
> times a year (in so much as i've seen), the typical response is
> pissing fight, with python priests to tell them not to start another
> wiki, or “you should apply in our church first and formulate a PEP
> proposal first or kindly donate or otherwise fuckoff”, and so on.
> 
> i've wrote several articles about this issue, total time spend on this
> is probably more than 2 months full-time work. See:
> 
> • Python Documentation Problems
>   http://xahlee.org/perl-python/python_doc_index.html
> 
> just about each article above generates a thread of flames.
> 
> I also have re-wrote the entire python regex doc in 2005:
> 
> • Pyhton Regex Documentation: String Pattern Matching
>   http://xahlee.org/perl-python/python_re-write/lib/module-re.html
> 
> there are some positive reviews, but most are drawn out by nay-sayers.
> 
> I often receive thank you emails for 2 particular articles, which are
> most frequently google searched as indicated by my weblog:
> 
> • Python Doc Problem Example: gzip
>   http://xahlee.org/perl-python/python_doc_gzip.html
> 
> • Python Doc Problem Example: sort()
>   http://xahlee.org/perl-python/python_doc_sort.html
> 
> • Sorting in Python and Perl
>   http://xahlee.org/perl-python/sort_list.html
> 
> See also:
> 
> • Language, Purity, Cult, and Deception
>   http://xahlee.org/UnixResource_dir/writ/lang_purity_cult_deception.html
> 
>   Xah
> ∑ http://xahlee.org/
> 
> ☄
> 
> On Jul 31, 1:10 pm, kj  wrote:
>> I'm pretty new to Python, and I like a lot overall, but I find the
>> documentation for Python rather poor, overall.
>>
>> I'm sure that Python experts don't have this problem: they have
>> internalized some good ways to access the documentation, are
>> productive with it, and therefore have lost the ability to see why
>> the Python documentations is deficient for beginners.  This explains
>> why a suboptimal situation can persist like this: those who are
>> most able fix it are also the least able to perceive it.
>>
>> I've heard similar complaints from other experienced programmers
>> who are trying out Python for the first time: poor documentation.
>>
>> Here is an *entirely typical* example: on some Unix, try
>>
>> % pydoc urllib
>>
>> The displayed documentation mention the optional parameter "data"
>> in practically every function listed (a few dozen of them).  This
>> parameter is not documented *anywhere* on that page.  All that we
>> are told is that its default value is always None.
>>
>> I'm sure that I can find a full description of this parameter if
>> I fire up Google, and search online.  In fact, more likely than
>> not, I'll find far more documentation than I want.  But my point
>> is that a programmer should not need to do this.  The full
>> documentation should be readily accessible directly through a few
>> keystrokes.
>>
>> I would love to know how experienced Python programmers quickly
>> zero in on the Python documentation they need.
>>
>> TIA!
>>
>> kynn
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Need help in configuration for TimedRotatingFileHandler

2009-08-09 Thread Lokesh Maremalla
Hi Dave,

I have modified the code as mentioned in reply and is working fine. But
still i am facing an issue and the issue is described below.

In configuration file i have coded the TimedRotatingFileHandler like
args=("G:\\lok_sib\\logs\\rotate_test", 'D', 1)

step1: Executed the code and got the log file with the information
step2: Modified the system time from current day to next day
step3: End up with the error and the error is pasted below

Traceback (most recent call last):
  File "c:\Python25\lib\logging\handlers.py", line 74, in emit
self.doRollover()
  File "c:\Python25\lib\logging\handlers.py", line 274, in doRollover
os.rename(self.baseFilename, dfn)
WindowsError: [Error 32] The process cannot access the file because it is
being used by another process

Python version - 2.5.4

Thanks for your time.

Regards,
Lokesh


On Mon, Aug 10, 2009 at 2:45 AM, Dave Angel  wrote:

> Lokesh wrote:
>
>> Hi,
>>
>> Need help in configure the TimedRotatingFileHandler from configuration
>> file
>>
>> I have tried with the below code and ended up with the error, code is
>> pasted below
>> Error - IOError: [Errno 2] No such file or directory: 'G:\\lok_sib\
>> \logs\rotate_test'
>> [loggers]
>> keys=root,simpleExample
>>
>> [handlers]
>> keys=consoleHandler,timedRotatingFileHandler
>>
>> [formatters]
>> keys=simpleFormatter
>>
>> [logger_root]
>> level=DEBUG
>> handlers=consoleHandler
>>
>> [logger_simpleExample]
>> level=DEBUG
>> handlers=timedRotatingFileHandler
>> qualname=simpleExample
>> propagate=0
>>
>> [handler_consoleHandler]
>> class=StreamHandler
>> level=DEBUG
>> formatter=simpleFormatter
>> args=(sys.stdout,)
>>
>> [handler_timedRotatingFileHandler]
>> class=handlers.TimedRotatingFileHandler
>> level=DEBUG
>> formatter=simpleFormatter
>> args=("G:\lok_sib\logs\rotate_test", 'midnight', 1)
>>
>> [formatter_simpleFormatter]
>> format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
>> datefmt='%Y-%m-%d %H:%M:%S'
>>
>>
>> Thanks or your time
>> Regards,
>> Lokesh
>>
>>
>>
> I don't see code there, I see lots of config data, presumably in an .ini
> file.   So I don't know how you're reading it in, and converting it to
> Python variables, but I know where I'd look, based on your error message.
>
> The following line:
>
> args=("G:\lok_sib\logs\rotate_test", 'midnight', 1)
>
> seems to contain a Python string.  But there are unescaped backslashes
> within it.  You can get away with it in two cases, because \l  isn't a valid
> escape sequence.  But in the case of \r, it looks like a newline character.
>
> Anyway, all three of those backslashes probably need to be doubled.
>
> args=("G:\\lok_sib\\logs\\rotate_test", 'midnight', 1)
>
> Two other cures that may work, depending on context:   change the
> backslashes to forward slashes, or use a raw string.
>
> But as I said earlier, you don't show in any way what code is interpreting
> this line, so it's all just guesswork.
>
> DaveA
>
>


-- 
Thanks & Regards,
Lokesh.
lokeshmarema...@gmail.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Need help in configuration for TimedRotatingFileHandler

2009-08-09 Thread Lokesh Maremalla
Hi Dave,

I forgot to provide the information about the code how I am using logger
Here is the complete scenario

I have modified the code as mentioned in reply and is working fine. But
still I am facing an issue and the issue is described below.

In configuration file i have coded the TimedRotatingFileHandler like
args=("G:\\lok_sib\\logs\\rotate_test", 'D', 1)

Code:
mlogger = logging.getLogger("simpleExample")
def a_view(request):
mlogger.debug("a_view called")
if request.method== "POST" :
mlogger.debug("post function")
else:
mlogger.debug("serve function")

Execution:
step1: Executed the code and got the log file with the information
step2: Modified the system time from current day to next day
step3: End up with the error and the error is pasted below

Traceback (most recent call last):
  File "c:\Python25\lib\logging\handlers.py", line 74, in emit
self.doRollover()
  File "c:\Python25\lib\logging\handlers.py", line 274, in doRollover
os.rename(self.baseFilename, dfn)
WindowsError: [Error 32] The process cannot access the file because it is
being used by another process

Python version - 2.5.4

I guess my output should be like this for the next day
-a new log file rotate_test. should generate in the respective
location

Please correct me if I am wrong.


Thanks for your time.

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


Re: Using Python to automate builds

2009-08-09 Thread Tim Roberts
Kosta  wrote:
>
>
>What I would like to do, is to open a cmd window, and start a Python
>script.  This script would then (based upon input arguments), build
>different flavors of the driver (fre, chk, x86, x64) and do some post
>processing (create cat files, sign, etc.).
>
>I was hoping to take advantage as much as possible of exisiting
>infrastructure from the WDK.  I am able to call setenv.bat and provide
>all the input parameters.  One of the things setenv.bat does is change
>the path environment variable.  However, this is not captured by
>Python.  I could duplicate the functionality, but I'd rather not.  Is
>there a way to capture all enviroment variable changes being made by a
>batch file from Python?

My suggestion is that you just call "setenv" again every time you start a
new process.  My "build everything" batch file has a series of sections
something like this:

  setlocal
  set LAST=%CD%
  call %DDK%\bin\setenv %DDK% chk WXP no_oacr
  @echo on
  set USERNAME=timr
  cd %LAST%
  build %BLD%
  endlocal

  setlocal
  set LAST=%CD%
  call %DDK%\bin\setenv %DDK% fre WXP no_oacr
  @echo on
  set USERNAME=timr
  cd %LAST%
  build %BLD%
  endlocal

  setlocal
  set LAST=%CD%
  call %DDK%\bin\setenv %DDK% chk WLH x64 no_oacr
  @echo on
  set USERNAME=timr
  cd %LAST%
  build %BLD%
  endlocal
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: reloading the module imported as 'from ... import ...'

2009-08-09 Thread Steven D'Aprano
On Sun, 09 Aug 2009 20:43:41 -0700, AlF wrote:

> Hi,
> 
> what is the best way to reload the module imported using 'from ...
> import ...'


Have you tried "from ... import ..." again?



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


Re: Pywin32 @ windows 7

2009-08-09 Thread Tim Roberts
"Algirdas Brazas"  wrote:
>
>Did anyone manage to get windows extensions installet on windows 7 64 bit? As 
>far as I try I get only "Setup program invalid or damaged".

I've been running 32-bit Python 2.5 and the 32-bit versions of PyWin32 and
wxPython on Windows 7 64-bit for many months.  No problems.

I have not tried the 64-bit Python and PyWin32 builds yet.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Windows 7 : any problems installing or running Python ?

2009-08-09 Thread Tim Roberts
Dave WB3DWE wrote:
>
>Anybody tried it ? 
>Is anything broken, ie is the whole shootin' match good to go ?
>I'm esp interested in WConio for 3.0/3.1 which I use heavily.

I've been running the 32-bit builds of Python 2.5, PyWin32, and wxPython on
Windows 7 64-bit for many months.  No problems at all.

I hated Vista; I would only run it if my clients insisted on having their
drivers tested on it.  Vista SP1 was somewhat better, but I don't mind
Windows 7 at all.  I might even upgrade my primary development machine from
XP.  A number of the usually cranky driver developers have expressed the
same opinion.  Microsoft might actually have a winner here.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: reloading the module imported as 'from ... import ...'

2009-08-09 Thread AlF

Steven D'Aprano wrote:

On Sun, 09 Aug 2009 20:43:41 -0700, AlF wrote:


Hi,

what is the best way to reload the module imported using 'from ...
import ...'



Have you tried "from ... import ..." again?



I have not because of an assumption that "import" imports the module 
just once. In fact this still works that way:


here is a terminal 1:

$ cat > a.py
a=1
$ cat > a.py
a=2
$


and terminal 2:

>>> from a import a
>>> a
1
>>> a
1
>>> from a import a
>>> a
1
>>>

In spite of changing a.py in fly, the imported a is still 1


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


Re: Client/Server based on SocketServer and Windows

2009-08-09 Thread Kiki
Thank you Dennis

I'm using 2 differents editor, which may be the cause of such a mess
in the indentation.

I must admitt that I lazily rely on those (not so bad indeed) editors.

"If indentation whas bad they would have tell me"

Too bad am i

Won't post misindeted code anymore.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Unrecognized escape sequences in string literals

2009-08-09 Thread John Nagle

Carl Banks wrote:

IOW it's an error-prone mess.  It would be better if Python (like C)
treated \ consistently as an escape character.  (And in raw strings,
consistently as a literal.)


   Agreed.  For one thing, if another escape character ever has to be
added to the language, that may change the semantics of previously
correct strings.  If "\" followed by a non-special character is treated
as an error, that doesn't happen.

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


Re: Unrecognized escape sequences in string literals

2009-08-09 Thread Steven D'Aprano
On Sun, 09 Aug 2009 17:56:55 -0700, Douglas Alan wrote:

> Steven D'Aprano wrote:
> 
>> Why should a backslash in a string literal be an error?
> 
> Because in Python, if my friend sees the string "foo\xbar\n", he has no
> idea whether the "\x" is an escape sequence, or if it is just the
> characters "\x", unless he looks it up in the manual, or tries it out in
> the REPL, or what have you. 

Fair enough, but isn't that just another way of saying that if you look 
at a piece of code and don't know what it does, you don't know what it 
does unless you look it up or try it out?


> My friend is adamant that it would be better
> if he could just look at the string literal and know. He doesn't want to
> be bothered to have to store stuff like that in his head. He wants to be
> able to figure out programs just by looking at them, to the maximum
> degree that that is feasible.

I actually sympathize strongly with that attitude. But, honestly, your 
friend is a programmer (or at least pretends to be one *wink*). You can't 
be a programmer without memorizing stuff: syntax, function calls, modules 
to import, quoting rules, blah blah blah. Take C as an example -- there's 
absolutely nothing about () that says "group expressions or call a 
function" and {} that says "group a code block". You just have to 
memorize it. If you don't know what a backslash escape is going to do, 
why would you use it? I'm sure your friend isn't in the habit of randomly 
adding backslashes to strings just to see whether it will still compile.

This is especially important when reading (as opposed to writing) code. 
You read somebody else's code, and see "foo\xbar\n". Let's say you know 
it compiles without warning. Big deal -- you don't know what the escape 
codes do unless you've memorized them. What does \n resolve to? chr(13) 
or chr(97) or chr(0)? Who knows? 

Unless you know the rules, you have no idea what is in the string. 
Allowing \y to resolve to a literal backslash followed by y doesn't 
change that. All it means is that some \c combinations return a single 
character, and some return two.



> In comparison to Python, in C++, he can just look "foo\xbar\n" and know
> that "\x" is a special character. (As long as it compiles without
> warnings under g++.)

So what you mean is, he can just look at "foo\xbar\n" AND COMPILE IT 
USING g++, and know whether or not \x is a special character.

[sarcasm] Gosh. That's an enormous difference from Python, where you have 
to print the string at the REPL to know what it does. [/sarcasm]

Aside:
\x isn't a special character:

>>> "\x"
ValueError: invalid \x escape

However, \xba is:

>>> "\xba"
'\xba'
>>> len("\xba")
1
>>> ord("\xba")
186



> He's particularly annoyed too, that if he types "foo\xbar" at the REPL,
> it echoes back as "foo\\xbar". He finds that to be some sort of annoying
> DWIM feature, and if Python is going to have DWIM features, then it
> should, for example, figure out what he means by "\" and not bother him
> with a syntax error in that case.

Now your friend is confused. This is a good thing. Any backslash you see 
in Python's default string output is *always* an escape:

>>> "a string with a 'proper' escape \t (tab)"
"a string with a 'proper' escape \t (tab)"
>>> "a string with an 'improper' escape \y (backslash-y)"
"a string with an 'improper' escape \\y (backslash-y)"

The REPL is actually doing him a favour. It always escapes backslashes, 
so there is no ambiguity. A backslash is displayed as \\, any other \c is 
a special character.


> Of course I think that he's overreacting a bit. 

:)


> My point of view is that
> every language has *some* warts; Python just has a bit fewer than most.
> It would have been nice, I should think, if this wart had been "fixed"
> in Python 3, as I do consider it to be a minor wart.

And if anyone had cared enough to raise it a couple of years back, it 
possibly might have been.


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


Re: Unrecognized escape sequences in string literals

2009-08-09 Thread Steven D'Aprano
On Sun, 09 Aug 2009 18:34:14 -0700, Carl Banks wrote:

>> Why should a backslash in a string literal be an error?
> 
> Because the behavior of \ in a string is context-dependent, which means
> a reader can't know if \ is a literal character or escape character
> without knowing the context, and it means an innocuous change in context
> can cause a rather significant change in \.

*Any* change in context is significant with escapes.

"this \nhas two lines"

If you change the \n to a \t you get a significant difference. If you 
change the \n to a \y you get a significant difference. Why is the first 
one acceptable but the second not?


> IOW it's an error-prone mess.

I've never had any errors caused by this. I've never seen anyone write to 
this newsgroup confused over escape behaviour, or asking for help with an 
error caused by it, and until this thread, never seen anyone complain 
about it either.

Excuse my cynicism, but I believe that you are using "error-prone" to 
mean "I don't like this behaviour" rather than "it causes lots of errors".



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


Re: reloading the module imported as 'from ... import ...'

2009-08-09 Thread Steven D'Aprano
On Sun, 09 Aug 2009 22:48:31 -0700, AlF wrote:

> Steven D'Aprano wrote:
>> On Sun, 09 Aug 2009 20:43:41 -0700, AlF wrote:
>> 
>>> Hi,
>>>
>>> what is the best way to reload the module imported using 'from ...
>>> import ...'
>> 
>> 
>> Have you tried "from ... import ..." again?
>> 
>> 
> I have not because of an assumption that "import" imports the module
> just once. 

Ah, of course the cached module will still reflect the older version. 
Sorry, I was thinking about solving a different problem:

- In module "main" call "from A import a"
- Some other part of your code modifies A.a
- You want to have the imported a be refreshed with the value of A.a


No, my suggestion won't help in this situation.

Instead, you can:

(1) Delete the module from sys.modules, forcing Python to re-read it from 
disk:

import sys
del sys.modules['A']
from A import a

or

(2) Recognize that Python doesn't specifically support what you're trying 
to do. reload() is a convenience function, and you probably should stick 
to the "import A; A.a" form.


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


Re: Unrecognized escape sequences in string literals

2009-08-09 Thread Steven D'Aprano
On Sun, 09 Aug 2009 23:03:14 -0700, John Nagle wrote:

> if another escape character ever has to be
> added to the language, that may change the semantics of previously
> correct strings.

And that's the only argument in favour of prohibiting non-special 
backslash sequences I've seen yet that is even close to convincing.


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