Re: Sys.path entries

2009-12-30 Thread Marco Salden
On Dec 30, 8:13 pm, Alan Harris-Reid  wrote:
> Hi there,
>
> In my sys.path (interpreter only, no application loaded), I have the
> following strange entries...
> 'C:\\WINDOWS\\system32\\python31.zip'.  This file does not exist
> anywhere (although python31.dll does exist in \windows\system32\), where
> could it have come from?
> 'C:\\program files\\python31\\lib\\plat-win'.  There is no such
> directory, although I can see that this has been added by the PYTHONPATH
> varible in PyConfig.h (when is this loaded?)
>
> Is there any way of removing these entries, or are they best left where
> they are?  (I am using Python 3.1 on WinXP)
>
> Also, regarding PyConfig.h - is this read every time I start Python.exe?
>
> Many thanks,
> Alan Harris-Reid

Hi Alan,

Same for me: C:\Windows\system32\python25.zip is in the only non-"C:
\Python25" directroy&file in my sys.path (under Python 2.5).
No idea why it needs it. And also in my case the zip file isnt in that
location anyway. So also not 3K only or so.
But I have no issues with it (so far :-)), do you? Do you run into
problems because of this in the path?

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


Re: Importing bitly.py in twitter-gedit.py

2009-12-30 Thread Vikash Dhankar
any reply to my query ..
please send me

On Thu, Dec 31, 2009 at 10:28 AM, Vikash Dhankar wrote:

> Hi,
> I am newbie in the python, I am stuck into a small problem.
>
> Me and my friend are working on the gedit based Twitter plugin.
> http://code.google.com/p/gedit-twitter-plugin/
>
> Now I want to add the tiny URL thing into this. I am using the bitly
> API for this.
> Its is already available in the python bitly.py
> http://code.google.com/p/python-bitly/
>
> now i want to use this bitly.py into the main file ( importing the
> bitly.py to the twitter_gedit.py) .
>
> One thing more, bitly.py uses the django.utils so you can download
> that from http://www.djangoproject.com/download/
>
> Thanks. its open
>



-- 
Every Morning
Say yourself that today is going to be a great day.I am going to make
someone happy today...
Cheers " ; "
Georgy
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Create attribute from string

2009-12-30 Thread Chris Rebert
On Wed, Dec 30, 2009 at 9:22 PM, AON LAZIO  wrote:
> Hi,
>     I would like to know how we could create attribute from string
>
> say I want to assign value 0.05 to an object attribute
>
> I like to input "SIGNIFICANT" and 0.05 and get
> object.SIGFICANT equals to 0.05

setattr(obj, "SIGNIFICANT", 0.05)

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


Re: Cookies

2009-12-30 Thread Carsten Haese
Victor Subervi wrote:
> You know, neither one of those tutorials I followed gave clear, or any,
> instruction about putting a
> print cookie
> statement in the header! How misleading!

Don't blame the tutorials for your failure to read them carefully. The
tutorial you mentioned
(http://www.doughellmann.com/PyMOTW/Cookie/index.html) says the
following right at the beginning: "The Cookie module defines classes for
parsing and creating HTTP cookie *headers*." [Emphasis mine.]

Further down it says: "The output is a valid Set-Cookie *header* ready
to be passed to the client as part of the HTTP response." [Emphasis
mine.] You even copy-and-pasted a snippet containing that very sentence
into an earlier post on this thread, so how you can now claim that the
tutorial didn't mention this is quite beyond me.

--
Carsten Haese
http://informixdb.sourceforge.net

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


Re: getting name of passed reference

2009-12-30 Thread Tim Roberts
Joel Davis  wrote:
>
>Emile, essentially, the situation is that I'm trying to create an API
>for consumption scripting. As it stands now, in initial development
>they can pass callback function. The idea was to enable them to pass
>variables and have the handling function determine the type and just
>drop the value into it instead of calling function with the value as
>an argument. The problem with that approach is determining exactly
>which variable was passed. My idea was to use this to capture the name
>and then modify the globals for the executing frame so that the passed
>variable represents the new value.

You're making some rather dangerous and unwarranted assumptions here.
Consider your original code:

   def MyFunc ( varPassed ):
  print varPassed;
 
   MyFunc(nwVar)

What's going to happen if I do this:

   MyFunc( nwVar+1 )
   MyFunc( 27 )
   MyFunc( "abcde" )

If the thing passed in is a list or an object, you can modify the object in
place without trickery.  You can check that with the "type" operator:

   if type(varPassed) == list:
  pass
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: subprocess returncode is masked

2009-12-30 Thread Yinon Ehrlich
On Dec 30, 7:59 pm, Nobody  wrote:
> On Mon, 28 Dec 2009 17:12:23 +0100, Emmanuel wrote:
> > I'm using Python 2.6 and the new subprocess module to get the exit value
> > of an external executable. It appears the return value given by wait()
> > or poll() operations is masked under Unix: I only get the lower 8 bits.
> > So an exit value of 0x0402 in the C program will be seen as 0x02 in
> > Python. And this does not happen on Windows...
> > Any idea why that is ?
>
> That's how Unix works.
>
> The exit status of a process as reported by wait() (etc) is a 16-bit
> value (the first Unix systems had a 16-bit "int"). The top 8 bits (8-15)
> contain the exit code passed to exit() or "return"ed from main(),
> truncated to 8 bits. The bottom 7 bits (0-6) contain the signal number if
> the process was terminated by a signal. Bit 7 is set if the process dumped
> core.

See also: http://docs.python.org/library/os.html#os.wait
-- 
http://mail.python.org/mailman/listinfo/python-list


whoops: create a splash window in python

2009-12-30 Thread Ron Croonenberg

sorry about posting with the wrong subject...

*
hello,

is there a way, in python, to create a splash window and when the 
program has completed disappears by sending a msg to it? (I tried 
creating two gtk windows but gtk_main doesn't seem to return unless it 
gets closed.)


tia

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


Re: I think I found a bug in Python 2.6.4 (in the inspect module)

2009-12-30 Thread Ron Croonenberg

hello,

is there a way, in python, to create a splash window and when the 
program has completed disappears by sending a msg to it? (I tried 
creating two gtk windows but gtk_main doesn't seem to return unless it 
gets closed.)


tia

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


Create attribute from string

2009-12-30 Thread AON LAZIO
Hi,
I would like to know how we could create attribute from string

say I want to assign value 0.05 to an object attribute

I like to input "SIGNIFICANT" and 0.05 and get
object.SIGFICANT equals to 0.05

Thanks

-- 
Passion is my style
-- 
http://mail.python.org/mailman/listinfo/python-list


Thread performance on Python 2.6

2009-12-30 Thread Rodrick Brown
I started dabbling with threads in python and for some odd reason the
performance seems extremely poor on my 2 core system.
It this a simplified version spawn 2 threads write some data to a file and
time the results vs doing the same sequentially.
Why is the performance so much slower with the threaded version?


#!/usr/bin/python
import time
from threading import Thread
from tempfile import NamedTemporaryFile

BYTES=1000
class FileWriterThread(Thread):
def __init__(self,filenam):
Thread.__init__(self)
self.filenam = filenam

def run(self):
self.filename = NamedTemporaryFile(delete=False)
start = time.time()
for count in xrange(1,BYTES):
self.filename.write(str(count))
self.filename.write("\n")
end = time.time()

return (end - start)

def fileWriter(bytesToWrite):
f = NamedTemporaryFile(delete=False)
start = time.time()
for n in xrange(1,bytesToWrite):
f.write(str(n))
f.write("\n")
end = time.time()
return (end - start)

if __name__ == "__main__":
#tmpfile = NamedTemporaryFile(delete=False)
total = 0.0
start = time.time()
for x in xrange(2):
c = FileWriterThread(BYTES)
c.start()
c.join()
end = time.time()
print "Runtime (thread based): %f" % (end - start)
for x in xrange(2):
c = fileWriter(BYTES)
print "Runtime (None thread based): %f" % c
total += c
print "Total Runtime (None thread based): %f "  % total


rbr...@laptop:~/code/python$ python filewriter_thr.py
Runtime (thread based): 66.721260
Runtime (None thread based): 16.52
Runtime (None thread based): 16.078885
Total Runtime (None thread based): 32.078937

rbr...@laptop:~/code/python$ grep ^cpu.*cores /proc/cpuinfo
cpu cores : 2
cpu cores : 2

-- 
[ Rodrick R. Brown ]
http://www.rodrickbrown.com http://www.linkedin.com/in/rodrickbrown
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Windows, IDLE, __doc_, other

2009-12-30 Thread Lie Ryan

On 12/30/2009 6:21 AM, W. eWatson wrote:

Lie Ryan wrote:

On 12/29/2009 5:10 AM, W. eWatson wrote:

Lie Ryan wrote:

If you're on Windows, don't use the "Edit with IDLE" right-click
hotkey since that starts IDLE without subprocess. Use the shortcut
installed in your Start menu.

When I go to Start and select IDLE, Saves or Opens want to go into
C:/Python25. I have to motor over to my folder where I keep the source
code. The code is in a folder about 4 levels below the top. That's a bit
awkward.

Is there a way to go directly to the folder I normally work in?


These are the various "workarounds", I've used or heard:

1. Open using "Edit in IDLE", close it; then open IDLE properly from 
Start Menu and open your file from the list of "Recent files"
2. Shift-RightClick on the folder, get to "Open Command Window Here". 
Use python interpreter from there to execute "python -m idlelib.idle 
myfile.py".

3. create a .bat or shortcut file in your working directory to start IDLE
4. [GENERIC WARNING: Editing registry may damage your system] [SPECIFIC 
WARNING: There must be a reason the IDLE devs put the -n flag on the 
context menu, I'm not fully aware of the complications, and I disclaim 
myself from any damage that may be caused] Open Registry Editor, browse 
to these:

HKEY_CLASSES_ROOT\Python.File\shell\Edit with IDLE\command
HKEY_CLASSES_ROOT\Python.NoConFile\shell\Edit with IDLE\command
and remove the -n flag from the commands
--
http://mail.python.org/mailman/listinfo/python-list


Importing bitly.py in twitter-gedit.py

2009-12-30 Thread Vikash Dhankar
Hi,
I am newbie in the python, I am stuck into a small problem.

Me and my friend are working on the gedit based Twitter plugin.
http://code.google.com/p/gedit-twitter-plugin/

Now I want to add the tiny URL thing into this. I am using the bitly
API for this.
Its is already available in the python bitly.py
http://code.google.com/p/python-bitly/

now i want to use this bitly.py into the main file ( importing the
bitly.py to the twitter_gedit.py) .

One thing more, bitly.py uses the django.utils so you can download
that from http://www.djangoproject.com/download/

Thanks. its open
#!/usr/bin/python2.4
#
# Copyright 2009 Empeeric LTD. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from django.utils import simplejson
import urllib,urllib2
import urlparse
import string

BITLY_BASE_URL = "http://api.bit.ly/";
BITLY_API_VERSION = "2.0.1"

VERBS_PARAM = { 
 'shorten':'longUrl',   
 'expand':'shortUrl', 
 'info':'shortUrl',
 'stats':'shortUrl',
 'errors':'',
}

class BitlyError(Exception):
  '''Base class for bitly errors'''
  
  @property
  def message(self):
'''Returns the first argument used to construct this error.'''
return self.args[0]

class Api(object):
""" API class for bit.ly """
def __init__(self, login, apikey):
self.login = vikashdhankar
self.apikey = R_a55b050e658854f6846a01faa92f66ee 
self._urllib = urllib2

def shorten(self,longURL):
""" 
Takes either:
A long URL string and returns shortened URL string
Or a list of long URL strings and returnes a list of shortened URL strings.
"""
if not isinstance(longURL, list):
longURL = [longURL]

for index,url in enumerate(longURL):
if not url.startswith("http"):
longURL[index] = "http://"; + url

request = self._getURL("shorten",longURL)
result = self._fetchUrl(request)
json = simplejson.loads(result)
self._CheckForError(json)

res = []
for item in json['results'].values():
if item['shortKeywordUrl'] == "":
res.append(item['shortUrl'])
else:
res.append(item['shortKeywordUrl'])

if len(res) == 1:
return res[0]
else:
return res

def expand(self,shortURL):
""" Given a bit.ly url or hash, return long source url """
request = self._getURL("expand",shortURL)
result = self._fetchUrl(request)
json = simplejson.loads(result)
self._CheckForError(json)
return json['results'][string.split(shortURL, '/')[-1]]['longUrl']

def info(self,shortURL):
""" 
Given a bit.ly url or hash, 
return information about that page, 
such as the long source url
"""
request = self._getURL("info",shortURL)
result = self._fetchUrl(request)
json = simplejson.loads(result)
self._CheckForError(json)
return json['results'][string.split(shortURL, '/')[-1]]

def stats(self,shortURL):
""" Given a bit.ly url or hash, return traffic and referrer data.  """
request = self._getURL("stats",shortURL)
result = self._fetchUrl(request)
json = simplejson.loads(result)
self._CheckForError(json)
return Stats.NewFromJsonDict(json['results'])

def errors(self):
""" Get a list of bit.ly API error codes. """
request = self._getURL("errors","")
result = self._fetchUrl(request)
json = simplejson.loads(result)
self._CheckForError(json)
return json['results']

def setUrllib(self, urllib):
'''Override the default urllib implementation.

Args:
  urllib: an instance that supports the same API as the urllib2 module
'''
self._urllib = urllib

def _getURL(self,verb,paramVal): 
if not isinstance(paramVal, list):
paramVal = [paramVal]
  
params = [
  ('version',BITLY_API_VERSION),
  ('format','json'),
  ('login',self.login),
  ('apiKey',self.apikey),
]

verbParam = VERBS_PARAM[verb]   
if verbParam:
for val in paramVal:
params.append(( verbParam,val ))
   
encode

Re: Dangerous behavior of list(generator)

2009-12-30 Thread Benjamin Kaplan
On Wed, Dec 30, 2009 at 7:01 PM, Steven D'Aprano
 wrote:
>
> I don't see why. What's wrong with it? Unless you embed it in a call to
> list, or similar, it will explicitly raise StopIteration as expected.
>
>
>> I used to have that a lot in cases where not finding at least one valid
>> foo is an actual fatal error.
>
> What's wrong with the obvious solution?
>
> if not any(foo for foo in foos if foo.bar):
>    raise ValueError('need at least one valid foo')

That would require 2 iterations through foos- once in the test, once
for the assignment if successful. If foos takes a long time to iterate
through, it might be faster to put a try-except around the original
statement, catch the StopIteration, and raise a ValueError in its
place. Which I agree is much better practice than letting the
StopIteration signal the fatal error.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: I think I found a bug in Python 2.6.4 (in the inspect module)

2009-12-30 Thread Lie Ryan

On 12/30/2009 9:10 AM, inhahe wrote:

Python 2.6.4 (r264:75708, Oct 26 2009, 08:23:19) [MSC v.1500 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.

import inspect
def a(b=1): pass



inspect.getargvalues(a)

Traceback (most recent call last):
   File "", line 1, in
   File "C:\Python26\lib\inspect.py", line 816, in getargvalues
 args, varargs, varkw = getargs(frame.f_code)
AttributeError: 'function' object has no attribute 'f_code'

dir(a)

['__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr_
_', '__dict__', '__doc__', '__format__', '__get__', '__getattribute__', '__globa
ls__', '__hash__', '__init__', '__module__', '__name__', '__new__', '__reduce__'
, '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subcla
sshook__', 'func_closure', 'func_code', 'func_defaults', 'func_dict', 'func_doc'
, 'func_globals', 'func_name']




So i'm guessing that the attribute has been changed from func_code to
f_code but the inspect module wasn't updated to reflect that.


No, that wasn't the case. The argument of inspect.getargvalues() is a 
'frame object' not 'function object'.


e.g.:
>>> inspect.getargvalues(inspect.currentframe())

You could argue that the error message is misleading (should be 
TypeError instead), do you want a bug report on that?

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


Re: Bare Excepts

2009-12-30 Thread Steve Holden
Victor Subervi wrote:
> On Wed, Dec 30, 2009 at 3:29 PM, Ben Finney  > wrote:
> 
> samwyse mailto:samw...@gmail.com>> writes:
> 
> > I inherited some code that used bare excepts *everywhere*.  There were
> > about 4K lines of code, IIRC, and I think that they were more except
> > clauses than elses.
> 
> Visual Basic programmers will learn how to write “ON ERROR RESUME NEXT”
> http://www.vbinfozine.com/a_onerror.shtml> in any language put
> before them.
> 
> 
> Yet another example of children belittling others to make themselves
> feel important.
> beno
> 
So turn the mirror in yourself, and ask yourself why you just made that
comment? It takes all sorts to make a world, and we all need to run
along. Surely it's easier to ignore that kind of stuff than to
perpetuate it?

regards
 Steve
-- 
Steve Holden   +1 571 484 6266   +1 800 494 3119
PyCon is coming! Atlanta, Feb 2010  http://us.pycon.org/
Holden Web LLC http://www.holdenweb.com/
UPCOMING EVENTS:http://holdenweb.eventbrite.com/

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


Re: Cookies

2009-12-30 Thread Steve Holden
Victor Subervi wrote:
> You know, neither one of those tutorials I followed gave clear, or any,
> instruction about putting a
> print cookie
> statement in the header! How misleading!
> beno
> 
At the risk of repeating myself, if you understood more about what you
are trying to do you wouldn't have needed to be told because you would
have known that the cookies were transmitted as HTTP headers and that
you had to somehow put that information into the headers (in other
words, that creating a cookie was not sufficient to insert it into the
HTTP output stream).

regards
 Steve
-- 
Steve Holden   +1 571 484 6266   +1 800 494 3119
PyCon is coming! Atlanta, Feb 2010  http://us.pycon.org/
Holden Web LLC http://www.holdenweb.com/
UPCOMING EVENTS:http://holdenweb.eventbrite.com/

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


Re: Cookies

2009-12-30 Thread Victor Subervi
You know, neither one of those tutorials I followed gave clear, or any,
instruction about putting a
print cookie
statement in the header! How misleading!
beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Bare Excepts

2009-12-30 Thread Victor Subervi
On Wed, Dec 30, 2009 at 3:29 PM, Ben Finney

> wrote:

> samwyse  writes:
>
> > I inherited some code that used bare excepts *everywhere*.  There were
> > about 4K lines of code, IIRC, and I think that they were more except
> > clauses than elses.
>
> Visual Basic programmers will learn how to write “ON ERROR RESUME NEXT”
> http://www.vbinfozine.com/a_onerror.shtml> in any language put
> before them.
>

Yet another example of children belittling others to make themselves feel
important.
beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python and FastCGI

2009-12-30 Thread John Nagle

Steffen Ebermann wrote:

Hi,

this might be a little off topic (could be any other language) 
but I'm trying to set up Python to use FastCGI instead of plain CGI.


The basic setup is no problem but every tutorial (including Python's 
'HOWTO Use Python in the web') ends with some basic dispatch file and 
that's it. I guess I should know how to go about from there, but,

well I don't.

I guess I could put an execfile('index.py') into the dispatcher and
then rewrite my code for FastCGI (i.e. replace every print with
req.write() for jonpy), but that doesn't seem right to me.

Is there a better solution or do I misunderstand something entirely?
I would be glad if someone could point me in the right direction.

Thanks in advance.


   You don't print in an FCGI program.  At the end of the function,
you return a reply string.

   Here's the main program of a live FCGI application.  This is
from something that answers XMLHttpRequest request, rather than
serving HTML pages.  So it outputs XML.

Things to note:

1. FCGI programs can run for a long time, like days. So you
have to handle the possible loss of a database connection, as
is done here.

2. Catch and handle all exceptions.  FCGI won't give you much
information in the error log.

3. You have to specify everything that goes in the HTTP headers
by calling start_response().

4. Notice the last line:
WSGIServer(QuickSitetruthQuery).run()

That's the call which tells WSGIServer what function to call
for each request.

5. If you put an FCGI file in a directory from which Apache
will run CGI files, your FCGI program will be run as a CGI
program.  Everything will appear to work, because the FCGI
library understands this is a debug mode.  But you're loading
the program on each use, so the overhead is huge, as with CGI.
CGI is built into Apache at too low a level, and it will run
something as CGI even when you've told it a directory is
supposed to be used for FCGI.  So create an "fcgi" directory
someplace other than "cgi" and tell Apache to use that for
FCGI.

FCGI is a good system; it's just that the documentation isn't
very good.This code has been running a live
web site for two years now.


John Nagle

#!/usr/local/bin/python
### ... application-specific stuff deleted
from fcgi import WSGIServer
import MySQLdb
import cgi  
import urllib
import InfoDisplay  
import miscutils
db = None # database connection, held open for life of FCGI
#
#   The application
#
def QuickSitetruthQuery(environ, start_response):
global db   # static global - active database handle
try:
if db : # if previously attached
try :
db.ping() # test whether connection is still up
except MySQLdb.OperationalError, message:   # loss of conn.
db = None # we lost database connection
if db is None : # if no valid database handle
db = miscutils.dbattach(kdbfile) # connect to database
status = '200 OK' # normal status
headers = [('Content-type','text/xml'), ('charset','utf-8')]
reqlist = cgi.parse_qsl(environ['QUERY_STRING']) # Parse params
priority = 1# priority of request
sourceip = environ['REMOTE_ADDR'] # get IP address of client
urls = []   # list of URLs to check
for item in reqlist :   # for all items
(key, value) = item # extract item
if key.lower() == 'url' :   # want all "url" items,
urls.append(value)
elif key.lower() == 'priority' :# if priority
priority = int(value)   # get priority value
#   Make request; no waiting, no details
outstr = InfoDisplay.getratingXMLquick(db, kdbfile,
   urls, priority, sourceip) # get the rating XML
needretry = outstr.find('status="202"') >= 0   # if retry soon
if needretry :  # if the client will need to retry this request
headers.append(('Expires','-1')) # expire immediately
start_response(status, headers) # compose result
s = kprefixxml + outstr + ksuffixxml# construct output XML
return [s.encode('utf8')]   # encode as UTF8
except Exception, message:  # if trouble, report to user
#   Error handling
status = "500 Internal Error on Server"
response_headers = [("Content-type","text/html")]
start_response(status, response_headers)
s = "Internal error - request not processed.\n\n" +
traceback.format_exc()
s = s.replace("\n","")   # convert to HTML
return [s]
#
#Main FCGI program
#
WSGIServer(QuickSitetruthQuery).run()
--

Re: Python and FastCGI

2009-12-30 Thread MRAB

Steffen Ebermann wrote:

Hi,

this might be a little off topic (could be any other language) 
but I'm trying to set up Python to use FastCGI instead of plain CGI.


The basic setup is no problem but every tutorial (including Python's 
'HOWTO Use Python in the web') ends with some basic dispatch file and 
that's it. I guess I should know how to go about from there, but,

well I don't.

I guess I could put an execfile('index.py') into the dispatcher and
then rewrite my code for FastCGI (i.e. replace every print with
req.write() for jonpy), but that doesn't seem right to me.

Is there a better solution or do I misunderstand something entirely?
I would be glad if someone could point me in the right direction.

Thanks in advance.


Well, you don't have to replace every 'print', because it outputs by
calling sys.stdout.write(), so you could redirect the output by
replacing stdout with an instance that has a 'write' method, eg 'req'.
It might be as simple as doing:

sys.stdout = req


It might be worth a try.
--
http://mail.python.org/mailman/listinfo/python-list


Python and FastCGI

2009-12-30 Thread Steffen Ebermann
Hi,

this might be a little off topic (could be any other language) 
but I'm trying to set up Python to use FastCGI instead of plain CGI.

The basic setup is no problem but every tutorial (including Python's 
'HOWTO Use Python in the web') ends with some basic dispatch file and 
that's it. I guess I should know how to go about from there, but,
well I don't.

I guess I could put an execfile('index.py') into the dispatcher and
then rewrite my code for FastCGI (i.e. replace every print with
req.write() for jonpy), but that doesn't seem right to me.

Is there a better solution or do I misunderstand something entirely?
I would be glad if someone could point me in the right direction.

Thanks in advance.

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


Re: How to test a URL request in a "while True" loop

2009-12-30 Thread Steve Holden
Brian D wrote:
[...]
> I'm definitely acquiring some well-deserved schooling -- and it's
> really appreciated. I'd seen the "is/is not" preference before, but it
> just didn't stick.
> 
Yes, a lot of people have acquired the majority of their Python
education from this list - I have certainly learned a thing or two from
it over the years, and had some very interesting discussions.

is/is not are about object identity. Saying

  a is b

is pretty much the same thing as saying

  id(a) == id(b)

so it's a test that two expressions are references to the exact same
object. So it works with None, since there is only ever one value of
.

Be careful not to use it when there can be several different but equal
values, though.

> I see now that "pass" is redundant -- thanks for catching that.
> 
regards
 Steve
-- 
Steve Holden   +1 571 484 6266   +1 800 494 3119
PyCon is coming! Atlanta, Feb 2010  http://us.pycon.org/
Holden Web LLC http://www.holdenweb.com/
UPCOMING EVENTS:http://holdenweb.eventbrite.com/

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


Re: How to test a URL request in a "while True" loop

2009-12-30 Thread Brian D
On Dec 30, 7:08 pm, MRAB  wrote:
> Brian D wrote:
> > Thanks MRAB as well. I've printed all of the replies to retain with my
> > pile of essential documentation.
>
> > To follow up with a complete response, I'm ripping out of my mechanize
> > module the essential components of the solution I got to work.
>
> > The main body of the code passes a URL to the scrape_records function.
> > The function attempts to open the URL five times.
>
> > If the URL is opened, a values dictionary is populated and returned to
> > the calling statement. If the URL cannot be opened, a fatal error is
> > printed and the module terminates. There's a little sleep call in the
> > function to leave time for any errant connection problem to resolve
> > itself.
>
> > Thanks to all for your replies. I hope this helps someone else:
>
> > import urllib2, time
> > from mechanize import Browser
>
> > def scrape_records(url):
> >     maxattempts = 5
> >     br = Browser()
> >     user_agent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:
> > 1.9.0.16) Gecko/2009120208 Firefox/3.0.16 (.NET CLR 3.5.30729)'
> >     br.addheaders = [('User-agent', user_agent)]
> >     for count in xrange(maxattempts):
> >         try:
> >             print url, count
> >             br.open(url)
> >             break
> >         except urllib2.URLError:
> >             print 'URL error', count
> >             # Pretend a failed connection was fixed
> >             if count == 2:
> >                 url = 'http://www.google.com'
> >             time.sleep(1)
> >             pass
>
> 'pass' isn't necessary.
>
> >     else:
> >         print 'Fatal URL error. Process terminated.'
> >         return None
> >     # Scrape page and populate valuesDict
> >     valuesDict = {}
> >     return valuesDict
>
> > url = 'http://badurl'
> > valuesDict = scrape_records(url)
> > if valuesDict == None:
>
> When checking whether or not something is a singleton, such as None, use
> "is" or "is not" instead of "==" or "!=".
>
> >     print 'Failed to retrieve valuesDict'
>
>

I'm definitely acquiring some well-deserved schooling -- and it's
really appreciated. I'd seen the "is/is not" preference before, but it
just didn't stick.

I see now that "pass" is redundant -- thanks for catching that.

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


Re: Which version of MSVC?90.DLL's to distribute with Python 2.6 based Py2exe executables?

2009-12-30 Thread prakash jp
Hi all,
#use py2exe properly to create a single distributable exe

#setup.py- create a single exe that runs all boxex

from distutils.core import setup
import py2exe
import sys
# no arguments
if len(sys.argv) == 1:
sys.argv.append("py2exe")
# creates a standalone .exe file, no zip files
setup( options = {"py2exe": {"compressed": 1, "optimize": 2, "ascii": 1,
"bundle_files": 1}},
   zipfile = None,
   # replace test.py with your own code filename here ...
   console = [{"script": *'test.py*'}] )
---

vc ++ redistributable is a good option as well.


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


Re: How to test a URL request in a "while True" loop

2009-12-30 Thread MRAB

Brian D wrote:

Thanks MRAB as well. I've printed all of the replies to retain with my
pile of essential documentation.

To follow up with a complete response, I'm ripping out of my mechanize
module the essential components of the solution I got to work.

The main body of the code passes a URL to the scrape_records function.
The function attempts to open the URL five times.

If the URL is opened, a values dictionary is populated and returned to
the calling statement. If the URL cannot be opened, a fatal error is
printed and the module terminates. There's a little sleep call in the
function to leave time for any errant connection problem to resolve
itself.

Thanks to all for your replies. I hope this helps someone else:

import urllib2, time
from mechanize import Browser

def scrape_records(url):
maxattempts = 5
br = Browser()
user_agent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:
1.9.0.16) Gecko/2009120208 Firefox/3.0.16 (.NET CLR 3.5.30729)'
br.addheaders = [('User-agent', user_agent)]
for count in xrange(maxattempts):
try:
print url, count
br.open(url)
break
except urllib2.URLError:
print 'URL error', count
# Pretend a failed connection was fixed
if count == 2:
url = 'http://www.google.com'
time.sleep(1)
pass


'pass' isn't necessary.


else:
print 'Fatal URL error. Process terminated.'
return None
# Scrape page and populate valuesDict
valuesDict = {}
return valuesDict

url = 'http://badurl'
valuesDict = scrape_records(url)
if valuesDict == None:


When checking whether or not something is a singleton, such as None, use
"is" or "is not" instead of "==" or "!=".


print 'Failed to retrieve valuesDict'


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


Re: How to test a URL request in a "while True" loop

2009-12-30 Thread Brian D
Thanks MRAB as well. I've printed all of the replies to retain with my
pile of essential documentation.

To follow up with a complete response, I'm ripping out of my mechanize
module the essential components of the solution I got to work.

The main body of the code passes a URL to the scrape_records function.
The function attempts to open the URL five times.

If the URL is opened, a values dictionary is populated and returned to
the calling statement. If the URL cannot be opened, a fatal error is
printed and the module terminates. There's a little sleep call in the
function to leave time for any errant connection problem to resolve
itself.

Thanks to all for your replies. I hope this helps someone else:

import urllib2, time
from mechanize import Browser

def scrape_records(url):
maxattempts = 5
br = Browser()
user_agent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:
1.9.0.16) Gecko/2009120208 Firefox/3.0.16 (.NET CLR 3.5.30729)'
br.addheaders = [('User-agent', user_agent)]
for count in xrange(maxattempts):
try:
print url, count
br.open(url)
break
except urllib2.URLError:
print 'URL error', count
# Pretend a failed connection was fixed
if count == 2:
url = 'http://www.google.com'
time.sleep(1)
pass
else:
print 'Fatal URL error. Process terminated.'
return None
# Scrape page and populate valuesDict
valuesDict = {}
return valuesDict

url = 'http://badurl'
valuesDict = scrape_records(url)
if valuesDict == None:
print 'Failed to retrieve valuesDict'
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dangerous behavior of list(generator)

2009-12-30 Thread Steven D'Aprano
On Wed, 30 Dec 2009 15:18:11 -0800, Tom Machinski wrote:

> Thanks for the comment and discussion guys.
> 
> Bottom line, I'm going to have to remove this pattern from my code:
> 
>   foo = (foo for foo in foos if foo.bar).next()

I don't see why. What's wrong with it? Unless you embed it in a call to 
list, or similar, it will explicitly raise StopIteration as expected.


> I used to have that a lot in cases where not finding at least one valid
> foo is an actual fatal error. 

What's wrong with the obvious solution?

if not any(foo for foo in foos if foo.bar):
raise ValueError('need at least one valid foo')



> But using StopIteration to signal a fatal
> condition becomes a bug when interacting with list() as shown in the
> original post.

You shouldn't use StopIteration to signal fatal conditions, because 
that's not what it is for. It's acceptable to catch it when *directly* 
calling next, but otherwise you should expect that StopIteration will be 
caught and suppressed by just about anything.


> It would be nice if there was a builtin for "get the first element in a
> genexp, or raise an exception (which isn't StopIteration)", 

Not everything needs to be a built-in.

def get_first_or_fail(iterable_or_sequence):
it = iter(iterable_or_sequence)
try:
return it.next()  # use next(it) in Python 3
except StopIteration:
raise ValueError('empty iterable')

This is perfectly usable as a helper function, or it's short enough to be 
used in-line if you prefer.


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


Re: class version of func_globals?

2009-12-30 Thread Jan Kaliszewski

29-12-2009 samwyse  wrote:


On Dec 29, 5:18 am, Dave Angel  wrote:

samwyse wrote:
> Is there any way to get the global namespace of the module in which a
> class was defined?  Answers for both Python 2.x and 3.x will be
> cheerfully accepted.

I don't know if it's the same in general, but consider the following
sequence in 2.6:

import sys

class MyClass(object):
    pass

print "class--", dir(MyClass)
print "module--", dir(MyClass.__module__)
mod = sys.modules[MyClass.__module__]
print mod
print "globals--", dir(mod)

DaveA


Excellent!  Exactly what I wanted, but wasn't clever enough to figure
out for myself.  Thank you very much.


But dir(mod) gives you only names, not objects (though, of course, you
can get them "manually" with getattr(mod, name)). To get from a class
the same you get from function using func_globals (i.e. dictionary with
names as keys and objects as values), use:

mod = sys.modules[MyClass.__module__]  # (as above)
vars(mod)  # or mod.__dict__, though vars(mod) seems to me more elegant

Cheers,
*j

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


Re: Dangerous behavior of list(generator)

2009-12-30 Thread Tom Machinski
Thanks for the comment and discussion guys.

Bottom line, I'm going to have to remove this pattern from my code:

  foo = (foo for foo in foos if foo.bar).next()

I used to have that a lot in cases where not finding at least one
valid foo is an actual fatal error. But using StopIteration to signal
a fatal condition becomes a bug when interacting with list() as shown
in the original post.

It would be nice if there was a builtin for "get the first element in
a genexp, or raise an exception (which isn't StopIteration)", sort of
like:

  from itertools import islice

  def first_or_raise(genexp):
  L = list(islice(genexp, 1))
  if not L:
  raise RuntimeError('no elements found')
  return L[0]

I also think Jean-Paul's had a good point about how the problems in
the  list/genexp interaction could be addressed.

Thank you,

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


Re: Thanks for the help not given :)

2009-12-30 Thread Aahz
In article ,
J   wrote:
>> Jon Clements wrote:
>>
>>> You have a bear that likes a Python? The one I have just keeps going
>>> on about Piglet and eating my honey reserves...
>
>As for Jon, and Aahz, I'd try the teddy bear approach, but the last
>one I knew led me down the dark path to Perl and thus I try to avoid
>them whenever possible ;-)

Don't worry, you have now been inoculated.
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

Weinberg's Second Law: If builders built buildings the way programmers wrote 
programs, then the first woodpecker that came along would destroy civilization.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: The infamous "distutils has already been patched by" error

2009-12-30 Thread Aahz
[p&e]

In article ,
David  <71da...@libero.it> wrote:
>
>I am writing these notes because there is  little or no  documentation about
>this annoying problem.
>
>The error message in subject appears when you try to get the list of
>installed modules under the help() enviroment.

Please file a report at
http://bugs.python.org/
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

Weinberg's Second Law: If builders built buildings the way programmers wrote 
programs, then the first woodpecker that came along would destroy civilization.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: the need for 64 bits

2009-12-30 Thread Aahz
In article ,
Cameron Simpson   wrote:
>On 29Dec2009 21:42, Aahz  wrote:
>| In article 
><8950e4a5-f630-4ffb-b7ed-5c539913a...@a6g2000yqm.googlegroups.com>,
>| Mensanator   wrote:
>| >Ah, the 8 GB Mac wouldn't have helped. Glad I didn't spend the extra
>| >$1000.
>| 
>| It's almost always cheaper to buy your Mac and then upgrade the RAM
>| separately.
>
>Unless it's a Macbook Air. Then you're stuck with 2GB max:-(

No VM for you!  I'm already unhappy with VM performance on my 4GB
machine; I can't wait for the weekend to install 8GB instead.
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

Weinberg's Second Law: If builders built buildings the way programmers wrote 
programs, then the first woodpecker that came along would destroy civilization.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: detect interactivity

2009-12-30 Thread Steven D'Aprano
On Wed, 30 Dec 2009 14:42:12 +0100, Vito 'ZeD' De Tullio wrote:

> Steven D'Aprano wrote:
> 
> 
>>> if I run 'python <<< "import sys; print(sys.ps1)"', I get an error.
>> 
>> Of course you do, because you're not running interactively
> 
> Excuse me, why do you say that?

Two reasons.

First, because sys.ps1 is documented as only existing in an interactive 
environment, and sure enough, sys.ps1 fails to exist when you run the 
above.

And secondly, and much more importantly, if you run that command, you do 
not get an interactive prompt.

The format of the command being run is a bash "here string", more-or-less 
equivalent to either of:

echo "import sys; print(sys.ps1)" | python
python -c "import sys; print(sys.ps1)"

both of which also exit with AttributeError.

If you really want to see what's going on, have a look at this:


[st...@sylar ~]$ python -i -c "import sys; print(sys.ps1)"
Traceback (most recent call last):
  File "", line 1, in 
AttributeError: 'module' object has no attribute 'ps1'
>>> sys.ps1
'>>> '


The -c switch tells Python to execute whatever comes next, and the -i 
switch tells Python to enter interactive mode afterwards. At first, 
sys.ps1 does not exist and you get an AttributeError, but then the -i 
switch kicks in, sys.ps1 is defined and you get a prompt.



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


Re: Dynamic text color

2009-12-30 Thread John Posner
On Wed, 30 Dec 2009 12:58:06 -0500, Dave McCormick   
wrote:



Hi All,

I am new to Python and the list so I hope  I am posting this correctly...

I am working on a way to have text automatically formated in a Tkiniter  
Text widget and would like some input on my code.
Currently I am using Python 2.5 because the server I use has that  
installed. Tkinter is tk8.4.


Most of the time when I type red, blue, or green the code works as  
expected.  When I copy paste text into the widget the last line is  
parsed with part of the previous lines

So I guess the problem is in the "looping"?

Here is my code:
from Tkinter import *
root = Tk()
def get_position(event):
start = 1.0


A couple of problems here: you define "start", but then never use it.  
Worse, it looks like you don't understand that a line-column index into a  
Tkinter Text widget is a STRING, not a FLOAT.




while 1:   pos = Tbox.search("red",END,backwards=TRUE)


I suggest that you use Tbox.get() instead of Tbox.search(), and then use  
Python's more powerful text-search tools. More on this below.




if not pos:
break
red = pos + "-1c"
Tbox.tag_add("red", pos, float(pos)+.03)
Tbox.tag_config("red", foreground="red")


You don't want to define the "red" tag every time get_position() is  
executed -- that is, every time the user presses a key. Define the  
red/green/blue tags just once, right after you create the Text widget.




 pos = Tbox.search("blue",END,backwards=TRUE)
if not pos:
break
blue = pos + "-1c"
Tbox.tag_add("blue", pos, float(pos)+.04)
Tbox.tag_config("blue", foreground="blue")

pos = Tbox.search("green",END,backwards=TRUE)
if not pos:
break
green = pos + "-1c"
Tbox.tag_add("green", pos, float(pos)+.05)
Tbox.tag_config("green", foreground="green")


The previous 6 lines are almost identical to the 6 lines that precede  
them. This is fine for prototyping, but when you find yourself writing  
code like this, think about using a loop or a parameterized function call.  
For example, you might write this function:


  def insert_color_markup(color):
  ...

... and then call it as many times as you need to:

  insert_color_markup("red")
  insert_color_markup("green")
  insert_color_markup("blue")

Now, about those text-search tools: the "re" (regular expression) module  
include the function "finditer". This is a real power tool, combining  
regular expressions and Python iterators -- both of which can be  
intimidating to newcomers. But it's just what you want, IMHO. I hope the  
following annotated IDLE transcript convinces you:


Python 2.6.4 (r264:75708, Oct 26 2009, 08:23:19) [MSC v.1500 32 bit  
(Intel)] on win32

import re



text = """The red ball is red, not green. On other other

... hand, the green ball has both red and blue highlights.
... Thank you.
... """


re.finditer("red", text)



... not too exciting, but this is better:


list(re.finditer("red", text))
[<_sre.SRE_Match object at 0x00C01F70>, <_sre.SRE_Match object at  
0x00C06E20>, <_sre.

SRE_Match object at 0x00C06E58>]

... this list indicates that we got three hits on the word "red"


[ matchobj.span() for matchobj in re.finditer("red", text) ]

[(4, 7), (16, 19), (77, 80)]

... paydirt: a list of (start,end) pairs for an invocation of  
Text.tag_add()


One more hint: forget about the line-column indexes into the contexts of a  
Text widget. Just count characters from the beginning, e.g.:


   "1.0 + %d chars" % start_position


break

Tbox = Text(root,width=40, height=15, wrap=CHAR)
Tbox.grid(column=0, row=0, sticky=(N+W+E+S))
root.grid_columnconfigure(0, weight=1)
root.grid_rowconfigure(0, weight=1)
Tbox.bind("", get_position)
Tbox.focus()
root.mainloop()

Thank you,
Dave


I hope this set of hints is helpful, and not too disjointed, terse, or  
cryptic. I think this is a cute little app!


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


Re: DST and datetime

2009-12-30 Thread Ben Finney
"W. eWatson"  writes:

> =Program
> from datetime import datetime, timedelta
> import time
>
> DST_dict = { # West coast, 8 hours from Greenwich for PST
>  2007:("2007/03/11 02:00:00", "2007/11/04 02:00:00"),
>  2008:("2008/03/09 02:00:00", "2008/11/02 02:00:00"),
>  2009:("2009/03/08 02:00:00", "2009/11/01 02:00:00"),
>  2010:("2010/03/14 02:00:00", "2010/11/07 02:00:00")}

Or you could use the ready-made wheel maintained by others:

tzinfo Objects
http://docs.python.org/library/datetime.html#tzinfo-objects>

World timezone definitions, modern and historical
http://pypi.python.org/pypi/pytz>

-- 
 \  “Ignorance more frequently begets confidence than does |
  `\   knowledge.” —Charles Darwin, _The Descent of Man_, 1871 |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Bare Excepts

2009-12-30 Thread Ben Finney
samwyse  writes:

> I inherited some code that used bare excepts *everywhere*.  There were
> about 4K lines of code, IIRC, and I think that they were more except
> clauses than elses.

Visual Basic programmers will learn how to write “ON ERROR RESUME NEXT”
http://www.vbinfozine.com/a_onerror.shtml> in any language put
before them.

-- 
 \ “I'm a born-again atheist.” —Gore Vidal |
  `\   |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to test a URL request in a "while True" loop

2009-12-30 Thread Brian D
On Dec 30, 12:31 pm, Philip Semanchuk  wrote:
> On Dec 30, 2009, at 11:00 AM, Brian D wrote:
>
>
>
> > I'm actually using mechanize, but that's too complicated for testing
> > purposes. Instead, I've simulated in a urllib2 sample below an attempt
> > to test for a valid URL request.
>
> > I'm attempting to craft a loop that will trap failed attempts to
> > request a URL (in cases where the connection intermittently fails),
> > and repeat the URL request a few times, stopping after the Nth attempt
> > is tried.
>
> > Specifically, in the example below, a bad URL is requested for the
> > first and second iterations. On the third iteration, a valid URL will
> > be requested. The valid URL will be requested until the 5th iteration,
> > when a break statement is reached to stop the loop. The 5th iteration
> > also restores the values to their original state for ease of repeat
> > execution.
>
> > What I don't understand is how to test for a valid URL request, and
> > then jump out of the "while True" loop to proceed to another line of
> > code below the loop. There's probably faulty logic in this approach. I
> > imagine I should wrap the URL request in a function, and perhaps store
> > the response as a global variable.
>
> > This is really more of a basic Python logic question than it is a
> > urllib2 question.
>
> Hi Brian,
> While I don't fully understand what you're trying to accomplish by  
> changing the URL to google.com after 3 iterations, I suspect that some  
> of your trouble comes from using "while True". Your code would be  
> clearer if the while clause actually stated the exit condition. Here's  
> a suggestion (untested):
>
> MAX_ATTEMPTS = 5
>
> count = 0
> while count <= MAX_ATTEMPTS:
>     count += 1
>     try:
>        print 'attempt ' + str(count)
>        request = urllib2.Request(url, None, headers)
>        response = urllib2.urlopen(request)
>        if response:
>           print 'True response.'
>     except URLError:
>        print 'fail ' + str(count)
>
> You could also save the results  (untested):
>
> MAX_ATTEMPTS = 5
>
> count = 0
> results = [ ]
> while count <= MAX_ATTEMPTS:
>     count += 1
>     try:
>        print 'attempt ' + str(count)
>        request = urllib2.Request(url, None, headers)
>        f = urllib2.urlopen(request)
>        # Note that here I ignore the doc that says "None may be
>        # returned if no handler handles the request". Caveat emptor.
>        results.append(f.info())
>        f.close()
>     except URLError:
>        # Even better, append actual reasons for the failure.
>        results.append(False)
>
> for result in results:
>     print result
>
> I guess if you're going to do the same number of attempts each time, a  
> for loop would be more expressive, but you probably get the idea.
>
> Hope this helps
> Philip

Nice to have options, Philip. Thanks! I'll give your solution a try in
mechanize as well. I really can't thank you enough for contributing to
helping me solve this issue. I love Python.
-- 
http://mail.python.org/mailman/listinfo/python-list


DST and datetime

2009-12-30 Thread W. eWatson

Try this. It works for me and my application.

=Program
from datetime import datetime, timedelta
import time

DST_dict = { # West coast, 8 hours from Greenwich for PST
 2007:("2007/03/11 02:00:00", "2007/11/04 02:00:00"),
 2008:("2008/03/09 02:00:00", "2008/11/02 02:00:00"),
 2009:("2009/03/08 02:00:00", "2009/11/01 02:00:00"),
 2010:("2010/03/14 02:00:00", "2010/11/07 02:00:00")}

def adjust_DST(DT_stamp, spring, fall):
# /mm/dd hh:mm:ss in,
print "Date: ", DT_stamp
format = '%Y/%m/%d %H:%M:%S'
dt = datetime(*(time.strptime(DT_stamp, format)[0:6])) # get six tuple
dspring = datetime(*(time.strptime(spring, format)[0:6]))
dfall   = datetime(*(time.strptime(fall, format)[0:6]))
if ((dt >= dspring) and (dt <= dfall)):
print "   adjustment"
adj = timedelta(seconds = 3600)
dt = dt + adj
else:
print "   no adjustment"
format = '%Y/%m/%d %H:%M:%S'
return dt.strftime(format)

print "DST Adjustment"
print "   " + adjust_DST("2007/03/28 12:45:10", \
"2007/03/11 02:00:00", "2007/11/04 02:00:00" )
print "   " + adjust_DST("2009/11/26 20:35:15", \
"2007/03/11 02:00:00", "2007/11/04 02:00:00" )

===Results==
ST Adjustment
Date:  2007/03/28 12:45:10
   adjustment
   2007/03/28 13:45:10
Date:  2009/11/26 20:35:15
   no adjustment
   2009/11/26 20:35:15
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python 2.6 ftplib has timeout parameter, but how to detect a timeout

2009-12-30 Thread Giampaolo Rodola'
On 30 Dic, 18:52, MrJean1  wrote:
> Brendan,
>
> The timeout argument of the FTP class (and the connect method) is used
> only to establish the connection to FTP sockets.  If the timeout
> expires, an error called socket.timeout is raised.
>
> AFAIK, the timeout argument does not limit FTP transfers.  To impose a
> time limit on FTP transfers, try using the timelimited function from
> this recipe:
>
>  
>
> /Jean
>
> On Dec 14, 11:08 am, Brendan  wrote:
>
>
>
> > I was quite happy to see that ftplib in Python 2.6 now has a timeout
> > parameter. With large file downloads my script would often hang,
> > presumably from timing out. Now that there is a timeout parameter, how
> > would I detect when a timeout occurs?

Sorry, I forgot about this.
I had also opened a ticket for this, a long time ago:
http://bugs.python.org/issue4814

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


Sys.path entries

2009-12-30 Thread Alan Harris-Reid


Hi there,

In my sys.path (interpreter only, no application loaded), I have the 
following strange entries...
'C:\\WINDOWS\\system32\\python31.zip'.  This file does not exist 
anywhere (although python31.dll does exist in \windows\system32\), where 
could it have come from?
'C:\\program files\\python31\\lib\\plat-win'.  There is no such 
directory, although I can see that this has been added by the PYTHONPATH 
varible in PyConfig.h (when is this loaded?)


Is there any way of removing these entries, or are they best left where 
they are?  (I am using Python 3.1 on WinXP)


Also, regarding PyConfig.h - is this read every time I start Python.exe?

Many thanks,
Alan Harris-Reid
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to test a URL request in a "while True" loop

2009-12-30 Thread MRAB

Brian D wrote:

On Dec 30, 11:06 am, samwyse  wrote:

On Dec 30, 10:00 am, Brian D  wrote:


What I don't understand is how to test for a valid URL request, and
then jump out of the "while True" loop to proceed to another line of
code below the loop. There's probably faulty logic in this approach. I
imagine I should wrap the URL request in a function, and perhaps store
the response as a global variable.
This is really more of a basic Python logic question than it is a
urllib2 question.

There, I've condensed your question to what you really meant to say.
You have several approaches.  First, let's define some useful objects:>>> 
max_attempts = 5

def do_something(i):

assert 2 < i < 5

Getting back to original question, if you want to limit the number of
attempts, don't use a while, use this:


for count in xrange(max_attempts):

print 'attempt', count+1
do_something(count+1)

attempt 1
Traceback (most recent call last):
  File "", line 3, in 
do_something(count+1)
  File "", line 2, in do_something
assert 2 < i < 5
AssertionError

If you want to keep exceptions from ending the loop prematurely, you
add this:


for count in xrange(max_attempts):

print 'attempt', count+1
try:
do_something(count+1)
except StandardError:
pass

Note that bare except clauses are *evil* and should be avoided.  Most
exceptions derive from StandardError, so trap that if you want to
catch errors.  Finally, to stop iterating when the errors cease, do
this:


try:

for count in xrange(max_attempts):
print 'attempt', count+1
try:
do_something(count+1)
raise StopIteration
except StandardError:
pass
except StopIteration:
pass

attempt 1
attempt 2
attempt 3

Note that StopIteration doesn't derive from StandardError, because
it's not an error, it's a notification.  So, throw it if and when you
want to stop iterating.

BTW, note that you don't have to wrap your code in a function.
do_something could be replaced with it's body and everything would
still work.


I'm totally impressed. I love elegant code. Could you tell I was
trained as a VB programmer? I think I can still be reformed.

I appreciate the admonition not to use bare except clauses. I will
avoid that in the future.

I've never seen StopIteration used -- and certainly not used in
combination with a try/except pair. That was an exceptionally valuable
lesson.

I think I can take it from here, so I'll just say thank you, Sam, for
steering me straight -- very nice.


Instead of raising StopIteration you could use 'break':

for count in xrange(max_attempts):
print 'attempt', count + 1
try:
do_something(count + 1)
break
except StandardError:
pass

The advantage, apart from the length, is that you can then add the
'else' clause to the 'for' loop, which will be run if it _didn't_ break
out of the loop. If you break out only after do_something() is
successful, then not breaking out means that do_something() never
succeeded:

for count in xrange(max_attempts):
print 'attempt', count + 1
try:
do_something(count + 1)
break
except StandardError:
pass
else:
print 'all attempts failed'
--
http://mail.python.org/mailman/listinfo/python-list


Re: Portable way to tell if a process is still alive

2009-12-30 Thread Nobody
On Tue, 29 Dec 2009 12:35:11 +0430, Laszlo Nagy wrote:

> Suppose we have a program that writes its process id into a pid file. 
> Usually the program deletes the pid file when it exists... But in some 
> cases (for example, killed with kill -9 or TerminateProcess) pid file is 
> left there. I would like to know if a process (given with its process 
> id) is still running or not. I know that this can be done with OS 
> specific calls. But that is not portable. It can also be done by 
> executing "ps -p 23423" with subprocess module, but that is not portable 
> either. Is there a portable way to do this?
> 
> If not, would it be a good idea to implement this (I think very 
> primitive) function in the os module?

Not only is there no way to do it portably, there is no way to do it
reliably for the general case. The problem is that processes do not have
unique identifiers. A PID only uniquely identifies a running process; once
the process terminates, its PID becomes available for re-use.

On Unix, it's easy enough to detect whether a given PID is in use:
kill(pid, 0) will fail with ESRCH if the pid isn't in use.

But if the PID *is* in use, you don't know whether it's being used for the
process which wrote the PID file, or if that process died and its PID is
now being re-used by another process.

A more reliable approach would be for the creator to write not only its
PID, but also its start time to the file. Any subsequent process which
re-uses the PID is bound to have a later start time. However, the
difference could conceivably be less than a second, and getting the start
time of a process to better than a second isn't portable between Unices,
and may not even be possible.

More reliable still would be for the creator to place a lock on the
PID file, then test for the presence of the lock. Ensure that
testing for the lock doesn't itself lock the file in a way which could
fool other processes testing for the presence of a lock; e.g. have the
creator place an exclusive lock and test by attempting to place a shared
lock.


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


Re: How to test a URL request in a "while True" loop

2009-12-30 Thread Philip Semanchuk


On Dec 30, 2009, at 11:00 AM, Brian D wrote:


I'm actually using mechanize, but that's too complicated for testing
purposes. Instead, I've simulated in a urllib2 sample below an attempt
to test for a valid URL request.

I'm attempting to craft a loop that will trap failed attempts to
request a URL (in cases where the connection intermittently fails),
and repeat the URL request a few times, stopping after the Nth attempt
is tried.

Specifically, in the example below, a bad URL is requested for the
first and second iterations. On the third iteration, a valid URL will
be requested. The valid URL will be requested until the 5th iteration,
when a break statement is reached to stop the loop. The 5th iteration
also restores the values to their original state for ease of repeat
execution.

What I don't understand is how to test for a valid URL request, and
then jump out of the "while True" loop to proceed to another line of
code below the loop. There's probably faulty logic in this approach. I
imagine I should wrap the URL request in a function, and perhaps store
the response as a global variable.

This is really more of a basic Python logic question than it is a
urllib2 question.


Hi Brian,
While I don't fully understand what you're trying to accomplish by  
changing the URL to google.com after 3 iterations, I suspect that some  
of your trouble comes from using "while True". Your code would be  
clearer if the while clause actually stated the exit condition. Here's  
a suggestion (untested):


MAX_ATTEMPTS = 5

count = 0
while count <= MAX_ATTEMPTS:
   count += 1
   try:
  print 'attempt ' + str(count)
  request = urllib2.Request(url, None, headers)
  response = urllib2.urlopen(request)
  if response:
 print 'True response.'
   except URLError:
  print 'fail ' + str(count)



You could also save the results  (untested):

MAX_ATTEMPTS = 5

count = 0
results = [ ]
while count <= MAX_ATTEMPTS:
   count += 1
   try:
  print 'attempt ' + str(count)
  request = urllib2.Request(url, None, headers)
  f = urllib2.urlopen(request)
  # Note that here I ignore the doc that says "None may be
  # returned if no handler handles the request". Caveat emptor.
  results.append(f.info())
  f.close()
   except URLError:
  # Even better, append actual reasons for the failure.
  results.append(False)

for result in results:
   print result

I guess if you're going to do the same number of attempts each time, a  
for loop would be more expressive, but you probably get the idea.



Hope this helps
Philip
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to test a URL request in a "while True" loop

2009-12-30 Thread Brian D
On Dec 30, 11:06 am, samwyse  wrote:
> On Dec 30, 10:00 am, Brian D  wrote:
>
> > What I don't understand is how to test for a valid URL request, and
> > then jump out of the "while True" loop to proceed to another line of
> > code below the loop. There's probably faulty logic in this approach. I
> > imagine I should wrap the URL request in a function, and perhaps store
> > the response as a global variable.
>
> > This is really more of a basic Python logic question than it is a
> > urllib2 question.
>
> There, I've condensed your question to what you really meant to say.
> You have several approaches.  First, let's define some useful objects:>>> 
> max_attempts = 5
> >>> def do_something(i):
>
>         assert 2 < i < 5
>
> Getting back to original question, if you want to limit the number of
> attempts, don't use a while, use this:
>
> >>> for count in xrange(max_attempts):
>
>         print 'attempt', count+1
>         do_something(count+1)
>
> attempt 1
> Traceback (most recent call last):
>   File "", line 3, in 
>     do_something(count+1)
>   File "", line 2, in do_something
>     assert 2 < i < 5
> AssertionError
>
> If you want to keep exceptions from ending the loop prematurely, you
> add this:
>
> >>> for count in xrange(max_attempts):
>
>         print 'attempt', count+1
>         try:
>                 do_something(count+1)
>         except StandardError:
>                 pass
>
> Note that bare except clauses are *evil* and should be avoided.  Most
> exceptions derive from StandardError, so trap that if you want to
> catch errors.  Finally, to stop iterating when the errors cease, do
> this:
>
> >>> try:
>
>         for count in xrange(max_attempts):
>                 print 'attempt', count+1
>                 try:
>                         do_something(count+1)
>                         raise StopIteration
>                 except StandardError:
>                         pass
> except StopIteration:
>         pass
>
> attempt 1
> attempt 2
> attempt 3
>
> Note that StopIteration doesn't derive from StandardError, because
> it's not an error, it's a notification.  So, throw it if and when you
> want to stop iterating.
>
> BTW, note that you don't have to wrap your code in a function.
> do_something could be replaced with it's body and everything would
> still work.

I'm totally impressed. I love elegant code. Could you tell I was
trained as a VB programmer? I think I can still be reformed.

I appreciate the admonition not to use bare except clauses. I will
avoid that in the future.

I've never seen StopIteration used -- and certainly not used in
combination with a try/except pair. That was an exceptionally valuable
lesson.

I think I can take it from here, so I'll just say thank you, Sam, for
steering me straight -- very nice.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: subprocess returncode is masked

2009-12-30 Thread Nobody
On Mon, 28 Dec 2009 17:12:23 +0100, Emmanuel wrote:

> I'm using Python 2.6 and the new subprocess module to get the exit value 
> of an external executable. It appears the return value given by wait() 
> or poll() operations is masked under Unix: I only get the lower 8 bits. 
> So an exit value of 0x0402 in the C program will be seen as 0x02 in 
> Python. And this does not happen on Windows...
> Any idea why that is ?

That's how Unix works.

The exit status of a process as reported by wait() (etc) is a 16-bit
value (the first Unix systems had a 16-bit "int"). The top 8 bits (8-15)
contain the exit code passed to exit() or "return"ed from main(),
truncated to 8 bits. The bottom 7 bits (0-6) contain the signal number if
the process was terminated by a signal. Bit 7 is set if the process dumped
core.

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


Dynamic text color

2009-12-30 Thread Dave McCormick

Hi All,

I am new to Python and the list so I hope  I am posting this correctly...

I am working on a way to have text automatically formated in a Tkiniter 
Text widget and would like some input on my code.
Currently I am using Python 2.5 because the server I use has that 
installed. Tkinter is tk8.4.


Most of the time when I type red, blue, or green the code works as 
expected.  When I copy paste text into the widget the last line is 
parsed with part of the previous lines

So I guess the problem is in the "looping"?

Here is my code:
from Tkinter import *
root = Tk()
def get_position(event):
   start = 1.0
   while 1:   
   pos = Tbox.search("red",END,backwards=TRUE)

   if not pos:
   break
   red = pos + "-1c"
   Tbox.tag_add("red", pos, float(pos)+.03)
   Tbox.tag_config("red", foreground="red")

   pos = Tbox.search("blue",END,backwards=TRUE)

   if not pos:
   break
   blue = pos + "-1c"
   Tbox.tag_add("blue", pos, float(pos)+.04)
   Tbox.tag_config("blue", foreground="blue")

   pos = Tbox.search("green",END,backwards=TRUE)
   if not pos:
   break
   green = pos + "-1c"
   Tbox.tag_add("green", pos, float(pos)+.05)
   Tbox.tag_config("green", foreground="green")
   break

Tbox = Text(root,width=40, height=15, wrap=CHAR)
Tbox.grid(column=0, row=0, sticky=(N+W+E+S))
root.grid_columnconfigure(0, weight=1)
root.grid_rowconfigure(0, weight=1)
Tbox.bind("", get_position)
Tbox.focus()
root.mainloop()

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


Re: Python 2.6 ftplib has timeout parameter, but how to detect a timeout

2009-12-30 Thread MrJean1
Brendan,

The timeout argument of the FTP class (and the connect method) is used
only to establish the connection to FTP sockets.  If the timeout
expires, an error called socket.timeout is raised.

AFAIK, the timeout argument does not limit FTP transfers.  To impose a
time limit on FTP transfers, try using the timelimited function from
this recipe:

 

/Jean



On Dec 14, 11:08 am, Brendan  wrote:
> I was quite happy to see that ftplib in Python 2.6 now has a timeout
> parameter. With large file downloads my script would often hang,
> presumably from timing out. Now that there is a timeout parameter, how
> would I detect when a timeout occurs?

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


Re: socket programming

2009-12-30 Thread Mark Tolonen


"Zubin Mithra"  wrote in message 
news:8e7c74320912300315r625f4c89kb8002e4b8c384...@mail.gmail.com...

The code snippet i have pasted at,

http://paste.pocoo.org/show/160555/

produces a traceback which also has been pasted at the above link. The
snippet attempts at socket programming using OOPs concepts. Please help.

Thankx in advance
Zubin Mithra


If you're trying to be a server, you need to listen() before accept(), and I 
wouldn't call the method "connect()".


If you're trying to be a client, you can skip the bind() and call connect() 
instead of accept().


-Mark


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


Re: Simple distributed example for learning purposes?

2009-12-30 Thread Nobody
On Sat, 26 Dec 2009 20:06:02 +, Tim Golden wrote:

> I'm trying to come up with something which will illustrate
> the usefulness of a distributed processing model. Since I
> may not be using the term "distributed" exactly, my
> criteria are:
> 
> * It should be clear that the application produces results
> sooner when run via multiple cooperating computers 
> than when run on one. 
> 
> * The problem being solved should be broadly comprehensible by
> the students. This rules out some abstruse mathematical
> calculation which would benefit from multiple processors but
> which will fail to engage their interest.

Rendering fractals? Easy to parallelise, easy to code, easy to make slow
enough that the speed-up is noticeable.

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


Re: Cookies

2009-12-30 Thread Victor Subervi
On Wed, Dec 30, 2009 at 12:51 PM, Carsten Haese wrote:

> Victor Subervi wrote:
> > Comments from a left-brain thinker without any concept of how difficult
> > it is for a right-brain thinker to think like you. Care to compare
> > poetry? I'd bury you.
>
> That may be so, but the difference is that Steve is not trying to earn a
> living writing poetry as far as I know, whereas you appear to be trying
> to earn a living writing programs. If you can't learn to think like a
> programmer, sooner or later you'll have to face the grim reality that
> you'll never earn a living as a programmer. Maybe you should try to earn
> a living as a poet instead.
>

PS. There is something I am led to explore in programming. I'm doing ok.
Once I'm on my feet (I just arrived back in the states from the Dominican
Republic where I went broke) I'll go back to outsourcing and just be the
front end for my business. I'm damn good in sales. But I have to build this
shopping cart first, and frankly, despite it all, I'm rather enjoying it.
Yeah, if you can find me a publisher who's interested in a ripping hot epic
poem, let me know. Haven't found one yet...wrong century. I'm working up my
singing to start hitting the clubs and make money that way. But Carsten, I
dont' work for money. I work for fun. And despite it all, I actually enjoy
this. So I will continue...until something I enjoy more, like maybe music
and dance, intervenes.
beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Cookies

2009-12-30 Thread Victor Subervi
On Wed, Dec 30, 2009 at 12:51 PM, Carsten Haese wrote:

> Victor Subervi wrote:
> > Comments from a left-brain thinker without any concept of how difficult
> > it is for a right-brain thinker to think like you. Care to compare
> > poetry? I'd bury you.
>
> That may be so, but the difference is that Steve is not trying to earn a
> living writing poetry as far as I know, whereas you appear to be trying
> to earn a living writing programs. If you can't learn to think like a
> programmer, sooner or later you'll have to face the grim reality that
> you'll never earn a living as a programmer. Maybe you should try to earn
> a living as a poet instead.
>

EEK GADS! He can't even understand a metaphor! Can't you use your right
brain to understand a metaphor?! Do you have to take EVERYTHING literally?
Poor soul! You've lost it!

Revenge is sweet :)

LOL

(Disclaimer: The above statements were made with tongue planted firmly in
cheek. They are not intended to give offense.)
beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to test a URL request in a "while True" loop

2009-12-30 Thread samwyse
On Dec 30, 10:00 am, Brian D  wrote:

> What I don't understand is how to test for a valid URL request, and
> then jump out of the "while True" loop to proceed to another line of
> code below the loop. There's probably faulty logic in this approach. I
> imagine I should wrap the URL request in a function, and perhaps store
> the response as a global variable.
>
> This is really more of a basic Python logic question than it is a
> urllib2 question.

There, I've condensed your question to what you really meant to say.
You have several approaches.  First, let's define some useful objects:
>>> max_attempts = 5
>>> def do_something(i):
assert 2 < i < 5

Getting back to original question, if you want to limit the number of
attempts, don't use a while, use this:

>>> for count in xrange(max_attempts):
print 'attempt', count+1
do_something(count+1)

attempt 1
Traceback (most recent call last):
  File "", line 3, in 
do_something(count+1)
  File "", line 2, in do_something
assert 2 < i < 5
AssertionError

If you want to keep exceptions from ending the loop prematurely, you
add this:

>>> for count in xrange(max_attempts):
print 'attempt', count+1
try:
do_something(count+1)
except StandardError:
pass

Note that bare except clauses are *evil* and should be avoided.  Most
exceptions derive from StandardError, so trap that if you want to
catch errors.  Finally, to stop iterating when the errors cease, do
this:

>>> try:
for count in xrange(max_attempts):
print 'attempt', count+1
try:
do_something(count+1)
raise StopIteration
except StandardError:
pass
except StopIteration:
pass

attempt 1
attempt 2
attempt 3


Note that StopIteration doesn't derive from StandardError, because
it's not an error, it's a notification.  So, throw it if and when you
want to stop iterating.

BTW, note that you don't have to wrap your code in a function.
do_something could be replaced with it's body and everything would
still work.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Which version of MSVC?90.DLL's to distribute with Python 2.6 based Py2exe executables?

2009-12-30 Thread kakarukeys
I tried on a fresh XP on VM. I moved all dlls in C:\WINDOWS\WinSxS
which are in the file handles shown by Process Explorer including the
3 CRT dlls to the my dist folder and the two subfolders suggested by
http://wiki.wxpython.org/py2exe. It didn't work out. My app couldn't
start. Windows XP gave a cryptic error asking me to reinstall the app.

After installing vcredist_x86.exe, my app starts fine. There isn't a
choice here. You HAVE TO bundle vcredist_x86.exe with your installer
and convince your customers that it is necessary to increase the file
size by 2MB.

If anyone figure out how to do as http://wiki.wxpython.org/py2exe, or
on a Python compiled with a free GNU compiler, avoiding all these BS.
I will pay him/her $10.
-- 
http://mail.python.org/mailman/listinfo/python-list


Solved: TypeError: startView() takes exactly 1 argument (3 given)

2009-12-30 Thread Ron Croonenberg


ok, problem solved.

In the directory the plugin lives I have(had) a directory called 
'backup' to save things just in case I mess up.


Guess what, RB apparently looks into that directory too and uses the 
class, py file, it finds there instead of the one I am making changes to.


Dave Angel wrote:

Ron Croonenberg wrote:

Hello,

I am trying to write a plugin for Rhythmbox in python and run into a 
'strange' problem. For a method (an action for clicking a button) I 
started a method and however many arguments I use, it keeps giving me 
the same error:


'TypeError: startView() takes exactly 1 argument (3 given)'

does someone have any pointers or tips?, thanks;

Ron

here is the code I have the problem with:

import rb
import pygtk
import gtk, gobject


pygtk.require('2.0')



class tb_button (rb.Plugin):

#
# the init thing
#
   def __init__(self):
  rb.Plugin.__init__(self)

#
# the activate thing
#
   def activate(self, shell):
  self.shell = shell

  view_button = """
  

  


  

  
  """

  # create a new action
  action = gtk.Action('viewAction',
_(' _View'),
_('Browse Track '), "")

  # connect it
  action.connect('activate', self.startView, shell)
  action_group = gtk.ActionGroup('NewActionGroup')
  action_group.add_action(action)
  shell.get_ui_manager().insert_action_group(action_group)

  # add it to the toolbar
  ui_manager = shell.get_ui_manager()
  ui_manager.add_ui_from_string(view_button)



#
# Start the  View
#
   def startView(self, widget, shell, se):
# nothing yet
  return


Please give the complete error traceback, and make sure it matches the 
code you post.  I'm guessing that the subset of the error message you're 
quoting occurs when you define startView() as taking only self as a 
parameter.


A quick caveat.  I'm not familiar with GTK in particular, but I 
recognize the paradigm.  You're defining an event handler (startView).  
And you define a certain set of parameters (not arguments), presently 
called self, widge, shell, and se.


But you're not calling it, you're connecting it to an action.  So when 
that action triggers (or event happens), the GUI system will call your 
event handler.  You don't control the arguments it passes, and 
apparently it passes 3.  So you need to change the formal parameters in 
your def to match.


More specifically what are those parameters ?  I don't know, but you 
should be able to tell from sample pyGTK sources, or somebody else can 
chime in.  And maybe I'm totally nuts here.


DaveA



--
==
main(p){printf(p,34,p="main(p){printf(p,34,p=%c%s%c,34); }",34); }
==
Ron Croonenberg   |
  | Phone: 1 765 658 4761
Lab Instructor &  | Fax:   1 765 658 4732
Technology Coordinator|
  |
Department of Computer Science| e-mail: r...@depauw.edu
DePauw University |
275 Julian Science & Math Center  |
602 South College Ave.|
Greencastle, IN  46135|
==

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


Re: Cookies

2009-12-30 Thread Victor Subervi
On Wed, Dec 30, 2009 at 12:43 PM, Carsten Haese wrote:

> Anyway, the likely answer is that you guessed incorrectly. As I said
> before, you need to make sure that the cookie is printed as part of the
> page headers. I'll give you one last hint: The page header is where
> you're printing the "Content-type" line.
>

Ok. Thank you.

  print 'Content-Type: text/html'
  print cookie
  print
  print '''

'''

That worked. Threw a new error LOL.
Thanks,
beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Cookies

2009-12-30 Thread Carsten Haese
Victor Subervi wrote:
> Comments from a left-brain thinker without any concept of how difficult
> it is for a right-brain thinker to think like you. Care to compare
> poetry? I'd bury you.

That may be so, but the difference is that Steve is not trying to earn a
living writing poetry as far as I know, whereas you appear to be trying
to earn a living writing programs. If you can't learn to think like a
programmer, sooner or later you'll have to face the grim reality that
you'll never earn a living as a programmer. Maybe you should try to earn
a living as a poet instead.

--
Carsten Haese
http://informixdb.sourceforge.net

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


Re: call to pypcap in separate thread blocks other threads

2009-12-30 Thread Dmitry Teslenko
On Wed, Dec 30, 2009 at 18:25, aspineux  wrote:
> On Dec 30, 3:07 pm, Dmitry Teslenko  wrote:
>> On Wed, Dec 30, 2009 at 16:18, aspineux  wrote:
>> > On Dec 30, 1:34 pm, Dmitry Teslenko  wrote:
>> >> Hello!
>> >> I'm making gui gtk application. I'm using pypcap
>> >> (http://code.google.com/p/pypcap/) to sniff some network packets.
>> >> To avoid gui freezing I put pcap call to another thread.
>> >> Pypcap call looks like:
>>
>> >> pc = pcap.pcap()
>> >> pc.setfilter('tcp')
>> >> for ts, pkt in pc:
>> >>         spkt = str(pkt)
>> >>         ...
>>
>> >> Sadly, but this call in another thread blocks gtk gui thread anyway.
>> >> If I substitute pcap call with something else separate thread don't block
>> >> gui thread.
>>
>> >> Using another process instead of thead isn't appropriate.
>>
>> >> Thread initialization looks like and takes place before gtk.main():
>>
>> >> self.__pcap_thread = threading.Thread(target = self.get_city_from_pcap)
>> >> self.__pcap_thread.start()
>>
>> > Did you try using build-in gtk thread ?
>>
>> > Regards
>>
>> > Alain Spineux                         |  aspineux gmail com
>> > Your email 100% available             |  http://www.emailgency.com
>> > NTBackup frontend sending mail report |  http://www.magikmon.com/mkbackup
>>
>> >> --
>> >> A: Because it messes up the order in which people normally read text.
>> >> Q: Why is top-posting such a bad thing?
>> >> A: Top-posting.
>> >> Q: What is the most annoying thing in e-mail?
>> > --
>> >http://mail.python.org/mailman/listinfo/python-list
>>
>> No. What makes it different?
>
> It allow you to access to you GTK widgets from your threads (you have
> rules to follow to do that).
>
> What are you doing from inside your "pcap" thread ?
>
>
>
>>
>> --
>> A: Because it messes up the order in which people normally read text.
>> Q: Why is top-posting such a bad thing?
>> A: Top-posting.
>> Q: What is the most annoying thing in e-mail?
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>

I do this thing:

>> >> pc = pcap.pcap()
>> >> pc.setfilter('tcp')
>> >> for ts, pkt in pc:
>> >>         spkt = str(pkt)
>> >>         ...

pc.next() blocks other threads. I visit project page and ppl mention
similar issues. Now I think it's pypcap-related problem and project
page is right place to discuss this issue.
Thanks for support.

-- 
A: Because it messes up the order in which people normally read text.
Q: Why is top-posting such a bad thing?
A: Top-posting.
Q: What is the most annoying thing in e-mail?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: call to pypcap in separate thread blocks other threads

2009-12-30 Thread Grant Edwards
On 2009-12-30, Dmitry Teslenko  wrote:

> I'm making gui gtk application. I'm using pypcap
> (http://code.google.com/p/pypcap/) to sniff some network packets.
> To avoid gui freezing I put pcap call to another thread.
> Pypcap call looks like:
>
> pc = pcap.pcap()
> pc.setfilter('tcp')
> for ts, pkt in pc:
>   spkt = str(pkt)
>   ...
>
> Sadly, but this call in another thread blocks gtk gui thread anyway.
> If I substitute pcap call with something else separate thread don't block
> gui thread.

It sounds like the pcap wrapper code doesn't release the GIL
before making a blocking system call.  If that's the case,
you'll have to do some hacking on the C-language extension
module code.

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


Re: Cookies

2009-12-30 Thread Carsten Haese
Victor Subervi wrote:
> I've revised the code thus:
> 
>   cookie = os.environ.has_key('HTTP_COOKIE')
>   if not cookie:
> cookie = Cookie.SimpleCookie()
> cExpires, cPath, cComment, cDomain, cMaxAge, cVersion = myCookie()
> cookie['lastvisit'] = str(time.time())
> cookie['lastvisit']['expires'] = cExpires
> cookie['lastvisit']['path'] = cPath
> cookie['lastvisit']['comment'] = cComment
> cookie['lastvisit']['domain'] = cDomain
> cookie['lastvisit']['max-age'] = cMaxAge
> cookie['lastvisit']['version'] = cVersion
> print cookie
> cookieFlag = 'new'
>  
> Unfortunately, this still prints "new" for the cookieFlag no matter how
> many times I refresh. Please advise.

That tells me nothing, because once again you're not posting your
complete code.

Anyway, the likely answer is that you guessed incorrectly. As I said
before, you need to make sure that the cookie is printed as part of the
page headers. I'll give you one last hint: The page header is where
you're printing the "Content-type" line.

--
Carsten Haese
http://informixdb.sourceforge.net

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


Re: regex object limitations/behavior for large regexes?

2009-12-30 Thread Aaron Watters
Sorry, I should have looked harder.

I found this:
   http://bugs.python.org/issue1160

It looks exactly like my use case.  drat.

   -- Aaron Watters http://whiffdoc.appspot.com

===
less is more.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Bare Excepts

2009-12-30 Thread Victor Subervi
On Wed, Dec 30, 2009 at 12:23 PM, Steve Holden  wrote:

> Victor Subervi wrote:
> > On Wed, Dec 30, 2009 at 9:23 AM, Jean-Michel Pichavant
> [...]
> > In your example you must lookt at your sql module documentation to
> > know which kind of exception it can throw.
> >
> >
> > Or just throw the exception once and grab it. Okay, thanks ;)
> > beno
> >
> Now *that* is using your brain. Good thinking!
>

Bless you Steve. I use it all the time. It's just more difficult for me to
process left-brain stuff ;)
beno

The Logos has come to bear
http://logos.13gems.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Any way to use cProfile in a multi-threaded program?

2009-12-30 Thread Jonathan Hartley
On Dec 30, 3:00 pm, mk  wrote:
> I'm stumped; I read somewhere that one would have to modify Thread.run()
>   method but I have never modified Python methods nor would I really
> want to do it.
>
> Is there any way to start cProfile on each thread and then combine the
> stats?
>
> Regards,
> mk


Well, you can start cProfile from any arbitrary point within your
program, using the code:

  import cProfile
  import .mymodule
  command = 'mymodule.myfunction()'
  cProfile.runctx(command, globals(), locals(),
filename='profile.out')

Conventionally this is run at the start of your program (and myfunction
() is something that you call to startup the remainder of your
program), but one solution for you might be to run this after the
threads have been created. You'll have to run this in each thread, and
myfunction() will be the function required for the thread to do its
work. Maybe each thread should output to a different filename, using
something like filename='profile%s' % (threading.current_thread
().ident,)

As for combining the outputs from each thread, I don't know what the
cProfile output format is, so I can't help you there.

There might be better ways, but I don't know them.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Cookies

2009-12-30 Thread Victor Subervi
On Wed, Dec 30, 2009 at 12:19 PM, Steve Holden  wrote:

> Carsten Haese wrote:
> I will point out again, without the least expectation that it will do
> any good, that the reason this problem has occurred is that Victor
> simply refuses to take the time to absorb the principles of what he is
> attempting before attempting it.
>
> This is what I call "programming with a trowel" - take a chunk of code
> from here and a chunk from there, splash a little bit of cement logic
> around to glue everything together, and hope it works. The advanced part
> of the strategy here is to then throw the resulting mess at an
> accommodating newsgroup in the hope that the readers will turn it into
> working code.
>
> It's as though he had taken the front half of a motor cycle and the back
> half of a saloon car, welded them together without bothering to make any
> electrical or fuel line connections, and then complaining that "the
> vehicle doesn't work". Of course it doesn't, because there is no
> underlying understanding of the principles involved.
>
> The interesting thing is that the web site is apparently being put
> together to sell something. I have no idea what that something might be,
> but I am as sure as I can be that I don't want to buy it, just from the
> insight I have gained into the vendor's thought processes from the
> various threads I have recently been involved in.
>

Comments from a left-brain thinker without any concept of how difficult it
is for a right-brain thinker to think like you. Care to compare poetry? I'd
bury you.

>
> regards
>

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


Re: Bare Excepts

2009-12-30 Thread Steve Holden
Victor Subervi wrote:
> On Wed, Dec 30, 2009 at 9:23 AM, Jean-Michel Pichavant
[...]
> In your example you must lookt at your sql module documentation to
> know which kind of exception it can throw.
> 
> 
> Or just throw the exception once and grab it. Okay, thanks ;)
> beno
> 
Now *that* is using your brain. Good thinking!

regards
 Steve
-- 
Steve Holden   +1 571 484 6266   +1 800 494 3119
PyCon is coming! Atlanta, Feb 2010  http://us.pycon.org/
Holden Web LLC http://www.holdenweb.com/
UPCOMING EVENTS:http://holdenweb.eventbrite.com/

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


regex object limitations/behavior for large regexes?

2009-12-30 Thread Aaron Watters
I'm thinking of a design which automatically generates
regex objects which are essentially disjunctions of simple
pattern alternatives.  The number of alternatives might
conceivably run into the thousands or more.

This raises the question: do regex objects behave nicely
when the regex gets very large?  Do they remain as fast?
Do they display reasonable (linear or n log n) memory
growth?  Do they just stop working at some point?

Please reply if you have any experience with very
large regexes or other insights.

Thanks in advance.  -- Aaron Watters

===
less is more
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Cookies

2009-12-30 Thread Victor Subervi
On Wed, Dec 30, 2009 at 11:54 AM, Carsten Haese wrote:

> Victor Subervi wrote:
> > Here again is my code:
> >
> > #! /usr/bin/python
> >
> > import string
> > import cgitb; cgitb.enable()
> > import MySQLdb
> > import cgi
> > import sys,os
> > sys.path.append(os.getcwd())
> > from login import login
> > import datetime, Cookie, random
> > from particulars import title
> > from templateFrame import top, bottom
> > from particulars import myCookie
> > import time
> > import fpformat
> > from sets import Set
> > from particulars import ourOptions
> >
> > def cart():
> >   print '''Content-Type: text/html\r\n
> > 
> > 
> > '''
> >   cookie = os.environ.has_key('HTTP_COOKIE')
> >   if not cookie:
> > cookie = Cookie.SimpleCookie()
> > cExpires, cPath, cComment, cDomain, cMaxAge, cVersion = myCookie()
> > cookie['lastvisit'] = str(time.time())
> > cookie['lastvisit']['expires'] = cExpires
> > cookie['lastvisit']['path'] = cPath
> > cookie['lastvisit']['comment'] = cComment
> > cookie['lastvisit']['domain'] = cDomain
> > cookie['lastvisit']['max-age'] = cMaxAge
> > cookie['lastvisit']['version'] = cVersion
> > cookie['mycookie'] = 'mycookie'
> > cookieFlag = 'new'
> >   else:
> > cookie = Cookie.SimpleCookie(cookie)
> > cookieFlag = 'old'
> > #  Don't know what to do with this. It's for when client won't accept
> > cookies
> > #  sessionDir = os.environ['DOCUMENT_ROOT'] + '/tmp/.session'
> > #  session = shelve.open(sessionDir + '/sess_' + sid, writeback=True)
> > #  session['lastvisit'] = repr(time.time())
> > #  session.close()
> >   print cookieFlag
> >   cookie.load(cookie)
> >   print cookie
> >  ...
> >
> > Please advise.
>
> Pardon me for not being able to read your mind. The code you're now
> posting is significantly more code than your first post included. The
> line that I had determined to be missing is in fact not missing, you
> just didn't bother to post your actual code.
>

As my British father would have said, you're a gentleman and a scholar...


>
> Now that you've posted your actual code, I can see that the actual
> problem is that the line is in the wrong place.
>
> The line in question is <>, and it's responsible for
> printing a "Set-Cookie" *HEADER*, which is a fact that at least one of
> the tutorials you pointed out has mentioned. You're printing it where it
> doesn't belong, in the middle of your HTML output. You need to
> reorganize your print statements such that the Set-Cookie header is
> printed in the header of your script's output.
>

I've revised the code thus:

  cookie = os.environ.has_key('HTTP_COOKIE')
  if not cookie:
cookie = Cookie.SimpleCookie()
cExpires, cPath, cComment, cDomain, cMaxAge, cVersion = myCookie()
cookie['lastvisit'] = str(time.time())
cookie['lastvisit']['expires'] = cExpires
cookie['lastvisit']['path'] = cPath
cookie['lastvisit']['comment'] = cComment
cookie['lastvisit']['domain'] = cDomain
cookie['lastvisit']['max-age'] = cMaxAge
cookie['lastvisit']['version'] = cVersion
print cookie
cookieFlag = 'new'

Unfortunately, this still prints "new" for the cookieFlag no matter how many
times I refresh. Please advise.
TIA,
beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Cookies

2009-12-30 Thread Steve Holden
Carsten Haese wrote:
> Victor Subervi wrote:
[...]
> Pardon me for not being able to read your mind. The code you're now
> posting is significantly more code than your first post included. The
> line that I had determined to be missing is in fact not missing, you
> just didn't bother to post your actual code.
> 
> Now that you've posted your actual code, I can see that the actual
> problem is that the line is in the wrong place.
> 
> The line in question is <>, and it's responsible for
> printing a "Set-Cookie" *HEADER*, which is a fact that at least one of
> the tutorials you pointed out has mentioned. You're printing it where it
> doesn't belong, in the middle of your HTML output. You need to
> reorganize your print statements such that the Set-Cookie header is
> printed in the header of your script's output.
> 
I will point out again, without the least expectation that it will do
any good, that the reason this problem has occurred is that Victor
simply refuses to take the time to absorb the principles of what he is
attempting before attempting it.

This is what I call "programming with a trowel" - take a chunk of code
from here and a chunk from there, splash a little bit of cement logic
around to glue everything together, and hope it works. The advanced part
of the strategy here is to then throw the resulting mess at an
accommodating newsgroup in the hope that the readers will turn it into
working code.

It's as though he had taken the front half of a motor cycle and the back
half of a saloon car, welded them together without bothering to make any
electrical or fuel line connections, and then complaining that "the
vehicle doesn't work". Of course it doesn't, because there is no
underlying understanding of the principles involved.

The interesting thing is that the web site is apparently being put
together to sell something. I have no idea what that something might be,
but I am as sure as I can be that I don't want to buy it, just from the
insight I have gained into the vendor's thought processes from the
various threads I have recently been involved in.

regards
 Steve
-- 
Steve Holden   +1 571 484 6266   +1 800 494 3119
PyCon is coming! Atlanta, Feb 2010  http://us.pycon.org/
Holden Web LLC http://www.holdenweb.com/
UPCOMING EVENTS:http://holdenweb.eventbrite.com/

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


How to test a URL request in a "while True" loop

2009-12-30 Thread Brian D
I'm actually using mechanize, but that's too complicated for testing
purposes. Instead, I've simulated in a urllib2 sample below an attempt
to test for a valid URL request.

I'm attempting to craft a loop that will trap failed attempts to
request a URL (in cases where the connection intermittently fails),
and repeat the URL request a few times, stopping after the Nth attempt
is tried.

Specifically, in the example below, a bad URL is requested for the
first and second iterations. On the third iteration, a valid URL will
be requested. The valid URL will be requested until the 5th iteration,
when a break statement is reached to stop the loop. The 5th iteration
also restores the values to their original state for ease of repeat
execution.

What I don't understand is how to test for a valid URL request, and
then jump out of the "while True" loop to proceed to another line of
code below the loop. There's probably faulty logic in this approach. I
imagine I should wrap the URL request in a function, and perhaps store
the response as a global variable.

This is really more of a basic Python logic question than it is a
urllib2 question.

Any suggestions?

Thanks,
Brian


import urllib2
user_agent = 'Windows; U; Windows NT 5.1; en-US; rv:1.9.0.10) Gecko/
2009042316 Firefox/3.0.10'
user_agent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:
1.9.0.16) ' \
 'Gecko/2009120208 Firefox/3.0.16 (.NET CLR 3.5.30729)'
headers={'User-Agent':user_agent,}
url = 'http://this is a bad url'
count = 0
while True:
count += 1
try:
print 'attempt ' + str(count)
request = urllib2.Request(url, None, headers)
response = urllib2.urlopen(request)
if response:
print 'True response.'
if count == 5:
count = 0
url = 'http://this is a bad url'
print 'How do I get out of this thing?'
break
except:
print 'fail ' + str(count)
if count == 3:
url = 'http://www.google.com'
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Cookies

2009-12-30 Thread Carsten Haese
Victor Subervi wrote:
> Here again is my code:
> 
> #! /usr/bin/python
> 
> import string
> import cgitb; cgitb.enable()
> import MySQLdb
> import cgi
> import sys,os
> sys.path.append(os.getcwd())
> from login import login
> import datetime, Cookie, random
> from particulars import title
> from templateFrame import top, bottom
> from particulars import myCookie
> import time
> import fpformat
> from sets import Set
> from particulars import ourOptions
> 
> def cart():
>   print '''Content-Type: text/html\r\n
> 
> 
> '''
>   cookie = os.environ.has_key('HTTP_COOKIE')
>   if not cookie:
> cookie = Cookie.SimpleCookie()
> cExpires, cPath, cComment, cDomain, cMaxAge, cVersion = myCookie()
> cookie['lastvisit'] = str(time.time())
> cookie['lastvisit']['expires'] = cExpires
> cookie['lastvisit']['path'] = cPath
> cookie['lastvisit']['comment'] = cComment
> cookie['lastvisit']['domain'] = cDomain
> cookie['lastvisit']['max-age'] = cMaxAge
> cookie['lastvisit']['version'] = cVersion
> cookie['mycookie'] = 'mycookie'
> cookieFlag = 'new'
>   else:
> cookie = Cookie.SimpleCookie(cookie)
> cookieFlag = 'old'
> #  Don't know what to do with this. It's for when client won't accept
> cookies
> #  sessionDir = os.environ['DOCUMENT_ROOT'] + '/tmp/.session'
> #  session = shelve.open(sessionDir + '/sess_' + sid, writeback=True)
> #  session['lastvisit'] = repr(time.time())
> #  session.close()
>   print cookieFlag
>   cookie.load(cookie)
>   print cookie
>  ...
> 
> Please advise.

Pardon me for not being able to read your mind. The code you're now
posting is significantly more code than your first post included. The
line that I had determined to be missing is in fact not missing, you
just didn't bother to post your actual code.

Now that you've posted your actual code, I can see that the actual
problem is that the line is in the wrong place.

The line in question is <>, and it's responsible for
printing a "Set-Cookie" *HEADER*, which is a fact that at least one of
the tutorials you pointed out has mentioned. You're printing it where it
doesn't belong, in the middle of your HTML output. You need to
reorganize your print statements such that the Set-Cookie header is
printed in the header of your script's output.

--
Carsten Haese
http://informixdb.sourceforge.net

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


multithreading, performance, again...

2009-12-30 Thread mk

Hello everyone,

I have figured out (sort of) how to do profiling of multithreaded 
programs with cProfile, it goes something like this:


#!/usr/local/bin/python

import cProfile
import threading

class TestProf(threading.Thread):
def __init__(self, ip):

threading.Thread.__init__(self)
self.ip = ip


def run(self):
prof = cProfile.Profile()
retval = prof.runcall(self.runmethod)
prof.dump_stats('tprof' + self.ip)

def runmethod(self):
pass


tp = TestProf('10.0.10.10')

tp.start()
tp.join()


The problem is, now that I've done profiling in the actual program 
(profiled version here: http://python.domeny.com/cssh_profiled.py) with 
9 threads and added up stats (using pstats.Stats.add()), the times I get 
are trivial:


>>> p.strip_dirs().sort_stats('cumulative').print_stats(10)
Wed Dec 30 16:23:59 2009csshprof9.156.44.113
Wed Dec 30 16:23:59 2009csshprof9.156.46.243
Wed Dec 30 16:23:59 2009csshprof9.156.46.89
Wed Dec 30 16:24:00 2009csshprof9.156.47.125
Wed Dec 30 16:24:00 2009csshprof9.156.47.17
Wed Dec 30 16:24:00 2009csshprof9.156.47.29
Wed Dec 30 16:24:01 2009csshprof9.167.41.241
Wed Dec 30 16:24:02 2009csshprof9.168.119.15
Wed Dec 30 16:24:02 2009csshprof9.168.119.218

 39123 function calls (38988 primitive calls) in 6.004 CPU seconds

   Ordered by: cumulative time
   List reduced from 224 to 10 due to restriction <10>

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
90.0000.0006.0040.667 cssh.py:696(runmethod)
  1000.0040.0005.4670.055 threading.py:389(wait)
   820.0250.0005.4600.067 threading.py:228(wait)
  4005.4000.0135.4000.013 {time.sleep}
90.0000.0005.2630.585 cssh.py:452(ssh_connect)
90.0030.0005.2620.585 client.py:226(connect)
90.0010.0002.8040.312 
transport.py:394(start_client)

90.0050.0012.2540.250 client.py:391(_auth)
   180.0010.0002.1150.117 
transport.py:1169(auth_publickey)
   180.0010.0002.0300.113 
auth_handler.py:156(wait_for_response)





It's not burning CPU time in the main thread (profiling with cProfile 
indicated smth similar to the above), it's not burning it in the 
individual worker threads - so where the heck it is burning this CPU 
time? bc 'top' shows heavy CPU load during most of the time of the 
program run.


help...

regards,
mk

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


Re: TypeError: startView() takes exactly 1 argument (3 given)

2009-12-30 Thread Ron Croonenberg



Dave Angel wrote:

Ron Croonenberg wrote:

Hello,

I am trying to write a plugin for Rhythmbox in python and run into a 
'strange' problem. For a method (an action for clicking a button) I 
started a method and however many arguments I use, it keeps giving me 
the same error:


'TypeError: startView() takes exactly 1 argument (3 given)'

does someone have any pointers or tips?, thanks;

Ron

here is the code I have the problem with:

import rb
import pygtk
import gtk, gobject


pygtk.require('2.0')



class tb_button (rb.Plugin):

#
# the init thing
#
   def __init__(self):
  rb.Plugin.__init__(self)

#
# the activate thing
#
   def activate(self, shell):
  self.shell = shell

  view_button = """
  

  


  

  
  """

  # create a new action
  action = gtk.Action('viewAction',
_(' _View'),
_('Browse Track '), "")

  # connect it
  action.connect('activate', self.startView, shell)
  action_group = gtk.ActionGroup('NewActionGroup')
  action_group.add_action(action)
  shell.get_ui_manager().insert_action_group(action_group)

  # add it to the toolbar
  ui_manager = shell.get_ui_manager()
  ui_manager.add_ui_from_string(view_button)



#
# Start the  View
#
   def startView(self, widget, shell, se):
# nothing yet
  return


Please give the complete error traceback, and make sure it matches the 
code you post.  I'm guessing that the subset of the error message you're 
quoting occurs when you define startView() as taking only self as a 
parameter.


A quick caveat.  I'm not familiar with GTK in particular, but I 
recognize the paradigm.  You're defining an event handler (startView).  
And you define a certain set of parameters (not arguments), presently 
called self, widge, shell, and se.


But you're not calling it, you're connecting it to an action.  So when 
that action triggers (or event happens), the GUI system will call your 
event handler.  You don't control the arguments it passes, and 
apparently it passes 3.  So you need to change the formal parameters in 
your def to match.


More specifically what are those parameters ?  I don't know, but you 
should be able to tell from sample pyGTK sources, or somebody else can 
chime in.  And maybe I'm totally nuts here.


DaveA




Hello Dave,

I don't think you're nuts *lol*.  Actually I have been thinking along a 
similar line. (although I am new to python and probably thinking along C 
lines too much)


I saw some postings/articles that I found with google mentioning a 
python bug with that behavior. (However I think that the chances of me 
running into a bug vs me making a mistake is probably 1:)


What I think is weird though is that it doesn't matter how many 
parameters I put there. The error msg is still the same. (it doesn't 
matter if I actually put 1, 2, 3, 4 or even 5 there.  the message is 
exactly the same.'expecting 1 given 3'


I changed the debug level to see if I could get more messages.
(It is a rhythmbox plugin,  for debugging I have to start is with 
something like 'GST_DEBUG=3 rhythmbox &>log-file')
If I change the debug level to 5 or so I still only get that one error 
msg and nothing else. (yes surprised me too)


Ron

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


Re: call to pypcap in separate thread blocks other threads

2009-12-30 Thread aspineux
On Dec 30, 3:07 pm, Dmitry Teslenko  wrote:
> On Wed, Dec 30, 2009 at 16:18, aspineux  wrote:
> > On Dec 30, 1:34 pm, Dmitry Teslenko  wrote:
> >> Hello!
> >> I'm making gui gtk application. I'm using pypcap
> >> (http://code.google.com/p/pypcap/) to sniff some network packets.
> >> To avoid gui freezing I put pcap call to another thread.
> >> Pypcap call looks like:
>
> >> pc = pcap.pcap()
> >> pc.setfilter('tcp')
> >> for ts, pkt in pc:
> >>         spkt = str(pkt)
> >>         ...
>
> >> Sadly, but this call in another thread blocks gtk gui thread anyway.
> >> If I substitute pcap call with something else separate thread don't block
> >> gui thread.
>
> >> Using another process instead of thead isn't appropriate.
>
> >> Thread initialization looks like and takes place before gtk.main():
>
> >> self.__pcap_thread = threading.Thread(target = self.get_city_from_pcap)
> >> self.__pcap_thread.start()
>
> > Did you try using build-in gtk thread ?
>
> > Regards
>
> > Alain Spineux                         |  aspineux gmail com
> > Your email 100% available             |  http://www.emailgency.com
> > NTBackup frontend sending mail report |  http://www.magikmon.com/mkbackup
>
> >> --
> >> A: Because it messes up the order in which people normally read text.
> >> Q: Why is top-posting such a bad thing?
> >> A: Top-posting.
> >> Q: What is the most annoying thing in e-mail?
> > --
> >http://mail.python.org/mailman/listinfo/python-list
>
> No. What makes it different?

It allow you to access to you GTK widgets from your threads (you have
rules to follow to do that).

What are you doing from inside your "pcap" thread ?



>
> --
> A: Because it messes up the order in which people normally read text.
> Q: Why is top-posting such a bad thing?
> A: Top-posting.
> Q: What is the most annoying thing in e-mail?

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


Re: Cookies

2009-12-30 Thread Victor Subervi
On Wed, Dec 30, 2009 at 9:56 AM, Carsten Haese wrote:

> So, guess again. The "trivial example" has three more lines of code. One
> of them is unlike any line you have in your code. That's the line
> responsible for producing the "Set-Cookie" header, and that's the line
> you're missing.
>

So you're suggesting I somehow execute this code:
python Cookie_setheaders.py
in my script? I presume I'd change "Cookie_setheaders.py" to my file name.
That doesn't make sense to me.

I'm sorry but I'm lost. The page on which you said had the missing line:
http://www.doughellmann.com/PyMOTW/Cookie/index.html
has the following code:

import Cookie
c = Cookie.SimpleCookie()
c['mycookie'] = 'cookie_value'
print c

All of which is in my code. The tutorial gave this printout:

$ python Cookie_setheaders.py
Set-Cookie: mycookie=cookie_value

It also has this code:

import Cookie
import datetime

def show_cookie(c):
print c
for key, morsel in c.iteritems():
print
print 'key =', morsel.key
print '  value =', morsel.value
print '  coded_value =', morsel.coded_value
for name in morsel.keys():
if morsel[name]:
print '  %s = %s' % (name, morsel[name])

which, when I tried it, printed nothing at all. Not a very good tutorial :(

This page
http://webpython.codepoint.net/cgi_set_the_cookie
has the following code:

#!/usr/bin/env python
import time
print 'Set-Cookie: lastvisit=' + str(time.time());
print 'Content-Type: text/html\n'
print ''
print 'Server time is', time.asctime(time.localtime())
print ''



#!/usr/bin/env python
import time, Cookie
cookie = Cookie.SimpleCookie()
cookie['lastvisit'] = str(time.time())
print cookie
print 'Content-Type: text/html\n'
print ''
print 'Server time is', time.asctime(time.localtime())
print ''

all of which is included in my code (except for extraneous print
statements). Here again is my code:

#! /usr/bin/python

import string
import cgitb; cgitb.enable()
import MySQLdb
import cgi
import sys,os
sys.path.append(os.getcwd())
from login import login
import datetime, Cookie, random
from particulars import title
from templateFrame import top, bottom
from particulars import myCookie
import time
import fpformat
from sets import Set
from particulars import ourOptions

def cart():
  print '''Content-Type: text/html\r\n


'''
  cookie = os.environ.has_key('HTTP_COOKIE')
  if not cookie:
cookie = Cookie.SimpleCookie()
cExpires, cPath, cComment, cDomain, cMaxAge, cVersion = myCookie()
cookie['lastvisit'] = str(time.time())
cookie['lastvisit']['expires'] = cExpires
cookie['lastvisit']['path'] = cPath
cookie['lastvisit']['comment'] = cComment
cookie['lastvisit']['domain'] = cDomain
cookie['lastvisit']['max-age'] = cMaxAge
cookie['lastvisit']['version'] = cVersion
cookie['mycookie'] = 'mycookie'
cookieFlag = 'new'
  else:
cookie = Cookie.SimpleCookie(cookie)
cookieFlag = 'old'
#  Don't know what to do with this. It's for when client won't accept
cookies
#  sessionDir = os.environ['DOCUMENT_ROOT'] + '/tmp/.session'
#  session = shelve.open(sessionDir + '/sess_' + sid, writeback=True)
#  session['lastvisit'] = repr(time.time())
#  session.close()
  print cookieFlag
  cookie.load(cookie)
  print cookie
 ...

Please advise.
TIA,
beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Any way to use cProfile in a multi-threaded program?

2009-12-30 Thread mk


I'm stumped; I read somewhere that one would have to modify Thread.run() 
 method but I have never modified Python methods nor would I really 
want to do it.


Is there any way to start cProfile on each thread and then combine the 
stats?


Regards,
mk

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


Re: How to write simple code to match strings?

2009-12-30 Thread Stefan Behnel

Steven D'Aprano, 30.12.2009 07:01:

def _re_match_items(s):
# Setup some regular expressions.
COMMON_RE = r'\$?([-+]?[0-9,]*\.?[0-9,]+)'
FLOAT_RE = COMMON_RE + '$'
BRACKETED_FLOAT_RE = r'\(' + COMMON_RE + r'\)$'
DATE_RE = r'\d{1,2}-\w+-\d{1,2}$'
mo = re.match(FLOAT_RE, s)  # "mo" short for "match object"
if mo:
return float(mo.group(1).replace(',', ''))
# Otherwise mo will be None and we go on to the next test.
mo = re.match(BRACKETED_FLOAT_RE, s)
if mo:
return -float(mo.group(1).replace(',', ''))
if re.match(DATE_RE, s):
return dateutil.parser.parse(s, dayfirst=True)
raise ValueError("bad string can't be matched")


Given that this is meant for converting single data items, which may happen 
quite frequently in a program (depending on the size of the input), you 
might want to use pre-compiled regexps here.


Also, you can convert the above into a single regexp with multiple 
alternative groups and then just run the matcher once, e.g. (untested):


COMMON_RE = r'\$?([-+]?[0-9,]*\.?[0-9,]+)'
FLOAT_RE = COMMON_RE + '$'
BRACKETED_FLOAT_RE = r'\(' + COMMON_RE + r'\)$'
DATE_RE = r'(\d{1,2}-\w+-\d{1,2})$'  # note the surrounding () I added

match_data_items = re.compile('|'.join(
[BRACKETED_FLOAT_RE, FLOAT_RE, DATE_RE])).match

def convert_data_item(s):
# ...
match = match_data_items(s)
if match:
bfloat_value, float_value, date_value = match.groups()
if bfloat_value:
return -float(bfloat_value.replace(',', ''))
if float_value:
return float(bfloat_value.replace(',', ''))
if date_value:
return dateutil.parser.parse(date_value, dayfirst=True)
raise ...

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


Re: Bare Excepts

2009-12-30 Thread samwyse
On Dec 30, 7:23 am, Jean-Michel Pichavant 
wrote:

> Rule N°2:
> dont use BARE EXCEPT, or you'll piss off MRAB for good :o). Beside from
> kidding, don't use bare except.

I inherited some code that used bare excepts *everywhere*.  There were
about 4K lines of code, IIRC, and I think that they were more except
clauses than elses.  Eventually, I used sed to add a print_exc() after
each one, just so I could figure out what the expected exceptions
were.  It was so bad that I seriously considered writing a program
just to parse all the tracebacks from my instrumented version and then
revise the source code for me, but I didn't want to accidentally miss
any "real" errors.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: call to pypcap in separate thread blocks other threads

2009-12-30 Thread Dmitry Teslenko
On Wed, Dec 30, 2009 at 16:18, aspineux  wrote:
> On Dec 30, 1:34 pm, Dmitry Teslenko  wrote:
>> Hello!
>> I'm making gui gtk application. I'm using pypcap
>> (http://code.google.com/p/pypcap/) to sniff some network packets.
>> To avoid gui freezing I put pcap call to another thread.
>> Pypcap call looks like:
>>
>> pc = pcap.pcap()
>> pc.setfilter('tcp')
>> for ts, pkt in pc:
>>         spkt = str(pkt)
>>         ...
>>
>> Sadly, but this call in another thread blocks gtk gui thread anyway.
>> If I substitute pcap call with something else separate thread don't block
>> gui thread.
>>
>> Using another process instead of thead isn't appropriate.
>>
>> Thread initialization looks like and takes place before gtk.main():
>>
>> self.__pcap_thread = threading.Thread(target = self.get_city_from_pcap)
>> self.__pcap_thread.start()
>
> Did you try using build-in gtk thread ?
>
> Regards
>
> Alain Spineux                         |  aspineux gmail com
> Your email 100% available             |  http://www.emailgency.com
> NTBackup frontend sending mail report |  http://www.magikmon.com/mkbackup
>
>>
>> --
>> A: Because it messes up the order in which people normally read text.
>> Q: Why is top-posting such a bad thing?
>> A: Top-posting.
>> Q: What is the most annoying thing in e-mail?
> --
> http://mail.python.org/mailman/listinfo/python-list
>

No. What makes it different?


-- 
A: Because it messes up the order in which people normally read text.
Q: Why is top-posting such a bad thing?
A: Top-posting.
Q: What is the most annoying thing in e-mail?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Cookies

2009-12-30 Thread Carsten Haese
Victor Subervi wrote:
> On Tue, Dec 29, 2009 at 3:43 PM, Carsten Haese  > wrote:
> You apparently haven't followed the tutorials carefully enough. You do
> know that a cookie is a piece of information that's stored in your
> browser, don't you? So tell me, which of the above lines of code do you
> suppose is responsible for informing your browser of the cookie's
> contents?
> 
> 
> This one:
> 
> cookie = SimpleCookie()
> 
> In the tutorial found here, for example:
> 
> http://www.doughellmann.com/PyMOTW/Cookie/index.html
> 
> I read the following:
> 
> 
> Cookies are used as state management, and as such as usually set by the
> server to be stored and returned by the client. The most trivial example
> of creating a cookie looks something like:
> 
> import Cookie
> 
> c = Cookie.SimpleCookie()
> c['mycookie'] = 'cookie_value'
> print c
> 
> The output is a valid Set-Cookie header ready to be passed to the client
> as part of the HTTP response:
> 
> $ python Cookie_setheaders.py
> Set-Cookie: mycookie=cookie_value
> 
> 
> Do not the printout words "Set-cookie" indicate the cookie has been set?

That's exactly what that printout indicates, and ONLY that printout
indicates that. Without that printout, no cookie will be set in the
browser, because that printout is what transports the contents of the
cookie to the browser. However, the line <>
is not responsible for producing that printout, which can be tested
easily in a Python command line:

py> import Cookie
py> c = Cookie.SimpleCookie()
py>

As you can see, no printout is generated.

By the way, expecting a line of code to produce content that is
established in lines of codes that follow it requires a mental execution
model of Python that involves magic, mind reading, or time travel, none
of which are features Python is known for.

So, guess again. The "trivial example" has three more lines of code. One
of them is unlike any line you have in your code. That's the line
responsible for producing the "Set-Cookie" header, and that's the line
you're missing.

--
Carsten Haese
http://informixdb.sourceforge.net

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


Re: Bare Excepts

2009-12-30 Thread Victor Subervi
On Wed, Dec 30, 2009 at 9:23 AM, Jean-Michel Pichavant <
jeanmic...@sequans.com> wrote:

> Victor Subervi wrote:
>
>  On Wed, Dec 30, 2009 at 9:09 AM, Victor Subervi 
> > victorsube...@gmail.com>> wrote:
>>
>>
>>Anyway, you should definitely use a coding rule checker, like
>>pylint or pyckeck. It would sometimes point you into the correct
>>direction. For instance, pylint will tell you that except: pass is
>>often (not always) a clue for bad design/pattern and issue
>>warnings for it.
>>
>> How about this:
>>
>>try:
>>  id = form.getfirst('id')
>>  sql = 'update %s set ProdID="%s" Quantity="%s" %s where ID="%s";' %
>> (tmpTable, prodid, quantity, sqlUpdateMiddle, id)
>>  cursor.execute(sql)
>>  db.commit()
>>except:
>>  raise
>>  How does one get around sql calls that fail?
>> beno
>>
>>  Rule N° 1:
> put the minimum code in try blocks
>
> Rule N°2:
> dont use BARE EXCEPT, or you'll piss off MRAB for good :o). Beside from
> kidding, don't use bare except.
>
>
>  id = form.getfirst('id')
>  sql = 'update %s set ProdID="%s" Quantity="%s" %s where ID="%s";' %
> (tmpTable, prodid, quantity, sqlUpdateMiddle, id)
>  try:
>
> cursor.execute(sql)
> db.commit()
>   except NAME_OF_THE_EXCEPTION :
> raise # reraising without doing anything else is meaninless, you could
> remove the try block
>
>
> In your example you must lookt at your sql module documentation to know
> which kind of exception it can throw.
>

Or just throw the exception once and grab it. Okay, thanks ;)
beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: detect interactivity

2009-12-30 Thread Vito 'ZeD' De Tullio
Steven D'Aprano wrote:


>> if I run 'python <<< "import sys; print(sys.ps1)"', I get an error.
> 
> Of course you do, because you're not running interactively

Excuse me, why do you say that?

-- 
By ZeD

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


Re: Bare Excepts

2009-12-30 Thread Jean-Michel Pichavant

Victor Subervi wrote:
On Wed, Dec 30, 2009 at 9:09 AM, Victor Subervi 
mailto:victorsube...@gmail.com>> wrote:



Anyway, you should definitely use a coding rule checker, like
pylint or pyckeck. It would sometimes point you into the correct
direction. For instance, pylint will tell you that except: pass is
often (not always) a clue for bad design/pattern and issue
warnings for it.

How about this:

try:
  id = form.getfirst('id')
  sql = 'update %s set ProdID="%s" Quantity="%s" %s where 
ID="%s";' % (tmpTable, prodid, quantity, sqlUpdateMiddle, id)

  cursor.execute(sql)
  db.commit()
except:
  raise
 
How does one get around sql calls that fail?

beno


Rule N° 1:
put the minimum code in try blocks

Rule N°2:
dont use BARE EXCEPT, or you'll piss off MRAB for good :o). Beside from 
kidding, don't use bare except.


  id = form.getfirst('id')
  sql = 'update %s set ProdID="%s" Quantity="%s" %s where ID="%s";' % 
(tmpTable, prodid, quantity, sqlUpdateMiddle, id)

  try:
 cursor.execute(sql)
 db.commit()
   except NAME_OF_THE_EXCEPTION :
 raise # reraising without doing anything else is meaninless, you 
could remove the try block



In your example you must lookt at your sql module documentation to know 
which kind of exception it can throw.


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


Re: call to pypcap in separate thread blocks other threads

2009-12-30 Thread aspineux
On Dec 30, 1:34 pm, Dmitry Teslenko  wrote:
> Hello!
> I'm making gui gtk application. I'm using pypcap
> (http://code.google.com/p/pypcap/) to sniff some network packets.
> To avoid gui freezing I put pcap call to another thread.
> Pypcap call looks like:
>
> pc = pcap.pcap()
> pc.setfilter('tcp')
> for ts, pkt in pc:
>         spkt = str(pkt)
>         ...
>
> Sadly, but this call in another thread blocks gtk gui thread anyway.
> If I substitute pcap call with something else separate thread don't block
> gui thread.
>
> Using another process instead of thead isn't appropriate.
>
> Thread initialization looks like and takes place before gtk.main():
>
> self.__pcap_thread = threading.Thread(target = self.get_city_from_pcap)
> self.__pcap_thread.start()

Did you try using build-in gtk thread ?

Regards

Alain Spineux |  aspineux gmail com
Your email 100% available |  http://www.emailgency.com
NTBackup frontend sending mail report |  http://www.magikmon.com/mkbackup

>
> --
> A: Because it messes up the order in which people normally read text.
> Q: Why is top-posting such a bad thing?
> A: Top-posting.
> Q: What is the most annoying thing in e-mail?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Bare Excepts

2009-12-30 Thread Victor Subervi
On Wed, Dec 30, 2009 at 9:09 AM, Victor Subervi wrote:

>
>> Anyway, you should definitely use a coding rule checker, like pylint or
> pyckeck. It would sometimes point you into the correct direction. For
> instance, pylint will tell you that except: pass is often (not always) a
> clue for bad design/pattern and issue warnings for it.
>
> How about this:

try:
  id = form.getfirst('id')
  sql = 'update %s set ProdID="%s" Quantity="%s" %s where ID="%s";' %
(tmpTable, prodid, quantity, sqlUpdateMiddle, id)
  cursor.execute(sql)
  db.commit()
except:
  raise

How does one get around sql calls that fail?
beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Bare Excepts

2009-12-30 Thread Victor Subervi
On Wed, Dec 30, 2009 at 9:04 AM, Jean-Michel Pichavant <
jeanmic...@sequans.com> wrote:

> Victor Subervi wrote:
>
>> Hi;
>> I'll trouble-shoot bare excepts as I work on new code. I'll trouble-shoot
>> the others that don't (seem to) cause problems later. Here's a new one:
>>
>>for optionsStore, storeOptions in ourOptions().iteritems():
>>  if store == optionsStore:
>>for option in storeOptions:
>>  try:
>>fromForm = form.getfirst(option)
>>try:
>>  fromForm, junk = string.split(fromForm, ':')
>>except:
>>  pass # This is only an expedient to split options that have a
>> colon in them, such as the colors
>>fromForm = string.replace(fromForm, '-', '')
>>sql = 'select "%s" from %s%s t join %s p where p.ID=t.ID;' %
>> (fromForm, store, (option[0].upper() + option[1:]), store)
>> #print sql
>>cursor.execute(sql)
>>try:
>>  optionsPrices += cursor.fetchone()[0]
>>except TypeError:
>>  pass # There is no options price for this.
>>  except:
>>raise
>>  If there are no values entered into table (in this case "productsSizes")
>> for the given product ID, then "optionsPrices" should not be added unto. Am
>> I doing this correctly? Or is there a better way than capturing ALL
>> TypeErrors?
>> TIA,
>> beno
>>
> Hello,
>
> Do not use the 'try except' clause when 'if then' can perfectly handle the
> case.
>
> i.e.
>
>   try:
> fromForm, junk = string.split(fromForm, ':')
>   except:
> pass # This is only an expedient to split options that have a
> colon in them, such as the colors
>
> would be better written
>
>
> # This is only an expedient to split options that have a colon in them,
> such as the colors
> if ':' in fromForm:
>   fromForm, junk = fromForm.split(':')
>
> or
>
> fromForm = fromForm.split(':')[0]
>
>
> Anyway, you should definitely use a coding rule checker, like pylint or
> pyckeck. It would sometimes point you into the correct direction. For
> instance, pylint will tell you that except: pass is often (not always) a
> clue for bad design/pattern and issue warnings for it.
>
> In a more general manner, use try blocks when the code can throw exceptions
> upon condition you do not control. When you know about the conditions, use
> the if statement.
>
> No:
>
> a = None
> try:
>   a.split()
> except AttributeError:
>   pass
>
>
> Yes:
>
> a = None
> if a:
>   a.split()
>
> Exception are required in the following example:
>
> try:
>   main()
> except KeyboardInterrupt:
>   print 'interrupted by user'
>
> Cheers,
>
> JM
>
> Thank you.
beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Bare Excepts

2009-12-30 Thread Jean-Michel Pichavant

Victor Subervi wrote:

Hi;
I'll trouble-shoot bare excepts as I work on new code. I'll 
trouble-shoot the others that don't (seem to) cause problems later. 
Here's a new one:


for optionsStore, storeOptions in ourOptions().iteritems():
  if store == optionsStore:
for option in storeOptions:
  try:
fromForm = form.getfirst(option)
try:
  fromForm, junk = string.split(fromForm, ':')
except:
  pass # This is only an expedient to split options that 
have a colon in them, such as the colors

fromForm = string.replace(fromForm, '-', '')
sql = 'select "%s" from %s%s t join %s p where p.ID=t.ID;' 
% (fromForm, store, (option[0].upper() + option[1:]), store)

#print sql
cursor.execute(sql)
try:
  optionsPrices += cursor.fetchone()[0]
except TypeError:
  pass # There is no options price for this.
  except:
raise
 
If there are no values entered into table (in this case 
"productsSizes") for the given product ID, then "optionsPrices" should 
not be added unto. Am I doing this correctly? Or is there a better way 
than capturing ALL TypeErrors?

TIA,
beno

Hello,

Do not use the 'try except' clause when 'if then' can perfectly handle 
the case.


i.e.
   try:
 fromForm, junk = string.split(fromForm, ':')
   except:
 pass # This is only an expedient to split options that 
have a colon in them, such as the colors


would be better written

# This is only an expedient to split options that have a colon in them, 
such as the colors

if ':' in fromForm:
   fromForm, junk = fromForm.split(':')

or

fromForm = fromForm.split(':')[0]


Anyway, you should definitely use a coding rule checker, like pylint or 
pyckeck. It would sometimes point you into the correct direction. For 
instance, pylint will tell you that except: pass is often (not always) a 
clue for bad design/pattern and issue warnings for it.


In a more general manner, use try blocks when the code can throw 
exceptions upon condition you do not control. When you know about the 
conditions, use the if statement.


No:

a = None
try:
   a.split()
except AttributeError:
   pass


Yes:

a = None
if a:
   a.split()

Exception are required in the following example:

try:
   main()
except KeyboardInterrupt:
   print 'interrupted by user'

Cheers,

JM

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


call to pypcap in separate thread blocks other threads

2009-12-30 Thread Dmitry Teslenko
Hello!
I'm making gui gtk application. I'm using pypcap
(http://code.google.com/p/pypcap/) to sniff some network packets.
To avoid gui freezing I put pcap call to another thread.
Pypcap call looks like:

pc = pcap.pcap()
pc.setfilter('tcp')
for ts, pkt in pc:
spkt = str(pkt)
...

Sadly, but this call in another thread blocks gtk gui thread anyway.
If I substitute pcap call with something else separate thread don't block
gui thread.

Using another process instead of thead isn't appropriate.

Thread initialization looks like and takes place before gtk.main():

self.__pcap_thread = threading.Thread(target = self.get_city_from_pcap)
self.__pcap_thread.start()

-- 
A: Because it messes up the order in which people normally read text.
Q: Why is top-posting such a bad thing?
A: Top-posting.
Q: What is the most annoying thing in e-mail?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: detect interactivity

2009-12-30 Thread Roald de Vries

On Dec 30, 2009, at 4:10 AM, Steve Holden wrote:

Roald de Vries wrote:


On Dec 30, 2009, at 2:28 AM, Dave Angel wrote:


Roald de Vries wrote:

On Dec 29, 2009, at 8:34 PM, Dave Angel wrote:

Antoine Pitrou wrote:

Le Tue, 29 Dec 2009 16:09:58 +0100, Roald de Vries a écrit :



Dear all,

Is it possible for a Python script to detect whether it is  
running
interactively? It can be useful for e.g. defining functions  
that are

only useful in interactive mode.



Try the isatty() method (*) on e.g. stdin:

$ python -c "import sys; print sys.stdin.isatty()"
True
$ echo "" | python -c "import sys; print sys.stdin.isatty()"
False


Your test determines whether input is redirected.  But I think the
OP was asking how to detect whether the script was being run  
from an

interpreter prompt.


That was my question indeed. Is it possible?



If I had had a good answer, I would have supplied it in my earlier
message.

The sneaky answer would be that a script cannot be used  
interactively,

as once you import it from the interpreter, it's a module, not a
script.  So you can detect that it's not a script, by examing  
__name__
in the usual way.  If it's a script, it'll have a value of  
"__main__".


But that won't tell you if you're running inside an IDE, or using  
the

-i switch on the Python command line, or probably a bunch of other
questions.  I don't know of any "correct" answer, and I'm not sure
what the real use case is for knowing.  Are you really going to
somehow define a different set of functions???


I'm using a database, and want to use python interactively to  
manipulate

it. On the other hand, I also want to be able to use it
non-interactively. In that case, it would be a waste of CPU to load  
the

function/class definitions meant for interactive use.


This is an extreme case of premature optimization. Write the code and
run it. Do you have any idea how much extra time and memory loading  
the
additional code will require? If not, it's a waste of your time to  
even

think about omitting the stuff required for interactive use.

Once you get a handle on the structures and functions required for
interactive vs. non-interactive use you can consider refactoring the
code so that the non-interactive programs don't need to import the  
stuff

that's exclusively for interactive use. But frankly I wouldn't waste
your time.


Actually, performance is not much if an issue for what I want to do;  
it's mainly interest in 'how should I do this in general'.  I'll just  
leave in all the code, and if it becomes a real issue, I'll separate  
the code over an interactive and a non-interactive script. Thanks for  
your inputs.


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


Re: Python 2.6 ftplib has timeout parameter, but how to detect a timeout

2009-12-30 Thread Giampaolo Rodola'
On 14 Dic, 20:08, Brendan  wrote:
> I was quite happy to see that ftplib in Python 2.6 now has a timeout
> parameter. With large file downloads my script would often hang,
> presumably from timing out. Now that there is a timeout parameter, how
> would I detect when a timeout occurs?

The socket object will raise a timeout exception during recv() or send
().


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


Re: How to write simple code to match strings?

2009-12-30 Thread Steven D'Aprano
On Tue, 29 Dec 2009 23:07:15 -0800, beginner wrote:

>> def convert_data_item(s):
>>     if s = '-':
[...]
> I don't know if it should be s=='-' or s='-'. I thought == means equal
> and = means assignment?

Er, you're absolutely right.

Sorry for that, that's an embarrassing brain-fart. I don't know what I 
was thinking.


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


Re: Absolute beginner

2009-12-30 Thread Luc
Also thanks Ben and Simon for your help !

On Dec 30, 1:07 pm, Luc  wrote:
> Thanks Krister !
> Should have read specific 3.1 documentation :-(  .
>
> Regards,  Luc
>
> On Dec 30, 12:56 pm, Krister Svanlund 
> wrote:
>
> > In Python 3 the syntax for print has changed to print() so just put
> > braces around the string and you'r good to go!
>
> > On Wed, Dec 30, 2009 at 12:48 PM,   wrote:
> > > Hi there,
> > > I installed python 3.1 on Windows Vista PC.
> > > Am an absolute beginner with Python.
> > > This is my problem :
>
> > > In Idle :
>
> > > Python 3.1.1 (r311:74483, Aug 17 2009, 17:02:12) [MSC v.1500 32 bit
> > > (Intel)] on win32
> > > Type "copyright", "credits" or "license()" for more information.
> >  print "Hello"
> > > SyntaxError: invalid syntax (, line 1)
>
> > > At a dos-prompt :
>
> > > Python 3.1.1 (r311:74483, Aug 17 2009, 17:02:12) [MSC v.1500 32 bit
> > > (Intel)] on
> > > win32
> > > Type "help", "copyright", "credits" or "license" for more information.
> >  print "Hello"
> > >  File "", line 1
> > >    print "Hello"
> > >                ^
> > > SyntaxError: invalid syntax
>
> > > Looks stupid, probably is, but I cannot figure it out.
>
> > > Thanks for any help !
>
> > > Lucky
>
> > > --
> > >http://mail.python.org/mailman/listinfo/python-list
>
>

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


Re: Absolute beginner

2009-12-30 Thread Luc

Thanks Krister !
Should have read specific 3.1 documentation :-(  .

Regards,  Luc

On Dec 30, 12:56 pm, Krister Svanlund 
wrote:
> In Python 3 the syntax for print has changed to print() so just put
> braces around the string and you'r good to go!
>
> On Wed, Dec 30, 2009 at 12:48 PM,   wrote:
> > Hi there,
> > I installed python 3.1 on Windows Vista PC.
> > Am an absolute beginner with Python.
> > This is my problem :
>
> > In Idle :
>
> > Python 3.1.1 (r311:74483, Aug 17 2009, 17:02:12) [MSC v.1500 32 bit
> > (Intel)] on win32
> > Type "copyright", "credits" or "license()" for more information.
>  print "Hello"
> > SyntaxError: invalid syntax (, line 1)
>
> > At a dos-prompt :
>
> > Python 3.1.1 (r311:74483, Aug 17 2009, 17:02:12) [MSC v.1500 32 bit
> > (Intel)] on
> > win32
> > Type "help", "copyright", "credits" or "license" for more information.
>  print "Hello"
> >  File "", line 1
> >    print "Hello"
> >                ^
> > SyntaxError: invalid syntax
>
> > Looks stupid, probably is, but I cannot figure it out.
>
> > Thanks for any help !
>
> > Lucky
>
> > --
> >http://mail.python.org/mailman/listinfo/python-list
>
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Absolute beginner

2009-12-30 Thread Ben Finney
lucbo...@hotmail.com writes:

> I installed python 3.1 on Windows Vista PC.

Thank you for this information, it's essential to solving the problem.

> Python 3.1.1 (r311:74483, Aug 17 2009, 17:02:12) [MSC v.1500 32 bit
> (Intel)] on win32
> Type "copyright", "credits" or "license()" for more information.
> >>> print "Hello"
> SyntaxError: invalid syntax (, line 1)

You need to follow the correct documentation for the version of Python
you're using. The above is invalid syntax — in Python 3. (It was valid,
in Python 2.)

Please work through the Python tutorial for the version of Python you're
using http://docs.python.org/3.1/tutorial/>, running each exercise
and experimenting until you understand it before going to the next.

Good hunting, and keep at it!

-- 
 \“If you go to a costume party at your boss's house, wouldn't |
  `\ you think a good costume would be to dress up like the boss's |
_o__)  wife? Trust me, it's not.” —Jack Handey |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Absolute beginner

2009-12-30 Thread Simon Brunning
2009/12/30  :

> At a dos-prompt :
>
> Python 3.1.1 (r311:74483, Aug 17 2009, 17:02:12) [MSC v.1500 32 bit
> (Intel)] on
> win32
> Type "help", "copyright", "credits" or "license" for more information.
 print "Hello"
>  File "", line 1
>    print "Hello"
>                ^
> SyntaxError: invalid syntax

You are using Python 2 syntax, but a Python 3 interpreter. So, either
download an earlier version of Python, or use a tutorial which covers
Python 3.

Rather unlucky timing, really - Python 3 is the first non-trivially
backward incompatible version for a very long time - at least a decade
and a half.

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


Re: Absolute beginner

2009-12-30 Thread Krister Svanlund
In Python 3 the syntax for print has changed to print() so just put
braces around the string and you'r good to go!

On Wed, Dec 30, 2009 at 12:48 PM,   wrote:
> Hi there,
> I installed python 3.1 on Windows Vista PC.
> Am an absolute beginner with Python.
> This is my problem :
>
> In Idle :
>
> Python 3.1.1 (r311:74483, Aug 17 2009, 17:02:12) [MSC v.1500 32 bit
> (Intel)] on win32
> Type "copyright", "credits" or "license()" for more information.
 print "Hello"
> SyntaxError: invalid syntax (, line 1)
>
> At a dos-prompt :
>
> Python 3.1.1 (r311:74483, Aug 17 2009, 17:02:12) [MSC v.1500 32 bit
> (Intel)] on
> win32
> Type "help", "copyright", "credits" or "license" for more information.
 print "Hello"
>  File "", line 1
>    print "Hello"
>                ^
> SyntaxError: invalid syntax

>
> Looks stupid, probably is, but I cannot figure it out.
>
> Thanks for any help !
>
> Lucky
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Absolute beginner

2009-12-30 Thread lucbonne
Hi there,
I installed python 3.1 on Windows Vista PC.
Am an absolute beginner with Python.
This is my problem :

In Idle :

Python 3.1.1 (r311:74483, Aug 17 2009, 17:02:12) [MSC v.1500 32 bit
(Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> print "Hello"
SyntaxError: invalid syntax (, line 1)

At a dos-prompt :

Python 3.1.1 (r311:74483, Aug 17 2009, 17:02:12) [MSC v.1500 32 bit
(Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> print "Hello"
  File "", line 1
print "Hello"
^
SyntaxError: invalid syntax
>>>

Looks stupid, probably is, but I cannot figure it out.

Thanks for any help !

Lucky

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


socket programming

2009-12-30 Thread Zubin Mithra
The code snippet i have pasted at,

http://paste.pocoo.org/show/160555/

produces a traceback which also has been pasted at the above link. The
snippet attempts at socket programming using OOPs concepts. Please help.

Thankx in advance
Zubin Mithra
-- 
http://mail.python.org/mailman/listinfo/python-list


Bare Excepts

2009-12-30 Thread Victor Subervi
Hi;
I'll trouble-shoot bare excepts as I work on new code. I'll trouble-shoot
the others that don't (seem to) cause problems later. Here's a new one:

for optionsStore, storeOptions in ourOptions().iteritems():
  if store == optionsStore:
for option in storeOptions:
  try:
fromForm = form.getfirst(option)
try:
  fromForm, junk = string.split(fromForm, ':')
except:
  pass # This is only an expedient to split options that have a
colon in them, such as the colors
fromForm = string.replace(fromForm, '-', '')
sql = 'select "%s" from %s%s t join %s p where p.ID=t.ID;' %
(fromForm, store, (option[0].upper() + option[1:]), store)
#print sql
cursor.execute(sql)
try:
  optionsPrices += cursor.fetchone()[0]
except TypeError:
  pass # There is no options price for this.
  except:
raise

If there are no values entered into table (in this case "productsSizes") for
the given product ID, then "optionsPrices" should not be added unto. Am I
doing this correctly? Or is there a better way than capturing ALL
TypeErrors?
TIA,
beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Cookies

2009-12-30 Thread Victor Subervi
On Tue, Dec 29, 2009 at 3:43 PM, Carsten Haese wrote:

> Victor Subervi wrote:
> > Hi;
> > I have these lines:
> >
> >   cookie = os.environ.get('HTTP_COOKIE')
> >   if not cookie:
> > cookie = Cookie.SimpleCookie()
> > cExpires, cPath, cComment, cDomain, cMaxAge, cVersion = myCookie()
> > cookie['lastvisit'] = str(time.time())
> > cookie['lastvisit']['expires'] = cExpires
> > cookie['lastvisit']['path'] = cPath
> > cookie['lastvisit']['comment'] = cComment
> > cookie['lastvisit']['domain'] = cDomain
> > cookie['lastvisit']['max-age'] = cMaxAge
> > cookie['lastvisit']['version'] = cVersion
> > cookieFlag = 'new'
> >   else:
> > cookie = Cookie.SimpleCookie(cookie)
> > cookieFlag = 'old'
> >   print '''Content-Type: text/html\r\n
> > 
> > 
> > '''
> >   print cookieFlag
> >
> > cookieFlag prints 'new'. Every time. Even when I refresh. I've imported
> > Cookie. I've followed the tutorials :-} I've already been through my
> > problem with trying to find the cookies on this computer. The fact that
> > I'm using gmail is proof that cookies are enabled. I have also tried:
> > cookie = os.environ.has_key('HTTP_COOKIE')
> > Please advise.
>
> You apparently haven't followed the tutorials carefully enough. You do
> know that a cookie is a piece of information that's stored in your
> browser, don't you? So tell me, which of the above lines of code do you
> suppose is responsible for informing your browser of the cookie's contents?
>

This one:

cookie = SimpleCookie()

In the tutorial found here, for example:

http://www.doughellmann.com/PyMOTW/Cookie/index.html

I read the following:


Cookies are used as state management, and as such as usually set by the
server to be stored and returned by the client. The most trivial example of
creating a cookie looks something like:

import Cookie

c = Cookie.SimpleCookie()
c['mycookie'] = 'cookie_value'
print c

The output is a valid Set-Cookie header ready to be passed to the client as
part of the HTTP response:

$ python Cookie_setheaders.py
Set-Cookie: mycookie=cookie_value


Do not the printout words "Set-cookie" indicate the cookie has been set?
Furthermore, none of the tutorials I have found state anything differently.
Another example is found here:

http://webpython.codepoint.net/cgi_set_the_cookie

Please advise.
TIA,
beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Another Sets Problem

2009-12-30 Thread Victor Subervi
On Tue, Dec 29, 2009 at 6:08 PM, Emile van Sebille  wrote:

> On 12/29/2009 12:52 PM Victor Subervi said...
>
>> On Tue, Dec 29, 2009 at 4:30 PM, Carsten Haese > > wrote:
>>You need to rethink your priorities. Understanding your code is a
>>prerequisite, not a luxury. You keep saying that you'll get around to
>>understanding your code when it's done. My point is that your code will
>>never be done if you don't take the time to understand it.
>>
>>
>> I'm trying to understand it, for crying out loud!
>>
>
> You're kidding, right?  When you can identify that your output is wrong,
> correctly identify the three line for loop in your program where the error
> must be occurring, and still not identify the error?
>
> And then, no mea culpa?
>

I am trying. What part of "I am trying" don't you don't understand? Go away.
I'm not looking at any more of your responses.
beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Portable way to tell if a process is still alive

2009-12-30 Thread Michel Claveau - MVP
Hi!

For Windows, you can use the command-line  tasklist

Example:
   tasklist
   tasklist /FI "IMAGENAME eq iexplore.exe"
   tasklist /FI "PID eq 4044" /FO LIST

The last line is for known PID. Prior for search by (exe's) name.
Note than STATUS give if the process is RUNNING / NOT RESPONDING / etc.
And...tasklist /?  for help.

@+
-- 
Michel Claveau 




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


  1   2   >