Re: Where is the syntax for the dict() constructor ?!

2007-07-06 Thread Hendrik van Rooyen
 "Marc 'BlackJack' Rintsch" <[EMAIL PROTECTED]> wrote:
> On Fri, 06 Jul 2007 08:34:55 +0200, Hendrik van Rooyen wrote:
> 
> > You can even do it more simply - by writing a GetField() that
> > scans for either the delimiter or end of line or end of file, and 
> > returns the "field" found, along with the delimiter that caused 
> > it to exit, and then writing a GetRecord() that repetitively calls
> > the GetField and assembles the row record until the delimiter 
> > returned is either the end of line or the end of file, remembering 
> > that the returned field may be empty, and handling the cases based 
> > on the delimiter returned when it is.
> > 
> > This also makes all the decisions based on the current character
> > read, no lookahead as far as I can see.
> > 
> > Also no state variables, no switch statements...
> > 
> > Is this the method that you would call "Mickey Mouse"?
> 
> Maybe, because you've left out all handling of quoting and escape
> characters here.  Consider this:
> 
> erik,viking,"ham, spam and eggs","He said ""Ni!""","line one
> line two"
> 
> That's 5 elements:
> 
> 1: eric
> 2: viking
> 3: ham, spam and eggs
> 4: He said "Ni!"
> 5: line one
>line two

Also true - What can I say - I can only wriggle and mutter...

I see that you escaped the quotes by doubling them up -
What would the following parse to?:

 erik,viking,ham, spam and eggs,He said "Ni!",line one
 line two

- Hendrik


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


Getting the home directory in Python and a bug in os.path.expanduser

2007-07-06 Thread Edward Diener
What is the generic operating system way of getting the home directory ?

I am guessing it is os.path.expanduser("~"). Is there a better way or an 
alternate way ?

If it is as I surmise, the aforementioned expanduser("~") of os.path 
seems incorrect to me under Windows. The document says:

"On Windows, only "~" is supported; it is replaced by the environment 
variable HOME or by a combination of HOMEDRIVE and HOMEPATH."

But HOME is never the home directory for Windows, only the combination 
of HOMEDRIVE and HOMEPATH is valid, which is always set. If MSYS is 
installed under Windows, where HOME must be set to the MSYS home 
directory for a given user in order to emulate Linux/Unix, attempting to 
use os.path.expanduser("~") will incorrectly return the MSYS home 
directory for a given user rather than the Windows home directory for 
the logged in user. So I think the os.path.expanduser("~") works 
incorrectly in this case and needs to be fixed, else you are telling 
users never to use MSYS under Windows.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: object references/memory access

2007-07-06 Thread Alex Martelli
Dennis Lee Bieber <[EMAIL PROTECTED]> wrote:
   ...
>   Think VMS was the most applicable for that behavior... Haven't seen
> any dynamic priorities on the UNIX/Linux/Solaris systems I've
> encountered...

Dynamic priority scheduling is extremely common in Unixen today (and has
been for many years); see e.g.

for the _enhancements_ FreeBSD 5.2 brought to this idea a few years ago,
for example.


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


Re: How would I write this C code in Python?

2007-07-06 Thread Steven D'Aprano
On Fri, 06 Jul 2007 17:31:50 +, DeveloperX wrote:

> Python Attempt: Please note that since I can't type TABs online
> easily, I am using the @ character to represent TABs in the following
> Python code.

Why not indent with spaces, just like you did for the example C code?


-- 
Steven.


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


Re: C++ Modules for python: How to?

2007-07-06 Thread John Machin
On Jul 7, 9:26 am, Robert Dailey <[EMAIL PROTECTED]> wrote:
> On Jul 6, 3:06 pm, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
>
>
>
> > Robert Dailey schrieb:
>
> > > Hi,
>
> > > I'm interested in making a C++ library of mine usable through python.
> > > Python does a similar thing with Expat (the non-validating XML
> > > parser). I notice that with Expat, python is importing a C++ header
> > > file into a PY file and the interface is available to python. I've
> > > read through the python documentation as well as done a little bit of
> > > google research and I've not been able to find a tutorial of some sort
> > > on how to do this. Perhaps I just don't know the right words to search
> > > for.
>
> > > If anyone could lead me in the right direction (possibly an article,
> > > tutorial, etc) I would greatly appreciate it.
>
> > The best thing to do is to offer your C++-lib with a C-style interface.
> > Then you can use python's ctypes (included since python2.5) to access
> > the shared library.
>
> > If you insist on using C++, you can expose the lib using several
> > available wrapper generators. I know of three: SIP, Swig &
> > Boost::Python. The first I've got some very good first-hand experience.
> > The second is somewhat primitive IHMO. The third I never used.
>
> > Use these to google in this group, you'll find plenty of stuff.
>
> > Diez
>
> How do I install SIP? I can't seem to do this. I've downloaded the
> package and read the README file, but I don't see a way of installing
> it on windows. I ran the configure.py file but then it generates
> makefiles to run which can't be run on windows. I also attempted to
> download QT but it doesn't appear to be free (it's an evaluation and I
> don't feel like submitting my personal information to download it).
>
> Am I missing something?

Probably.

"makefiles ... which can't be run on windows"??? Have you acquired a
make program [if necessary] and tried it? What happened?

The free Borland compiler comes with a make.exe. If you plan to use
GCC, you will probably need this:
http://gnuwin32.sourceforge.net/packages/make.htm
I understand that if you have a Microsoft compiler, you should have an
nmake.exe.

If all else fails, e-mail the package author, supplying some relevant
information, like what compiler you are using, what options you used
on the configure.py run, which "make" you are using, what happened
when you ran that make, ...


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


Re: Repeating Thread Error

2007-07-06 Thread Steve Holden

Jonathan Shan wrote:

Hello,

I am trying to call a function every 5 seconds. My understanding of
time.sleep() is during the sleep time everything "stops". However, in
my application, there are background processes that must be running
continuously during the five second interval. Thus, threading.Timer
seems like a good function. Here is the relevant code:

# background processes
t = threading.Timer(5.0, function_name, [arguments])
while True:
 # Do background processes run inside while loop?
 t.start()

The above code generates an error:
AssertionError: thread already started

Any hints on how to fix the error? Also, do background processes run
inside while loops?

Thanks in advance,
Jonathan Shan

Here's a little thread-test program I wrote a few years ago. I hope it 
will explain how threads and sleeps interact.


regards
 Steve
--
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden
--- Asciimercial --
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
--- Thank You for Reading -

import time, threading, random

class MyThread(threading.Thread):
""" Each thread picks a 'random' integer between 0 and 19 and reports
in once per second for that many seconds.
"""

def run(self):
iterations = random.randint(0, 19)
print "Thread", self.getName(), "starting", iterations, "iterations"
for i in range(iterations):
print "   ", self.getName(), "is reporting "
time.sleep(1)
print self.getName(), "is DONE"

def test():
threadList = []
iterCount = 0

# Create 5 MyThread() threads
for i in range(5) :
thread = MyThread()
threadList.append(thread)

# Start all threads
for thread in threadList:
thread.start()

# As long as we have more than just the 'main' thread running, print out
# a status message
while threading.activeCount() > 1 :
print "-- after", iterCount, "sleeps", \
  str(threading.activeCount()), "threads running including main"
iterCount += 1
time.sleep(1)
print "Only main thread remains"

if __name__ == '__main__':
test()
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: ImportError: "No Module named xxx"

2007-07-06 Thread John Machin
On Jul 7, 7:37 am, Robert Dailey <[EMAIL PROTECTED]> wrote:
> On Jul 6, 4:04 pm, Bjoern Schliessmann 
>
>
> [EMAIL PROTECTED]> wrote:
> > Robert Dailey wrote:
> > > The description of -m is confusing in the documentation, what does
> > > it really do?
>
> > IMHO, it's quite clear. What's unclear with this description:
>
> > -m module-nameSearches sys.path for the named module and runs
> >   the corresponding .py file as a script.
>

>
> Perhaps the confusing part is their definition of "Script".

"They" have not provided a definition of "script", confusing or
otherwise.

"runs ... as a script" means like what happens when you do this:
python compile.py

>  I figured
> any .py file was a "python script", in that it has code to execute-
> making it a script.

Not necessarily; a .py file can be intended solely for import, and
would do nothing useful/visible if executed as a script.

However, back to your problem ..

The documentation for -m says "module-name". The error message says
"No module named compile.py". The name of the module is "compile", not
"compile.py". If you are desperate to use the -m option, do this:
python -m compile

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


Re: Repeating Thread Error

2007-07-06 Thread jimxu
hmm.. why use while True? After 5 secs, the function is going to run. so

t = threading.Thread(5.0, func)
t.start()

should just work. Put it in a infinite loop will start the thread and  
then start a the stopped thread... forever.

Jim


On Jul 6, 2007, at 2:40 PM, Jonathan Shan wrote:

> Hello,
>
> I am trying to call a function every 5 seconds. My understanding of
> time.sleep() is during the sleep time everything "stops". However, in
> my application, there are background processes that must be running
> continuously during the five second interval. Thus, threading.Timer
> seems like a good function. Here is the relevant code:
>
> # background processes
> t = threading.Timer(5.0, function_name, [arguments])
> while True:
>  # Do background processes run inside while loop?
>  t.start()
>
> The above code generates an error:
> AssertionError: thread already started
>
> Any hints on how to fix the error? Also, do background processes run
> inside while loops?
>
> Thanks in advance,
> Jonathan Shan
>
> -- 
> http://mail.python.org/mailman/listinfo/python-list

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


Re: Expandable 2D Dictionaries?

2007-07-06 Thread Steve Holden
Jean-Paul Calderone wrote:
> On Fri, 06 Jul 2007 15:43:55 -, Robert Dailey <[EMAIL PROTECTED]> wrote:
>> Hi,
>>
>> I am interested in creating an expandable (dynamic) 2D dictionary. For
>> example:
>>
>> myvar["cat"]["paw"] = "Some String"
>>
>> The above example assumes "myvar" is declared. In order for this to
>> work, I have to know ahead of time the contents of the dictionary. For
>> the above to work, my declaration must look like:
>>
>> myvar = {"cat": {"paw":""} }
>>
>> I would like to not have to declare my dictionary like this, as it
>> does not allow it to be expandable. I'm very new to Python (I'm a
>> professional C++ programmer. Any comparisons to C++ would help me
>> understand concepts).
>>
>> Is there a way that when I index into my dictionary using an "unknown"
>> index (string), that python will dynamically add that key/value pair?
> 
> This gets much easier if you change your structure around a bit:
> 
> d = {}
> d["cat", "paw"] = "some string"
> 
> Jean-Paul

Unfortunately that makes it somewhat more difficult to retrieve the set 
of entries whose first index is "cat". I realise that we don't have much 
in the way of use cases here, but it would seem that the original 
motivation for a two-level dictionary might have been such a requirement.

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden
--- Asciimercial --
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
--- Thank You for Reading -

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


Re: C++ Modules for python: How to?

2007-07-06 Thread Robert Dailey
On Jul 6, 3:06 pm, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
> Robert Dailey schrieb:
>
> > Hi,
>
> > I'm interested in making a C++ library of mine usable through python.
> > Python does a similar thing with Expat (the non-validating XML
> > parser). I notice that with Expat, python is importing a C++ header
> > file into a PY file and the interface is available to python. I've
> > read through the python documentation as well as done a little bit of
> > google research and I've not been able to find a tutorial of some sort
> > on how to do this. Perhaps I just don't know the right words to search
> > for.
>
> > If anyone could lead me in the right direction (possibly an article,
> > tutorial, etc) I would greatly appreciate it.
>
> The best thing to do is to offer your C++-lib with a C-style interface.
> Then you can use python's ctypes (included since python2.5) to access
> the shared library.
>
> If you insist on using C++, you can expose the lib using several
> available wrapper generators. I know of three: SIP, Swig &
> Boost::Python. The first I've got some very good first-hand experience.
> The second is somewhat primitive IHMO. The third I never used.
>
> Use these to google in this group, you'll find plenty of stuff.
>
> Diez

How do I install SIP? I can't seem to do this. I've downloaded the
package and read the README file, but I don't see a way of installing
it on windows. I ran the configure.py file but then it generates
makefiles to run which can't be run on windows. I also attempted to
download QT but it doesn't appear to be free (it's an evaluation and I
don't feel like submitting my personal information to download it).

Am I missing something? Thank you for your reply.

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


Re: Repeating Thread Error

2007-07-06 Thread Marc 'BlackJack' Rintsch
On Fri, 06 Jul 2007 14:40:16 -0700, Jonathan Shan wrote:

> I am trying to call a function every 5 seconds. My understanding of
> time.sleep() is during the sleep time everything "stops".

Not "everything", just the thread in which `sleep()` is called.

> However, in my application, there are background processes that must be
> running continuously during the five second interval.

Then start them as threads and they will run all the time.

> Thus, threading.Timer seems like a good function. Here is the relevant
> code:
> 
> # background processes
> t = threading.Timer(5.0, function_name, [arguments])
> while True:
>  # Do background processes run inside while loop?
>  t.start()
> 
> The above code generates an error:
> AssertionError: thread already started
> 
> Any hints on how to fix the error?

A thread can only be started once but you try to start the `Timer` over
and over.  And you don't wait, so even if this would "work" you would
start many, many `Timer`\s as fast as the ``while`` loop runs. The
`Timer`\s would all run the function after five seconds.  It's like::

  while True:
  function_name(*arguments)

just with a five second delay.

> Also, do background processes run inside while loops?

This question doesn't make much sense to me.  Do ``while`` loops block
other threads?  No of course not.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Auto-parallelizing with decorators?

2007-07-06 Thread Kirk Strauser
In article <[EMAIL PROTECTED]>,
 Kirk Strauser <[EMAIL PROTECTED]> wrote:

> I was thinking about how a lot of Lisp proponents claim that Lisp is
> inherently parallelizable because its functions don't have (or are not
> supposed to have) side effects, and therefore the compiler can easily tell
> which calls may be run in parallel instead of strictly serially.  I'm not a
> Lisp expert so I can't say whether that's true or not, but it seems like an
> interesting idea for Python.

By the way, I uploaded a sample implementation (in Python) of what I had 
in mind to http://www.honeypot.net/multi-processing-map-python .  Please 
let me know what you think of it and whether it seems remotely 
interesting or goofy.
-- 
Kirk Strauser
-- 
http://mail.python.org/mailman/listinfo/python-list


Repeating Thread Error

2007-07-06 Thread Jonathan Shan
Hello,

I am trying to call a function every 5 seconds. My understanding of
time.sleep() is during the sleep time everything "stops". However, in
my application, there are background processes that must be running
continuously during the five second interval. Thus, threading.Timer
seems like a good function. Here is the relevant code:

# background processes
t = threading.Timer(5.0, function_name, [arguments])
while True:
 # Do background processes run inside while loop?
 t.start()

The above code generates an error:
AssertionError: thread already started

Any hints on how to fix the error? Also, do background processes run
inside while loops?

Thanks in advance,
Jonathan Shan

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


Re: ImportError: "No Module named xxx"

2007-07-06 Thread Robert Dailey
On Jul 6, 4:04 pm, Bjoern Schliessmann  wrote:
> Robert Dailey wrote:
> > The description of -m is confusing in the documentation, what does
> > it really do?
>
> IMHO, it's quite clear. What's unclear with this description:
>
> -m module-nameSearches sys.path for the named module and runs
>   the corresponding .py file as a script.
>
> Regards,
>
> Björn
>
> --
> BOFH excuse #191:
>
> Just type 'mv * /dev/null'.

Perhaps the confusing part is their definition of "Script". I figured
any .py file was a "python script", in that it has code to execute-
making it a script.

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

Re: ImportError: "No Module named xxx"

2007-07-06 Thread Bjoern Schliessmann
Robert Dailey wrote:

> The description of -m is confusing in the documentation, what does
> it really do?

IMHO, it's quite clear. What's unclear with this description:

-m module-nameSearches sys.path for the named module and runs
  the corresponding .py file as a script.

Regards,


Björn


-- 
BOFH excuse #191:

Just type 'mv * /dev/null'.

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


hi everyone if you want to be come a member please follow the lınk

2007-07-06 Thread kasim
Sample email


Dear __,


I recently joined AGLOCO because of a friend recommended it to me. I
am now promoting it to you because I like the idea and I want you to
share in what I think will be an exciting new Internet concept.


AGLOCO's story is simple:


Do you realize how valuable you are? Advertisers, search providers and
online retailers are paying billions to reach you while you surf.  How
much of that money are you making? NONE!


AGLOCO thinks you deserve a piece of the action.


AGLOCO collects money from those companies on behalf of its members.
(For example, Google currently pays AOL 10 cents for every Google
search by an AOL user. And Google still has enough profit to pay $1.6
billion dollars for YouTube, an 18-month old site full of content that
YouTube's users did not get paid for!


AGLOCO will work to get its Members their share of this and more.


AGLOCO is building a new form of online community that they call an
Economic Network. They are not only paying Members their fair share,
but they're building a community that will generate the kind of
fortune that YouTube made. But instead of that wealth making only a
few people rich, the entire community will get its share.


What's the catch? No catch - no spyware, no pop-ups and no spam -
membership and software are free and AGLOCO is 100% member owned.
Privacy is a core value and AGLOCO never sells or rents member
information.


So do both of us a favor: Sign up for AGLOCO right now! If you use
this link to sign up, I automatically get credit for referring you and
helping to build AGLOCO. http://www.agloco.com/r/BBFR2592
 foll


Thanks

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


Re: The best platform and editor for Python

2007-07-06 Thread J Sisson

On 7/6/07, Ed Jensen <[EMAIL PROTECTED]> wrote:


Alex Martelli <[EMAIL PROTECTED]> wrote:
> Calling all vi/vim users (and we'll heartily appreciate the support of
> TextMate fans, BBEdit ones, etc, etc) -- we're at risk being defined out
> of existence, since we're neither happy with Emacs nor wanting anything
> like Visual Studio, and yet Kay claims that people in either category
> make up the whole (one half plus the other half) and so that WE DON'T
> EXIST!!!  A ridiculous claim to be sure, but we'd better let Herr
> Schluehr know that in no uncertain terms...

vi/vim/gvim user here...  :)
--
http://mail.python.org/mailman/listinfo/python-list



Reaganomics?  1/2 + 1/2 + 1/2 = 100%?

Interesting concept...

Oh, vi/vim user here, too =)

--
Computers are like air conditioners...
They quit working when you open Windows.
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: The best platform and editor for Python

2007-07-06 Thread Ed Jensen
Alex Martelli <[EMAIL PROTECTED]> wrote:
> Calling all vi/vim users (and we'll heartily appreciate the support of
> TextMate fans, BBEdit ones, etc, etc) -- we're at risk being defined out
> of existence, since we're neither happy with Emacs nor wanting anything
> like Visual Studio, and yet Kay claims that people in either category
> make up the whole (one half plus the other half) and so that WE DON'T
> EXIST!!!  A ridiculous claim to be sure, but we'd better let Herr
> Schluehr know that in no uncertain terms...

vi/vim/gvim user here...  :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python's "only one way to do it" philosophy isn't good?

2007-07-06 Thread Douglas Alan
"Chris Mellon" <[EMAIL PROTECTED]> writes:

> Sure, but thats part of the general refcounting vs GC argument -
> refcounting gives (a certain level of) timeliness in resource
> collection, GC often only runs under memory pressure. If you're
> saying that we should keep refcounting because it provides better
> handling of non-memory limited resources like file handles, I
> probably wouldn't argue. But saying we should keep refcounting
> because people like to and should write code that relies on implicit
> scope level object destruction I very strongly argue against.

And why would you do that?  People rely very heavily in C++ on when
destructors will be called, and they are in fact encouraged to do so.
They are, in fact, encouraged to do so *so* much that constructs like
"finally" and "with" have been rejected by the C++ BDFL.  Instead, you
are told to use smart pointers, or what have you, to clean up your
allocated resources.

I so no reason not to make Python at least as expressive a programming
language as C++.

>> > Relying on the specific semantics of refcounting to give
>> > certain lifetimes is a logic error.
>> >
>> > For example:
>> >
>> > f = some_file() #maybe it's the file store for a database implementation
>> > f.write('a bunch of stuff')
>> > del f
>> > #insert code that assumes f is closed.

>> That's not a logic error if you are coding in CPython, though I agree
>> that in this particular case the explicit use of "with" would be
>> preferable due to its clarity.

> I stand by my statement. I feel that writing code in this manner is
> like writing C code that assumes uninitialized pointers are 0 -
> regardless of whether it works, it's erroneous and bad practice at
> best, and actively harmful at worst.

That's a poor analogy.  C doesn't guarantee that pointers will be
initialized to 0, and in fact, they typically are not.  CPython, on
other other hand, guarantees that the refcounter behaves a certain
way.

There are languages other than C that guarantee that values are
initialized in certain ways.  Are you going to also assert that in
those languages you should not rely on the initialization rules?

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


Re: The file executing

2007-07-06 Thread Benjamin
On Jul 3, 8:56 am, Sebastian Wiesner <[EMAIL PROTECTED]> wrote:
> [ Benjamin <[EMAIL PROTECTED]> ]
>
> > On Jul 2, 9:47 pm, Justin Ezequiel <[EMAIL PROTECTED]>
>
> > wrote:
> > > On Jul 3, 9:40 am, Benjamin <[EMAIL PROTECTED]> wrote:
> > > > How does one get the path to the file currently executing (not the
> > > > cwd). Thank you
>
> > > os.path.dirname(sys.argv[0])
>
> > The returns the file that was called first, but not the one currently
> > executing...
>
> Use __file__ instead of sys.argv[0]
So:
if __name__ == "main":
currentDir = os.path.dirname(sys.argv[0])
else:
currentDir = os.path.dirname(__file__)
>
> --
> Freedom is always the freedom of dissenters.
>   (Rosa Luxemburg)
>
>  signature.asc
> 1KDownload


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


Re: C++ Modules for python: How to?

2007-07-06 Thread Diez B. Roggisch
Robert Dailey schrieb:
> Hi,
> 
> I'm interested in making a C++ library of mine usable through python.
> Python does a similar thing with Expat (the non-validating XML
> parser). I notice that with Expat, python is importing a C++ header
> file into a PY file and the interface is available to python. I've
> read through the python documentation as well as done a little bit of
> google research and I've not been able to find a tutorial of some sort
> on how to do this. Perhaps I just don't know the right words to search
> for.
> 
> If anyone could lead me in the right direction (possibly an article,
> tutorial, etc) I would greatly appreciate it.

The best thing to do is to offer your C++-lib with a C-style interface. 
Then you can use python's ctypes (included since python2.5) to access 
the shared library.

If you insist on using C++, you can expose the lib using several 
available wrapper generators. I know of three: SIP, Swig & 
Boost::Python. The first I've got some very good first-hand experience. 
The second is somewhat primitive IHMO. The third I never used.

Use these to google in this group, you'll find plenty of stuff.

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


Re: Auto-parallelizing without decorators?

2007-07-06 Thread John Nagle
Kirk Strauser wrote:
> I was thinking about how a lot of Lisp proponents claim that Lisp is
> inherently parallelizable because its functions don't have (or are not
> supposed to have) side effects, and therefore the compiler can easily tell
> which calls may be run in parallel instead of strictly serially.  I'm not a
> Lisp expert so I can't say whether that's true or not, but it seems like an
> interesting idea for Python.
> 
> Suppose that Python had a new decorator, say "@parallelizable".  Functions
> so decorated would be eligible for multi-processed or multi-threaded
> execution by such native constructs as list comprehensions, or the map()
> function.

That implies much smarter compilers than we've seen to date for Python.

A more useful idea might be to provide a map/reduce library in the
sense that Google uses the term.

Google's concept of "map/reduce" is that the mapped function is applied
to all the elements of the list simultaneously, up to the limits of resources
available.  The result of each function is a name/value tuple.  The
reduction process consists of collecting all tuples with the same name
and feeding them to copies of the "reduce" function in no particular order,
with the "reduce" function producing fewer output tuples than input tuples.
The "reduce" function is applied repeatedly in a tree sense until all
output tuples have been reduced.

See:

http://labs.google.com/papers/mapreduce.html

Contrast this with Python's "reduce", which is inherently sequential.

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


Re: ImportError: "No Module named xxx"

2007-07-06 Thread Robert Dailey
Never mind, I found the problem. I was doing:

python -m compile.py

I really should have been doing:

python compile.py


The description of -m is confusing in the documentation, what does it
really do?

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


ImportError: "No Module named xxx"

2007-07-06 Thread Robert Dailey
I created a basic python file and made an attempt to execute it from
the command line, however it gives me a weird error after the python
file has been executed:

Traceback (most recent call last):
  File "C:\Python25\lib\runpy.py", line 87, in run_module
raise ImportError("No module named " + mod_name)
ImportError: No module named compile.py


The command I executed was: "python -m compile.py" (compile.py is my
python script)

Can anyone help me figure out why it's doing this?

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


C++ Modules for python: How to?

2007-07-06 Thread Robert Dailey
Hi,

I'm interested in making a C++ library of mine usable through python.
Python does a similar thing with Expat (the non-validating XML
parser). I notice that with Expat, python is importing a C++ header
file into a PY file and the interface is available to python. I've
read through the python documentation as well as done a little bit of
google research and I've not been able to find a tutorial of some sort
on how to do this. Perhaps I just don't know the right words to search
for.

If anyone could lead me in the right direction (possibly an article,
tutorial, etc) I would greatly appreciate it.

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


Re: IDEs for COM scripting: C# v. Python v. Iron Python v. JPython

2007-07-06 Thread John J. Lee
"Méta-MCI" <[EMAIL PROTECTED]> writes:
[...]
> And, all COM-servers builds with Python are dynamic-COM-server.

Not true.  Look for "comtypes" on this page:

http://python.net/crew/theller/ctypes/

[...]
> about Iron Python: is there a good IDE for it that has a typing assist?

MS calls this "typing assist" feature IntelliSense:

http://msdn.microsoft.com//msdnmag/issues/06/10/clrinsideout/default.aspx

"""
The Visual Studio SDK ships with a Visual Studio Integration sample of
IronPython. This features IronPython projects to be created, syntax
coloring, debugging, and IntelliSense® in Python files and the
IronPython console. This is another example of the benefits of being a
full-fledged .NET citizen: Visual Studio support!
"""

But things are changing very quickly with IronPython ATM.  If you want
to do anything with IronPython ATM, you'd be mad not to be subscribed
to the IronPython mailing list.  Try reading recent messages there,
and asking there if still in doubt, what the current situation is (may
*well* have changed since that article, and in particular you're very
likely to need just the right versions of everything for this to work
-- not necessarily the latest versions).


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

Re: urllib to cache 301 redirections?

2007-07-06 Thread John J. Lee
"O.R.Senthil Kumaran" <[EMAIL PROTECTED]> writes:

> Hi,
> There is an Open Tracker item against urllib2 library python.org/sf/735515
> which states that.
> urllib / urllib2 should cache the results of 301 (permanent) redirections.
> This shouldn't break anything, since it's just an internal optimisation
> from one point of view -- but it's also what the RFC (2616, section 10.3.2, 
> first para) says
> SHOULD happen. 
>
> I am trying to understand, what does it mean.
> Should the original url be avaiable to the user upon request as urllib
> automatically calls the redirect_request and provides the redirected url only?

urllib2, you mean.

Regardless of this bug, Request.get_full_url() should be (and is)
whatever URL the request instance was originally constructed with.


> I am not completely getting what "cache - redirection" implies and what should
> be done with the urllib2 module. Any pointers?

When a 301 redirect occurs after a request for URL U, via
urllib2.urlopen(U), urllib2 should remember the result of that
redirection, viz a second URL, V.  Then, when another
urllib2.urlopen(U) takes place, urllib2 should send an HTTP request
for V, not U.  urllib2 does not currently do this.  (Obviously the
cache -- that is, the dictionary or whatever that stores the mapping
from URLs U to V -- should not be maintained by function urlopen
itself.  Perhaps it should live on the redirect handler.)

302 redirections are temporary and are handled correctly in this
respect already by urllib2.


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


Re: file reading anomaly

2007-07-06 Thread Gerry
Final update: problem solved.  In the big script, the snippet was
reading depstats.txt which hadn't been closed.

Sorry for all the bother.

Gerry

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


Re: Restarting a Python Application

2007-07-06 Thread kyosohma
On Jul 3, 5:00 pm, Matimus <[EMAIL PROTECTED]> wrote:
> On Jul 3, 2:27 pm, [EMAIL PROTECTED] wrote:
>
>
>
> > Hi,
>
> > I packaged up an application I am developing into an executable. In
> > the application, it has user configurable options. I would like a way
> > to restart the application so that the new options the user chooses
> > can be applied. Firefox can restart itself. Does anyone know how to
> > accomplish this in Python?
>
> > Here is what I tried:
>
> > 
>
> > exePath = os.path.join(os.getcwd(), 'myprogram.exe')
> > subprocess.Popen(exePath)
> > sys.exit()
>
> > 
>
> > This didn't work. It closed the program, but another instance did not
> > appear.
>
> > Tips would be appreciated.
>
> > Mike
>
> You could package your program into a function or class and just
> restart that.
>
> [code]
> # global flag for restart.
> do_restart = False
>
> def main(args=None):
> # program code
> # set do_restart and return to restart
>
> if __name__ == "__main__":
> retval = main()
> while do_restart:
> retval = main()
> sys.exit(retval)
>
> [/code]

Actually I am using wxPython for a GUI front-end. Thus, it is already
in a class. I am not sure how to apply your idea to a program that is
already running in an infinite event loop.

Mike

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


Re: file reading anomaly

2007-07-06 Thread Gerry
Update:

   The PC seems to not be a factor (same problem exist on two PCs).

   The entire script does some computation and writes depstats.txt.
The code snippet below attempts to read depstats.txt and write another
file.  When the code below is run stand-alone, it succeeds.  When run
in-line as part of the program that wrote depstats.txt, there are
three possible outcomes:

it stops reading after 4096 bytes (not counting \r's); no error
messages
it stops reading after 8192 bytes (not counting \r's); no error
messages
or it succeeds.

The first two are much more likely.

Trying buffersize parameters of -1, 0, 1, 1000, 8192, 16384 in the
open call for m all had no apparent effect.

Any ideas what could possibly be wrong earlier to cause this?


m   = open("depstats.txt","r", 2)
n   = open("newds.txt",   "w")

linesout= 0
bytes   = 0

for line in m:
bytes   += len(line)
print   len(line), len(line.split()), bytes
t   = line.split()
if len(t) < 13:
print "not enough fields, only", len(t)
print t
sys.exit()
while len(t) < 43:
t.append(0)
t.append("F2")
t   = [str(x) for x in t]
print   >> n, " ".join(t)
linesout+= 1

print "linesout", linesout

m.close()
n.close()



On Jul 6, 12:48 pm, Gerry <[EMAIL PROTECTED]> wrote:
> Python 2.5, Windows XP.
>
> I have a 48-line text file written by a Windows python script,
>
> I try to read it as follows:
>
> f   = open ("depstats.txt", "r", 0)

> for index, line in enumerate(f):
> print index, len(line), len(line.split())
> f.close()
>
> On one PC, this runs without any problem.
>
> On another, it appears to succeed (no run-time errors) but does not
> read all the lines.  If I print the lines and sum of the line lengths
> so far inside the loop, the program can be seen to have only read the
> first N bytes, where N is either 4096, or 8192.
>
> Any ideas?
>
> Thanks,
>
> Gerry




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


Re: connecting to serial port + python

2007-07-06 Thread Cameron Laird
In article <[EMAIL PROTECTED]>,
Japan Shah  <[EMAIL PROTECTED]> wrote:
>Hello,
>
>I am trying to connect my Nokia 6610 using usb cable,
>I have installed usb-serial driver of it.
>
>
>I hv tested it with Hyperterminal and it works fine.
>
>but when I wrote a python script I am not able to receive the responce
>from the device.
.
.
.
It's quite likely that you do NOT want to regard this as
a "serial port" device as commonly understood.  It's even 
more likely that you're going to be very happy once you
start reading about gammu http://www.gammu.org/ >,
an open-source project (or collection of open-source pro-
jects) focussed on mobile telephony handset devices,
especially those from Nokia.

Gammu works particularly well with the 6610 and closely-
related handsets, in my experience; I've been using it so
for a couple of years.

What's your preferred (desktop) operating system?  Which
cable did you buy?  Is it compatible with one made at the
Nokia factories?  Not all USB cables are alike ...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Mixing Python and C threads

2007-07-06 Thread Stéphane Larouche
Aahz  pythoncraft.com> writes:
> In article  python.org>,
> =?utf-8?b?U3TDqXBoYW5l?= Larouche   polymtl.ca> wrote:
> >
> >If I call the methods in the C++ modules from the Python main thread, I
> >don't have any problem. However, they are usually called from another
> >Python thread (using the threading module) to keep the GUI responsive
> >and, then, Python crashes.
> 
> The question is whether your C++ code is designed to be called from
> multiple threads.  That is, if you call your C++ code from a *single*
> non-main thread, does it work?

Thank you for the quick answer.

It does work if I call it from a single non-main thread. But everything must be
called from that thread, including the import of the module.

I still do not understand what is the problem. The C++ code is not thread safe,
but I call it from 1 Python thread at a time. Anyway, I have always called it
from multiple Python threads without any problem. Having put a few printf in the
module, I can say that it crashes exactly when it tries to create C threads.

Am I missing something?

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


Re: Expandable 2D Dictionaries?

2007-07-06 Thread Marc 'BlackJack' Rintsch
On Fri, 06 Jul 2007 16:22:35 +, Robert Dailey wrote:

> On Jul 6, 11:09 am, Jean-Paul Calderone <[EMAIL PROTECTED]> wrote:
>> This gets much easier if you change your structure around a bit:
>>
>> d = {}
>> d["cat", "paw"] = "some string"
>>
>> Jean-Paul
> 
> I like this format. I'm not familiar with it however. In my research
> of python I was not aware it was legal to have comma operators inside
> of the brackets. What does this mean? Is there some terminology that I
> can search for to research this concept? Thanks.

It's mapping the tuple ('cat', 'paw') to 'some string'.  Commas make
tuples.  The parenthesis are just necessary for the literal empty tuple
and if the syntax would be ambiguous otherwise.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How would I write this C code in Python?

2007-07-06 Thread Marc 'BlackJack' Rintsch
On Fri, 06 Jul 2007 17:31:50 +, DeveloperX wrote:

> I am trying to figure out how to rewrite the following chunk of code
> in Python:
> 
> C source
> [code]
> typedef struct PF
> {
>   int flags;
>   long user;
>   char*filename;
>   unsigned char buffer[MAXBUFFERSIZE];
> } PF;
> 
> typedef BLOCK
> {
>   PF * packdata;
> } BLOCK;
> 
> BLOCK* blocks;
> [/code]
> 
> My first idea was to create a class for PF and a class for BLOCK, but
> I got lost somewhere along the lines. :\
> 
> Python Attempt: Please note that since I can't type TABs online
> easily, I am using the @ character to represent TABs in the following
> Python code.
> [code]
> class PF:
> @def __init__(self):
> @@self.flags, self.user = 0, 0
> @@self.filename = ''
> @@self.buffer = []
> 
> class BLOCK:
> @def __init__(self):
> @@self.packdata = []
> 
> blocks = []
> [/code]
> 
> Any Python Gurus out there that can help me?

At a first glance it looks okay but unless we know what you are going to
do with these data structures it's hard to tell if it is really the best
"translation".

`PF.buffer` might be better a string or an `array.array`.  And is `BLOCK`
really just a structure with *one* member?  Looks a bit odd IMHO.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


How would I write this C code in Python?

2007-07-06 Thread DeveloperX
I am trying to figure out how to rewrite the following chunk of code
in Python:

C source
[code]
typedef struct PF
{
  int flags;
  long user;
  char*filename;
  unsigned char buffer[MAXBUFFERSIZE];
} PF;

typedef BLOCK
{
  PF * packdata;
} BLOCK;

BLOCK* blocks;
[/code]

My first idea was to create a class for PF and a class for BLOCK, but
I got lost somewhere along the lines. :\

Python Attempt: Please note that since I can't type TABs online
easily, I am using the @ character to represent TABs in the following
Python code.
[code]
class PF:
@def __init__(self):
@@self.flags, self.user = 0, 0
@@self.filename = ''
@@self.buffer = []

class BLOCK:
@def __init__(self):
@@self.packdata = []

blocks = []
[/code]

Any Python Gurus out there that can help me?

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


Re: Tiny/small/minimalist Python?

2007-07-06 Thread Cameron Laird
In article <[EMAIL PROTECTED]>,
Irmen de Jong  <[EMAIL PROTECTED]> wrote:
>Paul Rubin wrote:
>> rtk <[EMAIL PROTECTED]> writes:
>>> FYI.. I wanted a simple version of Python to run on an ancient DEC
>>> Alpha box.  I got VMS Python 2.5 up and running but it is too slow to
>>> use.  It takes *minutes* to get the interpreter prompt after typing
>>> 'python'! 
>> 
>> Something is wrong.  Maybe it's trying to DNS itself and timing out,
>> or something like that.
>
>Something is definately wrong.
>
>Back in the days my port of Python to the Commodore Amiga machine ran
>quite comfortably on a 50 mhz CPU with 4 Mb of RAM. (ok ok it was
>Python 1.5.2, that has to be said).
>Python started in about 5 seconds on that Amiga if I remember
>correctly. I'm quite sure your 'ancient' DEC Alpha box is way more
>powerful than my Amiga back then.
>
>--Irmen

Me, too.

I'm all for Lua--I began promoting it over ten years ago.  However,
I was also working on Alphas at about that time, as well as VMS, and
of course with Python.  While I don't recall that I ever had occasion
to test Python under VMS for Alpha much, I've used every other 
combination quite a bit.  Something's fishy about this report of a
minute-long launch-time.
-- 
http://mail.python.org/mailman/listinfo/python-list


file reading anomaly

2007-07-06 Thread Gerry
Python 2.5, Windows XP.

I have a 48-line text file written by a Windows python script,

I try to read it as follows:



f   = open ("depstats.txt", "r", 0)
for index, line in enumerate(f):
print index, len(line), len(line.split())
f.close()

On one PC, this runs without any problem.

On another, it appears to succeed (no run-time errors) but does not
read all the lines.  If I print the lines and sum of the line lengths
so far inside the loop, the program can be seen to have only read the
first N bytes, where N is either 4096, or 8192.

Any ideas?

Thanks,

Gerry

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


Re: Expandable 2D Dictionaries?

2007-07-06 Thread Robert Dailey
Thank you all very much for your valuable replies. I wasn't aware that
tuples were valid keys in a dictionary object. This is actually the
solution I was looking for. Thank you all once again.

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


Re: what is wrong with that r"\"

2007-07-06 Thread i3dmaster
Then you can use other chars as the delimiter, [EMAIL PROTECTED]@b@ or r!a!b!,  
etc... The import thing is so long as the interpreter doesn't get  
confused on the data and the delimiter.  sed also allows for  
arbitrary delimiters too as long as you maintain the integrity of the  
original meaning...

-Jim

On Jul 6, 2007, at 5:20 AM, Tim Roberts wrote:

> Matthieu TC <[EMAIL PROTECTED]> wrote:
>
>> May I suggest giving the possibility to use any delimiter for a  
>> raw string?  just like in Vi or ruby.
>>
>> Vi:
>> %s_a_b_g  is valid and so is  %s/a/b/g
>>
>> Ruby:
>> %q{dj'\ks'a\'"}   or %q-dj'\ks'a\'"-
>>
>> So as long as your regex does not use all the valid characters,  
>> readability is maintained.
>
> But what about my program that wants to use r_a_b_ as an identifier?
> -- 
> Tim Roberts, [EMAIL PROTECTED]
> Providenza & Boekelheide, Inc.
> -- 
> http://mail.python.org/mailman/listinfo/python-list

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


Re: Expandable 2D Dictionaries?

2007-07-06 Thread Tommy Nordgren

On 6 jul 2007, at 17.43, Robert Dailey wrote:

> Hi,
>
> I am interested in creating an expandable (dynamic) 2D dictionary. For
> example:
>
> myvar["cat"]["paw"] = "Some String"
>
> The above example assumes "myvar" is declared. In order for this to
> work, I have to know ahead of time the contents of the dictionary. For
> the above to work, my declaration must look like:
>
> myvar = {"cat": {"paw":""} }
>
> I would like to not have to declare my dictionary like this, as it
> does not allow it to be expandable. I'm very new to Python (I'm a
> professional C++ programmer. Any comparisons to C++ would help me
> understand concepts).
>
> Is there a way that when I index into my dictionary using an "unknown"
> index (string), that python will dynamically add that key/value pair?
>
> Thanks.
>
The best way to do this, is probably to implement your own class. As  
far as I
know, Python supports operator overloads, although the syntax is  
different than C++.
--
What is a woman that you forsake her, and the hearth fire and the  
home acre,
to go with the old grey Widow Maker.  --Kipling, harp song of the  
Dane women
Tommy Nordgren
[EMAIL PROTECTED]



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


Re: Expandable 2D Dictionaries?

2007-07-06 Thread Robert Dailey
On Jul 6, 11:09 am, Jean-Paul Calderone <[EMAIL PROTECTED]> wrote:
> On Fri, 06 Jul 2007 15:43:55 -, Robert Dailey <[EMAIL PROTECTED]> wrote:
> >Hi,
>
> >I am interested in creating an expandable (dynamic) 2D dictionary. For
> >example:
>
> >myvar["cat"]["paw"] = "Some String"
>
> >The above example assumes "myvar" is declared. In order for this to
> >work, I have to know ahead of time the contents of the dictionary. For
> >the above to work, my declaration must look like:
>
> >myvar = {"cat": {"paw":""} }
>
> >I would like to not have to declare my dictionary like this, as it
> >does not allow it to be expandable. I'm very new to Python (I'm a
> >professional C++ programmer. Any comparisons to C++ would help me
> >understand concepts).
>
> >Is there a way that when I index into my dictionary using an "unknown"
> >index (string), that python will dynamically add that key/value pair?
>
> This gets much easier if you change your structure around a bit:
>
> d = {}
> d["cat", "paw"] = "some string"
>
> Jean-Paul

I like this format. I'm not familiar with it however. In my research
of python I was not aware it was legal to have comma operators inside
of the brackets. What does this mean? Is there some terminology that I
can search for to research this concept? Thanks.

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


Re: Expandable 2D Dictionaries?

2007-07-06 Thread Matimus
I'm not sure I completely understand what you want, but if you are
using Python2.5 defaultdict might be useful. Below is some example
code using defaultdict.


[code]
from collections import defaultdict

myvar = defaultdict(dict)

myvar["cat"]["paw"] = "SomeString"
myvar["dog"]["tail"] = "wags"
myvar["cat"]["tongue"] = "sand-paper"
myvar["mouse"]["likes"] = "cheese"
[/code]

The documentation can do a better job of explaining how this works
than I can: http://docs.python.org/lib/defaultdict-objects.html

-Matt

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


Re: Expandable 2D Dictionaries?

2007-07-06 Thread Jean-Paul Calderone
On Fri, 06 Jul 2007 15:43:55 -, Robert Dailey <[EMAIL PROTECTED]> wrote:
>Hi,
>
>I am interested in creating an expandable (dynamic) 2D dictionary. For
>example:
>
>myvar["cat"]["paw"] = "Some String"
>
>The above example assumes "myvar" is declared. In order for this to
>work, I have to know ahead of time the contents of the dictionary. For
>the above to work, my declaration must look like:
>
>myvar = {"cat": {"paw":""} }
>
>I would like to not have to declare my dictionary like this, as it
>does not allow it to be expandable. I'm very new to Python (I'm a
>professional C++ programmer. Any comparisons to C++ would help me
>understand concepts).
>
>Is there a way that when I index into my dictionary using an "unknown"
>index (string), that python will dynamically add that key/value pair?

This gets much easier if you change your structure around a bit:

d = {}
d["cat", "paw"] = "some string"

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


Re: Expandable 2D Dictionaries?

2007-07-06 Thread Carsten Haese
On Fri, 2007-07-06 at 15:43 +, Robert Dailey wrote:
> Hi,
> 
> I am interested in creating an expandable (dynamic) 2D dictionary. For
> example:
> 
> myvar["cat"]["paw"] = "Some String"
> 
> The above example assumes "myvar" is declared. In order for this to
> work, I have to know ahead of time the contents of the dictionary. For
> the above to work, my declaration must look like:
> 
> myvar = {"cat": {"paw":""} }
> 
> I would like to not have to declare my dictionary like this, as it
> does not allow it to be expandable. I'm very new to Python (I'm a
> professional C++ programmer. Any comparisons to C++ would help me
> understand concepts).
> 
> Is there a way that when I index into my dictionary using an "unknown"
> index (string), that python will dynamically add that key/value pair?

Sounds like a job for Python2.5's defaultdict:

from collections import defaultdict
class magicdict(defaultdict):
   def __init__(self):
  self.default_factory = magicdict

myvar = magicdict()
myvar["cat"]["paw"] = "Some String"

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


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


Re: Auto-parallelizing with decorators?

2007-07-06 Thread Kirk Strauser
Stefan Behnel wrote:

> Wouldn't that require parallelism in the interpreter first? Mind the
> GIL...

That may be.  I'd bet though that I could whip up a native Python workalike
using os.fork() that would work around GIL, at least on Unix (just because
I don't know if Windows has os.fork(), having never looked for it).

I know something like this wouldn't be the easiest thing to implement, but
honestly, having such beautiful constructs as map() and list comprehensions
available is just begging for an application like this.
-- 
Kirk Strauser
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Expandable 2D Dictionaries?

2007-07-06 Thread Robert Dailey
On Jul 6, 10:54 am, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
> Robert Dailey wrote:
> > Hi,
>
> > I am interested in creating an expandable (dynamic) 2D dictionary. For
> > example:
>
> > myvar["cat"]["paw"] = "Some String"
>
> > The above example assumes "myvar" is declared. In order for this to
> > work, I have to know ahead of time the contents of the dictionary. For
> > the above to work, my declaration must look like:
>
> > myvar = {"cat": {"paw":""} }
>
> > I would like to not have to declare my dictionary like this, as it
> > does not allow it to be expandable. I'm very new to Python (I'm a
> > professional C++ programmer. Any comparisons to C++ would help me
> > understand concepts).
>
> > Is there a way that when I index into my dictionary using an "unknown"
> > index (string), that python will dynamically add that key/value pair?
>
> Not really, unless you know that the first level of values are _always_
> dicts.
>
> What you can do is to use
>
> myvar.setdefault('cat', {})['paw'] = "Some String"
>
> Diez

Could you emphasize what you mean by "unless you know that the first
level of values are _always_ dicts."?

Could I create a class wrapper that automates this? I could have an
insert() method of some sort. However I would have to research if it's
possible to overload operators in python.

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


Re: Expandable 2D Dictionaries?

2007-07-06 Thread Diez B. Roggisch
Robert Dailey wrote:

> Hi,
> 
> I am interested in creating an expandable (dynamic) 2D dictionary. For
> example:
> 
> myvar["cat"]["paw"] = "Some String"
> 
> The above example assumes "myvar" is declared. In order for this to
> work, I have to know ahead of time the contents of the dictionary. For
> the above to work, my declaration must look like:
> 
> myvar = {"cat": {"paw":""} }
> 
> I would like to not have to declare my dictionary like this, as it
> does not allow it to be expandable. I'm very new to Python (I'm a
> professional C++ programmer. Any comparisons to C++ would help me
> understand concepts).
> 
> Is there a way that when I index into my dictionary using an "unknown"
> index (string), that python will dynamically add that key/value pair?

Not really, unless you know that the first level of values are _always_
dicts.

What you can do is to use

myvar.setdefault('cat', {})['paw'] = "Some String"

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


Expandable 2D Dictionaries?

2007-07-06 Thread Robert Dailey
Hi,

I am interested in creating an expandable (dynamic) 2D dictionary. For
example:

myvar["cat"]["paw"] = "Some String"

The above example assumes "myvar" is declared. In order for this to
work, I have to know ahead of time the contents of the dictionary. For
the above to work, my declaration must look like:

myvar = {"cat": {"paw":""} }

I would like to not have to declare my dictionary like this, as it
does not allow it to be expandable. I'm very new to Python (I'm a
professional C++ programmer. Any comparisons to C++ would help me
understand concepts).

Is there a way that when I index into my dictionary using an "unknown"
index (string), that python will dynamically add that key/value pair?

Thanks.

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


Re: Auto-parallelizing with decorators?

2007-07-06 Thread Stefan Behnel
Kirk Strauser wrote:
> Suppose that Python had a new decorator, say "@parallelizable".  Functions
> so decorated would be eligible for multi-processed or multi-threaded
> execution by such native constructs as list comprehensions, or the map()
> function.

Wouldn't that require parallelism in the interpreter first? Mind the GIL...

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


Auto-parallelizing with decorators?

2007-07-06 Thread Kirk Strauser
I was thinking about how a lot of Lisp proponents claim that Lisp is
inherently parallelizable because its functions don't have (or are not
supposed to have) side effects, and therefore the compiler can easily tell
which calls may be run in parallel instead of strictly serially.  I'm not a
Lisp expert so I can't say whether that's true or not, but it seems like an
interesting idea for Python.

Suppose that Python had a new decorator, say "@parallelizable".  Functions
so decorated would be eligible for multi-processed or multi-threaded
execution by such native constructs as list comprehensions, or the map()
function.  Their logic could be something along the lines of:

1) Is every function in the "function expression" of map() or a list
comprehension decorated with @parallelizable?  If not, use the normal
implementation.
2) Spawn an appropriate number of child threads and queue values to be
processed.
3) As results return, either store them in the result list (for map()), or
insert them into their place in the output queue to be consumed by users of
a list comprehension.

In #2, "appropriate" could default to something like 2 times the number of
CPUs detected in the system (which could be found the first time it was
needed so that programs that don't use this functionality don't pay for
finding that information).  I could imagine that it'd be useful to pass
hints to the decorator to more explicitly size the thread pool, such as:

@parallelizable(number=100)
def lightweightfunction:
"""Launch as many parallel copies as you can"""

@parallelizable(perproc=1)
def heavierfunction:
"""Only run one copy per CPU"""

@parallelizable(number=2)
def bigslowfunction:
"""This benefits from parallel execution, but don't kill the system"""

Would something like this have merit?  I like the idea because it's
completely optional; if you don't use it, you never have to deal with the
side effects.  However, if you take care to make your functions loosely
coupled and not dependent on execution order, you could get a nice speedup
every single time you give Python permission to schedule your repeated
function calls.
-- 
Kirk Strauser
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: VB frontend to Python COM backend

2007-07-06 Thread nik
Thank you for the lead. That is exactly what I was wishing for.

Thank you,
Nik

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


Re: Mixing Python and C threads

2007-07-06 Thread Aahz
In article <[EMAIL PROTECTED]>,
=?utf-8?b?U3TDqXBoYW5l?= Larouche  <[EMAIL PROTECTED]> wrote:
>
>If I call the methods in the C++ modules from the Python main thread, I
>don't have any problem. However, they are usually called from another
>Python thread (using the threading module) to keep the GUI responsive
>and, then, Python crashes.

The question is whether your C++ code is designed to be called from
multiple threads.  That is, if you call your C++ code from a *single*
non-main thread, does it work?
-- 
Aahz ([EMAIL PROTECTED])   <*> http://www.pythoncraft.com/

I support the RKAB
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Re-raising exceptions with modified message

2007-07-06 Thread Gerard Flanagan
On Jul 6, 12:18 am, Christoph Zwerschke <[EMAIL PROTECTED]> wrote:
> Sorry for the soliloquy, but what I am really using is the following so
> that the re-raised excpetion has the same type:
>
> def PoliteException(e):
>  class PoliteException(e.__class__):
>  def __init__(self, e):
>  self._e = e
>  def __getattr__(self, name):
>  return getattr(self._e, name)
>  def __str__(self):
>  if isinstance(self._e, PoliteException):
>  return str(self._e)
>  else:
>  return '\n%s: %s, I am sorry!' % (
>  self._e.__class__.__name__, str(self._e))
>  return PoliteException(e)
>
> try:
>  unicode('\xe4')
> except Exception, e:
>  raise PoliteException(e)

Would a decorator work here?


class PoliteException(Exception):
def __init__(self, e):
self._e = e
def __getattr__(self, name):
return getattr(self._e, name)
def __str__(self):
return '\n%s: %s, I am sorry!' % (
self._e.__class__.__name__, str(self._e))

def politefail(fn):
def wrapper(*args, **kwargs):
try:
return fn(*args, **kwargs)
except Exception, e:
raise PoliteException(e)
return wrapper

@politefail
def funktion():
 unicode('\xe4')

funktion()

@politefail
def raise_exception(err, *args):
raise err(*args)


def funktion():
if 1 != 2:
raise_exception(ArithmeticError, '1 is not equal to 2.')

print
funktion()

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


Mixing Python and C threads

2007-07-06 Thread Stéphane Larouche
I am currently developing a software called OpenFilters (available at
www.polymtl.ca/larfis). Most of the software is written in Python, but the
classes that do the hard work are written in C++ modules. Since, nowadays, most
new computers have multiple cores and that I want to speed up the software, I am
currently trying to add some multithreading to the C++ modules using openmp.

If I call the methods in the C++ modules from the Python main thread, I don't
have any problem. However, they are usually called from another Python thread
(using the threading module) to keep the GUI responsive and, then, Python
crashes.

The C++ multithreaded part does not call any Python function. It crashes whether
it is surrounded by Py_BEGIN_ALLOW_THREADS/Py_END_ALLOW_THREADS or not. I am
using Python 2.5 on Windows XP. The modules are compiled with gcc 4.2 (MinGW
unofficial release available at
http://www.esnips.com/doc/9dba8ac7-70c7-4f98-a0fa-8ea315267073/gcc-4.2.0mingw-
release-patched-SSE).

Has anybody had a similar problem? Do you know how to solve it?

Thank you for your help,

Stéphane Larouche


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

Re: VB frontend to Python COM backend

2007-07-06 Thread Harry George
nik <[EMAIL PROTECTED]> writes:

> I have a VB6 application that I would like to attach to a python
> communications application.
>
> I have come across several discussions on using VB with a Python COM
> back-end, but no starting point. I haven't had anymore luck with
> google at finding out what this method is called and where to find
> more information or examples on it. I would really appreciate it if
> someone could point me in the right direction for using python objects
> from VB.
>
> Thank you,
> Nik
>

Search for "python win32 book".   You want "Python Programming on Win32"
 By Mark J.. Hammond, Andy Robinson.  It covers exactly this case.

-- 
Harry George
PLM Engineering Architecture
-- 
http://mail.python.org/mailman/listinfo/python-list


Maria Sharapova Angelina joli

2007-07-06 Thread A KOURNIKOVA
Maria Sharapova   Angelina joli
search   engines  ,
cams  ,  adult , photogallery , dating , travel , autos, cars , real estate , 
ads , spor , shopping , domain names

www.alphasearch.gr-- 
http://mail.python.org/mailman/listinfo/python-list

Re: VB frontend to Python COM backend

2007-07-06 Thread Giles Brown
On 6 Jul, 06:58, nik <[EMAIL PROTECTED]> wrote:
> I have a VB6 application that I would like to attach to a python
> communications application.
>
> I have come across several discussions on using VB with a Python COM
> back-end, but no starting point. I haven't had anymore luck with
> google at finding out what this method is called and where to find
> more information or examples on it. I would really appreciate it if
> someone could point me in the right direction for using python objects
> from VB.
>
> Thank you,
> Nik

Try this for starters...

http://www.oreilly.com/catalog/pythonwin32/chapter/ch12.html

Giles


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


Re: Where is the syntax for the dict() constructor ?!

2007-07-06 Thread Neil Cerutti
On 2007-07-06, Neil Cerutti <[EMAIL PROTECTED]> wrote:
> On 2007-07-05, John Machin <[EMAIL PROTECTED]> wrote:
>> On Jul 6, 5:31 am, Neil Cerutti <[EMAIL PROTECTED]> wrote:
>>>
>>> Mostly you can use the default 'excel' dialect and be quite
>>> happy, since Excel is the main reason anybody still cares about
>>> this unecessarily hard to parse (it requires more than one
>>> character of lookahead for no reason except bad design) data
>>> format.
>>
>> One cares about this format because people create data files of
>> millions of rows (far exceeding the capacity of Excel (pre-2007)) in
>> many imaginative xSV dialects, some of which are not handled by the
>> Python csv module.
>>
>> I don't know what you mean by "requires more than one
>> character of lookahead"
>
> It's because of the silly way that quotes are quoted in quoted
> fields.
>
> "a,""b",c
>
> But I'm not a parsing expert by any means.

Moreover, the most common version of csv uses both escape and
shift codes, when only escape codes were really needed, and then
compounds this stupidity by using the same character for escaping
and shifting.

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


Re: Python's "only one way to do it" philosophy isn't good?

2007-07-06 Thread Chris Mellon
On 7/5/07, Douglas Alan <[EMAIL PROTECTED]> wrote:
> "Chris Mellon" <[EMAIL PROTECTED]> writes:
>
> >> Some people here have been arguing that all code should use "with" to
> >> ensure that the files are closed.  But this still wouldn't solve the
> >> problem of the large data structures being left around for an
> >> arbitrary amount of time.
>
> > I don't think anyone has suggested that. Let me be clear about *my*
> > position: When you need to ensure that a file has been closed by a
> > certain time, you need to be explicit about it. When you don't care,
> > just that it will be closed "soonish" then relying on normal object
> > lifetime calls is sufficient. This is true regardless of whether
> > object lifetimes are handled via refcount or via "true" garbage
> > collection.
>
> But it's *not* true at all when relying only on a "true GC"!  Your
> program could easily run out of file descriptors if you only have a
> real garbage collector and code this way (and are opening lots of
> files).  This is why destructors are useless in Java -- you can't rely
> on them *ever* being called.  In Python, however, destructors are
> quite useful due to the refcounter.
>

Sure, but thats part of the general refcounting vs GC argument -
refcounting gives (a certain level of) timeliness in resource
collection, GC often only runs under memory pressure. If you're saying
that we should keep refcounting because it provides better handling of
non-memory limited resources like file handles, I probably wouldn't
argue. But saying we should keep refcounting because people like to
and should write code that relies on implicit scope level object
destruction I very strongly argue against.

> > Relying on the specific semantics of refcounting to give
> > certain lifetimes is a logic error.
> >
> > For example:
> >
> > f = some_file() #maybe it's the file store for a database implementation
> > f.write('a bunch of stuff')
> > del f
> > #insert code that assumes f is closed.
>
> That's not a logic error if you are coding in CPython, though I agree
> that in this particular case the explicit use of "with" would be
> preferable due to its clarity.
>

I stand by my statement. I feel that writing code in this manner is
like writing C code that assumes uninitialized pointers are 0 -
regardless of whether it works, it's erroneous and bad practice at
best, and actively harmful at worst.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Where is the syntax for the dict() constructor ?!

2007-07-06 Thread Neil Cerutti
On 2007-07-05, John Machin <[EMAIL PROTECTED]> wrote:
> On Jul 6, 5:31 am, Neil Cerutti <[EMAIL PROTECTED]> wrote:
>>
>> Mostly you can use the default 'excel' dialect and be quite
>> happy, since Excel is the main reason anybody still cares about
>> this unecessarily hard to parse (it requires more than one
>> character of lookahead for no reason except bad design) data
>> format.
>
> One cares about this format because people create data files of
> millions of rows (far exceeding the capacity of Excel (pre-2007)) in
> many imaginative xSV dialects, some of which are not handled by the
> Python csv module.
>
> I don't know what you mean by "requires more than one
> character of lookahead"

It's because of the silly way that quotes are quoted in quoted
fields.

"a,""b",c

But I'm not a parsing expert by any means.

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


Re: The best platform and editor for Python

2007-07-06 Thread Neil Cerutti
On 2007-07-06, Alex Martelli <[EMAIL PROTECTED]> wrote:
> Kay Schluehr <[EMAIL PROTECTED]> wrote:
>> half of the community is happy with Emacs and the other half
>> wants to program in a VS-like environment, neither consensus
>> nor progress has
>
> Calling all vi/vim users (and we'll heartily appreciate the
> support of TextMate fans, BBEdit ones, etc, etc) -- we're at
> risk being defined out of existence, since we're neither happy
> with Emacs nor wanting anything like Visual Studio, and yet Kay
> claims that people in either category make up the whole (one
> half plus the other half) and so that WE DON'T EXIST!!!  A
> ridiculous claim to be sure, but we'd better let Herr Schluehr
> know that in no uncertain terms...
  
Wow! That explains why I had so much trouble eating me Wheaties
this morning.

Can I still post messages if I don't exist?

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


Re: list.append not working?

2007-07-06 Thread Rex Turnbull
Wildemar Wildenburger wrote:
> Abhishek Jain wrote:
>> with every iteration your previous values are overwritten ('md' is a 
>> dictionary) so thats why your are observing this ouput..
>>
>> check  if the following patch solves your problem
>>
>> for entity in temp:
>> md['module']= entity.addr.get('module')
>> md['id']=entity.addr.get('id')
>> md['type']=entity.addr.get('type')
>> #print md
>> mbusentities.append(md)
>> md = {}
>> #print mbusentities
>>
>>
>> Regards
>> Abhi
> This will work, but may I suggest putting the md = {} line at the 
> *beginning* of the loop?
> I find seeing it at the end HIGHLY confusing. Declaring it in the 
> beginning makes sense, because you declare/initialize, then use it. But 
> using and *then* initializing it for the next iteration is kind of 
> quirky, because it breaks the logical encapsulation I would like to see 
> in *one* loop iteration.
> 
> /W

Hear, hear! to the declaration at the beginning.  Just went through a 
long bug search due to a similar behaviour.  Terrible.  I try to view 
the body of a loop as if it were a separate function/method.  If it 
makes sense from that point of view, it will make sense in 3 months. I 
mean, why would you want ot initialize something when you're done with it?

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


Re: Learn Oracle Database Administration in 10 Minutes

2007-07-06 Thread Stefan Behnel
[EMAIL PROTECTED] wrote:
> Learn Oracle Database Administration in 10 Minutes. No kidding. Check
> it yourself,
> 
> http://www.takveen.com

It already takes longer than 10 minutes to install, so I have the time to
learn more than I find in that book before I even get to using it.

Besides, this is completely off-topic spam.

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


Learn Oracle Database Administration in 10 Minutes

2007-07-06 Thread [EMAIL PROTECTED]
Learn Oracle Database Administration in 10 Minutes. No kidding. Check
it yourself,

http://www.takveen.com


Only good analogy makes complex concepts simple!

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


Re: Re-raising exceptions with modified message

2007-07-06 Thread Neil Cerutti
On 2007-07-06, Alex Popescu <[EMAIL PROTECTED]> wrote:
> On Jul 6, 4:20 am, Christoph Zwerschke <[EMAIL PROTECTED]> wrote:
>> Alex Popescu wrote:
>> > Probably the simplest solution would be to create a new exception and
>> > wrapping the old one and the additional info. Unfortunately, this
>> > may have a huge impact on 3rd party code that was catching the
>> > original exception. So, I think you should create an utility
>> > factory-like function that is either creating a new exception
>> > instance as the one caught and with the additional information,
>>
>> Right, I have gone with that (see the example with the PoliteException
>> class somewhere below).
>>
>> > or an utility that knows how to modify the caught exception according
>> > to its type.
>>
>> I guess you mean something like this (simplified):
>>
>> except Exception, e:
>>  if getattr(e, 'reason'):
>>  e.reason += "sorry"
>>  else:
>>  e.message += "sorry"
>>
>> The problem is that these attribute names are not standardized and can
>> change between Python versions. Not even "args" is sure, and if a class
>> has "message" it does not mean that it is displayed. Therefore I think
>> the first approach is better.
>>
>> > In the first case you will need somehow to tell to the new instance
>> > exception the real stack trace, because by simply raising
>> > a new one the original stack trace may get lost.
>>
>> Yes, but thats a different problem that is easy to solve.
>
> Yeah maybe for a python guy, but I am a newbie. I would really
> appreciate if you can show in this thread how this can be done
> in Python.

Chech out the docs for sys.exc_info(), and for the raise
statement.

When handling an exception, you can rethrow a different
exception, but with the same traceback, by using the three-arg
version of raise.

See one of my earlier posts in this thread for a working example
(although it didn't solve Chris's problem).

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


Re: deliberate versus os socket timeout

2007-07-06 Thread Robin Becker
John J. Lee wrote:
> 
> What do you mean "is in fact true"?  Is what true?  That the reason is
> always formatted in those ways when those particular errors occur?
> Not sure there's any reason to rely on that: I'd expect .reason to be
> an exception object, so (reading the docs for module socket)
> e.reason.args[0] should be the error code if one is available, in this
> case errno.ETIMEDOUT (i.e. WSAETIMEDOUT, which means the timeout
> occurred before a connection was established).  Sometimes
> e.reason.args will be length-1, and e.reason.args[0] will be a string,
> again according to the docs for module socket.
> 

well I suspect there's a whole twisty maze of stuff to do to reliably detect 
whether a timeout was deliberate or not so I'll pass on that.

.
> 
>> More importantly is there anything I can do to avoid these wrong os
>> inspired timeouts? I'm just using urllib2 to read from a remote site
> [...]
> 
> Please define "wrong" ;-)
> 

well if I ask to be timed out after 120 seconds I don't expect a timeout error 
after 20 so I would define the 20 second case to be somehow wrong or unexpected.

> Googling suggests Windows doesn't let you configure its connect
> timeout, except through a registry setting:
> 
> http://www.tech-archive.net/Archive/VC/microsoft.public.vc.language/2005-09/msg00918.html

the implication of windows providing its own timeout seems to make the socket 
defaulttimeout irrelevant since I can have no per socket control over it. I 
think this came up before and I just forgot about it mumble mumble
-- 
Robin Becker

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


Re: SMTP server w/o using Twisted framework

2007-07-06 Thread Steve Holden
Gerhard Häring wrote:
> _spitFIRE wrote:
>> [looking up DNS MX records]
>> Thanks for the pointer. However, as I said currently, I can't use
>> anything other than the standard libraries.
> 
> Sure you can. You just need to get rid of the "only standard library" 
> requirement rule.
> 
> That works best by showing the alternatives to whoever set that requirement:
> 
> - use pyDNS
> - use an existing (probably non-Python) SMTP daemon
> - reimplement some parts of pyDNS yourself and develop a basic (crappy) 
> SMTP daemon yourself
> 
> For doing the latter, you should budget at least one week.
> 
> FWIW another reason why SMTP servers should retry on temporary failure 
> is that increasing use of Greylisting (*), which was precisely designed 
> to filter out mail from "crappy" servers, like botnets, and - well - 
> cheap custom written ones ;-)
> 
I'd actually use dnspython in preference to pyDNS, it's very easy to 
use. I have some MX-server lookup code somewhere in the vault, if you 
can use an external library.

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden
--- Asciimercial --
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
--- Thank You for Reading -
-- 
http://mail.python.org/mailman/listinfo/python-list


Auto-response for your message to the "marketing-python" mailing list

2007-07-06 Thread marketing-python-bounces
This mailing list has been retired.  Please use the new Python
Advocacy mailing list instead:

http://mail.python.org/mailman/listinfo/advocacy

Thanks!

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


Re: Where is the syntax for the dict() constructor ?!

2007-07-06 Thread Marc 'BlackJack' Rintsch
On Fri, 06 Jul 2007 08:34:55 +0200, Hendrik van Rooyen wrote:

> "John Machin"  wrote:
> 
>> 
>> I don't know what you mean by "requires more than one
>> character of lookahead" -- any non-Mickey-Mouse implementation of a
>> csv reader will use a finite state machine with about half-a-dozen
>> states, and data structures no more complicated than (1) completed
>> rows received so far (2) completed fields in current row (3) bytes in
>> current field. When a new input byte arrives, what to do can be
>> determined based on only that byte and the current state; no look-
>> ahead into the input stream is required, nor is any look-back into
>> those data structures.
>> 
> 
> True.
> 
> You can even do it more simply - by writing a GetField() that
> scans for either the delimiter or end of line or end of file, and 
> returns the "field" found, along with the delimiter that caused 
> it to exit, and then writing a GetRecord() that repetitively calls
> the GetField and assembles the row record until the delimiter 
> returned is either the end of line or the end of file, remembering 
> that the returned field may be empty, and handling the cases based 
> on the delimiter returned when it is.
> 
> This also makes all the decisions based on the current character
> read, no lookahead as far as I can see.
> 
> Also no state variables, no switch statements...
> 
> Is this the method that you would call "Mickey Mouse"?

Maybe, because you've left out all handling of quoting and escape
characters here.  Consider this:

erik,viking,"ham, spam and eggs","He said ""Ni!""","line one
line two"

That's 5 elements:

1: eric
2: viking
3: ham, spam and eggs
4: He said "Ni!"
5: line one
   line two

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Re-raising exceptions with modified message

2007-07-06 Thread Alex Popescu
On Jul 6, 4:20 am, Christoph Zwerschke <[EMAIL PROTECTED]> wrote:
> Alex Popescu wrote:
> > Probably the simplest solution would be to create a new exception and
> > wrapping the old one and the additional info. Unfortunately, this
> > may have a huge impact on 3rd party code that was catching the
> > original exception. So, I think you should create an utility
> > factory-like function that is either creating a new exception
> > instance as the one caught and with the additional information,
>
> Right, I have gone with that (see the example with the PoliteException
> class somewhere below).
>
> > or an utility that knows how to modify the caught exception according
> > to its type.
>
> I guess you mean something like this (simplified):
>
> except Exception, e:
>  if getattr(e, 'reason'):
>  e.reason += "sorry"
>  else:
>  e.message += "sorry"
>
> The problem is that these attribute names are not standardized and can
> change between Python versions. Not even "args" is sure, and if a class
> has "message" it does not mean that it is displayed. Therefore I think
> the first approach is better.
>
> > In the first case you will need somehow to tell to the new instance
> > exception the real stack trace, because by simply raising
> > a new one the original stack trace may get lost.
>
> Yes, but thats a different problem that is easy to solve.
>

Yeah maybe for a python guy, but I am a newbie. I would really
appreciate if you can show in this thread how this can be done in
Python.

tia,

./alex
--
.w( the_mindstorm )p.

PS: sorry for reposting, but it looks like my previous message hasn't
gone through :-(.



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


Re: Re-raising exceptions with modified message

2007-07-06 Thread Alex Popescu
On Jul 6, 4:20 am, Christoph Zwerschke <[EMAIL PROTECTED]> wrote:
> Alex Popescu wrote:
>

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


Re: MethodType/FunctionType and decorators

2007-07-06 Thread Alex Popescu
On Jul 6, 6:19 am, [EMAIL PROTECTED] (Alex Martelli) wrote:
> Alex Popescu <[EMAIL PROTECTED]> wrote:
>
>...
>
> > frameworks (TestNG is not a unit testing framework,
> > but a full flavored testing framework that fits perfectly functional
> > testing, integration testing, and with some of the
> > very advanced features even performance and load testing).
>
> Nice!  Does it have any integration/interoperability with FIT/Fitnesse,
> btw?  For certain kinds of "functional testing" (where the specs are to
> be mostly written by people with no programming skills but strong
> business, accounting, &c, i.e., people _used_ to thinking in terms of
> tables and spreadsheets) I find that approach very interesting...
>
> Alex

That's an interesting idea! We never tried that before but I will
definitely look into it. Thanks for the suggestion Alex.

./alex
--
.w( the_mindstorm )p.


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


Re: Writing a read only attribute

2007-07-06 Thread Martin v. Löwis
> root = Tk()
> 
> # save call address
> original_tk_call = root.tk.call
> 
> # disable tcl command execution (this is the read-only attribute)
> root.tk.call = tk_dummy_call
> 
> ... some code ...
> 
> # restore tcl command execution
> root.tk.call = original_tk_call
> 
> 
> My goal is to make instances of Tkinter widgets without the effects of
> commands directed to the tcl interpreter but preserving all effects at
> python level.

You can try to put in a fake Tk object into root.tk, as root.tk is not
read-only. However, I would expect you run into other problems trying
to do so.

To change root.tk.call, you need to modify the implementation of the
_tkinter module.

Regards,
Martin

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


Writing a read only attribute

2007-07-06 Thread Fabrizio Pollastri
My code is the following:

from Tkinter import *

def tk_dummy_call(*args):
   return

root = Tk()

# save call address
original_tk_call = root.tk.call

# disable tcl command execution (this is the read-only attribute)
root.tk.call = tk_dummy_call

... some code ...

# restore tcl command execution
root.tk.call = original_tk_call


My goal is to make instances of Tkinter widgets without the effects of 
commands directed to the tcl interpreter but preserving all effects at 
python level.

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


Re: Writing a read only attribute

2007-07-06 Thread Michele Simionato
On Jul 6, 8:27 am, Fabrizio Pollastri <[EMAIL PROTECTED]> wrote:
> Hello,
> it is possible to force in some way a write to a read-only attribute of
> a python object?  In which case?
> Thanks for any answer.
>
> F. Pollastri

What do you mean by read-only attribute?
If you are trying to change attributes of built-in objects, there is
no hope:

>>> 'astring'.upper = 2
---
exceptions.AttributeError

AttributeError: 'str' object attribute 'upper' is read-only

If the read-only attribute has been implemented via a property, there
is a way
to write it, but you should tell us more about your case.

Michele Simionato

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


Re: converting datetime object in UTC to local time

2007-07-06 Thread i3dmaster
How about subclass datetime.tzinfo? That way you can use asttimezone
to transfer utc to localtime. It requires an aware object though not
naive. A bit more coding, but a lot less converting...

Jim

On Jul 3, 5:16 pm, Matt <[EMAIL PROTECTED]> wrote:
> Hi all,
>
> So a lot of digging on doing this and still not a fabulous solution:
>
> import time
>
> # this takes the last_modified_date naivedatetime, converts it to a
> # UTC timetuple, converts that to a timestamp (seconds since the
> # epoch), subtracts the timezone offset (in seconds), and then
> converts
> # that back into a timetuple...   Must be an easier way...
> mytime = time.localtime(time.mktime(last_modified_date.utctimetuple())
> - time.timezone)
>
> lm_date_str = time.strftime("%m/%d/%Y %I:%M %p %Z", mytime)
>
> last_modified_date is a naivedatetime.datetimeobject
>
> A previous version gave me something like:
>
> mytime 
> =datetime.datetime.fromtimestamp(time.mktime(last_modified_date.utctimetuple())
> - time.timezone)
>
> lm_date_str = mytime.strftime("%m/%d/%Y %I:%M %p %Z")
>
> But this gave me no timezone since thedatetimeobject is still
> naive.  And I'm going from adatetimeto a timetuple to a timestamp
> back to adatetime...
>
> All this seems like a lot of monkeying around to do something that
> should be simple -- is there a simple way to do this without requiring
> some other module?
>
> thx
>
> Matt


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


Re: SMTP server w/o using Twisted framework

2007-07-06 Thread Gerhard Häring
_spitFIRE wrote:
> [looking up DNS MX records]
> Thanks for the pointer. However, as I said currently, I can't use
> anything other than the standard libraries.

Sure you can. You just need to get rid of the "only standard library" 
requirement rule.

That works best by showing the alternatives to whoever set that requirement:

- use pyDNS
- use an existing (probably non-Python) SMTP daemon
- reimplement some parts of pyDNS yourself and develop a basic (crappy) 
SMTP daemon yourself

For doing the latter, you should budget at least one week.

FWIW another reason why SMTP servers should retry on temporary failure 
is that increasing use of Greylisting (*), which was precisely designed 
to filter out mail from "crappy" servers, like botnets, and - well - 
cheap custom written ones ;-)

-- Gerhard


(*) http://en.wikipedia.org/wiki/Greylisting - I use it myself
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: import

2007-07-06 Thread Gary Herron
jolly wrote:
> Hey guys,
>
> I'm rather new to python and i'm have trouble(as usual)
>
> I want to know if it is possible to change where 'import' looks
> this will save me clogging up my python directory
>
> Thanks
>   
Easily done.  The value of sys.path is a list of directories that import 
looks through to satisfy an import.  Just import sys and append a new 
directory to sys.path. 

import sys
sys.path.append('/your/directory/of/importable/modules')
// Then import code from your directory.


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


Re: import

2007-07-06 Thread Amit Khemka
On 7/6/07, jolly <[EMAIL PROTECTED]> wrote:
> Hey guys,
>
> I'm rather new to python and i'm have trouble(as usual)

Hope it becomes un-usual with Python !

>
> I want to know if it is possible to change where 'import' looks
> this will save me clogging up my python directory

Yes.  You can tell python where all to look for importing modules.

import sys
sys.path.append("/this/is/my/modules/path")


> Thanks

Welcome !

cheers,

-- 

Amit Khemka
website: www.onyomo.com
wap-site: www.owap.in
Home Page: www.cse.iitd.ernet.in/~csd00377

Endless the world's turn, endless the sun's Spinning, Endless the quest;
I turn again, back to my own beginning, And here, find rest.
-- 
http://mail.python.org/mailman/listinfo/python-list