Re: unify els database

2007-07-03 Thread rbsharp
On Jul 2, 3:35 pm, luca72 <[EMAIL PROTECTED]> wrote:
> Hello
>
> How i can use to connect to a unify els database with python
>
> Regards
>
> Luca

Hello,
could you be more specific. I know that there is a ODBC-Driver for
unify, if this is an option then it might be easier. Or do you want to
connect to the unify-database using HLI? And if so, on what platform?
I work with the unify database using HLI on various unix platforms. It
was by no means easy, but it can be made to work.

Greetings,
Richard Sharp

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


Re: Correct abstraction for TK

2007-07-03 Thread Laurent Pointal
[EMAIL PROTECTED] a écrit :
> I'm looking for a good example of how to correctly abstract TK code
> from the rest of my program. I want to just get some user info and
> then get 4 values from the GUI. Right now I've written it OOP per the
> examples on python.org but it doesn't seem to be meshing very well
> with the rest of my project.
> 
> Can anyone suggest some examples so that I can get more ideas?
> 
> Thanks,
> Luke
> 

Maybe try with easygui [1]. The multenterbox [2] seem to be right to 
enter 4 values [3]... Its really a nice tool to have a quick and clean 
user input solution with GUI in a function.

A+

Laurent.

[1] http://www.ferg.org/easygui/
[2] http://www.ferg.org/easygui/screenshot-multenterbox.png
[3] From the doc:
MULTENTERBOX AND MULTPASSWORDBOX --
GETTING INFORMATION FROM THE USER ABOUT MULTIPLE FIELDS
===

Multenterbox is a simple way of showing multiple enterboxes on a single
screen.  Multpasswordbox has the same interface as multenterbox, but
when it is displayed, the last of the fields is assumed to be a
password, and is masked with asterisks.

def multenterbox(message="Fill in values for the fields."
 , title=""
 , argListOfFieldNames  = []
 , argListOfFieldValues = []
 ):
 """Show screen with multiple data entry fields.
 The third argument is a list of fieldnames.
 The the forth argument is a list of field values.

 If there are fewer values than names, the list of values is padded
 with empty strings until the number of values is the same as the
 number of names.

 If there are more values than names, the list of values
 is truncated so that there are as many values as names.

 Returns a list of the values of the fields,
 or None if the user cancels the operation.

 Here is some example code, that shows how values returned from
 multenterbox can be checked for validity before they are accepted.
 --
 msg = "Enter your personal information"
 title = "Credit Card Application"
 fieldNames = ["Name","Street Address","City","State","ZipCode"]
 fieldValues = []  # we start with blanks for the values
 fieldValues = multenterbox(msg,title, fieldNames)

 # make sure that none of the fields was left blank
 while 1:
 if fieldValues == None: break
 errmsg = ""
 for i in range(len(fieldNames)):
if fieldValues[i].strip() == "":
errmsg = errmsg + ('"%s" is a required field.\n\n' %
fieldNames[i])
 if errmsg == "": break # no problems found
 fieldValues = multenterbox(errmsg, title, fieldNames,
 fieldValues)

 print "Reply was:", fieldValues
 
 """
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python compilation ??

2007-07-03 Thread Duncan Booth
Steve Holden <[EMAIL PROTECTED]> wrote:

> Absolutely. I should, of course, have said that only imported modules 
> have the results of the compilation stored as a .pyc file.
> 
> One must presume this is to save the file write time during development 
> when the program is almost always different fro the last time you ran it.

Or possibly to save disc space if you have a lot of scripts.

I think it is a reasonable compromise: if you are running a script it seems 
unlikely that you will notice the additional time to compile one script on 
top of the time to load the interpreter, but if your script imports a few 
hundred other modules the time to compile them is definitely noticeable.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Correct abstraction for TK

2007-07-03 Thread Paul Rubin
[EMAIL PROTECTED] writes:
> I'm looking for a good example of how to correctly abstract TK code
> from the rest of my program. I want to just get some user info and
> then get 4 values from the GUI. Right now I've written it OOP per the
> examples on python.org but it doesn't seem to be meshing very well
> with the rest of my project.

Simplest: just have gui operations call the application code.  The
application main loop is just the gui event loop.  Example (first tk
program I ever wrote, and one of my first python programs):

   http://www.nightsong.com/phr/python/calc.py

That might be enough for what you're doing.

Fancier: put gui in separate thread.  Be careful, it's not reentrant;
all communication with the application has to be through queues, sort
of like writing a miniature web server.  Most straightforward is to
pass tuples like (function, args, **kwargs) through the queues, where
the opposite end invokes the function on the arg list.  There are some
recipes in the Python cookbook for triggering the event loop on a
periodic timeout from inside tkinter.

See also "model-view-controller" for a more complex design approach
intended to separate the interface from the application logic.

Finally, consider total separation by embedding an http server in the
application, so the gui is a web browser and you write a web app.
It's often easier to code a simple html interface than to mess with
the damn Tk widgets and trying to get them to look decent on the
screen, plus it lets you easily put the client on a remote machine,
support multiple clients simultaneously, etc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Probably simple syntax error

2007-07-03 Thread Duncan Booth
ptn <[EMAIL PROTECTED]> wrote:

> PASCAL   -->PYTHON
> 5 div 2  -->   5/2
better:  5//2

The behaviour of 5/2 varies according to command line options and/or 
__future__ imports. e.g. If you start Python with the -Qwarn option 5/2 
will generate a warning; if you start Python with -Qnew (or use "from 
__future__ import division") then 5/2 will give you 2.5.

It is best, if you mean integer division, to always use the integer 
division operator.

> 5 mod 2-->   5 % 2
> 5/2-->   5/2.(Notice the little dot at the end)

Also note that those relationships only hold where both operands are 
positive. 

Python: -3//2 ---> -2
Pascal: -3 div 2 ---> either -1 or -2 is allowed by the standard.

Python: 3 % -2 ---> -1
Pascal: 3 mod -2 --> error
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Portable general timestamp format, not 2038-limited

2007-07-03 Thread Paul Rubin
[EMAIL PROTECTED] writes:
> As for the primacy of UTC vs. TAI, this is the classical chicken and
> egg problem.  The bureaucratic reality is opposed to the physical
> reality.

Well, if you're trying to pick just one timestamp standard, I'd say
you're better off using a worldwide one rather than a national one, no
matter how the bureaucracies work.  TAI is derived from atomic clocks
all over the world, while the national metrology labs are more subject
to error and desynchronization, and whatever legal primacy they have
is good in only one country.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Programming Idiomatic Code

2007-07-03 Thread Bruno Desthuilliers
Nathan Harmston a écrit :
> Hi,
> 
> I m sorry but I m bored at work (and no ones looking so I can write
> some Python) and following a job advertisement post,I decided to write
> the code to do its for the one entitled Ninjas or something like that.
> I was wondering what could be done to my following code to make it
> more idiomatic...or whether it was idiomatic and to be honest what
> idiomatic really means. All comments greatly appreciated and welcomed.
> 
> Thanks in advance
> 
> Nathan
> 
> import urllib2,sys
> from elementtree.ElementTree import parse
> 
> base_url = "http://api.etsy.com/feeds/xml_user_details.php?id=";

Using a module global for this kind of data is usually a bad idea 
(except eventually for run-once throw-away scripts, and even then...)

> def read_id_file(filename):
>""" reads a file and generates a list of ids from it"""
>ids = [ ]
>try:
> id_file = open(filename, "r")
> for l in id_file:
>ids.append( l.strip("\n") )
> id_file.close()

Python has other idioms for this (list comprehensions etc).


>except e:
>print e
>os._exit(99)

This is a very bad way to handle exceptions.
1/ you use a catch-all except clause, when you should be specific about 
what kind of exceptions you are willing to handle here
2/ names starting with an underscore are not part of the API. You should 
not use them unless you have a *very* compelling reason to do so.
3/ stdout is for normal outputs. Error messages and such should go to stderr
3/ anyway, if it's for printing the exception then exit, you'd better 
not handle anything - you'd have a similar result, but with a full 
traceback.

>return ids

def read_id_file(filename):
   try:
 f = open(filename)
   except IOError, e:
 print >> sys.stderr, \
   "failed to open %s for reading : %s" \
% (filename, e)
 return None
   else:
 ids = [l.strip() for l in f]
 f.close()
 return ids


> def generate_count(id_list):
>""" takes a list of ids and returns a dictionary of cities with
> associated counts"""
>city_count = {}
>for i in id_list:
>url = "%s%s" %(base_url,i)

base_url should be passed in as an argument.

> req = urllib2.Request(url)

I assume there's a problem with indentation here...

> try:
>xml = parse(urllib2.urlopen(url)).getroot()
>city  = xml.findtext('user/city')
> except e:
>print e.reason
>os._exit(99)

cf above

> try:
>city_count[city] += 1
>except:

should be 'except KeyError:'

>city_count[city] = 1

This idiom is appropriate if you expect few exceptions - that is, if the 
normal case is that city_count.has_key(city) == True. Else, you'd better 
use an explicit test, a defaultdict, etc. The idiomatic expliciti test 
would be:

   if city not in city_count:
 city_count['city'] = 1
   else:
  city_count[city] += 1


>return city_count
> 
> if __name__=='__main__':
>if len(sys.argv) is 1:

'is' is the identity operator. *Never* use it for numeric equality test. 
This should be:
  if len(sys.argv) == 1:

>id_list = [ 42346, 77290, 729 ]
>else:
>try: id_list = read_id_file(sys.argv[1])
>except e: print e

cf above about exception handling.

And FWIW, here, I would have used a try/except :

try:
  filename = sys.argv[1]
except IndexError:
  id_list = [1, 2, 3]
  print >> sys.stderr, \
"no id file passed, using default id_list %" % id_list
else:
  print >> sys.stderr, \
"reading id_list from id_file %s" % filename
  id_list = read_if_file(filename)

if not id_list:
  sys.exit(1)

>for k, v in generate_count(id_list).items():
>print "%s: %i" %(k, v)

There's a simpler way:

  for item in generate_count(id_list).iteritems():
  print "%s: %i" % item
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python compilation ??

2007-07-03 Thread Bruno Desthuilliers
Evan Klitzke a écrit :
> On 7/2/07, Cathy Murphy <[EMAIL PROTECTED]> wrote:
>> Is python a compiler language or interpreted language. If it is 
>> interpreter
>> , then why do we have to compile it?
> 
> It's an interpreted language. It is compiled into bytecode 

By this definition, Java is an interpreted language.

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

Re: Portable general timestamp format, not 2038-limited

2007-07-03 Thread Richard Heathfield
Paul Rubin said:

> [EMAIL PROTECTED] writes:
>> As for the primacy of UTC vs. TAI, this is the classical chicken and
>> egg problem.  The bureaucratic reality is opposed to the physical
>> reality.
> 
> Well, if you're trying to pick just one timestamp standard, I'd say
> you're better off using a worldwide one rather than a national one, no
> matter how the bureaucracies work.

In that case, the obvious choice is Greenwich Mean Time.  :-)

Seriously, GMT is recognised all over the world (far more so, in fact, 
than UTC, which tends to be recognised only by some well-educated 
people, and there are precious few of those), so why not use it?

I always leave my PC's clock set to GMT, partly out of this desire to 
support a single timestamp standard, and (it must be said) partly out 
of general cussedness.

-- 
Richard Heathfield 
Email: -www. +rjh@
Google users: 
"Usenet is a strange place" - dmr 29 July 1999
-- 
http://mail.python.org/mailman/listinfo/python-list


DatePart From String

2007-07-03 Thread Robert Rawlins - Think Blue
Hello Guys,

 

I have a date/time as a string which looks like this: 2007-02-01 00:00:00

 

I'm trying to get my hands on the different date parts of that string in the
following formats:

 

Time Only: 00:00:00

Day As Number: 01

Month As Number: 02

Day As Word: Monday

 

I've tried using the time.strptime() function without much success so
thought I'd come and ask your advice.

 

Thanks guys for any advice,

 

Rob

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

Re: try/finally in threads

2007-07-03 Thread Diez B. Roggisch
George Sakkis wrote:

> I posted this on the Pyro list but I'm not sure if it's related
> specifically to Pyro. The "finally" clause below is not executed when
> f() runs on on a (daemon) thread and the program exits. DAEMON here is
> a global Pyro.code.Daemon instance.
> 
> def f():
>try: DAEMON.requestLoop()
>finally:
># nothing is printed if f() runs in a thread
>print "i am here!!"
>DAEMON.shutdown()
>print "i am over!!"
> 
> Is "finally" not guaranteed to be executed in a non-main thread or is
> there something else going on ?

Well, that's pretty much the idea behind daemon threads - that they are
terminated immediately. If it were otherwise, a little endless-loop in that
finally-statement of yours would cause the program termination to hang
endlessly. 

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


Re: need help with win32com

2007-07-03 Thread Graeme Glass
On Jul 2, 6:38 pm, Thomas <[EMAIL PROTECTED]> wrote:
> I want to be able to access an excel file and extract the code from
> the macro that is in the file.  How can I do this?
>
> --
> ~Thomas~

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/483742

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


Re: Vista 64 + Python2.5 + wxpython 28 issue

2007-07-03 Thread Jorgen Grahn
On Fri, 29 Jun 2007 21:15:00 -0600, William Heymann <[EMAIL PROTECTED]> wrote:
> On Friday 29 June 2007, Martin v. Löwis wrote:
>> > There was no need for me to use 64 so I have switched back to 32 and
>> > works fine.
>> >
>> > Python is not ready for the 64 world yet ;)
>>
>> It's a matter of standpoint. 64 bit is not ready for the world, yet.
>
> I think you mean 64bit windows. 64bit linux has been working great.

Put differently: when everybody has a C compiler and the C source code
for things tends to be available, any change to the CPU architecture
is mostly painless.

/Jorgen

-- 
  // Jorgen Grahn   R'lyeh wgah'nagl fhtagn!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Programming Idiomatic Code

2007-07-03 Thread Nathan Harmston
HI,

Thanks to everyone for your comments ( i never knew "with" existed,
but to quote Borat "I like", unfortunately I cant apply for the job as
i m in the UK and dont have the experience but hey 10 minutes of
programming python beats 12 hours of programming in Clipper-derived
unreadable drivel (you dont know how much I appreciate Python atm).

I have one question though:

Using a module global for this kind of data is usually a bad idea
(except eventually for run-once throw-away scripts, and even then...)

Why is this a bad idea?

Thanks in advance

Nathan

PS I am very ashamed I wrote:
  if (len(sys.argv)) is 1 ..
  I would ask that this is never spoken of again, oh well
off to work I go
-- 
http://mail.python.org/mailman/listinfo/python-list


Python IRC bot using Twisted

2007-07-03 Thread ddtm
I'm using an example of IRC bot (_ttp://twistedmatrix.com/projects/
words/documentation/examples/ircLogBot.py) to create my own bot. But I
have a problem. I'm trying to make my bot send messages periodically.
But I can't find a way of adding Timer or something similar to my code
so that it could work. Could somebody modify an example to make IRC
bot send anything to chat every 20 seconds?

P.S. Timer should not lock the main program (I think it should work in
other thread or so)
P.P.S. Could somebody write a code of delay between messages too? In
pseudocode it looks like this:
  sleep(20)
  sendMessage(channel,'lopata')
This delay should be non-locking too.
P.P.P.S. Sorry for my bad English (and for a noob question too)

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


Python 2.5 from source without tcl/tk

2007-07-03 Thread Florian Demmer
Hi,

I am going nuts here... I thought had a solution for this a few weekas
ago but my hdd crashed and i put the note i wrote somewhere I had no
backup.

The system is a RedHat Enterprise 4 and I cannot install additional
rpms.
While the ./configure seems to go through fine I get a "INFO: Can't
locate Tcl/Tk libs and/or headers" during the make.

tk.h and tcl.h are in /usr/include
In other discussions I found that a missing X11/Xlib.h can be the
problem. That I don't have and cannot install.

Is there a way to completely leave out the tcl stuff when compiling?

I think what i did few weeks back was temporarily moving some tcl/tk
files away and back after the installation... but I cannot get it to
work now :(

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


Re: DatePart From String

2007-07-03 Thread Dave
Robert Rawlins - Think Blue  thinkbluemedia.co.uk> writes:


> I’ve tried using the time.strptime() function without much success so
> thought I’d come and ask your advice.
> 

How exactly does it not work?? This works for me:

from time import mktime, strptime
from datetime import datetime

datetime_string = '2007-02-01 00:00:00'
datetime_object = datetime.fromtimestamp(
  mktime(strptime(datetime_string,'%Y-%m-%d %H:%M:%S')))

print datetime_object.year
print datetime_object.month
print datetime_object.day
print datetime_object.hour
print datetime_object.minute
print datetime_object.second

HTH,
Dave








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

Re: Bug in Python class static variable?

2007-07-03 Thread Bruza
On Jul 2, 1:21 pm, Duncan Booth <[EMAIL PROTECTED]> wrote:
> Bruza <[EMAIL PROTECTED]> wrote:
> > On Jul 2, 3:52 am, Duncan Booth <[EMAIL PROTECTED]> wrote:
> >> Bruza <[EMAIL PROTECTED]> wrote:
> >> > I am trying to define a class static variable. But the value of the
> >> > static variable seems to be only defined inside the file that the
> >> > class is declared. See the code below. When I run "python w.py", I
> >> > got:
>
> >> When you run "python w.py" the *script* w.py is loaded as the module
> >> __main__. Importing a module called 'w' creates a new module which is
> >> unrelated to __main__. If you want access to variables defined in the
> >> main script then you need to import __main__.
>
> >> Don't use 'from module import *':
>
> >> The import statements are executed when the interpreter reaches them
> >> in the source. Even if you fix your code to import from __main__, the
> >> values you try to import from __main__ won't exist when the import
> >> statement executes: the first 'from a import *' will load and execute
> >> all of module 'a', but when that executes 'from __main__ import *' it
> >> just imports names defined in the main script *before* a was
> >> imported.
>
> >> In general, don't try to do this: put all your classes into modules
> >> and just put minimal startup code into a script.
>
> > Duncan,
>
> > Thanks for replying. However, I am still confused...
> > Even if I put "from __main__ import *" in both "a.py" and "w.py", I
> > still got
> > the same results. So, how should I re-structure my program to make the
> > class
> > static variable works???
>
> Option 1:
> In w.py put:
>
> import a
>
> and then refer to a.ClassA
>
> In a.py put:
>
> import __main__
>
> and then refer to __main__.ClassW
>
> But better, option 2:
>
> Create a new file script.py which contains:
>
> import w
> if __name__=='__main__':
> w.startup()
>
> then in a use 'import w' and in w use 'import a' and refer to a.ClassA and
> w.ClassW as above.
>
> Try to think through the order in which Python interprets your code:
> remember everything is interpreted. Both 'import' statements and 'class'
> statements are really just variation on an assignment, so none of the names
> exist until the lines which declare them have been executed. A line 'import
> a' is roughly the same as:
>
>a = __import__(something)
>
> and a statement such as 'class ClassA: whatever' is roughly the same as:
>
>   ClassA = type('ClassA', baseclasses, dict)
>
> You should never attempt to use the 'from X import *' form of import when
> you have modules which include each other (you might get away with it if
> you move the imports to the end of the module instead of the beginning, but
> it is much simpler just to import the modules, and good practice in any
> case).

Duncan,

Thanks for the reply; both approaches worked!! Looks like the problem
is because
of "ClassW" is defined in the default "__main__" module, not the "w"
module as
I thought.

I also figured out a 3rd approach adding the following code in "w.py".
The idea
is that I force the program to import "w.py" as "w" if "w.py" is
loaded into
"__main__". Then I can run the qualified "w.startup()". And it also
works :-)...

if __name__ == '__main__':
import w
w.startup()

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


15 Exercises to Know A Programming Language

2007-07-03 Thread Martin
I am trying to improve my Python skills through some exercises.
Currently I am working on Larry's "15 exercises to know a programming
language " (http://www.knowing.net/
PermaLink,guid,f3b9ba36-848e-43f8-9caa-232ec216192d.aspx). The first
exercise is this:

"Write a program that takes as its first argument one of the words
'sum,' 'product,' 'mean,' or 'sqrt'  and for further arguments a
series of numbers. The program applies the appropriate function to
the series."

My solution so far is this:

http://dpaste.com/13469/

I would really like some feedback. Is this a good solution? is it
efficient? robust? what could be improved? any not looking for a
revised solution, hints on what to improve are also very welcome.

Martin

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


Re: need help with win32com

2007-07-03 Thread John Machin
On Jul 3, 7:06 pm, Graeme Glass <[EMAIL PROTECTED]> wrote:
> On Jul 2, 6:38 pm, Thomas <[EMAIL PROTECTED]> wrote:
>
> > I want to be able to access an excel file and extract the code from
> > the macro that is in the file.  How can I do this?
>
> > --
> > ~Thomas~
>
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/483742

The OP wants to extract the code of a macro. The above URL points to
an interesting recipe for an extra layer on top of xlrd's data-
extraction API. xlrd, as documented, avoids macros. The OP needs, as
his subject suggests, help with win32com, which is AFAIK the only
possible Python-related candidate for a solution to his problem.

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


Python and ARexx (was Re: Tiny/small/minimalist Python?)

2007-07-03 Thread Jorgen Grahn
On Tue, 03 Jul 2007 05:25:28 GMT, Dennis Lee Bieber <[EMAIL PROTECTED]> wrote:
> On Tue, 03 Jul 2007 02:26:43 +0200, Irmen de Jong
> <[EMAIL PROTECTED]> declaimed the following in comp.lang.python:
>
>> 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
...

> And your's was likely more powerful than mine... I only had 2MB and no MMU
> 1.5.2 was great (and even more fun combined with ARexx)

How does Python combine with ARexx?  Can you control applications
which provide an ARexx interface?

I stopped using my Amiga 4000/030 in 1996 or so, long before I
realized C isn't always the best choice for getting things done. I
messed around a bit with ARexx though, and while I found it neat to be
able to script an application from the inside or from the outside
using ARexx, I didn't really care for the language itself -- too
primitive for anything but the tiniest programs.

/Jorgen

-- 
  // Jorgen Grahn   R'lyeh wgah'nagl fhtagn!
-- 
http://mail.python.org/mailman/listinfo/python-list


Freeze and problem with shared libraries

2007-07-03 Thread [EMAIL PROTECTED]
I am trying to use freeze to create a single binary executable for one
of my program. When I run freeze, it runs fine with the following
modules. These modules are available in the dyn-load directory and I
can import them from the python interpreter.
Warning: unknown modules remain: _bisect _heapq _locale _random
_socket
Make also runs fine, but when I run the program on another machine, it
compiles saying could not import these modules. Any idea how to get
this working...

Or can I have a directory of shared libs in a directory and do,
import imp
imp.load_dynamic()
This will not be as good as having a single binary file, but will work
I guess...

Thanks.
-
Suresh

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


A new data structrue in python: Tree

2007-07-03 Thread Roc Zhou

Recently I tried to create a new data structure in python: Tree, by operator
overloading. I want it can act as a builtin type, such as list and dict.

Luckily the basic definition has been finished now, the document is in the
code and unittest. And I have put the HTML doc at:
http://crablfs.sourceforge.net/tree.html

The source code is in SVN:
https://crablfs.svn.sourceforge.net/svnroot/crablfs/caxes/trunk/lib/
the files are tree.py and tree_ut.py.

Now I want to get more advices and feedbacks, so I post this mail.

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

restructuredtext latin1 encoding (FAQ?)

2007-07-03 Thread Helmut Jarausch
Hi,

I did try to find something on the net but I couldn't find anything useful.

Is there a way to write documents with the reST tools using the Latin1
encoding?

Many thanks for a hint,

Helmut Jarausch

Lehrstuhl fuer Numerische Mathematik
RWTH - Aachen University
D 52056 Aachen, Germany
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: restructuredtext latin1 encoding (FAQ?)

2007-07-03 Thread Marc 'BlackJack' Rintsch
On Tue, 03 Jul 2007 12:12:04 +0200, Helmut Jarausch wrote:

> Is there a way to write documents with the reST tools using the Latin1
> encoding?

Yes of course there is.  Just write the documents in Latin-1 encoding. 
Take a look at the charset command line options if Latin-1 is not the
default encoding used by your operating system.

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


Re: 15 Exercises to Know A Programming Language

2007-07-03 Thread Marc 'BlackJack' Rintsch
On Tue, 03 Jul 2007 09:58:16 +, Martin wrote:

> "Write a program that takes as its first argument one of the words
> 'sum,' 'product,' 'mean,' or 'sqrt'  and for further arguments a
> series of numbers. The program applies the appropriate function to
> the series."
> 
> My solution so far is this:
> 
> http://dpaste.com/13469/
> 
> I would really like some feedback. Is this a good solution? is it
> efficient? robust? what could be improved? any not looking for a
> revised solution, hints on what to improve are also very welcome.

Don't use `eval()` if it is not absolutely necessary.  Especially if the
input comes from a user it's a security hole.  `float()` is the function
to use here.

`mean()` does not work as you try to divide a list by a number.

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


RE: DatePart From String

2007-07-03 Thread Robert Rawlins - Think Blue
Hello Dave,

Thanks for getting back to me, I had been trying to use it like this:

time.strptime('2007-01-01 00:00:00','%H:%M:%S')

I was getting an error thrown at me: ValueError: time data did not match 
format:  data=2007-01-01 00:00:00  fmt=%H:%M:%S

I see how your solution works, but I'm hoping to trip is down a little bit as 
this has to be used in a conditional statement such as the one below:

If time.strftime('%H:%M:%S') > time.strptime('2007-01-01 
00:00:00','%H:%M:%S')
Print 'Later In The Day'

You see how that works? I'm basically trying to check if the current time is 
later that the one defined in my string.

Are you able to give me a working example of how I might do this with my 
conditional?

Thanks Dave,

Rob

-Original Message-
From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf Of Dave
Sent: 03 July 2007 10:46
To: python-list@python.org
Subject: Re: DatePart From String

Robert Rawlins - Think Blue  thinkbluemedia.co.uk> writes:


> I’ve tried using the time.strptime() function without much success so
> thought I’d come and ask your advice.
> 

How exactly does it not work?? This works for me:

from time import mktime, strptime
from datetime import datetime

datetime_string = '2007-02-01 00:00:00'
datetime_object = datetime.fromtimestamp(
  mktime(strptime(datetime_string,'%Y-%m-%d %H:%M:%S')))

print datetime_object.year
print datetime_object.month
print datetime_object.day
print datetime_object.hour
print datetime_object.minute
print datetime_object.second

HTH,
Dave








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

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

Re: restructuredtext latin1 encoding (FAQ?)

2007-07-03 Thread Helmut Jarausch
Marc 'BlackJack' Rintsch wrote:
> On Tue, 03 Jul 2007 12:12:04 +0200, Helmut Jarausch wrote:
> 
>> Is there a way to write documents with the reST tools using the Latin1
>> encoding?
> 
> Yes of course there is.  Just write the documents in Latin-1 encoding. 
> Take a look at the charset command line options if Latin-1 is not the
> default encoding used by your operating system.
> 

Many thanks!

Is there also a way to tell it  dugui.py ?

Helmut.

-- 
Helmut Jarausch

Lehrstuhl fuer Numerische Mathematik
RWTH - Aachen University
D 52056 Aachen, Germany
-- 
http://mail.python.org/mailman/listinfo/python-list


newbie-question

2007-07-03 Thread TK
Hi,

how can I implement a socket timeout?

Thanx for help.

o-o

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


Re: 15 Exercises to Know A Programming Language

2007-07-03 Thread Martin
On Jul 3, 12:25 pm, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote:
> On Tue, 03 Jul 2007 09:58:16 +, Martin wrote:
> > "Write a program that takes as its first argument one of the words
> > 'sum,' 'product,' 'mean,' or 'sqrt'  and for further arguments a
> > series of numbers. The program applies the appropriate function to
> > the series."
>
> > My solution so far is this:
>
> >http://dpaste.com/13469/
>
> > I would really like some feedback. Is this a good solution? is it
> > efficient? robust? what could be improved? any not looking for a
> > revised solution, hints on what to improve are also very welcome.
>
> Don't use `eval()` if it is not absolutely necessary.  Especially if the
> input comes from a user it's a security hole.  `float()` is the function
> to use here.
>
> `mean()` does not work as you try to divide a list by a number.
>
> Ciao,
> Marc 'BlackJack' Rintsch

Thanks for the feedback. I have posted a revised version here (http://
dpaste.com/13474/) where mean works. The reason I use eval is I want
it to work for complex numbers too, but I guess i could check for the
presence of a "j" in the arguments instead.

Martin

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


Re: newbie-question

2007-07-03 Thread Bjoern Schliessmann
TK wrote:

> how can I implement a socket timeout?

What exactly do you mean by "socket timeout"? Which OS?

> Thanx for help.

Thanks for choosing an adequate subject next time.

Regards,


Björn

-- 
BOFH excuse #84:

Someone is standing on the ethernet cable, causing a kink in the
cable

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


Re: newbie-question

2007-07-03 Thread Stargaming
TK wrote:
> how can I implement a socket timeout?

Risking an inadequate answer (since your description was not that 
detailled, try to express a little more exact!), I can suggest 
http://starship.python.net/crew/theller/pyhelp.cgi to browse the 
documentation. If you enter "timeout", the first match will be a good 
pointer. Look through the socket manual 
(http://docs.python.org/lib/module-socket.html) for timeout.

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


Re: 15 Exercises to Know A Programming Language

2007-07-03 Thread Daniel Nogradi
> > > "Write a program that takes as its first argument one of the words
> > > 'sum,' 'product,' 'mean,' or 'sqrt'  and for further arguments a
> > > series of numbers. The program applies the appropriate function to
> > > the series."
> >
> > > My solution so far is this:
> >
> > >http://dpaste.com/13469/
> >
> > > I would really like some feedback. Is this a good solution? is it
> > > efficient? robust? what could be improved? any not looking for a
> > > revised solution, hints on what to improve are also very welcome.
> >
> > Don't use `eval()` if it is not absolutely necessary.  Especially if the
> > input comes from a user it's a security hole.  `float()` is the function
> > to use here.
> >
> > `mean()` does not work as you try to divide a list by a number.
> >
>
> Thanks for the feedback. I have posted a revised version here (http://
> dpaste.com/13474/) where mean works. The reason I use eval is I want
> it to work for complex numbers too, but I guess i could check for the
> presence of a "j" in the arguments instead.


Hi, if I invoke your program without arguments an uncaught exception
is raised. Wouldn't it be better to inform the user that an argument
is expected?

See http://docs.python.org/tut/node10.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Programming Idiomatic Code

2007-07-03 Thread Bruno Desthuilliers
Nathan Harmston a écrit :
> HI,
(snip)
> I have one question though:
> 
> Using a module global for this kind of data is usually a bad idea
> (except eventually for run-once throw-away scripts, and even then...)
> 
> Why is this a bad idea?

Don't you have any idea ?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: 15 Exercises to Know A Programming Language

2007-07-03 Thread John Machin
On Jul 3, 7:58 pm, Martin <[EMAIL PROTECTED]> wrote:
> I am trying to improve my Python skills through some exercises.
> Currently I am working on Larry's "15 exercises to know a programming
> language " (http://www.knowing.net/
> PermaLink,guid,f3b9ba36-848e-43f8-9caa-232ec216192d.aspx). The first
> exercise is this:
>
> "Write a program that takes as its first argument one of the words
> 'sum,' 'product,' 'mean,' or 'sqrt'  and for further arguments a
> series of numbers. The program applies the appropriate function to
> the series."
>
> My solution so far is this:
>
> http://dpaste.com/13469/
>
> I would really like some feedback. Is this a good solution? is it
> efficient? robust? what could be improved? any not looking for a
> revised solution, hints on what to improve are also very welcome.
>
> Martin

sum is a builtin function in Python 2.3 and later. You could do
something like this:

try:
sum
except NameError:
def sum(args):
return reduce(operator.add, args)

Tested with 2.5 back to 2.1, and 1.5.2 :-)

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


Re: PEP 3107 and stronger typing (note: probably a newbie question)

2007-07-03 Thread Roy Smith
[EMAIL PROTECTED] (Alex Martelli) wrote:
> Eckel's and Martin's well-known essays on why good testing can replace
> strict static type checking:
> 
> 

I've read the first before.  I just re-read it.  There seem to be three 
different concepts all being talked about at the same time.

1) Static vs. dynamic checking.
2) Type (is-a) checking vs. behavior (has-a) checking.
3) Automatic (i.e. compiler generated) vs. manually written tests.

They all allow you to write manual tests.  No sane programmer will rely 
exclusively on the automatic checks, no matter what flavor they are.  The 
interesting thing is that most people seem to conflate items 1 and 2 above 
into two composite camps: static type checking vs. dynamic behavior 
checking.  There's really no reason you can't have dynamic type checking 
(things that raise TypeError in Python, for example, or C++'s 
dynamic_cast).  There's also no reason you can't have static behavior 
checking (Java's interfaces).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: good matlab interface

2007-07-03 Thread [EMAIL PROTECTED]
On Jul 2, 3:02 pm, Brian Blais <[EMAIL PROTECTED]> wrote:
> On Jun 30, 2007, at 2:31 AM, felix seltzer wrote:
>
> > Does any one know of a good matlab interface?
> > I would just use scipy or numpy, but i also need to use
> > the matlab neural network functions.  I have tried PyMat, but am
> > having
> > a hard time getting it to install correctly.

did you try mlabwrap? for me it worked without problems.
http://mlabwrap.sourceforge.net/

bernhard


>
> What problems are you having installing?  I had one problem with the
> terrible matlab license server, which I had to solve by making site-
> packages world writable, installing pymat as a user, and then
> removing the world writable flag.  Root just didn't have access to
> matlab on my machine.  :P
>
> bb


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


Re: Python IRC bot using Twisted

2007-07-03 Thread Jean-Paul Calderone
On Tue, 03 Jul 2007 09:46:59 -, ddtm <[EMAIL PROTECTED]> wrote:
>I'm using an example of IRC bot (_ttp://twistedmatrix.com/projects/
>words/documentation/examples/ircLogBot.py) to create my own bot. But I
>have a problem. I'm trying to make my bot send messages periodically.
>But I can't find a way of adding Timer or something similar to my code
>so that it could work. Could somebody modify an example to make IRC
>bot send anything to chat every 20 seconds?
>
>P.S. Timer should not lock the main program (I think it should work in
>other thread or so)
>P.P.S. Could somebody write a code of delay between messages too? In
>pseudocode it looks like this:
>  sleep(20)
>  sendMessage(channel,'lopata')
>This delay should be non-locking too.
>P.P.P.S. Sorry for my bad English (and for a noob question too)
>

You can use reactor.callLater to schedule a one-time event to happen at
some future point:

reactor.callLater(20, sendMessage, channel, 'lopata')

There is also a utility class, twisted.internet.task.LoopingCall, which
you can use to schedule an event to occur repeatedly at some interval:

call = LoopingCall(sendMessage, channel, 'lopata')
loopDeferred = call.start(20)

You can read more about these APIs in the scheduling howto:

http://twistedmatrix.com/projects/core/documentation/howto/time.html

Or you can refer to the generated API documentation:

http://twistedmatrix.com/documents/current/api/twisted.internet.interfaces.IReactorTime.html
http://twistedmatrix.com/documents/current/api/twisted.internet.task.LoopingCall.html

Hope this helps,

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


Re: Portable general timestamp format, not 2038-limited

2007-07-03 Thread Martin Gregorie
Peter J. Holzer wrote:
> On 2007-07-03 05:12, Scott David Daniels <[EMAIL PROTECTED]> wrote:
>> TOPS-20 did an interesting format which suggest an interesting variant:
>>  Tops-20:  36-bit (the machine word size) fixed-bit representation
>>of days since a given moment (the first Photographic
>>plates of the sky).  The "binary point" was at the middle
>>of the word; the low order 18 bits were the time of day
>>(GMT), the high-order 18 bits were the days-since date.
>>
I think there's a definite practical advantage in storing dates as a day 
count from a base date and providing a standard set of 
procedures/methods to convert it to and from a human-readable format. It 
makes all sorts of date calculations much easier. For instance, if 
there's a requirement to produce statements dated for the last day of 
the current month the pseudo code is simply:
- convert the date to ccyymmdd format
- add 1 to the month, adjusting the year and century to fix
   year roll-over and set the day to 1
- convert back to day count and subtract 1
- the result, output in readable form is the last day of the month
   irrespective of month length, leap years, etc.

I don';t think it matters what the base date is, though the Astronomical 
base date [12 noon on 1 JAN -4712 (4713 BC)] may be as good as any. 
Other bases I've seen (apart from UNIX date) are ICL 1900 mainframes, 
which set day zero as 31 Dec 1899 and held the time separately. ICL 2900 
systems held the date and time as microseconds since 00:00:00 1900-01-01 
in a 64 bit word, which is also easy to deal with and allows the same 
set of date arithmetic operations as a straight day number.

BTW, be sure to distinguish Julian Day and Modified Julian Day (used by 
astronomers from the "Julian Date" that [used to] be used by IBM 
mainframes. The former is a day count but the latter is day within year 
(yyddd). JD and MJD are described in:

http://tycho.usno.navy.mil/mjd.html


-- 
martin@   | Martin Gregorie
gregorie. | Essex, UK
org   |
-- 
http://mail.python.org/mailman/listinfo/python-list


Debugging "broken pipe" (in telnetlib)

2007-07-03 Thread Samuel
Hi,

When using telnetlib, the connection sometimes breaks with the
following error:

"error: (32, 'Broken pipe')"

where the traceback points to

self.sock.send(buffer)

in telnetlib.py. The problem is unreproducible, but happens fairly
often (approx. 5% of the time). Any idea how to debug such a problem?
How can I find out what broke the pipe?

-Samuel

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


what is wrong with that r"\"

2007-07-03 Thread alf
question without words:

 >>> r"\"
   File "", line 1
 r"\"
^
SyntaxError: EOL while scanning single-quoted string
 >>> r"\ "
'\\ '
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: unify els database

2007-07-03 Thread luca72
Hello and thanks for your answer, the unify db is on unix-sco and i
need to connect with linux machine with python

Regards

Luca

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


Re: Debugging "broken pipe" (in telnetlib)

2007-07-03 Thread Jean-Paul Calderone
On Tue, 03 Jul 2007 05:12:22 -0700, Samuel <[EMAIL PROTECTED]> wrote:
>Hi,
>
>When using telnetlib, the connection sometimes breaks with the
>following error:
>
>"error: (32, 'Broken pipe')"
>
>where the traceback points to
>
>self.sock.send(buffer)
>
>in telnetlib.py. The problem is unreproducible, but happens fairly
>often (approx. 5% of the time). Any idea how to debug such a problem?
>How can I find out what broke the pipe?

EPIPE results when writing to a socket for which writing has been shutdown.
This most commonly occurs when the socket has closed.  You need to handle
this exception, since you can't absolutely prevent the socket from being
closed.  There might be some other change which would be appropriate, though,
if it is the case that something your application is doing is causing the
socket to be closed (for example, sending a message which the remote side
decides is invalid and causing it to close the socket explicitly from its
end).  It's difficult to make any specific suggestions in that area without
knowing exactly what your program does.

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


Re: Pretty Scheme, ??? Python

2007-07-03 Thread Neil Cerutti
On 2007-07-02, Paul McGuire <[EMAIL PROTECTED]> wrote:
> On Jul 2, 3:56 pm, Neil Cerutti <[EMAIL PROTECTED]> wrote:
> from pyparsing import *

It's always good when your messages start like that. ;)

> """
> Ok, here is the step-by-step, beginning with your posted BNF.
> (Based on your test cases, I think the '{}'s are really
> supposed to be '()'s.)

Yeah, the Scheme version of WAE uses curlies in examples just so
it looks slightly different from Scheme, although since the
Scheme version is built on the Scheme read function, it actually
accepts several different kinds of delimiters.

Python didn't need to do that, I thought.

My first impulse when programming this exercise was to ape the
Scheme strategy, going with a syntax analogous to Python's, using
Python's code or AST modules. But it turns out I'm not a clever
enough language designer.

Moreover, the fun of the book I mentioned is in designing the
semantics of the programs. The book basically punts parsing,
leaving it up to the 'read' function. So basically, Python gets
up to speed (except for the define-type and type-case macros)
simply by implementing a read with enough functionality for each
mini-langauge.

> ;  ::=
> ;   
> ;   | { +   }
> ;   | { -   }
> ;   | {with { } }
> ;   | 
>
> The most basic building blocks in pyparsing are Literal and
> Word. With these, you compose "compound" elements using And and
> MatchFirst, which are bound to the operators '+' and '|' (on
> occasion, Or is required, bound to operator '^', but not for
> this simple parser). Since you have a recursive grammar, you
> will also need Forward. Whitespace is skipped implicitly.
>
> Only slightly more advanced is the Group class, which will
> impart hierarchy and structure to the results - otherwise,
> everything just comes out as one flat list of tokens.  You may
> be able to remove these in the final parser, depending on your
> results after steps 1 and 2 in the "left for the student" part
> below, but they are here to help show structure of the parsed
> tokens.
>
> As convenience functions go, I think the most common are oneOf
> and delimitedList.  oneOf might be useful here if you want to
> express id as a single-char variable; otherwise, just use
> Word(alphas).
>
> At this point you should be able to write a parser for this WAE
> grammar.  Like the following 9-liner:
> """
>
> LPAR = Literal("(").suppress()
> RPAR = Literal(")").suppress()
>
> wae = Forward()
> num = Word(nums)
> id = oneOf( list(alphas) )

The above shadows 'id'; I suppose 'ident' would be better.

> addwae = Group( LPAR + "+" + wae + wae + RPAR )
> subwae = Group( LPAR + "-" + wae + wae + RPAR )
> withwae = Group( LPAR + "with" + LPAR + id + wae + RPAR + wae + RPAR )
>
> wae << (addwae | subwae | withwae | num | id)
>
> tests = """\
>  3
>  (+ 3 4)
>  (with (x (+ 5 5)) (+ x x))""".splitlines()
>
> for t in tests:
> print t
> waeTree = wae.parseString(t)
> print waeTree.asList()
> print
>
> """
> If you extract and run this script, here are the results:
>  3
> ['3']
>
>  (+ 3 4)
> [['+', '3', '4']]
>
>  (with (x (+ 5 5)) (+ x x))
> [['with', 'x', ['+', '5', '5'], ['+', 'x', 'x']]]

How can I make it barf for testcases like '(+ 2 3))'? It doesn't
seem to expect an Eof.

> Left as an exercise for the student:
> 1. Define classes NumWAE, IdWAE, AddWAE, SubWAE, and WithWAE whose
> __init__ methods take a ParseResults object named tokens (which you
> can treat as a list of tokens), and each with a calc() method to
> evaluate them accordingly.
> 2. Hook each class to the appropriate WAE class using setParseAction.
> Hint: here is one done for you:  num.setParseAction(NumWAE)
> 3. Modify the test loop to insert an evaluation of the parsed tree.

I use doctest, so it looks quite different. On the other hand, it
actually checks that the results are correct. ;)

> Extra credit: why is id last in the set of alternatives defined
> for the wae expression?

I'm not sure. When I moved it to first all my valid tests still
passed, but one of the deliberately erroneous ones caused
a different exception, e.g., '(+ 2)'. Writing my own parser does
make error handling more predictable, but probably PyParsing can
be configured to do what I want.

My AST's from the first version of the program translated easily
into your program, with almost no muss or fuss. The muss is that,
since all the __init__ functions now expect a token list instead
of named arguments, they are now cryptic, and creating AST's
manually became annoying. The fuss is that I do have to create
one in With's calc function. It should be unnecessary for the AST
objects to be so dependent upon the grammar to work correctly.
I suppose a solution would be to add another layer of abstraction
in between.

Read it and weep. The program hasn't changed much. It's still
uglier than the Scheme. Attached at the end is my original sexp
and WAE parser, for comparison with the PyParsing portion of the
program. This time I've included all the tests, but no

connecting to serial port + python

2007-07-03 Thread Japan Shah
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.

import os
import re
import time
import sys
from threading import Thread
import serial

class connect_serial(Thread):
   def __init__(self,socks):
  Thread.__init__(self)
  self.sock = socks
  self.count = 0

   def run(self):
  self.count = 0
  try:
while 1:
   self.count +=1
   if (self.count>=5):
  break

   lines = self.sock.read(100)
   if lines:
  print lines
  print 'read
success---'
   else:
  print 'nothing to read',str(self.getName())
  except Exception,e:
print self.getName()

print time.ctime()
print
try:
conn1 = serial.Serial(4)
conn1.baudrate = '9600'
conn1.parity = serial.PARITY_EVEN
conn1.timeout=1
except Exception,e:
print 'port is Buzy'
sys.exit(-1)
print '--'
print 'getSupportedBaudrates',conn1.getSupportedBaudrates()
print 'getSupportedByteSizes',conn1.getSupportedByteSizes()
print 'getSupportedParities',conn1.getSupportedParities()
print 'getSupportedStopbits',conn1.getSupportedStopbits()
print '--'
print 'getBaudrates',conn1.getBaudrate()
print 'getByteSizes',conn1.getByteSize()
print 'getParities',conn1.getParity()
print 'getStopbits',conn1.getStopbits()
print '--'
print 'port is in use',conn1.portstr
list1 = []

command = ['AT','ATI','ATl1','AT+GMMM']

for cmd in command:
   conn1.write(str(cmd))
   th = connect_serial(conn1)
   list1.append(th)
   th.start()

for th1 in list1:
print 'started joining',th1.getName(), 'counter :',th1.count
th1.join()

print time.ctime()

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


Re: what is wrong with that r"\"

2007-07-03 Thread kyosohma
On Jul 3, 7:15 am, alf <[EMAIL PROTECTED]> wrote:
> question without words:
>
>  >>> r"\"
>File "", line 1
>  r"\"
> ^
> SyntaxError: EOL while scanning single-quoted string
>  >>> r"\ "
> '\\ '

One slash escapes the following character, so the proper way of
writing it is either

r"\\" or r"\""

See http://docs.python.org/ref/strings.html for more information.

Mike

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


Re: what is wrong with that r"\"

2007-07-03 Thread Jean-Paul Calderone
On Tue, 03 Jul 2007 06:16:43 -0700, [EMAIL PROTECTED] wrote:
>On Jul 3, 7:15 am, alf <[EMAIL PROTECTED]> wrote:
>> question without words:
>>
>>  >>> r"\"
>>File "", line 1
>>  r"\"
>> ^
>> SyntaxError: EOL while scanning single-quoted string
>>  >>> r"\ "
>> '\\ '
>
>One slash escapes the following character, so the proper way of
>writing it is either
>
>r"\\" or r"\""
>
>See http://docs.python.org/ref/strings.html for more information.

I wonder if the OP was asking how to spell the one-length string \?
In that case, the answer is that it can't be done using raw strings,
but "\\" does it.  Backslash escapes aren't interpreted in raw strings,
but you still can't end a raw string with a backslash.

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


Re: what is wrong with that r"\"

2007-07-03 Thread kyosohma
On Jul 3, 8:25 am, Jean-Paul Calderone <[EMAIL PROTECTED]> wrote:
> On Tue, 03 Jul 2007 06:16:43 -0700, [EMAIL PROTECTED] wrote:
> >On Jul 3, 7:15 am, alf <[EMAIL PROTECTED]> wrote:
> >> question without words:
>
> >>  >>> r"\"
> >>File "", line 1
> >>  r"\"
> >> ^
> >> SyntaxError: EOL while scanning single-quoted string
> >>  >>> r"\ "
> >> '\\ '
>
> >One slash escapes the following character, so the proper way of
> >writing it is either
>
> >r"\\" or r"\""
>
> >Seehttp://docs.python.org/ref/strings.htmlfor more information.
>
> I wonder if the OP was asking how to spell the one-length string \?
> In that case, the answer is that it can't be done using raw strings,
> but "\\" does it.  Backslash escapes aren't interpreted in raw strings,
> but you still can't end a raw string with a backslash.
>
> Jean-Paul

Very true...sometimes I need to read these weird posts 2 or 3 times.

Mike

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


Re: Pretty Scheme, ??? Python

2007-07-03 Thread Paul McGuire
Neil -

>> The above shadows 'id'; I suppose 'ident' would be better.
Doh! I found the id() shadowing later, changed my var to id_ so as
not to stray from your BNF too much.

>> How can I make it barf for testcases like '(+ 2 3))'? It doesn't
>> seem to expect an Eof.
To force parsing to the end of string, add a StringEnd instance
where you expect there to be the end of the input string. Change:
waeTree = wae.parseString(t)
to:
waeTree = (wae + StringEnd()).parseString(t)

>> The muss is that,
>> since all the __init__ functions now expect a token list instead
>> of named arguments, they are now cryptic, and creating AST's
>> manually became annoying. The fuss is that I do have to create
>> one in With's calc function. It should be unnecessary for the
>> AST objects to be so dependent upon the grammar to work
>> correctly.
I agree 1000%.  The pyparsing method for this is to use
setResultsName.  Here is the grammar, with results names defined
to match those in your original.  And you are absolutely correct,
using named fields like this makes your code MUCH more robust, and
less dependent on the grammar.


num = Combine( Optional("-") + Word(nums) ).setResultsName("n")
id_ = oneOf( list(alphas) ).setResultsName("v")
addwae = Group( LPAR + "+" + wae.setResultsName("lhs") +
 wae.setResultsName("rhs") + RPAR )
subwae = Group( LPAR + "-" + wae.setResultsName("lhs") +
 wae.setResultsName("rhs") + RPAR )
withwae = Group( LPAR + "with" + LPAR +
id_.setResultsName("bound_id") +
wae.setResultsName("named_expr") + RPAR +
wae.setResultsName("bound_body") + RPAR )

Now your calc methods can refer to them using:
self.tokens.lhs
self.tokens.bound_id
etc.


Here is my alternative solution (not using results names).  I used
the base WAE class to accept the tokens as the initialization var,
then unpack the list into variables in each respective calc()
method.  I did not see the need for a subst() method.  There is a
complete s-exp parser at the pyparsing wiki examples page:
http://pyparsing.wikispaces.com/space/showimage/sexpParser.py

-- Paul



class WAE(object):
ids = {}
def __init__(self,tokens):
# need to deref element 0 because of Groups
self.tokens = tokens[0]

class NumWAE(WAE):
def calc(self):
return int(self.tokens)

class IdWAE(WAE):
def getId(self):
return self.tokens
def calc(self):
return WAE.ids[self.getId()][-1]

class BinOpWAE(WAE):
def calc(self):
op,a,b = self.tokens
return self.opfn(a.calc(), b.calc())

class AddWAE(BinOpWAE):
opfn = staticmethod(lambda a,b:a+b)

class SubWAE(BinOpWAE):
opfn = staticmethod(lambda a,b:a-b)

class WithWAE(WAE):
def calc(self):
op,varid,varexpr,withexpr = self.tokens
varname = varid.getId()
if varname not in WAE.ids:
WAE.ids[varname] = []
WAE.ids[varname].append( varexpr.calc() )
ret = withexpr.calc()
WAE.ids[varname].pop()
return ret

for expr,cls in zip((num,id_,addwae,subwae,withwae),
 (NumWAE,IdWAE,AddWAE,SubWAE,WithWAE)):
expr.setParseAction(cls)

for t in tests:
print t
waeTree = wae.parseString(t)[0]
print waeTree.calc()
print

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


mysteries of urllib/urllib2

2007-07-03 Thread Adrian Smith
I'm trying to use urllib2 to download a page (I'd rather use urllib,
but I need to change the User-Agent header to look like a browser or
G**gle won't send it to me, the big meanies). The following (pinched
from Dive Into Python) seems to work perfectly in Idle, but falls at
the final hurdle when run as a cgi script - can anyone suggest
anything I may have overlooked?

request = urllib2.Request(some_URL)
request.add_header('User-Agent', 'some_plausible_string')
opener = urllib2.build_opener()
data = opener.open(request).read()

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


Re: Python IRC bot using Twisted

2007-07-03 Thread ddtm
On 3, 16:01, Jean-Paul Calderone <[EMAIL PROTECTED]> wrote:
> On Tue, 03 Jul 2007 09:46:59 -, ddtm <[EMAIL PROTECTED]> wrote:
> >I'm using an example of IRC bot (_ttp://twistedmatrix.com/projects/
> >words/documentation/examples/ircLogBot.py) to create my own bot. But I
> >have a problem. I'm trying to make my bot send messages periodically.
> >But I can't find a way of adding Timer or something similar to my code
> >so that it could work. Could somebody modify an example to make IRC
> >bot send anything to chat every 20 seconds?
>
> >P.S. Timer should not lock the main program (I think it should work in
> >other thread or so)
> >P.P.S. Could somebody write a code of delay between messages too? In
> >pseudocode it looks like this:
> >  sleep(20)
> >  sendMessage(channel,'lopata')
> >This delay should be non-locking too.
> >P.P.P.S. Sorry for my bad English (and for a noob question too)
>
> You can use reactor.callLater to schedule a one-time event to happen at
> some future point:
>
> reactor.callLater(20, sendMessage, channel, 'lopata')
>
> There is also a utility class, twisted.internet.task.LoopingCall, which
> you can use to schedule an event to occur repeatedly at some interval:
>
> call = LoopingCall(sendMessage, channel, 'lopata')
> loopDeferred = call.start(20)
>
> You can read more about these APIs in the scheduling howto:
>
>http://twistedmatrix.com/projects/core/documentation/howto/time.html
>
> Or you can refer to the generated API documentation:
>
> http://twistedmatrix.com/documents/current/api/twisted.internet.inter...http://twistedmatrix.com/documents/current/api/twisted.internet.task
>
> Hope this helps,
>
> Jean-Paul

Thank you very much! It's a very useful information. One more
question: can I cancel the DelayedCall using its ID (it is returned
from callLater(...)) from another function? In example bot there are
two functions:
def joined(self, channel):
  ...
def privmsg(self, user, channel, msg):
  ...
For example, I add callLater(...) to joined(...) function and I'd like
to cancel this in privmsg(...) function. What should I do?

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


Re: The file executing

2007-07-03 Thread Benjamin
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...

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


Re: Portable general timestamp format, not 2038-limited

2007-07-03 Thread Peter J. Holzer
On 2007-07-03 08:57, Richard Heathfield <[EMAIL PROTECTED]> wrote:
> Paul Rubin said:
>> [EMAIL PROTECTED] writes:
>>> As for the primacy of UTC vs. TAI, this is the classical chicken and
>>> egg problem.  The bureaucratic reality is opposed to the physical
>>> reality.
>> 
>> Well, if you're trying to pick just one timestamp standard, I'd say
>> you're better off using a worldwide one rather than a national one, no
>> matter how the bureaucracies work.
>
> In that case, the obvious choice is Greenwich Mean Time.  :-)

Hardly. That hasn't been in use for over 35 years (according to
Wikipedia).


> Seriously, GMT is recognised all over the world (far more so, in fact,
> than UTC, which tends to be recognised only by some well-educated
> people, and there are precious few of those), so why not use it?

While the layman may recognize the term "GMT", he almost certainly means
"UTC" when he's talking about GMT. GMT was based on astronomical
observations and the be best approximation available today is probably
UT1, which may differ from UTC by up to 0.5 seconds.

> I always leave my PC's clock set to GMT,

Your PC is directly linked to an observatory? Impressive :-). If you
synchronize your PC to any external time source, it's almost certainly
UTC, not GMT or UT1. If you don't synchronize it it's so far off that it
doesn't matter.

hp

-- 
   _  | Peter J. Holzer| I know I'd be respectful of a pirate 
|_|_) | Sysadmin WSR   | with an emu on his shoulder.
| |   | [EMAIL PROTECTED] |
__/   | http://www.hjp.at/ |-- Sam in "Freefall"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: what is wrong with that r"\"

2007-07-03 Thread Neil Cerutti
On 2007-07-03, alf <[EMAIL PROTECTED]> wrote:
> question without words:
>
> >>> r"\"
>File "", line 1
>  r"\"
> ^
> SyntaxError: EOL while scanning single-quoted string
> >>> r"\ "
> '\\ '

>From the Python Language Reference 2.4.1 String Literals:

   When an "r" or "R" prefix is present, a character following a
   backslash is included in the string without change, and all
   backslashes are left in the string. For example, the string
   literal r"\n" consists of two characters: a backslash and a
   lowercase "n". String quotes can be escaped with a backslash,
   but the backslash remains in the string; for example, r"\"" is
   a valid string literal consisting of two characters: a
   backslash and a double quote; r"\" is not a valid string
   literal (even a raw string cannot end in an odd number of
   backslashes). Specifically, a raw string cannot end in a
   single backslash (since the backslash would escape the
   following quote character). Note also that a single backslash
   followed by a newline is interpreted as those two characters
   as part of the string, not as a line continuation. 

-- 
Neil Cerutti
Ask about our plans for owning your home --sign at mortgage company
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python IRC bot using Twisted

2007-07-03 Thread Jean-Paul Calderone
On Tue, 03 Jul 2007 13:44:34 -, ddtm <[EMAIL PROTECTED]> wrote:
>On 3, 16:01, Jean-Paul Calderone <[EMAIL PROTECTED]> wrote:
> [snip]
>
>Thank you very much! It's a very useful information. One more
>question: can I cancel the DelayedCall using its ID (it is returned
>from callLater(...)) from another function? In example bot there are
>two functions:
>def joined(self, channel):
>  ...
>def privmsg(self, user, channel, msg):
>  ...
>For example, I add callLater(...) to joined(...) function and I'd like
>to cancel this in privmsg(...) function. What should I do?
>

Yep.  The object callLater returns has a `cancel' method (some others, too)
which will prevent the function from being called at the scheduled time.

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


Re: The file executing

2007-07-03 Thread Sebastian Wiesner
[ 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]

-- 
Freedom is always the freedom of dissenters.
  (Rosa Luxemburg)


signature.asc
Description: This is a digitally signed message part.
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Portable general timestamp format, not 2038-limited

2007-07-03 Thread Richard Heathfield
Peter J. Holzer said:

> On 2007-07-03 08:57, Richard Heathfield <[EMAIL PROTECTED]> wrote:
>> Paul Rubin said:
>>> [EMAIL PROTECTED] writes:
 As for the primacy of UTC vs. TAI, this is the classical chicken
 and
 egg problem.  The bureaucratic reality is opposed to the physical
 reality.
>>> 
>>> Well, if you're trying to pick just one timestamp standard, I'd say
>>> you're better off using a worldwide one rather than a national one,
>>> no matter how the bureaucracies work.
>>
>> In that case, the obvious choice is Greenwich Mean Time.  :-)
> 
> Hardly. That hasn't been in use for over 35 years (according to
> Wikipedia).

Nonsense. I use it every day, and have been doing so for - well, rather 
more than 35 years.

>> Seriously, GMT is recognised all over the world (far more so, in
>> fact, than UTC, which tends to be recognised only by some
>> well-educated people, and there are precious few of those), so why
>> not use it?
> 
> While the layman may recognize the term "GMT", he almost certainly
> means "UTC" when he's talking about GMT.

Most people of my acquaintance who use the term "GMT" mean precisely 
that - Greenwich Mean Time.



>> I always leave my PC's clock set to GMT,
> 
> Your PC is directly linked to an observatory?

Nope. My PC *defines* GMT. If the observatory wants to know what the 
exact time is, they only have to ask.

-- 
Richard Heathfield 
Email: -www. +rjh@
Google users: 
"Usenet is a strange place" - dmr 29 July 1999
-- 
http://mail.python.org/mailman/listinfo/python-list


MySQL -->Python-->XML for JSviz

2007-07-03 Thread Picio
Hello all, I need some advice to choose an xml generator for jsviz a
tool in javascript to create some wonderful graphs (SnowFlake or Force
directed).

Starting from a SQL table (mysql) I need to create a XML file with a
structure like this:

  
  
  
  
  
  


Where nodes attributes are the MySQL table fields (the PK will be the
attribute).
I know there are a lot of good tools to do this in pyhton (some maybe
is already shipped with pyton itself), but since I need a lot of
flexibility for the future I'd like to use an Object relational mapper
like SQLAlchemy or SQLObject todo the job. When I say flexibility, I
have in mind a solution to have multiple formats coming outside of the
ORM:
json, csv, plain text etc...
Am I wrong?
Can someone advice something?

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


Fwd: Infotech Enterprises Limited

2007-07-03 Thread Vivek Kumar
-- Forwarded message --
From: Mahendra <[EMAIL PROTECTED]>
Date: Jul 3, 2007 5:17 PM
Subject: Infotech Enterprises Limited
To: [EMAIL PROTECTED]




Hi

Further to our discussions, We are looking for Python developers/ C++
who are willing to work in Hyderabad. Infotech Enterprises Limited is
a CMMIL5 company with morethan 5500 professionals working in to
Various domains. For further information you can logonto

www.Infotech-Enterprises .com





Regards
Mahendra Rao.A
Human Resources Team
Infotech Enterprises Limited
Email: [EMAIL PROTECTED]
  www.infotech-Enterprises.com

Tel : 040 - 23124040
Plotno - 11; Software units Layout
Madhapur
Hyderabad
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Programming Idiomatic Code

2007-07-03 Thread Douglas Woodrow
On Tue, 3 Jul 2007 10:19:07, Nathan Harmston 
<[EMAIL PROTECTED]> wrote
>
>i m in the UK and dont have the experience but hey 10 minutes of
>programming python beats 12 hours of programming in Clipper-derived
>unreadable drivel (you dont know how much I appreciate Python atm).

"Clipper-derived unreadable drivel"

I'm intrigued, what language are you working in?

Clipper v5 was a pretty impressive development language for 1990 - with 
code blocks, a flexible pre-processor, garbage collection, exception 
handling, decent speed and an API to allow easy integration with 
routines written in c.

It doesn't have to be unreadable at all (unless it's written by someone 
who thinks it is dBase).

-- 
Doug Woodrow

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


Re: Correct abstraction for TK

2007-07-03 Thread Luke Hoersten
Thanks for all the suggestions guys. I'm realizing that I need to
chose more of a specific paradigm. With closures, I was able to stay
away from unneeded classes before but Tk brings it to a whole other
level.

Thanks again,
Luke

On Jul 3, 2:50 am, Paul Rubin  wrote:
> [EMAIL PROTECTED] writes:
> > I'm looking for a good example of how to correctly abstract TK code
> > from the rest of my program. I want to just get some user info and
> > then get 4 values from the GUI. Right now I've written it OOP per the
> > examples on python.org but it doesn't seem to be meshing very well
> > with the rest of my project.
>
> Simplest: just have gui operations call the application code.  The
> application main loop is just the gui event loop.  Example (first tk
> program I ever wrote, and one of my first python programs):
>
>http://www.nightsong.com/phr/python/calc.py
>
> That might be enough for what you're doing.
>
> Fancier: put gui in separate thread.  Be careful, it's not reentrant;
> all communication with the application has to be through queues, sort
> of like writing a miniature web server.  Most straightforward is to
> pass tuples like (function, args, **kwargs) through the queues, where
> the opposite end invokes the function on the arg list.  There are some
> recipes in the Python cookbook for triggering the event loop on a
> periodic timeout from inside tkinter.
>
> See also "model-view-controller" for a more complex design approach
> intended to separate the interface from the application logic.
>
> Finally, consider total separation by embedding an http server in the
> application, so the gui is a web browser and you write a web app.
> It's often easier to code a simple html interface than to mess with
> the damn Tk widgets and trying to get them to look decent on the
> screen, plus it lets you easily put the client on a remote machine,
> support multiple clients simultaneously, etc.


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


Re: mysteries of urllib/urllib2

2007-07-03 Thread Ben Cartwright
On Jul 3, 9:43 am, Adrian Smith <[EMAIL PROTECTED]> wrote:
> The following (pinched
> from Dive Into Python) seems to work perfectly in Idle, but falls at
> the final hurdle when run as a cgi script - can anyone suggest
> anything I may have overlooked?
>
> request = urllib2.Request(some_URL)
> request.add_header('User-Agent', 'some_plausible_string')
> opener = urllib2.build_opener()
> data = opener.open(request).read()

Most likely the account that cgi script is running as does not have
permissions to access the net. Check the traceback to be sure. Put
this at the top of your cgi script:

import cgitb; cgitb.enable()

--Ben

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


allow scripts to use .pth files?

2007-07-03 Thread Alan Isaac
Suppose I have a directory `scripts`.
I'd like the scripts to have access to a package
that is not "installed", i.e., it is not on sys.path.
On this list, various people have described a variety
of tricks they use, but nobody has proposed a 
pretty way to allow this.
I am therefore assuming there is not one. (?)

How about allowing a `scripts.pth` file in such a `scripts`
directory, to work like a path configuration file?
(But to be used only when __name__=="__main__".)
Drawbacks?

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


Re: trouble with sqlite under debian etch

2007-07-03 Thread Gerhard Häring
Rustom Mody wrote:
> I was trying to follow the sqlalchemy tutorial on my debian etch box
> and got stuck with installation.  Any help/pointers will be welcome.
> 
> First after installing sqlalchemy needed some sqlite package
> synaptic showed me packages python-pysqlite, python-pysqlite1.1 and
> python-pysqlite2.
> [...]

Or just use Python 2.5, which includes a "sqlite3" module that 
SQLAlchemy can use.

> Theres some confusion regarding numbers: python-pysqlite2 is for
> sqlite3 or some such thing

the 2 in python-pysqlite2 is for

> Tried python-pysqlite1.1 and got errors. Tried 2 and got version warnings.
> 
> Downloaded the tgz and did a setup build followed by a setup install
> 
> Now the
 db = create_engine('sqlite:///tutorial.db')
> gives me no module _sqlite

Did you execute that in the pysqlite root directory (i. e. the one that 
"setup.py" and friends are?). Unfortunately, any other working directory 
will be ok, but this one isn't.

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


POpen - Wait For Process To Complete

2007-07-03 Thread Robert Rawlins - Think Blue
Hello guys,

 

Quite a simple one I'm hoping. I've got a process that I run using popen
which writes to a file, I'm then going to read the file and parse its
contents. However, getting the application to wait until the process is
complete and finished writing before it reads and parses the file is
becoming complicated.

 

Popen is meant to have a wait() function along with a poll() function
(according to the docs), both of which can be used to make the app wait for
the process to finished, but for some reason I can't get them working, when
I try this:



Import popen2



  Process = popen2.popen4('This is my command to run from cmd')

 

  Process.wait()

 

  f = open('path/to/output/file.txt')

  new = f.read()

  f.close()

 

It throws back the following error to me:

 

push.wait()

AttributeError: 'tuple' object has no attribute 'wait'

 

Which is fair enough as popen4 returns a tuple containing the output streams
from the cmd command, but how the hell can I have it wait so I can read the
physical files?

 

I'll be interested to hear your thoughts guys,

 

Rob

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

python 3.0 or 3000 ....is it worth waiting??? Newbie Question

2007-07-03 Thread [EMAIL PROTECTED]
Hi
I'm considering learning Python...but with the python 3000 comming
very soon, is it worth waiting for?? I know that the old style of
coding python will run parallel with the new, but I mean, its going to
come to an end eventually.

What do you think??
Chris

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


Re: mysteries of urllib/urllib2

2007-07-03 Thread Adrian Smith
On Jul 3, 11:25 pm, Ben Cartwright <[EMAIL PROTECTED]> wrote:
> On Jul 3, 9:43 am, Adrian Smith <[EMAIL PROTECTED]> wrote:
>
> > The following (pinched
> > from Dive Into Python) seems to work perfectly in Idle, but
> > falls at the final hurdle when run as a cgi script - can
> > anyone suggest anything I may have overlooked?
>
> > request = urllib2.Request(some_URL)
> > request.add_header('User-Agent', 'some_plausible_string')
> > opener = urllib2.build_opener()
> > data = opener.open(request).read()
>
> Most likely the account that cgi script is running as does not
> have permissions to access the net. Check the traceback to be
> sure. Put this at the top of your cgi script:
>
> import cgitb; cgitb.enable()

Well, it worked with urllib (resulting in a G**gle 403 your-client-
does-not-have-permission-to-get-urlX page), so I think it must have
some access. Apparently there's a way to change the user-agent string
by subclassing urllib's URLopener class, but that's beyond my comfort
zone at present.

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


Re: python 3.0 or 3000 ....is it worth waiting??? Newbie Question

2007-07-03 Thread Daniel Nogradi
> Hi
> I'm considering learning Python...but with the python 3000 comming
> very soon, is it worth waiting for?? I know that the old style of
> coding python will run parallel with the new, but I mean, its going to
> come to an end eventually.
>
> What do you think??
> Chris


99% of what you would learn from python 2.x will be useful for python 3.0.

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


error return without exception set

2007-07-03 Thread Will McGugan
Hi,

Can anyone suggest a likely cause for the following exception...

Exception exceptions.SystemError: 'error return without exception set' 
in  ignored

Thanks

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


Re: python 3.0 or 3000 ....is it worth waiting??? Newbie Question

2007-07-03 Thread Alex Martelli
[EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:

> I'm considering learning Python...but with the python 3000 comming
> very soon, is it worth waiting for?? I know that the old style of
> coding python will run parallel with the new, but I mean, its going to
> come to an end eventually.

It will be years before Py3k is fully usable for "industrial-strength"
programming: the language itself must stabilize, then the standard
library, then third-party extensions.  And migrating from Python 2.6 to
Python 3000 will be very easy once the latter has all the 3rd party and
standard library modules you need -- just as moving from 2.5 to 2.6 will
be.  So, there's really no reason to wait: start learning Python with
2.5, the solid implementation available right now and with tons of 3rd
party extensions, tools, etc, and there will just be tiny amounts of
effort required to eventually move up a long time in the future.


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


Re: mysteries of urllib/urllib2

2007-07-03 Thread Ben Cartwright
On Jul 3, 11:14 am, Adrian Smith <[EMAIL PROTECTED]> wrote:
> > > The following (pinched
> > > from Dive Into Python) seems to work perfectly in Idle, but
> > > falls at the final hurdle when run as a cgi script
> > Put this at the top of your cgi script:
>
> > import cgitb; cgitb.enable()

Did you even try this?  Asking for Python help without posting the
traceback is like phoning your mechanic and saying, "My car is making
a generic rattling noise, can you tell me what the problem is without
looking under the hood?"

> Apparently there's a way to change the user-agent string
> by subclassing urllib's URLopener class, but that's beyond my comfort
> zone at present.

Untested:

import urllib
url = 'http://groups.google.com/group/Google-AJAX-Search-API/
browse_thread/thread/a0eb87ad13b11762'
opener = urllib.FancyURLopener()
opener.addheaders = [('User-Agent', 'Fauxzilla 4.0')]
data = opener.open(url).read()

Hope that helps,
--Ben

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


Re: ebay

2007-07-03 Thread jim
On 6 20 ,   11 20 , jim <[EMAIL PROTECTED]> wrote:
> hello: madam and sir . we sell all kinds of laptops and digital
> cam .our product is a quantity best, the price is the lowest in the
> world, i think you will be interested in our product . thanks a lot!
> Our Website:http://www.prs-123.com/Msn: [EMAIL PROTECTED]
> mail: [EMAIL PROTECTED] thanks for everyone good luck with
> everyone . @@@ hello : madam
> and sir. we sell all kinds of laptops and digital cam .our product is
> a quantity best, the price is the lowest in the world, i think you
> will be interested in our product . thanks a lot! Our 
> Website:http://www.prs-123.com/Msn: [EMAIL PROTECTED] mail:
> [EMAIL PROTECTED] thanks for everyone good luck with everyone
> @ hello: madam and sir .
> we sell all kinds of laptops and digital cam .our product is a
> quantity best, the price is the lowest in the world, i think you will
> be interested in our product . thanks a lot! Our 
> Website:http://www.prs-123.com/Msn: [EMAIL PROTECTED] mail:
> [EMAIL PROTECTED] thanks for everyone good luck with
> everyone . @@@ hello : madam and
> sir. we sell all kinds of laptops and digital cam .our product is a
> quantity best, the price is the lowest in the world, i think you will
> be interested in our product . thanks a lot! Our 
> Website:http://www.prs-123.com/Msn: [EMAIL PROTECTED] mail:
> [EMAIL PROTECTED] thanks for everyone good luck with everyone
> hello: madam and sir . we sell all kinds of laptops and digital
> cam .our product is a quantity best, the price is the lowest in the
> world, i think you will be interested in our product . thanks a lot!
> Our Website:http://www.prs-123.com/Msn: [EMAIL PROTECTED]
> mail: [EMAIL PROTECTED] thanks for everyone good luck with
> everyone . @@@ hello : madam
> and sir. we sell all kinds of laptops and digital cam .our product is
> a quantity best, the price is the lowest in the world, i think you
> will be interested in our product . thanks a lot! Our 
> Website:http://www.prs-123.com/Msn: [EMAIL PROTECTED] mail:
> [EMAIL PROTECTED] thanks for everyone good luck with everyone
> @ hello: madam and sir .
> we sell all kinds of laptops and digital cam .our product is a
> quantity best, the price is the lowest in the world, i think you will
> be interested in our product . thanks a lot! Our 
> Website:http://www.prs-123.com/Msn: [EMAIL PROTECTED] mail:
> [EMAIL PROTECTED] thanks for everyone good luck with
> everyone . @@@ hello : madam and
> sir. we sell all kinds of laptops and digital cam .our product is a
> quantity best, the price is the lowest in the world, i think you will
> be interested in our product . thanks a lot! Our 
> Website:http://www.prs-123.com/Msn: [EMAIL PROTECTED] mail:
> [EMAIL PROTECTED] thanks for everyone good luck with everyone
> hello: madam and sir . we sell all kinds of laptops and digital
> cam .our product is a quantity best, the price is the lowest in the
> world, i think you will be interested in our product . thanks a lot!
> Our Website:http://www.prs-123.com/Msn: [EMAIL PROTECTED]
> mail: [EMAIL PROTECTED] thanks for everyone good luck with
> everyone . @@@ hello : madam
> and sir. we sell all kinds of laptops and digital cam .our product is
> a quantity best, the price is the lowest in the world, i think you
> will be interested in our product . thanks a lot! Our 
> Website:http://www.prs-123.com/Msn: [EMAIL PROTECTED] mail:
> [EMAIL PROTECTED] thanks for everyone good luck with everyone
> @ hello: madam and sir .
> we sell all kinds of laptops and digital cam .our product is a
> quantity best, the price is the lowest in the world, i think you will
> be interested in our product . thanks a lot! Our 
> Website:http://www.prs-123.com/Msn: [EMAIL PROTECTED] mail:
> [EMAIL PROTECTED] thanks for everyone good luck with
> everyone . @@@ hello : madam and
> sir. we sell all kinds of laptops and digital cam .our product is a
> quantity best, the price is the lowest in the world, i think you will
> be interested in our product . thanks a lot! Our 
> Website:http://www.prs-123.com/Msn: [EMAIL PROTECTED] mail:
> [EMAIL PROTECTED] thanks for everyone good luck with everyone
> hello: madam and sir . we sell all kinds of laptops and digital
> cam .our product is a quantity best, the price is the lowest in the
> world, i think you will be interested in our product . thanks a lot!
> Our Website:http://www.prs-123.com/Msn: [EMAIL PROTECTED]
> mail: [EMAIL PROTECTED] thanks for everyone good luck with
> everyone . @@@ hello : madam
> and sir. we sell all kinds of laptops and digital cam .our product is
> a 

Re: python 3.0 or 3000 ....is it worth waiting??? Newbie Question

2007-07-03 Thread Jean-Paul Calderone
On Tue, 03 Jul 2007 15:13:46 -, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> 
wrote:
>Hi
>I'm considering learning Python...but with the python 3000 comming
>very soon, is it worth waiting for?? I know that the old style of
>coding python will run parallel with the new, but I mean, its going to
>come to an end eventually.
>
>What do you think??
>Chris

Python 3000 doesn't include many significant changes to the language.  If
you learn Python 2.x, almost all of what you learn will be applicable to
Python 3.x, if you ever choose to switch to it.  Since the Python development
team have promised tools for porting code and a Python 2.6 which will be
completely backwards compatible with Python 2.5 as well as provide feedback
about code which will not be compatible with Python 3.x
(), you'll be able to
convert any code you write for Python 2.x into Python 3.x code easily.

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


Re: Python IRC bot using Twisted

2007-07-03 Thread ddtm
On 3, 17:55, Jean-Paul Calderone <[EMAIL PROTECTED]> wrote:
> On Tue, 03 Jul 2007 13:44:34 -, ddtm <[EMAIL PROTECTED]> wrote:
> >On 3, 16:01, Jean-Paul Calderone <[EMAIL PROTECTED]> wrote:
> > [snip]
>
> >Thank you very much! It's a very useful information. One more
> >question: can I cancel the DelayedCall using its ID (it is returned
> >from callLater(...)) from another function? In example bot there are
> >two functions:
> >def joined(self, channel):
> >  ...
> >def privmsg(self, user, channel, msg):
> >  ...
> >For example, I add callLater(...) to joined(...) function and I'd like
> >to cancel this in privmsg(...) function. What should I do?
>
> Yep.  The object callLater returns has a `cancel' method (some others, too)
> which will prevent the function from being called at the scheduled time.
>
> Jean-Paul

I know what you are talking about, but the question is: How can I
cancel scheduled task in function that differs from
function where I scheduled the task? Demo bot on Twisted website has a
class with a bunch of predefined functions joined(...), privmsg(...)
and so on. I can't see any method of communicating these functions.
I'm new to Python and to Twisted framework.
The task is:
to call callLater(...) in joined(...)
to cancel the task in privmsg(...) on special condition

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


Re: Debugging "broken pipe" (in telnetlib)

2007-07-03 Thread Samuel
On Jul 3, 3:03 pm, Jean-Paul Calderone <[EMAIL PROTECTED]> wrote:
> EPIPE results when writing to a socket for which writing has been shutdown.
> This most commonly occurs when the socket has closed.  You need to handle
> this exception, since you can't absolutely prevent the socket from being
> closed.

The exception is already caught and logged, but this is really not
good enough. By "handling this exception", do you mean that there is a
way to handle it such that the connection still works? I found some
code that attempts to retry when SIGPIPE was received, but this only
results in the same error all over again.
Why can this not be prevented (in the general case)? Unless something
fancy happened, what can cause the socket to close? Looking at the raw
data received by the connected host, the connection gets lost in mid-
stream; I can not see anything that might cause the remote side to
close the connection (in which case I'd expect a "connection reset by
peer" or something).

> There might be some other change which would be appropriate, though,
> if it is the case that something your application is doing is causing the
> socket to be closed (for example, sending a message which the remote side
> decides is invalid and causing it to close the socket explicitly from its
> end).

The program is doing the same thing repeatedly and it works 95% of the
time, so I am fairly sure that nothing special is sent.

> It's difficult to make any specific suggestions in that area without
> knowing exactly what your program does.

Unfortunately the application is rather complex and a simple test case
is not possible.

Basically, it creates a number of daemon threads, each of which
creates a (thread local, non-shared) instance of telnetlib and
connects to a remote host. Are there any special conditions that must
be taken care of when opening a number of sockets in threads? (The
code runs on AIX 4.1, where Python supports native OS threads.)

-Samuel

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


ANN: Leo 4.4.3.1 released

2007-07-03 Thread Edward K Ream
Leo 4.4.3.1 is available at:
http://sourceforge.net/project/showfiles.php?group_id=3458&package_id=29106

Leo is a text editor, data organizer, project manager and much more. See:
http://webpages.charter.net/edreamleo/intro.html

The highlights of Leo 4.4.3.1:

- Fixed a few minor bugs reported since Leo 4.4.3 was released.
- Added better support for unit testing in Leo.

Links:
--
Leo:  http://webpages.charter.net/edreamleo/front.html
Home: http://sourceforge.net/projects/leo/
Download: http://sourceforge.net/project/showfiles.php?group_id=3458
CVS:  http://leo.tigris.org/source/browse/leo/
Quotes:   http://webpages.charter.net/edreamleo/testimonials.html

Edward

Edward K. Ream   email:  [EMAIL PROTECTED]
Leo: http://webpages.charter.net/edreamleo/front.html




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


Re: Python IRC bot using Twisted

2007-07-03 Thread Jean-Paul Calderone
On Tue, 03 Jul 2007 15:51:30 -, ddtm <[EMAIL PROTECTED]> wrote:
>On 3, 17:55, Jean-Paul Calderone <[EMAIL PROTECTED]> wrote:
>> On Tue, 03 Jul 2007 13:44:34 -, ddtm <[EMAIL PROTECTED]> wrote:
>> >On 3, 16:01, Jean-Paul Calderone <[EMAIL PROTECTED]> wrote:
>> > [snip]
>>
>> >Thank you very much! It's a very useful information. One more
>> >question: can I cancel the DelayedCall using its ID (it is returned
>> >from callLater(...)) from another function? In example bot there are
>> >two functions:
>> >def joined(self, channel):
>> >  ...
>> >def privmsg(self, user, channel, msg):
>> >  ...
>> >For example, I add callLater(...) to joined(...) function and I'd like
>> >to cancel this in privmsg(...) function. What should I do?
>>
>> Yep.  The object callLater returns has a `cancel' method (some others, too)
>> which will prevent the function from being called at the scheduled time.
>>
>> Jean-Paul
>
>I know what you are talking about, but the question is: How can I
>cancel scheduled task in function that differs from
>function where I scheduled the task? Demo bot on Twisted website has a
>class with a bunch of predefined functions joined(...), privmsg(...)
>and so on. I can't see any method of communicating these functions.
>I'm new to Python and to Twisted framework.
>The task is:
>to call callLater(...) in joined(...)
>to cancel the task in privmsg(...) on special condition

You need to preserve a reference to the object.  For example:

class IRCBot(Whatever):
def joined(...):
self.announceJoinedCall = reactor.callLater(...)

def privmsg(...):
self.announceJoinedCall.cancel()
self.announceJoinedCall = None

This skips over a bunch of details (what happens on multiple calls to
joined, what happens if privmsg is called after announceJoinedCall has
run, etc) but I hope it demonstrates the basic idea.

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


Re: Pretty Scheme, ??? Python

2007-07-03 Thread Neil Cerutti
On 2007-07-03, Paul McGuire <[EMAIL PROTECTED]> wrote:
> Here is my alternative solution (not using results names).  I used
> the base WAE class to accept the tokens as the initialization var,
> then unpack the list into variables in each respective calc()
> method.  I did not see the need for a subst() method. 

I used recursion to effect substitution of id's with their
values, whereas you chose to use a dictionary of stacks. I prefer
the functional solution for being simpler, and state-less.

Thanks for the nice example. I think I've seen enough to create
something satisfying.

There seems to be a bug in my current grammar. The factory for
BinOp is not getting the correct named results. Can you see
something I've messed up?

LPAR = Literal("(").suppress()
RPAR = Literal(")").suppress()

wae = Forward()
num = Word(nums).setResultsName('number')
id_ = Word(alphas).setResultsName('name')

binop = Group( LPAR + oneOf("+ -").setResultsName('op') + 
wae.setResultsName('lhs') + wae.setResultsName('rhs') + RPAR )
with_ = Group( LPAR + "with" + LPAR + id_.setResultsName('bound_id') + 
wae.setResultsName('named_expr') + RPAR + 
wae.setResultsName('bound_body') + RPAR )

wae << (binop | with_ | num | id_)

num.setParseAction(lambda t: Num(int(t.number)))
id_.setParseAction(lambda t: Id(t.name))
binop.setParseAction(lambda t: BinOp(t.op, t.lhs, t.rhs))
with_.setParseAction(lambda t: With(t.bound_id, t.named_expr, t.bound_body))

def parse(s):
return (wae + StringEnd()).parseString(s).asList()[0]

For test case:

 '(+ 3 45)'

I get:

C:\WINNT\system32\cmd.exe /c python wae.py
**
File "wae.py", line 6, in __main__
Failed example:
parse('(+ 3 45)')
Exception raised:
Traceback (most recent call last):
  File "c:\edconn32\python25\lib\doctest.py", line 1212, in __run
compileflags, 1) in test.globs
  File "", line 1, in 
parse('(+ 3 45)')
  File "wae.py", line 122, in parse
return (wae + StringEnd()).parseString(s).asList()[0]
  File "C:\edconn32\Python25\Lib\site-packages\pyparsing.py", line 906, in p
arseString
loc, tokens = self._parse( instring.expandtabs(), 0 )
  File "C:\edconn32\Python25\Lib\site-packages\pyparsing.py", line 784, in _
parseNoCache
loc,tokens = self.parseImpl( instring, preloc, doActions )
  File "C:\edconn32\Python25\Lib\site-packages\pyparsing.py", line 1961, in
parseImpl
loc, resultlist = self.exprs[0]._parse( instring, loc, doActions, callPr
eParse=False )
  File "C:\edconn32\Python25\Lib\site-packages\pyparsing.py", line 784, in _
parseNoCache
loc,tokens = self.parseImpl( instring, preloc, doActions )
  File "C:\edconn32\Python25\Lib\site-packages\pyparsing.py", line 2204, in
parseImpl
return self.expr._parse( instring, loc, doActions, callPreParse=False )
  File "C:\edconn32\Python25\Lib\site-packages\pyparsing.py", line 784, in _
parseNoCache
loc,tokens = self.parseImpl( instring, preloc, doActions )
  File "C:\edconn32\Python25\Lib\site-packages\pyparsing.py", line 2070, in
parseImpl
ret = e._parse( instring, loc, doActions )
  File "C:\edconn32\Python25\Lib\site-packages\pyparsing.py", line 810, in _
parseNoCache
tokens = fn( instring, tokensStart, retTokens )
  File "C:\edconn32\Python25\Lib\site-packages\pyparsing.py", line 658, in t
mp
return f(t)
  File "wae.py", line 118, in 
binop.setParseAction(lambda t: BinOp(t.op, t.lhs, t.rhs))
  File "wae.py", line 73, in __init__
'-': (operator.sub, 'Sub')}[op]
KeyError: ''
**

op ought to be '+' or '-'. In fact, testing showed than none of
the result names for binop are being set correctly.

-- 
Neil Cerutti
The word "genius" isn't applicable in football. A genius is a guy like Norman
Einstein. --Joe Theisman
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: MySQL -->Python-->XML for JSviz

2007-07-03 Thread Sells, Fred
Sometimes sneaky is better than elegant.  You could shell down to a command
line invocation of mysql and specify -xml as the output format.  I'm not
sure how close that format is to what you need or how much you could
leverage views (if using mysql 5.0). You could also use a command line xslt
processor to then redefine your xml output.  That way your data extraction
is one task and you could have many xsl files to convert as needed.

I have used parts of this technique and found it easy to create and debug;
but I have not used the xml output option of mysql.

I'm sure others will point out many excellent xml modules.

> -Original Message-
> From: [EMAIL PROTECTED]
> [mailto:[EMAIL PROTECTED]
> Behalf Of Picio
> Sent: Tuesday, July 03, 2007 10:08 AM
> To: python-list@python.org
> Subject: MySQL -->Python-->XML for JSviz
> 
> 
> Hello all, I need some advice to choose an xml generator for jsviz a
> tool in javascript to create some wonderful graphs (SnowFlake or Force
> directed).
> 
> Starting from a SQL table (mysql) I need to create a XML file with a
> structure like this:
> 
>   
>   
>   
>   
>   
>   
> 
> 
> Where nodes attributes are the MySQL table fields (the PK will be the
> attribute).
> I know there are a lot of good tools to do this in pyhton (some maybe
> is already shipped with pyton itself), but since I need a lot of
> flexibility for the future I'd like to use an Object relational mapper
> like SQLAlchemy or SQLObject todo the job. When I say flexibility, I
> have in mind a solution to have multiple formats coming outside of the
> ORM:
> json, csv, plain text etc...
> Am I wrong?
> Can someone advice something?
> 
> -- 
> http://mail.python.org/mailman/listinfo/python-list
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Debugging "broken pipe" (in telnetlib)

2007-07-03 Thread Jean-Paul Calderone
On Tue, 03 Jul 2007 08:54:25 -0700, Samuel <[EMAIL PROTECTED]> wrote:
>On Jul 3, 3:03 pm, Jean-Paul Calderone <[EMAIL PROTECTED]> wrote:
>> EPIPE results when writing to a socket for which writing has been shutdown.
>> This most commonly occurs when the socket has closed.  You need to handle
>> this exception, since you can't absolutely prevent the socket from being
>> closed.
>
>The exception is already caught and logged, but this is really not
>good enough. By "handling this exception", do you mean that there is a
>way to handle it such that the connection still works? I found some
>code that attempts to retry when SIGPIPE was received, but this only
>results in the same error all over again.

No, the exception indicates the connection is gone.  There is no way to
continue to transfer data using it.

>Why can this not be prevented (in the general case)? Unless something
>fancy happened, what can cause the socket to close? Looking at the raw
>data received by the connected host, the connection gets lost in mid-
>stream; I can not see anything that might cause the remote side to
>close the connection (in which case I'd expect a "connection reset by
>peer" or something).

It is the nature of TCP/IP that the connection might disappear at any
moment.  The reasons for this vary from someone explicitly calling the
close or shutdown API to a wire being unplugged somewhere between the
two communicating hosts to a traffic event which results in there being
insufficient physical resources to satisfy your particular connection, and
so on and so on.

It may be the case that whatever is causing your connection to be dropped
is entirely avoidable (I can't say, since I don't know what is causing your
connection to be dropped), but all of these other causes are not avoidable,
and your program might encounter one of them someday.

>
>> There might be some other change which would be appropriate, though,
>> if it is the case that something your application is doing is causing the
>> socket to be closed (for example, sending a message which the remote side
>> decides is invalid and causing it to close the socket explicitly from its
>> end).
>
>The program is doing the same thing repeatedly and it works 95% of the
>time, so I am fairly sure that nothing special is sent.
>
>> It's difficult to make any specific suggestions in that area without
>> knowing exactly what your program does.
>
>Unfortunately the application is rather complex and a simple test case
>is not possible.

I used to bother to spend days or weeks trying to track down a subtle bug
in a complex system, but I don't anymore. ;)  It's much better to spend
that time simplifying the software which exhibits the problem until it is
simple enough to understand and make the bug obvious.  Unit testing and
test-driven development have the advantage of pressuring you to write
code which is already split into simple enough pieces that this is usually
a relatively painless process.  For systems not written with this in mind,
it can be quite unpleasant to produce a simple example, but it's ultimately
still worthwhile.

>
>Basically, it creates a number of daemon threads, each of which
>creates a (thread local, non-shared) instance of telnetlib and
>connects to a remote host. Are there any special conditions that must
>be taken care of when opening a number of sockets in threads? (The
>code runs on AIX 4.1, where Python supports native OS threads.)

Oops.  Threads.  So there's a million possible bugs.  Oops AIX, heh,
that probably introduces another million.  I don't know of anything
specifically broken in Python tied to telnetlib and threading on AIX,
no, but that just leaves you with the usual suspects.

Since I don't have any further specific advice to give you in tracking
down this problem, maybe I'll just recommend that you take a look at
Twisted, which has a better (although probably somewhat harder to grasp)
telnet library, and will let you manage numerous connections without
threads.  (Of course, if you have a large existing system then switching
to something as drastically different as Twisted might not be an option,
but it doesn't hurt to suggest it.)

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


wxPython Cannot convert from the charset 'latin-1'

2007-07-03 Thread Helmut Jarausch
Hi,

I'm trying to teach  "dugui.py" (a tiny GUI for restructuredtext written in 
wxPython) to accept files in isolatin-1 encoding.  It displays e.g. German 
umlauts correctly but then I get a popup window saying
Python Error
Cannot convert from the charset 'latin-1'!

How can I find out where this did come from. Running it under pdb
isn't helpful either.

Many thanks for a hint,

Helmut Jarausch

Lehrstuhl fuer Numerische Mathematik
RWTH - Aachen University
D 52056 Aachen, Germany
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Pretty Scheme, ??? Python

2007-07-03 Thread Paul McGuire
On Jul 3, 11:08 am, Neil Cerutti <[EMAIL PROTECTED]> wrote:
>
> C:\WINNT\system32\cmd.exe /c python wae.py
> **
> File "wae.py", line 6, in __main__
> Failed example:
> parse('(+ 3 45)')
> Exception raised:
> Traceback (most recent call last):
>   File "c:\edconn32\python25\lib\doctest.py", line 1212, in __run
> compileflags, 1) in test.globs
>   File "", line 1, in 
> parse('(+ 3 45)')
>   File "wae.py", line 122, in parse
> return (wae + StringEnd()).parseString(s).asList()[0]
>   File "C:\edconn32\Python25\Lib\site-packages\pyparsing.py", line 906, 
> in p
> arseString
> loc, tokens = self._parse( instring.expandtabs(), 0 )
>   File "C:\edconn32\Python25\Lib\site-packages\pyparsing.py", line 784, 
> in _
> parseNoCache
> loc,tokens = self.parseImpl( instring, preloc, doActions )
>   File "C:\edconn32\Python25\Lib\site-packages\pyparsing.py", line 1961, 
> in
> parseImpl
> loc, resultlist = self.exprs[0]._parse( instring, loc, doActions, 
> callPr
> eParse=False )
>   File "C:\edconn32\Python25\Lib\site-packages\pyparsing.py", line 784, 
> in _
> parseNoCache
> loc,tokens = self.parseImpl( instring, preloc, doActions )
>   File "C:\edconn32\Python25\Lib\site-packages\pyparsing.py", line 2204, 
> in
> parseImpl
> return self.expr._parse( instring, loc, doActions, callPreParse=False 
> )
>   File "C:\edconn32\Python25\Lib\site-packages\pyparsing.py", line 784, 
> in _
> parseNoCache
> loc,tokens = self.parseImpl( instring, preloc, doActions )
>   File "C:\edconn32\Python25\Lib\site-packages\pyparsing.py", line 2070, 
> in
> parseImpl
> ret = e._parse( instring, loc, doActions )
>   File "C:\edconn32\Python25\Lib\site-packages\pyparsing.py", line 810, 
> in _
> parseNoCache
> tokens = fn( instring, tokensStart, retTokens )
>   File "C:\edconn32\Python25\Lib\site-packages\pyparsing.py", line 658, 
> in t
> mp
> return f(t)
>   File "wae.py", line 118, in 
> binop.setParseAction(lambda t: BinOp(t.op, t.lhs, t.rhs))
>   File "wae.py", line 73, in __init__
> '-': (operator.sub, 'Sub')}[op]
> KeyError: ''
> **
>
> op ought to be '+' or '-'. In fact, testing showed than none of
> the result names for binop are being set correctly.
>
> --
> Neil Cerutti
> The word "genius" isn't applicable in football. A genius is a guy like Norman
> Einstein. --Joe Theisman

I think the problem is with your Groups, that they are wrapping the
ParseResults into a single-element list.  Try either of the following
(but not both!):
1. Remove Group from the definitions of binop and with_.

binop = ( LPAR + oneOf("+ -").setResultsName('op') +
wae.setResultsName('lhs') + wae.setResultsName('rhs') +
RPAR )
with_ = ( LPAR + "with" + LPAR + id_.setResultsName('bound_id') +
wae.setResultsName('named_expr') + RPAR +
wae.setResultsName('bound_body') + RPAR )

2. Change the parse actions to deref the 0'th element of t for binop
and with_.

num.setParseAction(lambda t: Num(int(t.number)))
id_.setParseAction(lambda t: Id(t.name))
binop.setParseAction(lambda t: BinOp(t[0].op, t[0].lhs, t[0].rhs))
with_.setParseAction(lambda t: With(t[0].bound_id, t[0].named_expr,
t[0].bound_body))

As a troubleshooting measure, you can also create an explicit method,
and then decorate it with pyparsing's built-in @traceParseAction
decorator.

@traceParseAction
def test(t):
return BinOp(t.op,t.lhs,t.rhs)

This should print out information on the arguments being passed to
test, and the results being returned.

-- Paul

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


Re: mysteries of urllib/urllib2

2007-07-03 Thread John Nagle
Adrian Smith wrote:
> I'm trying to use urllib2 to download a page (I'd rather use urllib,
> but I need to change the User-Agent header to look like a browser or
> G**gle won't send it to me, the big meanies). The following (pinched
> from Dive Into Python) seems to work perfectly in Idle, but falls at
> the final hurdle when run as a cgi script - can anyone suggest
> anything I may have overlooked?
> 
> request = urllib2.Request(some_URL)
> request.add_header('User-Agent', 'some_plausible_string')
> opener = urllib2.build_opener()
> data = opener.open(request).read()

I doubt that's the problem here, but don't use a USER-AGENT string
that ends in "m" without a preceding "m" when the USER-AGENT
string is the last element of the header.  Coyote Point load balancers
will drop the packet.

(Coyote Point uses regular expressions to parse HTTP headers, and
I think somebody wrote "\m" where they meant "\n".)

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


Re: POpen - Wait For Process To Complete

2007-07-03 Thread Yongjian Xu

That's by using the P3/P4 classes not the function. the function does not
provide wait() call, it simply does it for you by default.

Jim

On 7/3/07, Robert Rawlins - Think Blue <[EMAIL PROTECTED]>
wrote:


Hello guys,



Quite a simple one I'm hoping. I've got a process that I run using popen
which writes to a file, I'm then going to read the file and parse its
contents. However, getting the application to wait until the process is
complete and finished writing before it reads and parses the file is
becoming complicated.



Popen is meant to have a wait() function along with a poll() function
(according to the docs), both of which can be used to make the app wait for
the process to finished, but for some reason I can't get them working, when
I try this:



Import popen2



  Process = popen2.popen4('This is my command to run from
cmd')



  Process.wait()



  f = open('path/to/output/file.txt')

  new = f.read()

  f.close()



It throws back the following error to me:



push.wait()

AttributeError: 'tuple' object has no attribute 'wait'



Which is fair enough as popen4 returns a tuple containing the output
streams from the cmd command, but how the hell can I have it wait so I can
read the physical files?



I'll be interested to hear your thoughts guys,



Rob

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





--
Yongjian (Jim) Xu
===
Sysops
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Pretty Scheme, ??? Python

2007-07-03 Thread Paul McGuire
By the way, the next release of pyparsing will allow you to shortcut
all of these .setResultsName calls, using this notation instead:

binop = ( LPAR +
oneOf("+ -")('op') +
wae('lhs') +
wae('rhs') + RPAR )
with_ = ( LPAR + "with" + LPAR +
id_('bound_id') +
wae('named_expr') + RPAR +
wae('bound_body') + RPAR )

This is implemented in the latest version in the SF SVN repository.

-- Paul

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


Re: Portable general timestamp format, not 2038-limited

2007-07-03 Thread sla29970
On Jul 3, 1:10 am, Paul Rubin  wrote:
> Well, if you're trying to pick just one timestamp standard, I'd say
> you're better off using a worldwide one rather than a national one, no
> matter how the bureaucracies work.  TAI is derived from atomic clocks
> all over the world, while the national metrology labs are more subject
> to error and desynchronization, and whatever legal primacy they have
> is good in only one country.

For the purposes of an operational system there is an important
difference between a time scale which is practically available in real
time and a time scale which is not available until next month.  There
is no available source for TAI, and in the current scheme of things
there cannot be one for there is no mechanism for distributing it.

There are two reasonably reliable worldwide time sources right now:
Russia's GLONASS and US GPS.  GPS time is based on UTC(USNO).
UTC(USNO) is TA(USNO) minus leap seconds.  Note that is TA(USNO), not
TAI(USNO), for USNO cannot define anything named TAI.

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


python app to emulate terminal to dialup bulletin board

2007-07-03 Thread Sells, Fred
We need to automate the download of data that is now done manually via a
terminal session to a dialup bulletin board.  The user uses this to upload
and download files.  Hard to believe in this day and age, but true.

I've tried google, but the terms are just too common; all I get is clutter.

So I need a python module (or snippets) that:
1. setup and execute a standard dialup with appropriate parity,
stop-bits, etc
2. can emulate hyperterm including sending and receiving files

I know anything worth doing has already been done in python by someone, but
I have not had much luck finding it.  Perhaps I just don't know the best
words to put into google.

can I get a few helpful links for y'all.

thanks.



---
The information contained in this message may be privileged and / or
confidential and protected from disclosure. If the reader of this message is
not the intended recipient, you are hereby notified that any dissemination,
distribution or copying of this communication is strictly prohibited. If you
have received this communication in error, please notify the sender
immediately by replying to this message and deleting the material from any
computer.
---
-- 
http://mail.python.org/mailman/listinfo/python-list


PyObjC and Xcode

2007-07-03 Thread Horace Enea
I'm trying to use Python on a Mac running OSX 10.4.9. I installed Python 
2.5 along with Idle. My problem is that Xcode no longer works with 
PyObjC. It gives an error message: ImportError: No module named 
PyObjCTools. I've down-loaded PyObjC and re-installed it along with 
PyObjCTools, but still get the same error from Xcode. Any suggestions?

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


Re: Pretty Scheme, ??? Python

2007-07-03 Thread Neil Cerutti
On 2007-07-03, Paul McGuire <[EMAIL PROTECTED]> wrote:
> 2. Change the parse actions to deref the 0'th element of t for
> binop and with_.
>
> num.setParseAction(lambda t: Num(int(t.number)))
> id_.setParseAction(lambda t: Id(t.name))
> binop.setParseAction(lambda t: BinOp(t[0].op, t[0].lhs, t[0].rhs))
> with_.setParseAction(lambda t: With(t[0].bound_id, t[0].named_expr,
> t[0].bound_body))

Thanks, that solves it.

Now to get on with this exercise and find out which version turns
out to be easier to modify and extend as the book progresses
through all the different programming language features it
covers. Scheme is bound to have an unfair advantage, though, as
the book was composed for Scheme.

I plan to see if I can create a class factory that behaves like
the define-type macro, though. That should prove rather useful.
The most tedious thing about the Python version is the cruft
required by the class hierarchy.

-- 
Neil Cerutti
I pulled into a lay-by with smoke coming from under the bonnet. I realized the
car was on fire so took my dog and smothered it with a blanket. --Insurance
Claim Blooper
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: allow scripts to use .pth files?

2007-07-03 Thread half . italian
On Jul 3, 7:35 am, Alan Isaac <[EMAIL PROTECTED]> wrote:
> Suppose I have a directory `scripts`.
> I'd like the scripts to have access to a package
> that is not "installed", i.e., it is not on sys.path.
> On this list, various people have described a variety
> of tricks they use, but nobody has proposed a
> pretty way to allow this.
> I am therefore assuming there is not one. (?)
>
> How about allowing a `scripts.pth` file in such a `scripts`
> directory, to work like a path configuration file?
> (But to be used only when __name__=="__main__".)
> Drawbacks?
>
> Alan Isaac

import sys
sys.path.append("../scripts")

import Module_from_scripts_dir

~Sean

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


Re: object references/memory access

2007-07-03 Thread John Nagle
dlomsak wrote:
> Paul Rubin wrote:
> 
>>dlomsak <[EMAIL PROTECTED]> writes:
>>
>>>knowledge of the topic to help. If the above are not possible but you
>>>have a really good idea for zipping large amounts of data from one
>>>program to another, I'd like to hear it.

> Well, I was using the regular pickle at first but then I switched to
> just using repr() / eval() because the resulting string doesn't have
> all the extra 's1=' and all that so it cuts down on the amount of data
> I have to send for large returns when you cut out all of that
> formatting. The speed of the above method is pretty high even for
> really large returns and it works fine for a list of dictionaries.

 OK, that's where the time is going.  It's not the interprocess
communication cost, it's the marshalling cost.  "repr/eval" is not
an efficient way to marshall.   Try using "pack" and "unpack", if
you control both ends of the connection.

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


Re: wxPython Cannot convert from the charset 'latin-1'

2007-07-03 Thread kyosohma
On Jul 3, 11:16 am, Helmut Jarausch <[EMAIL PROTECTED]> wrote:
> Hi,
>
> I'm trying to teach  "dugui.py" (a tiny GUI for restructuredtext written in
> wxPython) to accept files in isolatin-1 encoding.  It displays e.g. German
> umlauts correctly but then I get a popup window saying
> Python Error
> Cannot convert from the charset 'latin-1'!
>
> How can I find out where this did come from. Running it under pdb
> isn't helpful either.
>
> Many thanks for a hint,
>
> Helmut Jarausch
>
> Lehrstuhl fuer Numerische Mathematik
> RWTH - Aachen University
> D 52056 Aachen, Germany

Probably your best bet is to post wxPython specific questions to the
wxPython user's group: http://www.wxpython.org/maillist.php

But I did a little Google-fu and found this for you:

http://wiki.wxpython.org/index.cgi/UnicodeBuild

Mike

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


Re: python 3.0 or 3000 ....is it worth waiting??? Newbie Question

2007-07-03 Thread M�ta-MCI
Hi!

> Python 3000 doesn't include many significant changes to the language

One exemple : non-Ascii characters in identifiers (= no significatif 
change?)


Michel Claveau


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


Re: how to send files via bluetooth with python to a mobile

2007-07-03 Thread Drex
Hi, I tried the example from the site
http://dev.zuckschwerdt.org/openobex/wiki/ObexFtpExampleClientPython

but I am getting the following error:

 /home/daniel/projekty/_moje/python/send_txt_to_mobile.py
Traceback (most recent call last):
 File "/home/daniel/projekty/_moje/python/send_txt_to_mobile.py", line
5, in
devs = cli.discover();
 File "/usr/local/lib/python2.5/site-packages/obexftp/__init__.py",
line 37, in
__getattr__ = lambda self, name: _swig_getattr(self, client, name)
 File "/usr/local/lib/python2.5/site-packages/obexftp/__init__.py",
line 21, in _swig_getattr
raise AttributeError,name
AttributeError: discover

on this line:
devs = cli.discover()

any idea what might cause it?

thanks in advance
dz

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


Re: object references/memory access

2007-07-03 Thread John Nagle
Steve Holden wrote:
> Karthik Gurusamy wrote:
> 
>> On Jul 1, 12:38 pm, dlomsak <[EMAIL PROTECTED]> wrote:
> 
> [...]
> 
>>
>> I have found the stop-and-go between two processes on the same machine
>> leads to very poor throughput. By stop-and-go, I mean the producer and
>> consumer are constantly getting on and off of the CPU since the pipe
>> gets full (or empty for consumer). Note that a producer can't run at
>> its top speed as the scheduler will pull it out since it's output pipe
>> got filled up.

 This is in fact true, but the overheads of CPython are so large
that you don't usually see it.  If message passing in CPython is slow,
it's usually because the marshalling cost is too high.  As I mentioned
previously, try "pack" instead of "pickle" or "repr" if you control
the interface on both ends of the connection.

 I've used QNX, the message-passing real time operating system,
extensively.  QNX has the proper mechanisms to handle interprocess
communication efficiently; we could pipe uncompressed video through
the message passing system and only use 3% of the CPU per stream.
QNX deals with the "stop and go" problem properly; interprocess
communication via MsgSend and MsgReceive works more like a subroutine
call than a queued I/O operation.  In the normal case, you pay for
a byte copy and a context switch for a message pass, but it's
not necessary to take a trip through the scheduler.

 Not many operating systems get this right.  Minix 3 does,
and there are infrequently used facilities in NT that almost do.
But pipes, sockets, and System V IPC as in Linux all take you through
the scheduler extra times.  This is a killer if there's another compute
bound process running; on each message pass you lose your turn for
the CPU.

(There have been worse operating systems.  The classic MacOS allows
you one (1) message pass per clock tick, or 60 messages per second.)

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


Re: error return without exception set

2007-07-03 Thread Peter Otten
Will McGugan wrote:

> Can anyone suggest a likely cause for the following exception...
> 
> Exception exceptions.SystemError: 'error return without exception set'
> in  ignored

The "Exception ... ignored" part is probably caused by an exception in a
finally block during garbage collection:

>>> def f():
... try:
... yield 42
... finally:
... 1/0
...
>>> g = f()
>>> g.next()
42
>>> del g
Exception exceptions.ZeroDivisionError: 'integer division or modulo by zero'
in  ignored

The "error return without exception set" part looks like a failed
consistency check in ceval.c -- perhaps caused by a broken extension
written in C. 

But you'd have to give some more context.

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


Help building GUI with Tix

2007-07-03 Thread infidel
I am trying to build a GUI using the Tix module.  What I want is a
paned window with a tree in the left pane and a notebook in the right
pane.  I keep getting an error that I don't understand when adding
these widgets to the panes:

PythonWin 2.5.1 (r251:54863, May  1 2007, 17:47:05) [MSC v.1310 32 bit
(Intel)] on win32.
Portions Copyright 1994-2006 Mark Hammond - see 'Help/About PythonWin'
for further copyright information.
>>> import Tix
>>> app = Tix.Tk("Demo")
>>> panes = Tix.PanedWindow(app)
>>> panes.pack(fill=Tix.BOTH, expand=True)
>>> tree = Tix.Tree(panes)
>>> panes.add(tree)
Traceback (most recent call last):
  File "", line 1, in 
  File "C:\Program Files\Python25\lib\lib-tk\Tix.py", line 1220, in
add
self.tk.call(self._w, 'add', name, *self._options(cnf, kw))
TclError: bad window path name ".16442432..16442432"
>>>

What am I missing?

TIA

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


Re: Programming Idiomatic Code

2007-07-03 Thread Nathan Harmston
> > Using a module global for this kind of data is usually a bad idea
> > (except eventually for run-once throw-away scripts, and even then...)
> >
> > Why is this a bad idea?
>
> Don't you have any idea ?
> --

Not really.problem with access, using unneeded memory... I
grasping at straws here...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Programming Idiomatic Code

2007-07-03 Thread Nathan Harmston
> "Clipper-derived unreadable drivel"
>
> I'm intrigued, what language are you working in?
>
> Clipper v5 was a pretty impressive development language for 1990 - with
> code blocks, a flexible pre-processor, garbage collection, exception
> handling, decent speed and an API to allow easy integration with
> routines written in c.
>
> It doesn't have to be unreadable at all (unless it's written by someone
> who thinks it is dBase).
>

Whilst I ve never programmed in standard clipper this language is an
inhouse language (I would tell you the company but then they would
know I wasnt working) developed from Clipper. It has no exception
handling, no code blocks, the subroutines arent really subroutines and
dont return anything they just write to a global variable which you
access after the call. The speed is amazingly slow, it crawls. And
dont even start me on GOTOsyou try to make your code easy to read
and maintain but it just looks like you ve gone on a 2 day binge and
been ill over your VDU. Perl IMO is a 1 day binge problem.

They do use real clipper here and it sounds a lot better than this
bstard son. C integration, oh to do some real programming would be
amazing.

I think its just a poor implementation of Clipper and it makes it
appreciate the genius of python, the indentation, the ease of reading,
ease of maintainingits so perfect.

Now if only I could convince them to move to
Pythondreams.

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


Re: python 3.0 or 3000 ....is it worth waiting??? Newbie Question

2007-07-03 Thread Marc 'BlackJack' Rintsch
On Tue, 03 Jul 2007 19:54:57 +0200, Méta-MCI wrote:

>> Python 3000 doesn't include many significant changes to the language
> 
> One exemple : non-Ascii characters in identifiers (= no significatif 
> change?)

Not in the sense that old code doesn't work anymore.  ASCII sources still
work in Python 3000.  And this change may be already in a Python 2.x
before P3K.

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

  1   2   >