urllib, urlretrieve method, how to get headers?

2011-07-01 Thread Даниил Рыжков
Hello, everyone!

How can I get headers with urlretrieve? I want to send request and get
headers with necessary information before I execute urlretrieve(). Or
are there any alternatives for urlretrieve()?

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


Re: how to call a function for evry 10 secs

2011-07-01 Thread Ulrich Eckhardt
Ulrich Eckhardt wrote:
> I'll take this to the developers mailinglist and see if they
> consider the behaviour a bug.

Filed as bug #12459.

Uli

-- 
Domino Laser GmbH
Geschäftsführer: Thorsten Föcking, Amtsgericht Hamburg HR B62 932

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


Re: Trying to chain processes together on a pipeline

2011-07-01 Thread Peter Otten
Andrew Berg wrote:

> Okay, so I've refactored those except WindowsError blocks into calls to
> a function and fixed the os.devnull bug, but I still can't get the
> triple chain working. I added calls to ffmpeg_proc.stdout.close() and
> sox_proc.stdout.close(), but I really am not sure where to put them. The
> following code works if SoX isn't part of the chain (that is, if vol ==
> 1), but not otherwise (the Nero encoder says "truncation error" after it
> finishes; the same error I get if omit the close() calls):

I can't reproduce your setup, but I'd try using communicate() instead of 
wait() and close().

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


Re: urllib, urlretrieve method, how to get headers?

2011-07-01 Thread Chris Rebert
On Fri, Jul 1, 2011 at 12:03 AM, Даниил Рыжков  wrote:
> Hello, everyone!
>
> How can I get headers with urlretrieve? I want to send request and get
> headers with necessary information before I execute urlretrieve(). Or
> are there any alternatives for urlretrieve()?

You can use regular urlopen(), get the headers using the .info()
method of the resulting object, and do the file writing manually.

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


Re: urllib, urlretrieve method, how to get headers?

2011-07-01 Thread Peter Otten
Даниил Рыжков wrote:

> How can I get headers with urlretrieve? I want to send request and get
> headers with necessary information before I execute urlretrieve(). Or
> are there any alternatives for urlretrieve()?
 
It's easy to do it manually:

>>> import urllib2

Connect to website and inspect headers:

>>> f = urllib2.urlopen("http://www.python.org";)
>>> f.headers["Content-Type"]
'text/html'

Write page content to file:

>>> with open("tmp.html", "w") as dest:
... dest.writelines(f)
...

Did we get what we expected?

>>> with open("tmp.html") as f: print f.read().split("title")[1]
...
>Python Programming Language – Official Website>>

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


Re: Trying to chain processes together on a pipeline

2011-07-01 Thread Andrew Berg
On 2011.07.01 02:26 AM, Peter Otten wrote:
> I can't reproduce your setup, but I'd try using communicate() instead of 
> wait() and close().
I don't really know what communicate() does. The docs don't give much
info or any examples (that explain communicate() anyway), and don't say
when communicate() is useful.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Trying to chain processes together on a pipeline

2011-07-01 Thread Chris Rebert
On Fri, Jul 1, 2011 at 1:02 AM, Andrew Berg  wrote:
> On 2011.07.01 02:26 AM, Peter Otten wrote:
>> I can't reproduce your setup, but I'd try using communicate() instead of
>> wait() and close().
> I don't really know what communicate() does.

"Read data from stdout and stderr, until end-of-file is reached. Wait
for process to terminate."
It then returns the read data as two strings. It's pretty straightforward.

> The docs don't give much
> info or any examples (that explain communicate() anyway), and don't say
> when communicate() is useful.

They are slightly roundabout in that respect. The warnings for .wait()
and .stdout/err explain communicate()'s utility:
"Warning: This will deadlock when using stdout=PIPE and/or stderr=PIPE
and the child process generates enough output to a pipe such that it
blocks waiting for the OS pipe buffer to accept more data. ***Use
communicate() to avoid that.***" [emphasis added]

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


Re: urllib, urlretrieve method, how to get headers?

2011-07-01 Thread Даниил Рыжков
Thanks, everyone!
Problem solved.
--
Regards,
Daniil
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: urllib, urlretrieve method, how to get headers?

2011-07-01 Thread Даниил Рыжков
Hello again!
Another question: urlopen() reads full file's content, but how can I
get page by small parts?

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


FOX Toolkit

2011-07-01 Thread Gisle Vanem

In http://docs.python.org/faq/gui.html I came across
FOX Toolkit and the binding FXPy. The latter, it seems
is no longer officially supported (hasn't for the last 7-8 
years). So my question. Has anybody to your knowledge 
tweaked FOX and FXPy to work with Python 2.7?


--gv

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


Re: Using decorators with argument in Python

2011-07-01 Thread John Posner
On 2:59 PM, Ethan Furman wrote:



> def __call__(self, func=None):
> if func is None:
> return self._call()
> self.func = func
> return self
> def _call(self):
> print("\n" + self.char * 50)
> self.func()
> print(self.char * 50 + '\n')
>

I believe the "if" block should be:

  if func is None:
  self._call()
  return

Or perhaps the _call() method should be revised:

  def _call(self):
  print("\n" + self.char * 50)
  retval = self.func()
  print(self.char * 50 + '\n')
  return retval

-John

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


Re: how to call a function for evry 10 secs

2011-07-01 Thread Rune Strand
from threading import Timer

def Func_to_call:
   do_stuff()

my_timer = Timer(10, Func_to_call)
my_timer.start()

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


An ODBC interface for Python 3?

2011-07-01 Thread kozmikyak
Does anyone here have a Python 3 environment that can access MSSQL
using SQLAlchemy, running on a Windows 7 box?  If so, I would like
some assistance making it happen.

The last post on this was mid-2010.  It was mentioned that pyodbc had
a Python 3 branch.  I've been unable to get it compiled and working on
Windows 7 32-bit or 64-bit, even after applying patches mentioned in
one of the project's tracking issues.

Right now anyone forced to support Windows clients, Microsoft SQL, and
SQLAlchemy has no option if wanting to use Python 3.2.  Neither
pymssql or pyodbc compiles out-of-the-box for Python 3.2.  ceODBC
compiles and runs, but SQLAlchemy project has stated that it has no
desire to write yet another dialect supporting ceODBC for MSSQL.

I'm not mentioning this just to complain; I'm just stating it out in
the open so that it's known.  Indeed, even if one doesn't want to use
MSSQL, the only free ODBC interface I know of that works on Python 3
is ceODBC, and it is not supported by other modules such as
SQLAlchemy.

I'm wondering how I could best make something like this happen.  I've
written to the SQLAlchemy and pyodbc projects.  I have average Python
programming skills and have a Windows Python environment with C
compiler installed; perhaps if the authors respond I can assist.

If someone else has already figured out how to make this happen,
please let me know.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: urllib, urlretrieve method, how to get headers?

2011-07-01 Thread Kushal Kumaran
On Fri, Jul 1, 2011 at 2:23 PM, Даниил Рыжков  wrote:
> Hello again!
> Another question: urlopen() reads full file's content, but how can I
> get page by small parts?
>

Set the Range header for HTTP requests.  The format is specified here:
http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35.  Note
that web servers are not *required* to support this header.

In [10]: req = 
urllib2.Request('http://cdimage.debian.org/debian-cd/6.0.2.1/amd64/iso-cd/debian-6.0.2.1-amd64-CD-1.iso',
headers = { 'Range' : 'bytes=0-499' })

In [11]: f = urllib2.urlopen(req)

In [12]: data = f.read()

In [13]: len(data)
Out[13]: 500

In [14]: print f.headers
Date: Fri, 01 Jul 2011 16:59:39 GMT
Server: Apache/2.2.14 (Unix)
Last-Modified: Sun, 26 Jun 2011 16:54:45 GMT
ETag: "ebff2f-2870-4a6a04ab27f10"
Accept-Ranges: bytes
Content-Length: 500
Age: 225
Content-Range: bytes 0-499/678428672
Connection: close
Content-Type: application/octet-stream


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


Re: urllib, urlretrieve method, how to get headers?

2011-07-01 Thread Chris Rebert
On Fri, Jul 1, 2011 at 1:53 AM, Даниил Рыжков  wrote:
> Hello again!
> Another question: urlopen() reads full file's content, but how can I
> get page by small parts?

I don't think that's true. Just pass .read() the number of bytes you
want to read, just as you would with an actual file object.

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


Re: ANN: pyparsing 1.5.6 released!

2011-07-01 Thread Waldek M.
Dnia Thu, 30 Jun 2011 23:09:18 -0700 (PDT), Paul McGuire napisał(a):
> After about 10 months, there is a new release of pyparsing, version
> 1.5.6.  This release contains some small enhancements, some bugfixes,
> and some new examples.

Thanks! That is great news.

I'm not using pyparsing right now, but I used to and surely
will. I just wish it was included in the standard Python distribution
some day...

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


Re: Enhanced dir() function

2011-07-01 Thread Tim Chase

On 06/30/2011 11:29 PM, Steven D'Aprano wrote:

The dir() function is designed for interactive use, inspecting objects for
the names of attributes and methods.

Here is an enhanced version that allows you to pass a glob to filter the
names you see:

Comments and improvements welcome.


Having not seen any other comments on it fly by, I thought I'd 
respond.  While in general I like the idea, I'm not sure when I'd 
go to the effort of bringing the function into my namespace when 
I could just do something like


  >>> [s for s in dir(...) if test_of_interest(s)]

If it came in as an effortless (i.e. O(1) where I do it once and 
never again; not an O(n) where n=the number of times I invoke 
Python) default replacement for dir(), I'd reach for it a lot 
more readily.  I seem to recall there's some environment-var or 
magic file-name that gets sourced on every startup.


I use the list-comp version on a regular basis:

  # implementation of which magic methods?
  [s for s in dir(foo) if s.startswith('__') and s.endswith('__')]

  # ignore magic methods
  [s for s in dir(foo) if not (s.startswith('__') and 
s.endswith('__'))]


  # constants
  [s for s in dir(foo) if s.isupper()]

  # keywording
  [s for s in dir(foo) if 'bar' in s.lower()]

Anyways, even if it just includes a brief blurb about "and this 
is how you get it automatically in every Python session" (or a 
link to the docs on how to do that), it would raise it from "meh" 
to "nifty".


-tim


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


Re: Enhanced dir() function

2011-07-01 Thread Ethan Furman

Tim Chase wrote:
If it came in as an effortless (i.e. O(1) where I do it once and never 
again; not an O(n) where n=the number of times I invoke Python) default 
replacement for dir(), I'd reach for it a lot more readily.  I seem to 
recall there's some environment-var or magic file-name that gets sourced 
on every startup.


interact.py
8<---
import os, sys
sys.ps1 = '--> '

from cookbook.utils import dir  # or whereever you keep your copy
sys.modules['__builtin__'].dir = dir
8<---


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


Re: Enhanced dir() function

2011-07-01 Thread Steven D'Aprano
Tim Chase wrote:

> On 06/30/2011 11:29 PM, Steven D'Aprano wrote:
>> The dir() function is designed for interactive use, inspecting objects
>> for the names of attributes and methods.
>>
>> Here is an enhanced version that allows you to pass a glob to filter the
>> names you see:
>>
>> Comments and improvements welcome.
> 
> Having not seen any other comments on it fly by, I thought I'd
> respond.  While in general I like the idea, I'm not sure when I'd
> go to the effort of bringing the function into my namespace when
> I could just do something like
> 
>>>> [s for s in dir(...) if test_of_interest(s)]

If test_of_interest is complex, then the list comp is the better solution.
Globbing dir is intended for simple globs (naturally!), not complex filter
functions of arbitrary complexity. The equivalent is globbing in the shell:

[steve@sylar python]$ dir p*.py
parallel_map.py  partition.py  perms.py  proc.py  pyprimes.py
paragraphs.pypeekable.py   pi.py progress.py


> If it came in as an effortless (i.e. O(1) where I do it once and
> never again; not an O(n) where n=the number of times I invoke
> Python) default replacement for dir(), I'd reach for it a lot
> more readily.  I seem to recall there's some environment-var or
> magic file-name that gets sourced on every startup.

There is some talk on the python-ideas mailing list about enhancing the
built-in dir().

But in the meantime, you can add it to your site.py module, or better still,
use your own personal startup file rather than the system site.py. I have
an environment variable set in my .bashrc file:

export PYTHONSTARTUP=/home/steve/python/startup.py

and then put code I want to run at startup in startup.py. For Windows users,
I don't know how to set environment variables, but I dare say it would be
something similar: set the environment variable PYTHONSTARTUP to a file
name, and put the code in that file.


> I use the list-comp version on a regular basis:
> 
># implementation of which magic methods?
>[s for s in dir(foo) if s.startswith('__') and s.endswith('__')]

This would become:

dir(foo, "__*__")


># ignore magic methods
>[s for s in dir(foo) if not (s.startswith('__') and
> s.endswith('__'))]

dir(foo, "[!_]*[!_]")

although strictly speaking, my version only tests for one leading and
trailing underscore, not two.

># constants
>[s for s in dir(foo) if s.isupper()]

That's beyond the capabilities of simple globbing.


># keywording
>[s for s in dir(foo) if 'bar' in s.lower()]

I'm of two minds about case-insensitive globbing. It could be done with a
slight change to the function, but I'm not sure if I want to.


> Anyways, even if it just includes a brief blurb about "and this
> is how you get it automatically in every Python session" (or a
> link to the docs on how to do that), it would raise it from "meh"
> to "nifty".

Thanks for the feedback.


-- 
Steven

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


Nested/Sub Extensions in Python

2011-07-01 Thread H Linux
Dear all,

I am currently fighting with a problem writing a set of Python
extensions in C. I want to structure the whole package (here called
smt for sub-module test) into different sub-modules, e.g. according to
this layout:

smt.foo.func()

I can only build a module
>import foo
>print foo.func(1,2)

Once I try to nest this, I cannot get the module to load anymore:
>import smt.bar
Traceback (most recent call last):
  File "", line 1, in 
ImportError: No module named bar

I have found the following hints on the web:
http://stackoverflow.com/questions/1681281/nested-python-c-extensions-modules
I have also found that XEN has a python module which does this, but
http://www.google.de/codesearch#4Wqoij9clTg/tools/python/setup.py

Still I am unable to get this to work. What am I missing? In case it
matters, this is on Ubuntu10.4/Python2.6.5 Below are listings from my
source files.

Thanks in advance for any help,
Hartwig


1. setup.py:
from distutils.core import setup, Extension
PACKAGE_NAME = 'smt'
setup(
name = PACKAGE_NAME,
version  = '0.1',
author   = 'Myself',
packages = [PACKAGE_NAME],
ext_modules  = [ Extension('foo', ['src/foo.c']),
 Extension('smt.bar', ['src/bar.c'])  ]
)

2. src/bar.c
#include 

static PyObject*
bar_func(PyObject *self, PyObject *args)
{
PyObject *a, *b;

if (!PyArg_UnpackTuple(args, "func", 2, 2, &a, &b)) {
return NULL;
}

return PyNumber_Add(a, b);
}

static PyMethodDef bar_methods[] = {
  {"func", bar_func, METH_VARARGS, NULL},
{NULL, NULL}
};

PyMODINIT_FUNC
initbar(void)
{
Py_InitModule("smt.bar", bar_methods);
}

3. src/foo.c
#include 

static PyObject*
foo_func(PyObject *self, PyObject *args)
{
PyObject *a, *b;
if (!PyArg_UnpackTuple(args, "func", 2, 2, &a, &b)) {
return NULL;
}
return PyNumber_Add(a, b);
}

static PyMethodDef foo_methods[] = {
{"func", foo_func, METH_VARARGS, NULL},
{NULL, NULL}
};

PyMODINIT_FUNC
initfoo(void)
{
Py_InitModule("foo", foo_methods);
}

4. Code Layout:
├── setup.py
├── smt
│   └── __init__.py
└── src
├── bar.c
└── foo.c
-- 
http://mail.python.org/mailman/listinfo/python-list


How to get a dateiled process information on windows?

2011-07-01 Thread Leandro Ferreira
I need to write an application that monitors the memory consumption of
a process, there is some library that facilitates this work?
I searched on google found nothing more interesting.

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


Re: How to get a dateiled process information on windows?

2011-07-01 Thread Tim Golden

On 01/07/2011 21:06, Leandro Ferreira wrote:

I need to write an application that monitors the memory consumption of
a process, there is some library that facilitates this work?
I searched on google found nothing more interesting.


Have a look at WMI

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


Does anyone know of a python tapi module

2011-07-01 Thread Alister Ware
The subject probably say is all but to elaborate.

I am looking for a way to communicate with a tapi driver for a PBX so I 
can experiment with creating some CTI (Computer Telephony Integration) 
software.


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


Re: How to get a dateiled process information on windows?

2011-07-01 Thread Christian Heimes
Am 01.07.2011 22:06, schrieb Leandro Ferreira:
> I need to write an application that monitors the memory consumption of
> a process, there is some library that facilitates this work?
> I searched on google found nothing more interesting.

Have a look at psutil http://code.google.com/p/psutil/ . It works on all
major platforms and gives you extended system information (processes,
threads, memory, cpu).

Christian

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


Re: Nested/Sub Extensions in Python

2011-07-01 Thread Carl Banks
On Friday, July 1, 2011 1:02:15 PM UTC-7, H Linux wrote:
> Once I try to nest this, I cannot get the module to load anymore:
> >import smt.bar
> Traceback (most recent call last):
>   File "", line 1, in 
> ImportError: No module named bar

[snip]

> PyMODINIT_FUNC
> initbar(void)
> {
>   Py_InitModule("smt.bar", bar_methods);
> }

This should be: Py_InitModule("bar", bar_methods);

That's probably it; other than that, it looks like you did everything right.  
What does the installed file layout look like after running distutils setup?


Carl Banks

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


Re: urllib, urlretrieve method, how to get headers?

2011-07-01 Thread Даниил Рыжков
Thanks, everyone!
Problem solved.

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


Re: Nested/Sub Extensions in Python

2011-07-01 Thread Corey Richardson
Excerpts from H Linux's message of Fri Jul 01 16:02:15 -0400 2011:
> Dear all,
> 
> I am currently fighting with a problem writing a set of Python
> extensions in C.

If you haven't seen it yet, Cython is a *very* nice tool for writing
C extensions. http://cython.org/
-- 
Corey Richardson
  "Those who deny freedom to others, deserve it not for themselves"
 -- Abraham Lincoln
-- 
http://mail.python.org/mailman/listinfo/python-list


subtle error slows code by 10x (builtin sum()) - replace builtin sum without using import?

2011-07-01 Thread bdb112
First a trap for new players, then a question to developers

Code accelerated by numpy can be slowed down by a large factor is you
neglect to import numpy.sum .

from timeit import Timer
frag = 'x=sum(linspace(0,1,1000))'
Timer(frag ,setup='from numpy import linspace').timeit(1000)
# 0.6 sec
Timer(frag, setup='from numpy import sum, linspace').timeit(1000)  #
difference is I import numpy.sum
# 0.04 sec  15x faster!

This is obvious of course - but it is very easy to forget to import
numpy.sum and pay the price in execution.

Question:
Can I replace the builtin sum function globally for test purposes so
that my large set of codes uses the replacement?

The replacement would simply issue warnings.warn() if it detected an
ndarray argument, then call the original sum
I could then find the offending code and use the appropriate import to
get numpy.sum
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: subtle error slows code by 10x (builtin sum()) - replace builtin sum without using import?

2011-07-01 Thread Albert Hopkins


On Friday, July 1 at 19:17 (-0700), bdb112 said:

> Question:
> Can I replace the builtin sum function globally for test purposes so
> that my large set of codes uses the replacement?
> 
> The replacement would simply issue warnings.warn() if it detected an
> ndarray argument, then call the original sum
> I could then find the offending code and use the appropriate import to
> get numpy.sum

You shouldn't do this, but you could use the __builtins__ module

e.g.

>>> __builtins__.sum = numpy.sum # bad



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


Re: Is the Usenet to mailing list gateway borked?

2011-07-01 Thread TP
On Thu, Jun 30, 2011 at 11:41 AM, Thomas 'PointedEars' Lahn
 wrote:
> Thomas Guettler wrote:
>
>> On 30.06.2011 03:24, Thomas 'PointedEars' Lahn wrote:
>>> Andrew Berg wrote:
 […]
>>>
>>> As for your question in the Subject, I do not know since I am reading the
>>> newsgroup.
>>>
>>> Therefore, however, I can tell you that the mailing list to Usenet
>>> gateway is seriously borked, as missing References header fields are not
>>> generated by the gateway.  As a result, there are few if any threads left
>>> in the newsgroup, which makes it an increasing PITA to read.  (And no,
>>> threading by Subject is a stupid idea.)
>>>
>>> Would someone responsible *please* fix this?  I am willing to provide
>>> assistance, see also my suggestion in
>>> .
>>
>> Who is responsible?
>
> If I knew that I would not ask here.
>
>> I think in the past there were not many broken threads. I wonder what
>> changed this.
>
> One factor, as I see it, is an increasing number of people using e-mail
> clients that do not generate the References header field, as it is only a
> SHOULD, not a MUST per RFC 5322, or people using mail clients that are FUBAR
> (like G2, Google Groups and Mail).  But that header field is mandatory for
> Network News (RFC 5536), and if it is missing you create a mess for
> newsreaders (applications and people alike).  "Bugs" making a slumbering
> real bug in the gateway implementation apparent.
>
> But that appears to be only half the truth as e.g. I can retrieve none of
> the messages that  of
> 15:19 GMT+02:00 today refers to, regardless from where they supposedly
> originated.  I am not deleting messages locally and I have a rather fast and
> reliable newsfeed, so the messages should have arrived by now.
>
> --
> PointedEars
>
> Bitte keine Kopien per E-Mail. / Please do not Cc: me.
> --
> http://mail.python.org/mailman/listinfo/python-list
>

Not sure if this is relevant. I use mail.google.com to follow mailing
lists and a large proportion of python-list traffic ends up in my
gmail spam folder for some reason?

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


Re: Is the Usenet to mailing list gateway borked?

2011-07-01 Thread Chris Angelico
On Fri, Jul 1, 2011 at 8:33 PM, TP  wrote:
> Not sure if this is relevant. I use mail.google.com to follow mailing
> lists and a large proportion of python-list traffic ends up in my
> gmail spam folder for some reason?

Set a filter (you can "Filter messages like this") that says "Never
spam". That stops that from happening.

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


Re: subtle error slows code by 10x (builtin sum()) - replace builtin sum without using import?

2011-07-01 Thread Chris Torek
In article 
bdb112   wrote:
>First a trap for new players, then a question to developers
>
>Code accelerated by numpy can be slowed down by a large factor is you
>neglect to import numpy.sum .
>
>from timeit import Timer
>frag = 'x=sum(linspace(0,1,1000))'
>Timer(frag ,setup='from numpy import linspace').timeit(1000)
># 0.6 sec
>Timer(frag, setup='from numpy import sum, linspace').timeit(1000)  #
>difference is I import numpy.sum
># 0.04 sec  15x faster!
>
>This is obvious of course - but it is very easy to forget to import
>numpy.sum and pay the price in execution.
>
>Question:
>Can I replace the builtin sum function globally for test purposes so
>that my large set of codes uses the replacement?
>The replacement would simply issue warnings.warn() if it detected an
>ndarray argument, then call the original sum
>I could then find the offending code and use the appropriate import to
>get numpy.sum


Sure, just execute code along these lines before running any of
the tests:

import __builtin__
import warnings

_sys_sum = sum # grab it before we change __builtin__.sum

def hacked_sum(sequence, start=0):
if isinstance(sequence, whatever):
warnings.warn('your warning here')
return _sys_sum(sequence, start)

__builtin__.sum = hacked_sum

(You might want to grab a stack trace too, using the traceback
module.)  You said "without using import" but all you have to
do is arrange for python to import this module before running
any of your own code, e.g., with $PYTHONHOME and a modified
site file.
-- 
In-Real-Life: Chris Torek, Wind River Systems
Intel require I note that my opinions are not those of WRS or Intel
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W)  +1 801 277 2603
email: gmail (figure it out)  http://web.torek.net/torek/index.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to call a function for evry 10 secs

2011-07-01 Thread Rune
>Dennis Lee Bieber: 
>   Timer() is a one-shot; per the OPs requirements even it would need
> to be placed within a loop to invoke multiple calls -- so there isn't
> much gain in terms of lines of code... And worse, since it calls the
> function asynchronously and not sequentially, a delay time for each
> instance would have to be computed inside the loop too...

The first/last task for the called function may be to instantiate a new Timer - 
depending on what "every 10 secs" means. The OP does not detail his actual 
problem, so I can't see that the async/sequential issue.

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