recursion problem

2005-03-03 Thread vegetax
I am trying to make convert a directory "tree" in a list of list, but cant
find the algoritm =( ,for example a directory tree like :

+root
 +doc
   ele1
   ele2
   +doc3
ele3
 +doc2
  ele4

 ele5

should convert into:

root[
 doc,
 [ele1,ele2,doc3,[ele3]],
 doc2,
 [ele4],
 ele5
]

I realy dont have any clue of how to do it =( ,so far i get something like
this : [doc1,ele1,ele2,doc3,ele3,doc2,ele4,ele5] instead of
   [doc1,[ele1,ele2,doc3,[ele3]],doc2,[ele4],ele5]

I need this in order to print a directory tree with htmlgen library which
uses nested lists to represent trees.

#!/usr/bin/python
from os import listdir
from os.path import isdir,join,basename

dirpath  = '/tmp/test/'
res = []

def rec(f):
print f
for ele in listdir(f):
ele = join(f,ele)
if isdir(ele):
rec(ele)
else :
res.append(ele)

rec(dirpath)
print res


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


Re: How to write python plug-ins for your own python program?

2005-03-03 Thread Simon Wittber
> You mean like 'import'? :)

That's how I would do it. It's the simplest thing, that works.

exec("import %s as plugin" % pluginName)
plugin.someMethod()

where pluginName is the name of the python file, minus the ".py" extension.

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


Re: Faster way to do this...

2005-03-03 Thread Timo Virkkala
Harlin Seritt wrote:
Roy, I like what you showed: nums = [a for a in range(100)] . My
mistake for not expressing my question as well as I should have. Not
only am I looking for a way to fill in 100 spots (more or less) in an
array er... list, but I'd like to be able to do it in intervals of
2, 4, 8 etc. as well as other things.
range(2, 100, 4)
How about you fire up the interactive python and try
help(range)
;)
--
Timo Virkkala
--
http://mail.python.org/mailman/listinfo/python-list


PythonWin, AutoDoc and german keyboards...

2005-03-03 Thread Werner Merkl
Hallo,
PythonWin is really great and like to use it all the time.
But, I use to an us keyboard and get support strings (.__doc__).
On the other side, most of my colleges use German keyboards and
the do not get these strings at all.
We are using:
 - Python 2.4
 - PyWin32 203
Here is an example:
---
When we enter range with us keyboard we get:
>>> range(
 [range([start,] stop[, step]) -> list of integers]
When we do this with German keyboard we get... nothing,
except we enter:
>>> range)
 [range([start,] stop[, step]) -> list of integers]
You see, if we press ")" on German KB, which is "(" on us KB
we get the help...
BTW: Changes to Python24\Lib\site-packages\pythonwin\pywin\default.cfg
didn't help.
Is this a known issue?
And is there a work around?
Or do we have to take an other IDE like SPE?
Thank you in advance
Werner Merkl
--
http://mail.python.org/mailman/listinfo/python-list


Re: What is the best way to handle a command line argument that includes an escape sequence like \n?

2005-03-03 Thread Antoon Pardon
Op 2005-03-02, Joe schreef <[EMAIL PROTECTED]>:
> I'm using Python 2.4 on Windows XP SP2.
>
> I'm trying to receive a command line argument that is a newline (\n)
>
> Here is the command line to use
>
> sample.py "\n"

Are you sure this supplies a newline and not the string  

> Here is a sample.py script
>
> import sys
>
> c = sys.argv[1]
>
> # when run c is set to \\n instead of \n.
>
> I created a test batch file
>
> echo %1
>
> to confirm that it was not the cmd.exe command processor causing the issue.

I'm not sure this confirms anything. IMO it is possible that echo
will translate   to , giving you the
impression that you have provideded a newline on the command line
while in fact you have not.

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


Re: How to write python plug-ins for your own python program?

2005-03-03 Thread Mark Rowe
On Mar 3, 2005, at 9:33 PM, Simon Wittber wrote:
You mean like 'import'? :)
That's how I would do it. It's the simplest thing, that works.
exec("import %s as plugin" % pluginName)
plugin.someMethod()
where pluginName is the name of the python file, minus the ".py" 
extension.
A better method would be something along the lines of:
plugin = __import__(pluginName)
plugin.someMethod()
This avoids the potential security problem that `exec' poses as well as 
the need to parse + interpret the string.

Regards,
Mark Rowe

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


Re: PythonWin, AutoDoc and german keyboards...

2005-03-03 Thread Neil Hodgson
Werner Merkl:

> When we enter range with us keyboard we get:
>  >>> range(
>   [range([start,] stop[, step]) -> list of integers]
>
> When we do this with German keyboard we get... nothing,
>...
> BTW: Changes to Python24\Lib\site-packages\pythonwin\pywin\default.cfg
> didn't help.

   It appears that the bindings are done by key code rather than character.
You may be able to patch this up in pythonwin\pywin\scintilla\keycodes.py

   Neil


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


scrollbar dependencies

2005-03-03 Thread Marion
Hello.

I am using Tkinter and Pmw.
I would like to build 2 canvases/frames that are scrollable together
horizontally, and independently vertically (so, the vertical
scrollbars should not be moved by the horizontal one).

So I built a Pmw.ScrolledFrame() containing the 2 canvases,
horizontally scrollable. Now I am trying to build 2 independent
vertical scrollbars,
--> wich command is linked to each canvas (whose parent is
Pmw.ScrolledFrame.component('frame'),
--> and which parent is root (to be packed outside the Pmw.ScrolledFrame).

Is this possible or not ? If not, does somebody allready did that another way ?

Thanks a lot.

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


matplotlib under Zope

2005-03-03 Thread fabian
i develop an application under zope with windows 2000
and i would like integrate graphs.

the problem is that the installation of matplotlib doesn't find the python of 
zope 
and so i can't make graph. Maybe a problem of register?

could you help me?

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


Re: Gordon McMillan installer and Python 2.4

2005-03-03 Thread Svein Brekke
> Seriously, if you're only interested in Windows, just use py2exe, or if
> you want Linux+Windows, try cx_Freeze.

According to the command line help for cx_Freeze and py2exe, they
cannot pack my program with additional installation files into one
self-extracting .exe file (which is what I want to do).

Am I wrong on this?

McMillan's installer lets me easily do this for python 2.3, but
crashes on python 2.4.

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


Re: How to write python plug-ins for your own python program?

2005-03-03 Thread Terry Hancock
On Wednesday 02 March 2005 11:28 pm, Tian wrote:
> I am writing an audio game using Python. in this game you can apply
> some sound effects for the clips you have recorded. I want to make this
> function extensible. I want user to be able to add new sound effect
> plug-ins in the future.
> 
> I want the plug-in to be a simple python code (text file) and a
> description file. I will set some rules for plug-in writing (like you
> must inherit some class and implement some method). I hope plugin can
> be added while original program is running. Is there any good method to
> read in python code and test availability and invoke the functions
> inside?

It's not hard to scrape the contents of a directory and import any modules
you find (i.e. to implement a "plugin directory").  I do it here (beware 
line-wrap):

http://cvs.sourceforge.net/viewcvs.py/narya-project/Narya1/VarImage/Operators/__init__.py?rev=1.1&view=markup

You might not want to have the reading code in the same directory as the
plugins -- you don't have to do it that way.  Take a look at the __import__()
built-in in the Python Library Reference for more information.

I'm sure it's possible to run this code periodically at runtime, although I
prefer to do it only at startup (what if one of the plugins is faulty and
crashes the program?).

Cheers,
Terry

-- 
--
Terry Hancock ( hancock at anansispaceworks.com )
Anansi Spaceworks  http://www.anansispaceworks.com

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


Re: PYGTK, Google Suggest-like GUI

2005-03-03 Thread Ali
I guess what i am looking for is auto-completion but with a drop-down
list...

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


Re: os.stat('')[stat.ST_INO] on Windows

2005-03-03 Thread "Martin v. Löwis"
Tim Roberts wrote:
Hmmm, yes, but nearly 100% of Unix geeks have seen an inode number in their
programming adventures, whereas I'll bet not 1 in 10,000 Windows hardliners
has ever seen an MFT entry.
That is going to change. At my university, students learn what an MFT
record is and how it is structured as part of the operating system
course, just as they learn what an inode is.
I'll grant you that a MFT records are less visible, primarily because
people don't do hard links all that often. That might be changing as
well.
There are things you can do with an inode number, but there's nothing you
can do with an MFT ordinal.
Like what? On NTFS and Win32, you can even convert an inode number
efficiently back to a path name (actually, all path names), something
you cannot do on a typical Unix system (atleast not efficiently).
So, I'll grant that my answer was too specific, but I still believe the
answer to the original question is "no".
Yes, but that's the stupidity of the MS C library, which doesn't use
the nFileIndexHigh/nFileIndexLow fields of the
BY_HANDLE_FILE_INFORMATION structure (it also is the stupidity of the
Win32 API, which claims that you need an open file to support the
notion of a file identifier).
Regards,
Martin
--
http://mail.python.org/mailman/listinfo/python-list


Re: HELP: Python equivalent of UNIX command "touch"

2005-03-03 Thread Tim G
Since no-one's suggested this yet, I highly recommend
UnxUtils: http://unxutils.sourceforge.net/ which includes
a touch.exe. Obviously, this doesn't answer your call for
a Python version, but if you're happy with touch under
Unix, maybe this will work for you.

TJG

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


Re: PYGTK, Google Suggest-like GUI

2005-03-03 Thread Ali
Oh well, the cool guys of GTK have just the thing i wanted called
EntryCompletion.
Here's the link in case someone else stumbles over here:

http://www.pygtk.org/pygtk2tutorial/sec-EntryCompletion.html

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


Re: scrollbar dependencies

2005-03-03 Thread Eric Brunel
On 3 Mar 2005 01:06:48 -0800, Marion <[EMAIL PROTECTED]> wrote:
Hello.
I am using Tkinter and Pmw.
I would like to build 2 canvases/frames that are scrollable together
horizontally, and independently vertically (so, the vertical
scrollbars should not be moved by the horizontal one).
So I built a Pmw.ScrolledFrame() containing the 2 canvases,
horizontally scrollable.
I'd not go that way: a Pmw.ScrolledFrame is not supposed to be used this 
way, and you may have great troubles making it work as you want...
[snip]
Is this possible or not ? If not, does somebody allready did that another way ?
Here is a solution using only pure-Tkinter:
--DualCanvas.py--
from Tkinter import *
## Main window
root = Tk()
root.grid_rowconfigure(0, weight=1)
root.grid_rowconfigure(1, weight=1)
root.grid_columnconfigure(0, weight=1)
## First canvas
c1 = Canvas(root, width=200, height=100, bd=2, relief=SUNKEN,
  scrollregion=(0, 0, 500, 500))
c1.grid(row=0, column=0, sticky='nswe')
## Second canvas
c2 = Canvas(root, width=200, height=100, bd=2, relief=SUNKEN,
  scrollregion=(0, 0, 500, 500))
c2.grid(row=1, column=0, sticky='nswe')
## Special function scroll both canvases horizontally
def xscrollboth(*args):
  c1.xview(*args)
  c2.xview(*args)
## Horizontal scrollbar for both canvases
hScroll = Scrollbar(root, orient=HORIZONTAL, command=xscrollboth)
hScroll.grid(row=2, column=0, sticky='we')
## Vertical scrollbars
vScroll1 = Scrollbar(orient=VERTICAL, command=c1.yview)
vScroll1.grid(row=0, column=1, sticky='ns')
vScroll2 = Scrollbar(orient=VERTICAL, command=c2.yview)
vScroll2.grid(row=1, column=1, sticky='ns')
## Associate scrollbars to canvases
c1.configure(xscrollcommand=hScroll.set, yscrollcommand=vScroll1.set)
c2.configure(xscrollcommand=hScroll.set, yscrollcommand=vScroll2.set)
## Put a few things in canvases so that we see what's going on
c1.create_oval(80, 80, 120, 120, fill='red')
c1.create_oval(380, 80, 420, 120, fill='red')
c1.create_oval(80, 380, 120, 420, fill='red')
c1.create_oval(380, 380, 420, 420, fill='red')
c2.create_oval(80, 80, 120, 120, fill='blue')
c2.create_oval(380, 80, 420, 120, fill='blue')
c2.create_oval(80, 380, 120, 420, fill='blue')
c2.create_oval(380, 380, 420, 420, fill='blue')
## Go!
root.mainloop()
-
The "trick" is simply to create a function accepting the same arguments as the 
xview methods on canvases and forward these arguments to the xview methods of both canvases. 
You then pass this function to the command option of both scrollbars, and voilà. The link 
canvas -> scrollbar is done the usual way.
HTH
--
python -c 'print "".join([chr(154 - ord(c)) for c in 
"U(17zX(%,5.z^5(17l8(%,5.Z*(93-965$l7+-"])'
--
http://mail.python.org/mailman/listinfo/python-list


Re: Need direction to kill a virus

2005-03-03 Thread Anthra Norell



Josef Albert Meile, James Stroud, Sean 
Blakey,
 
Thank you very very much for your valuable 
suggestions and kind encouragement.
 
Frederic
 

( No, I don't have any particular affection for 
Microsoft stuff. Very much on the contrary. I have a plan to start 
using Unix. This plan is over twenty years old. Back then Unix didn't fit 
into PCs. So I did MS-DOS. The practical side of it was that I was more in touch 
with the rest of the (PC) world. As long as I could use DOS I resisted Windows, 
but in the end had to yield or face serious disconnection from the rest of the 
world. The upshot is that my applications are Windows-based and 
so, unfortunately, is my relative expertise. I do have a Red Hat Linux 
package patiently waiting to be installed. I haven't felt comfortable with the 
idea of experimenting on a work-horse machine and another one (in working 
order) I don't have. So, Linux has been sitting on the shelf and indubitably 
isn't the latest version anymore. But no matter, as in every crisis there are 
seeds of opportunities to be picked and sowed ... )
 
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: yield_all needed in Python

2005-03-03 Thread Nick Coghlan
Douglas Alan wrote:
Wouldn't
   yield *(x for x in gen1(arg))
be sufficient, and would already be supported by the proposal at
hand?
It would, but, as Steven pointed out, the * in func(*args) results in 
tuple(args) being passed to the underlying function.

So I see no reason to expect "yield *iterable" to imply a for loop that yields 
the iterators contents. IMO, it's even more of a stretch than the tuple 
unpacking concept (at least that idea involves tuples!)

Whereas:
  yield x for x in iterable if condition
Maps to:
  for x in iterable:
if condition:
  yield x
Just as:
  [x for x in iterable if condition]
Maps to:
  lc = []
  for x in iterable:
if condition:
  lc.append(x)
And:
  (x for x in iterable if condition)
Maps to:
  def g()
for x in iterable:
   if condition:
  yield x
And removing a couple of parentheses is at least as clear as adding an asterisk 
to the front :)

Cheers,
Nick.
--
Nick Coghlan   |   [EMAIL PROTECTED]   |   Brisbane, Australia
---
http://boredomandlaziness.skystorm.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: [egenix-users] Re: mx.ODBC 2.0.7 bug?

2005-03-03 Thread M.-A. Lemburg
Thanks for forwarding the message, Steve.
Steve Holden wrote:
Joe wrote:
Python 2.4
Windows XP SP2
MS Access 2000
mx.ODBC 2.0.7
Problem data truncation occuring (here's the actual error message):
mxODBC.Warning: ('01004', 5, '[Microsoft][ODBC Microsoft Access 
Driver] String data, right truncated on column number 3 (Expr1002)', 
3326)

I believe that  have found a bug in mx.ODBC not properly assigning the 
correct data type to a column.

Here is a sample script that demonstrates the problem and why I think 
it is being handled incorrectly:

# NOTE memo1 and memo2 are memo fields in the test_table
import mx.ODBC.Windows
dbs = mx.ODBC.Windows.connect('database', '', '')
sql = "select memo1, memo2, memo1 & ' ' & memo2 from test_table where 
record_id = 1"

c   = dbs.cursor()
c.execute(sql)
print
print 'mxODBC SQL DataTypes:'
print
for i in mx.ODBC.Windows.sqltype:
print i, mx.ODBC.Windows.sqltype[i]
print
print 'Column DataTypes:'
print
for i in range(len(c.description)):
print c.description[i][1]
c.close()
dbs.close()
When you run this script it produces the following output:
mxODBC SQL DataTypes:
1 CHAR
2 NUMERIC
3 DECIMAL
4 INTEGER
5 SMALLINT
6 FLOAT
7 REAL
8 DOUBLE
9 DATE
10 TIME
11 TIMESTAMP
12 VARCHAR
91 TYPE_DATE
92 TYPE_TIME
93 TYPE_TIMESTAMP
-1 LONGVARCHAR
-10 WCHAR_LONGVARCHAR
-9 WCHAR_VARCHAR
-8 WCHAR
-7 BIT
-6 TINYINT
-5 BIGINT
-4 LONGVARBINARY
-3 VARBINARY
-2 BINARY
Column DataTypes:
-1
-1
12
From the output you can see that memo1 and memo2 are both determined 
to be of type longvarchar (-1) but when the columns are concatenated 
together the resulting column is given a type of varchar (12).  
Obviously this is why the data truncation is occurring.

Is this a known problem?
No, but then the MS Access ODBC drivers are always full of
surprises :-) (things have gotten a lot better recently, though).
I can work around the problem using a converter function:
def converter(position, sqltype, sqllen):
print 'in :', position, sqltype, sqllen
if position == 2:
sqltype = -1
sqllen  = 1073741823
print 'out:', position, sqltype, sqllen
return sqltype, sqllen
and then using:
c.setconverter(converter)
but shouldn't mx.ODBC have properly assigned the correct sqltype and 
sqllen for the concatenated memo columns in the first place?
mxODBC gets the select column information from the ODBC driver
and then fetches the data rows based on that information.
In the above case, the Access ODBC driver tells mxODBC that
the third column is of type VARCHAR and passes it some
length information that obviously is wrong.
The only way to fix this is using a converter like you did.
BTW, do you have more info on the length of the memo field
contents and the value that Access passes back as sqllen
for the third column ?
It is possible that this is some off-by-one bug in the driver.
We could work around that by creating a larger buffer to
hold the data.
This is a very nice piece of deduction, and I am copying this message to 
you and to the egenix-users list, since that's generally a reliable way 
to get Marc-Andre's attention.
Indeed :-) (don't read c.l.p that often these days)
I'm not convinced that it demonstrates an mxODBC bug, since I don't 
believe that the ampersand is actioned by the drivers, but I'm not the 
best one to be authoritative about this.

others-who-read-this-reply-will-ly y'rs  - steve
--
Marc-Andre Lemburg
eGenix.com
Professional Python Services directly from the Source  (#1, Mar 03 2005)
>>> Python/Zope Consulting and Support ...http://www.egenix.com/
>>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/
>>> mxODBC, mxDateTime, mxTextTools ...http://python.egenix.com/

::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,FreeBSD for free ! 
--
http://mail.python.org/mailman/listinfo/python-list


Re: looking for expertise

2005-03-03 Thread klappnase
"Neil Hodgson" <[EMAIL PROTECTED]> wrote in message news:<[EMAIL PROTECTED]>...
> Michael:
> 
> > Like I said, it's only supposed to run on linux; anyway, is it likely
> > that problems will arise when filenames I have to handle have
> > basically three sources:
> > ...
> > 3. filenames created by user input
> 
>Have you worked out how you want to handle user input that is not
> representable in the encoding? It is easy for users to input any characters
> into a Unicode enabled UI either through invoking an input method or by
> copying and pasting from another application or character chooser applet.
> 
>Neil

As I must admit, no. I just couldn't figure out that someone will really do 
this.

I guess I could add a test like (pseudo code):

try:
test = fsdecode(input)# convert to unicode
test.encode(sysencoding)
except:
# show a message box with something like "Invalid file name"

Please tell me if you find any other possible gotchas.

Thanks so far

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


Re: scrollbar dependencies

2005-03-03 Thread Harlin Seritt
Pardon a question I should already know the answer to, but what are the
*args in the:

def xscrollboth(*args):
   c1.xview(*args) 
   c2.xview(*args) 

Thanks,

Harlin

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


Re: Need some simple coding help

2005-03-03 Thread mx2k

 thx again, this code is nearly doing as we want and we think to have
figured out how to change it to meet our requirments. also thx for the
tip using a heap...

should there be more problems i'll post again!

[mx]

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


starting windows program from python based on file extension ?

2005-03-03 Thread kowald
Hi everybody,

I used python to build a HTML file and now I would like to
automatically start my browser to display this file. I guess I could
use os.system(), but then I had to specify a specific path to the
browser.

I wonder if it is possible to tell windows to open "myFile.html" using
the program that is registered to open html files (similar to double
clicking on the file).

Any idea how to do that from python ??

Many thanks,

   Alex

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


Multiline regex help

2005-03-03 Thread Yatima
Hey Folks,

I've got some info in a bunch of files that kind of looks like so:

Gibberish
53
MoreGarbage
12
RelevantInfo1
10/10/04
NothingImportant
ThisDoesNotMatter
44
RelevantInfo2
22
BlahBlah
343
RelevantInfo3
23
Hubris
Crap
34

and so on...

Anyhow, these "fields" repeat several times in a given file (number of
repetitions varies from file to file). The number on the line following the
"RelevantInfo" lines is really what I'm after. Ideally, I would like to have
something like so:

RelevantInfo1 = 10/10/04 # The variable name isn't actually important
RelevantInfo3 = 23   # it's just there to illustrate what info I'm
 # trying to snag.

Score[RelevantInfo1][RelevantInfo3] = 22 # The value from RelevantInfo2

Collected from all of the files.

So, there would be several of these "scores" per file and there are a bunch
of files. Ultimately, I am interested in printing them out as a csv file but
that should be relatively easy once they are trapped in my array of doom
.

I've got a fairly ugly "solution" (I am using this term *very* loosely)
using awk and his faithfail companion sed, but I would prefer something in
python.

Thanks for your time.

-- 
McGowan's Madison Avenue Axiom:
If an item is advertised as "under $50", you can bet it's not $19.95.
-- 
http://mail.python.org/mailman/listinfo/python-list


pytone / _bsddb

2005-03-03 Thread Bas van Gils
Hi all,

I've been using the `pytone' tool for playing my mp3's for a while. Great
tool. However, after upgrading Python to version 2.4 it stopped working. The
traceback that I get is this:

--
Traceback (most recent call last):  
  File "src/pytone.py", line 104, in ?  
songdbid = songdbmanager.addsongdb(songdbname,  
+config.database[songdbname])   
  File "/home/basvg/bin/PyTone-2.2.1/src/services/songdb.py", line 147, in  
+addsongdb  
import songdbs.local
  File "/home/basvg/bin/PyTone-2.2.1/src/services/songdbs/local.py", line   
+24, in ?   
import bsddb.dbshelve   
  File "/usr/lib/python2.4/bsddb/__init__.py", line 47, in ?
import _bsddb   
ImportError: No module named _bsddb 
--

The mentioned line in __init__.py is:

--
import _bsddb  
--

I had a look around through /usr/lib/python2.4 but I couldn't find a _bsddb
indeed. Can anyone help me get my favorite py-tool to work again ;-)?

Bas


-- 
<[EMAIL PROTECTED]> - GPG Key ID: 2768A493  -  http://www.cs.ru.nl/~basvg
Radboud University Nijmegen Institute for Computing and Information Sciences

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


RE: starting windows program from python based on file extension ?

2005-03-03 Thread Tim Golden
[EMAIL PROTECTED]
| I used python to build a HTML file and now I would like to
| automatically start my browser to display this file. I guess I could
| use os.system(), but then I had to specify a specific path to the
| browser.
| 
| I wonder if it is possible to tell windows to open "myFile.html" using
| the program that is registered to open html files (similar to double
| clicking on the file).
| 
| Any idea how to do that from python ??

Python 2.3.5c1 (#61, Jan 25 2005, 19:52:06) [MSC v.1200 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.startfile

>>> help (os.startfile)
Help on built-in function startfile:

startfile(...)
startfile(filepath) - Start a file with its associated application.

This acts like double-clicking the file in Explorer, or giving the file
name as an argument to the DOS "start" command:  the file is opened
with whatever application (if any) its extension is associated.

startfile returns as soon as the associated application is launched.
There is no option to wait for the application to close, and no way
to retrieve the application's exit status.

The filepath is relative to the current directory.  If you want to use
an absolute path, make sure the first character is not a slash ("/");
the underlying Win32 ShellExecute function doesn't work if it is.

>>>


TJG


This e-mail has been scanned for all viruses by Star. The
service is powered by MessageLabs. For more information on a proactive
anti-virus service working around the clock, around the globe, visit:
http://www.star.net.uk

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


Re: starting windows program from python based on file extension ?

2005-03-03 Thread Duncan Booth
 wrote:

> I wonder if it is possible to tell windows to open "myFile.html" using
> the program that is registered to open html files (similar to double
> clicking on the file).
> 
> Any idea how to do that from python ??

>>> import webbrowser
>>> webbrowser.open('test.html')

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


Re: yield_all needed in Python

2005-03-03 Thread Nick Coghlan
Jeremy Bowers wrote:
At first I liked this, but the reason that is a syntax error is that it is
"supposed" to be
def f():
yield (x for x in gen1(arg))
which today on 2.4 returns a generator instance which will in turn
yield one generator instance from the genexp
And it would continue to do so in the future. On the other hand, removing the 
parens makes it easy to write things like tree traversal algorithms:

def left_to_right_traverse(node):
  yield x for x in node.left
  yield node .value
  yield x for x in node.right
In reality, I expect yielding each item of a sub-iterable to be more common than 
building a generator that yields generators.

, and I am quite uncomfortable
with the difference between the proposed behaviors with and without the
parens.
Why? Adding parentheses can be expected to have significant effects when it 
causes things to be parsed differently. Like the example I posted originally:

  [x for x in iterable]  # List comp (no parens == eval in place)
  [(x for x in iterable)] # Parens - generator goes in list
Or, for some other cases where parentheses severely affect parsing:
  print x, y
  print (x, y)
  assert x, y
  assert (x, y)
If we want to pass an iterator into a function, we use a generator expression, 
not extended call syntax. It makes sense to base a sub-iterable yield syntax on 
the former, rather than the latter.

Moreover, since "yield" is supposed to be analogous to "return", what does
return x for x in gen1(arg)
do? Both "it returns a list" and "it returns a generator" have some
arguments in their favor.
No, it would translate to:
  for x in gen1(arg):
return x
Which is nonsense, so you would never make it legal.
And I just now note that any * syntax, indeed, any syntax at all will
break this.
As you noted, this argument is specious because it applies to *any* change to 
the yield syntax - yield and return are fundamentally different, since yield 
allows resumption of processing on the next call to next().

> You know, given the marginal gains this gives anyway,
I'm not so sure the gains will be marginal. Given the penalties CPython imposes 
on recursive calls, eliminating the nested "next()" invocations could 
significantly benefit any code that uses nested iterators.

An interesting example where this could apply is:
def flatten(iterable):
  for item in iterable:
if item is iterable:
  # Do the right thing for self-iterative things
  # like length 1 strings
  yield iterable
  raise StopIteration
try:
  itr = iter(item):
except TypeError:
  yield item
else:
  yield x for x in flatten(item)
Cheers,
Nick.
P.S. Which looks more like executable pseudocode?
def traverse(node):
  yield *node.left
  yield node .value
  yield *node.right
def traverse(node):
  yield x for x in node.left
  yield node .value
  yield x for x in node.right
--
Nick Coghlan   |   [EMAIL PROTECTED]   |   Brisbane, Australia
---
http://boredomandlaziness.skystorm.net
--
http://mail.python.org/mailman/listinfo/python-list


Calling python scripts from php

2005-03-03 Thread Michael Livingston
Hi all,

I'm currently working on a project to develop an online simulation model of
the juvenile justice system in Queensland.  We've developed the simulation
model using the python module simPy and currently we're trying to link the
simulation model to a web interface.  Unfortunately, the web interface and
its interactions with the database have been separately developed in PHP and
ASP.  Rather than rebuilding the web interface using python, we're looking
for an easy way to call a python script from within PHP.  In particular,
we'd like to have the script called but, as running the model can take some
time, we'd prefer if the browser didn't have to sit and wait while the
script was running (instead, we intend to notify the user via email when
their model has completed).  So all we really want to do is start the script
off and running (it's a simple call to a python method).

If you're particularly interested in helping me out and if I've not been
entirely clear, you can go to:

 http://210.49.85.147:8000/justicemodel/login.php

and log in using the user name: temp and the password: pass, select a model
and go to the workspace - the button 'run model' is what we want to trigger
the python script, while all the rest of the website (setting up the model
scenarios, viewing output etc etc) has been developed in php and asp.  Any
assistance anyone can offer me would be greatly appreciated.

Thanks a lot,
Michael


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


Re: How to delete a module file

2005-03-03 Thread Olivier Ravard
Le lundi 28 fÃvrier 2005 Ã 17:08 +, Dennis Lee Bieber a Ãcrit :
> On Mon, 28 Feb 2005 16:43:45 +0100, Olivier Ravard
> <[EMAIL PROTECTED]> declaimed the following in
> comp.lang.python:
> 
> > 
> > Remark : This problem does not exist under Linux.
> >
>   I think Linux just masks the situation. Windows won't let you
> delete the file because the OS still has it open (linked) to the process
> that did the import.
> 
>   Linux deletes the directory entry, so other programs can't find
> the file -- but the OS still has an unseen link to the actual file; the
> actual file doesn't go away until the total link count falls to 0.
> 

So, what is the solution ?



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


Setting default option values for Tkinter widgets

2005-03-03 Thread Harlin Seritt
There are certain options for Tkinter widgets that have default values
that I don't much care for (borderwidth, font come to mind) and
continuously change when I'm building interfaces. With a bit of
tweaking I have been able to give the widgets a look that rivals the
best of them. However, I get tired of doing this when I'm writing code
and would like a way that I could universally change them on my system.
I have tried to find where in the class files (Tkinter.py) that I can
change these and haven't been able to find them. Are there certain
lines in certain files/modules/classes that I can change the values for
these things like font, border, etc.?

Thanks,

Harlin

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


Re: scrollbar dependencies

2005-03-03 Thread Eric Brunel
On 3 Mar 2005 02:38:59 -0800, Harlin Seritt <[EMAIL PROTECTED]> wrote:
Pardon a question I should already know the answer to, but what are the
*args in the:
def xscrollboth(*args):
   c1.xview(*args)
   c2.xview(*args)
Thanks,
Harlin
If your question is about the syntax, it's just the way of passing any 
number of arguments to a function as explained in:
http://docs.python.org/tut/node6.html#SECTION00673
If your question is about what will actually be passed in these arguments, the 
answer is simply: I don't know, and I don't care. That's why I used a *args: I 
just want to pass to the c1.xview and c2.xview methods exactly what was passed 
to my xscrollboth function. Since Python allows me to just pass the list of 
arguments unchanged, I happily do it.
--
python -c 'print "".join([chr(154 - ord(c)) for c in 
"U(17zX(%,5.z^5(17l8(%,5.Z*(93-965$l7+-"])'
--
http://mail.python.org/mailman/listinfo/python-list


Re: starting windows program from python based on file extension ?

2005-03-03 Thread F. Petitjean
Le 3 Mar 2005 02:53:51 -0800, [EMAIL PROTECTED] a écrit :
> Hi everybody,
> 
> I used python to build a HTML file and now I would like to
> automatically start my browser to display this file. I guess I could
> use os.system(), but then I had to specify a specific path to the
> browser.
> 
> I wonder if it is possible to tell windows to open "myFile.html" using
> the program that is registered to open html files (similar to double
> clicking on the file).
> 
> Any idea how to do that from python ??
import os
os.startfile("myFile.html")
# on windows only
> 
> Many thanks,
> 
>Alex
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Setting default option values for Tkinter widgets

2005-03-03 Thread Eric Brunel
On 3 Mar 2005 03:02:48 -0800, Harlin Seritt <[EMAIL PROTECTED]> wrote:
There are certain options for Tkinter widgets that have default values
that I don't much care for (borderwidth, font come to mind) and
continuously change when I'm building interfaces. With a bit of
tweaking I have been able to give the widgets a look that rivals the
best of them. However, I get tired of doing this when I'm writing code
and would like a way that I could universally change them on my system.
I have tried to find where in the class files (Tkinter.py) that I can
change these and haven't been able to find them. Are there certain
lines in certain files/modules/classes that I can change the values for
these things like font, border, etc.?
tk allows to write your preffered options to an option file and to load it 
via the method option_readfile in your application.
For an example on how the options can be set, see:
http://mini.net/tcl/10424
The file should contain the arguments passed to "option add" commands.
For a reference on what options are available and how to specify them in an 
option file, see the tk manual pages here:
http://www.tcl.tk/man/tcl8.4/TkCmd/contents.htm
The name for the widget is usually the name of the corresponding Tkinter class; the name 
for the option is the second name found in the standard and widget-specific options 
sections in the man pages (named "Database name" in the section text). So for 
example, if you want to set the default select color for checkbuttons, you'll put in your 
option file a line:
*Checkbutton.selectColor: blue
HTH
--
python -c 'print "".join([chr(154 - ord(c)) for c in 
"U(17zX(%,5.z^5(17l8(%,5.Z*(93-965$l7+-"])'
--
http://mail.python.org/mailman/listinfo/python-list


Re: Multiline regex help

2005-03-03 Thread Kent Johnson
Yatima wrote:
Hey Folks,
I've got some info in a bunch of files that kind of looks like so:
Gibberish
53
MoreGarbage
12
RelevantInfo1
10/10/04
NothingImportant
ThisDoesNotMatter
44
RelevantInfo2
22
BlahBlah
343
RelevantInfo3
23
Hubris
Crap
34
and so on...
Anyhow, these "fields" repeat several times in a given file (number of
repetitions varies from file to file). The number on the line following the
"RelevantInfo" lines is really what I'm after. Ideally, I would like to have
something like so:
RelevantInfo1 = 10/10/04 # The variable name isn't actually important
RelevantInfo3 = 23   # it's just there to illustrate what info I'm
 # trying to snag.
Here is a way to create a list of [RelevantInfo, value] pairs:
import cStringIO
raw_data = '''Gibberish
53
MoreGarbage
12
RelevantInfo1
10/10/04
NothingImportant
ThisDoesNotMatter
44
RelevantInfo2
22
BlahBlah
343
RelevantInfo3
23
Hubris
Crap
34'''
raw_data = cStringIO.StringIO(raw_data)
data = []
for line in raw_data:
if line.startswith('RelevantInfo'):
key = line.strip()
value = raw_data.next().strip()
data.append([key, value])
print data

Score[RelevantInfo1][RelevantInfo3] = 22 # The value from RelevantInfo2
I'm not sure what you mean by this. Do you want to build a Score dictionary 
as well?
Kent
Collected from all of the files.
So, there would be several of these "scores" per file and there are a bunch
of files. Ultimately, I am interested in printing them out as a csv file but
that should be relatively easy once they are trapped in my array of doom
.
I've got a fairly ugly "solution" (I am using this term *very* loosely)
using awk and his faithfail companion sed, but I would prefer something in
python.
Thanks for your time.
--
http://mail.python.org/mailman/listinfo/python-list


Re: class factory example needed (long)

2005-03-03 Thread Gary Ruben
Thanks Steven and Kent, both of your suggestions look good to me. I'll 
try both out and pick one.
Gary

Gary Ruben wrote:
OK, I've managed to get this to work with Rainer's method, but I 
realised it is not the best way to do it, since the methods are being 
added by the constructor, i.e. they are instance methods. This means 
that every time a foo object is created, a whole lot of code is being 
run. It would be better to do the same thing with class 'static' 
methods, if this is possible, so that the methods are created just once.
Is this possible?
Gary
--
http://mail.python.org/mailman/listinfo/python-list


Re: function expression with 2 arguments

2005-03-03 Thread Xah Lee

Roel Schroeven wrote:
> (lambda x, y: x+y)(a, b)

Thanks. That's what i was looking for.

where in Pytho doc can one find this? or the lambda with multiple
params?


> Most often the lambda is not used directly, but passed to a function.

That is because the IT morons has been throughly brainwashed by
imperative shits. (and these morons don't even know it)

i'll explain the ins and outs of expressions of functions some other
day.

 Xah
 [EMAIL PROTECTED]
 http://xahlee.org/PageTwo_dir/more.html

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


Re: pytone / _bsddb

2005-03-03 Thread Bas van Gils
On 2005-03-03, Bas van Gils <[EMAIL PROTECTED]> wrote:
> Hi all,
>
> I've been using the `pytone' tool for playing my mp3's for a while. Great
> tool. However, after upgrading Python to version 2.4 it stopped working. The
> traceback that I get is this:
[ ... ]

Great, I found it myself. The problem was a version of db that was `too new'.
Apparently Python didn't like this version of db. After downgrading it and
rebuilding Python everything worked as expected. Yay!

Bas


-- 
<[EMAIL PROTECTED]> - GPG Key ID: 2768A493  -  http://www.cs.ru.nl/~basvg
Radboud University Nijmegen Institute for Computing and Information Sciences

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


Re: canvassing for assistance

2005-03-03 Thread Sean McIlroy
'scale' puts the lower-right corner of a bounding box where the
pointer is, while keeping the upper-left corner where it was before
(or, if the relevant item's coordinates aren't of bounding-box type,
the function does nothing).

Thanks for the link.

Peace,
STM


"[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote in message news:<[EMAIL 
PROTECTED]>...
> Sean, nice work on canvasser!  One question: what is the purpose of
> 'scale'?  I notice that if you have already drawn a line on the canvas,
> then 'scale' can be used to draw a straight-line element extending from
> the end of the previous freehand line, but if you start with a blank
> screen, 'scale' has no effect.
> 
> BTW if you want to extend your app further, take a look at paint.py in
> the Vaults of Parnassus:
> http://py.vaults.ca/apyllo.py?i=173784088
> 
> cheers,
> S
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What is the best way to handle a command line argument that includes an escape sequence like \n?

2005-03-03 Thread Joe
Hi Steve,

I've been using Python for many years, just hadn't had to deal with an 
escape sequence in the command line args. :-) and couldn't find the solution 
in the docs.

It is easy to prove my assertion:

import sys
c = sys.argv[1]
print len(c)
print 'Line 1', c, 'Line 2'

Output:
2
Line 1 \n Line 2

Versus:

import sys
c = sys.argv[1]
print len(c)
print 'Line 1', c.decode('string_escape'), 'Line 2'

Output:
2
Line 1
Line 2

Agreed, it is much easier on Unix to deal with this, I have not seen a way 
to get the XP command interpreter to allow a multiline command line as you 
described.

Your solution was exactly what I need.  I had an escape sequence entered on 
the command line and needed to decode the string so that Python used it as 
an escape sequence, in fact the sequence really is part of the output that 
the program produces.

Thanks again for your assistance.

Regards,

Joe

> I don't want you getting more confused rather than less - newcomers are 
> sometimes confused by Python's encoding of backslashes and such when 
> printing out strings. What is your evidence for the assertion that c is 
> set to \\n rather than \n?
>
> In Unix, it's easier to avoid this, since the shell lets you enter 
> multi-line strings (note that these lines may wrap in the mail):
>
> [EMAIL PROTECTED] sholden]$ python -c "import sys; print repr(sys.argv[1])" 
> "\n"
> '\\n'
> [EMAIL PROTECTED] sholden]$ python -c "import sys; print repr(sys.argv[1])" 
> "
> > "
> '\n'
>
> The first case simply demonstrates that the shell doesn't interpret 
> backslash escape sequences. I used repr() because that's what the 
> interpreter will print if you enter an expression at the interactive 
> prompt. The first case shows that the argument is two characters - you can 
> verify this using the len() function.
>
> The second case shows how (with a sensible command shell) you can provide 
> a newline as an argument.
>
> In Windows we can emulate the first case exactly:
> C:\Steve>C:\python24\python -c "import sys; print repr(sys.argv[1])" "\n"
> '\\n'
>
> Unfortunately Windows XP's command interpreter doesn't bother to wait 
> until you close a double-quote left open at the end of a line:
>
> C:\Steve>\python24\python -c "import sys; print repr(sys.argv[1])" "
> ''
>
> So someone else will have to tell you how to do that, but you should be 
> clear about what's happening before you try and correct the problem.
>
> regards
>  Steve
> -- 
> Meet the Python developers and your c.l.py favorites March 23-25
> Come to PyCon DC 2005  http://www.pycon.org/
> Steve Holden   http://www.holdenweb.com/ 


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


Re: What is the best way to handle a command line argument that includes an escape sequence like \n?

2005-03-03 Thread Joe
Antoon,

I tested the batch file :-)

The one line batchfile does prove it because it prints out  
and not .

See other post, decode is exactly what was needed to fix the problem.

Regards,

Joe

"Antoon Pardon" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Op 2005-03-02, Joe schreef <[EMAIL PROTECTED]>:
>> I'm using Python 2.4 on Windows XP SP2.
>>
>> I'm trying to receive a command line argument that is a newline (\n)
>>
>> Here is the command line to use
>>
>> sample.py "\n"
>
> Are you sure this supplies a newline and not the string  
>
>> Here is a sample.py script
>>
>> import sys
>>
>> c = sys.argv[1]
>>
>> # when run c is set to \\n instead of \n.
>>
>> I created a test batch file
>>
>> echo %1
>>
>> to confirm that it was not the cmd.exe command processor causing the 
>> issue.
>
> I'm not sure this confirms anything. IMO it is possible that echo
> will translate   to , giving you the
> impression that you have provideded a newline on the command line
> while in fact you have not.
>
> -- 
> Antoon Pardon 


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


file.getvalue() with _ or other characters

2005-03-03 Thread martijn
H!

I do this to get a htmlTOtext file

class mvbHTMLParser(htmllib.HTMLParser):

def __init__(self, formatter, verbose=0):
htmllib.HTMLParser.__init__(self,formatter,verbose)
self.imglist = []

def handle_image(self,src,alt,*args):
self.imglist.append(src)


file = StringIO.StringIO()
f = formatter.AbstractFormatter(formatter.DumbWriter(file))
p = mvbHTMLParser(f)
p.feed(html)
p.close()

print file.getvalue()

But then the _ characters are away.
is it possible to keep that character in file.getvalue()

[the p.anchorlist = oke : test_bla.html]

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


Re: Gordon McMillan installer and Python 2.4

2005-03-03 Thread Serge Orlov
Svein Brekke wrote:
> > Seriously, if you're only interested in Windows, just use py2exe,
> > or if you want Linux+Windows, try cx_Freeze.
>
> According to the command line help for cx_Freeze and py2exe, they
> cannot pack my program with additional installation files into one
> self-extracting .exe file (which is what I want to do).
>
> Am I wrong on this?

You're right, but that doesn't mean py2exe is not for you. Packing
a program, displaying a license, choosing installation directory
is not Python specific, just use a generic installer. They are better
because they have much more users than Python specific installers.
See for example http://nsis.sourceforge.net/features/featurelist/

Use py2exe to bundle python core, extentions and your program into
one directory, then use nsis to create the installator.

  Serge.

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


Re: windows bat file question

2005-03-03 Thread Peter Hansen
Tim Roberts wrote:
Tom Willis <[EMAIL PROTECTED]> wrote:
rem = """-*-Python-*- script
@echo off
rem  DOS section 
rem You could set PYTHONPATH or TK environment variables here
python %*
This should make it work:
  python %0.bat %*
Only, among other issues, if you type the full path to the
batch file, or if it's in the current directory.  This
approach fails if you put the batch file in a directory
somewhere along your path.
There are only a couple of useful ways to do this sort of
thing under Windows operating systems, and the easiest by
far is to abandon any support for Windows 98 and just use
the PATHEXT support in Windows NT/XP and friends.
-Peter
--
http://mail.python.org/mailman/listinfo/python-list


Re: Gordon McMillan installer and Python 2.4

2005-03-03 Thread Peter Hansen
Svein Brekke wrote:
Seriously, if you're only interested in Windows, just use py2exe, or if
you want Linux+Windows, try cx_Freeze.

According to the command line help for cx_Freeze and py2exe, they
cannot pack my program with additional installation files into one
self-extracting .exe file (which is what I want to do).
Am I wrong on this?
As far as py2exe goes, no, you're not wrong.
On the other hand, there are readily available utilities that
will do what you are asking for, independent of Python and py2exe
and everything else.  Standalone single-file packagers.
Unfortunately I don't recall the names of any, but I'm pretty
sure you can find one if you look, or someone else will remind
us of the names.
-Peter
--
http://mail.python.org/mailman/listinfo/python-list


Re: function expression with 2 arguments

2005-03-03 Thread Peter Hansen
Xah Lee wrote:
Roel Schroeven wrote:
(lambda x, y: x+y)(a, b)
Thanks. That's what i was looking for.
where in Pytho doc can one find this? or the lambda with multiple
params?
Most often the lambda is not used directly, but passed to a function.
That is because the IT morons has been throughly brainwashed by
imperative shits. (and these morons don't even know it)
i'll explain the ins and outs of expressions of functions some other
day.
After you read about them, I guess?   We look forward to your
profound words on the subject.
Sheesh...
--
http://mail.python.org/mailman/listinfo/python-list


Re: Gordon McMillan installer and Python 2.4

2005-03-03 Thread Just
In article <[EMAIL PROTECTED]>,
 "Serge Orlov" <[EMAIL PROTECTED]> wrote:

> Svein Brekke wrote:
> > > Seriously, if you're only interested in Windows, just use py2exe,
> > > or if you want Linux+Windows, try cx_Freeze.
> >
> > According to the command line help for cx_Freeze and py2exe, they
> > cannot pack my program with additional installation files into one
> > self-extracting .exe file (which is what I want to do).
> >
> > Am I wrong on this?
> 
> You're right, but that doesn't mean py2exe is not for you. Packing
> a program, displaying a license, choosing installation directory
> is not Python specific, just use a generic installer. They are better
> because they have much more users than Python specific installers.
> See for example http://nsis.sourceforge.net/features/featurelist/
> 
> Use py2exe to bundle python core, extentions and your program into
> one directory, then use nsis to create the installator.

It's not so much about the installation I suppose. A friend of mine is 
packaging an app for Windows, and he _really_ likes the installed thing 
to be a single-file .exe, not a folder with many things. Apparently 
McMillan Installer does that very nicely. Too bad it doesn't support 
Python 2.4 (yet).

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


Re: Gordon McMillan installer and Python 2.4

2005-03-03 Thread Richie Hindle

[Svein]
> According to the command line help for cx_Freeze and py2exe, they
> cannot pack my program with additional installation files into one
> self-extracting .exe file (which is what I want to do).

[Peter]
> On the other hand, there are readily available utilities that
> will do what you are asking for, independent of Python and py2exe
> and everything else.  Standalone single-file packagers.

InnoSetup is the most popular free single-file-installer generator for
Windows.  NSIS is probably second.

-- 
Richie Hindle
[EMAIL PROTECTED]

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


Re: file.getvalue() with _ or other characters

2005-03-03 Thread Peter Hansen
[EMAIL PROTECTED] wrote:
file = StringIO.StringIO()
f = formatter.AbstractFormatter(formatter.DumbWriter(file))
p = mvbHTMLParser(f)
p.feed(html)
p.close()
print file.getvalue()
But then the _ characters are away.
is it possible to keep that character in file.getvalue()
I consider this a defect in StringIO, but it's pretty easy to
fix it, at least for the narrow usage you describe:
class PreservingStringIO(StringIO.StringIO):
def close(self):
pass
file = PreservingStringIO()
...etc
The problem is (if I'm right about this) that the close()
method on the object returned by mvbHTMLParser() will actually
call close() on the file object in the formatter (whether
directly or not, I don't know).  One might consider _this_
a bug as well, but if the above approach works, in the end
it's no big deal.
So basically redefine close() to do nothing (or have it save
a copy of the buffer's getvalue() results first) and you
should be good to go.
-Peter
--
http://mail.python.org/mailman/listinfo/python-list


Re: passing lists

2005-03-03 Thread Earl Eiland
This message contains the responses to two previous messages:

In response to Steven B.,the statements
Raw_packet_queue = enqueue(..., Raw_packet_queue, ...)  
print 'Sort 1 Raw_packet_queue is', Raw_packet_queue
produce the output
Sort 1 Raw_packet_queue is [[(,
'\x00\x00\xd1\xf0\x
[EMAIL PROTECTED]
81\x8a\x02\xbf\xb1\x13\x00\x16\xe5/\xd5\xa7vu\x0e\x08\x80\x10\xf8\xe0\x8a[\x00\x
00\x01\x01\x08\n\x15\xb7\x13\xba\x8e\x91\x9a\xfd'), ['E\x00\x004',
'@\x00', '\x0
6',
'\x89N\xa2j\x81\x8a\x02\xbf\xb1\x13\x00\x16\xe5/\xd5\xa7vu\x0e\x08\x80\x10\x
f8\xe0\x8a[\x00\x00\x01\x01\x08\n\x15\xb7\x13\xba\x8e\x91\x9a\xfd']]]

This consists of two lists [[pcap packet header, pcap packet body], [a
list of selected IP header fields]].  Raw_packet_queue[0][0][1] should
return the 'pcap packet body' list element.


In response to Steve H., the traceback is
Traceback (most recent call last):
  File "../Devel_2.py", line 125, in ?
Inbound_Results = Parser.Sort(Inb_sequence,
"Inbound-dump-"+Run_ID+"-Dropped
.dmp", "Inbound-dump-"+Run_ID+"-Created.dmp")
  File
"/home/earl/ResearchProjects/IntrusionResistance/NewPhasee2/Parser.py",
l
ine 291, in Sort
if Raw_packet_queue[ctr][1] == Passed_IP: Last_Passed, Last_Dropped,
Raw_pac
ket_queue = Match(Created, Passed, Raw_packet_queue, Raw, False,
Last_Passed, La
st_Dropped, First_Created, ctr)
  File
"/home/earl/ResearchProjects/IntrusionResistance/NewPhasee2/Parser.py",
l
ine 132, in Match
Last_Passed = Raw_packet_queue[0][0][1]
TypeError: unsubscriptable object

On Wed, 2005-03-02 at 15:34, Steve Holden wrote:
> Earl Eiland wrote:
> > def Match(..., Raw_packet_queue, ...):
> > ...
> > print 'in Match, Raw_Packet_queue is', Raw_packet_queue # this returns
> > 'Reader object at 0xaaa'
> > ...
> > return [Last_Passed, Last_Dropped, Raw_packet_queue] # this causes
> > 'unsubscriptable object'error message
> > 
> > #*
> > def Main(...):
> > Raw_packet_queue = []
> > ...
> > Raw_packet_queue = enqueue(..., Raw_packet_queue, ...) # this works
> > ... 
> > if Raw_packet_queue[ctr][1] == Passed_IP: Last_Passed, Last_Dropped,
> 
>   oops!
> > Raw_packet_queue = Match(..., Raw_packet_queue, ...) # the problem
> > starts here
> > ...
> > 
> Rule one: ALWAYS include the actual traceback, rather than providing 
> your interporetation of what it means (though you are then free to do 
> that, too).
> 
> What makes you think it's the Match() call that's causing the problem?
> 
> I'd be willing to bet money it's the double-subscripting of 
> Raw_packet_queue - if item [ctr] on the Raw_packet_queue isn't a list or 
> a dict then subscripting it by [1] will give you the error message that 
> you quote.
> 
> But if you had included the traceback you would have made it unnecessary 
> for me to use my psychic powers :-)
> 
> regards
>   Steve
> 
> > On Wed, 2005-03-02 at 14:09, Bill Mill wrote:
> > 
> >>Earl,
> >>
> >>Please post the smallest snippet of code you can which illustrates
> >>your problem. No list is an unsubscriptable object, so you seem to be
> >>passing something that is not a list to your function.
> >>
> >>As it stands, you don't give enough information to give an actual answer.
> >>
> >>Peace
> >>Bill Mill
> >>bill.mill at gmail.com
> > 
> > 
> >>
> >>On Wed, 02 Mar 2005 14:05:18 -0700, Earl Eiland <[EMAIL PROTECTED]> wrote:
> >>
> >>>I have a program in which I'm passing a list to functions.  When I
> >>>reference an element in a function to which it is passed, I get the
> >>>error message "unsubscriptable object".  When printing the list contents
> >>>in that same function, I get "xxx is ".  How do
> >>>I pass a list?
> >>>
> >>>Earl Eiland
> >>>
> >>>--
> >>>http://mail.python.org/mailman/listinfo/python-list
> >>>
> > 
> > 
> -- 
> Meet the Python developers and your c.l.py favorites March 23-25
> Come to PyCon DC 2005  http://www.pycon.org/
> Steve Holden   http://www.holdenweb.com/

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


Re: mx.ODBC 2.0.7 bug?

2005-03-03 Thread Joe
Hi Steve,

Thanks, I find you get much better help when you provide the details needed 
for your case instead of expecting others to invest alot of their time 
before you did your homework.

Thanks for sending it over to Marc.  Last time I found a bug in the mx stuff 
(YEARS AGO) I sent it directly to Marc but was trying not to bother him 
until I tried the list first.

One point I forgot to mention in the previous reply is that AFTER the 
converter function is setup and used if you examine the 
cursor.description[column][1] values it still has the old sqltype and 
sqllen.  Not sure if that would be considered a bug or not?  I would have 
expected that the converter hook would have also modified the description 
info to match what the converter hook did.

Thanks again for your assistance.

Regards,

Joe


> This is a very nice piece of deduction, and I am copying this message to 
> you and to the egenix-users list, since that's generally a reliable way to 
> get Marc-Andre's attention.
>
> I'm not convinced that it demonstrates an mxODBC bug, since I don't 
> believe that the ampersand is actioned by the drivers, but I'm not the 
> best one to be authoritative about this.
>
> others-who-read-this-reply-will-ly y'rs  - steve
> -- 
> Meet the Python developers and your c.l.py favorites March 23-25
> Come to PyCon DC 2005  http://www.pycon.org/
> Steve Holden   http://www.holdenweb.com/ 


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


Re: function expression with 2 arguments

2005-03-03 Thread Xah Lee
PS sorry for the rude remarks out of nowhere.

 Xah

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


Online Programming Contest (Python solutions accepted) + Amazon offer

2005-03-03 Thread Sridhar
Hi,

We, the students of CEG, Anna University [1] are organizing an online
programming contest as part of aBaCus [2] 2005.  The contest itself
will start on 6th March 2005 at 1:00 pm IST [3] and will end after 5
hours.  You have to solve the problems posted at the start of the
contest.  Teams ranking high will be awared the prizes.

As a special note, inspite of C,C++ and Java we also allow Python [4]
this time.  So we hope a lot of Pythonistas also could attend the
contest for fun. :-)

Top performers would be considered to join the 'Circle of Innovation'
at Amazon India [5]. You may also have a chance to be considered for
Internships/Externships/Work at Amazon India!


For more details about the contest, visit the contest page

 --   http://203.197.138.181/OPC  --

[1] http://en.wikipedia.org/wiki/Anna_University
[2] http://www.annauniv.edu/abacus/
[3] Indian Standard Time (IST) is the time zone for India. It is 5
hours and 30 minutes ahead of GMT/UTC.
[4] http://www.python.org
[5] http://india.amazon.com/circle.php

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


Re: windows bat file question

2005-03-03 Thread Duncan Booth
Peter Hansen wrote:

>> This should make it work:
>>   python %0.bat %*
> 
> Only, among other issues, if you type the full path to the
> batch file, or if it's in the current directory.  This
> approach fails if you put the batch file in a directory
> somewhere along your path.

The simplest fix, assuming we aren't talking Win9x is probably:

 python "%~f0" %*

> There are only a couple of useful ways to do this sort of
> thing under Windows operating systems, and the easiest by
> far is to abandon any support for Windows 98 and just use
> the PATHEXT support in Windows NT/XP and friends.

And if you can't be bothered with PATHEXT then just make sure to always 
type the .py in as part of the command line: 

   C:\>myscript.py

will run a Python script without any messing. If the script is in the 
current directory then you can use tab completion to avoid typing the whole 
name anyway.

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


Re: function expression with 2 arguments

2005-03-03 Thread Steve Holden
Xah Lee wrote:
PS sorry for the rude remarks out of nowhere.
 Xah
Wow, signs of developing inter-personal skills. I must assume that 
c.l.py is having its benign influence on you too!

regards
 Steve
--
Meet the Python developers and your c.l.py favorites March 23-25
Come to PyCon DC 2005  http://www.pycon.org/
Steve Holden   http://www.holdenweb.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: file.getvalue() with _ or other characters

2005-03-03 Thread martijn
mmm I'm a newbie with python.

I did this but don't work:

class mvbHTMLParser(htmllib.HTMLParser):

def __init__(self, formatter, verbose=0):
htmllib.HTMLParser.__init__(self,formatter,verbose)
self.imglist = []

def handle_image(self,src,alt,*args):
self.imglist.append(src)

class PreservingStringIO(StringIO.StringIO):
 def close(self):
 pass

file = PreservingStringIO()
f = formatter.AbstractFormatter(formatter.DumbWriter(file))
p = mvbHTMLParser(f)
p.feed(html)
p.close() 

print file.getvalue()


 i will try some things

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


Re: passing lists

2005-03-03 Thread Kent Johnson
Earl Eiland wrote:
This message contains the responses to two previous messages:
In response to Steven B.,the statements
Raw_packet_queue = enqueue(..., Raw_packet_queue, ...)  
print 'Sort 1 Raw_packet_queue is', Raw_packet_queue
produce the output
Sort 1 Raw_packet_queue is [[(,
'\x00\x00\xd1\xf0\x
[EMAIL PROTECTED]
81\x8a\x02\xbf\xb1\x13\x00\x16\xe5/\xd5\xa7vu\x0e\x08\x80\x10\xf8\xe0\x8a[\x00\x
00\x01\x01\x08\n\x15\xb7\x13\xba\x8e\x91\x9a\xfd'), ['E\x00\x004',
'@\x00', '\x0
6',
'\x89N\xa2j\x81\x8a\x02\xbf\xb1\x13\x00\x16\xe5/\xd5\xa7vu\x0e\x08\x80\x10\x
f8\xe0\x8a[\x00\x00\x01\x01\x08\n\x15\xb7\x13\xba\x8e\x91\x9a\xfd']]]
This consists of two lists [[pcap packet header, pcap packet body], [a
list of selected IP header fields]].  Raw_packet_queue[0][0][1] should
return the 'pcap packet body' list element.
No, Raw_packet_queue[0] is [pcap packet header, pcap packet body] so Raw_packet_queue[0][1] is pcap 
packet body. Raw_packet_queue[0][0][1] is (pcap packet header)[1] which doesn't work.

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


Re: i18n: looking for expertise

2005-03-03 Thread Serge Orlov
klappnase wrote:
> Hello all,
>
> I am trying to internationalize my Tkinter program using gettext and
> encountered various problems, so it looks like it's not a trivial
> task.

Considered that you decided to support old python versions, it's true.
Unicode support has gradually improved. If you choose to target old
python version, basically you're dealing with years old unicode
support.

> After some "research" I made up a few rules for a concept that I hope
> lets me avoid further encoding trouble, but I would feel more
> confident if some of the experts here would have a look at the
> thoughts I made so far and told me if I'm still going wrong somewhere
> (BTW, the program is supposed to run on linux only). So here is what
> I have so far:
>
> 1. use unicode instead of byte strings wherever possible. This can be
> a little tricky, because in some situations I cannot know in advance
> if a certain string is unicode or byte string; I wrote a helper
> module for this which defines convenience methods for fail-safe
> decoding/encoding of strings and a Tkinter.UnicodeVar class which I
> use to convert user input to unicode on the fly (see the code below).

I've never used tkinter, but I heard good things about it. Are you
sure it's not you who made it to return byte string sometimes?
Anyway, your idea is right, make IO libraries always return unicode.

> 3. make sure to NEVER mix unicode and byte strings within one
> expression

As a rule of thumb you should convert byte strings into unicode
strings at input and back to byte strings at output. This way
the core of your program will have to deal only with unicode
strings.

> 4. in order to maintain code readability it's better to risk excess
> decode/encode cycles than having one too few.

I don't think so. Either you need decode/encode or you don't.

> 5. file operations seem to be delicate;

You should be ready to handle unicode errors at file operations as
well as for example ENAMETOOLONG error. Any file system with path
argument can throw it, I don't think anything changed here with
introduction of unicode. For example access can return 11 (on
my linux system) error codes, consider unicode error to be twelveth.

> at least I got an error when I
> passed a filename that contains special characters as unicode to
> os.access(), so I guess that whenever I do file operations
> (os.remove(), shutil.copy() ...) the filename should be encoded back
> into system encoding before;

I think python 2.3 handles that for you. (I'm not sure about the
version)
If you have to support older versions, you have to do it yourself.


> 6. messages that are printed to stdout should be encoded first, too;
> the same with strings I use to call external shell commands.

If you use stdout as dump device just install the encoder in the
beginning of your program, something like

sys.stdout = codecs.getwriter(...) ...
sys.stderr = codecs.getwriter(...) ...


  Serge.

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


binutils "strings" like functionality?

2005-03-03 Thread cjl
Hey all:

I am working on a little script that needs to pull the strings out of a
binary file, and then manipulate them with python.

The command line utility "strings" (part of binutils) has exactly the
functionality I need, but I was thinking about trying to implement this
in pure python.

I did some reading on opening and reading binary files, etc., and was
just wondering if people think this is possible, or worth my time (as a
learning exercise), or if something like this already exists.

-cjl

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


converting time tuple to datetime struct

2005-03-03 Thread Michael Jard
there a shorter way then:
datetime.fromtimestamp(time.mktime(time.strptime("20-3-2005","%d-%b-%y")))

thanks,
Mike

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


Re: converting time tuple to datetime struct

2005-03-03 Thread gry
[your "%b" is supposed to be the abbreviated month name, not the
number.  Try "%m"]

In [19]: datetime.datetime(*time.strptime("20-3-2005","%d-%m-%Y")[:6])
Out[19]: datetime.datetime(2005, 3, 20, 0, 0)

Cheers,
   George

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


Python 2.4 & PostgreSQL 8 segfault

2005-03-03 Thread Adrian Immler
hello,

i have compiled and installed postgres8 --with-prefix=/usr/local/postgres8
(& several other options) and have no other version of postgres on my
system. python is compiled and make'd --with-prefix=/usr.

i have added the libpath of postgres to /etc/ld.so.conf and a ldconfig -v
also told me that the libraries are found. i tried to install PyGreSQL,
pyPgSQL and psycoPG. after i found out how to tell all those make systems
where my libraries and includes are i got it installed. but no matter
which module i try to use ... it segfaults. even if i try to view the
documentation via pydoc -p  in my browser, as soon as i click on
such a module the pydoc server shuts down with segfault. what is wrong ?

do i have to compile those modules against a postgres7 and then connect to
a postgres8?

any ideas ?

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


Re: unicode and socket

2005-03-03 Thread TZOTZIOY
On 18 Feb 2005 19:10:36 -0800, rumours say that [EMAIL PROTECTED] might have
written:

>It's really funny, I cannot send a unicode stream throuth socket with
>python while all the other languages as perl,c and java can do it.

I don't know about perl.  What I think you mean by unicode in C most probably is
the wchar_t, which is Unicode encoded as 'ucs-2' or 'utf-16' (little or big
endian, depending on your platform) or maybe a 4-byte int, for which I don't
know a Python equivalent.  And I /assume/ in Java that Unicode is equivalent to
'utf-16' encoded strings when input/output.

Perhaps Unicode encoded as 'utf-16' is what you're after.  However, Unicode
encoded as 'utf-8' (like others also suggested) might be what you /should/ be
using, given that this encoding has some attractive properties (no null bytes,
no spurious control characters etc).

Don't interpret as weakness the explicitness requested from Python.
-- 
TZOTZIOY, I speak England very best.
"Be strict when sending and tolerant when receiving." (from RFC1958)
I really should keep that in mind when talking with people, actually...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How would you program this?

2005-03-03 Thread Duncan Smith

"engsol" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> There is a number puzzle which appears in the daily paper.
> Because I'm between Python projects, I thought it might be
> fun to write a program to solve it20 minute job, max.
>
> On closer inspection, it became apparent that it's not a
> simple thing to program. How would you approach it?
>
> The puzzle: a 4 x 4 grid. The rows are summed (and given), the
> cols are summed (and given), and the two diagonals are summed,
> and given. In addition, 4 clues are given, but none of the 4 are in
> the same row or col.
>
> Example from today's paper:...solution time is 8 minutes, 1 second,
> so they say.
>
> The set of allowable numbers  is 1 thru 9
>
> Rows:
> 3 + B + C + D = 22
> E + F + 8 + H = 26
> I + J + K + 8 = 31
> M + 7 + O + P = 25
>
> Col sums:
> 24, 18, 31, 31
>
> Diag sums:
> 3 + F + K + P = 24
> M + J + 8 + D = 24
>
>
>
> The first impulse is to just brute force it with nested for loops,
> but the calculator shows the possible combinations are
> 9^12 = 5,159,780,352, which would take much too long.
>
> Another approach would be to inspect each square and determine
> what the range of reasonable numbers would be. For example,
>
> if A + 9 + C + D = 14, then A, C, D can only have a value of 1 or 2 or 3,
> which would greatly reduce the for loop range of A, C and D.
> While useful, it's still a manual task.
>
> I can't help but think there's a better way. If you have a real Python
> project, this isn't worth your time, but if a student, it might be a good
> exercise to think how you'd do it.
> Norm B

This sort of thing actually is a real Python project for me.  Unfortunately
you don't generally (in practice) end up with constraints on diagonals in
contingency tables, so my code can't solve this particular problem.  You
might be interested in checking out the shuttle algorithm (Fienberg and
Dobra), and seeing if you can tweak it to handle more general constraints.

Duncan


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


Re: pytone / _bsddb

2005-03-03 Thread helmi03
Downgrading???
I think the author of this pytone software should upgrade. I just
upgrade all my python stuff in my FreeBSD box to python 2.4 :(

I had this same problem before too.

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


Re: passing lists

2005-03-03 Thread Steve Holden
Earl Eiland wrote:
This message contains the responses to two previous messages:
[...]

In response to Steve H., the traceback is
Traceback (most recent call last):
  File "../Devel_2.py", line 125, in ?
Inbound_Results = Parser.Sort(Inb_sequence,
"Inbound-dump-"+Run_ID+"-Dropped
.dmp", "Inbound-dump-"+Run_ID+"-Created.dmp")
  File
"/home/earl/ResearchProjects/IntrusionResistance/NewPhasee2/Parser.py",
l
ine 291, in Sort
if Raw_packet_queue[ctr][1] == Passed_IP: Last_Passed, Last_Dropped,
Raw_pac
ket_queue = Match(Created, Passed, Raw_packet_queue, Raw, False,
Last_Passed, La
st_Dropped, First_Created, ctr)
  File
"/home/earl/ResearchProjects/IntrusionResistance/NewPhasee2/Parser.py",
l
ine 132, in Match
Last_Passed = Raw_packet_queue[0][0][1]
TypeError: unsubscriptable object
On Wed, 2005-03-02 at 15:34, Steve Holden wrote:
Earl Eiland wrote:
def Match(..., Raw_packet_queue, ...):
...
print 'in Match, Raw_Packet_queue is', Raw_packet_queue # this returns
'Reader object at 0xaaa'
...
return [Last_Passed, Last_Dropped, Raw_packet_queue] # this causes
'unsubscriptable object'error message
#*
def Main(...):
Raw_packet_queue = []
...
Raw_packet_queue = enqueue(..., Raw_packet_queue, ...) # this works
... 
if Raw_packet_queue[ctr][1] == Passed_IP: Last_Passed, Last_Dropped,
   
 oops!
Raw_packet_queue = Match(..., Raw_packet_queue, ...) # the problem
starts here
...
Rule one: ALWAYS include the actual traceback, rather than providing 
your interporetation of what it means (though you are then free to do 
that, too).

What makes you think it's the Match() call that's causing the problem?
I'd be willing to bet money it's the double-subscripting of 
Raw_packet_queue - if item [ctr] on the Raw_packet_queue isn't a list or 
a dict then subscripting it by [1] will give you the error message that 
you quote.

But if you had included the traceback you would have made it unnecessary 
for me to use my psychic powers :-)

regards
 Steve
[...]
On Wed, 02 Mar 2005 14:05:18 -0700, Earl Eiland <[EMAIL PROTECTED]> wrote:

I have a program in which I'm passing a list to functions.  When I
reference an element in a function to which it is passed, I get the
error message "unsubscriptable object".  When printing the list contents
in that same function, I get "xxx is ".  How do
I pass a list?
Earl Eiland
Earl:
It seems you code isn't optimized for debugging :-)
Why all the use of lists? I suspect (though I don;t mean to demean your 
programming skill) that you might be better to define object classes to 
represent things like the elements of your Raw_packet_queue. Then, 
rather than having to refer to

  Raw_packet_queue[0][0][1]
you would be able to use something a little more helpful like
  Raw_packet_queue[0].pkt_hdr.something
which would make the code more readable and also more writable!
Anyhow, the problem appears to be somewhere other than you originally 
suggested, since the code you originally posted didn't IIRC, contain any 
reference to Raw_packet_queue[0][0][1], while the traceback specifically 
points to such a reference as the cause of the problem.

If Kent Johnson is wrong about the cause of the problem then please get 
back to the list. And think about refactoring the code to avoid all 
those lists and tuples - they don't appear to be the appropriate 
structures for optimum readability!

regards
 Steve
--
Meet the Python developers and your c.l.py favorites March 23-25
Come to PyCon DC 2005  http://www.pycon.org/
Steve Holden   http://www.holdenweb.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: What is the best way to handle a command line argument that includes an escape sequence like \n?

2005-03-03 Thread Steve Holden
Joe wrote:
Hi Steve,
I've been using Python for many years, just hadn't had to deal with an 
escape sequence in the command line args. :-) and couldn't find the solution 
in the docs.

It is easy to prove my assertion:
import sys
c = sys.argv[1]
print len(c)
print 'Line 1', c, 'Line 2'
Output:
2
Line 1 \n Line 2
The "2" appears to prove *my* assertion that the argument passed by the 
shell to your Python program consists of 2 characters, "\\" followed by "n".

Versus:
import sys
c = sys.argv[1]
print len(c)
print 'Line 1', c.decode('string_escape'), 'Line 2'
Output:
2
Line 1
Line 2
As does this.
Agreed, it is much easier on Unix to deal with this, I have not seen a way 
to get the XP command interpreter to allow a multiline command line as you 
described.

Your solution was exactly what I need.  I had an escape sequence entered on 
the command line and needed to decode the string so that Python used it as 
an escape sequence, in fact the sequence really is part of the output that 
the program produces.

In fairness it was Steven Bethard's solution that gave you the solution 
you needed. As long as ytour problem is solved, that's fine, and it 
appears that you've solved it in a reasonably cross-platform way.

Thanks again for your assistance.
Always happy to help when I can!
regards
 Steve
--
Meet the Python developers and your c.l.py favorites March 23-25
Come to PyCon DC 2005  http://www.pycon.org/
Steve Holden   http://www.holdenweb.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: converting time tuple to datetime struct

2005-03-03 Thread Michael Jard
Yeah, that was just an oversight while retyping the code. Thanks from
the prompt reply, it was just what I needed.

Mike

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


Re: binutils "strings" like functionality?

2005-03-03 Thread Fuzzyman
I don't know anything about binutils strings, other than that a quick
google reveals that you can search binary files for printable strings
with it.

In python the following code will read a binary file into a single
string :

long_string = open(filename, 'rb').read()

You can then slice long_string, iterate over it... or do whatever you
like with it.

Now you *ought* to be creating a proepr file handle and closing it. You
probably don't want to read the whole file into memory at once, etc
But implementing these thigns are trivial.

What particular aspect of 'strings' did you want to implement ?

Regards,

Fuzzy
http://www.voidspace.org.uk/python/index.shtml

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


tkinter entry eat chars?

2005-03-03 Thread phil
In a Tkinter entry field (or Pmw entry)
how could I eat charactres?
Say a certain char is keyed in. Say &
I notice in the event handler for .
I don't want any more charactres to display or
be in the field until I handle a see, in the
event handler, another character. Say ?
Can the event handler somehow destroy the char?
Thanks
--
http://mail.python.org/mailman/listinfo/python-list


tkinter absorb chars

2005-03-03 Thread phil
Sorry for the repost, but moderator
jeld the last one,
In a Tkinter entry field (or Pmw entry)
how could I eat charactres?
Say a certain char is keyed in. Say &
I notice in the event handler for .
I don't want any more charactres to display or
be in the field until I handle, in the
event handler, another character. Say ?
Can the event handler somehow destroy the chars
in the meantime?
Thanks
--
http://mail.python.org/mailman/listinfo/python-list


Re: tkinter absorb chars

2005-03-03 Thread Jeff Epler
On Wed, Mar 02, 2005 at 04:58:03PM -0600, phil wrote:
> Sorry for the repost, but moderator
> jeld the last one,

We saw both posts.

> In a Tkinter entry field (or Pmw entry)
> how could I eat charactres?

create a binding on the widget for the particular character you want to
treat specially.  If you want to suppress that character, return the
string "break" from the binding.  Example:

from Tkinter import *
t = Tkinter.Tk()
e = Tkinter.Entry(t); e.pack()
e.bind("x", lambda event: "break")

Jeff


pgpdlybvqgp9Z.pgp
Description: PGP signature
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: file.getvalue() with _ or other characters

2005-03-03 Thread Peter Otten
[EMAIL PROTECTED] wrote:

> I do this to get a htmlTOtext file

[...]

> But then the _ characters are away.
> is it possible to keep that character in file.getvalue()

Just to make sure: you did look into the HTML file and verified that there
are actually underscores and not spaces that are _rendered_ similar to "_"
via some text or CSS?

Peter


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


Re: binutils "strings" like functionality?

2005-03-03 Thread Larry Bates
Take a look at python's struct module in the standard library.
Many people use it to manipulate binary objects at the byte
level with great success.

Larry Bates


cjl wrote:
> Hey all:
> 
> I am working on a little script that needs to pull the strings out of a
> binary file, and then manipulate them with python.
> 
> The command line utility "strings" (part of binutils) has exactly the
> functionality I need, but I was thinking about trying to implement this
> in pure python.
> 
> I did some reading on opening and reading binary files, etc., and was
> just wondering if people think this is possible, or worth my time (as a
> learning exercise), or if something like this already exists.
> 
> -cjl
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: binutils "strings" like functionality?

2005-03-03 Thread Kent Johnson
cjl wrote:
Hey all:
I am working on a little script that needs to pull the strings out of a
binary file, and then manipulate them with python.
The command line utility "strings" (part of binutils) has exactly the
functionality I need, but I was thinking about trying to implement this
in pure python.
I did some reading on opening and reading binary files, etc., and was
just wondering if people think this is possible, or worth my time (as a
learning exercise), or if something like this already exists.
I think a bare-bones version is pretty simple:
- read the file
- use re.split() to split on non-printable characters (string.printable could 
be handy here)
- print anything in the resulting list that is at least 4 characters
Since you mention this as a learning exercise I'll refrain from posting code but it's only a handful 
of lines...of course implementing all of 'strings' is a bit more work.

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


Re: Multiline regex help

2005-03-03 Thread Steven Bethard
Yatima wrote:
Hey Folks,
I've got some info in a bunch of files that kind of looks like so:
Gibberish
53
MoreGarbage
12
RelevantInfo1
10/10/04
NothingImportant
ThisDoesNotMatter
44
RelevantInfo2
22
BlahBlah
343
RelevantInfo3
23
Hubris
Crap
34
and so on...
Anyhow, these "fields" repeat several times in a given file (number of
repetitions varies from file to file). The number on the line following the
"RelevantInfo" lines is really what I'm after. Ideally, I would like to have
something like so:
RelevantInfo1 = 10/10/04 # The variable name isn't actually important
RelevantInfo3 = 23   # it's just there to illustrate what info I'm
 # trying to snag.
Score[RelevantInfo1][RelevantInfo3] = 22 # The value from RelevantInfo2
A possible solution, using the re module:
py> s = """\
... Gibberish
... 53
... MoreGarbage
... 12
... RelevantInfo1
... 10/10/04
... NothingImportant
... ThisDoesNotMatter
... 44
... RelevantInfo2
... 22
... BlahBlah
... 343
... RelevantInfo3
... 23
... Hubris
... Crap
... 34
... """
py> import re
py> m = re.compile(r"""^RelevantInfo1\n([^\n]*)
....*
...^RelevantInfo2\n([^\n]*)
....*
...^RelevantInfo3\n([^\n]*)""",
...re.DOTALL | re.MULTILINE | re.VERBOSE)
py> score = {}
py> for info1, info2, info3 in m.findall(s):
... score.setdefault(info1, {})[info3] = info2
...
py> score
{'10/10/04': {'23': '22'}}
Note that I use DOTALL to allow .* to cross line boundaries, MULTILINE 
to have ^ apply at the start of each line, and VERBOSE to allow me to 
write the re in a more readable form.

If I didn't get your dict update quite right, hopefully you can see how 
to fix it!

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


using Tkinter from IDLE

2005-03-03 Thread neutrinman
How do I use Tkinter from IDLE? Tkinter can be used from IDLE attached
(Bto python 2.2, IDLE 0.8. But I couldn't use from IDLE attached to
(Bpython 2.3, IDLE 1.0.3. When I execute the code below:
(Bfrom Tkinter import *
(Broot = Tk()
(Bthe window appears form IDLE 0.8, but not from IDLE 1.0.3.
(B
(B-- 
(Bhttp://mail.python.org/mailman/listinfo/python-list

Re: How to delete a module file

2005-03-03 Thread Thomas Heller
Dennis Lee Bieber <[EMAIL PROTECTED]> writes:

> On Thu, 03 Mar 2005 12:29:58 +0100, Olivier Ravard
> <[EMAIL PROTECTED]> declaimed the following in
> comp.lang.python:
>
>> 
>> So, what is the solution ?
>> 
>> 
>   As the old joke concludes... "... stop doing that".
>
>   I don't think Windows has any means to delete a file that it
> considers open. You might be able to /rename/ it to something else
> (since the OS knows where the "open" file is, it doesn't care about the
> name anymore), but the delete still has to be done after all users of
> the file have closed it.

Even if you are able to remove/rename the file, it won't help you
anyway, because there's no way to reload an extension module in a sane
way.  AFAIK.

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


greedy match wanted

2005-03-03 Thread alexk
Hi,

I would like to request your help.

My problem is as follows. I want to match urls, and therefore I have a
group
of long valid domain names in my regex:

 (?:com|org|net|biz|info|ac|cc|gs|ms|
 sh|st|tc|tf|tj|to|vg|ad|ae|af|ag|
 com\.ag|ai|off\.ai|al|an|ao|aq|
 com\.ar|net\.ar|org\.ar|as|at|co\.at| ... ) ...

However, for a url like kuku.com.to it matches the kuku.com part,
while I want it to match the whole kuku.com.to. Notice that both "com"
and "com.to" are present in the group above.

1. How do I give precedence for "com.to" over "com" in the above group
?
Maybe I can somehow sort it by lexicographic order and then by length,
or divide it to a set of sub-groups by length ?

Thanks for any help,
Alex.

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


Re: binutils "strings" like functionality?

2005-03-03 Thread Steve Holden
Kent Johnson wrote:
cjl wrote:
Hey all:
I am working on a little script that needs to pull the strings out of a
binary file, and then manipulate them with python.
The command line utility "strings" (part of binutils) has exactly the
functionality I need, but I was thinking about trying to implement this
in pure python.
I did some reading on opening and reading binary files, etc., and was
just wondering if people think this is possible, or worth my time (as a
learning exercise), or if something like this already exists.

I think a bare-bones version is pretty simple:
- read the file
- use re.split() to split on non-printable characters (string.printable 
could be handy here)
- print anything in the resulting list that is at least 4 characters

The binutils version may well use a zero terminator character to 
differentiate between random chunks of printable characters and those 
explicitly genreated as strings from C. Or it may not ...

Since you mention this as a learning exercise I'll refrain from posting 
code but it's only a handful of lines...of course implementing all of 
'strings' is a bit more work.

regards
 Steve
--
Meet the Python developers and your c.l.py favorites March 23-25
Come to PyCon DC 2005  http://www.pycon.org/
Steve Holden   http://www.holdenweb.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: binutils "strings" like functionality?

2005-03-03 Thread Fredrik Lundh
"cjl" wrote:

> I am working on a little script that needs to pull the strings out of a
> binary file, and then manipulate them with python.
>
> The command line utility "strings" (part of binutils) has exactly the
> functionality I need, but I was thinking about trying to implement this
> in pure python.

something like this could work:

import re

text = open(file, "rb").read()

for m in re.finditer("([\x20-\x7f]{4,})[\n\0]", text):
print m.start(), repr(m.group(1))

you may wish to modify the "[\x20-\x7f]" part to match your definition of
"printable characters".  "[-,.!?\w ]" is a reasonable choice in many cases...

if the files can be huge, use the mmap module to map the file into memory,
and run the RE on the mapped view.

 



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


Re: Regular Expressions: large amount of or's

2005-03-03 Thread Manlio Perillo
On Tue, 1 Mar 2005 15:03:50 -0500, Tim Peters <[EMAIL PROTECTED]>
wrote:

>[André Søreng]
>> Given a string, I want to find all ocurrences of
>> certain predefined words in that string. Problem is, the list of
>> words that should be detected can be in the order of thousands.
>>
>> With the re module, this can be solved something like this:
>>
>> import re
>>
>> r = re.compile("word1|word2|word3|...|wordN")
>> r.findall(some_string)
>>
>> Unfortunately, when having more than about 10 000 words in
>> the regexp, I get a regular expression runtime error when
>> trying to execute the findall function (compile works fine, but slow).
>>
>> I don't know if using the re module is the right solution here, any
>> suggestions on alternative solutions or data structures which could
>> be used to solve the problem?
>
>Put the words you're looking for into a set (or as the keys of a dict
>in older Pythons; the values in the dict are irrelevant).
>
>I don't know what you mean by "word", so write something that breaks
>your string into what you mean by words.  Then:
>
>for word in something_that_produces_words(the_string):
>if word in set_of_words:
># found one
>


I have the same problem.
Unfortunately the meaning of a "word" depends on the word.
As an example I would like to count the number of occurrences of
movies titles in some text.

Maybe lex is more optimized?
Unfortunately is seems that there are no lex versions that generate
python (or PyRex) code.



Thanks and regards   Manlio Perillo

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


Accessing Python parse trees

2005-03-03 Thread Manlio Perillo
Hi.
With module parser it is possible to access Python parse trees.
But this only works for 'external' source.
I would like to known if, at least in theory, it can be possible to
access Python parse trees from 'inside' a script.


As a simple example:


def on_parsing(ast):
 ...


@parsing -> on_parsing
some statement



This will call on_parsing function with the AST object generated from
the next statement:

on_parsing(parser.suit(somestatement))



Thanks and regards  Manlio Perillo

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


Re: Regular Expressions: large amount of or's

2005-03-03 Thread Manlio Perillo
Hi.

Python allows to subclass builtin classes but the Python Interpreter
uses builtin types.
As an example keyword arguments are inserted in a dict but I would
like to use an user defined SortedDict.

There are plans to add such a feature in a future version?


Thanks and regards  Manlio Perillo
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Regular Expressions: large amount of or's

2005-03-03 Thread Manlio Perillo
Hi.

Python allows to subclass builtin classes but the Python Interpreter
uses builtin types.
As an example keyword arguments are inserted in a dict but I would
like to use an user defined SortedDict.

There are plans to add such a feature in a future version?


Thanks and regards  Manlio Perillo
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: greedy match wanted

2005-03-03 Thread Kent Johnson
alexk wrote:
My problem is as follows. I want to match urls, and therefore I have a
group
of long valid domain names in my regex:
 (?:com|org|net|biz|info|ac|cc|gs|ms|
 sh|st|tc|tf|tj|to|vg|ad|ae|af|ag|
 com\.ag|ai|off\.ai|al|an|ao|aq|
 com\.ar|net\.ar|org\.ar|as|at|co\.at| ... ) ...
However, for a url like kuku.com.to it matches the kuku.com part,
while I want it to match the whole kuku.com.to. Notice that both "com"
and "com.to" are present in the group above.
1. How do I give precedence for "com.to" over "com" in the above group
?
Maybe I can somehow sort it by lexicographic order and then by length,
or divide it to a set of sub-groups by length ?
According to the docs for re:
"As the target string is scanned, REs separated by "|" are tried from left to right. When one 
pattern completely matches, that branch is accepted. This means that once A matches, B will not be 
tested further, even if it would produce a longer overall match. In other words, the "|" operator is 
never greedy."

So putting "com.to" before "com" does what you want.
 >>> import re
 >>> re.search(r'com|com\.to', 'kuku.com.to').group()
'com'
 >>> re.search(r'com\.to|com', 'kuku.com.to').group()
'com.to'
Kent
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to write python plug-ins for your own python program?

2005-03-03 Thread David M. Cooke
Simon Wittber <[EMAIL PROTECTED]> writes:

>> You mean like 'import'? :)
>
> That's how I would do it. It's the simplest thing, that works.
>
> exec("import %s as plugin" % pluginName)
> plugin.someMethod()
>
> where pluginName is the name of the python file, minus the ".py" extension.

You'd better hope someone doesn't name their plugin
'os; os.system("rm -rf /"); import sys'

Use __import__ instead.

-- 
|>|\/|<
/--\
|David M. Cooke
|cookedm(at)physics(dot)mcmaster(dot)ca
-- 
http://mail.python.org/mailman/listinfo/python-list


replacing builtins (WAS: Regular Expressions: large amount of or's)

2005-03-03 Thread Steven Bethard
Manlio Perillo wrote:
> Python allows to subclass builtin classes but the Python Interpreter
> uses builtin types.
> As an example keyword arguments are inserted in a dict but I would
> like to use an user defined SortedDict.
>
> There are plans to add such a feature in a future version?
Note that it's polite to start a new thread when you change topic.
That said, I don't expect Python will ever let you replace things like 
this -- it means that libraries would not be able to depend on 
consistent behavior across users.  What would happen if I did something 
like:

class BrokenDict(dict):
def __getitem__(self, key):
raise TypeError
and then set Python's dict to this dict instead?  I would break pretty 
much every function that takes a **kwargs argument.

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


py2exe

2005-03-03 Thread demon_slayer2839
I'm a newbie at programmin. I've downloaded Python and am going through
"How to think like a computer scientist". I've also downloaded py2exe
and I don't really know how to use it. For one what is the disutil?
thanks for the help yall.

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


problem with recursion

2005-03-03 Thread vegetax
I am trying to make convert a directory "tree" in a list of list, but cant
find the algoritm =( ,for example a directory tree like :

+root
 +doc
   ele1
   ele2
   +doc3
ele3
 +doc2
  ele4

 ele5

should convert into:

root[
 doc,
 [ele1,ele2,doc3,[ele3]],
 doc2,
 [ele4],
 ele5
]

I dont have any idea how to do it =( ,so far i get something like
this : [doc1,ele1,ele2,doc3,ele3,doc2,ele4,ele5] instead of
   [doc1,[ele1,ele2,doc3,[ele3]],doc2,[ele4],ele5]

I need this in order to print a directory tree with htmlgen library which
uses nested lists to represent trees.

#!/usr/bin/python
from os import listdir
from os.path import isdir,join,basename

dirpath  = '/tmp/test/'
res = []

def rec(f):
print f
for ele in listdir(f):
ele = join(f,ele)
if isdir(ele):
# append the directory name  
  res.append(basename(ele))
rec(ele)
else :
res.append(basename(ele))

rec(dirpath)
print res
###

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


Re: using Tkinter from IDLE

2005-03-03 Thread Russell Blau
<[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]

> How do I use Tkinter from IDLE? Tkinter can be used from IDLE attached
> to python 2.2, IDLE 0.8. But I couldn't use from IDLE attached to
> python 2.3, IDLE 1.0.3. When I execute the code below:

> from Tkinter import *
> root = Tk()

> the window appears form IDLE 0.8, but not from IDLE 1.0.3.

Add the line:

root.mainloop()

at the end of your code.


-- 
I don't actually read my hotmail account, but you can replace hotmail with
excite if you really want to reach me.



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


Re: rearrange text

2005-03-03 Thread Russell Blau
"Daniel Skinner" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> If I have the following text
>
> var = '1,2,3,4'
>
> and I want to use the comma as a field delimeter and rearrange the
> fields to read
>
> '1,3,2,4'
>
> How would I accomplish this in python?

Well, it kind of depends on how you want to do the rearranging, whether the
data in the fields is always going to be numbers or could be some other kind
of object, etc.

In general, though, what you seem to be looking for is:

mylist = var.split(',')
rearrange(mylist)
newvar = ','.join(mylist)


-- 
I don't actually read my hotmail account, but you can replace hotmail with
excite if you really want to reach me.



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


Grid not getting updated

2005-03-03 Thread Gensek
I'm using wxPython. My program has a loop where it puts data in a grid
cell, and then goes for some more processing. Well, some of the cells
are used to indicate progress, but their usefulness is hindered by the
fact that the grid refuses to change until the loop finishes, when it
shows the final result.

What can I do about this?

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


Grid not getting updated

2005-03-03 Thread Gensek
I have a wxPython program, and it has a loop. I want to be able to
break the loop by pushing a button. But it doesn't react to events
until the loop finishes, which is sort of pointless.

What's the best way to get it to work? Do I need threads? Or is there a
more convenient way?

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


Re: problem with recursion

2005-03-03 Thread [EMAIL PROTECTED]
take a look at os.walk, it is documented in the library documentation

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


Re: How would you program this?

2005-03-03 Thread Russell Blau
"Dennis Lee Bieber" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> On Wed, 2 Mar 2005 13:44:07 -0500, "Russell Blau" <[EMAIL PROTECTED]>
> declaimed the following in comp.lang.python:
>
> >
> > What you have is a set of 10 linear equations in 11 variables.  Normally
>
> Worse -- there are 12 unknowns in the 10 equations...

Yup, I need to grow two more fingers, I guess.


-- 
I don't actually read my hotmail account, but you can replace hotmail with
excite if you really want to reach me.




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


Re: py2exe

2005-03-03 Thread James Stroud
I'm sure that you will get plenty of lambasting for this kind of post, but 
since you are new...

(1) try google first
(2) read the "how to be a hacker" page:
  
(3) read the "how to ask questions" page:
  

Then post.

Welcome to the python community. We look forward to interacting with you.

James

On Thursday 03 March 2005 09:59 am, [EMAIL PROTECTED] wrote:
> I'm a newbie at programmin. I've downloaded Python and am going through
> "How to think like a computer scientist". I've also downloaded py2exe
> and I don't really know how to use it. For one what is the disutil?
> thanks for the help yall.

-- 
James Stroud, Ph.D.
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095
-- 
http://mail.python.org/mailman/listinfo/python-list


Ruby on Rails or Perl's Maypole..is there a Python equivalent

2005-03-03 Thread Gary Nutbeam
I've noticed that the Perl camp has a very nice web/database environment
called Maypole. Ruby has the Rails environment which on the surface seems
similar to Maypole. I can't find anything in Python that ties a database
to a web interface anywhere near as well as Ruby on Rails or Maypole.

I see the behemoth Zope having the best web/database integration, but
unfortunately I don't want to spent weeks writing xml for the interface.

Does anyone know of something similar to Rails or Maypole in Python?

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


Re: py2exe

2005-03-03 Thread jpolera
This looks like a pretty quick introduction/instruction page for
py2exe:

http://starship.python.net/crew/theller/py2exe/

How did we ever live without Google?


[EMAIL PROTECTED] wrote:
> I'm a newbie at programmin. I've downloaded Python and am going
through
> "How to think like a computer scientist". I've also downloaded py2exe
> and I don't really know how to use it. For one what is the disutil?
> thanks for the help yall.

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


Re: any Python equivalent of Math::Polynomial::Solve?

2005-03-03 Thread Alex Renelt
Cousin Stanley wrote:
Alex 
  Thanks for posting your generalized numarray
  eigenvalue solution 
  It's been almost 30 years since I've looked at
  any characteristic equation, eigenvalue, eignevector
  type of processing and at this point I don't recall
  many of the particulars 
  Not being sure about the nature of the monic( p ) function,
  I implemented it as an element-wise division of each
  of the coefficients 
This is correct. The aim is that p has a leading coefficient that equals 1.
  Is this anywhere near the correct interpretation
  for monic( p ) ?
  Using the version below, Python complained
  about the line 
. M[ -1 , : ] = -p[ : -1 ]
Works for me. Did you perhaps use a list (type(p) == type([])) for p?
Then python does not know what -p means (numeric or numarray does).
  So, in view of you comments about slicing in you follow-up,
  I tried without the slicing on the right 
.. M[ -1 , : ] = -p[ -1 ]
That's wrong because you don't set a slice but a single item!
Old code should work. We need all coefficients but the leading coeff. So 
take the slice p[:-1].

  The following code will run and produce results,
  but I'm wondering if I've totally screwed it up
  since the results I obtain are different from
  those obtained from the specific 5th order Numeric
  solution previously posted here 
. from numarray import *
.
. import numarray.linear_algebra as LA
.
. def monic( this_list ) :
.
. m  = [ ]
.
. last_item = this_list[ -1 ]
.
. for this_item in this_list :
.
. m.append( this_item / last_item )
.
. return m
your function equals the following one:
def monic(p): return p / p[-1]
But you have to ensure that p is an array object. It does element-wise 
operations per default.

Remember we need future division or take float(p[-1]) or the denominator.
.
.
. def roots( p ) :
.
. p = monic( p )
.
. n = len( p )   # degree of polynomial
The degree is len(p) -1 or something smaller (some people are calling 
len(p) -1 a "degree bound" instead). It is smaller if p contains leading 
zeros which should be deleted, e.g. P(x) = x^2 + 4 x + 4 could be entered as
	p = array([4, 4, 1, 0, 0])
which would produce a deg of 4 instead of 2.
.
. z = zeros( ( n , n ) )
.
. M = asarray( z , typecode = 'f8' )  # typecode = c16, complex
.
. M[ : -1 , 1 : ] = identity( n - 1 )
.
. M[ -1 , : ] = -p[ -1 ]# removed :  slicing on the right
.
. return LA.eigenvalues( M )
.
.
. coeff = [ 1. , 3. , 5. , 7. , 9. ]
remember to use an array or convert it on-the-fly inside your roots 
function:

M[-1,:] = - asarray(p)[:-1]
.
. print 'Coefficients ..'
. print
. print '%s' % coeff
. print
. print 'Eigen Values .. '
. print
.
. eigen_values = roots( coeff )
.
. for this_value in eigen_values :
.
. print '%s' % this_value
.
Any clues would be greatly appreciated 

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


  1   2   3   >