parsing a dbIII file

2007-08-07 Thread korovev76
Hello everybody, I'm new to python (...I work with cobol...)

I have to parse a file (that is a dbIII file) whose stucture look like
this:
|string|, |string|, |string that may contain commas inside|, 1, 2, 3, |
other string|

Is there anything in python that parses this stuff?


thanks a lot
korovev

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


Re: parsing a dbIII file

2007-08-07 Thread Steve Holden
[EMAIL PROTECTED] wrote:
> Hello everybody, I'm new to python (...I work with cobol...)
> 
> I have to parse a file (that is a dbIII file) whose stucture look like
> this:
> |string|, |string|, |string that may contain commas inside|, 1, 2, 3, |
> other string|
> 
> Is there anything in python that parses this stuff?
> 
> 
> thanks a lot
> korovev
> 
That's not a standard dBaseIII data file though, correct? It looks more 
like something that was produced *from* a dBaseIII file.

If the format is similar to Excel's CSV format then the csv module from 
Python's standard library may well be what you want. Otherwise there are 
parsers at all levels - one called PyParsing is quite popular, and I am 
sure other readers will have their own suggestions.

I am not sure whether the pipe bars actually appear in your data file, 
so it is difficult to know quite exactly what to suggest, but I would 
play with the file in an interactive interpreter session first to see 
whether csv can do the job.

Good luck with your escape from COBOL!

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

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


Re: help with flexible decorators

2007-08-07 Thread Bruno Desthuilliers
james_027 a écrit :
> Hi,
> 
> I want to write a flexible decorators to edit a function that may have
> 1 or more arguments...
> 
> def enhance(func):
> def new(x):
> #do something ...
> return func(x)
> return new
> 
> @enhance
> def method_a(x):
> #do something ...
> 
> While the enhance decorator work with functions of 1 argument, how do
> I make it to work with more than one arguments.

Use *args (for positional args) and **kw (for keyword args):

def enhance(func):
 def new(*args, **kw):
 #do something ...
 return func(*args, **kw)
 return new

@enhance
def method_a(x):
 #do something ...


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


Re: parsing a dbIII file

2007-08-07 Thread korovev76
On 7 Ago, 09:21, Steve Holden <[EMAIL PROTECTED]> wrote:

> That's not a standard dBaseIII data file though, correct? It looks more
> like something that was produced *from* a dBaseIII file.
yeap... unfortunately it is not...



> Good luck with your escape from COBOL!

i'm not escaping by now... Actually I'd like to use cobol for the rest
of my life (as a programmer) ;-)
But thanx anyway!

korovev

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


Regular Expression Groups - loop

2007-08-07 Thread shahargs
Hi,
I'm trying to write application which parse one page to sentences and
then, check every group for few things.

The code:
rawstr = r"""([^.?!]+[.?!])"""
regex=re.compile(rawstr)
matchs=regex.search(document)
document, is the text i parsing. I cheked it in Kodos, and everything
worked well. but, i'm trying to write for loop which check every
group.

I tried:
for group in matchs.groups():
but then, it's check only the first group. and i tried:
for group in matchs.group():
but then it's checking every letter, not every sentence.

is anyone know how i should write this loop to check every group on
the groups collection that the regular expression return?

Shahar.

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


Re: boolean operations on sets

2007-08-07 Thread Bruno Desthuilliers
Flavio a écrit :
> Hi, I have been playing with set operations lately and came across a
> kind of surprising result given that it is not mentioned in the
> standard Python tutorial:
> 
> with python sets,   intersections  and unions are supposed to be done
> like this:
> In [7]:set('casa') & set('porca')
> Out[7]:set(['a', 'c'])
> 
> In [8]:set('casa') | set('porca')
> Out[8]:set(['a', 'c', 'o', 'p', 's', 'r'])
> 
> and they work correctly. Now what is confusing is that if you do:
> 
> In [5]:set('casa') and set('porca')
> Out[5]:set(['a', 'p', 'c', 'r', 'o'])
> 
> In [6]:set('casa') or set('porca')
> Out[6]:set(['a', 'c', 's'])
> 
> The results are not what you would expect from an AND  or OR
> operation, from the mathematical point of view! aparently the "and"
> operation is returning the the second set, and the "or" operation is
> returning the first.

the semantic of 'and' and 'or' operators in Python is well defined and 
works the same for all types AFAIK.

> If python developers wanted these operations to reflect the
> traditional (Python) truth value for data structures: False for empty
> data structures and True otherwise, why not return simply True or
> False?
>
> So My question is: Why has this been implemented in this way? 

Because Python long lived without the 'bool' type - considering None, 
numeric zero, empty string and empty containers as false (ie : 
'nothing', and anything else as true (ie : 'something').

> I can
> see this confusing many newbies...

Yes, and this has been one of the arguments against the introduction of 
the bool type. Changing this behaviour would have break lot of existing 
code, and indeed, not changing it makes things confusing.

OTHO - and while I agree that there may be cases of useless complexities 
in Python -, stripping a language from anything that might confuse a 
newbie doesn't make great languages.
-- 
http://mail.python.org/mailman/listinfo/python-list


re: mmm-mode, python-mode and doctest-mode?

2007-08-07 Thread Edward Loper
[John J Lee]
> Is it possible to get doctest-mode to work with mmm-mode and python-mode 
> nicely so that docstrings containing doctests are editable in 
> doctest-mode?

I recently released a new version of doctest-mode [1], and I came across 
your email [2] (it was on the first page of google hits for 
"doctest-mode").  So I decided to have a go at getting doctest-mode to 
play nicely with mmm-mode.  The result is available here:

https://python-mode.svn.sf.net/svnroot/python-mode/trunk/python-mode/doctest-mode.el

I still consider it alpha code (the version that's available for 
download on the official doctest-mode webpage [3] doesn't include the 
mmm-mode features), but it works pretty well for me.  If you want to 
give it a spin, let me know what you think.  The following should load 
everything you need:

(autoload 'doctest-mode "doctest-mode" "doctest mode" t)
(autoload 'doctest-register-mmm-classes "doctest-mode")
(doctest-register-mmm-classes t t)

It defines 2 classes.  Quoting from the docstring for doctest-register- 
mmm-classes:

> `doctest-docstring'
> 
> Used to edit docstrings containing doctest examples in python-
> mode.  Docstring submode regions start and end with triple-quoted
> strings (\"\"\").  In order to avoid confusing start-string
> markers and end-string markers, all triple-quote strings in the
> buffer are treated as submode regions (even if they're not
> actually docstrings).  Use (C-c % C-d) to insert a new doctest-
> docstring region.  When `doctest-execute' (C-c C-c) is called
> inside a doctest-docstring region, it executes just the current
> docstring.  The globals for this execution are constructed by
> importing the current buffer's contents in Python.
> 
> `doctest-example'
> 
> Used to edit doctest examples in text-editing modes, such as
> `rst-mode' or `text-mode'.  Docstring submode regions start with
> optionally indented prompts (>>>) and end with blank lines.  Use
> (C-c % C-e) to insert a new doctest-example region.  When
> `doctest-execute' (C-c C-c) is called inside a doctest-example
> region, it executes all examples in the buffer.

Take care,
-Edward

[1] doctest-mode 0.4 announcement:
 
http://mail.python.org/pipermail/python-announce-list/2007-August/006038.html

[2] email re mmm-mode:
 http://mail.python.org/pipermail/python-list/2005-November/354482.html

[3] doctest-mode homepage:
 http://www.cis.upenn.edu/~edloper/projects/doctestmode/

[4] doctest-mode walkthrough:
 http://tinyurl.com/25bljc

[5] doctest-mode subversion:
 
https://python-mode.svn.sf.net/svnroot/python-mode/trunk/python-mode/doctest-mode.el


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


Re: Regular Expression Groups - loop

2007-08-07 Thread Peter Otten
 [EMAIL PROTECTED] wrote:

> I'm trying to write application which parse one page to sentences and
> then, check every group for few things.
> 
> The code:
> rawstr = r"""([^.?!]+[.?!])"""
> regex=re.compile(rawstr)
> matchs=regex.search(document)
> document, is the text i parsing. I cheked it in Kodos, and everything
> worked well. but, i'm trying to write for loop which check every
> group.
> 
> I tried:
> for group in matchs.groups():
> but then, it's check only the first group. and i tried:
> for group in matchs.group():
> but then it's checking every letter, not every sentence.
> 
> is anyone know how i should write this loop to check every group on
> the groups collection that the regular expression return?

A group denotes a subexpression of a single match:

>>> re.compile("(a+)(b*)").search("xaaabbxbb").groups()
('aaa', 'bb')

To get multiple matches use the findall() or finditer() methods, e. g.

>>> for match in  re.compile("([^.?!]+[.?!])").finditer("Is that what you
want? Yes! At least I think so..."):
... match.group()
...
'Is that what you want?'
' Yes!'
' At least I think so.'

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


Re: Regular Expression Groups - loop

2007-08-07 Thread Marc 'BlackJack' Rintsch
On Tue, 07 Aug 2007 00:44:49 -0700, shahargs wrote:

> I'm trying to write application which parse one page to sentences and
> then, check every group for few things.
> 
> The code:
>   rawstr = r"""([^.?!]+[.?!])"""
>   regex=re.compile(rawstr)
>   matchs=regex.search(document)
> document, is the text i parsing. I cheked it in Kodos, and everything
> worked well. but, i'm trying to write for loop which check every
> group.
> 
> I tried:
>   for group in matchs.groups():
> but then, it's check only the first group. and i tried:

There is only one group in your regular expression.  I guess you are
confusing groups within one match with multiples matches in the text. 
`re.search()` finds exactly one sentence.  If you want all sentences use
`re.find_all()` or `re.find_iter()`.

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


Re: Regular Expression Groups - loop

2007-08-07 Thread shahargs
Thank You, Marc and Peter. now, it's working.

Shahar.

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


setuptools bbfreeze install egg error

2007-08-07 Thread vedrandekovic
Hello,

I was download egg file bbfreeze-0.95.2-py2.4-win32.egg ( for windows
of course ),and I have setuptools
version 0.6c6 after I try install this with setuptools:

$ ez_setup bbfreeze-0.95.2-py2.4-win32.egg
Traceback (most recent call last):
   File "C:\Python24\Lib\site-packages\ez_setup.py", line 226, in ?
  main(sys.argv[1:])
   File "C:\Python24\Lib\site-packages\ez_setup.py", line 183, in main
  from setuptools.command.easy_install import main
   File "C:\Python24\Lib\site-packages\setuptools\command
\easy_install.py", line 16, in ?
  from distutils import log,dir_util
ImportError: cannot import name log


Regards,
Vedran

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


get wikipedia source failed (urrlib2)

2007-08-07 Thread shahargs
Hi,
I'm trying to get wikipedia page source with urllib2:
usock = urllib2.urlopen("http://en.wikipedia.org/wiki/
Albert_Einstein")
data = usock.read();
usock.close();
return data
I got exception because HTTP 403 error. why? with my browser i can't
access it without any problem?

Thanks,
Shahar.

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


Re: How to use C enum in Python CTypes?

2007-08-07 Thread rozniy
On Aug 7, 2:11 pm, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote:
> On Tue, 07 Aug 2007 04:57:19 +, rozniy wrote:
> > typedef enum olss_tag
> >{
> >OLSS_AD,
> >OLSS_DA,
> >OLSS_DIN,
> >OLSS_DOUT,
> >OLSS_SRL,
> >OLSS_CT
> >}
> > OLSS;
>
> > I managed to fudge the HDEV, UINT and PHDASS types as CTypes c_long(),
> > but I am not sure how translate a C enum into Python...
>
> > This site
> >http://python.net/crew/theller/ctypes/tutorial.html#bugs-todo-and-non...
>
> > says that enumeration types is not implemented,
> > "Enumeration types are not implemented. You can do it easily yourself,
> > using c_int as the base class."
>
> I would just define constants:
>
> (OLSS_AD,
>  OLSS_DA,
>  OLSS_DIN,
>  OLSS_DOUT,
>  OLSS_SRL,
>  OLSS_CT) = map(ctypes.c_int, xrange(6))
>
> Ciao,
> Marc 'BlackJack' Rintsch- Hide quoted text -
>
> - Show quoted text -


Wouldn't that assign integer values 0 to 5 to the things? I don't know
if it'll give me the correct results.

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


Re: How to use C enum in Python CTypes?

2007-08-07 Thread Marc 'BlackJack' Rintsch
On Tue, 07 Aug 2007 02:13:38 -0700, rozniy wrote:

> On Aug 7, 2:11 pm, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote:
>> On Tue, 07 Aug 2007 04:57:19 +, rozniy wrote:
>> > This site
>> >http://python.net/crew/theller/ctypes/tutorial.html#bugs-todo-and-non...
>>
>> > says that enumeration types is not implemented,
>> > "Enumeration types are not implemented. You can do it easily yourself,
>> > using c_int as the base class."
>>
>> I would just define constants:
>>
>> (OLSS_AD,
>>  OLSS_DA,
>>  OLSS_DIN,
>>  OLSS_DOUT,
>>  OLSS_SRL,
>>  OLSS_CT) = map(ctypes.c_int, xrange(6))
> 
> Wouldn't that assign integer values 0 to 5 to the things?

Yes.

> I don't know if it'll give me the correct results.

It should.  Enumerations in C are more or less just integer constants.

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


Re: get wikipedia source failed (urrlib2)

2007-08-07 Thread shahargs
On 7   , 11:54, [EMAIL PROTECTED] wrote:
> Hi,
> I'm trying to get wikipedia page source with urllib2:
> usock = urllib2.urlopen("http://en.wikipedia.org/wiki/
> Albert_Einstein")
> data = usock.read();
> usock.close();
> return data
> I got exception because HTTP 403 error. why? with my browser i can't
> access it without any problem?
>
> Thanks,
> Shahar.

This source works fine for other site. the problem is in wikipedia. is
someone now any solution for this problem?

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


Re: Redirecting stderr to null and revert

2007-08-07 Thread greg
reubendb wrote:
> def nullStderr():
>   sys.stderr.flush()
>   err = open('/dev/null', 'a+', 0)
>   os.dup2(err.fileno(), sys.stderr.fileno())
> 
> def revertStderr():
>   sys.stderr = sys.__stderr__

You're doing the redirection at one level and
trying to revert it at a different level.

If this is a Python function that's doing its
output by writing to sys.stderr, there's a
much simpler way to do the redirection:

   sys.stderr = open('/dev/null', 'w')

(that's the Python builtin function 'open',
not the one in os). Then your revertStderr
function will work.

BTW I'd arrange for the reversion to be done
in a try-finally, e.g.

   nullStderr()
   try:
 do_something()
   finally:
 revertStderr()

so you won't get stuck with a redirected stderr
if an exception occurs, and thereby not be able
to see the traceback!

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


Re: get wikipedia source failed (urrlib2)

2007-08-07 Thread Lawrence Oluyede
<[EMAIL PROTECTED]> wrote:
> This source works fine for other site. the problem is in wikipedia. is
> someone now any solution for this problem?

Wikipedia, AFAIK, bans requests without a User Agent.
http://www.voidspace.org.uk/python/articles/urllib2.shtml#headers

-- 
Lawrence, oluyede.org - neropercaso.it
"It is difficult to get a man to understand 
something when his salary depends on not
understanding it" - Upton Sinclair
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Global package variable, is it possible?

2007-08-07 Thread Bruno Desthuilliers
Chris Allen a écrit :
> On Aug 6, 12:41 am, Bruno Desthuilliers  [EMAIL PROTECTED]> wrote:
>> Chris Allen a écrit :
>>
(snip)
>> Hi Chris...
>> I've read all the thread, and it seems that your problem is mostly to
>> share a single dynamic state (the config) between several modules. So I
>> do wonder: have you considered the use of the Singleton pattern (or one
>> of it's variants...) ?
> 
> Thanks, I don't know anything about python singletons. 

It's a design pattern, so it's not realluy language specific. I thought 
about this because some of your wordings in various posts in this thread 
clearly called for such a pattern, but Ben is right, it won't probably 
buy you more than a plain python module (which are one of the possible 
implementations of the Singleton pattern).
-- 
http://mail.python.org/mailman/listinfo/python-list


seeking tinter module

2007-08-07 Thread Jean-François Piéronne
I'm looking for a module name tinter (not tkinter...)

from http://www.vex.net/parnassus/apyllo.py?i=97497223
status: Dead and Gone

Google return no location to download it, only a few
articles mentionned it, for example:
http://www.ibm.com/developerworks/linux/library/l-python6.html


Does someone has still a copy of this module?


Thanks,

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


Re: regexp problem in Python

2007-08-07 Thread Ant
On Aug 3, 10:41 pm, Ehsan <[EMAIL PROTECTED]> wrote:
...
> what can I do? what's wrong whit this pattern? thanx for your comments

Nothing. There's something wrong with the code you are using the regex
with. Post it and we may be able to help. Like Lawrence has said, it's
likely to be that you are using m.group(1) with your match object
instead of m.group(0) - the former gets the first group (i.e.
everything between the first set of parens - in your case the wmv|3gp
expression), whereas the latter will return the entire match.

Post your actual code, not just the regex.

--
Ant...

http://antroy.blogspot.com/



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


Re: seeking tinter module

2007-08-07 Thread Peter Otten
Jean-François Piéronne wrote:

> I'm looking for a module name tinter (not tkinter...)
> 
> from http://www.vex.net/parnassus/apyllo.py?i=97497223
> status: Dead and Gone
> 
> Google return no location to download it, only a few
> articles mentionned it, for example:
> http://www.ibm.com/developerworks/linux/library/l-python6.html
> 
> 
> Does someone has still a copy of this module?

http://www.google.com/codesearch?q=lang%3Apython+file%3Atinter.py&hl=de&btnG=Code+suchen

gives one hit.

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


Re: How to use C enum in Python CTypes?

2007-08-07 Thread Jim Langston
"rozniy" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> On Aug 7, 2:11 pm, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote:
>> On Tue, 07 Aug 2007 04:57:19 +, rozniy wrote:
>> > typedef enum olss_tag
>> >{
>> >OLSS_AD,
>> >OLSS_DA,
>> >OLSS_DIN,
>> >OLSS_DOUT,
>> >OLSS_SRL,
>> >OLSS_CT
>> >}
>> > OLSS;
>>
>> > I managed to fudge the HDEV, UINT and PHDASS types as CTypes c_long(),
>> > but I am not sure how translate a C enum into Python...
>>
>> > This site
>> >http://python.net/crew/theller/ctypes/tutorial.html#bugs-todo-and-non...
>>
>> > says that enumeration types is not implemented,
>> > "Enumeration types are not implemented. You can do it easily yourself,
>> > using c_int as the base class."
>>
>> I would just define constants:
>>
>> (OLSS_AD,
>>  OLSS_DA,
>>  OLSS_DIN,
>>  OLSS_DOUT,
>>  OLSS_SRL,
>>  OLSS_CT) = map(ctypes.c_int, xrange(6))
>>
>> Ciao,
>> Marc 'BlackJack' Rintsch- Hide quoted text -
>>
>> - Show quoted text -
>
>
> Wouldn't that assign integer values 0 to 5 to the things? I don't know
> if it'll give me the correct results.

Yes, that's how C's and C++'s enums work, unless an override is given (which 
I know you can do in C++ for sure).  Otherwise, they are just numbers 
starting at 0.  The size of the intergers (byte, 2 bytes, 4 bytes, etc..) is 
implemenation defined I believe, but an int normally works. 


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


Re: seeking tinter module

2007-08-07 Thread Jean-François Piéronne
Peter Otten wrote:
> Jean-François Piéronne wrote:
> 
>> I'm looking for a module name tinter (not tkinter...)
>>
>> from http://www.vex.net/parnassus/apyllo.py?i=97497223
>> status: Dead and Gone
>>
>> Google return no location to download it, only a few
>> articles mentionned it, for example:
>> http://www.ibm.com/developerworks/linux/library/l-python6.html
>>
>>
>> Does someone has still a copy of this module?
> 
> http://www.google.com/codesearch?q=lang%3Apython+file%3Atinter.py&hl=de&btnG=Code+suchen
> 
> gives one hit.
> 

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


Re: seeking tinter module

2007-08-07 Thread Neil Cerutti
On 2007-08-07, Jean-François Piéronne <[EMAIL PROTECTED]> wrote:
> I'm looking for a module name tinter (not tkinter...)
>
> from http://www.vex.net/parnassus/apyllo.py?i=97497223
> status: Dead and Gone
>
> Google return no location to download it, only a few
> articles mentionned it, for example:
> http://www.ibm.com/developerworks/linux/library/l-python6.html
>
> Does someone has still a copy of this module?

Here's a Google Cache of the source code I managed to dig up:

http://64.233.169.104/search?q=cache:wRcuIGPk-yYJ:svn.wishy.org/svn/repos/geezer/trunk/boss3client/geezer/widgets/tinter.py+tinter.py&hl=en&ct=clnk&cd=1&gl=us

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


distutils

2007-08-07 Thread vedrandekovic
Hello again,

Is there any patch for python "distutils", for this

>>> from distutils import log,dir_util
ImportError: cannot import name log


Regards,
Vedran

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


Re: distutils

2007-08-07 Thread Steve Holden
[EMAIL PROTECTED] wrote:
> Hello again,
> 
> Is there any patch for python "distutils", for this
> 
 from distutils import log,dir_util
> ImportError: cannot import name log
> 
What version of Python are you running with? It looks as though there 
may be something wrong with your installation if it's recent:

[EMAIL PROTECTED] ~/Projects/Python
$ python
Python 2.5.1 (r251:54863, May 18 2007, 16:56:43)
[GCC 3.4.4 (cygming special, gdc 0.12, using dmd 0.125)] on cygwin
Type "help", "copyright", "credits" or "license" for more information.
 >>> from distutils import log
 >>> import distutils.log
 >>>

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

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


ensuring GNU readline isn't used

2007-08-07 Thread Josh Paetzel
Is there a way to ensure that GNU readline isn't used (even though
support may have been compiled in?).  I'm experiencing a licensing
problem, I'd like to use the "cmd" module, for example, but my code is
proprietary and hence, if cmd uses readline, I can't use cmd.
Unfortunately, I can't control if the Python interpreter my customers
may be using has readline compiled in.  So, I'm wondering if there is
anyway to tell Python libraries like "cmd" to not use GNU's readline?
 
Alternatively, could we just include pyreadline as readline instead?

-- 
Thanks,

Josh Paetzel


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

Re: ensuring GNU readline isn't used

2007-08-07 Thread Duncan Booth
Josh Paetzel <[EMAIL PROTECTED]> wrote:

> Is there a way to ensure that GNU readline isn't used (even though
> support may have been compiled in?).  I'm experiencing a licensing
> problem, I'd like to use the "cmd" module, for example, but my code is
> proprietary and hence, if cmd uses readline, I can't use cmd.

I think you have misread the GPL: just because your non-GPL code *can* be 
used with something covered by the GPL doesn't mean your code is infected 
by the GPL. Your code doesn't require a GPL module to run (you can use a 
version of cmd compiled without readline), and you aren't attempting to 
distribute it with a GPL module, so you don't need to care how the end user 
chooses to run it.

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


Re: Importing * From a Package

2007-08-07 Thread Patrick Doyle
> There's no reliable way to differentiate between names which you defined
> using something other than an import statement, names you defined with an
> import statement with the intent of publishing them as part of your external
> API, and names you defined with an import statement which you only intended
> to use internally.  So Python doesn't even try to differentiate betweem them.
>
ok, that makes sense

> >"[It] imports whatever names are defined in the package [including]
> >any submodules of the package that were explicitly loaded by previous
> >import statements."
This is the part that has me confused -- why does "from package import
*" go on to import names that were explicitly loaded by previous
import statements?

Here is a contrived example (contrived by virtue of culling it out of
an existing code base I was reorganizing into packages when I stumbled
across this:

Directory structure:
./
./SDRGen
./SDRGen/__init__.py
./SDRGen/TFGenerator.py

The SDRGen/__init__.py file is empty.
The SDRGen/TFGenerator.py file contains the following 2 lines:

class TFGenerator:
pass


Now, at the python prompt I type (and get) the following:

>>> from SDRGen.TFGenerator import *
>>> TFGenerator

>>> from SDRGen import *
>>> TFGenerator
http://mail.python.org/mailman/listinfo/python-list


Re: step through .py file in a .NET application written in C# in Visual Studio

2007-08-07 Thread Paul McGuire
On Aug 6, 5:22 pm, Bo <[EMAIL PROTECTED]> wrote:
> Hello All,
>
> I am experimenting IronPython in Visual Studio.  Here is what I have,
> what I did and what I want
>
> 1.  I have installed Visual Studio SDK 4.0 according to this 
> bloghttp://blogs.msdn.com/aaronmar/archive/2006/02/16/a-bit-more-on-ironp...
>
> If I run Visual Studio under Experimental Hive, a Python file opened
> is color coded.
>
> 2.  Also, my computer has apparently installed some IronPython DLL
> because my Visual Studio can recoginize the following class:
> IronPython.Hosting.PythonEngine.
>
> If I declare something like the following in Visual Studio:
>
> public static class MyPythonClass {
>private static IronPython.Hosting.PythonEngine   MY_ENGINE;
>   //suppose I have created an instance of PhythonEngine and assigned
> to MY_ENGINE
>
>
> }
>
> If I do "Go to Definition" of PythonEngine, I can navigate to the
> Definition of PythonEngine, but it is from MetaData.
>
> 3.  In my .NET application (written in C#) , I can invoke the
> execution of an external python file using something like:
> MyPythonClass.MY_ENGINE.ExecuteFile("myPythonFileWithAbsolutePath.py")
>
> The python file (myPythonFileWithAbsolutePath.py) can be executed all
> right, but I want to step through it to debug it.  Any suggestions on
> how to do it?
>
> Thanks a bunch.
>
> Bo

Um, make sure you compile with debug?

I have coded in Boo, which is very Python-like, and it will step
through the debugger just fine, so IP should do the same in theory.
But I've not used IP, so all I can give are generic "are you sure it's
plugged in?" type of suggestions.

Hmm, upon rereading your post, I see that you want the debugger to
step through a separate file that was executed using ExecuteFile.
Unless there are some debug options on ExecuteFile, I'd say your
chances are slim, since the file being executed is not really part of
the image being debugged.  You could also try explicitly invoking the
debugger from within the file that you are loading, using (this works
from Boo):

System.Diagnostics.Debugger.Launch()
System.Diagnostics.Debugger.Break()


-- Paul

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


Re: can't import SimpleXMLRPCDisptacher from SimpleXMLRPCServer

2007-08-07 Thread bhamdeveloper
On Aug 6, 1:01 pm, bhamdeveloper <[EMAIL PROTECTED]> wrote:
> from my server I can't import SimpleXMLRPCDispatcher.  please 
> seehttp://intertubewaypoint.com/metaweblog/for the stacktrace/error
> message.  This onle happens on my server; I am trying to integrate the
> metaweblog api into my blog and it is barfing when trying to get that
> dispatcher.  Anyone seen this and have a quick fix?

fixed, I was doing something stupid

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


Re: Tkinter or wxpython?

2007-08-07 Thread Chris Mellon
On 06 Aug 2007 15:25:51 -0700, Paul Rubin
<"http://phr.cx"@nospam.invalid> wrote:
> "Chris Mellon" <[EMAIL PROTECTED]> writes:
> > You repeatedly have used the word "slickness" as a pejorative. I find
> > that offensive and it's insulting to users. When I write applications,
> > I want the interface to be as smooth and trouble free as possible,
>
> It's a perjorative when it's done for its own sake and doesn't really
> help the user.  This happens a lot.  When it helps the user, as it
> sometimes does, then it's not perjorative.
>

To me, "slick" means well lubricated and smooth. It means that there
are no rough spots in your interaction. I use the term "flash" for
cosmetic features.

> > As a matter of time spent in development, I do not find that
> > non-trivial UIs are significantly easier to develop using web
> > interfaces.
>
> That's possibly true, but a lot of the time, trivial interfaces are
> enough.  Look at Google search, one of the most complex apps ever
> built (tens or hundreds of MLOC, massive distributed crawler
> infrastructure, 100's of PhD's figuring out the algorithms, etc.) but
> its interface is simple HTML that you would probably call trivial.  It
> is quite possibly the most popular application in the world.
>

When you start talking about trivializing the interface, what you're
actually talking about is trivializing the *process*. The UI is just a
mechanism for interaction. If you have complex interactions, then you
need complex UI (or your users have to do a lot of manual steps).

Search is a good example of trivial interaction. It's not really the
common case, though - in a regular web browser there's a half dozen
minimal points of interaction, and some of them are fairly
complicated. In terms of man-hours spent, raw data entry is one of the
largest cases of human-computer interaction and it's a significantly
more complex interface than search.

As you point out, the complexity of the interaction is only loosely
coupled to the complexity of the application itself, and the art of
designing simple interactions with complex systems is one of the
hallmarks of good design. Apple is generally quite good at this. Note
even so that simple interactions can have or require rather
complicated UI metaphors. Drag and drop is a very visceral, intuitive
interface (it's the second thing my 4 year old figured out how to do,
button clicking was the first) but it's quite complicated to
implement.

I rather suspect that Google has rather more complicated internal
administrative and reporting interfaces for the search engine, too.

> > As a matter of respect for the user, I'm not going to tell them to use
> > a trivial UI if a non-trivial one will save them time, learning
> > effort, or frustration. In order to make this decision, I like to work
> > with the people actually using it and watch them at work. To see what
> > kind of extra steps they have to take and where I can save them time
> > or inaccuracy or frustration.
>
> Right.  Obviously this has to be decided according to the specific
> needs of the application.  A lot of times, trivial interfaces are
> easier to learn than nontrivial ones, precisely because they are
> trivial so there is less to learn.  Again look at Google search for an
> example.
>
> Also, at least for in-house applications, while the user's time counts
> (since their time costs your customer money), your development time
> and deployment effort also costs money that comes from exactly the
> same place, so you have to take into consideration the number of
> users, amount of time they will spend using the program, just how much
> of that time (if any) a fancier interface will save, etc.

Business constraints are always there in software development. You
don't get enough testing, you don't have access to representative test
data, you don't have direct user feedback. And of course the guy
signing the checks, who often isn't the guy using the application, may
decide that an hour of your time isn't worth 100 hours aggravation
from his minimum wage data entry folks. But *I* care about that 100
hours and to the greatest extent possible within my ability and
contract, I will minimize that burden on them.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: is it possible to improve traceback messages ?

2007-08-07 Thread Sion Arrowsmith
Zentrader  <[EMAIL PROTECTED]> wrote:
>This is the "standard" way AFAIK
>.try :
>.   some_process
>.except :
>.   import trackback, sys
>.   et, ev, tb = sys.exc_info()
>.   while tb :
>.co = tb.tb_frame.f_code
>.print "Filename = " + str(co.co_filename)
>.print  "Error Line # = " + str(traceback.tb_lineno(tb))
>.tb = tb.tb_next
>.   print "error type = ", et
>.   print "error var name  = ", ev

Personally, I find:

try:
some_process
except:
import traceback
traceback.print_exc()
raise

just as informative and much easier to write.

-- 
\S -- [EMAIL PROTECTED] -- http://www.chaos.org.uk/~sion/
   "Frankly I have no feelings towards penguins one way or the other"
-- Arthur C. Clarke
   her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Importing * From a Package

2007-08-07 Thread Duncan Booth
"Patrick Doyle" <[EMAIL PROTECTED]> wrote:

> Why does Python include the submodules that were explicitly loaded by
> previous imports?  Does it go out of it's way to do so?  If so, why?
> What purpose does it serve?  Or, is it a natural fallout of the manner
> in which imports are processed?  If so, could somebody guide my
> intuition as to why this would be such a natural fallout?
> 

It is a natural fallout of the manner in which imports are processed. 
When you explicitly load a submodule a reference to the submodule is 
stored in the parent module. When you do 'from module import *' and the 
imported module doesn't define __all__, you create a reference in the 
current module to everything referenced by the imported module (except 
for variables beginning with '_').

Python makes no distinction at all between the objects named in the 
imported module: they all get imported, i.e. assigned into the current 
scope no matter how they got there.

If you use your example:

>>> import SDRGen
>>> dir(SDRGen)
['__builtins__', '__doc__', '__file__', '__name__', '__path__']
>>> from SDRGen.TFGenerator import *
>>> dir(SDRGen)
['TFGenerator', '__builtins__', '__doc__', '__file__', '__name__', 
'__path__']
>>>

The line 'from SDRGen.TFGenerator import *' always creates the name 
TFGenerator in the SDRGen module (and it will create the SDRGen module 
if it has to). A subsequent 'from SDRGen import *' is simply doing the 
equivalent of:

for name in dir(SDRGen):
   if not name.startswith('_'):
   setattr(current_module, getattr(SDRGen, name))

except of course the variables name and current_module don't exist.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: get position is scrolled wxScrolledWindow

2007-08-07 Thread kyosohma
On Aug 6, 11:20 pm, Astan Chee <[EMAIL PROTECTED]> wrote:
> Hi,
> I have a wxScrolledWindow, and some things drawn on it. I've hooked the
> left click event to a certain function I've got. Anyway, everytime I do
> a event.GetPosition() on the position of the mouse on the
> wxScrolledWindow, it returns the physical location or position of the
> mouse. Does anyone have any examples or advice on how to get the real or
> position of the window including where it has been scrolled?
> Thanks
> Astan

This sounds like a job for the wxPython list. You should try posting
there: http://www.wxpython.org/maillist.php

I also found this: 
http://aspn.activestate.com/ASPN/Mail/Message/wxpython-users/3536900

Mike

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


Re: All leading tabs or all leading spaces - why isn't that enforced?

2007-08-07 Thread Omari Norman
> I suppose we Pythonistas are just too permissive for our own good. 
> Consider the opportunity to use mixed tabs and spaces a piece of rope of 
> your preferred length ...

I thought I remembered reading somewhere that Python 3000 will ban tabs
as indentation characters, but now I can't turn up a link for it...

-- 
You can't lose what you never had.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Web based Reporting tool for Python

2007-08-07 Thread vasudevram

Madhu Alagu wrote:
> Hi
>
>
>
> I am looking template based report tools for python.It has the ability
> to deliver rich content onto the screen, to the printer or into PDF,
> HTML, XLS, CSV and XML files.
>
>
>
>
>
> Thanks,
>
> Madhu Alagu

I don't know if there's a _single_ tool that can do all you want
(there may be, just that I don't know of one), but there are many
tools that can each do some part of it. Here are some, off the top of
my head - Googling should get you more for each category.

For templating - Cheetah, others.

For PDF - ReportLab. PDFLib has Python bindings too, but its paid for
commercial use, IIRC.

For HTML - Python standard library itself has some stuff, there must
be others.

For XLS/CSV - CSV output is easy enough to "roll your own". Then
import the CSV into Excel. If this isn't good enough (and it may not
be, depending on your needs, as it requires manual (ok, it is possible
to sort of automate that too using COM) import of the CSV into Excel.
Google for a Python lib for direct XLS generation.

For XML - like CSV, for simple XML, can be written by you (its just
outputting XML tags, attributes and content from your code). There
might be issues with encodings, etc. - in which case use a lib. Python
has many XML libs - do some research.
David Mertz and Uche Ogbuji, among others, have written a lot of
articles on Python and XML, many of them are about reviewing and
comparing various libs like ElementTree, Gnosis XML utilities  and
others. Many of those and other articles are on IBM developerWorks and
XML.com.

Vasudev Ram
http://www.dancingbison.com
http://jugad.livejournal.com
http://sourceforge.net/projects/xtopdf

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


Issues of state (was: Tkinter or wxpython?)

2007-08-07 Thread Cameron Laird
In article <[EMAIL PROTECTED]>,
Chris Mellon <[EMAIL PROTECTED]> wrote:
.
[scores of lines
of vigorous debate]
.
.
>Moreover, if you *don't* need global access or zero-deployment
>(zero-deployment is always nice but most environments where you can
>reasonably force a specific browser and version also have IT
>infrastructure), then you should ask yourself if forcing your
>application in the web app model (I haven't even touched on the whole
>stateless HTTP being mapped to a stateful environment issue, or the
>need to manage the local web server) actually buys you anything. I
.
.
.
Go ahead:  touch on statefulness.  I've been pondering the topic
lately, and wonder what's new on the subject.  I find it plenty
difficult to cast this as anything but a big liability for the
Web app team.
-- 
http://mail.python.org/mailman/listinfo/python-list


Which GUI toolkit (was: Tkinter or wxpython?)

2007-08-07 Thread Cameron Laird
In article <[EMAIL PROTECTED]>,
Bryan Hepworth  <[EMAIL PROTECTED]> wrote:
.
[waaay too
much quoted text
for my taste]
.
.
>> I'm not trying to claim that there are no benefits to web
>> applications. But I often see people touting the web as a *superior
>> application platform*, which is simply false, and as innately simpler
>> to develop for, which is also false.
>>   
>I'm also in a similar predicament starting to look at Python for the 
>first time.
>
>I'd be curious to know peoples take on other GUI's like pygtk and pyqt 
>for example to get a fuller picture. As a total newbie the list seems 
>daunting so taking advantage of other peoples experiences seems like a 
>good idea.
>
>Bryan

The traditional answer is, "We've already discussed that far too
often; go search the comp.lang.python archive on your own, because
all the answers are there."

I regard that as unhelpful.  http://wiki.python.org/moin/ChoosingGuiToolkits > *could* be a good
answer, but it's not, at least not yet.  Perhaps the best immediate
help is http://wiki.python.org/moin/GuiProgramming >.

Even better, maybe:  read through these materials, start to integrate
your own findings into what the Wiki already makes available, and
likely others of us will pitch in.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter or wxpython?

2007-08-07 Thread Cameron Laird
In article <[EMAIL PROTECTED]>,
Paul Rubin   wrote:
.
.
.
>I should also add: there is also the possibility of running a Python
>program with an embedded http server on the same desktop as the
>browser, using the browser purely as a gui, but with the Python
>program having complete access to the file system and so forth.  This
>could be seen as combining the disadvantages of both the remote web
>server approach (i.e. gui elements constrained by the browser) and the
>all-desktop approach (deployment issues).  However, a lot of the time
>it's still just plain easier to do.  Whenever I've written a desktop
>gui app I've always just been shocked at how much time goes into
>making the gui look decent and do the right stuff, even though none of
>mine have been even slightly slick (they've all been for industrial
>applications).  When I do a web gui, it's been just a matter of
>tossing some html into a file or into some print statements, viewing
>it in a browser, and tweaking it a little as needed.  Maybe that's
>mostly a matter of the lousy state of gui toolkits, and we actually
>need a toolkit that's more like an embedded browser.  But we don't
>have that at the moment.

One key to Tkinter's longevity lurks there.  While
many whine about the antiquity of the appearance of
Tkinter's widgets, they have the virtue of sensible
defaults; more than any other toolkit, Tkinter comes
up with minimal refinements in a sensible and
consistent state.  While those with an artistic eye
assure me the simplest Tkinter programs look worse
that corresponding ones built with any other toolkit,
they behave the most coherently in regards to resizing
and so on.

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


Re: RTF 2 Tiff

2007-08-07 Thread cjankowski
On Aug 6, 4:04 pm, Larry Bates <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] wrote:
> > Hi all,
> > I am trying to convert an RTF file to a Tiff image using Python.  This
> > process will convert several hundred images daily.  Currently I am
> > able to get the RTF file into a text format using Rtf2Txt.py, but I
> > loose the images contained in the RTF file.  I have the same problem
> > when I convert to .HTML using Rtf2Html.py.  I do not have a sample
> > that I can share because of HIPPA regulations.  Can anyone please help
> > me?
>
> > Thanks,
>
> > Chris J.
>
> Google turns up lots of solutions, but you didn't tell us what operating 
> system
> you are running on.  Most likely you will want to automate one of the off-the
> shelf solutions rather than trying to roll your own.
>
> -Larry

We are running Windows Operating Systems.  I was not able to find
anything that actually would convert the images via command line or
interface.  I tried a couple of boxed solutions and they only convert
the text portions.  I would perfer to not reinvent the wheel.  I did
find someone has created RTF's using Python and images, but I need to
reverse the process.

Thanks again,

Chris J.

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


Re: making a opc client in Python and use opc server Events

2007-08-07 Thread jp . eugster
On 28 juin, 16:55, [EMAIL PROTECTED] wrote:
> On 4 juin, 11:32, [EMAIL PROTECTED] wrote:
>
>
>
>
>
> > Hi all
> > I have a sample code to implement opc client in Python. i use a
> > file .py making by makepy with pythonwin for Com Interface.
> > i can get all server in machine, connect to server opc, disconnect,
> > add group, add item, read, write item in server opc.
>
> > import win32com.client  # librairie pour utiliser l'interface COM/DCOM
> > from win32com.client import gencache
> > gencache.EnsureModule('{DFB83232-A952-11D2-A46B-00C04F796375}', 0, 1,
> > 0)
>
> > for svr in opcserver.GetOPCServers():
> > print svr
>
> > #connect to server OPC Demo Simulation from Matrikon
> > opcserver.Connect('Matrikon.OPC.Simulation.1')
>
> > # Instance object Groups
> > groups=opcserver.OPCGroups
> > #add group
> > group=groups.Add('Group1')
>
> > #instance onject Items
> > items=group.OPCItems
> > # add item in server opc
> > tem=items.AddItem('File1.item1',1)
>
> > #read item value
> > item.Read(win32com.client.constants.OPCDevice)
>
> > # write a new value
> > item.Write(100)
>
> > #read item value
> > item.Read(win32com.client.constants.OPCDevice)
> > #if no pb you have 100 :)
>
> > #Disconnect
> > #opcserver.Disconnect()
>
> > BUT, and BUT, i want to use a event from opc server for uodating item
> > value with this below class. And i don't konw how make it
> > help me plz
>
> > opcserver=win32com.client.Dispatch('OPC.Automation.1')
> > and now i want to use events from opc server. in a class:
> > class DIOPCGroupEvent:
> > class DIOPCGroupsEvent:
> > class DIOPCServerEvent:
>
> Try this:
>
> # Event Handlers
> class ServerEvent:
> def __init__(self):
> print 'Init ServerEvent'
>
> def OnServerShutDown(self, Reason):
> print 'OnServerShutDown', Reason
>
> class GroupEvent:
> def __init__(self):
> print 'Init GroupEvent'
>
> def OnAsyncCancelComplete(self, CancelID):
> print 'OnAsyncCancelComplete', CancelID
>
> def OnDataChange(self, TransactionID, NumItems, ClientHandles,
> ItemValues, Qualities, TimeStamps):
> print 'OnDataChange', zip(ClientHandles, ItemValues, 
> Qualities)
>
> def OnAsyncReadComplete(self, TransactionID, NumItems, ClientHandles,
> ItemValues, Qualities,
>  TimeStamps, Errors):
> print 'OnAsyncReadComplete', zip(ClientHandles, ItemValues,
> Qualities)
>
> def OnAsyncWriteComplete(self, TransactionID, NumItems,
> ClientHandles, Errors):
> print 'OnAsyncWriteComplete', zip(ClientHandles, Errors)
>
> class GroupsEvent:
> def __init__(self):
> print 'Init GroupsEvent'
>
> def OnGlobalDataChange(self, TransactionID, GroupHandle, NumItems,
> ClientHandles, ItemValues,
>  Qualities, TimeStamps):
> print 'OnGlobalDataChange', zip(ClientHandles, ItemValues,
> Qualities)
>
> opc = DispatchWithEvents('Matrikon.OPC.Automation.1', ServerEvent)
>
> groups = DispatchWithEvents(opc.OPCGroups, GroupsEvent)
> groups.DefaultGroupIsActive = True
> groups.DefaultGroupUpdateRate = 2000
>
> group1 = DispatchWithEvents(groups.Add('G1'), GroupEvent)
> group2 = DispatchWithEvents(groups.Add('G2'), GroupEvent)
> #etc ...
>
> It works for the GroupsEvents but I don't get the GroupEvent for each
> group, I may still do someting wrong..- Masquer le texte des messages 
> précédents -
>
> - Afficher le texte des messages précédents -

In order to get the GroupEvent, you have to keep a reference to the
group you add
eg:
g1 = groups.Add('G1')
group1 = DispatchWithEvents(g1, GroupEvent)
etc...

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

Re: Importing * From a Package

2007-08-07 Thread Patrick Doyle
On 7 Aug 2007 13:54:21 GMT, Duncan Booth <[EMAIL PROTECTED]> wrote:
> "Patrick Doyle" <[EMAIL PROTECTED]> wrote:
>
> > Why does Python include the submodules that were explicitly loaded by
> > previous imports?  Does it go out of it's way to do so?  If so, why?
> > What purpose does it serve?  Or, is it a natural fallout of the manner
> > in which imports are processed?  If so, could somebody guide my
> > intuition as to why this would be such a natural fallout?
> >
>
> It is a natural fallout of the manner in which imports are processed.
> When you explicitly load a submodule a reference to the submodule is
> stored in the parent module. When you do 'from module import *' and the
> imported module doesn't define __all__, you create a reference in the
> current module to everything referenced by the imported module (except
> for variables beginning with '_').
>
Ahhh, I see it now
>>> import SDRGen
>>> dir()
['SDRGen', '__builtins__', '__doc__', '__name__']

>>> dir(SDRGen)
['__builtins__', '__doc__', '__file__', '__name__', '__path__']

>>> from SDRGen import *
>>> dir()
['SDRGen', '__builtins__', '__doc__', '__name__']
>>> dir(SDRGen)
['__builtins__', '__doc__', '__file__', '__name__', '__path__']
(notice, no changes)

>>> from SDRGen.TFGenerator import TFGenerator
>>> dir()
['SDRGen', 'TFGenerator', '__builtins__', '__doc__', '__name__']
>>> TFGenerator

(as expected)

>>> dir(SDRGen)
['TFGenerator', '__builtins__', '__doc__', '__file__', '__name__', '__path__']
>>> SDRGen.TFGenerator


and that's what led to my confusion... when my script later did a
>>> from SDRGen import *

The 'TFGenerator' name got changed from a reference to the
'TFGenerator' class to a reference to the 'SDRGen.TFGenerator' module.

and now it makes sense.

Thanks.

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


Re: All leading tabs or all leading spaces - why isn't that enforced?

2007-08-07 Thread Neil Cerutti
On 2007-08-07, Omari Norman <[EMAIL PROTECTED]> wrote:
>> I suppose we Pythonistas are just too permissive for our own good. 
>> Consider the opportunity to use mixed tabs and spaces a piece of rope of 
>> your preferred length ...
>
> I thought I remembered reading somewhere that Python 3000 will
> ban tabs as indentation characters, but now I can't turn up a
> link for it...

Tabs are going to be banned in the C Style Guide for Python 3000
source code, but they aren't being banned from Python 3000 code.

-- 
Neil Cerutti
The concert held in Fellowship Hall was a great success. Special thanks are
due to the minister's daughter, who labored the whole evening at the piano,
which as usual fell upon her. --Church Bulletin Blooper
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: distutils

2007-08-07 Thread vedrandekovic
On 7 kol, 14:53, Steve Holden <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] wrote:
> > Hello again,
>
> > Is there any patch for python "distutils", for this
>
>  from distutils import log,dir_util
> > ImportError: cannot import name log
>
> What version of Python are you running with? It looks as though there
> may be something wrong with your installation if it's recent:
>
> [EMAIL PROTECTED] ~/Projects/Python
> $ python
> Python 2.5.1 (r251:54863, May 18 2007, 16:56:43)
> [GCC 3.4.4 (cygming special, gdc 0.12, using dmd 0.125)] on cygwin
> Type "help", "copyright", "credits" or "license" for more information.
>  >>> from distutils import log
>  >>> import distutils.log
>  >>>
>
> regards
>   Steve
> --
> Steve Holden+1 571 484 6266   +1 800 494 3119
> Holden Web LLC/Ltd  http://www.holdenweb.com
> Skype: holdenweb  http://del.icio.us/steve.holden
> --- Asciimercial --
> Get on the web: Blog, lens and tag the Internet
> Many services currently offer free registration
> --- Thank You for Reading -

Hello,

My version of python is 2.4 and I'am running it with Windows XP

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


Re: parsing a dbIII file

2007-08-07 Thread Jay Loden
[EMAIL PROTECTED] wrote:
> Hello everybody, I'm new to python (...I work with cobol...)
> 
> I have to parse a file (that is a dbIII file) whose stucture look like
> this:
> |string|, |string|, |string that may contain commas inside|, 1, 2, 3, |
> other string|

There are a number of relatively simple options that come to mind, including
regular expressions:

# BEGIN CODE #

import re

#
# dbIII.txt:
# |string|, |string|, |string|, |string|, |,1,2,3,4|, |other string|
#
handle = open('dbIII.txt')
for line in handle.xreadlines():
for match in re.finditer(r'\|\s*([^|]+)\s*\|,*', line):
for each in match.groups():
print each

handle.close()

# END CODE #


Without knowing what you need to do with the data, it's hard to suggest a better
method for parsing it. The above should work, provided that the data is always
in the format | data | with no pipe symbols in between the ones used as 
separators.

HTH,

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


python system subprocess win32

2007-08-07 Thread mclaugb
Hello ALl,
I have a compiled program "conv.exe" that works as follows:
>>conv.exe
-
Please selection from the following options.  press "h" for help, "p" for 
print, "r" for readfile.
Enter your request now:
...

Is there a way to script python using the subprocess method to start this 
program "conv.exe" and then send a "r" to the command line to make it, say, 
readfile.

I have tried the following but the .communicate("r) is not doing anything

import subprocess
import time

a=subprocess.Popen("c:\\mcml\\conv.exe")
time.sleep(1)
(stdout, stderr) = a.communicate("r")

Many thanks,
Bryan


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


Re��: ��get wikipedia source failed�� (��urrlib2��)

2007-08-07 Thread Michael J��. ��Fromberger
In article‭ <[EMAIL PROTECTED]>,‬
‭ [EMAIL PROTECTED] wrote‭:‬

‭> ‬Hi‭,‬
‭> ‬I'm trying to get wikipedia page source with urllib2‭:‬
‭> ‬usock‭ = 
‬urllib2‭.‬urlopen‭("‬http‭://‬en.wikipedia.org/wiki‭/‬
‭> ‬Albert_Einstein‭")‬
‭> ‬data‭ = ‬usock.read‭();‬
‭> ‬usock.close‭();‬
‭> ‬return data
‭> ‬I got exception because HTTP 403‭ ‬error‭. ‬why‭? ‬with my 
browser i can't
‭> ‬access it without any problem‭?‬
‭> ‬
‭> ‬Thanks‭,‬
‭> ‬Shahar‭.‬

It appears that Wikipedia may inspect the contents of the User-Agent‭ ‬
HTTP header‭, ‬and that it does not particularly like the string it‭ ‬
receives from Python's urllib‭.  ‬I was able to make it work with urllib‭ 
‬
via the following code‭:‬

import urllib

class CustomURLopener‭ (‬urllib.FancyURLopener‭):‬
‭  ‬version‭ = '‬Mozilla/5.0‭'‬

urllib‭.‬_urlopener‭ = ‬CustomURLopener‭()‬

u‭ = 
‬urllib.urlopen‭('‬http‭://‬en.wikipedia.org/wiki/Albert_Einstein‭')‬
data‭ = ‬u.read‭()‬

I'm assuming a similar trick could be used with urllib2‭, ‬though I 
didn't‭ ‬
actually try it‭.  ‬Another thing to watch out for‭, ‬is that some 
sites‭ ‬
will redirect a public URL X to an internal URL Y‭, ‬and will check that‭ 
‬
access to Y is only permitted if the Referer field indicates coming from‭ ‬
somewhere internal to the site‭.  ‬I have seen both of these techniques‭ 
‬
used to foil screen-scraping‭.‬

Cheers‭,‬
‭-‬M

‭-- ‬
Michael J‭. ‬Fromberger‭ | ‬Lecturer‭, ‬Dept‭. ‬of 
Computer Science
http‭://‬www.dartmouth.edu‭/‬~sting‭/  | ‬Dartmouth College‭, 
‬Hanover‭, ‬NH‭, ‬USA
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Tkinter or wxpython?

2007-08-07 Thread kyosohma
On Aug 7, 9:00 am, [EMAIL PROTECTED] (Cameron Laird) wrote:
> In article <[EMAIL PROTECTED]>,
> Paul Rubin   wrote:
> .
> .
> .
>
>
>
> >I should also add: there is also the possibility of running a Python
> >program with an embedded http server on the same desktop as the
> >browser, using the browser purely as a gui, but with the Python
> >program having complete access to the file system and so forth.  This
> >could be seen as combining the disadvantages of both the remote web
> >server approach (i.e. gui elements constrained by the browser) and the
> >all-desktop approach (deployment issues).  However, a lot of the time
> >it's still just plain easier to do.  Whenever I've written a desktop
> >gui app I've always just been shocked at how much time goes into
> >making the gui look decent and do the right stuff, even though none of
> >mine have been even slightly slick (they've all been for industrial
> >applications).  When I do a web gui, it's been just a matter of
> >tossing some html into a file or into some print statements, viewing
> >it in a browser, and tweaking it a little as needed.  Maybe that's
> >mostly a matter of the lousy state of gui toolkits, and we actually
> >need a toolkit that's more like an embedded browser.  But we don't
> >have that at the moment.
>
> One key to Tkinter's longevity lurks there.  While
> many whine about the antiquity of the appearance of
> Tkinter's widgets, they have the virtue of sensible
> defaults; more than any other toolkit, Tkinter comes
> up with minimal refinements in a sensible and
> consistent state.  While those with an artistic eye
> assure me the simplest Tkinter programs look worse
> that corresponding ones built with any other toolkit,
> they behave the most coherently in regards to resizing
> and so on.

I am curious. What are these "sensible defaults" that you mention?

If you set up a wxPython program's sizers appropriately, the program
should resize logically. But I think Tkinter is a little bit easier in
that respect. However, you can get pretty granular in how you want
items to behave in wxPython that you may not be able to do in Tkinter.
I just don't know.

I've used both, so I'm interested in hearing your opinion.

Mike

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


Re: python system subprocess win32

2007-08-07 Thread kyosohma
On Aug 7, 9:48 am, "mclaugb" <[EMAIL PROTECTED]> wrote:
> Hello ALl,
> I have a compiled program "conv.exe" that works as follows:>>conv.exe
>
> -
> Please selection from the following options.  press "h" for help, "p" for
> print, "r" for readfile.
> Enter your request now:
> ...
> 
> Is there a way to script python using the subprocess method to start this
> program "conv.exe" and then send a "r" to the command line to make it, say,
> readfile.
>
> I have tried the following but the .communicate("r) is not doing anything
>
> import subprocess
> import time
>
> a=subprocess.Popen("c:\\mcml\\conv.exe")
> time.sleep(1)
> (stdout, stderr) = a.communicate("r")
>
> Many thanks,
> Bryan

Use the sys.argv method. In the code that you have compiled, put the
following lines in:



import sys
default = sys.argv[1]
if default:
   # check which option it is and run it appropriately
else:
   # print your menu here



Then you should be able to do the subprocess Popen command:

subprocess.Popen("c:\\mcml\\conv.exe r")

You may need to turn the shell on...

subprocess.Popen("c:\\mcml\\conv.exe r", shell=True)

Hopefully that gives you some ideas anyway.

Mike

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


Re: parsing a dbIII file

2007-08-07 Thread Paul McGuire
On Aug 7, 2:21 am, Steve Holden <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] wrote:
> > Hello everybody, I'm new to python (...I work with cobol...)
>
> > I have to parse a file (that is a dbIII file) whose stucture look like
> > this:
> > |string|, |string|, |string that may contain commas inside|, 1, 2, 3, |
> > other string|
>
As Steve mentioned pyparsing, here is a pyparsing version for cracking
your data:

from pyparsing import *

data = "|string|, |string|, |string that may contain commas inside|,
1, 2, 3, |other string|"

integer = Word(nums)
# change unquoteResults to True to omit '|' chars from results
string = QuotedString("|", unquoteResults=False)
itemList = delimitedList( integer | string )

# parse the data and print out the results as a simple list
print itemList.parseString(data).asList()

# add a parse action to convert integer strings to actual integers
integer.setParseAction(lambda t:int(t[0]))

# reparse the data and now get converted integers in results
print itemList.parseString(data).asList()

Prints:

['|string|', '|string|', '|string that may contain commas inside|',
'1', '2', '3', '|other string|']
['|string|', '|string|', '|string that may contain commas inside|', 1,
2, 3, '|other string|']

-- Paul

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


Re: parsing a dbIII file

2007-08-07 Thread Jerry Hill
On 8/7/07, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> I have to parse a file (that is a dbIII file) whose stucture look like
> this:
> |string|, |string|, |string that may contain commas inside|, 1, 2, 3, |
> other string|

The CSV module is probably the easiest way to go:

>>> data = "|string|, |string|, |string that may contain commas
inside|, 1, 2, 3, |other string|"
>>> import csv
>>> reader = csv.reader([data], quotechar="|", skipinitialspace=True)
>>> for row in reader:
print row

['string', 'string', 'string that may contain commas inside', '1',
'2', '3', 'other string']

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


Re: distutils

2007-08-07 Thread Steve Holden
[EMAIL PROTECTED] wrote:
> On 7 kol, 14:53, Steve Holden <[EMAIL PROTECTED]> wrote:
>> [EMAIL PROTECTED] wrote:
>>> Hello again,
>>> Is there any patch for python "distutils", for this
>> from distutils import log,dir_util
>>> ImportError: cannot import name log
>> What version of Python are you running with? It looks as though there
>> may be something wrong with your installation if it's recent:
>>
>> [EMAIL PROTECTED] ~/Projects/Python
>> $ python
>> Python 2.5.1 (r251:54863, May 18 2007, 16:56:43)
>> [GCC 3.4.4 (cygming special, gdc 0.12, using dmd 0.125)] on cygwin
>> Type "help", "copyright", "credits" or "license" for more information.
>>  >>> from distutils import log
>>  >>> import distutils.log
>>  >>>
>>
> Hello,
> 
> My version of python is 2.4 and I'am running it with Windows XP
> 
Your installation must be corrupted, then:

Microsoft Windows XP [Version 5.1.2600]
(C) Copyright 1985-2001 Microsoft Corp.

C:\Steve>\python24\python
Python 2.4.4 (#71, Oct 18 2006, 08:34:43) [MSC v.1310 32 bit (Intel)] on 
win32
Type "help", "copyright", "credits" or "license" for more information.
 >>> from distutils import log
 >>>


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

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


Another question about variable args.

2007-08-07 Thread Steven W. Orr
I have a structure I need to pack. I call struct.pack about a dozen times 
and each call takes about 53 arguments.

I create a sequence of the arguments:
a1 = 1
a2 = 2
a3 = 3
etc...
a54 = 88
myseq = (a1, a2, a3, a4 etc... a53)
Also I made

def mpack ( fmt, *ss ):
 print type(ss)
 for ii in ss:
 print 'ii = ', ii, 'type(ii) = ', type(ii)
 for ii in list(ss):
 print 'ii = ', ii, 'type(ii) = ', type(ii)
 return struct.pack(fmt, *ss )

In my main, this first print statement works.
print 'main:', mpack(ff, a, b, c, d, e, f, g, h, i)

1. For the life of me, I can't figure out what to do to get the next print 
to work. The idea is that I want to make my code clearer by not passing 
50+ args each time and to instead pass a sequence which when evaluated 
will be the desired list of args.

print 'main:', mpack(ff, subseq)

2. And then, if possible, I'd like to do it in such a way that one myseq 
is defined, its value can automagically be re-eval'd so I don't have to 
re-assign to myseq each time one of the 50+ variables changes prior to 
calling pack.

Does this make sense?

-- 
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: All leading tabs or all leading spaces - why isn't that enforced?

2007-08-07 Thread James Antill
On Tue, 07 Aug 2007 02:53:18 +, John Nagle wrote:

> One can argue over tab vs. space indentation, but mixing the two is just
> wrong.  Why not have CPython report an error if a file has both leading
> tabs and leading spaces?  I know that was proposed at some point, but I
> don't think it ever went in. That would catch a common error introduced
> during maintenance.

 While I agree it should be default, you can enable extra checking with
-tt. Eg.

% jhexdump /tmp/abcd.py
0x: 2321 202F 7573 722F 6269 6E2F 7079 7468  #! /usr/bin/pyth
0x0010: 6F6E 202D 7474 0A0A 6966 2054 7275 653A  on -tt..if True:
0x0020: 0A09 7072 696E 7420 2261 220A 2020 2020  ..print "a".
0x0030: 2020 2020 7072 696E 7420 2262 220A   print "b".
% /tmp/abcd.py
  File "/tmp/abcd.py", line 5
print "b"
^
TabError: inconsistent use of tabs and spaces in indentation
% python /tmp/abcd.py
a
b

...note that this doesn't require all spaces or all tabs, just that
their usage has to be consistent.

-- 
James Antill -- [EMAIL PROTECTED]
C String APIs use too much memory? ustr: length, ref count, size and
read-only/fixed. Ave. 44% overhead over strdup(), for 0-20B strings
http://www.and.org/ustr/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python system subprocess win32

2007-08-07 Thread mclaugb
At the moment, I cannot figure a way of running this precompiled "conv.exe" 
using commandline arguments.

Thus, I need Python to call the program, wait until it loads up, then enter 
a known sequence of characters so that the function will run.
The program conv.exe I call looks like this.
--
Welcome to conv.exe
This program was written by 

Please select from the following options: h- (help) r- (read) ...etc
Enter your request:
-
I need Python to start the program, wait a second and then issue a few 
characters to the program.

Hope this makes more sense!
Bryan

<[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> On Aug 7, 9:48 am, "mclaugb" <[EMAIL PROTECTED]> wrote:
>> Hello ALl,
>> I have a compiled program "conv.exe" that works as follows:>>conv.exe
>>
>> -
>> Please selection from the following options.  press "h" for help, "p" for
>> print, "r" for readfile.
>> Enter your request now:
>> ...
>> 
>> Is there a way to script python using the subprocess method to start this
>> program "conv.exe" and then send a "r" to the command line to make it, 
>> say,
>> readfile.
>>
>> I have tried the following but the .communicate("r) is not doing anything
>>
>> import subprocess
>> import time
>>
>> a=subprocess.Popen("c:\\mcml\\conv.exe")
>> time.sleep(1)
>> (stdout, stderr) = a.communicate("r")
>>
>> Many thanks,
>> Bryan
>
> Use the sys.argv method. In the code that you have compiled, put the
> following lines in:
>
> 
>
> import sys
> default = sys.argv[1]
> if default:
>   # check which option it is and run it appropriately
> else:
>   # print your menu here
>
> 
>
> Then you should be able to do the subprocess Popen command:
>
> subprocess.Popen("c:\\mcml\\conv.exe r")
>
> You may need to turn the shell on...
>
> subprocess.Popen("c:\\mcml\\conv.exe r", shell=True)
>
> Hopefully that gives you some ideas anyway.
>
> Mike
> 


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


Re: python system subprocess win32

2007-08-07 Thread kyosohma
On Aug 7, 11:07 am, "mclaugb" <[EMAIL PROTECTED]> wrote:
> At the moment, I cannot figure a way of running this precompiled "conv.exe"
> using commandline arguments.
>
> Thus, I need Python to call the program, wait until it loads up, then enter
> a known sequence of characters so that the function will run.
> The program conv.exe I call looks like this.
> --
> Welcome to conv.exe
> This program was written by 
>
> Please select from the following options: h- (help) r- (read) ...etc
> Enter your request:
> -
> I need Python to start the program, wait a second and then issue a few
> characters to the program.
>
> Hope this makes more sense!
> Bryan
>
> <[EMAIL PROTECTED]> wrote in message
>
> news:[EMAIL PROTECTED]
>
> > On Aug 7, 9:48 am, "mclaugb" <[EMAIL PROTECTED]> wrote:
> >> Hello ALl,
> >> I have a compiled program "conv.exe" that works as follows:>>conv.exe
>
> >> -
> >> Please selection from the following options.  press "h" for help, "p" for
> >> print, "r" for readfile.
> >> Enter your request now:
> >> ...
> >> 
> >> Is there a way to script python using the subprocess method to start this
> >> program "conv.exe" and then send a "r" to the command line to make it,
> >> say,
> >> readfile.
>
> >> I have tried the following but the .communicate("r) is not doing anything
>
> >> import subprocess
> >> import time
>
> >> a=subprocess.Popen("c:\\mcml\\conv.exe")
> >> time.sleep(1)
> >> (stdout, stderr) = a.communicate("r")
>
> >> Many thanks,
> >> Bryan
>
> > Use the sys.argv method. In the code that you have compiled, put the
> > following lines in:
>
> > 
>
> > import sys
> > default = sys.argv[1]
> > if default:
> >   # check which option it is and run it appropriately
> > else:
> >   # print your menu here
>
> > 
>
> > Then you should be able to do the subprocess Popen command:
>
> > subprocess.Popen("c:\\mcml\\conv.exe r")
>
> > You may need to turn the shell on...
>
> > subprocess.Popen("c:\\mcml\\conv.exe r", shell=True)
>
> > Hopefully that gives you some ideas anyway.
>
> > Mike

Oh. I thought you had compiled the program yourself. I suppose you
could use SendKeys then. I have a couple links here:

http://pythonlibrary.org/python/SendKeys

It's pretty hackneyed, but I've used the SendKeys module to automate
Firefox to some degree.

Mike

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


Adding a list of descriptors to a class

2007-08-07 Thread Bob B.
I've been playing with descriptors lately.  I'm having one problem I
can't seem to find the answer to.  I want to assign a descriptor to a
list of attributes.  I know I should be able to add these somewhere in
the class's __dict__, but I can't figure out where.  Here's some code:

class MyDesc(object):
  def __init__(self, name=None, initVal=None):
self.name = name
self.value = initVal

  def __get__(self, obj, objtype):
// Do some stuff
self.value = "blah"
return self.value

class MyClass(object):
  attributes = ('attr1', 'attr2')
  for attr in attributes:
exec ("%s=MyDesc('%s')") % (attr, attr)

  // More stuff in the class

Ok, that "exec" is an ugly hack.  There's gotta be someway to plop
this straight into the class's __dict__ without doing that, but when I
try adding self.__class__.__dict__[attr] = MyDesc(attr) in MyClass's
__init__ method, I get the error: "TypeError: 'dictproxy' object does
not support item assignment"

Any ideas?

Thanks,
Bob

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


Re: Adding a list of descriptors to a class

2007-08-07 Thread Marc 'BlackJack' Rintsch
On Tue, 07 Aug 2007 09:25:32 -0700, Bob B. wrote:

> Ok, that "exec" is an ugly hack.  There's gotta be someway to plop
> this straight into the class's __dict__ without doing that, but when I
> try adding self.__class__.__dict__[attr] = MyDesc(attr) in MyClass's
> __init__ method, I get the error: "TypeError: 'dictproxy' object does
> not support item assignment"

Does ``setattr(self.__class__, attr, MyDesc(attr))`` work?

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


Re: Adding a list of descriptors to a class

2007-08-07 Thread Steven Bethard
Bob B. wrote:
> I've been playing with descriptors lately.  I'm having one problem I
> can't seem to find the answer to.  I want to assign a descriptor to a
> list of attributes.  I know I should be able to add these somewhere in
> the class's __dict__, but I can't figure out where.  Here's some code:
> 
> class MyDesc(object):
>   def __init__(self, name=None, initVal=None):
> self.name = name
> self.value = initVal
> 
>   def __get__(self, obj, objtype):
> // Do some stuff
> self.value = "blah"
> return self.value
> 
> class MyClass(object):
>   attributes = ('attr1', 'attr2')
>   for attr in attributes:
> exec ("%s=MyDesc('%s')") % (attr, attr)
> 
>   // More stuff in the class
> 
> Ok, that "exec" is an ugly hack.  There's gotta be someway to plop
> this straight into the class's __dict__ without doing that, but when I
> try adding self.__class__.__dict__[attr] = MyDesc(attr) in MyClass's
> __init__ method, I get the error: "TypeError: 'dictproxy' object does
> not support item assignment"

Probably the simplest thing is to just add the attributes after the 
class body, e.g.::

 >>> class MyClass(object):
 ... pass
 ...
 >>> for attr in ['attr1', 'attr2']:
 ... setattr(MyClass, attr, MyDesc(attr))
 ...
 >>> c = MyClass()
 >>> c.attr1
 'blah'

Another option would be to use a metaclass to set the class attributes 
at class creation time::

 >>> class Meta(type):
 ... def __init__(cls, name, bases, bodydict):
 ... for attr in cls._desc_attrs:
 ... setattr(cls, attr, MyDesc(attr))
 ...
 >>> class MyClass(object):
 ... __metaclass__ = Meta
 ... _desc_attrs = ['attr1', 'attr2']
 ...
 >>> c = MyClass()
 >>> c.attr1
 'blah'


HTH,

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


Re: Adding a list of descriptors to a class

2007-08-07 Thread Bob B.
> Probably the simplest thing is to just add the attributes after the
> class body, e.g.::
>
>  >>> class MyClass(object):
>  ... pass
>  ...
>  >>> for attr in ['attr1', 'attr2']:
>  ... setattr(MyClass, attr, MyDesc(attr))
>  ...
>  >>> c = MyClass()
>  >>> c.attr1
>  'blah'
>

That worked.  Thanks.


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


re.sub does not replace all occurences

2007-08-07 Thread Christoph Krammer
Hello everybody,

I wanted to use re.sub to strip all HTML tags out of a given string. I
learned that there are better ways to do this without the re module,
but I would like to know why my code is not working. I use the
following:

def stripHtml(source):
  source = re.sub("[\n\r\f]", " ", source)
  source = re.sub("<.*?>", "", source, re.S | re.I | re.M)
  source = re.sub("&(#[0-9]{1,3}|[a-z]{3,6});", "", source, re.I)
  return source

But the result still has some tags in it. When I call the second line
multiple times, all tags disappear, but since HTML tags cannot be
overlapping, I do not understand this behavior. There is even a
difference when I omit the re.I (IGNORECASE) option. Without this
option, some tags containing only capital letters (like ) were
kept in the string when doing one processing run but removed when
doing multiple runs.

Perhaps anyone can tell me why this regex is behaving like this.

Thanks and regards,
 Christoph

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


Re: distutils

2007-08-07 Thread vedrandekovic
On 7 kol, 18:00, Steve Holden <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] wrote:
> > On 7 kol, 14:53, Steve Holden <[EMAIL PROTECTED]> wrote:
> >> [EMAIL PROTECTED] wrote:
> >>> Hello again,
> >>> Is there any patch for python "distutils", for this
> >> from distutils import log,dir_util
> >>> ImportError: cannot import name log
> >> What version of Python are you running with? It looks as though there
> >> may be something wrong with your installation if it's recent:
>
> >> [EMAIL PROTECTED] ~/Projects/Python
> >> $ python
> >> Python 2.5.1 (r251:54863, May 18 2007, 16:56:43)
> >> [GCC 3.4.4 (cygming special, gdc 0.12, using dmd 0.125)] on cygwin
> >> Type "help", "copyright", "credits" or "license" for more information.
> >>  >>> from distutils import log
> >>  >>> import distutils.log
>
> > Hello,
>
> > My version of python is 2.4 and I'am running it with Windows XP
>
> Your installation must be corrupted, then:
>
> Microsoft Windows XP [Version 5.1.2600]
> (C) Copyright 1985-2001 Microsoft Corp.
>
> C:\Steve>\python24\python
> Python 2.4.4 (#71, Oct 18 2006, 08:34:43) [MSC v.1310 32 bit (Intel)] on
> win32
> Type "help", "copyright", "credits" or "license" for more information.
>  >>> from distutils import log
>  >>>
>
> regards
>   Steve
> --
> Steve Holden+1 571 484 6266   +1 800 494 3119
> Holden Web LLC/Ltd  http://www.holdenweb.com
> Skype: holdenweb  http://del.icio.us/steve.holden
> --- Asciimercial --
> Get on the web: Blog, lens and tag the Internet
> Many services currently offer free registration
> --- Thank You for Reading -

Hi,

Is there any other solution I need this for script installing with
setuptools,now I was install and Python 2.5 too,but same error
again.

PS: I was try your previously example also:

cd c:\Python24\python

then:
>>> from distutils import log - but same error again

any other solution?

Regards,
Vedran

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


Re: distutils

2007-08-07 Thread Irmen de Jong
[EMAIL PROTECTED] wrote:
> Hello again,
> 
> Is there any patch for python "distutils", for this
> 
 from distutils import log,dir_util
> ImportError: cannot import name log
> 
> 
> Regards,
> Vedran
> 

Are you sure you haven't written a module yourself called distutils.py ?
(that one will hide the standard distutils module)

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


Re: Another question about variable args.

2007-08-07 Thread Neil Cerutti
On 2007-08-07, Steven W. Orr <[EMAIL PROTECTED]> wrote:
> I have a structure I need to pack. I call struct.pack about a dozen times 
> and each call takes about 53 arguments.
>
> I create a sequence of the arguments:
> a1 = 1
> a2 = 2
> a3 = 3
> etc...
> a54 = 88
> myseq = (a1, a2, a3, a4 etc... a53)
> Also I made
>
> def mpack ( fmt, *ss ):
>  print type(ss)
>  for ii in ss:
>  print 'ii = ', ii, 'type(ii) = ', type(ii)
>  for ii in list(ss):
>  print 'ii = ', ii, 'type(ii) = ', type(ii)
>  return struct.pack(fmt, *ss )
>
> In my main, this first print statement works.
> print 'main:', mpack(ff, a, b, c, d, e, f, g, h, i)
>
> 1. For the life of me, I can't figure out what to do to get the
> next print to work. The idea is that I want to make my code
> clearer by not passing 50+ args each time and to instead pass a
> sequence which when evaluated will be the desired list of args.
>
> print 'main:', mpack(ff, subseq)
>
> 2. And then, if possible, I'd like to do it in such a way that
> one myseq is defined, its value can automagically be re-eval'd
> so I don't have to re-assign to myseq each time one of the 50+
> variables changes prior to calling pack.

A functor might be a fun solution.

class mpack_maker(object):
  def __init__(self, fmt, *args):
self.fmt = fmt
self.arg_list = list(args)
  def __call__(self, slice=None, subseq=None):
if slice:
  self.arg_list[slice] = subseq
return struct.pack(self.fmt, *self.arg_list)

You can pass in a slice object and a subsequence to change
arguments (permanently).

>>> mpack = mpack_maker(ff, a, b, c, d, e, f, g, h)
>>> mpack() # Call the function
>>> mpack(slice(5, 7), [0, 7]) # Change args 5 and 6, and call again.

The args you can change are limited by the slicing powers of
Python, and probably combining arg-changing with calling the
function isn't wise, but that's a sketch anyhow.

-- 
Neil Cerutti
We couldn't beat... us.  We couldn't even beat us.  I was trying to think of
somebody bad, and I couldn't think of anybody else.  Us. --Tim Legler
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: re.sub does not replace all occurences

2007-08-07 Thread Marc 'BlackJack' Rintsch
On Tue, 07 Aug 2007 10:28:24 -0700, Christoph Krammer wrote:

> Hello everybody,
> 
> I wanted to use re.sub to strip all HTML tags out of a given string. I
> learned that there are better ways to do this without the re module,
> but I would like to know why my code is not working. I use the
> following:
> 
> def stripHtml(source):
>   source = re.sub("[\n\r\f]", " ", source)
>   source = re.sub("<.*?>", "", source, re.S | re.I | re.M)
>   source = re.sub("&(#[0-9]{1,3}|[a-z]{3,6});", "", source, re.I)
>   return source
> 
> But the result still has some tags in it. When I call the second line
> multiple times, all tags disappear, but since HTML tags cannot be
> overlapping, I do not understand this behavior. There is even a
> difference when I omit the re.I (IGNORECASE) option. Without this
> option, some tags containing only capital letters (like ) were
> kept in the string when doing one processing run but removed when
> doing multiple runs.

Can you give some example HTML where it fails?

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


Re: distutils

2007-08-07 Thread vedrandekovic
On 7 kol, 19:37, Irmen de Jong <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] wrote:
> > Hello again,
>
> > Is there any patch for python "distutils", for this
>
>  from distutils import log,dir_util
> > ImportError: cannot import name log
>
> > Regards,
> > Vedran
>
> Are you sure you haven't written a module yourself called distutils.py ?
> (that one will hide the standard distutils module)
>
> --irmen


I was search for all distutils files and folders and I'am sure there
is no distutils except "c:\Python24\Lib\distutils"

Regards,
Vedran

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


Dealing with multiple excel sheets

2007-08-07 Thread Rohan
Hello,
I would like to write a script which does the following job.
Take column1 and 7 from 10 different excel sheets and pasthe them into
a new excel worksheet.
Any ideas on how to do it
Thanks,

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


Re: re.sub does not replace all occurences

2007-08-07 Thread Neil Cerutti
On 2007-08-07, Christoph Krammer <[EMAIL PROTECTED]> wrote:
> Hello everybody,
>
> I wanted to use re.sub to strip all HTML tags out of a given string. I
> learned that there are better ways to do this without the re module,
> but I would like to know why my code is not working. I use the
> following:
>
> def stripHtml(source):
>   source = re.sub("[\n\r\f]", " ", source)
>   source = re.sub("<.*?>", "", source, re.S | re.I | re.M)
>   source = re.sub("&(#[0-9]{1,3}|[a-z]{3,6});", "", source, re.I)
>   return source
>
> But the result still has some tags in it. When I call the
> second line multiple times, all tags disappear, but since HTML
> tags cannot be overlapping, I do not understand this behavior.
> There is even a difference when I omit the re.I (IGNORECASE)
> option. Without this option, some tags containing only capital
> letters (like ) were kept in the string when doing one
> processing run but removed when doing multiple runs.
>
> Perhaps anyone can tell me why this regex is behaving like
> this.

>>> import re
>>> help(re.sub)
Help on function sub in module re:

sub(pattern, repl, string, count=0)
Return the string obtained by replacing the leftmost
non-overlapping occurrences of the pattern in string by the
replacement repl.  repl can be either a string or a callable;
if a callable, it's passed the match object and must return
a replacement string to be used.

And from the Python Library Reference for re.sub:

The pattern may be a string or an RE object; if you need to
specify regular expression flags, you must use a RE object,
or use embedded modifiers in a pattern; for example,
"sub("(?i)b+", "x", " ")" returns 'x x'. 

The optional argument count is the maximum number of pattern
occurrences to be replaced; count must be a non-negative
integer. If omitted or zero, all occurrences will be
replaced. Empty matches for the pattern are replaced only
when not adjacent to a previous match, so "sub('x*', '-',
'abc')" returns '-a-b-c-'. 

In other words, the fourth argument to sub is count, not a set of
re flags.

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


Re: distutils

2007-08-07 Thread Peter Otten
 [EMAIL PROTECTED] wrote:

> On 7 kol, 19:37, Irmen de Jong <[EMAIL PROTECTED]> wrote:

>> Are you sure you haven't written a module yourself called distutils.py ?
>> (that one will hide the standard distutils module)

> I was search for all distutils files and folders and I'am sure there
> is no distutils except "c:\Python24\Lib\distutils"

What does

>>> import distutils
>>> distutils.__file__
'/usr/lib/python2.5/distutils/__init__.pyc'

print on your machine?

Peter

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


Re: re.sub does not replace all occurences

2007-08-07 Thread Christoph Krammer
Neil Cerutti schrieb:
> In other words, the fourth argument to sub is count, not a set of
> re flags.

I knew it had to be something very stupid.

Thanks a lot.

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


Re: Dealing with multiple excel sheets

2007-08-07 Thread kyosohma
On Aug 7, 1:05 pm, Rohan <[EMAIL PROTECTED]> wrote:
> Hello,
> I would like to write a script which does the following job.
> Take column1 and 7 from 10 different excel sheets and pasthe them into
> a new excel worksheet.
> Any ideas on how to do it
> Thanks,

Try studying this code:

http://snippets.dzone.com/posts/show/2036

or this:

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

or this:

http://mathieu.fenniak.net/plotting-in-excel-through-pythoncom/

Learning COM objects can be fun...or it can be a pain, depending on
your attitude and what you're trying to automate.

Mike

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


Re: Dealing with multiple excel sheets

2007-08-07 Thread Neil Cerutti
On 2007-08-07, Rohan <[EMAIL PROTECTED]> wrote:
> I would like to write a script which does the following job.
> Take column1 and 7 from 10 different excel sheets and pasthe
> them into a new excel worksheet. Any ideas on how to do it

Get the xlrd Python module. It'll come in handy.

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


Heterogeneous lists

2007-08-07 Thread Gordon Airporte
This is one of those nice, permissive Python features but I was 
wondering how often people actually use lists holding several different 
types of objects.
It looks like whenever I need to group different objects I create a 
class, if only so I can use more meaningful names than '[2]' for the items.
How often do these show up in your code?
Is this simply the upshot of the underlying arrays holding only object 
references of some sort?
-- 
http://mail.python.org/mailman/listinfo/python-list


re: mmm-mode, python-mode and doctest-mode?

2007-08-07 Thread John J Lee
On Tue, 7 Aug 2007, Edward Loper wrote:

> [John J Lee]
>> Is it possible to get doctest-mode to work with mmm-mode and python-mode 
>> nicely so that docstrings containing doctests are editable in doctest-mode?
>
> I recently released a new version of doctest-mode [1], and I came across your 
> email [2] (it was on the first page of google hits for "doctest-mode").  So I 
> decided to have a go at getting doctest-mode to play nicely with mmm-mode. 
> The result is available here:
>
> https://python-mode.svn.sf.net/svnroot/python-mode/trunk/python-mode/doctest-mode.el

Nice!  Works for me so far (emacs 22).

I'm also very pleased to see that doctest-mode no longer attempts to 
auto-fill at the end of long lines -- that was extremely annoying, and the 
new behaviour is a big improvement.

Here's another wish.  My next-nearest doctest-mode annoyance: hitting TAB 
should have similar behaviour to python-mode.  So, the first press of the 
TAB key gets you a sensible guess at the indentation you want.  The second 
and subsequent TAB keypresses cycle through no indentation, '>>>' 
indentation, and '...' indentation.  Ideally this would be made to work in 
combination with the standard indentation-cycling behaviour in those cases 
where multiple indentations are allowed within Python code (so, it might 
be ' ... ', '', '>>> ', '... ','... ',
' ... ' as the TAB key is repeatedly pressed).


>> `doctest-example'
>>
>> Used to edit doctest examples in text-editing modes, such as
>> `rst-mode' or `text-mode'.  Docstring submode regions start with
>> optionally indented prompts (>>>) and end with blank lines.  Use
>> (C-c % C-e) to insert a new doctest-example region.  When
>> `doctest-execute' (C-c C-c) is called inside a doctest-example
>> region, it executes all examples in the buffer.

I couldn't immediately see how to get this working in a .doctest file, so 
haven't tried this yet.

Another wish: Even though I don't normally run code from emacs directly, I 
do think it would be very handy indeed to be able to execute a *single* 
doctest example from doctest-mode.  Don't know what keybinding would be 
conventional...


John

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


Re: Heterogeneous lists

2007-08-07 Thread Bruno Desthuilliers
Gordon Airporte a écrit :
> This is one of those nice, permissive Python features but I was 
> wondering how often people actually use lists holding several different 
> types of objects.

Depends on the definition of 'type'. I often have instances of different 
- possibly unrelated - classes in a same list. Fact is that these 
instances usually share a common (implied) interface, but, well, 
sometimes they don't...

> It looks like whenever I need to group different objects I create a 
> class, if only so I can use more meaningful names than '[2]' for the items.

You may not know, but Python has a builtin dict (ie : hashtable) type. 
It's very handy when you just want to "group different objects" while 
still using meaningful names.

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


Tuning - Styling

2007-08-07 Thread airconditi
Cool cars, tuning & styling, here you can find many tuned cars with
tons of pictures!!!

http://tuning-styling.blogspot.com/

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


Re: Heterogeneous lists

2007-08-07 Thread Jarek Zgoda
Bruno Desthuilliers napisał(a):

> Gordon Airporte a écrit :
>> This is one of those nice, permissive Python features but I was
>> wondering how often people actually use lists holding several
>> different types of objects.
> 
> Depends on the definition of 'type'. I often have instances of different
> - possibly unrelated - classes in a same list. Fact is that these
> instances usually share a common (implied) interface, but, well,
> sometimes they don't...

I love my lists of classes. I know, I'll go to hell for that.

-- 
Jarek Zgoda
http://jpa.berlios.de/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Adding a list of descriptors to a class

2007-08-07 Thread Bruno Desthuilliers
Marc 'BlackJack' Rintsch a écrit :
> On Tue, 07 Aug 2007 09:25:32 -0700, Bob B. wrote:
> 
> 
>>Ok, that "exec" is an ugly hack.  There's gotta be someway to plop
>>this straight into the class's __dict__ without doing that, but when I
>>try adding self.__class__.__dict__[attr] = MyDesc(attr) in MyClass's
>>__init__ method, I get the error: "TypeError: 'dictproxy' object does
>>not support item assignment"
> 
> 
> Does ``setattr(self.__class__, attr, MyDesc(attr))`` work?

In the __init__() ?

Yes indeed, it works. But it means that:
1/ the attributes are not set on the class before it has been 
instanciated at least once
2/ each time you instanciate the class, the attributes are rebound to 
new MyDesc instances

class MyDesc(object):
 def __init__(self, name=None, initVal=None):
 self.name = name
 self.value = initVal
 print "new %s" % self.__class__.__name__

 def __get__(self, obj, objtype):
 # Do some stuff
 #self.value = "blah"
 if obj is None:
 return self
 return self.value

class Marc(object):
 attributes = ('toto', 'tata')
 def __init__(self):
 cls = self.__class__
 for attr in cls.attributes:
 setattr(cls, attr, MyDesc(attr, attr))

 >>> Marc.toto
Traceback (most recent call last):
   File "", line 1, in ?
AttributeError: type object 'Marc' has no attribute 'toto'
 >>> m1 = Marc()
new MyDesc
new MyDesc
 >>> Marc.toto
<__main__.MyDesc object at 0x4033846c>
 >>> t = _
 >>> m2 = Marc()
new MyDesc
new MyDesc
 >>> Marc.toto is t
False
 >>>

So while it "works" (kinda), I would not recommand this solution. Even 
if you do test for the existence of the attribute before rebinding it, 
you'll have to go thru the whole dance each time you instanciate the class.

My 2 cents...
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Adding a list of descriptors to a class

2007-08-07 Thread Bruno Desthuilliers
Bob B. a écrit :
> I've been playing with descriptors lately.  I'm having one problem I
> can't seem to find the answer to.  I want to assign a descriptor to a
> list of attributes.  I know I should be able to add these somewhere in
> the class's __dict__, but I can't figure out where.  Here's some code:
> 
> class MyDesc(object):
>   def __init__(self, name=None, initVal=None):
> self.name = name
> self.value = initVal
> 
>   def __get__(self, obj, objtype):
> // Do some stuff
> self.value = "blah"
> return self.value
> 
> class MyClass(object):
>   attributes = ('attr1', 'attr2')
>   for attr in attributes:
> exec ("%s=MyDesc('%s')") % (attr, attr)
> 
>   // More stuff in the class
> 
> Ok, that "exec" is an ugly hack.  There's gotta be someway to plop
> this straight into the class's __dict__ without doing that, but when I
> try adding self.__class__.__dict__[attr] = MyDesc(attr) in MyClass's
> __init__ method, I get the error: "TypeError: 'dictproxy' object does
> not support item assignment"
> 
> Any ideas?

Steven already show you the simplest solution. Now if you want something 
"cleaner" (or at least more transparent to persons subclassing MyClass - 
which may or may not be a concern), you can use metaclasses too:

class MyDesc(object):
 def __init__(self, name=None, initVal=None):
 self.name = name
 self.value = initVal

 def __get__(self, obj, objtype):
 # Do some stuff
 #self.value = "blah"
 if obj is None:
 return self
 return self.value

class MyType(type):
 def __init__(cls, name, bases, dic):
 attributes = dic.get('attributes', None)
 if attributes is not None:
 for attrname, initval in attributes.iteritems():
 setattr(cls, attrname, MyDesc(attrname, initval))

class MyClass(object):
 __metaclass__ = MyType
 attributes = dict(attr1="attr1", attr2="attr2")

class MySubclass(MyClass):
 # let you override parent's attributes...
 attributes = dict(attr1="otherattr1", attr3="a new one")


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


Python FNV Hash

2007-08-07 Thread Edward Blake
Before I go through the work of wrapping the FNV hash source found on
http://isthe.com/chongo/tech/comp/fnv/ I thought I would ask here to see if
anyone already has an implementation of it available. I'm particularly
interested in hash_64, the 64 bit Fowler/Noll/Vo-0 FNV-1a hash code.
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Web based Reporting tool for Python

2007-08-07 Thread Jon Rosebaugh
On 2007-08-06 23:29:16 -0500, Madhu Alagu <[EMAIL PROTECTED]> said:

> Hi
> I am looking template based report tools for python.It has the ability
> to deliver rich content onto the screen, to the printer or into PDF,
> HTML, XLS, CSV and XML files.

I don't think this has been implemented in Python because it's a pretty 
boring thing to do, and things like JasperReports (in Java) and Crystal 
Reports already have the market pretty well tied up. What my company 
did was to use JasperReports via a web service we set up.

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


Re: Misleading wikipedia article on Python 3?

2007-08-07 Thread John J. Lee
Carsten Haese <[EMAIL PROTECTED]> writes:

> On Sun, 2007-08-05 at 23:09 +, John J. Lee wrote:
>> I just wanted to know: is it easy to make my code so it
>> runs on 2.6 and 3.0, without funny stuff like a code translator?
>
> That depends on your definitions of "easy" and "funny stuff." I'm pretty
> sure you'll be able to run the same source code on Python 2.6 and Python
> 3.0 without either one breaking, as long as the code is written
> sufficiently carefully. You may have to give up some Python 3.0 features
> and/or write compatibility shims depending on what features you'll need.
> Whether that's acceptable depends on the features you need and how much
> "yak shaving" you find acceptable.
[...]

If I had wanted to start analysing requirements for some specific
project, I'd have gone and done that!-) I was actually interested in
the general case (all existing projects), as perhaps you'll see if you
read my original post (my followup question you quote above was
deliberately blunt for rhetorical let's-move-this-discussion-along
purposes --  honestly, these literal-minded programmer types,
what CAN you do with them?-).

Do you *really* think that projects will fall 50-50 into the "yes" and
"no" camps, as you seem to imply -- after all, if you thought that one
case was more common, why wouldn't you mention which it was?

(where "yes" == "feasible to keep a single source code working in both
2.6 and 3.0", and of course it's taken as read that you can do the
generalisation to the -- I hope -- obvious continuum of cases
"between" "yes" and "no" without our needing to tiresomely spell it
out here)

I'll also add that previous comments from Guido have implied (to my
reading, admittedly without studying them like biblical texts) that
the great majority of projects will/should fall pretty squarely, in
his judgement, into the "no" camp -- i.e. NOT practical to keep 2.6
and 3.0 comptibility from a single source code without use of a
translation tool.  Does your "pretty sure"-ness stem from 1) a
knowledge of how 3.0 will look when it's done, 2) experience of
playing with the Py3k project as it is right now or 3) other?  What
sort of frequencies does your understanding of Py3k predict for the
"yes" and "no" cases?  By all means "use your skill and judgement" in
answering, rather than asking for clarification -- since that would
rather defeat the point of the question.


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


[pyserial - winXP] Serial port stop receiving data after a few hours, raise no error

2007-08-07 Thread pauland80

>My soft passively listen to a device sending +- 300 bytes of data each
>second. After several hours of work, the soft abruptly stops receiving
>data without any error, (while the device sends properly, of course)
>and I need to restart it (the python soft) to "reactivate" the ports.
>
>I read that when the serial port encounters an error (frame error or
>so, I imagine?) it stop receiving data until the library function
>"getCommError()" is called.
>
>Am I on the good track? Can I call this function from my pyserial
>code?
>
>Why pyserial does'nt raise a serial.SerialException in this case?
>
>Notes:
>-
>I'm not working with plain serial ports, I use serial over USB (FTDI
>or so) and serial over Ethernet (moxa.com).
>I'm in 115k 8N1 and I use 4 ports simultaneously
>I use python 2.4 with pyserial 2.2 on Windows XP.




Late thanks for your both answers! (Please excuse me for that)

The problem was a bug in the device firmware.
But before finding this, I dugg lightly in the pyserial source and
found (to take with care!) :

+ getCommError(...) is (?) no more implemented in the win32 API (it
was in the win16 API) ; it is replaced by GetCommState(...) ; pyserial
use GetCommState(...) in _reconfigurePort()

+ pyserial use ClearCommError in the functions read(...) and
inWaiting(...) ; it takes somewhat different arguments than
GetCommState(...) but return the same (?) info AND clear the errors
(getcomm(Error|State) doesn't (?)).

+ the errors on the serial flow (overrun and so) seem just cleared
away and not followed to the application by pyserial.

PA

the links :
delta win 16/32 on msdn : http://msdn2.microsoft.com/en-us/library/aa383678.aspx
GetCommState() on msdn : http://msdn2.microsoft.com/en-us/library/aa363260.aspx
ClearCommError() on msdn : 
http://msdn2.microsoft.com/en-us/library/aa363180.aspx

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


Re: ensuring GNU readline isn't used

2007-08-07 Thread John J. Lee
Duncan Booth <[EMAIL PROTECTED]> writes:

> Josh Paetzel <[EMAIL PROTECTED]> wrote:
>
>> Is there a way to ensure that GNU readline isn't used (even though
>> support may have been compiled in?).  I'm experiencing a licensing
>> problem, I'd like to use the "cmd" module, for example, but my code is
>> proprietary and hence, if cmd uses readline, I can't use cmd.
>
> I think you have misread the GPL: just because your non-GPL code *can* be 
> used with something covered by the GPL doesn't mean your code is infected 
> by the GPL. Your code doesn't require a GPL module to run (you can use a 
> version of cmd compiled without readline), and you aren't attempting to 
> distribute it with a GPL module, so you don't need to care how the end user 
> chooses to run it.

Indeed -- I recall coming across some commercial control &
data-acquisition software which was distributed with an inferior
readline work-alike library, but came with detailed instructions for
how to use GNU readline instead.  All users who had the time and good
sense presumably linked with readline proper.


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


Re: Misleading wikipedia article on Python 3?

2007-08-07 Thread Martin v. Löwis
> Do you *really* think that projects will fall 50-50 into the "yes" and
> "no" camps, as you seem to imply -- after all, if you thought that one
> case was more common, why wouldn't you mention which it was?

I know you didn't ask me this time, but I answer anyway: I don't know.

I *really* think that only experience can tell, and that any kind of
prediction on that matter is futile FUD (as FUD, it might be successful,
of course). I do so using all my skill and judgment. Only when people
actually start to try porting, list specific issues that they actually
ran into (rather than listing issues they anticipate to run into),
only then I can make guesses as to what the common case will be.

Ask this question a year from now again.

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


Re: Web based Reporting tool for Python

2007-08-07 Thread Jay Loden
Madhu Alagu wrote:
> I am looking template based report tools for python.It has the ability
> to deliver rich content onto the screen, to the printer or into PDF,
> HTML, XLS, CSV and XML files.

As others have mentioned, I don't believe that all of the above is implemented
in a single package. However, Python can most definitely deal with all of the
above formats.

For HTML templating I can highly recommend Clearsilver:
http://www.clearsilver.net/ it's written in C with Python (and other language)
wrappers, is very fast and is also extensible.

For PDF:
ReportLab - http://www.reportlab.org/downloads.html
  - 
http://www.ibm.com/developerworks/linux/library/l-sc6.html?loc=dwmain

For XSLT:
4Suite, libxml - http://uche.ogbuji.net/tech/akara/nodes/2003-01-01/python-xslt

For CSV and XML:
csv module, libxml, lxml, ElemenTree modules

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


Re: Misleading wikipedia article on Python 3?

2007-08-07 Thread John J. Lee
"Martin v. Löwis" <[EMAIL PROTECTED]> writes:

>> Do you *really* think that projects will fall 50-50 into the "yes" and
>> "no" camps, as you seem to imply -- after all, if you thought that one
>> case was more common, why wouldn't you mention which it was?
>
> I know you didn't ask me this time, but I answer anyway: I don't know.
>
> I *really* think that only experience can tell, and that any kind of
> prediction on that matter is futile FUD (as FUD, it might be successful,
> of course). I do so using all my skill and judgment. Only when people
> actually start to try porting, list specific issues that they actually
> ran into (rather than listing issues they anticipate to run into),
> only then I can make guesses as to what the common case will be.
[...]

By this criterion, Guido himself is engaging in FUD, as near as I can
tell (of course, I don't believe he is doing that; I also can't
believe that the effective requirements for the project are quite as
decoupled from source compatibility considerations as has sometimes
been implied by some of those working on the project).


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

Re: Buffering HTML as HTMLParser reads it?

2007-08-07 Thread Bruno Desthuilliers
[EMAIL PROTECTED] a écrit :
> Hello,
> 
> I am working on a project where I'm using python to parse HTML pages,
> transforming data between certain tags. Currently the HTMLParser class
> is being used for this. In a nutshell, its pretty simple -- I'm
> feeding the contents of the HTML page to HTMLParser, then I am
> overriding the appropriate handle_ method to handle this extracted
> data. In that method, I take the found data and I transform it into
> another string based on some logic.
> 
> Now, what I would like to do here is take that transformed string and
> put it "back into" the HTML document. Has anybody ever implemented
> something like this with HTMLParser?

Works the same with any sax (event-based) parser. First subclass the 
parser, adding a 'buffer' (best is to use a file-like object so you can 
either write to a stream, a file, a cStringIO etc) attribute to it and 
making all the handlers writing to this buffer. Then subclass your 
customized parser, and only override the needed handlers.

Q&D example implementation:

def format_attrs(attrs) :
   return ' '.join('%s=%s' % attr for attr in attrs)

def format_tag(tag, attrs, formats):
   attrs = format_attrs(attrs)
   return formats[bool(attrs)] % dict(tag=tag, attrs=attrs)

class BufferedHTMLParser(HTMLParser):
   START_TAG_FORMATS = ('<%(tag)s>', '<%(tag)s %(attrs)s>')
   STARTEND_TAG_FORMATS = ('<%(tag)s />', '<%(tag)s %(attrs)s />')

   def __init__(self, buffer):
 self.buffer = buffer

   def handle_starttag(self, tag, attrs):
  self.buffer.write(format_tag(tag,attrs,self.START_TAG_FORMATS))

   def handle_startendtag(self, tag):
 self.buffer.write(format_tag(tag,attrs,self.STARTEND_TAG_FORMATS))

   def handle_endtag(self, tag):
 self.buffer.write(' % tag)

   def handle_data(self, data):
 self.buffer.write(data)

   # etc for all handlers


class MyParser(BufferedHtmlParser):
def handle_data(self, data):
   data = data.replace(
 'Ni',
 "Ekky-ekky-ekky-ekky-z'Bang, zoom-Boing, z'nourrrwringmm"
 )
   BufferedHTMLParser.handle_data(self, data)

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


passing vars to py scipts in cron jobs

2007-08-07 Thread brad
What's the proper way to call a py script and pass in variables while 
doing cron jobs? I can run the scripts fine from idle, python, etc using 
raw_input() to prompt users. The scripts have classes with methods that 
need arguments. Here's an example... I want to run c1.d1(v,v,v) then 
c2.d2(v,v,v)

class c1:
   # User defined vars
def d1(var1, var2, var3):
   pass

class c2:
# User defined vars
def d2(var1, var2, var3):
   pass

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


Re: Heterogeneous lists

2007-08-07 Thread Tony
On Aug 7, 8:53 pm, Jarek Zgoda <[EMAIL PROTECTED]> wrote:
.
>
> I love my lists of classes. I know, I'll go to hell for that.
>
> --
> Jarek Zgodahttp://jpa.berlios.de/

And I love my shelved lists of classes..

Tony

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


Re: Heterogeneous lists

2007-08-07 Thread faulkner
On Aug 7, 2:53 pm, Gordon Airporte <[EMAIL PROTECTED]> wrote:
> This is one of those nice, permissive Python features but I was
> wondering how often people actually use lists holding several different
> types of objects.
> It looks like whenever I need to group different objects I create a
> class, if only so I can use more meaningful names than '[2]' for the items.
> How often do these show up in your code?
> Is this simply the upshot of the underlying arrays holding only object
> references of some sort?

how else would you implement an n-ary tree? eg, AST, CST, minimax, GP.

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


Re: passing vars to py scipts in cron jobs

2007-08-07 Thread Will Maier
On Tue, Aug 07, 2007 at 05:45:46PM -0400, brad wrote:
> What's the proper way to call a py script and pass in variables
> while doing cron jobs? I can run the scripts fine from idle,
> python, etc using raw_input() to prompt users. The scripts have
> classes with methods that need arguments. 

This is commonly done with either sys.argv (a list of arguments
passed when invoking the script) or os.environ (a dictionary of
environment variables and values). Use either to instantiate your
classes or run functions.

-- 

[Will [EMAIL PROTECTED]|http://www.lfod.us/]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Email

2007-08-07 Thread Rohan
On Aug 3, 7:22 pm, SMERSH009 <[EMAIL PROTECTED]> wrote:
> On Aug 3, 9:47 am,Rohan<[EMAIL PROTECTED]> wrote:
>
>
>
> > On Aug 2, 1:06 pm, Laurent Pointal <[EMAIL PROTECTED]> wrote:
>
> > >Rohanwrote:
> > > > I was wondering if there could be an arrangement where a file could be
> > > > attached and send as an email.
> > > > For ex
> > > > f = open(add.txt,w)
> > > > f.write('python')
> > > > f.close()
>
> > > > Now I would like to send an email with add.txt as an attachment, is it
> > > > possible ?
> > > > some one give me a pointer towards this.
>


> > > You can use iMailer as an example script to get parts:
>
> > >http://nojhan.free.fr/article.php3?id_article=22
>
> > > A+
>
> > > Laurent.
>
> > Laurent the link you gave me is in a language unknown to me if you
> > have anything that expalains in english, then let me know.
> > thanks
>
> Did you try Google translate?  Here is the tiny url of the page you
> wanted translatedhttp://tinyurl.com/3xlcmc

Thanks everyone,
I'm able to write a script which reads the file and puts it in the
message. I would like to attach the file is it possible?

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


Destruction of generator objects

2007-08-07 Thread Stefan Bellon
Hi all,

I'm generating a binding from Python to C using SWIG. On the C side I
have iterators over some data structures. On the Python side I
currently use code like the following:

def get_data(obj):
result = []
iter = make_iter(obj)
while more(iter):
item = next(iter)
result.append(item)
destroy(iter)
return result

Now I'd like to transform it to a generator function like the following
in order to make it more memory and time efficient:

def get_data(obj):
iter = make_iter(obj)
while more(iter):
yield next(iter)
destroy(iter)

But in the generator case, I have a problem if the generator object is
not iterated till the StopIteration occurs, but if iteration is stopped
earlier. In that case, the C iterator's destroy is not called, thus the
resource is not freed.

Is there a way around this? Can I add some sort of __del__() to the
generator object so that in case of an early destruction of the
generator object, the external resource is freed as well?

I'm looking forward to hearing your hints!

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


Re: Something in the function tutorial confused me.

2007-08-07 Thread Ricardo Aráoz
Lee Fleming wrote:
> Thanks for all the help, everyone. I guess I was confused with default
> arguments that were mutable and immutable. I will continue to look
> over these posts until I understand what is happening.
> 
> I cannot believe the number of helpful responses I got!
> 

Apparently he didn't understand.
Neither did I.

Either (i)y's initial value (None or []) is saved somewhere to be
retrieved every time the function is called without 2nd argument, or
(ii) y keeps the value it has when last exiting the function (if there
is a third option, please mention it).

(i) (a) whenever the function is called without 2nd argument the value
None is retrieved and assigned to y, thus causing [] to be assigned to y
by the 'if' statement.
(i) (b) But then if it is "def f(x, y = [])" the list [] should be ALSO
saved somewhere and when the function is called without 2nd argument it
should be retrieved and assigned to y, thus y would always be [] when
you enter the function without 2nd arg.

(ii) (b) if y keeps the value it has when last exiting the function that
would explain that the second time you call it the list returned will
have two members.
(ii) (a) But then if it is "def f(x, Y = None)" when the "if" is
evaluated the empty list is assigned to y. So y will NO LONGER be None.
The second time the function is called y is NOT None (remember it keeps
it's last value) and the function returns a list with two members.

So, as I see it, the behavior is not coherent, the function treats y
differently according to the value it has assigned.

Please correct me!




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


Re: ensuring GNU readline isn't used

2007-08-07 Thread Ben Finney
Josh Paetzel <[EMAIL PROTECTED]> writes:

> Is there a way to ensure that GNU readline isn't used (even though
> support may have been compiled in?).  I'm experiencing a licensing
> problem

Note that the GPL (the license terms of readline) is like any other
valid copyright license in that it only restricts acts covered by
copyright. You have no responsibility to prevent others from using a
GPL-covered work.

Anyone may use a GPL-covered work they receive for any purpose without
further permission; nobody needs a copyright license for that (despite
what some copyright holders might prefer). Copyright covers acts of
copying and distribution, so you *do* need license to do those things
with someone's work.

> but my code is proprietary

That's unfortunate. I hope you can fix that.

> and hence, if cmd uses readline, I can't use cmd.

Not true; you can derive from and redistribute cmd, so long as you
comply with the license on cmd.

-- 
 \  "What I have to do is see, at any rate, that I do not lend |
  `\   myself to the wrong which I condemn."  -- Henry Thoreau, _Civil |
_o__)Disobedience_ |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: step through .py file in a .NET application written in C# in Visual Studio

2007-08-07 Thread jingwu . mail
On Aug 7, 9:24 am, Paul McGuire <[EMAIL PROTECTED]> wrote:
> On Aug 6, 5:22 pm, Bo <[EMAIL PROTECTED]> wrote:
>
>
>
> > Hello All,
>
> > I am experimenting IronPython in Visual Studio.  Here is what I have,
> > what I did and what I want
>
> > 1.  I have installed Visual Studio SDK 4.0 according to 
> > thisbloghttp://blogs.msdn.com/aaronmar/archive/2006/02/16/a-bit-more-on-ironp...
>
> > If I run Visual Studio under Experimental Hive, aPythonfile opened
> > is color coded.
>
> > 2.  Also, my computer has apparently installed some IronPython DLL
> > because my Visual Studio can recoginize the following class:
> > IronPython.Hosting.PythonEngine.
>
> > If I declare something like the following in Visual Studio:
>
> > public static class MyPythonClass {
> >private static IronPython.Hosting.PythonEngine   MY_ENGINE;
> >   //suppose I have created an instance of PhythonEngine and assigned
> > to MY_ENGINE
> >
>
> > }
>
> > If I do "Go to Definition" of PythonEngine, I can navigate to the
> > Definition of PythonEngine, but it is from MetaData.
>
> > 3.  In my .NET application (written in C#) , I can invoke the
> > execution of an externalpythonfile using something like:
> > MyPythonClass.MY_ENGINE.ExecuteFile("myPythonFileWithAbsolutePath.py")
>
> > Thepythonfile (myPythonFileWithAbsolutePath.py) can be executed all
> > right, but I want to step through it to debug it.  Any suggestions on
> > how to do it?
>
> > Thanks abunch.
>
> > Bo
>
> Um, make sure you compile with debug?
>
> I have coded in Boo, which is veryPython-like, and it will step
> through the debugger just fine, so IP should do the same in theory.
> But I've not used IP, so all I can give are generic "are you sure it's
> plugged in?" type of suggestions.
>
> Hmm, upon rereading your post, I see that you want the debugger to
> step through a separate file that was executed using ExecuteFile.
> Unless there are some debug options on ExecuteFile, I'd say your
> chances are slim, since the file being executed is not really part of
> the image being debugged.  You could also try explicitly invoking the
> debugger from within the file that you are loading, using (this works
> from Boo):
>
> System.Diagnostics.Debugger.Launch()
> System.Diagnostics.Debugger.Break()
>
> -- Paul


Thanks Paul, for giving me the suggestions.  I will try your
suggestion.

I have been struggling with the most of today.  Here is a summary of
what I have found.  May be useful to other

1.  My IronPython DLL is version 1.1.  It is download here
http://www.codeplex.com/Wiki/View.aspx?ProjectName=IronPython

2.  Apparently, there is a problem with either the ipy.exe or
IronPython.DLL that one cannot step into a function (F11 in visual
studio).  Here is the discussion
http://lists.ironpython.com/pipermail/users-ironpython.com/2007-May/004957.html

I am not sure if this is related to my case.

3.  Here is Jim Hugunin's presentation
http://msdn.microsoft.com/msdntv/episode.aspx?xml=episodes/en/20051110PythonJH/manifest.xml

Apparently, he can step through the external ironpython file in an C#
application.  He probably used an old version of Iron Python.  The
method he used to execute the external iron python file is
Engine.Runfile()


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


Re: Something in the function tutorial confused me.

2007-08-07 Thread David Wahler
On 8/7/07, Ricardo Aráoz <[EMAIL PROTECTED]> wrote:
> Lee Fleming wrote:
> > Thanks for all the help, everyone. I guess I was confused with default
> > arguments that were mutable and immutable. I will continue to look
> > over these posts until I understand what is happening.
> >
> > I cannot believe the number of helpful responses I got!
> >
>
> Apparently he didn't understand.
> Neither did I.
>
> Either (i)y's initial value (None or []) is saved somewhere to be
> retrieved every time the function is called without 2nd argument, or
> (ii) y keeps the value it has when last exiting the function (if there
> is a third option, please mention it).
>

It's option (i).

> (i) (a) whenever the function is called without 2nd argument the value
> None is retrieved and assigned to y, thus causing [] to be assigned to y
> by the 'if' statement.

Yep.

> (i) (b) But then if it is "def f(x, y = [])" the list [] should be ALSO
> saved somewhere and when the function is called without 2nd argument it
> should be retrieved and assigned to y, thus y would always be [] when
> you enter the function without 2nd arg.

No, when the def statement is executed, the expression [] is
evaluated, and the result of this evaluation is an empty list. It's a
reference to this list that is saved, not the expression itself. All
invocations of the function that use the default argument refer to the
same list, so if it gets modified the modifications persist.

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

Re: Something in the function tutorial confused me.

2007-08-07 Thread Steve Holden
Ricardo Aráoz wrote:
> Lee Fleming wrote:
>> Thanks for all the help, everyone. I guess I was confused with default
>> arguments that were mutable and immutable. I will continue to look
>> over these posts until I understand what is happening.
>>
>> I cannot believe the number of helpful responses I got!
>>
> 
> Apparently he didn't understand.
> Neither did I.
> 
> Either (i)y's initial value (None or []) is saved somewhere to be
> retrieved every time the function is called without 2nd argument, or
> (ii) y keeps the value it has when last exiting the function (if there
> is a third option, please mention it).
> 
> (i) (a) whenever the function is called without 2nd argument the value
> None is retrieved and assigned to y, thus causing [] to be assigned to y
> by the 'if' statement.
> (i) (b) But then if it is "def f(x, y = [])" the list [] should be ALSO
> saved somewhere and when the function is called without 2nd argument it
> should be retrieved and assigned to y, thus y would always be [] when
> you enter the function without 2nd arg.
> 
> (ii) (b) if y keeps the value it has when last exiting the function that
> would explain that the second time you call it the list returned will
> have two members.
> (ii) (a) But then if it is "def f(x, Y = None)" when the "if" is
> evaluated the empty list is assigned to y. So y will NO LONGER be None.
> The second time the function is called y is NOT None (remember it keeps
> it's last value) and the function returns a list with two members.
> 
> So, as I see it, the behavior is not coherent, the function treats y
> differently according to the value it has assigned.
> 
> Please correct me!

OK. The difference is that [] is a mutable value, while None is 
immutable. So when the function starts out with [] as y's value, and the 
value gets changed, the same value is used the next time the function is 
called and the second call sees the mutated value.

When the function starts out with None as y's value any assignment to y 
causes it to reference a different value (since None is immutable). So 
the next time the function is called y is pointing at the None that it 
was pointing at the last time the function was called (since None cannot 
be mutated).

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

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


  1   2   >