Re: web service between python and c#

2008-01-08 Thread Jeroen Ruigrok van der Werven
-On [20080108 07:24], abhishek ([EMAIL PROTECTED]) wrote:
>but have no idea on how to interface it with c# client.

Totally depends on what exactly you need to accomplish.

Some solutions can just use SOAP or REST. Others need full-fledged XML-RPC or
other similar solutions. Some just use a serialization format like JSON.

So what exactly are you trying to do?

-- 
Jeroen Ruigrok van der Werven  / asmodai
イェルーン ラウフロック ヴァン デル ウェルヴェン
http://www.in-nomine.org/ | http://www.rangaku.org/
And every word upon your spiralling cross is but a misled sun, a bitter
 loss...
-- 
http://mail.python.org/mailman/listinfo/python-list

Look for a string on a file and get its line number

2008-01-08 Thread Horacius ReX
Hi,

I have to search for a string on a big file. Once this string is
found, I would need to get the number of the line in which the string
is located on the file. Do you know how if this is possible to do in
python ?

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


Re: Tkinter variable trace problem

2008-01-08 Thread Peter Otten
C Martin wrote:

> What am I doing wrong in this code? The callback doesn't work from the Entry 
> widget.
> 
> ##start code
> import Tkinter
>   
> tk = Tkinter.Tk()
> var = Tkinter.StringVar()
> print var._name
> 
> def cb(name, index, mode):
>   print "callback called with name=%r, index=%r, mode=%r" % (name, index, 
> mode)
>   varValue = tk.getvar(name)
>   print "and variable value = %r" % varValue
> 
> var.trace('w', cb)
> 
> var.set('test')
> entry = Tkinter.Entry(tk, textvariable=var)
> entry.pack()
> 
> tk.mainloop()
> ##end code
> 
> It produces the following output. The first three lines appear right away, 
> and the exception occurs when you type in the entry widget:
> 
>>test.py
> PY_VAR0
> callback called with name='PY_VAR0', index='', mode='w'
> and variable value = 'test'
> callback called with name='PY_VAR0', index='', mode='w'
> Exception in Tkinter callback
> Traceback (most recent call last):
>   File "C:\Python25\lib\lib-tk\Tkinter.py", line 1403, in __call__
> return self.func(*args)
>   File "D:\APCC\Projects\Utilities\VisualData\test.py", line 9, in cb
> varValue = tk.getvar(name)
>   File "C:\Python25\lib\lib-tk\Tkinter.py", line 421, in getvar
> return self.tk.getvar(name)
> TclError: can't read "PY_VAR0": no such variable

A quick look in the Tkinter source reveals that you need
tk.globalgetvar(), not tk.getvar(). 

I would actually recommend var.get(), so that you don't have to mess with
these internals at all.

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


Re: Look for a string on a file and get its line number

2008-01-08 Thread Jeroen Ruigrok van der Werven
-On [20080108 09:21], Horacius ReX ([EMAIL PROTECTED]) wrote:
>I have to search for a string on a big file. Once this string is
>found, I would need to get the number of the line in which the string
>is located on the file. Do you know how if this is possible to do in
>python ?

(Assuming ASCII, otherwise check out codecs.open().)

big_file = open('bigfile.txt', 'r')

line_nr = 0
for line in big_file:
line_nr += 1
has_match = line.find('my-string')
if has_match > 0:
print 'Found in line %d' % (line_nr)

Something to this effect.

-- 
Jeroen Ruigrok van der Werven  / asmodai
イェルーン ラウフロック ヴァン デル ウェルヴェン
http://www.in-nomine.org/ | http://www.rangaku.org/
If you think that you know much, you know little... 
-- 
http://mail.python.org/mailman/listinfo/python-list

Strip lines from files

2008-01-08 Thread Francesco Pietra
I am posting again as previous identical message had alleged suspicious header.

I used successfully script

f=open("prod1-3_no_wat_pop.pdb", "r")
for line in f:
line=line.rstrip()
if "WAT" not in line:
print line
f.close()

to strip lines containing the word WAT from a very long file.

A variant need has now emerged, to perform the same task from a very long
series of shorter files trp.pdb.1, trp.pdb.2 ,.  Could you see how to adapt
the above script to the new need?

Or adapt

grep -v WAT trp.pdb.1

grep -v WAT trp.pdb.2



grep -v WAT trp.pdb.n

Unless you can think better to remove that pervasive molecule of water, to
avoid performing the calculation ex novo.

Thanks

francesco pietra


  

Be a better friend, newshound, and 
know-it-all with Yahoo! Mobile.  Try it now.  
http://mobile.yahoo.com/;_ylt=Ahu06i62sR8HDtDypao8Wcj9tAcJ 

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


python syntax:urgent

2008-01-08 Thread mpho raborife

Anyone please help me get this syntax right

subprocess.Popen(["gmmscore", "-i", Input, "-l", List, "-t",
 modeltype,
> "-m", str(mixture), "-d", str(dimension), "-v", str(vfloor), "-n", 
> str(number), "-r",
 str(results)])



   
-
Be a better friend, newshound, and know-it-all with Yahoo! Mobile.  Try it now.-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Look for a string on a file and get its line number

2008-01-08 Thread John Machin
On Jan 8, 7:33 pm, Jeroen Ruigrok van der Werven <[EMAIL PROTECTED]
nomine.org> wrote:
> -On [20080108 09:21], Horacius ReX ([EMAIL PROTECTED]) wrote:
>
> >I have to search for a string on a big file. Once this string is
> >found, I would need to get the number of the line in which the string
> >is located on the file. Do you know how if this is possible to do in
> >python ?
>
> (Assuming ASCII, otherwise check out codecs.open().)
>
> big_file = open('bigfile.txt', 'r')
>
> line_nr = 0
> for line in big_file:
> line_nr += 1
> has_match = line.find('my-string')
> if has_match > 0:

Make that >=

| >>> 'fubar'.find('fu')
| 0
| >>>

> print 'Found in line %d' % (line_nr)

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


Re: Look for a string on a file and get its line number

2008-01-08 Thread Jeroen Ruigrok van der Werven
-On [20080108 09:51], John Machin ([EMAIL PROTECTED]) wrote:
>Make that >=

Right you are. Sorry, was doing it quickly from work. ;)

And I guess the find will also be less precise if the word you are looking is
a smaller part of a bigger word. E.g. find 'door' in a line that has 'doorway'
in it.

So 't is merely for inspiration. ;)

-- 
Jeroen Ruigrok van der Werven  / asmodai
イェルーン ラウフロック ヴァン デル ウェルヴェン
http://www.in-nomine.org/ | http://www.rangaku.org/
From morning to night I stayed out of sight / Didn't recognise I'd become
No more than alive I'd barely survive / In a word, overrun...
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Strip lines from files

2008-01-08 Thread Jeroen Ruigrok van der Werven
-On [20080108 09:40], Francesco Pietra ([EMAIL PROTECTED]) wrote:
>A variant need has now emerged, to perform the same task from a very long
>series of shorter files trp.pdb.1, trp.pdb.2 ,.  Could you see how to adapt
>the above script to the new need?

Look at sys.argv and pass the list of files to your script as a wildcard:

./myscript.py trp.pdb.*

And iterate over every argv you have to strip the WAT.

-- 
Jeroen Ruigrok van der Werven  / asmodai
イェルーン ラウフロック ヴァン デル ウェルヴェン
http://www.in-nomine.org/ | http://www.rangaku.org/
The wisdom of the wise, and the experience of ages, may be preserved by
quotations...
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Look for a string on a file and get its line number

2008-01-08 Thread Jeroen Ruigrok van der Werven
-On [20080108 09:51], John Machin ([EMAIL PROTECTED]) wrote:
>Make that >=
>
>| >>> 'fubar'.find('fu')

Or even just:

if 'my-string' in line:
   ...

Same caveat emptor applies though.

-- 
Jeroen Ruigrok van der Werven  / asmodai
イェルーン ラウフロック ヴァン デル ウェルヴェン
http://www.in-nomine.org/ | http://www.rangaku.org/
We're walking this earth. We're walking this shining earth...
-- 
http://mail.python.org/mailman/listinfo/python-list

popen question

2008-01-08 Thread Robert Latest
Hello,

look at this function:

--
def test():
child = os.popen('./slow')
for line in child:
print line
-

The program "slow" just writes the numbers 0 through 9 on stdout, one line a 
second, and then quits.

I would have expected the python program to spit out a numbers one by one, 
instead I see nothing for 10 seconds and then the whole output all at once.

How can I get and process the pipe's output at the pace it is generated?

Thanks,

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


Re: I'm searching for Python style guidelines

2008-01-08 Thread Ben Finney
ajaksu <[EMAIL PROTECTED]> writes:

> I've done this search before and it was very interesting, doing it
> again gave me new results that also seem valuable. Here's most of
> them (where PCG = Python Coding Guidelines).

Thanks, this is an awesome list. It's good to have a variety of real
examples when drafting a coding standard for a project.

> Do you think this could be a valuable addition to the Python wiki?

Definitely!

-- 
 \"The most merciful thing in the world... is the inability of |
  `\ the human mind to correlate all its contents."  -- Howard |
_o__)Philips Lovecraft |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: dictionary/hash and '1' versus 1

2008-01-08 Thread Piet van Oostrum
> "Diez B. Roggisch" <[EMAIL PROTECTED]> (DBR) wrote:

>DBR> So you can also do

>DBR> "" + some_object

>DBR> However,

>DBR> some_object + ""

>DBR> or

>DBR> 1 + ""

>DBR> don't work - the operator is only overloaded on the left argument.

There is no problem with 1+"" neither with new Integer(1)+"" in Java. Nor
any other object on the left hand side. The + operator is not tied to the
left hand side as in C++. if either side is a string and the other side has
a toString method it is OK. This is special-cased in the compiler. It is
defined in the language definition, not in the library definition.

-- 
Piet van Oostrum <[EMAIL PROTECTED]>
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: [EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python syntax:urgent

2008-01-08 Thread Jeroen Ruigrok van der Werven
-On [20080108 09:42], mpho raborife ([EMAIL PROTECTED]) wrote:
>subprocess.Popen(["gmmscore", "-i", Input, "-l", List, "-t",
> modeltype, "-m", str(mixture), "-d", str(dimension), "-v", str(vfloor),
> "-n", str(number), "-r", str(results)])

"gmmscore", "-i" seems a bit silly, why not just "gmmscore -i"?

You can always do something like (assuming all arguments are strings, adjust
accordingly):

s = "gmmscore -i %s -l %s -t %s -m %s -d %s -v %s -n %s -r %s" %
(Input, List, modeltype, str(mixture), str(dimension), str(vfloor),
 str(number), str(results))

subprocess.Popen([s])

-- 
Jeroen Ruigrok van der Werven  / asmodai
イェルーン ラウフロック ヴァン デル ウェルヴェン
http://www.in-nomine.org/ | http://www.rangaku.org/
Few are those who see with their own eyes and feel with their own hearts...
-- 
http://mail.python.org/mailman/listinfo/python-list

Passing contextual information when logging

2008-01-08 Thread Vinay Sajip
Some users of the logging package have raised an issue regarding the
difficulty of passing additional contextual information when logging.
For example, the developer of a networked application may want to log,
in addition to specifics related to to the network service being
provided, information about the IP address of the remote machine and
the username of the person logged into and using the service.

Python 2.4 introduced an 'extra' keyword argument which was intended
to hold a dict-like object containing additional information to be
added to a LogRecord. The additional information would then be printed
via placeholders in a format string.

While this works, it is a little unwieldy to use in practice, because
users need to provide the 'extra' parameter in every logging call.
This has led people in some instances to create context-specific
Logger instances (e.g. one logger for every connection). This has a
drawback in that a logger name can only provide limited contextual
information, and moreover, if the number of connections is effectively
unbounded over time, the number of Logger instances will also grow in
an unbounded way. (Logger instances are never garbage collected,
because references to them are always held in the logging package.
This alleviates a burden on users in that they never have to pass
loggers around, but means that creating a lot of Logger instances will
lead to a long-lived memory burden.)

One solution is to create a generic wrapper around loggers to which a
logger name and contextual information can be passed. The wrapper
would delegate logging calls to the logger with the specified name,
but would manipulate the arguments passed to the logging call to
insert the contextual information. I have created such a wrapper
class, called LoggerAdapter, which is in the example script located at

http://dpaste.com/30230/

I would welcome your views on whether the LoggerAdapter class is
suitable for adding to the logging package in Python 2.6/3.0. Does it
do what might reasonably be expected out of the box? LoggerAdapters
are, of course, garbage collected in the normal way and so impose no
particular memory burden.

Best regards,


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


Re: Pet Store

2008-01-08 Thread Marc 'BlackJack' Rintsch
On Mon, 07 Jan 2008 22:21:53 -0800, George Maggessy wrote:

> I'm an experience Java developer trying to learn Python. I just
> finished the Python tutorial on python.org and I'm currently reading
> the "Learning Python" book. However, if I could find something like a
> simple web app with some best practices, such as those famous "Java
> Pet Store" apps, I think that would help me to fill up some gaps in my
> learning process. Does anybody know any app like that?

Isn't that a web application using Java web frameworks?  So you are
looking for a Python web framework with a "Pet Store" tutorial?

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


Re: Pet Store

2008-01-08 Thread Jarek Zgoda
George Maggessy napisał(a):

> I'm an experience Java developer trying to learn Python. I just
> finished the Python tutorial on python.org and I'm currently reading
> the "Learning Python" book. However, if I could find something like a
> simple web app with some best practices, such as those famous "Java
> Pet Store" apps, I think that would help me to fill up some gaps in my
> learning process. Does anybody know any app like that?

TurboGears and Pylons both have "wiki" tutorials. Django has "poll"
tutorial. There are plenty others on the web.

-- 
Jarek Zgoda
Skype: jzgoda | GTalk: [EMAIL PROTECTED] | voice: +48228430101

"We read Knuth so you don't have to." (Tim Peters)
-- 
http://mail.python.org/mailman/listinfo/python-list


Python modules - how to create & which are better

2008-01-08 Thread grbgooglefan
I have embedded Python in my C++ application & creating Python
function from the expression. I am then evaluating those Python
compiled function (byte code) using PyObject_CallObject.

I want to create a Python module which will have functions called by
my user defined functions from the embedded Python interpreter.

What will be best approach in this case? Should I be creating
normal .py modules or .so modules (python extended with C code)?
For me, most important is the executiong speed of the code in these
modules. I want them to be fast, as those will be executed lot many
times & in time bound fashion.

Any suggestions on this?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: I'm searching for Python style guidelines

2008-01-08 Thread grflanagan
On Jan 8, 3:08 am, ajaksu <[EMAIL PROTECTED]> wrote:
> On Jan 7, 11:25 am, [EMAIL PROTECTED] wrote:
>
> > Anything written somewhere that's thorough? Any code body that should
> > serve as a reference?
>
> I've done this search before and it was very interesting, doing it
> again gave me new results that also seem valuable. Here's most of them
> (where PCG = Python Coding Guidelines).

[...]

>
> Do you think this could be a valuable addition to the Python wiki?
>

+1, absolutely

Here's the list in rest format:

--
FOSS Projects Style Guidelines
--

`Cogent project PCG`__

.. _Cogent PCG: http://jaynes.colorado.edu/PythonGuidelines.html

__ `Cogent PCG`_

`Cogent project Python Idioms`__

.. _Cogent Idioms: http://jaynes.colorado.edu/PythonIdioms.html

__ `Cogent Idioms`_

`Freevo Coding Standard`__

.. _Freevo PCG: http://doc.freevo.org/CodingStandard

__ `Freevo PCG`_

`Mercurial Basic Coding Style`__

.. _Mercurial PCG: 
http://www.selenic.com/mercurial/wiki/index.cgi/Basic_Coding_Style

__ `Mercurial PCG`_

`PyBlosxom Coding Style Guide`__

.. _PyBlosxom PCG: 
http://pyblosxom.sourceforge.net/blog/static/development#coding

__ `PyBlosxom PCG`_

`MoinMoin Coding Style`__

.. _MoinMoin PCG: http://moinmoin.wikiwikiweb.de/CodingStyle

__ `MoinMoin PCG`_

`Webware Style Guidelines`__

.. _Webware PCG: http://www.webwareforpython.org/Docs/StyleGuidelines.html

__ `Webware PCG`_

`NOAA Enhanced Forecaster Tools PCG`__

.. _NOAA PCG: 
http://www-md.fsl.noaa.gov/eft/developer/PythonCodingStandards.html

__ `NOAA PCG`_

`BioPython Coding Conventions`__

.. _BioPython PCG: http://biopython.org/wiki/Contributing#Coding_conventions

__ `BioPython PCG`_

`Mnet PCG`__

.. _Mnet PCG: http://mnet.sourceforge.net/coding_standards.html

__ `Mnet PCG`_

`Michael Foord's (aka Voidspace) PCG`__

.. _Michael PCG: 
http://www.voidspace.org.uk/python/weblog/arch_d7_2006_04_01.shtml#e296

__ `Michael PCG`_

`SQLObject Coding Style`__

.. _SQLObject PCG: http://www.sqlobject.org/DeveloperGuide.html#style-guide

__ `SQLObject PCG`_

`WxPython PCG`__

.. _WxPython PCG: http://www.wxpython.org/codeguidelines.php

__ `WxPython PCG`_

`Mailman PCG`__

.. _Mailman PCG: http://barry.warsaw.us/software/STYLEGUIDE.txt

__ `Mailman PCG`_

`VoiceCode PCG`__

.. _VoiceCode PCG: 
http://voicecode.iit.nrc.ca/VoiceCode/uploads/codingGuidelines.html

__ `VoiceCode PCG`_

`Bazaar Coding Style Guidelines`__

.. _Bazaar PCG: 
http://doc.bazaar-vcs.org/bzr.dev/en/developer-guide/HACKING.html#coding-style-guidlines

__ `Bazaar PCG`_

`IPython Developer Guidelines`__

.. _IPython PCG: 
http://ipython.scipy.org/moin/Developer_Zone/Developer_Guidelines

__ `IPython PCG`_

`OSAF Chandler PCG`__

.. _OSAF PCG: http://chandlerproject.org/Projects/ChandlerCodingStyleGuidelines

__ `OSAF PCG`_

`OSAF Chandler Epydoc Style Guide`__

.. _OSAF Epydoc: http://chandlerproject.org/Projects/ChandlerEpydocStyleGuide

__ `OSAF Epydoc`_

`Twisted Coding Standard`__

.. _Twisted PCG: 
http://twistedmatrix.com/trac/browser/trunk/doc/development/policy/coding-standard.xhtml?format=raw

__ `Twisted PCG`_

`PyPy RPython and CPython Coding Guidelines`__

.. _PyPy PCG: http://codespeak.net/pypy/dist/pypy/doc/coding-guide.html

__ `PyPy PCG`_

`Django PCG`__

.. _Django PCG: 
http://www.djangoproject.com/documentation/contributing/#coding-style

__ `Django PCG`_

`Docutils PCG`__

.. _Docutils PCG: 
http://docutils.sourceforge.net/docs/dev/policies.html#python-coding-conventions

__ `Docutils PCG`_

`Trac Coding Style`__

.. _Trac PCG: http://trac.edgewall.org/wiki/TracDev/CodingStyle

__ `Trac PCG`_

`OLPC PCG`__

.. _OLPC PCG: http://wiki.laptop.org/go/Python_Style_Guide

__ `OLPC PCG`_

`Skeletonz Coding and Naming Conventions`__

.. _Skeletonz PCG: 
http://orangoo.com/skeletonz/Developer_guide/Coding_convention/

__ `Skeletonz PCG`_

`CherryPy Code Conventions`__

.. _CherryPy PCG: http://www.cherrypy.org/wiki/CodeConventions

__ `CherryPy PCG`_

`Software Carpentry on style`__

.. _Software Carpentry PCG: http://www.swc.scipy.org/lec/style.html

__ `Software Carpentry PCG`_

`Zope's Coding Style`__

.. _Zope PCG: http://wiki.zope.org/zope3/CodingStyle

__ `Zope PCG`_

`The docstrings PEP`__

.. _docstrings: http://www.python.org/dev/peps/pep-0257/

__ `docstrings`_

`Pyflakes`__

.. _Pyflakes: http://divmod.org/trac/wiki/DivmodPyflakes

__ `Pyflakes`_

`PyChecker`__

.. _PyChecker: http://pychecker.sourceforge.net/

__ `PyChecker`_

`Pylint`__

.. _Pylint: http://www.logilab.org/857

__ `Pylint`_

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


Re: popen question

2008-01-08 Thread Marc 'BlackJack' Rintsch
On Tue, 08 Jan 2008 09:20:16 +, Robert Latest wrote:

> The program "slow" just writes the numbers 0 through 9 on stdout, one line a 
> second, and then quits.
> 
> I would have expected the python program to spit out a numbers one by one, 
> instead I see nothing for 10 seconds and then the whole output all at once.
> 
> How can I get and process the pipe's output at the pace it is generated?

Both processes have to make their communication ends unbuffered or line
buffered.  See the documentation of `os.popen()` for the `bufsize`
argument.  And do whatever is needed to output the numbers from ``slow``
unbuffered or line buffered.

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


Re: python syntax:urgent

2008-01-08 Thread Marc 'BlackJack' Rintsch
On Tue, 08 Jan 2008 10:03:56 +0100, Jeroen Ruigrok van der Werven wrote:

> -On [20080108 09:42], mpho raborife ([EMAIL PROTECTED]) wrote:
>>subprocess.Popen(["gmmscore", "-i", Input, "-l", List, "-t",
>> modeltype, "-m", str(mixture), "-d", str(dimension), "-v", str(vfloor),
>> "-n", str(number), "-r", str(results)])
> 
> "gmmscore", "-i" seems a bit silly, why not just "gmmscore -i"?

That's definitely *not* silly but the way to go.  There are two ways: The
above that calls the executable with the arguments as given, or with a
string like you suggests which is interpreted by a shell, so the arguments
must be escaped for that shell.  Which shell?  Depends on the system!

> You can always do something like (assuming all arguments are strings, adjust
> accordingly):
> 
> s = "gmmscore -i %s -l %s -t %s -m %s -d %s -v %s -n %s -r %s" %
> (Input, List, modeltype, str(mixture), str(dimension), str(vfloor),
>  str(number), str(results))
> 
> subprocess.Popen([s])

Here you are trying to start a program named "gmmscore -i ..." with no
arguments.  That fails (unless you really have a program with that name.  ;-)

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


Re: popen question

2008-01-08 Thread Robert Latest
Marc 'BlackJack' Rintsch wrote:

> Both processes have to make their communication ends unbuffered or line
> buffered.

Yeah, I figured something like that.

> And do whatever is needed to output the numbers from ``slow``
> unbuffered or line buffered.

Hm, "slow" of course is just a little test program I wrote for this purpose. 
In reality I want to call another program whose behavior I can't influence 
(well, technically I could because it's open-source, but let's assume it to 
be a black box for now).

If 'slow' or some other program does buffered output, how come I can see 
its output line-by-line in the shell?

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


Re: Look for a string on a file and get its line number

2008-01-08 Thread Martin Marcher
Jeroen Ruigrok van der Werven wrote:

> -On [20080108 09:21], Horacius ReX ([EMAIL PROTECTED]) wrote:
>>I have to search for a string on a big file. Once this string is
>>found, I would need to get the number of the line in which the string
>>is located on the file. Do you know how if this is possible to do in
>>python ?
> 
> (Assuming ASCII, otherwise check out codecs.open().)
> 
> big_file = open('bigfile.txt', 'r')
> 
> line_nr = 0
> for line in big_file:
> line_nr += 1
> has_match = line.find('my-string')
> if has_match > 0:
> print 'Found in line %d' % (line_nr)
> 
> Something to this effect.

apart from that look at the linecache module. If it's a big file it could
help you with subsequent access to the line in question

hth
martin

-- 
http://noneisyours.marcher.name
http://feeds.feedburner.com/NoneIsYours

You are not free to read this message,
by doing so, you have violated my licence
and are required to urinate publicly. Thank you.

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


Re: use fileinput to read a specific line

2008-01-08 Thread Martin Marcher
jo3c wrote:

> i need to read line 4 from a header file

http://docs.python.org/lib/module-linecache.html

~/2delete $ cat data.txt
L1
L2
L3
L4

~/2delete $ python
Python 2.5.1 (r251:54863, May  2 2007, 16:56:35)
[GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import linecache
>>> linecache.getline("data.txt", 2)
'L2\n'
>>> linecache.getline("data.txt", 5)
''
>>> linecache.getline("data.txt", 1)
'L1\n'
>>>


-- 
http://noneisyours.marcher.name
http://feeds.feedburner.com/NoneIsYours

You are not free to read this message,
by doing so, you have violated my licence
and are required to urinate publicly. Thank you.

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


Re: popen question

2008-01-08 Thread Robert Latest
Hrvoje Niksic wrote:

> stdio uses different buffering strategies depending on the output
> type.  When the output is a TTY, line buffering is used; when the
> output goes to a pipe or file, it is fully buffered.

Makes sense.

> If you see lines one by one, you are in luck, and you can fix things
> on the Python level simply by avoiding buffering in popen.  If not,
> you will need to resort to more advanced hackery (e.g. fixing stdio
> using LD_PRELOAD).

Do I really? After all, the shell itself doesn't hack stdio, does it?
Anyway, I'm taking this over to comp.unix.programmer since it really isn't a 
python problem.

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


Re: popen question

2008-01-08 Thread Hrvoje Niksic
Robert Latest <[EMAIL PROTECTED]> writes:

> If 'slow' or some other program does buffered output, how come I can
> see its output line-by-line in the shell?

stdio uses different buffering strategies depending on the output
type.  When the output is a TTY, line buffering is used; when the
output goes to a pipe or file, it is fully buffered.

> In reality I want to call another program whose behavior I can't
> influence (well, technically I could because it's open-source, but
> let's assume it to be a black box for now).

To test whether your black box buffers output to pipe, simply start it
like this:

$ ./slow | cat

If you see lines one by one, you are in luck, and you can fix things
on the Python level simply by avoiding buffering in popen.  If not,
you will need to resort to more advanced hackery (e.g. fixing stdio
using LD_PRELOAD).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: use fileinput to read a specific line

2008-01-08 Thread Fredrik Lundh
Martin Marcher wrote:

>> i need to read line 4 from a header file
> 
> http://docs.python.org/lib/module-linecache.html

I guess you missed the "using linecache will crash my computer due to 
memory loading, because i am working on 2000 files each is 8mb" part.



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


Paid subscription Python magazines

2008-01-08 Thread Jon Harrop

Are there any Python magazines that you can pay to subscribe to? (either
paper or on-line).

-- 
Dr Jon D Harrop, Flying Frog Consultancy Ltd.
http://www.ffconsultancy.com/products/?u
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: Look for a string on a file and get its line number

2008-01-08 Thread Ryan Ginstrom
> On Behalf Of Horacius ReX
> I have to search for a string on a big file. Once this string 
> is found, I would need to get the number of the line in which 
> the string is located on the file. Do you know how if this is 
> possible to do in python ?

This should be reasonable:

>>> for num, line in enumerate(open("/python25/readme.txt")):
if "Guido" in line:
print "Found Guido on line", num
break


Found Guido on line 1296
>>>

Regards,
Ryan Ginstrom

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


Re: Paid subscription Python magazines

2008-01-08 Thread Francesco Guerrieri
On Jan 8, 2008 11:17 AM, Jon Harrop <[EMAIL PROTECTED]> wrote:
>
> Are there any Python magazines that you can pay to subscribe to? (either
> paper or on-line).
>

Python Magazine comes to mind

www.pythonmagazine.com

I am subscribed and find it very good.

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


COM server and EXE

2008-01-08 Thread Teja
Hi All,

I have a Python COM server. I need to deploy it on various sytems.
When I run the COM server from
python its showing an output " Registered : sample.lib"

If I try to use the COM obj from a VB client like:

obj = CreateObject("sample.lib")

Its working fine without any errors

Now I am trying to convert this COM server to an exe through py2exe
and after I run the exe, I am
getting the same output " Registered : sample.lib"

But If I try to use the COM obj from a VB client like

obj = CreateObject("sample.lib")

A console pops up saying " Registered : sample.lib" and VB application
hangs there.
Its throwing a VB error that "ActiveX object cannot be
created..etc etc"

Any suggestions please...

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


(SOLVED) Re: popen question

2008-01-08 Thread Robert Latest
pexpect is the solution. Seems to wrap quite a bit of dirty pseudo-tty 
hacking.

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


Re: Python's great, in a word

2008-01-08 Thread alain
On Jan 7, 6:27 pm, "Henry Chang" <[EMAIL PROTECTED]> wrote:
> What exactly does it mean "a bycycle for the mind"??
>
> (assuming s/bycycle/bicycle)

Sorry for my bad spelling.
The original quote from Steve Jobs reads "the computer is a bicycle
for the mind".
This is what i feel when programming in Python: a productivity boost
compared to pedestrians and an immense pleasure.

Alain





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


Re: Python's great, in a word

2008-01-08 Thread Fredrik Lundh
[EMAIL PROTECTED] wrote:

> Would you Python old-timers try to agree on a word or two that
> completes:
> 
> The best thing about Python is ___.
> 
> Please, no laundry lists, just a word or two. I'm thinking "fluid" or
> "grace" but I'm not sure I've done enough to choose.

"its pencil-like qualities"



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


Re: Passing contextual information when logging

2008-01-08 Thread Antoine Pitrou

Hi Vinay,

> I would welcome your views on whether the LoggerAdapter class is
> suitable for adding to the logging package in Python 2.6/3.0. Does it
> do what might reasonably be expected out of the box?

I think it's quite suited to the problem, yes.

One question : why does the exception() method call Logger.error() rather than
Logger.exception() ?

One suggestion : pass in a Logger object rather than a logger name to the
LoggerAdapter constructor. (this also means that users could stack LoggerAdapter
objects if they wanted to)

Thanks

Antoine.


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


Re: COM server and EXE

2008-01-08 Thread Teja
On Jan 8, 3:33 pm, Teja <[EMAIL PROTECTED]> wrote:
> Hi All,
>
> I have a Python COM server. I need to deploy it on various sytems.
> When I run the COM server from
> python its showing an output " Registered : sample.lib"
>
> If I try to use the COM obj from a VB client like:
>
> obj = CreateObject("sample.lib")
>
> Its working fine without any errors
>
> Now I am trying to convert this COM server to an exe through py2exe
> and after I run the exe, I am
> getting the same output " Registered : sample.lib"
>
> But If I try to use the COM obj from a VB client like
>
> obj = CreateObject("sample.lib")
>
> A console pops up saying " Registered : sample.lib" and VB application
> hangs there.
> Its throwing a VB error that "ActiveX object cannot be
> created..etc etc"
>
> Any suggestions please...
>
> Regards,
> Tejovathi

Here is my sample COM server and py2exe setup file

testCOM.py

import win32com.client
import os.path
import shutil
from win32api import Sleep
import string
import os
import sys
import pythoncom

class FirstEx:

_reg_clsid_ = "{A6DE9DF8-5EBF-48E6-889E-C71CB84CFF2C}"
pythoncom.frozen = 1
if hasattr(sys, 'importers'):
# In the py2exe-packed version, specify the module.class
# to use. In the python script version, python is able
# to figure it out itself.
_reg_class_spec_ = "__main__.FirstEx"
_reg_desc_ = "My first COM server"
_reg_progid_ = "SAMPLE.Lib"
_public_methods_ = ['init', 'Version']
_public_attrs_ = ['softspace', 'noCalls']
_readonly_attrs_ = ['noCalls']
_reg_clsctx_ = pythoncom.CLSCTX_LOCAL_SERVER

def __init__(self):
self.softspace = 1
self.noCalls = 0


def Version(self):
self.noCalls = self.noCalls + 1

# insert "softspace" number of spaces
return "Version: 0.0.1"


if __name__=='__main__':
import sys
if hasattr(sys, 'importers'):
# running as packed executable.
if '--register' in sys.argv[1:] or '--unregister' in
sys.argv[1:]:
# --register and --unregister work as usual
import win32com.server.register
win32com.server.register.UseCommandLine(FirstEx)
else:
# start the server.
from win32com.server import localserver
localserver.main()
else:
import win32com.server.register
win32com.server.register.UseCommandLine(FirstEx)

 Here is my setup file:

#Start here
from distutils.core import setup
import py2exe

setup(options = {"py2exe": {"compressed": 1,
  "optimize": 2,
  "ascii": 1,
  "bundle_files": 1}},
zipfile = None,
com_server = ["win32com.servers.interp"],
console = ["testCOM.py"])
#End here


Here is my VB code:

Sub subRoutine()
Dim connection As Object
Dim returnvalue1 As String
Dim returnvalue2 As String
Dim flag3 As Boolean

Set connection = CreateObject("SAMPLE.Lib")
returnvalue1 = connection.Version()
MsgBox (returnvalue1)
End Sub


The non exe version of the COM server ie. directlly running the
testCOM.py registers the library properly and

in the VB application, the message box displays the version as 0.0.1.

But, after I create the EXE file using the setup.py file and run it,
it registers the library.

When I run the VB application, it hangs at the line

Set connection = CreateObject("SAMPLE.Lib")

and displays. " ACTIVEX cannot create the object"

Any suggestions please


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


Re: Open a List of Files

2008-01-08 Thread Fredrik Lundh
BJ Swope wrote:

> given a list such as
> 
> ['messages', 'recipients', 'viruses']
> 
> how would I iterate over the list and use the values as variables and 
> open the variable names a files?
> 
> I tried
> 
> for outfile in ['messages', 'recipients', 'viruses']:
> filename = os.path.join(Host_Path, outfile)
> outfile = open(filename, 'w')
> 
> But it's not working.

the code looks ok.  please define "not working".



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


Re: Paid subscription Python magazines

2008-01-08 Thread [EMAIL PROTECTED]
On Jan 8, 6:17 pm, Jon Harrop <[EMAIL PROTECTED]> wrote:
> Are there any Python magazines that you can pay to subscribe to? (either
> paper or on-line).

The Python Papers (www.pythonpapers.org) is a free e-journal,
including industry and academic articles.

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


Want a strange XML RPC server

2008-01-08 Thread Laszlo Nagy

  Hi,

I would like to have a strage XML RPC server. It should use one main 
thread for all connections.

I have some code like this (using a custom RPC server class):


server_address = (LISTEN_HOST, LISTEN_PORT) # (address, port)
server = mess.SecureXMLRPCServer.SecureXMLRPCServer(
server_address,
RequestHandler,
KEYFILE,CERTFILE,
allow_none=True,
logger = 
servicelog.getLogger('SecureXMLRPCServer',filename=LOGFILENAME),
logRequests=False,
stop_requested = stop_requested
)
rpcserver = RPCServer() # Object containing public RPC methods.
server.register_instance(rpcserver)

It works perfectly.

Now here is the tricky part. I would like to send back events. It is 
implemented by an RPC callback:

#1. client calls server.get_event()
#2. server waits until the event happens (or until a given timeout)
#3. server returns the event (if any)

The clients are running on multiple threads, and the idea is that any 
client can send an event by calling server.send_event(event).

That event will be returned to another client by the server. Since the 
clients are blocking (waiting for the RPC call to return), events will 
go from one client to another immediatelly (through the rpc server). 
This goes through different kinds of proxies, and can be used from 
different programming languages (Python and PHP clients, in my case...)

The problem is that in #2, waiting for the event to happen inside the 
RPC server's handler method will block all other connections to the RPC 
server.

Preferred solution: The get_event() method should run in a different 
thread inside the server, and return the event to its xmlrpc client from 
that thread. However, all other methods should use one main thread. I 
would like to implement this as a decorator like:


class RPCServer(object):
"""Object containing public RPC methods."""
def method1(self,arg1):
   .
def method2(self,arg1):
   .
def method3(self,arg1):
   .
  
@nonblocking
def get_event1(self):
try:
# Wait for 10 seconds until an event is available.
return self.asinharvester.queued_events1.get(True,10)
except Queue.Empty:
return None # Indicates that there was no queued event.
 
@nonblocking
def get_event2(self):
try:
# Wait for 10 seconds until an event is available.
return self.asinharvester.queued_events2.get(True,10)
except Queue.Empty:
return None # Indicates that there was no queued event.


Is this possible? I have no idea how to write this "nonblocking" decorator.

Thanks,

   Laszlo

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


Re: use fileinput to read a specific line

2008-01-08 Thread Fredrik Lundh
jo3c wrote:

> hi everybody
> im a newbie in python
> i need to read line 4 from a header file
> using linecache will crash my computer due to memory loading, because
> i am working on 2000 files each is 8mb
> 
> fileinput don't load the file into memory first
> how do i use fileinput module to read a specific line from a file?
> 
> for line in fileinput.Fileinput('sample.txt')
> 

I could have sworn that I posted working code (including an explanation 
why linecache wouldn't work) the last time you asked about this...  yes, 
here it is again:

 > i have a 2000 files with header and data
 > i need to get the date information from the header
 > then insert it into my database
 > i am doing it in batch so i use glob.glob('/mydata/*/*/*.txt')
 > to get the date on line 4 in the txt file i use
 > linecache.getline('/mydata/myfile.txt/, 4)
 >
 > but if i use
 > linecache.getline('glob.glob('/mydata/*/*/*.txt', 4) won't work

glob.glob returns a list of filenames, so you need to call getline once 
for each file in the list.

but using linecache is absolutely the wrong tool for this; it's designed 
for *repeated* access to arbitrary lines in a file, so it keeps all the
data in memory.  that is, all the lines, for all 2000 files.

if the files are small, and you want to keep the code short, it's easier 
to just grab the file's content and using indexing on the resulting list:

 for filename in glob.glob('/mydata/*/*/*.txt'):
 line = list(open(filename))[4-1]
 ... do something with line ...

(note that line numbers usually start with 1, but Python's list indexing 
starts at 0).

if the files might be large, use something like this instead:

 for filename in glob.glob('/mydata/*/*/*.txt'):
 f = open(filename)
 # skip first three lines
 f.readline(); f.readline(); f.readline()
 # grab the line we want
 line = f.readline()
 ... do something with line ...



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


Re: Open a List of Files

2008-01-08 Thread BJ Swope
On Jan 8, 2008 6:03 AM, Fredrik Lundh <[EMAIL PROTECTED]> wrote:

> BJ Swope wrote:
>
> > given a list such as
> >
> > ['messages', 'recipients', 'viruses']
> >
> > how would I iterate over the list and use the values as variables and
> > open the variable names a files?
> >
> > I tried
> >
> > for outfile in ['messages', 'recipients', 'viruses']:
> > filename = os.path.join(Host_Path, outfile)
> > outfile = open(filename, 'w')
> >
> > But it's not working.
>
> the code looks ok.  please define "not working".
>
> 
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>

Yep, defining "not working" is always helpful! :)

I want to have all 3 files open at the same time.  I will write to each of
the files later in my script but just the last file is open for writing.
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Open a List of Files

2008-01-08 Thread John Machin
On Jan 8, 10:03 pm, Fredrik Lundh <[EMAIL PROTECTED]> wrote:
> BJ Swope wrote:
> > given a list such as
>
> > ['messages', 'recipients', 'viruses']
>
> > how would I iterate over the list and use the values as variables and
> > open the variable names a files?
>
> > I tried
>
> > for outfile in ['messages', 'recipients', 'viruses']:
> > filename = os.path.join(Host_Path, outfile)
> > outfile = open(filename, 'w')
>
> > But it's not working.
>
> the code looks ok.  please define "not working".
>

To me, it looks bad. He's rebinding "outfile" inside the loop, which
is not good style, makes the reader slow down, back up, read the code
again ... however this doesn't stop this small code fragment from
opening the 3 files for write access -- assuming an import, and
suitable contents for "Host_Path".
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: popen question

2008-01-08 Thread Hrvoje Niksic
Robert Latest <[EMAIL PROTECTED]> writes:

>> If you see lines one by one, you are in luck, and you can fix things
>> on the Python level simply by avoiding buffering in popen.  If not,
>> you will need to resort to more advanced hackery (e.g. fixing stdio
>> using LD_PRELOAD).
>
> Do I really? After all, the shell itself doesn't hack stdio, does
> it?

Have you tried the "./slow | cat" test?  It's not about the shell
doing anything special, it's about slow's stdio choosing buffering
"appropriate" for the output device.  The hackery I referred to would
be necessary to force slow's stdio to use line buffering over
file/pipe output simply because there is no documented way to do that
(that I know of).

> Anyway, I'm taking this over to comp.unix.programmer since it really
> isn't a python problem.

It's still an often-encountered problem, so I believe a summary of the
solution(s) would be appreciated.
-- 
http://mail.python.org/mailman/listinfo/python-list


=?ISO-8859-1?Q?Intranet_Project_-_Rad_Or_Waterfall??=

2008-01-08 Thread bs866806
I have often used the analogy of building a bridge to explain to
business colleagues the difference between Rapid Application
Development (RAD) and Waterfall.

Let's say that we are in the middle ages and the Mayor of Kingston-
upon-Thames is evaluating whether or not to build a bridge over the
river to the north side, to replace the current ferry. The whole area
has been growing rapidly and a bridge at Kingston should give his town
a lead against competing local towns like Ham and Richmond (who also
have their own ferries).

However, building a bridge presents problems. Firstly, the bedrock
north and south of the river are very different. Secondly, the river
is still tidal at this point and its path continues to vary across the
floodplain. Finally - and perhaps most importantly - there is no
guarantee that the projected growth in cross-river traffic will indeed
materialise - or that people will wish to cross at this precise point,
rather than further up, or down, river. A new bridge could prove an
expensive white elephant and divert much-needed town resources away
from other projects. The increased local taxes required could also
scare the very businesses he is hoping to attract away to other local
towns.

Option 1 - Waterfall

Waterfall, as a methodology, is all about building reliable systems.
At each stage of the lifecycle, the results are correct. The Mayor's
engineer believes that - when building a bridge - the result needs to
be safe, sound and capable of lasting for decades. He recommends a
design phase, which includes thoroughly testing the bedrock by driving
piles and developing ways to limit the future variance of the river's
course. During the build phase, the bridge would be tested to ensure
it can take the loads that will be placed upon it and to deal with
high winds or flood conditions. The engineer confirms that each stage
would only start once the previous stage had been proved correct
beyond reasonable doubt. The stone bridge will take five whole years
to build (with a high upfront cost commitment). If the project were
ever stopped, the value tied up in phases to date would be lost. The
engineer reminds the Mayor that a collapsed bridge would not help his
place in history!

Option 2 - RAD

RAD, as a methodology is all about building relevant systems. The
argument runs that it is better to be there quickly with 80% of the
functionality in 20% of the time, so as to take full advantage of the
business opportunity. The Mayor's political advisors recommend the RAD
option; to lay a pontoon bridge first alongside the existing ferry.
This can be achieved in just three months, using a series of boats
with a makeshift road surface and swing bridge lock for river vessels
to navigate. The pontoon bridge allows the business model to be tested
very quickly; If the expected benefits materialise, then further
iterations of the bridge can be constructed later on. Sounds good, but
of course (overall) the costs will be higher than waterfall if a full,
stone bridge is ultimately required. In the meantime, if the river
changes course, or floods impact the area, then the pontoon bridge
will be washed away. His chief advisor reminds him that a bridge five
years from now would not help his re-election prospects two years
hence!

The Mayor's selected option

Hmm. Interesting, isn't it. Not a clear-cut decision. There are good
arguments for either approach. The Mayor's decision will ultimately
depend on (a) how sure he is of his own vision, (b) his financial and
time constraints and (c) how changeable these factors are likely to be
over time. In short, he has a trade-off decision of relevance vs.
reliability.

Turning the analogy onto Intranet Projects

In chapter 16 of my Intranet Portal Guide, I explore these concepts in
a bit more depth.However - put simply - the answer for you will depend
largely on how sure you are of your vision, the support of
stakeholders, the availability of resources and the degree of change
in your organisation and it's requirements.

If you are operating in a stable business environment and are well
funded and supported, then waterfall offers real benefits. You could
establish an Intranet Portal that is well founded, scalable and
secure. If not, then RAD could offer you the means to make some
progress now at low cost and use the results of your early work to
build a stronger case for future investment. It also allows you to
vary the approach - or begin again - should circumstances or
requirements change.

Most Intranet evangelists will find themselves perhaps in a mixed
situation, where there is support and funding but there is also the
risk of rapid changes to the underlying business environment and
requirements. Here, I would recommend a mixed approach: Use a
waterfall project to establish the underlying portal infrastructure
(as this platform will be the bedrock on which you will build and
needs to stand the test of time). Then use a RAD method to build the
content and applications 

Re: Look for a string on a file and get its line number

2008-01-08 Thread Jeroen Ruigrok van der Werven
-On [20080108 12:59], Wildemar Wildenburger ([EMAIL PROTECTED]) wrote:
>Style note:
>May I suggest enumerate (I find the explicit counting somewhat clunky) 
>and maybe turning it into a generator (I like generators):

Sure, I still have a lot to discover myself with Python.

I'll study your examples, thanks. :)

-- 
Jeroen Ruigrok van der Werven  / asmodai
イェルーン ラウフロック ヴァン デル ウェルヴェン
http://www.in-nomine.org/ | http://www.rangaku.org/
A conclusion is simply the place where you got tired of thinking...
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Open a List of Files

2008-01-08 Thread Fredrik Lundh
BJ Swope wrote:

> the code looks ok.  please define "not working".
> 
> Yep, defining "not working" is always helpful! :)
> 
> I want to have all 3 files open at the same time.  I will write to each 
> of the files later in my script but just the last file is open for writing.

to keep more than one file open, you need more than one variable, or a 
variable that can hold more than one object.

if the number of files may vary, put the file objects in a list.  if the 
number of files is constant, you might as well just use three variables 
and call open three times; e.g.

   def getfilename(name):
 return os.path.join(Host_Path, name)

   messages_file = open(getfilename("messages"), "w")
   recipients_file = open(getfilename("recipients"), "w")
   viruses_file = open(getfilename("viruses"), "w")



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


Re: Open a List of Files

2008-01-08 Thread Neil Cerutti
On Jan 8, 2008 6:54 AM, BJ Swope <[EMAIL PROTECTED]> wrote:
> > > given a list such as
> > >
> > > ['messages', 'recipients', 'viruses']
> > >
> > > how would I iterate over the list and use the values as variables and
> > > open the variable names a files?
> > >
> > > I tried
> > >
> > > for outfile in ['messages', 'recipients', 'viruses']:
> > > filename = os.path.join(Host_Path, outfile)
> > > outfile = open(filename, 'w')
> > >
> > > But it's not working.
>
> Yep, defining "not working" is always helpful! :)
>
>  I want to have all 3 files open at the same time.  I will write to each of
> the files later in my script but just the last file is open for writing.

Your code successfully opened them all, but kept a reference only to
the last one.

Try something like:

outfiles = [open(os.path.join(Host_Path, fname), 'w') for fname in fnames]

-- 
Neil Cerutti <[EMAIL PROTECTED]>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Open a List of Files

2008-01-08 Thread Martin Marcher
BJ Swope wrote:

> On Jan 8, 2008 6:03 AM, Fredrik Lundh <[EMAIL PROTECTED]> wrote:
> 
>> BJ Swope wrote:
>>
>> > given a list such as
>> >
>> > ['messages', 'recipients', 'viruses']
>> >
>> > how would I iterate over the list and use the values as variables and
>> > open the variable names a files?
>> >
>> > I tried
>> >
>> > for outfile in ['messages', 'recipients', 'viruses']:
>> > filename = os.path.join(Host_Path, outfile)
>> > outfile = open(filename, 'w')

files = dict()
l = ['messages', 'recipients', 'viruses']
for f in l:
files[f] = open(s.path.join(Host_Path, outfile), "w")

files["messages].write("a string")

hth
martin

PS: Code is untested

-- 
http://noneisyours.marcher.name
http://feeds.feedburner.com/NoneIsYours

You are not free to read this message,
by doing so, you have violated my licence
and are required to urinate publicly. Thank you.

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


Re: Look for a string on a file and get its line number

2008-01-08 Thread Wildemar Wildenburger
Jeroen Ruigrok van der Werven wrote:
> line_nr = 0
> for line in big_file:
> line_nr += 1
> has_match = line.find('my-string')
> if has_match > 0:
> print 'Found in line %d' % (line_nr)
> 
Style note:
May I suggest enumerate (I find the explicit counting somewhat clunky) 
and maybe turning it into a generator (I like generators):

def lines(big_file, pattern="my string"):
 for n, line in enumerate(big_file):
 if pattern in line:
 print 'Found in line %d' % (n)
 yield n

or for direct use, how about a simple list comprehension:

lines = [n for (n, line) in enumerate(big_file) if "my string" in line]

(If you're just going to iterate over the result, that is you do not 
need indexing, replace the brackets with parenthesis. That way you get a 
generator and don't have to build a complete list. This is especially 
useful if you expect many hits.)

Just a note.

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


Re: Open a List of Files

2008-01-08 Thread Chris
On Jan 8, 1:03 pm, Fredrik Lundh <[EMAIL PROTECTED]> wrote:
> BJ Swope wrote:
> > given a list such as
>
> > ['messages', 'recipients', 'viruses']
>
> > how would I iterate over the list and use the values as variables and
> > open the variable names a files?
>
> > I tried
>
> > for outfile in ['messages', 'recipients', 'viruses']:
> > filename = os.path.join(Host_Path, outfile)
> > outfile = open(filename, 'w')
>
> > But it's not working.
>
> the code looks ok.  please define "not working".
>
> 

Bad coding style in that one.  Do you have Write permissions to that
'Host_path' ?

import os, sys

FILELIST = ['messages', 'recipients', 'viruses']
HOST_PATH = os.getcwd()  # Or whatever path you are using

if not os.access(HOST_PATH, os.W_OK):
sys.exit('Unable to write to path specified.')

for file in FILELIST:
output_file = open(os.path.join(HOST_PATH, file), 'wb')
do_something_with_file()


A better definition of not working would be appreciated, Tracebacks if
you have.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Open a List of Files

2008-01-08 Thread Hrvoje Niksic
Fredrik Lundh <[EMAIL PROTECTED]> writes:

> BJ Swope wrote:
>
>> the code looks ok.  please define "not working".
>>
>> Yep, defining "not working" is always helpful! :)
>>
>> I want to have all 3 files open at the same time.  I will write to
>> each of the files later in my script but just the last file is open
>> for writing.
>
> to keep more than one file open, you need more than one variable, or a
> variable that can hold more than one object.
>
> if the number of files may vary, put the file objects in a list.

Or in a dict:

open_files = {}
for fn in ['messages', 'recipients', 'viruses']:
open_files[fn] = open(getfilename(fn), 'w')

# open_files['messages'] is the open file 'messages' etc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: use fileinput to read a specific line

2008-01-08 Thread Steven D'Aprano
On Mon, 07 Jan 2008 22:16:56 -0800, Russ P. wrote:

> One second thought, I wonder if the reference counting mechanism would
> be "smart" enough to automatically close the previous file on each
> iteration of the outer loop. If so, the files don't need to be
> explicitly closed.

Python guarantees[1] that files will be closed, but doesn't specify when 
they will be closed. I understand that Jython doesn't automatically close 
files until the program terminates, so even if you could rely on the ref 
counter to close the files in CPython, it won't be safe to do so in 
Jython. I don't know about IronPython or PyPy or the semi-mythical Parrot.

Given how little effort it is to explicitly close the files yourself, I 
don't see any reason to not close them, rather than relying on an 
implementation-dependent feature.



[1] Guarantee void under any circumstance that prevents files from being 
closed.

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


Re: Look for a string on a file and get its line number

2008-01-08 Thread Tim Chase
>> I have to search for a string on a big file. Once this string 
>> is found, I would need to get the number of the line in which 
>> the string is located on the file. Do you know how if this is 
>> possible to do in python ?
> 
> This should be reasonable:
> 
 for num, line in enumerate(open("/python25/readme.txt")):
>   if "Guido" in line:
>   print "Found Guido on line", num
>   break
> 
>   
> Found Guido on line 1296

Just a small caveat here:  enumerate() is zero-based, so you may
actually want add one to the resulting number:

  s = "Guido"
  for num, line in enumerate(open("file.txt")):
if s in line:
  print "Found %s on line %i" % (s, num + 1)
  break # optionally stop looking

Or one could use a tool made for the job:

  grep -n Guido file.txt

or if you only want the first match:

  sed -n '/Guido/{=;p;q}' file.txt

-tkc



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


Re: use fileinput to read a specific line

2008-01-08 Thread Scott David Daniels
Russ P. wrote:
> On Jan 7, 9:41 pm, Dennis Lee Bieber <[EMAIL PROTECTED]> wrote:
>> Given that the OP is talking 2000 files to be processed, I think I'd
>> recommend explicit open() and close() calls to avoid having lots of I/O
>> structures floating around...
>>
[effectively]
>> for fid in file_list:
>> fin = open(fid)
>> for cnt in xrange(4):
>> ln = fin.readline()
>> fin.close()
> One second thought, I wonder if the reference counting mechanism would
> be "smart" enough to automatically close the previous file on each
> iteration of the outer loop. If so, the files don't need to be
> explicitly closed.

I _hate_ relying on that, but context managers mean you don't have to.
There are good reasons to close as early as you can.  For example,
readers of files from zip files will eventually either be slower or
not work until the other readers close.

Here is what I imagine you want (2.5 or better):

 from __future__ import with_statement

 def pairing(names, position):
 for filename in names:
 with open(filename) as f:
 for n, line in enumerate(f):
 if n == position:
 break
 else:
 line = None  # indicate a short file
 yield filename, line
 ...
 for name, line in pairing(glob.glob('*.txt'), 3):
  do_something(name, line)

--Scott David Daniels
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Hot clips,great clips:

2008-01-08 Thread [EMAIL PROTECTED]
Hot clips,great clips:
http://groups.google.com/group/greatclips/web/great-clips
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: use fileinput to read a specific line

2008-01-08 Thread Fredrik Lundh
Steven D'Aprano wrote:

> Python guarantees[1] that files will be closed, but doesn't specify when 
> they will be closed. I understand that Jython doesn't automatically close 
> files until the program terminates, so even if you could rely on the ref 
> counter to close the files in CPython, it won't be safe to do so in 
> Jython.

 From what I can tell, Java's GC automatically closes file streams, so 
Jython will behave pretty much like CPython in most cases.  I sure 
haven't been able to make Jython run out by file handles by opening tons 
of files and discarding the file objects without closing them.  Has anyone?



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


Re: Passing contextual information when logging

2008-01-08 Thread Vinay Sajip
On 8 Jan, 09:46, Antoine Pitrou <[EMAIL PROTECTED]> wrote:
> One question : why does the exception() method call Logger.error() rather than
> Logger.exception() ?

exception() is a convenience method which adds the keyword argument
exc_info=1 to append traceback information to the log. Both
exception() and error() log at the ERROR level.

> One suggestion : pass in a Logger object rather than a logger name to the
> LoggerAdapter constructor. (this also means that users could stack 
> LoggerAdapter
> objects if they wanted to)

Done, see http://dpaste.com/30253/

Regards,

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


Re: windows service

2008-01-08 Thread kyosohma
On Jan 7, 6:42 pm, Michael Chesterton <[EMAIL PROTECTED]> wrote:
> I'm trying to get a program that uses M2Crypto ThreadingSSLServer to
> run in windows as a service. I have a few problem, it doesn't listen
> on its port and I don't know how to debug it.
>
> I used the pipeservice example as a framework to get it running as a
> service
>
>  def SvcDoRun(self):
>  # Write an event log record - in debug mode we will also
>  # see this message printed.
>  servicemanager.LogMsg(
>  servicemanager.EVENTLOG_INFORMATION_TYPE,
>  servicemanager.PYS_SERVICE_STARTED,
>  (self._svc_name_, '')
>  )
>
>  daemonserver = do_daemon()
>  while 1:
>  daemonserver.handle_request()
>
> I think I need a way to break out of that while loop when a service
> stop is sent, but not knowing what happening at that point I'm not
> sure how. It's not even listening on its port.
>
> daemonserver is
>
>  daemonserver = SSL.ThreadingSSLServer((host_ip_addr, int
> (host_port_num)), TestRequestHandler, ctx)
>
> any help?
>
> --
> Michael Chestertonhttp://chesterton.id.au/blog/http://barrang.com.au/
>
> --
> Michael Chestertonhttp://chesterton.id.au/blog/http://barrang.com.au/

Before you get it going as a service, test it as just a regular Python
script. I've created local servers using CherryPy before and been able
to test them. I recommend you do the same with yours before changing
it to a service.

If you have a firewall installed (which you should), you may need to
allow your program access through it. I've occasionally had to allow
localhost with some of the more stringent firewalls.

I found this post on creating a Windows Service for Windows 2000,
which can probably be modified for XP:
http://agiletesting.blogspot.com/2005/09/running-python-script-as-windows.html

There's also this one: 
http://essiene.blogspot.com/2005/04/python-windows-services.html

They both sound different from the way you did it, but maybe I
misunderstood.

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


Re: use fileinput to read a specific line

2008-01-08 Thread Martin Marcher
Fredrik Lundh wrote:

> Martin Marcher wrote:
> 
>>> i need to read line 4 from a header file
>> 
>> http://docs.python.org/lib/module-linecache.html
> 
> I guess you missed the "using linecache will crash my computer due to
> memory loading, because i am working on 2000 files each is 8mb" part.

oops sorry indeed

still the enumerate version seems fine:
>>> for no, line in enumerate(file("data.txt", "r")):
... print no, line
...

someone posted this already i think (or was it another thread?)

-- 
http://noneisyours.marcher.name
http://feeds.feedburner.com/NoneIsYours

You are not free to read this message,
by doing so, you have violated my licence
and are required to urinate publicly. Thank you.

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


Re: use fileinput to read a specific line

2008-01-08 Thread Hrvoje Niksic
Fredrik Lundh <[EMAIL PROTECTED]> writes:

> From what I can tell, Java's GC automatically closes file streams,
> so Jython will behave pretty much like CPython in most cases.

The finalizer does close the reclaimed streams, but since it is
triggered by GC, you have to wait for GC to occur for the stream to
get closed.  That means that something like:

open('foo', 'w').write(some_contents)

may leave 'foo' empty until the next GC.  Fortunately this pattern is
much rarer than open('foo').read(), but both work equally well in
CPython, and will continue to work, despite many people's dislike for
them.  (For the record, I don't use them in production code, but
open(...).read() is great for throwaway scripts and one-liners.)

> I sure haven't been able to make Jython run out by file handles by
> opening tons of files and discarding the file objects without
> closing them.

Java's generational GC is supposed to be quick to reclaim recently
discarded objects.  That might lead to swift finalization of open
files similar to what CPython's reference counting does in practice.

It could also be that Jython internally allocates so many Java objects
that the GC is triggered frequently, again resulting in swift
reclamation of file objects.  It would be interesting to monitor (at
the OS level) the number of open files maintained by the process at
any given time during the execution of such a loop.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Look for a string on a file and get its line number

2008-01-08 Thread Horacius ReX
Hi, thanks for the help. Then I got running the following code;

#!/usr/bin/env python

import os, sys, re, string, array, linecache, math

nlach = 12532

lach_list = sys.argv[1]
lach_list_file = open(lach_list,"r")
lach_mol2 = sys.argv[2] # name of the lachand mol2 file
lach_mol2_file = open(lach_mol2,"r")
n_lach_read=int(sys.argv[3])

# Do the following for the total number of lachands

# 1. read the list with the ranked lachands
for i in range(1,n_lach_read+1):
line = lach_list_file.readline()
ll = string.split (line)
#print i, ll[0]
lach = int(ll[0])
# 2. for each lachand, print mol2 file
# 2a. find lachand header in lachand mol2 file (example; kanaka)
# and return line number
line_nr = 0
for line in lach_mol2_file:
line_nr += 1
has_match = line.find('kanaka')
if has_match >= 0:
print 'Found in line %d' % (line_nr)
# 2b. print on screen all the info for this lachand
#   (but first need to read natoms and nbonds info)
#go to line line_nr + 1
ltr=linecache.getline(lach_mol2, line_nr + 1)
ll=ltr.split()
#print ll[0],ll[1]
nat=int(ll[0])
nb=int(ll[1])
# total lines to print:
#   header, 8
#   at, na
#   b header, 1
#   n
#   lastheaders, 2
#   so; nat + nb + 11
ntotal_lines = nat + nb + 11
# now we go to the beginning of the lachand
# and print ntotal_lines
for j in range(0,ntotal_lines):
print linecache.getline(lach_mol2, line_nr - 1 
+ j )


which almost works. In the last "for j" loop, i expected to obtain an
output like:

sdsdsdsdsdsd
sdsdsfdgdgdgdg
hdfgdgdgdg

but instead of this, i get:

sdsdsdsdsdsd

sdsdsfdgdgdgdg

hdfgdgdgdg

and also the program is very slow. Do you know how could i solve
this ?

thanks

Tim Chase wrote:
> >> I have to search for a string on a big file. Once this string
> >> is found, I would need to get the number of the line in which
> >> the string is located on the file. Do you know how if this is
> >> possible to do in python ?
> >
> > This should be reasonable:
> >
>  for num, line in enumerate(open("/python25/readme.txt")):
> > if "Guido" in line:
> > print "Found Guido on line", num
> > break
> >
> >
> > Found Guido on line 1296
>
> Just a small caveat here:  enumerate() is zero-based, so you may
> actually want add one to the resulting number:
>
>   s = "Guido"
>   for num, line in enumerate(open("file.txt")):
> if s in line:
>   print "Found %s on line %i" % (s, num + 1)
>   break # optionally stop looking
>
> Or one could use a tool made for the job:
>
>   grep -n Guido file.txt
>
> or if you only want the first match:
>
>   sed -n '/Guido/{=;p;q}' file.txt
>
> -tkc
-- 
http://mail.python.org/mailman/listinfo/python-list


Converting a bidimensional list in a bidimensional array

2008-01-08 Thread Santiago Romero

 Hi :)

 First of all, I must apologize for my poor english :)

 I'm starting with python and pygame and for testing (and learning)
purposes I wrote an small "Map Editor" for a small game project I'm
going to start next month.

 The tilemap editor is working fine, but reading Guido's Van Rossum
PYTHON TUTORIAL I found that my game map is "wasting" memory by using
about 16 bytes for each item in it, because every item in a python
list takes 16 bytes in memory. In the same tutorial, I found
references to the "array()" function of the "array" module.

 I'm trying to change my current working source code so that it works
with an array instead of using a list, but I'm not managing to do it.

 My tilemap is something like (think on 0=empty, 1=floor, 2=rock, and
so...):

[
[0 ,0, 0, 0, 0, 0, 0, 0 ,0],
[0 ,0, 0, 0, 0, 0, 0, 0 ,0],
[2 ,0, 0, 0, 0, 2, 2, 0 ,0],
(...)
[2 ,2, 0, 0, 2, 2, 2, 0 ,0],
[1 ,1, 1, 1, 1, 1, 1, 1 ,1],
]

 This is how I create the tilemap (and the clipboard, a copy of my
tilemap):

def __init__( self, bw, bh, tiles ):
  self.width, self.height = bw, bh
  self.tilemap = []
  self.clipboard = []
  (...)
  for i in range(bh):
 self.tilemap.append([0] * bw)
 self.clipboard.append([0] * bw)


 And that's how I'm using it (the functions I'm having trouble to
convert to use the array):

   #-
   def CopyToClipboard( self ):
  for j in range( self.height ):
 self.clipboard[j][:] = self.tilemap[j][:]

   #-
   def Draw( self, clear=1 ):
  screen = pygame.display.get_surface()
  if clear: self.Clear()

  for j in range(self.GetHeight()):
 for i in range(self.GetWidth()):
self.DrawBlock( i, j )

   #-
   def DrawBlock( self, x, y ):
  screen = pygame.display.get_surface()
  xd = (x * self.TileWidth()) + self.originx;
  yd = (y * self.TileHeight()) + self.originy;
  b = self.tilemap[y][x]
  self.tileset.tiles[b].Draw( screen, xd, yd )

   #-
   def ResizeWidth( self, new ):
  bw, bh = self.GetWidth(), self.GetHeight()

  if new > bw:
 for j in range(bh):
for i in range(new-bw):
   self.tilemap[j].append( 0 )
   self.clipboard[j].append( 0 )
 self.SetWidth( new )

  elif new < bw:
 for j in range(bh):
for i in range(bw-new):
   del self.tilemap[j][-1]
   del self.clipboard[j][-1]
 self.SetWidth( new )

   #-
   def ResizeHeight( self, new ):
  bw, bh = self.GetWidth(), self.GetHeight()

  if new > bh:
 for i in range(new-bh):
self.tilemap.append([0] * bw)
self.clipboard.append([0] * bw)
 self.SetHeight( new )

  elif new < bh:
 for i in range(1,bh-new):
 del self.tilemap[-1]
 self.SetHeight( new )



In fact, I'm even unable to create the array correctly:


 I've tried:

  self.tilemap = array('H', [])

  for i in range(bh):
 self.tilemap.append([0] * bw)

 and:

  for i in range(bh):

 for j in range(bw):
self.tilemap[i].append(0)


 But I receive errors like (either defining or using the array):

 b = self.tilemap[y][x]
TypeError: 'int' object is unsubscriptable

 or:

self.tilemap.append( [0] * bw )
TypeError: an integer is required



 So ... please ... any idea on how to convert my "python object" array
of lists to a bidimensional array and how to use it to index [y][x]
elements, or even resize it with the ResizeWidth() and Height()
functions?

 Thanks everybody.


PS: Please, think that I come from C/C++ so I still have some "C ways
of doing things" while there are better/faster ways to do the same in
Python. Feel free also to correct any "C-Style" programming way that
you can find in my source code above... :-)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Intranet Project - Rad Or Waterfall

2008-01-08 Thread GHUM
> Option 1 - Waterfall

I recommend to google "waterfall". First hit after those beatifull
pictures will be:

http://en.wikipedia.org/wiki/Waterfall_model

Within the first paragraph there is:

   """Ironically, Royce was actually presenting this model as an
example of a flawed, non-working model.(Royce 1970)"""


So I cannot fight the feeling of seeing the realisation of a xkcd-
strip when reading about waterfall models...

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


Re: list property fires get on append

2008-01-08 Thread Soviut
On Jan 6, 11:36 am, Carl Banks <[EMAIL PROTECTED]> wrote:
> On Sun, 06 Jan 2008 00:31:13 -0800, Soviut wrote:
> > I figured that an append would be treated as a set since I'm adding to
> > the list.  But what you say makes sense, although I can't say I'm happy
> > with the behaviour.  Is there any way I can get the append to fire a
> > set?  I'm thinking of properties from my C# background where i believe
> > that manipulation such this would be considered a set.
>
> You'd have to have to hook into the container object itself to detect the
> modification.  This might be pretty workable for you since it's an
> internal object.  Basically, instead of using a list, use a special list-
> like object that notifies it's owner when it changes.  Here's a simple
> example to point you in the right direction:
>
> class NotifierList(list):
>  def __init__(self,*args,**kwargs):
>  super(NotifierList,self).__init__(*args,**kwargs)
>  self.watchers = []
>  def add_watcher(self,watcher):
>  self.watchers.append(watcher)
>  def _notify_watchers(self):
>  for watcher in self.watchers:
>  watcher.object_changed(self)
>  def append(self,value):
>  super(NotifierList,self).append(value)
>  self._notify_watchers()
>  # override all other mutating calls, including __setitem__
>  # left as exercise
>
> class Hierarchy(object):
> def __init__(self):
> self.children = NotifierList()
> self.children.add_watcher(self)
> def object_changed(self,obj):
> print "self.children modified"
> # no need to make children a property then
> # unless you want to trap rebinding it to new object also
>
> A couple other minor suggestions:
>
> print is a statement, not a function.  You should write
>
> print "GETTING"
>
> not
>
> print("GETTING")
>
> The latter works, but it will cease to work if you want to print more
> than one thing.  Note that print is scheduled to become a function in
> Python 3.0, but for now it's a statement.
>
> Based on the name of your class and typical usage, I'm guessing that you
> probably want _children to be an instance attribute rather than a class
> attribute, so I redid it that way, but .)
>
> P.S. Is calling a method called "firing" in C#?
>
> Carl Banks

I just want to thank you for the example.  I implemented the
NotifierList class and modified it to suite my project.  It works
great.  Thanks again.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: stupid/style/list question

2008-01-08 Thread Fredrik Lundh
Giampaolo Rodola' wrote:

> To flush a list it is better doing "del mylist[:]" or "mylist = []"?
> Is there a preferred way? If yes, why?

The latter creates a new list object, the former modifies an existing 
list in place.

The latter is shorter, reads better, and is probably a bit faster in 
most cases.

The former should be used when it's important to clear a specific list 
object (e.g. if there are multiple references to the list).



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


copy a numpy array

2008-01-08 Thread jimgardener
hi,
(i posted this to numpy discussion grp couple of days back ..but it
fails to appear..)since it is needed for my work i would appreciate if
anyone can help me with this question


i have two ndarrays of 1000 elements each and want to copy all
elements from srcarray to destarray

srcarray=numpy.array(  [3973334.8381791776,,382999.6748692277] )

arrsize=1000
destarray=zeros(arrsize)

i copied all items from src to dest by using
destarray[0:arrsize]=srcarray[0:arrsize]

i don't know if this is the right way to do the copying.
is there a better(efficient?) way ?
jim

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


stupid/style/list question

2008-01-08 Thread Giampaolo Rodola'
I was wondering...
To flush a list it is better doing "del mylist[:]" or "mylist = []"?
Is there a preferred way? If yes, why?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: stupid/style/list question

2008-01-08 Thread Tim Chase
> To flush a list it is better doing "del mylist[:]" or "mylist = []"?
> Is there a preferred way? If yes, why?

It depends on what you want.  The former modifies the list
in-place while the latter just reassigns the name "mylist" to
point to a new list within the local scope as demonstrated by this:

  def d1(mylist):
"Delete in place"
del mylist[:]

  def d2(mylist):
"Just reassign"
mylist = []

  for test in [d1,d2]:
input = [1,2,3]
print 'Before:', input
print test.__doc__
test(input)
print 'After:', input
print

As performance goes, you'd have to test it, but I suspect it's
not a glaring difference, and would suspect that the latter is a
bit faster.


-tkc


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


Re: Python's great, in a word

2008-01-08 Thread Carl Banks
On Jan 7, 6:29 pm, MRAB <[EMAIL PROTECTED]> wrote:
> On Jan 7, 5:40 pm, Martin Marcher <[EMAIL PROTECTED]> wrote:> [EMAIL 
> PROTECTED] wrote:
> > > The best thing about Python is ___.
>
> > it's pythonicness.
>
> I think it sounds better as "its pythonicity".

Mixing Greek and Latin suffixes usually works better than mixing Greek
and Germanic, doesn't it.


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


Re: I'm searching for Python style guidelines

2008-01-08 Thread MartinRinehart
That's a great list, grflanagan! Thanks.

I looked at each and copied to my disk either as a .txt (cut/paste
from the browser) for a page or less or as .html (view source, chop
off head and non-guideline stuff, save). This is the list plus PEP 8
minus the software. (No disrespect for the software, just sticking to
written standards.) Zope may be a substantial guideline, but it linked
to a page of Zope links, all of which were broken.

This CSV file is sorted by filesize on my disk. One presumes that a
relationship exists between size and extent of coverage. (Warning:
Wiki text could be as much as twice the size of non-wiki for the same
content.) The third column is empty (spacer between size and URL).

A quick look (thorough analysis still required) shows that OLPC and
PyPy are, indeed, extensive standards.

one-laptop-per-child.html (olpc),74.3,,http://wiki.laptop.org/go/
Python_Style_Guide
pypy.html,64.2,,http://codespeak.net/pypy/dist/pypy/doc/coding-
guide.html
pep-008.html,35.6,,http://www.python.org/dev/peps/pep-0008/
knight.html,33.7,,http://jaynes.colorado.edu/PythonGuidelines.html
pep-257.html,23.8,,http://www.python.org/dev/peps/pep-0257/
webware.html,23.4,,http://www.webwareforpython.org/Docs/
StyleGuidelines.html
twisted.html,23.3,,http://twistedmatrix.com/trac/browser/trunk/doc/
development/policy/co...
voice-code.html,17.9,,http://voicecode.iit.nrc.ca/VoiceCode/uploads/
codingGuidelines.html
fsl.html,15.0,,http://www-md.fsl.noaa.gov/eft/developer/
PythonCodingStandards.html
wx.html,14.6,,http://www.wxpython.org/codeguidelines.php
mnet.html,14.5,,http://mnet.sourceforge.net/coding_standards.html
michael-foord.html,14.2,,http://www.voidspace.org.uk/python/weblog/
arch_d7_2006_04_01.shtml#e296
bazaar.html,10.4,,http://doc.bazaar-vcs.org/bzr.dev/en/developer-guide/
HACKING.html#cod...
ipython.html,10.2,,http://ipython.scipy.org/moin/Developer_Zone/
Developer_Guidelines
barry-warsaw.html,6.2,,http://barry.warsaw.us/software/STYLEGUIDE.txt
django.html,5.6,,http://www.djangoproject.com/documentation/
contributing/#coding-style
chandler.txt,4.0,,http://chandlerproject.org/Projects/
ChandlerCodingStyleGuidelines
pyblosxom.txt,3.8,,http://pyblosxom.sourceforge.net/blog/static/
development#coding
freevo.txt,3.4,,http://jaynes.colorado.edu/PythonGuidelines.html
sql-object.txt,2.7,,http://www.sqlobject.org/DeveloperGuide.html#style-
guide
biopython.txt,2.5,,http://biopython.org/wiki/
Contributing#Coding_conventions
tracdev.txt,1.8,,http://trac.edgewall.org/wiki/TracDev/CodingStyle
docutils,1.8,,http://docutils.sourceforge.net/docs/dev/
policies.html#python-coding-...
moinmoin.txt,1.8,,http://moinmoin.wikiwikiweb.de/CodingStyle
cherrypy.txt,1.5,,http://www.cherrypy.org/wiki/CodeConventions
skeletonz-naming.txt,1.4,,http://orangoo.com/skeletonz/Developer_guide/
Naming_convention/
mercurial.txt,0.9,,http://www.selenic.com/mercurial/wiki/index.cgi/
Basic_Coding_Style
skeletonz-coding.txt,0.6,,http://orangoo.com/skeletonz/Developer_guide/
Coding_convention/
software-carpentry.txt,0.1,,http://www.swc.scipy.org/lec/style.html
zope.txt,0.0,,http://wiki.zope.org/zope3/CodingStyle
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: copy a numpy array

2008-01-08 Thread Francesco Guerrieri
On Jan 8, 2008 4:32 PM, jimgardener <[EMAIL PROTECTED]> wrote:
> hi,
> (i posted this to numpy discussion grp couple of days back ..but it
> fails to appear..)since it is needed for my work i would appreciate if
> anyone can help me with this question
>
>
> i have two ndarrays of 1000 elements each and want to copy all
> elements from srcarray to destarray
>
> srcarray=numpy.array(  [3973334.8381791776,,382999.6748692277] )
>
> arrsize=1000
> destarray=zeros(arrsize)
>
> i copied all items from src to dest by using
> destarray[0:arrsize]=srcarray[0:arrsize]
>
> i don't know if this is the right way to do the copying.
> is there a better(efficient?) way ?
> jim


If you want the array to share the data, just use
destarray = numpy.array(srcarray)

Otherwise you can set the copy flag to False:

destarray = numpy.array(srcarray,copy=False)

 bye,
Francesco
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: I'm searching for Python style guidelines

2008-01-08 Thread Martin Vilcans
On 1/7/08, Guilherme Polo <[EMAIL PROTECTED]> wrote:
> 2008/1/7, [EMAIL PROTECTED] <[EMAIL PROTECTED]>:
> > Anything written somewhere that's thorough? Any code body that should
> > serve as a reference?
>
> PEP 8
> http://www.python.org/dev/peps/pep-0008/

The problem with PEP 8 is that even code in the standard libraries
doesn't follow the recommendations regarding the naming of functions
for example. The recommendation is to_separate_words_with_underscore,
but some code uses lowerCamelCase instead.

I tended to dislike the underscore convention, but after forcing
myself to use it for a while I'm starting to appreciate its beauty.

-- 
[EMAIL PROTECTED]
http://www.librador.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: I'm searching for Python style guidelines

2008-01-08 Thread Colin J. Williams
Martin Vilcans wrote:
> On 1/7/08, Guilherme Polo <[EMAIL PROTECTED]> wrote:
>> 2008/1/7, [EMAIL PROTECTED] <[EMAIL PROTECTED]>:
>>> Anything written somewhere that's thorough? Any code body that should
>>> serve as a reference?
>> PEP 8
>> http://www.python.org/dev/peps/pep-0008/
> 
> The problem with PEP 8 is that even code in the standard libraries
> doesn't follow the recommendations regarding the naming of functions
> for example. The recommendation is to_separate_words_with_underscore,
> but some code uses lowerCamelCase instead.
> 
> I tended to dislike the underscore convention, but after forcing
> myself to use it for a while I'm starting to appreciate its beauty.

I've come to like lowerCamelCase and a 
tab of 2.

A tab of 4 wastes more space than is 
needed for the occasional heavy
indenting.

Colin W.

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


Re: I'm searching for Python style guidelines

2008-01-08 Thread Neil Cerutti
On Jan 8, 2008 12:35 PM, Martin Vilcans <[EMAIL PROTECTED]> wrote:
> On 1/7/08, Guilherme Polo <[EMAIL PROTECTED]> wrote:
> > 2008/1/7, [EMAIL PROTECTED] <[EMAIL PROTECTED]>:
> > > Anything written somewhere that's thorough? Any code body that should
> > > serve as a reference?
> >
> > PEP 8
> > http://www.python.org/dev/peps/pep-0008/
>
> The problem with PEP 8 is that even code in the standard libraries
> doesn't follow the recommendations regarding the naming of functions
> for example. The recommendation is to_separate_words_with_underscore,
> but some code uses lowerCamelCase instead.
>
> I tended to dislike the underscore convention, but after forcing
> myself to use it for a while I'm starting to appreciate its beauty.

Conventions get broken when there's a good reason, e.g., elegant
looking "deque" instead of clumsy looking "Deque".

-- 
Neil Cerutti <[EMAIL PROTECTED]>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: copy a numpy array

2008-01-08 Thread gsal
I am new to python and everything related to it, and it so happens
that I just went through the numpy tutorial last night, it is in

http://www.scipy.org/Tentative_NumPy_Tutorial

and the answer to your question is in section 3.7

Basically, if you want to make a (deep) copy of it:

destarray = srcarray.copy()

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


Python or PowerShell ?

2008-01-08 Thread [EMAIL PROTECTED]

I am all about using the right tool for the right purposes, which is
why I have started reading the GettingStarted guide to PowerShell.  I
am curious if any other pythoneers have ventured into the world of
PowerShell.  Mostly, I am interested in grabbing perspectives on the
differences noticed from those that have working experience with using
both.

I dug up one article from Google that talked about comparison but that
was about it.

http://www.simple-talk.com/sql/database-administration/comparing-python-and-powershell-dba-scripting-/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Pet Store

2008-01-08 Thread George Maggessy
Yeap. It is. I'm looking for something like that app. Smth that I
could base my future developments on.

On Jan 8, 1:47 am, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote:
> On Mon, 07 Jan 2008 22:21:53 -0800, George Maggessy wrote:
> > I'm an experience Java developer trying to learn Python. I just
> > finished the Python tutorial on python.org and I'm currently reading
> > the "Learning Python" book. However, if I could find something like a
> > simple web app with some best practices, such as those famous "Java
> > Pet Store" apps, I think that would help me to fill up some gaps in my
> > learning process. Does anybody know any app like that?
>
> Isn't that a web application using Java web frameworks?  So you are
> looking for a Python web framework with a "Pet Store" tutorial?
>
> Ciao,
> Marc 'BlackJack' Rintsch

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


Re: Open source English dictionary to use programmatically w/ python

2008-01-08 Thread dgoldsmith_89
On Jan 7, 3:50 pm, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote:
> On Jan 7, 5:10 pm, dgoldsmith_89 <[EMAIL PROTECTED]> wrote:
>
>
>
> > On Jan 7, 2:54 pm, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote:
>
> > > On Jan 7, 4:37 pm, dgoldsmith_89 <[EMAIL PROTECTED]> wrote:
>
> > > > Can anyone point me to a downloadable open source English dictionary
> > > > suitable for programmatic use with python: I'm programming a puzzle
> > > > generator, and I need to be able to generate more or less complete
> > > > lists of English words, alphabetized.  Thanks!  DG
>
> > >www.puzzlers.orghasnumerousword lists & dictionarys in text
> > > format that can be downloaded. I recommend you insert them into
> > > some form of database. I have most of them in an Access db and
> > > it's 95 MB. That's a worse case as I also have some value-added
> > > stuff, the OSPD alone would be a lot smaller.
>
> > > 
>
> > Sorry for my ignorance: I can query an Access DB w/ standard SQL
> > queries (and this is how I would access it w/ Python)?
>
> Yes, if you have the appropriate way to link to the DB.
> I use Windows and ODBC from Win32. I don't know what you
> would use on a Mac.
>
> As Paul McGuire said, you could easily do this with SqlLite3.
> Personnaly, I always use Access since my job requires it
> and I find it much more convenient. I often use Crosstab
> tables which I think SqlLite3 doesn't support. Typically,
> I'll write complex queries in Access and simple select SQL
> statements in Python to grab them.
>
> Here's my anagram locator. (the [signature] is an example
> of the value-added I mentioned).
>
> ##  I took a somewhat different approach. Instead of in a file,
> ##  I've got my word list (562456 words) in an MS-Access database.
> ##  And instead of calculating the signature on the fly, I did it
> ##  once and added the signature as a second field:
> ##
> ##  TABLE CONS_alpha_only_signature_unique
> ##  --
> ##  CONS   text  75
> ##  signature  text  26
> ##
> ##  The signature is a 26 character string where each character is
> ##  the count of occurences of the matching letter. Luckily, in
> ##  only a single case was there more than 9 occurences of any
> ##  given letter, which turned not to be a word but a series of
> ##  words concatenated so I just deleted it from the database
> ##  (lots of crap in the original word list I used).
> ##
> ##  Example:
> ##
> ##  CONS signature
> ##  aah  200100 # 'a' occurs twice & 'h' once
> ##  aahed2001100100
> ##  aahing   201111
> ##  aahs 2001001000
> ##  aaii 200020
> ##  aaker2000101001
> ##  aal  200100
> ##  aalborg  2111001001
> ##  aalesund
> 20011001011010
> ##
> ##  Any words with identical signatures must be anagrams.
> ##
> ##  Once this was been set up, I wrote a whole bunch of queries
> ##  to use this table. I use the normal Access drag and drop
> ##  design, but the SQL can be extracted from each, so I can
> ##  simply open the query from Python or I can grab the SQL
> ##  and build it inside the program. The example
> ##
> ##signatures_anagrams_select_signature
> ##
> ##  is hard coded for criteria 9 & 10 and should be cast inside
> ##  Python so the criteria can be changed dynamically.
> ##
> ##
> ##  QUERY signatures_anagrams_longest
> ##  -
> ##  SELECT   Len([CONS]) AS Expr1,
> ##   Count(Cons_alpha_only_signature_unique.CONS) AS
> CountOfCONS,
> ##   Cons_alpha_only_signature_unique.signature
> ##  FROM Cons_alpha_only_signature_unique
> ##  GROUP BY Len([CONS]),
> ##   Cons_alpha_only_signature_unique.signature
> ##  HAVING   (((Count(Cons_alpha_only_signature_unique.CONS))>1))
> ##  ORDER BY Len([CONS]) DESC ,
> ##   Count(Cons_alpha_only_signature_unique.CONS) DESC;
> ##
> ##  This is why I don't use SQLite3, must have crosstab queries.
> ##
> ##  QUERY signatures_anagram_summary
> ##  
> ##  TRANSFORM Count(signatures_anagrams_longest.signature) AS
> CountOfsignature
> ##  SELECTsignatures_anagrams_longest.Expr1 AS [length of word]
> ##  FROM  signatures_anagrams_longest
> ##  GROUP BY  signatures_anagrams_longest.Expr1
> ##  PIVOT signatures_anagrams_longest.CountOfCONS;
> ##
> ##
> ##  QUERY signatures_anagrams_select_signature
> ##  --
> ##  SELECT   Len([CONS]) AS Expr1,
> ##   Count(Cons_alpha_only_signature_unique.CONS) AS
> CountOfCONS,
> ##   Cons_alpha_only_signature_unique.signature
> ##  FROM Cons_alpha_only_signature_unique
> ##  GROUP BY Len([CONS]),
> ##   Cons_alpha_only_signature_unique.signature
> ##  HAVING   (((Len([CONS]))=9) AND
> ##((Count(Con

Re: COM server and EXE

2008-01-08 Thread Giles Brown
On 8 Jan, 11:04, Teja <[EMAIL PROTECTED]> wrote:
> On Jan 8, 3:33 pm, Teja <[EMAIL PROTECTED]> wrote:
>
>
>
> > Hi All,
>
> > I have a Python COM server. I need to deploy it on various sytems.
> > When I run the COM server from
> > python its showing an output " Registered : sample.lib"
>
> > If I try to use the COM obj from a VB client like:
>
> > obj = CreateObject("sample.lib")
>
> > Its working fine without any errors
>
> > Now I am trying to convert this COM server to an exe through py2exe
> > and after I run the exe, I am
> > getting the same output " Registered : sample.lib"
>
> > But If I try to use the COM obj from a VB client like
>
> > obj = CreateObject("sample.lib")
>
> > A console pops up saying " Registered : sample.lib" and VB application
> > hangs there.
> > Its throwing a VB error that "ActiveX object cannot be
> > created..etc etc"
>
> > Any suggestions please...
>
> > Regards,
> > Tejovathi
>
> Here is my sample COM server and py2exe setup file
>
> testCOM.py
>
> import win32com.client
> import os.path
> import shutil
> from win32api import Sleep
> import string
> import os
> import sys
> import pythoncom
>
> class FirstEx:
>
> _reg_clsid_ = "{A6DE9DF8-5EBF-48E6-889E-C71CB84CFF2C}"
> pythoncom.frozen = 1
> if hasattr(sys, 'importers'):
> # In the py2exe-packed version, specify the module.class
> # to use. In the python script version, python is able
> # to figure it out itself.
> _reg_class_spec_ = "__main__.FirstEx"
> _reg_desc_ = "My first COM server"
> _reg_progid_ = "SAMPLE.Lib"
> _public_methods_ = ['init', 'Version']
> _public_attrs_ = ['softspace', 'noCalls']
> _readonly_attrs_ = ['noCalls']
> _reg_clsctx_ = pythoncom.CLSCTX_LOCAL_SERVER
>
> def __init__(self):
> self.softspace = 1
> self.noCalls = 0
>
> def Version(self):
> self.noCalls = self.noCalls + 1
>
> # insert "softspace" number of spaces
> return "Version: 0.0.1"
>
> if __name__=='__main__':
> import sys
> if hasattr(sys, 'importers'):
> # running as packed executable.
> if '--register' in sys.argv[1:] or '--unregister' in
> sys.argv[1:]:
> # --register and --unregister work as usual
> import win32com.server.register
> win32com.server.register.UseCommandLine(FirstEx)
> else:
> # start the server.
> from win32com.server import localserver
> localserver.main()
> else:
> import win32com.server.register
> win32com.server.register.UseCommandLine(FirstEx)
>
>  Here is my setup file:
>
> #Start here
> from distutils.core import setup
> import py2exe
>
> setup(options = {"py2exe": {"compressed": 1,
>   "optimize": 2,
>   "ascii": 1,
>   "bundle_files": 1}},
> zipfile = None,
> com_server = ["win32com.servers.interp"],
> console = ["testCOM.py"])
> #End here
>
> Here is my VB code:
>
> Sub subRoutine()
> Dim connection As Object
> Dim returnvalue1 As String
> Dim returnvalue2 As String
> Dim flag3 As Boolean
>
> Set connection = CreateObject("SAMPLE.Lib")
> returnvalue1 = connection.Version()
> MsgBox (returnvalue1)
> End Sub
>
> The non exe version of the COM server ie. directlly running the
> testCOM.py registers the library properly and
>
> in the VB application, the message box displays the version as 0.0.1.
>
> But, after I create the EXE file using the setup.py file and run it,
> it registers the library.
>
> When I run the VB application, it hangs at the line
>
> Set connection = CreateObject("SAMPLE.Lib")
>
> and displays. " ACTIVEX cannot create the object"
>
> Any suggestions please

A quick suggestion (didn't read very carefully sorry).
Make sure you register it with --debug and use the pythonwin tools-
>trace collector debugging tool.
See if you get any joy.  It may be you missed some vital library in
your py2exe
that causes a start-up time failure.

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


Re: Python or PowerShell ?

2008-01-08 Thread Torsten Bronger
Hallöchen!

[EMAIL PROTECTED] writes:

> I am all about using the right tool for the right purposes, [...]

Which purpose?

> I dug up one article from Google that talked about comparison but
> that was about it.
>
> http://www.simple-talk.com/sql/database-administration/comparing-python-and-powershell-dba-scripting-/

This comparison is about a very narrow field; additionally, it is a
field PowerShell was optimised for.

Tschö,
Torsten.

-- 
Torsten Bronger, aquisgrana, europa vetus
  Jabber ID: [EMAIL PROTECTED]
   (See http://ime.webhop.org for further contact info.)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: stupid/style/list question

2008-01-08 Thread Giampaolo Rodola'
On 8 Gen, 16:45, Fredrik Lundh <[EMAIL PROTECTED]> wrote:
> Giampaolo Rodola' wrote:
> > To flush a list it is better doing "del mylist[:]" or "mylist = []"?
> > Is there a preferred way? If yes, why?
>
> The latter creates a new list object, the former modifies an existing
> list in place.
>
> The latter is shorter, reads better, and is probably a bit faster in
> most cases.
>
> The former should be used when it's important to clear a specific list
> object (e.g. if there are multiple references to the list).
>
> 

I'm going to use the latter one, thanks.
-- 
http://mail.python.org/mailman/listinfo/python-list


Newbie question: Classes

2008-01-08 Thread Sam Garson
Hello all

Basically, I have created a program using tkinter without using any class
structure, simply creating widgets and functions (and finding ways around
passing variables from function to function, using global variables etc).
The program has become rather large ( lines?) I am trying to now put it into
a class structure, because I hear it is easier to handle.

So basically, I put all the stuff into a class, making the widgets in the
"def __init__(self, root)" (root being my Tk() ) and then I have had to put
a "self." in front of any instance of any variable or widget. Is this right?
it seems like nothing is any easier (except having variables locally). Is
this right? Should I be creating more classes for different things or what?

I can upload the .py if you want.

Thanks,

Sam

-- 
I intend to live forever - so far, so good.

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

Peer To Peer File Sharing...

2008-01-08 Thread Dom Rout
Hello.
Well, this is my first post on any USENET group anywhere, so I hope I
get it right. Basically, I just want to get some opinions on a plan of
mine for a new project.

I want to produce a small, peer to peer, file sharing network for the
use of myself and some of my friends. The purpose of this is basically
to allow us to share files conveniently without relying on technology
such as Windows Live Messenger (Yuck).

I have a VPS which I would like to dedicate to the task of acting as a
tracker, so I can run a server application written in python on it. I
will also write the first client in python, although I may go for a
different language for the client in the final version, for
performance. For now, Python is perfect because of the ease of use
that it offers and the fact that I already know a bit about socket
programming using it.

Also concerning architecture, I will also have a number of peers that
connect to the tracker and also to other peers, via an IP address
provided by the server, as necessary to download the files.

The files themselves should be split up into "Chunks" of fixed length,
which will be given an index and tracked by the server. The server
should know which clients have which chunks of a file, and when a
client needs to download a file the server should look for other
clients that have chunks from that file and give the IP address to the
client, which should then for a connection to this peer and download
the parts of the file that are available.

When managing the chunks of a file, I will need to use a mutex to
allow reading and writing of them. I should provide a getter and
setter method in each file to allow chunks to be placed into it more
conveniently. The getter and setter should both use mutex's to allow
multiple threads of uploads and downloads at the same time.

I will need to implement a username and password system, to restrict
the users of the system to people that I trust.

To uniquely identify a file, I would like to use a file path. There
should be a theoretical directory that contains all shared files,
although the client should be given the option of which files from the
directory to download.

This directory should look like:
"Global/"
"Global/Images/"
"Global/Music/"
"Users//"

It would be nice if it was possible to subscribe to certain
directories, and download new files from them as need be.

Well, these are my ideas so far. Is anything drastically obviously
wrong, and can anyone suggest to me any best practices when
implementing this sort of design?

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


Re: Python's great, in a word

2008-01-08 Thread James Matthews
We have such nice names so the word Python will be something people like and
not something people fear (A massive 12 foot snake) and Pythonic is a
behavior pattern we should all follow! In layman's terms it means we should
all act like snakes a little more!

On Jan 8, 2008 5:13 PM, Carl Banks <[EMAIL PROTECTED]> wrote:

> On Jan 7, 6:29 pm, MRAB <[EMAIL PROTECTED]> wrote:
> > On Jan 7, 5:40 pm, Martin Marcher <[EMAIL PROTECTED]> wrote:>
> [EMAIL PROTECTED] wrote:
> > > > The best thing about Python is ___.
> >
> > > it's pythonicness.
> >
> > I think it sounds better as "its pythonicity".
>
> Mixing Greek and Latin suffixes usually works better than mixing Greek
> and Germanic, doesn't it.
>
>
> Carl Banks
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
http://search.goldwatches.com/?Search=Movado+Watches
http://www.jewelerslounge.com
http://www.goldwatches.com
-- 
http://mail.python.org/mailman/listinfo/python-list

ZSI and .NET

2008-01-08 Thread Joseph Bernhardt
I am successfully using ZSI to create a web service for our internal use.  A
request containing a username and password will respond with user
information.

 

Sample Request:





Jough

joughspassword





 

Response for Sample Request:



   http://www.w3.org/2001/XMLSchema-instance";
id="ob7c7c8c0" xsi:type="xsd:string">[EMAIL PROTECTED]

   http://www.w3.org/2001/XMLSchema-instance";
id="o9ed5f5c" xsi:type="xsd:int">28

   http://www.w3.org/2001/XMLSchema-instance";
id="ob7cb4e30" xsi:type="xsd:string">[EMAIL PROTECTED]



 

Unfortunately, when I try to complete the request via C#, an exception will
be thrown when the response is deserialized: 

 

{"The specified type was not recognized: name='string',
namespace='http://www.w3.org/2001/XMLSchema', at ."}

 

I realize that my problem is mainly .NET based, but since it has to do with
datatypes I thought someone from here may be able to help me.

 

The python code is a simple CGI dispatched function.  Let me know if you
need to see it, or the wsdl.

 

Thanks!

 

Jough

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

Javascript parser

2008-01-08 Thread Christof Hoeke
hello,
is there any Javascript (not just JSON) parser for Python? I saw 
http://wwwsearch.sourceforge.net/python-spidermonkey/ which seems to be 
from 2003 and unmaintained and seems to be quite complicated to get to 
work anyway :(

Using Rhino from Jython is not really an option as I'd like to work in 
(C)Python only.

thanks for any hint

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


Re: Python or PowerShell ?

2008-01-08 Thread Martin P. Hellwig
Torsten Bronger wrote:
> Hallöchen!
> 
> [EMAIL PROTECTED] writes:
> 
>> I am all about using the right tool for the right purposes, [...]
> 
> Which purpose?
> 
>> I dug up one article from Google that talked about comparison but
>> that was about it.
>>
>> http://www.simple-talk.com/sql/database-administration/comparing-python-and-powershell-dba-scripting-/
> 
> This comparison is about a very narrow field; additionally, it is a
> field PowerShell was optimised for.
> 
> Tschö,
> Torsten.
> 
And adding to that, if you don't care about cross platform anyway, why 
even bother with python? I am sure that MS has tools that can do in a 
point and click kind of way all the things you might encounter.

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


Re: Peer To Peer File Sharing...

2008-01-08 Thread James Matthews
Look at the old source code of the Bittorrent client for ideas!

On Jan 8, 2008 8:51 PM, Dom Rout <[EMAIL PROTECTED]> wrote:

> Hello.
> Well, this is my first post on any USENET group anywhere, so I hope I
> get it right. Basically, I just want to get some opinions on a plan of
> mine for a new project.
>
> I want to produce a small, peer to peer, file sharing network for the
> use of myself and some of my friends. The purpose of this is basically
> to allow us to share files conveniently without relying on technology
> such as Windows Live Messenger (Yuck).
>
> I have a VPS which I would like to dedicate to the task of acting as a
> tracker, so I can run a server application written in python on it. I
> will also write the first client in python, although I may go for a
> different language for the client in the final version, for
> performance. For now, Python is perfect because of the ease of use
> that it offers and the fact that I already know a bit about socket
> programming using it.
>
> Also concerning architecture, I will also have a number of peers that
> connect to the tracker and also to other peers, via an IP address
> provided by the server, as necessary to download the files.
>
> The files themselves should be split up into "Chunks" of fixed length,
> which will be given an index and tracked by the server. The server
> should know which clients have which chunks of a file, and when a
> client needs to download a file the server should look for other
> clients that have chunks from that file and give the IP address to the
> client, which should then for a connection to this peer and download
> the parts of the file that are available.
>
> When managing the chunks of a file, I will need to use a mutex to
> allow reading and writing of them. I should provide a getter and
> setter method in each file to allow chunks to be placed into it more
> conveniently. The getter and setter should both use mutex's to allow
> multiple threads of uploads and downloads at the same time.
>
> I will need to implement a username and password system, to restrict
> the users of the system to people that I trust.
>
> To uniquely identify a file, I would like to use a file path. There
> should be a theoretical directory that contains all shared files,
> although the client should be given the option of which files from the
> directory to download.
>
> This directory should look like:
> "Global/"
> "Global/Images/"
> "Global/Music/"
> "Users//"
>
> It would be nice if it was possible to subscribe to certain
> directories, and download new files from them as need be.
>
> Well, these are my ideas so far. Is anything drastically obviously
> wrong, and can anyone suggest to me any best practices when
> implementing this sort of design?
>
> Thanks, Dominic Rout.
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
http://search.goldwatches.com/?Search=Movado+Watches
http://www.jewelerslounge.com
http://www.goldwatches.com
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Python or PowerShell ?

2008-01-08 Thread kyosohma
On Jan 8, 1:57 pm, "Martin P. Hellwig" <[EMAIL PROTECTED]> wrote:
> Torsten Bronger wrote:
> > Hallöchen!
>
> > [EMAIL PROTECTED] writes:
>
> >> I am all about using the right tool for the right purposes, [...]
>
> > Which purpose?
>
> >> I dug up one article from Google that talked about comparison but
> >> that was about it.
>
> >>http://www.simple-talk.com/sql/database-administration/comparing-pyth...
>
> > This comparison is about a very narrow field; additionally, it is a
> > field PowerShell was optimised for.
>
> > Tschö,
> > Torsten.
>
> And adding to that, if you don't care about cross platform anyway, why
> even bother with python? I am sure that MS has tools that can do in a
> point and click kind of way all the things you might encounter.
>
> --
> mph

I code mostly for Windows users, but I use Python almost exclusively.
Why?

1) Python is "free"
2) Microsoft Visual Studio is very expensive
3) Python is Open Source
4) Visual Studio is not Open Source
5) I can actually take the code from IDLE and refine it for my
purposes if it doesn't suit me. Good luck doing that with practically
anything Microsoft supplies.
6) With relative ease, I can go cross-platform with my code if
requirements change

I could go on. There are many good reasons to use Python (or some
other good open source language, like Ruby) even if you just program
for Windows.

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


Re: Look for a string on a file and get its line number

2008-01-08 Thread jcvanelst
On 8 jan, 03:19, Horacius ReX <[EMAIL PROTECTED]> wrote:
> Hi,
>
> I have to search for a string on a big file. Once this string is
> found, I would need to get the number of the line in which the string
> is located on the file. Do you know how if this is possible to do in
> python ?
>
> Thanks

hi, i'm no python whizzkid, but you can do a lot with the .index
syntax. If you do something like this, it'll return the index of the
first character of your string as it is found in your file. Note that
if you read a file like this there will be some special characters for
new lines and the list structure that python uses, so if you want to
know the exact line you will have to find that out by playing with a
small file. You can always use a command like:  print s[12]
if you want to know the exact 12th character in your file

infile = open("C:\\Users\\yourname\\Desktop\\", 'r')

f= yourfile.readlines()
s=str(f)
yourstring = s.index('mystring')


good luck,

)a((o
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: I'm searching for Python style guidelines

2008-01-08 Thread Matthew Woodcraft
Paul McGuire  <[EMAIL PROTECTED]> wrote:
> While not required by any means, you will also find it handy to follow
> *every* entry in the list with a comma, even the last one in the list
> (this is legal Python).  That is, in your example:
>
> foo =3D [
> 'too long',
> 'too long too',
> 'too long too',
> 'last item',
> ]
>
> Later on when you want to reorder the items, then you can just copy/
> paste whole lines, even if moving to or from the bottom of the list.
> This is also a good argument for putting the closing ']' on its own
> line, instead of on the same line as the last item.

The other good reason for doing these two things is that they fit
better with the line-based rules that most source code management
systems use for merging.

-M-

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


Re: I'm searching for Python style guidelines

2008-01-08 Thread Matthew Woodcraft
 <[EMAIL PROTECTED]> wrote:
> A quick look (thorough analysis still required) shows that OLPC and
> PyPy are, indeed, extensive standards.

> one-laptop-per-child.html 
> (olpc),74.3,,http://wiki.laptop.org/go/Python_Style_Guide

I think that's mostly PEP 8, with some notes added.

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


Re: Newbie question: Classes

2008-01-08 Thread Daniel Fetchinson
> Basically, I have created a program using tkinter without using any class
> structure, simply creating widgets and functions (and finding ways around
> passing variables from function to function, using global variables etc).
> The program has become rather large ( lines?) I am trying to now put it into
> a class structure, because I hear it is easier to handle.
>
> So basically, I put all the stuff into a class, making the widgets in the
> "def __init__(self, root)" (root being my Tk() ) and then I have had to put
> a "self." in front of any instance of any variable or widget. Is this right?
> it seems like nothing is any easier (except having variables locally). Is
> this right? Should I be creating more classes for different things or what?


Use the method that works best for you. If you like the procedural
approach more then don't worry about being object oriented. The good
thing is that python is multi-paradigm so if custom objects don't make
your life easier then just forget about them :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: mod-python on Mac OSX 10.5

2008-01-08 Thread Arnaud Delobelle
On Jan 8, 5:27 am, Gnarlodious <[EMAIL PROTECTED]> wrote:
> I am trying to install mod_python on OSX 10.5, Intel version.
>
> sudo apachectl configtest tells me this:
>
> httpd: Syntax error on line 114 of /private/etc/apache2/httpd.conf:
> Cannot load /usr/libexec/apache2/mod_python.so into server:
> dlopen(/usr/libexec/apache2/mod_python.so, 10): no suitable image
> found. Did find:\n\t/usr/libexec/apache2/mod_python.so: mach-o, but
> wrong architecture
>
> I attempted to follow instructions found on these pages but it didn't work:
>
> 
>
> 
>
> Can
>
> anyone tell me what is causing this error?

(Sorry no time to read the references you provide)

This is because httpd is running in 64 bits (arch x86_64) but
mod_python.so is only 32 bits by default.  You need to modify this.
what I did was:

make the following changes to src/Makefile:
* Add -arch x86_64 to the LDFLAGS line
* Change the build line in mod_python.so to:
$(APXS) $(INCLUDES) -c -Wc,"-arch x86_64" $(SRCS) $(LDFLAGS) $
(LIBS)

Now that I look at this, I don' know if both are necessary... But it
worked for me.

There was a discussion to the mod_python mailing list in october 2007:

http://www.modpython.org/pipermail/mod_python/2007-October/

--
Arnaud

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


mod-python on Mac OSX 10.5

2008-01-08 Thread Gnarlodious
I am trying to install mod_python on OSX 10.5, Intel version.

sudo apachectl configtest tells me this:

httpd: Syntax error on line 114 of /private/etc/apache2/httpd.conf: 
Cannot load /usr/libexec/apache2/mod_python.so into server: 
dlopen(/usr/libexec/apache2/mod_python.so, 10): no suitable image 
found. Did find:\n\t/usr/libexec/apache2/mod_python.so: mach-o, but 
wrong architecture

I attempted to follow instructions found on these pages but it didn't work:





Can 

anyone tell me what is causing this error?

-- Gnarlie
http://Gnarlodious.com/


-- 
Posted via a free Usenet account from http://www.teranews.com

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


Re: Modules and descriptors

2008-01-08 Thread Steven Bethard
Chris Leary wrote:
> As I understand it, the appeal of properties (and descriptors in
> general) in new-style classes is that they provide a way to
> "intercept" direct attribute accesses. This lets us write more clear
> and concise code that accesses members directly without fear of future
> API changes.
> 
> I love this feature of the language, but find that I still have to
> call getter/setter methods of module instances. Since module
> attributes are accessed by way of __dict__ and the module type has a
> valid __mro__, why doesn't the descriptor protocol apply to module
> instances?

Because it doesn't apply to class *instances*. Module-level code gets 
executed roughly like this::

 mod = ModuleType(...)
 exec module_code in mod.__dict__

So consider the similar code::

 >>> class C(object):
 ... pass
 ...
 >>> c = C()
 >>> exec '''
 ... def foo(self, *args):
 ... print self, args
 ... '''  in c.__dict__

A function ``foo`` has been added to the ``C`` instance. But *instances* 
don't invoke the descriptor protocol, so we the ``self`` parameter is 
not bound to the ``C`` instance::

 >>> c.foo()
 Traceback (most recent call last):
   File "", line 1, in 
 TypeError: foo() takes at least 1 argument (0 given)

So the straightforward answer to your question is that module instances 
don't invoke the descriptor protocol because instances in general don't 
invoke the protocol (only classes do).

The follow-up question is usually something like "well, can't we make 
module instances special and have them invoke the descriptor protocol?" 
Yes, in theory it would be possible, but it would break backwards 
compatibility in very bad ways. For example, every pure function you 
define at the module level would then become a bound method whenever it 
was accessed. Consider a simple module ``mod`` like::

 def foo(bar):
 return 'baz(%s)' % bar

If I try to use this module, and module instances invoke the descriptor 
protocol, then ``bar`` will always be bound to the module instance. That 
means we'd have to totally change how we right module level functions, 
and they'd have to start looking like this::

 def foo(mod, bar):
 return 'baz(%s)' % bar

That, of course, would break *tons* of existing code.

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


Re: Newbie question: Classes

2008-01-08 Thread kyosohma
On Jan 8, 3:31 pm, "Daniel Fetchinson" <[EMAIL PROTECTED]>
wrote:
> > Basically, I have created a program using tkinter without using any class
> > structure, simply creating widgets and functions (and finding ways around
> > passing variables from function to function, using global variables etc).
> > The program has become rather large ( lines?) I am trying to now put it into
> > a class structure, because I hear it is easier to handle.
>
> > So basically, I put all the stuff into a class, making the widgets in the
> > "def __init__(self, root)" (root being my Tk() ) and then I have had to put
> > a "self." in front of any instance of any variable or widget. Is this right?
> > it seems like nothing is any easier (except having variables locally). Is
> > this right? Should I be creating more classes for different things or what?
>
> Use the method that works best for you. If you like the procedural
> approach more then don't worry about being object oriented. The good
> thing is that python is multi-paradigm so if custom objects don't make
> your life easier then just forget about them :)

One great benefit to classes is the ability to take a generic class
and then subclass it. Or the ability to instantiate various objects
from one class.

Say you have a dog class. If you pass in the correct data, you can
instantiate a dalmatian, a Labrador or a mutt. They're all dogs, but
their all different too.

Enough of my babbling. Check out the following links for more info:

http://www.freenetpages.co.uk/hp/alan.gauld/tutclass.htm
http://www.diveintopython.org/object_oriented_framework/defining_classes.html
http://docs.python.org/tut/node11.html

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


Re: Python or PowerShell ?

2008-01-08 Thread Matimus
On Jan 8, 2:24 pm, Torsten Bronger <[EMAIL PROTECTED]>
wrote:
> Hallöchen!
>
> [EMAIL PROTECTED] writes:
> > I am all about using the right tool for the right purposes, [...]
>
> Which purpose?
>
> > I dug up one article from Google that talked about comparison but
> > that was about it.
>
> >http://www.simple-talk.com/sql/database-administration/comparing-pyth...
>
> This comparison is about a very narrow field; additionally, it is a
> field PowerShell was optimised for.

Also, the code looks like they took optimized PowerShell code, and
just hacked together something to do the equivalent Python. There
appears to be little or no attempt to create nice efficient Python
code. For a true comparison two things are missing. 1) The reverse, do
something in python and then try to write it in PowerShell. 2) be
diligent in doing as much as possible to make both versions as simple
as possible. Pick any two languages and I can make the argument that
either one is better than the other if I pick something that one
language is better at and spend as little time as possible writing the
other version.

That might be a good exercise. Anybody wanna attempt re-writing the
python examples in that article? Just one glance at it and I can see
it was written by a Python novice. Now, I don't think the finished
product will be as small as the PowerShell equivalent, but it might be
easier to read and will look a heck of a lot nicer than it currently
does.

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


ANN: matplotlib-0.91.2 - a python graphics package

2008-01-08 Thread [EMAIL PROTECTED]
A new release of matplotlib is posted to the sourceforge download
site.
You can read the release notes with links at
http://matplotlib.sourceforge.net/whats_new.html

  Download: Downloads: 
http://sourceforge.net/project/showfiles.php?group_id=80706
  Homepage: http://matplotlib.sourceforge.net
  Screenshots: http://matplotlib.sourceforge.net/screenshots.html


What's new:

enhanced mathtext - Complete revamp of matplotlib's internal math
layout and rendering engine. Michael Droetboom has improved the TeX
parser to significantly expand it's coverege, and implemeted Knuth's
box layout algorithms. Additionally, the much anticipated STIX fonts
for math expressions have come online and ship with matplotlib. See a
sample of the new mathtext at
http://matplotlib.sourceforge.net/screenshots.html#mathtext_examples

better configuration - Darren Dale has provided support for a site.cfg
configuration file to enable users and package maintainers to have
better control over the matplotlib build process. He has also provided
a (currently optional) enthought.traits enabled property configuration
to replace matplotlib's rc configuration using a maplotlib.conf file

writing to file-like objects - You can now pass file like objects (eg
StringIO) to all backends for hardcopy. This has been a much requested
feature for usage in web application servers.

record array support - New functions for loading, displaying and
saving numpy record arrays in matplotlib.mlab. See for example,
http://matplotlib.sourceforge.net/examples/loadrec.py

pyplot - Added a module matplotlib.pyplot which has all of pylab's
plotting functions (eg figure, plot, show, close) but does not import
the numpy namepace. This is useful for those who want to use the pylab
functionality w/o the namespace clutter.
http://matplotlib.sourceforge.net/matplotlib.pyplot.html

maskedarray - Added optional support for the scipy sandbox masked
array packaged. Configurable with an rc setting.

plotfile - Added new pylab/pyplot command plotfile for gnuplot style
file plotting
http://matplotlib.sourceforge.net/matplotlib.pyplot.html#-plotfile
http://matplotlib.sourceforge.net/examples/plotfile_demo.py

And lots more
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: stupid/style/list question

2008-01-08 Thread Raymond Hettinger
On Jan 8, 7:34 am, "Giampaolo Rodola'" <[EMAIL PROTECTED]> wrote:
> I was wondering...
> To flush a list it is better doing "del mylist[:]" or "mylist = []"?
> Is there a preferred way? If yes, why?


To empty an existing list without replacing it, the choices
are "del mylist[:]" and "mylist[:] = []".  Of the two, I
prefer the former because it reads more explicity (delete
all of the items from the list").  In terms of performance,
they are basically the same.

To replace a list, "mylist = []" is the way to go.  This is
an affirmative statement that you are creating a new list.

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


  1   2   >