Re: Python MIDI in 2008

2008-05-07 Thread Asun Friere
On May 6, 7:43 pm, Max M <[EMAIL PROTECTED]> wrote:

> This is old in the sense that it has been a while since I wrote it. But
> it is virtually bug free, so nothing much is happening.
>
> The midi standard does not change so there is no real reason to
> change/upgrade it.

Maybe you should add a method somehwere that does nothing much,
increment the version number and give it a 2008 date? ;)
--
http://mail.python.org/mailman/listinfo/python-list


Re: using sqlite3 - execute vs. executemany; committing ...

2008-05-07 Thread David
Hi Vlasta.

>
> tags_lookups[tag][item_dict[tag]] = tags_lookups[tag].get(item_dict[tag],
> set()) | set([idx])
>
> I thought, whether I am not overestimating myself with respect to the future
> maintaining of the code ... :-)

Here's a suggestion for readability and maintainability:

Make a search() method (possibly on the object storing the text),
which takes variable args.

You'd declare it something like this:

def search(self, **kwargs)

And call it like this:

text.search(line=123, VCC=1, etc)

Probably it would return a list of results (line numbers in the original text?).

Then inside the function build up the sets etc, and comment the logic
liberally so you can understand it later.

This approach should be much more readable the equivalent sqllite + SQL.

>
>  The suggested XML structure is actually almost the one, I use to prepare
> and control the input data before converting it to the one presented in the
> previous mail :-). The main problem is, that I can't seem to make it fully
> valid XML without deforming the structure of the text itself - it can't be
> easily decided,  what CUSTOM_TAG should be in some places - due to the
> overlapping etc.

I was originally going to suggest an overlapped tag format, similar to this:

Bold textBold and italicisedItalicised

But I changed my mind. It's seriously malformed :-) I think that for
now, your format, where your marker values remain 'active' until
changed to another value is the best way way to go. XML's problems
with this sort of thing are a know limitation.

See this link:

http://en.wikipedia.org/wiki/XML#Disadvantages_of_XML

"Expressing overlapping (non-hierarchical) node relationships requires
extra effort"

There is some research into the subject, but no major (ie widely-used)
Python libraries as far as I can tell.

Google for "overlapping markup" and "python overlapping markup" for
more information. Here's one interesting page I found:

http://www.wilmott.ca/python/xmlparser.html#OVERLAPPED

It discusses the issue in detail, and comes with a Python
implementation (I haven't checked it).

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


strftime() argument 1 must be str, not unicode

2008-05-07 Thread Alexandr N Zamaraev

Subj is bag?

Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit 
(Intel)] on win32

Type "help", "copyright", "credits" or "license" for more information.
>>> from datetime import datetime
>>> datetime.today().strftime('%Y_%m_%d %H_%M_%S.csv')
'2008_05_07 12_30_22.csv'
>>> datetime.today().strftime(u'%Y_%m_%d %H_%M_%S.csv')
Traceback (most recent call last):
  File "", line 1, in 
TypeError: strftime() argument 1 must be str, not unicode
--
http://mail.python.org/mailman/listinfo/python-list


Re: How do you debug memory usage?

2008-05-07 Thread David
>  Rsync uses a lot of memory:
>http://www.samba.org/rsync/FAQ.html#4
>  rdiff-backup uses librsync, not rsync.
>  I'm not sure if rsync uses librsync, but one could speculate that
>  they share some code and perhaps some of the same problems.
>  But 2GB seems excessive unless you are dealing with millions of files.
>  A memory leak seems more likely.
>

Thanks for your input. In case you're interested here's a link to my
post to a local Linux user group:

http://lists.clug.org.za/pipermail/clug-tech/2008-May/040532.html

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


Re: License selection for free software

2008-05-07 Thread Carl Banks
On May 7, 2:39 am, Paul Rubin  wrote:
> [EMAIL PROTECTED] (Ville M. Vainio) writes:
>
> > In practice, the probability of hijacking of source code by an evil
> > corporation is very low for most projects. And even when it did
> > happen, the evil corporation would likely submit patches.
>
> If they're going to submit patches then they shouldn't have any problem
> with the GPL.

Nonsense.  They could be more than willing to contribute their
patches, but aren't willing to accept the GPL's limitation to being
used only in open source packages.

LGPL?  No, there is probably no reason to have a serious problem with
that if you're going to submit patches, but GPL, yes.


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


Re: using sqlite3 - execute vs. executemany; committing ...

2008-05-07 Thread David
>
>  Google for "overlapping markup" and "python overlapping markup" for
>  more information. Here's one interesting page I found:
>

I found an interesting markup called LMNL, which supports overlapping markup:

http://lmnl.net/

Also, a survey which compares various markup languages, including LMNL:

http://www.cl.cam.ac.uk/~sjm217/projects/markup/survey/

I'm mainly mentioning this because of your past mail where you asked
for existing formats that could meet your needs.

For now your current markup should be fine. But you should research
LMNL too. You can information here also:

http://www.lmnl.org/wiki/index.php/Main_Page

Another, related markup is Creole:

http://www.lmnl.org/wiki/index.php/Creole

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


PEP 370 question

2008-05-07 Thread Paul Melis

In (the recently accepted) PEP 370 it says

"Current Python versions don't have a unified way to install packages 
into the home directory of a user (except for Mac Framework builds). 
Users are either forced to ask the system administrator to install or 
update a package for them or to use one of the many workarounds like 
Virtual Python [1], Working Env [2] or Virtual Env [3].


[...]

The feature can't be implemented using the environment variable 
PYTHONPATH. The env var just inserts a new directory to the beginning of 
sys.path but it doesn't parse the pth files in the directory. A full 
blown site-packages path is required for several applications and Python 
eggs."


I'm confused. For years I've been installing packages and extension 
modules locally using distutils's --prefix option, e.g. using


  python setup.py install --prefix=$HOME/local

Together with adding $HOME/local/lib/python2.4/site-package to my 
PYTHONPATH this works fine, even if there are packages that require a 
.pth file to work or that use Eggs (like setuptools and pygments).


So what limitation does the quoted paragraph in the PEP refer to?

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


Re: ]ANN[ Vellum 0.16: Lots Of Documentation and Watching

2008-05-07 Thread Ville Vainio
On May 6, 11:27 pm, hdante <[EMAIL PROTECTED]> wrote:

>  GPL can mix with other free software licenses, so people who write
> BSD code and do not wish to remain BSD clean are free to use GPL'd
> code. That's the important point.

No, it can't. It can only mix through aggregation, i.e. you can ship a
GPL'd "plugin" with BSD code as long as you don't import the plugin
directly.

Here's a real life example from ipython:

- Core IPython is BSD clean, and we intend to leave it that way
- If we imported a gpl'd module in some core ipython component, the
core component would be gpl (or something equally restrictive) as
well, through viral nature of the license
- Now, if you want a BSD-clean version of ipython (say, to embed it in
a commercial program - with which I have absolutely *no* problem, and
can only see good things coming from it), you would have to gleam out
all the uses of that module from the source code. Not very fun, esp.
if it's something important
- There is a GPL'd module in "extensions" folder of IPython, ipy_bzr
(that is because of bzrlib). It's never imported anywhere in ipython
source code, but the user can import it in ipy_user_conf.py. This
"contaminates" the config file and subsequently ipython (because it's
imported into python interpreter ipython is running on), but luckily
the user can opt out from importing it if he wishes to remain BSD
clean. Or he can delete the file altogether if he wishes.

Without GPL, none of this hair-splitting is necessary.

I guess I could have gone the Carl Banks route and just say "It scares
away some people". Consider my replies here an elaborate way of saying
the very same thing.
--
http://mail.python.org/mailman/listinfo/python-list


Re: License selection for free software

2008-05-07 Thread Paul Rubin
Carl Banks <[EMAIL PROTECTED]> writes:
> Nonsense.  They could be more than willing to contribute their
> patches, but aren't willing to accept the GPL's limitation to being
> used only in open source packages.

Oh, I see what you mean--I'm considering any derived work to be a
patch, which is maybe an overbroad use of that term.  If they are
willing to contribute their patches in that sense, the GPL shouldn't
be a problem.  If they want to just send back small scraps of
improvement while incorporating the GPL'd program into a closed
program, the GPL is doing its job if it prevents that.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Scanning through Windows registry...

2008-05-07 Thread Tim Golden

Unknown Hero wrote:

Tim Golden wrote:


[... snip long example ...]


Correct me if I'm wrong (which I just might be), but doesn't the above
code go through the keys behind HKEY_LOCAL_MACHINE\Software\Timsoft\ ?

Is it possible to use an empty value in:

  hTimSoft = _winreg.OpenKey (HKLM, r"Software\TimSoft")

like:

  hTimSoft = _winreg.OpenKey (HKLM, "")

so it would go all subkeys behind the "root" (in this case,
HKEY_LOCAL_MACHINE)?


Yes. (Well, you can try it and find out for yourself!). As I said, this
was code to illustrate some other poster's difficulty. I assume that
you're capable of twisting it to suit your own purposes :)


The code is supposed to work even if I don't know all possible subkeys
under HKEY_LOCAL_MACHINE. Creating dozens or hundreds of handles like
the above is a bit... unappealing.

Can I also use HKLM in the place of hTimSoft when I want to determine
the amount of subkeys it has, like you did over here:


Yes. You can put any key handle you like in place of my
hTimSoft of the predefined _winreg.HKEY_LOCAL_MACHINE. They're
just keys. I assume you'll want some kind of recursive function which
combines calls to EnumKeys and EnumValues. 


Anyway, the above code seems interesting. I'll try a few tweaks here
and there and see what happens.


I wasn't sure just how experienced you were with programming; although you
said you were new to Python I thought you might have experience elsewhere
which would help you out here. If you're really stuck, post back and I (or 
someone
else) can try to knock up a more pertinent example. The main thing is for you
to get hold of the _winreg docs -- which I know you mentioned before -- and to
grasp what the concepts are and how the API calls work. It's a low-level module,
simply exposing the raw API calls, which is why there are several wrapper 
modules
around it, but it's worth getting to understand what's going on under the 
covers.

TJG

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


Re: Am I missing something with Python not having interfaces?

2008-05-07 Thread Bruno Desthuilliers

jmDesktop a écrit :
(snip)


On the dynamic typing,
isn't that the same sort of thing that lots of scripting languages
do?


This is not restricted to scripting languages - that is, unless you'd 
call Smalltalk, Erlang or common lisp "scripting languages".


Also and FWIW, static typing in C is mostly here to help the compiler 
optimizing, and it's very common to use void pointers and typecast to 
get some genericity (cf the sort() function in C stdlib). And you have 
the same pattern in Java with "generic" containers storing only "object" 
instances, then you have to cast your objects back to the appropriate 
type (which may fails, leading to a runtime error).



 VBScript doesn't require you to define your variables,


You mean "to declare the type of your variables" ? Neither OCaml nor 
Haskell require this, and they are both statically and strongly typed.



but I
don't really want to use it for anything 


Neither do I, but not because of dynamic typing. By experience, dynamic 
typing works just fine for most applications. And by experience too, 
static typing doesn't magically make your code bullet-proof.



(used to use it a lot in
Classic ASP.)  I believe everyone that Python is great, but some of it
doesn't make sense to me as to why.  


Quite a lot of Java stopped making sens to me since I learned some other 
languages. And most of the "OO" (hem) complexity, patterns madness etc 
you'll typically find in Java code only exists because of the language's 
arbitrary restrictions and lack of expressivity.


Learn Python, learn Ruby or (preferably) Smalltalk, learn common lisp or 
(preferably) Scheme, learn OCaml or (preferably) Haskell, learn Erlang, 
and you'll find out that there's much more in programming and languages 
than can be dreamt of in Java's  philosophy !-)

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


Re: strftime() argument 1 must be str, not unicode

2008-05-07 Thread Andrii V. Mishkovskyi
2008/5/7 Alexandr N Zamaraev <[EMAIL PROTECTED]>:
> Subj is bag?
>
>  Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit
> (Intel)] on win32
>  Type "help", "copyright", "credits" or "license" for more information.
>  >>> from datetime import datetime
>  >>> datetime.today().strftime('%Y_%m_%d %H_%M_%S.csv')
>  '2008_05_07 12_30_22.csv'
>  >>> datetime.today().strftime(u'%Y_%m_%d %H_%M_%S.csv')
>  Traceback (most recent call last):
>   File "", line 1, in 
>  TypeError: strftime() argument 1 must be str, not unicode

Unicode and str objects are not the same. Why do you think that this
is a bug? Anyway, you can always use 'encode' method of unicode
objects:

In [2]: datetime.today().strftime('%Y-%m-%d %H-%M-%S.csv')
Out[2]: '2008-05-07 10-49-24.csv'

In [3]: datetime.today().strftime(u'%Y-%m-%d %H-%M-%S.csv')
---
TypeError Traceback (most recent call last)

/home/mishok/doc/python/ in ()

TypeError: strftime() argument 1 must be str, not unicode

In [4]: datetime.today().strftime(u'%Y-%m-%d %H-%M-%S.csv'.encode('utf-8'))
Out[4]: '2008-05-07 10-51-19.csv'

No offence, but have you read the tutorial?

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



-- 
Wbr, Andrii Mishkovskyi.

He's got a heart of a little child, and he keeps it in a jar on his desk.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Problem parsing SOAP envelope with ElementTree

2008-05-07 Thread Waldemar Osuch

Zvi wrote:

Hi All,

   Can someone tell me why id the following not working?


snip not working code



What am I doing wrong?


Here is working code.

8<-
from xml.etree import ElementTree as ET

data = """xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"; 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"; 
xmlns:xsd="http://www.w3.org/2001/XMLSchema";>


http://tempuri.org/";>




"""

env = ET.fromstring(data)
result = env.find('*//{http://tempuri.org/}Get2Result')
response = ET.fromstring(result.text)
for elm in response.getiterator():
print elm
8<-

In the future please paste complete examples. It helps me to help you.
They were two things that I found to be wrong:
- searching using wrong path. You missed *// in front of the tag
- parsing only once. There are two xml sources here.
  The first parse got you the representation of the Envelope.
  You have to parse the Get2Result payload to get at the
  interesting part

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


Why don't generators execute until first yield?

2008-05-07 Thread Martin Sand Christensen
Hi!

First a bit of context.

Yesterday I spent a lot of time debugging the following method in a
rather slim database abstraction layer we've developed:

,
| def selectColumn(self, table, column, where={}, order_by=[], group_by=[]):
| """Performs a SQL select query returning a single column
|
| The column is returned as a list. An exception is thrown if the
| result is not a single column."""
| query = build_select(table, [column], where, order_by, group_by)
| result = DBResult(self.rawQuery(query))
| if result.colcount != 1:
| raise QueryError("Query must return exactly one column", query)
| for row in result.fetchAllRowsAsList():
| yield row[0]
`

I'd just rewritten the method as a generator rather than returning a
list of results. The following test then failed:

,
| def testSelectColumnMultipleColumns(self):
| res = self.fdb.selectColumn('db3ut1', ['c1', 'c2'],
| {'c1':(1, 2)}, order_by='c1')
| self.assertRaises(db3.QueryError, self.fdb.selectColumn,
|   'db3ut1', ['c1', 'c2'], {'c1':(1, 2)}, order_by='c1')
`

I expected this to raise a QueryError due to the result.colcount != 1
constraint being violated (as was the case before), but that isn't the
case. The constraint it not violated until I get the first result from
the generator.

Now to the main point. When a generator function is run, it immediately
returns a generator, and it does not run any code inside the generator.
Not until generator.next() is called is any code inside the generator
executed, giving it traditional lazy evaluation semantics. Why don't
generators follow the usual eager evaluation semantics of Python and
immediately execute up until right before the first yield instead?
Giving generators special case semantics for no good reason is a really
bad idea, so I'm very curious if there is a good reason for it being
this way. With the current semantics it means that errors can pop up at
unexpected times rather than the code failing fast.

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


Re: use php in python httpservers

2008-05-07 Thread artasis
On May 6, 3:00 pm, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] wrote:
> > Hi, that is my task:
> > I need to create python webserver-like extension(dll) which will run
> > php and python scripts as plugins.
> > I have no problems with dll creating and run python scripts, but I
> > cannot understand how to run php(CLI is not a solution).
> > Is there a way to solve this problem? I've thought to implement php to
> > HTTPServer-like python module, but as I see it's impossible. Solutions
> > with creating intermediate C-based module is allowed, but better
> > without them :).
> > AFAIK, php5ts.dll is that what I must use but how integrate it to
> > python webserver? that is a question
>
> http://www.amazon.com/Extending-Embedding-PHP-Developers-Library/dp/0...
>
> Might be of help.
>
> And maybe the roadsend PHP-compiler.
>
> Diez
thanks! great book! this would help with Jeff recommendations to use
ctypes

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


Re: Why don't generators execute until first yield?

2008-05-07 Thread Ian Kelly
On Wed, May 7, 2008 at 2:29 AM, Martin Sand Christensen <[EMAIL PROTECTED]> 
wrote:
>  Now to the main point. When a generator function is run, it immediately
>  returns a generator, and it does not run any code inside the generator.
>  Not until generator.next() is called is any code inside the generator
>  executed, giving it traditional lazy evaluation semantics. Why don't
>  generators follow the usual eager evaluation semantics of Python and
>  immediately execute up until right before the first yield instead?
>  Giving generators special case semantics for no good reason is a really
>  bad idea, so I'm very curious if there is a good reason for it being
>  this way. With the current semantics it means that errors can pop up at
>  unexpected times rather than the code failing fast.

Isn't lazy evaluation sort of the whole point of replacing a list with
an iterator?  Besides which, running up to the first yield when
instantiated would make the generator's first iteration inconsistent
with the remaining iterations.  Consider this somewhat contrived
example:

def printing_iter(stuff):
for item in stuff:
print item
yield item

Clearly, the idea here is to create a generator that wraps another
iterator and prints each item as it yields it.  But using your
suggestion, this would instead print the first item at the time the
generator is created, rather than when the first item is actually
iterated over.

If you really want a generator that behaves the way you describe, I
suggest doing something like this:

def myGenerator(args):
immediate_setup_code()

def generator():
for item in actual_generator_loop():
yield item
return generator()
--
http://mail.python.org/mailman/listinfo/python-list


mxTexTools (Re: using sqlite3 - execute vs. executemany; committing ...)

2008-05-07 Thread M.-A. Lemburg

On 2008-05-07 00:07, Vlastimil Brom wrote:

Thanks for reminding me about
the mxTextTools; I looked at this package very quickly several months
ago and it seemed quite
complex and heavy-weight, but maybe I will reconsider this after some
investigation ...


mxTextTools gives you almost full C speed while still being programmable
in Python and without a compiler.

It is a low level parsing engine. Here's talk I gave on mxTextTools
last year:

http://www.egenix.com/library/presentations/EuroPython2007-Parsing-Languages-with-mxTextTools/

If you're looking for ways to hide the complexity, you could try
SimpleParse (which uses mxTextTools for the parsing, but provides a
grammar based front-end).

--
Marc-Andre Lemburg
eGenix.com

Professional Python Services directly from the Source  (#1, May 07 2008)
>>> Python/Zope Consulting and Support ...http://www.egenix.com/
>>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/
>>> mxODBC, mxDateTime, mxTextTools ...http://python.egenix.com/


 Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! 


   eGenix.com Software, Skills and Services GmbH  Pastor-Loeh-Str.48
D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg
   Registered at Amtsgericht Duesseldorf: HRB 46611
--
http://mail.python.org/mailman/listinfo/python-list


Re: Scanning through Windows registry...

2008-05-07 Thread Tim Golden

In a spirit of being helpful... :)

The code below (which I imagine every Windows programmer writes
sometime in their Python life) mimics the os.walk functionality, yielding
the key, subkeys, and values under a particular starting point in the
registry. The "if __name__ == '__main__'" test run at the bottom does
more-or-less what you were asking for originally, I think, converting
some name to some other name wherever it appears.


import _winreg

HIVES = {
 "HKEY_LOCAL_MACHINE" : _winreg.HKEY_LOCAL_MACHINE,
 "HKEY_CURRENT_USER" : _winreg.HKEY_CURRENT_USER,
 "HKEY_CLASSES_ROOT" : _winreg.HKEY_CLASSES_ROOT,
 "HKEY_USERS" : _winreg.HKEY_USERS,
 "HKEY_CURRENT_CONFIG" : _winreg.HKEY_CURRENT_CONFIG
}

class RegKey:
 
 def __init__ (self, name, key):

self.name = name
self.key = key
 
 def __str__ (self):

   return self.name

def walk (top):
 """walk the registry starting from the key represented by
 top in the form HIVE\\key\\subkey\\..\\subkey and generating
 key, subkey_names, values at each level.
 
 key is a lightly wrapped registry key, including the name

 and the HKEY object.
 subkey_names are simply names of the subkeys of that key
 values are 3-tuples containing (name, data, data-type).
 See the documentation for _winreg.EnumValue for more details.
 """
 if "\\" not in top: top += "\\"
 root, subkey = top.split ("\\", 1)
 key = _winreg.OpenKey (HIVES[root], subkey, 0, _winreg.KEY_READ | 
_winreg.KEY_SET_VALUE)
 
 subkeys = []

 i = 0
 while True:
   try:
 subkeys.append (_winreg.EnumKey (key, i))
 i += 1
   except EnvironmentError:
 break
 
 values = []

 i = 0
 while True:
   try:
 values.append (_winreg.EnumValue (key, i))
 i += 1
   except EnvironmentError:
 break

 yield RegKey (top, key), subkeys, values
 
 for subkey in subkeys:

   for result in walk (top + "\\" + subkey):
 yield result
 
if __name__ == '__main__':

 for key, subkey_names, values in walk ("HKEY_LOCAL_MACHINE\\Software\\Python"):
   print key
   for (name, data, type) in values:
 print "  ", name, "=>", data
 if type == _winreg.REG_SZ and "TJG" in data:
   _winreg.SetValueEx (key.key, name, 0, type, data.replace ("TJG", "XYZ"))



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


Re: saving a webpage's links to the hard disk

2008-05-07 Thread castironpi
On May 7, 1:40 am, Jetus <[EMAIL PROTECTED]> wrote:
> On May 4, 7:22 am, [EMAIL PROTECTED] wrote:
>
>
>
>
>
> > On May 4, 12:33 am, "Gabriel Genellina" <[EMAIL PROTECTED]>
> > wrote:
>
> > > En Sun, 04 May 2008 01:33:45 -0300, Jetus <[EMAIL PROTECTED]> escribió:
>
> > > > Is there a good place to look to see where I can find some code that
> > > > will help me to save webpage's links to the local drive, after I have
> > > > used urllib2 to retrieve the page?
> > > > Many times I have to view these pages when I do not have access to the
> > > > internet.
>
> > > Don't reinvent the wheel and use wgethttp://en.wikipedia.org/wiki/Wget
>
> > > --
> > > Gabriel Genellina
>
> > A lot of the functionality is already present.
>
> > import urllib
> > urllib.urlretrieve( 'http://python.org/', 'main.htm' )
> > from htmllib import HTMLParser
> > from formatter import NullFormatter
> > parser= HTMLParser( NullFormatter( ) )
> > parser.feed( open( 'main.htm' ).read( ) )
> > import urlparse
> > for a in parser.anchorlist:
> >     print urlparse.urljoin( 'http://python.org/', a )
>
> > Output snipped:
>
> > ...http://python.org/psf/http://python.org/dev/http://python.org/links/h...
> > ...
>
> How can I modify or add to the above code, so that the file references
> are saved to specified local directories, AND the saved webpage makes
> reference to the new saved files in the respective directories?
> Thanks for your help in advance.- Hide quoted text -
>
> - Show quoted text -

You'd have to convert filenames in the loop to a file system path; try
writing as is with makedirs( ).  You'd have to replace contents in a
file for links, so your best might be prefixing them with localhost
and spawning a small bounce-router.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Why don't generators execute until first yield?

2008-05-07 Thread Duncan Booth
Martin Sand Christensen <[EMAIL PROTECTED]> wrote:

> Now to the main point. When a generator function is run, it 
immediately
> returns a generator, and it does not run any code inside the 
generator.
> Not until generator.next() is called is any code inside the generator
> executed, giving it traditional lazy evaluation semantics. Why don't
> generators follow the usual eager evaluation semantics of Python and
> immediately execute up until right before the first yield instead?

You mean you expect the semantics of generators to be that when you 
create them, or every time you call next() they run until they hit yield 
and then (except for the initial run) return the result that was yielded 
the time before? It is easy enough to implement that, but could be a bit 
confusing for the user.

>>> def greedy(fn):
def greedygenerator(*args, **kw):
def delayed():
it = iter(fn(*args, **kw))
try:
res = it.next()
except StopIteration:
yield None
return
yield None
for value in it:
yield res
res = value
yield res
it = delayed()
it.next()
return it
return greedygenerator

>>> @greedy
def mygen(n):
for i in range(n):
print i
yield i


>>> x = mygen(3)
0
>>> list(x)
1
2
[0, 1, 2]
>>> x = mygen(0)
>>> list(x)
[]
>>> 

Now try:

   for command in getCommandsFromUser():
   print "the result of that command was", execute(command)

where getCommandsFromUser is a greedy generator that reads from stdin, 
and see why generators don't work that way.

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


Re: open filename with spaces in path

2008-05-07 Thread Chris
On May 7, 1:09 am, "Kam-Hung Soh" <[EMAIL PROTECTED]> wrote:
> On Wed, 07 May 2008 08:36:35 +1000, Michael Robertson  
>
> <[EMAIL PROTECTED]> wrote:
> > I'm having trouble opening a file in linux, whose path has spaces in it.
>
> > $ mkdir my\ test
> > $ echo test > my\ test/test.txt
> > $ python
>
> >  >>> open('./my test/test.txt')
> > Exception
> >  >>> open('./my\\ test/test.txt')
> > Exception
>
> Try a string literal by prefixing your path string with "r":
>
> open(r'./my test/test.txt')
>
> Seehttp://docs.python.org/ref/strings.html
>
> > but yet...
>
> >  >>> import os
> >  >>> os.chdir('./my test')
> >  >>> open('./test')
>
> > works just fine.
>
> Couldn't test on Linux, but in Windows ...
>
> >>> os.chdir('C:\temp\my test')
>
> Traceback (most recent call last):
>    File "", line 1, in 
> WindowsError: [Error 123] The filename, directory name, or volume label  
> syntax is incorrect: 'C:\temp\\my test'
>
> --
> Kam-Hung Soh http://kamhungsoh.com/blog";>Software Salariman

>>> os.chdir('C:/')
>>> os.getcwd()
'C:\\'
>>> os.chdir('C:\temp\my test')
Traceback (most recent call last):
  File "", line 1, in 
WindowsError: [Error 123] The filename, directory name, or volume
label syntax is incorrect: 'C:\temp\\my test'
>>> os.chdir('C:/temp/my test')
>>> os.getcwd()
'C:\\temp\\my test'

Windoze works fine if you hand it forward slashes.

>>> os.chdir('C:/')
>>> os.chdir(os.path.join('C:','temp','my test'))
>>> os.getcwd()
'C:\\temp\\my test'

And joining your target with os.path.join works to.
--
http://mail.python.org/mailman/listinfo/python-list


Re: python vs. grep

2008-05-07 Thread Anton Slesarev
I try to save my time not cpu cycles)

I've got file which I really need to parse:
-rw-rw-r--  1 xxx  xxx  3381564736 May  7 09:29 bigfile

That's my results:

$ time grep "python" bigfile | wc -l
2470

real0m4.744s
user0m2.441s
sys 0m2.307s

And python scripts:

import sys

if len(sys.argv) != 3:
   print 'grep.py  '
   sys.exit(1)

f = open(sys.argv[2],'r')

print ''.join((line for line in f if sys.argv[1] in line)),

$ time python grep.py "python" bigfile | wc -l
2470

real0m37.225s
user0m34.215s
sys 0m3.009s

Second script:

import sys

if len(sys.argv) != 3:
   print 'grepwc.py  '
   sys.exit(1)

f = open(sys.argv[2],'r',1)

print sum((1 for line in f if sys.argv[1] in line)),


time python grepwc.py "python" bigfile
2470

real0m39.357s
user0m34.410s
sys 0m4.491s

40 sec and 5. This is really sad...

That was on freeBSD.



On windows cygwin.

Size of bigfile is ~50 mb

$ time grep "python" bigfile | wc -l
51

real0m0.196s
user0m0.169s
sys 0m0.046s

$ time python grepwc.py "python" bigfile
51

real0m25.485s
user0m2.733s
sys 0m0.375s

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


Re: Python MIDI in 2008

2008-05-07 Thread Paul Boddie
On 6 Mai, 11:43, Max M <[EMAIL PROTECTED]> wrote:
>

[Python Midi]

> It does not have real time support even though I did write it with that
> support in mind. I just never got around to write it as I did not need
> it myself.
>
> I also developed it on Windows and I found it to be a bore to get real
> time midi working.
>
> It would probably be easier now that I am on Linux.

I was previously quite interested in getting MIDI output working for a
game I wrote, and I suppose that the Python Midi package would have
been of interest (with pygame probably handling the interface to the
hardware), but given the bizarre kernel module gymnastics required to
support real-time output (and I still don't know if my sound hardware
actually supports MIDI directly or not), I decided in the end to use
timidity to generate normal audio files and to send those through the
sound system instead. Of course, that more or less eliminates any real-
time aspects.

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


Re: python vs. grep

2008-05-07 Thread Ville Vainio
On May 6, 10:42 pm, Anton Slesarev <[EMAIL PROTECTED]> wrote:

> flines = (line for line in f if pat.search(line))

What about re.findall() / re.finditer() for the whole file contents?

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


Re: Why don't generators execute until first yield?

2008-05-07 Thread Martin Sand Christensen
> "Ian" == Ian Kelly <[EMAIL PROTECTED]> writes:
Ian> Isn't lazy evaluation sort of the whole point of replacing a list
Ian> with an iterator? Besides which, running up to the first yield when
Ian> instantiated would make the generator's first iteration
Ian> inconsistent with the remaining iterations.

That wasn't my idea, although that may not have come across quite
clearly enough. I wanted the generator to immediately run until right
before the first yield so that the first call to next() would start with
the first yield.

My objection is that generators _by default_ have different semantics
than the rest of the language. Lazy evaluation as a concept is great for
all the benefits it can provide, but, as I've illustrated, strictly lazy
evaluation semantics can be somewhat surprising at times and lead to
problems that are hard to debug if you don't constantly bear the
difference in mind. In this respect, it seems to me that my suggestion
would be an improvement. I'm not any kind of expert on languages,
though, and I may very well be missing a part of the bigger picture that
makes it obvous why things should be as they are.

As for code to slightly change the semantics of generators, that doesn't
really address the issue as I see it: if you're going to apply such code
to your generators, you're probably doing it exactly because you're
aware of the difference in semantics, and you're not going to be
surprised by it. You may still want to change the semantics, but for
reasons that are irrelevant to my point.

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


Re: License selection for free software

2008-05-07 Thread Paul Boddie
On 6 Mai, 19:22, [EMAIL PROTECTED] (Ville M. Vainio) wrote:
> Excuse the long post.

Excuse the cherry-picking from your long post. ;-)

[...]

> Also, you can do what Paul Boddie did - fork the project, or maintain
> patches that are under LGPL. With a liberal license, you have that
> privilege.

Sure, my patches were LGPL, if you'd like to consider it that way, but
I have to point out that the derived work maintained by me became LGPL
as a result - I wasn't offering the non-Paul Boddie version under the
original licence as well. Now, I did leave a fair amount of
information about the heritage of the code, so that anyone who is
scared of the LGPL could just go and get the original work, but that
is probably your only viable option if you want to revert to the old
licensing.

[...]

> I don't think BSD/MIT like license really annoys anyone. Think python
> here ;-)

As some have pointed out, it can discourage people from contributing.
I've said many times before that some companies might not contribute
to a permissively licensed project because their competitors could
leverage the benefit in proprietary software, and I consider Linux and
the involvement of companies like IBM to be a reasonable example of
this.

[...]

> Not at all, it's a very practical thing related to all the
> intellectual property lawyerage in corporate setting. With Vellum, it
> doesn't matter a lot because most of the tools are only used in-house,
> but it would still be nice if you could just grab the code from
> somewhere without having to think about license at all, or considering
> whether any of this would ever be needed for something that involves
> selling stuff under proprietary license.

You can almost never just "grab the code from somewhere without having
to think about [the] license" since even permissive licences typically
have a list of conditions that must be observed. Certainly, they
aren't as demanding as those in copyleft licences, but by not
observing them you are infringing someone's copyright.

[...]

> Also, for some reason, GPL is used for evil (dual-licensing schemes -
> make money but still gain the open source mindshare, and possibly rack
> up free contributions to something that is your *commercial product*)
> more often than it's used for good (gcc, Linux kernel - prevent IP
> exploitation and ensure that all improvements are freely accessible).

The whole "evil" aspect of dual-licensing schemes is mostly to do with
copyright assignment (or the contribution agreement), not licensing,
although the licences typically employed obviously prevent the wider
community from making proprietary versions of the software, thus
creating the conditions for a dual-licensing business. That said, it's
easy to refuse to play along with such schemes if you're motivated:
just don't agree to assign your copyright to someone else, or don't
license your contributions under permissive licences (which
interestingly takes us back to the issue of Python contributions and
the associated list of acceptable licences).

These days, some companies are getting a lot of bad publicity about
their project governance: Sun seem to be getting continuous criticism
about the management of OpenOffice.org, and now that they've picked up
MySQL, they'll presumably be the target of criticism by people who had
to sign over their ownership of patches in order to feed the MySQL
corporate machine. But again, this isn't a sign that the licence was
the problem: it's what people were asked to do with the copyright
which effectively negated the benefits of the licence for those
wanting to keep the software free and open.

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


FreeBSD KeyboardInterrupt not captured

2008-05-07 Thread radim . marek
Hi Guys,

during testing of my project on FreeBSD I've discovered stange
'feature' of time.sleep(). It works if single thread is running, but
when multi-threaded, the SIGINT signal seems not to be handled in same
way.

I've found three discussion about similar behavior with os.system()
but so far none of the suggested patches worked.

I've limited test to following code:

import time
import sys
import threading

class MyThread(threading.Thread):
def __init__(self):
super(MyThread, self).__init__()
self.start()

def run(self):
while True:
try:
time.sleep(10)
except KeyboardInterrupt:
print 'thread keyboard interrupt'

def main():
my = MyThread()

while True:
try:
time.sleep(5)
except KeyboardInterrupt:
print 'got it'

if __name__ == '__main__':
main()


Any suggestions?

Best regards,

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


PHP + TinyButStrong Python replacement

2008-05-07 Thread pistacchio
hi! i'm a php user and a python programmer. i'd love to use python for 
my server side needs but i can't seem to find what i'm looking for. for 
most of my php work i use mysql and tinyButStrong 
(http://www.tinybutstrong.com) which is a very lightweight template 
engine that offers powerful functionalities. you insert TBS tags in web 
pages like:


 [var.x] 

and it replaces [var.x] with the value of global variable x. it also 
makes blocks (and nested blocks) easy to implement:


 [blk1;block=begin] [blk1.val] 
[blk1;block=end] 


in the previous code it cycles throu all the values of the array blk1.

it does many more things, like htlm escaping, url and js encoding etc, 
conditional displaying etc, but it is not more confusing that inserting 
pieces of code into the HTML (aka: littering the code and kissing 
goodbye to the code/presentation separation). it comes in the form of a 
single file with a single class that you can easily include in the code 
and go.


now, i've searched the net and it seems full of python-based frameworks 
for doing server side scripting and templating, but none that suits my 
needs.


   1. i like writing code and i like control. i mean, open up the 
simplest text editor and write in it. i don't want something that is 
command-line driven or that writes code for me like ">>> 
makePagesFromThisDatabase()".
   2. i want something very lightweight. i don't want dozen of options, 
pre-made blogging parts ecc. i just need a good non invasive template 
engine and the basic functions for server side scripting, like session 
managing, request parsing, functions to manipulate html code (encodings etc)
   3. i don't want to beg my hosting provider to install the libraries. 
a simple include file should do the work.
   4. object oriented programming is not required (better: i prefer 
plain old procedural programming).


any help? thanks in advance
--
http://mail.python.org/mailman/listinfo/python-list


Re: License selection for free software

2008-05-07 Thread D'Arcy J.M. Cain
On 06 May 2008 23:00:01 -0700
Paul Rubin <"http://phr.cx"@NOSPAM.invalid> wrote:
> "Matt Porter" <[EMAIL PROTECTED]> writes:
> > > Python's non-GPL license certainly is annoying to some of us.
> > I'm intrigued - how can it be annoying?
> 
> It means GPL'd contributions can't be included in the main Python distro.

That's exactly what makes the GPL annoying to some of us.  It just
depends on your point of view.

-- 
D'Arcy J.M. Cain <[EMAIL PROTECTED]> |  Democracy is three wolves
http://www.druid.net/darcy/|  and a sheep voting on
+1 416 425 1212 (DoD#0082)(eNTP)   |  what's for dinner.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Why don't generators execute until first yield?

2008-05-07 Thread Martin Sand Christensen
> "Duncan" == Duncan Booth <[EMAIL PROTECTED]> writes:
[...]
Duncan> Now try:
Duncan> 
Duncan>for command in getCommandsFromUser():
Duncan>print "the result of that command was", execute(command)
Duncan> 
Duncan> where getCommandsFromUser is a greedy generator that reads from stdin, 
Duncan> and see why generators don't work that way.

I don't see a problem unless the generator isn't defined where it's
going to be used. In other similar input bound use cases, such as the
generator iterating over a query result set in my original post, I see
even less of a problem. Maybe I'm simply daft and you need to spell it
out for me. :-)

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


Re: Scanning through Windows registry...

2008-05-07 Thread Unknown Hero
Thank you, I think I can manage now. It's nice that you could spare
some time to help me in this, Tim. People like you make the world a
better place :)

I'll post my code here once I have time to write it, currently I'm
rather busy. That is merely for optimization suggestions and for
others who might need the same sort of code I did.


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


Re: Why don't generators execute until first yield?

2008-05-07 Thread Duncan Booth
Martin Sand Christensen <[EMAIL PROTECTED]> wrote:

>> "Duncan" == Duncan Booth <[EMAIL PROTECTED]> writes:
> [...]
> Duncan> Now try:
> Duncan> 
> Duncan>for command in getCommandsFromUser():
> Duncan>print "the result of that command was",
> execute(command) Duncan> 
> Duncan> where getCommandsFromUser is a greedy generator that reads
> from stdin, Duncan> and see why generators don't work that way.
> 
> I don't see a problem unless the generator isn't defined where it's
> going to be used. In other similar input bound use cases, such as the
> generator iterating over a query result set in my original post, I see
> even less of a problem. Maybe I'm simply daft and you need to spell it
> out for me. :-)

It does this:

>>> @greedy
def getCommandsFromUser():
while True:
yield raw_input('Command?')


>>> for cmd in getCommandsFromUser():
print "that was command", cmd


Command?hello
Command?goodbye
that was command hello
Command?wtf
that was command goodbye
Command?

Traceback (most recent call last):
  File "", line 1, in 
for cmd in getCommandsFromUser():
  File "", line 11, in delayed
for value in it:
  File "", line 4, in getCommandsFromUser
yield raw_input('Command?')
KeyboardInterrupt
--
http://mail.python.org/mailman/listinfo/python-list


Re: Why don't generators execute until first yield?

2008-05-07 Thread Marco Mariani

Duncan Booth wrote:


It does this:


@greedy

def getCommandsFromUser():
while True:
yield raw_input('Command?')



for cmd in getCommandsFromUser():

print "that was command", cmd


Command?hello
Command?goodbye
that was command hello
Command?wtf
that was command goodbye
Command?



Not here..


In [7]: def getCommandsFromUser():
while True:
yield raw_input('Command?')
   ...:
   ...:

In [10]: for cmd in getCommandsFromUser(): print "that was command", cmd
   :
Command?hi
that was command hi
Command?there
that was command there
Command?wuwuwuw
that was command wuwuwuw
Command?
--
http://mail.python.org/mailman/listinfo/python-list


Some issue with right click in TreeCtrl

2008-05-07 Thread tarun
Hello All,

Please find the code for a simple wx.TreeCtrl code. Whenever I right click
on any item in the Tree, I see the function, 'OnSelChanged' gets called
twice.

What I've just done is that I've associated the function 'OnRightClick' with
wx.EVT_TREE_ITEM_RIGHT_CLICK. And in this function, I say
self.tree.SelectItem(evt.GetItem(),True) to select the item and then so some
action for right click.

Can any one help.

Thanks & Regards,
Tarun

*Please find the code in the attachment and also below:-*

import wx
tests = ["All Tests",
  ["Suite1",
"test01",
 "test02",
 ["suite2","test03","test04"],
"test05",
  ],
  ["Suite3",
"test06",
"test07"
  ],
  ["Suite4",
"test08",
"test09"
  ],
  "test10",
  "test11",
]
class TestFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, title="Simple Tree", size=(400,500))
# Create the tree
self.tree = wx.TreeCtrl(self)
# Add a root node
root = self.tree.AddRoot(tests[0])
# Add nodes from our data set
self.AddTreeNodes(root, tests, 0)
# Bind some interesting events
self.Bind(wx.EVT_TREE_SEL_CHANGED, self.OnSelChanged, self.tree)
self.Bind(wx.EVT_TREE_ITEM_RIGHT_CLICK, self.OnRightClick,
self.tree)
# Expand the first level
self.tree.Expand(root)

def AddTreeNodes(self, father, aTestList,count):
if type(aTestList) == type([]):
l = len(aTestList)
i = 0
while i < l:
if i == 0:
if count ==1:
father = self.tree.AppendItem(father, aTestList[i])
else:
self.AddTreeNodes(father, aTestList[i],
1)
i = i + 1
if type(aTestList) == type(""):
self.tree.AppendItem(father, aTestList)

def OnRightClick(self, evt):
self.tree.SelectItem(evt.GetItem(),True)
print 'In OnRightClick Function...',self.GetItemText(evt.GetItem())

def GetItemText(self, item):
if item:
return self.tree.GetItemText(item)
else:
return ""

def OnSelChanged(self, evt):
print "OnSelChanged:   ", self.GetItemText(evt.GetItem())

app = wx.PySimpleApp(redirect=True)
frame = TestFrame()
frame.Show()
app.MainLoop()
import wx

tests = ["All Tests", 
["Suite1",
 "test01",
 "test02",
 ["suite2","test03","test04"],
 "test05", 
],
["Suite3",
 "test06",  
 "test07"
],
["Suite4",  
 "test08",
 "test09"
],  
"test10",
"test11",
]

class TestFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, title="Simple Tree", size=(400,500))

# Create the tree
self.tree = wx.TreeCtrl(self)

# Add a root node   
root = self.tree.AddRoot(tests[0])

# Add nodes from our data set
self.AddTreeNodes(root, tests, 0)

# Bind some interesting events
self.Bind(wx.EVT_TREE_SEL_CHANGED, self.OnSelChanged, self.tree)
self.Bind(wx.EVT_TREE_ITEM_RIGHT_CLICK, self.OnRightClick, self.tree)

# Expand the first level
self.tree.Expand(root)

def AddTreeNodes(self, father, aTestList,count):
if type(aTestList) == type([]): 
l = len(aTestList)
i = 0
while i < l:
if i == 0: 
if count ==1:
father = self.tree.AppendItem(father, aTestList[i])
else:
self.AddTreeNodes(father, aTestList[i], 1) 
i = i + 1

if type(aTestList) == type(""):
self.tree.AppendItem(father, aTestList)

def OnRightClick(self, evt):
self.tree.SelectItem(evt.GetItem(),True) 
print 'In OnRightClick Function...',self.GetItemText(evt.GetItem())

def GetItemText(self, item):
if item:
return self.tree.GetItemText(item)
else:
return "" 
  
def OnSelChanged(self, evt):
print "OnSelChanged:   ", self.GetItemText(evt.GetItem())

app = wx.PySimpleApp(redirect=True)
frame = TestFrame()
frame.Show()
app.MainLoop()--
http://mail.python.org/mailman/listinfo/python-list

Re: mxTexTools (Re: using sqlite3 - execute vs. executemany; committing ...)

2008-05-07 Thread Vlastimil Brom
2008/5/7, M.-A. Lemburg <[EMAIL PROTECTED]>:
>
> On 2008-05-07 00:07, Vlastimil Brom wrote:
>
> > Thanks for reminding me about
> > the mxTextTools; I looked at this package very quickly several months
> > ago and it seemed quite
> > complex and heavy-weight, but maybe I will reconsider this after some
> > investigation ...
> >
>
> mxTextTools gives you almost full C speed while still being programmable
> in Python and without a compiler.
>
> It is a low level parsing engine. Here's talk I gave on mxTextTools
> last year:
>
>
> http://www.egenix.com/library/presentations/EuroPython2007-Parsing-Languages-with-mxTextTools/
>
> If you're looking for ways to hide the complexity, you could try
> SimpleParse (which uses mxTextTools for the parsing, but provides a
> grammar based front-end).
>
> --
> Marc-Andre Lemburg
> eGenix.com
>
> Professional Python Services directly from the Source  (#1, May 07 2008)
> >>> Python/Zope Consulting and Support ...http://www.egenix.com/
> >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/
> >>> mxODBC, mxDateTime, mxTextTools ...http://python.egenix.com/
> 
>
>  Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! 
>
>
>   eGenix.com Software, Skills and Services GmbH  Pastor-Loeh-Str.48
>D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg
>   Registered at Amtsgericht Duesseldorf: HRB 46611
>

Thank you very much for the info and for the helpful references, Marc-Andre,
I'll definitely have to take a closer look at mxTextTools, thanks for making
it available.

Greetings,
 Vlasta
--
http://mail.python.org/mailman/listinfo/python-list

Learning question...

2008-05-07 Thread swapsun
Any idea why the following program does not work? I was learning IO on
Python and the following generates a TypeError: range() integer end
argument expected, got str.
I am a beginner.


# print input name (str k), j times using raw_input

def hello():
j=raw_input("Please type in the number of times you want to print
")
k=raw_input("Please type in your name ")
printname(j,k)

def printname(j,k):
  for i in range(j):
print ("Hello %s" % k)

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


Re: Why don't generators execute until first yield?

2008-05-07 Thread Marco Mariani

Marco Mariani wrote:


Not here..


Oh, sorry, I obviously didn't see the @greedy decorator amongst all the 
quoting levels.


Anyway, the idea doesn't make much sense to me :)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Why don't generators execute until first yield?

2008-05-07 Thread Duncan Booth
Marco Mariani <[EMAIL PROTECTED]> wrote:

> Duncan Booth wrote:
> 
>> It does this:
>> 
> @greedy
>> def getCommandsFromUser():
>>  while True:
>>   yield raw_input('Command?')
>> 
>>   
> for cmd in getCommandsFromUser():
>>  print "that was command", cmd
>> 
>>  
>> Command?hello
>> Command?goodbye
>> that was command hello
>> Command?wtf
>> that was command goodbye
>> Command?
> 
> 
> Not here..
> 
> 
> In [7]: def getCommandsFromUser():
>  while True:
>  yield raw_input('Command?')
> ...:
> ...:
> 
> In [10]: for cmd in getCommandsFromUser(): print "that was command", 
cmd
> :
> Command?hi
> that was command hi
> Command?there
> that was command there
> Command?wuwuwuw
> that was command wuwuwuw
> Command?
> 

Perhaps if you'd copied all of my code (including the decorator that was 
the whole point of it)...

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


Re: Learning question...

2008-05-07 Thread Diez B. Roggisch
[EMAIL PROTECTED] wrote:

> Any idea why the following program does not work? I was learning IO on
> Python and the following generates a TypeError: range() integer end
> argument expected, got str.
> I am a beginner.

Because raw_input does return you as string which you need explicitly
convert to a number, e.g. doing

i = int(input)

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


Re: Why don't generators execute until first yield?

2008-05-07 Thread Marco Mariani

Duncan Booth wrote:

Perhaps if you'd copied all of my code (including the decorator that was 
the whole point of it)...


Sure, I missed the point. Python's > symbols become quoting levels and 
mess up messages.


Anyway, I would loathe to start execution of a generator before starting 
to iterate through it. Especially when generators are passed around.

The current behavior makes perfect sense.

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


Re: Learning question...

2008-05-07 Thread Thomas Woelz
On 7 maio, 09:25, [EMAIL PROTECTED] wrote:
> Any idea why the following program does not work? I was learning IO on
> Python and the following generates a TypeError: range() integer end
> argument expected, got str.
> I am a beginner.
>
> 
> # print input name (str k), j times using raw_input
>
> def hello():
> j=raw_input("Please type in the number of times you want to print
> ")
> k=raw_input("Please type in your name ")

# add this:
j = int(j)

> printname(j,k)
>
> def printname(j,k):
>   for i in range(j):
> print ("Hello %s" % k)
> 

theres too much whitespace in the printname function, try to stick
with 4 spaces (and no tabs) for each block
--
http://mail.python.org/mailman/listinfo/python-list


Re: Scanning through Windows registry...

2008-05-07 Thread Mike Driscoll
On May 7, 4:45 am, Tim Golden <[EMAIL PROTECTED]> wrote:
> In a spirit of being helpful... :)
>
> The code below (which I imagine every Windows programmer writes
> sometime in their Python life) mimics the os.walk functionality, yielding
> the key, subkeys, and values under a particular starting point in the
> registry. The "if __name__ == '__main__'" test run at the bottom does
> more-or-less what you were asking for originally, I think, converting
> some name to some other name wherever it appears.
>
> 
> import _winreg
>
> HIVES = {
>   "HKEY_LOCAL_MACHINE" : _winreg.HKEY_LOCAL_MACHINE,
>   "HKEY_CURRENT_USER" : _winreg.HKEY_CURRENT_USER,
>   "HKEY_CLASSES_ROOT" : _winreg.HKEY_CLASSES_ROOT,
>   "HKEY_USERS" : _winreg.HKEY_USERS,
>   "HKEY_CURRENT_CONFIG" : _winreg.HKEY_CURRENT_CONFIG
>
> }
>
> class RegKey:
>
>   def __init__ (self, name, key):
>      self.name = name
>      self.key = key
>
>   def __str__ (self):
>     return self.name
>
> def walk (top):
>   """walk the registry starting from the key represented by
>   top in the form HIVE\\key\\subkey\\..\\subkey and generating
>   key, subkey_names, values at each level.
>
>   key is a lightly wrapped registry key, including the name
>   and the HKEY object.
>   subkey_names are simply names of the subkeys of that key
>   values are 3-tuples containing (name, data, data-type).
>   See the documentation for _winreg.EnumValue for more details.
>   """
>   if "\\" not in top: top += "\\"
>   root, subkey = top.split ("\\", 1)
>   key = _winreg.OpenKey (HIVES[root], subkey, 0, _winreg.KEY_READ | 
> _winreg.KEY_SET_VALUE)
>
>   subkeys = []
>   i = 0
>   while True:
>     try:
>       subkeys.append (_winreg.EnumKey (key, i))
>       i += 1
>     except EnvironmentError:
>       break
>
>   values = []
>   i = 0
>   while True:
>     try:
>       values.append (_winreg.EnumValue (key, i))
>       i += 1
>     except EnvironmentError:
>       break
>
>   yield RegKey (top, key), subkeys, values
>
>   for subkey in subkeys:
>     for result in walk (top + "\\" + subkey):
>       yield result
>
> if __name__ == '__main__':
>   for key, subkey_names, values in walk 
> ("HKEY_LOCAL_MACHINE\\Software\\Python"):
>     print key
>     for (name, data, type) in values:
>       print "  ", name, "=>", data
>       if type == _winreg.REG_SZ and "TJG" in data:
>         _winreg.SetValueEx (key.key, name, 0, type, data.replace ("TJG", 
> "XYZ"))
>
> 
>
> TJG

This is pretty cool stuff, Tim. Of course, it would also seriously
screw up some programs if you decided to replace the wrong phrase.
Just a word of warning to the OP: be sure to make a backup of the
registry before doing something like this. Trying to fix a messed up
registry from the command line is not a fun way to spend the
afternoon.

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


Re: using sqlite3 - execute vs. executemany; committing ...

2008-05-07 Thread Vlastimil Brom
Hi David,
thanks for your suggestions.
The mentioned line of code is actually already a part of such
a searching method,  thus it is beeing called in a similar way you
suggested, but anyhow it catched my eye ...;  Thanks for the references to
different markup systems, I haven't known many
of them before - I wish I had found them some moths ago - my searches
were probably too specific.
I'll take a look at it and see, if something could be used or adapted for my
current code.

Greetings,
   Vlasta
--
http://mail.python.org/mailman/listinfo/python-list

Re: PHP + TinyButStrong Python replacement

2008-05-07 Thread Mike Driscoll
On May 7, 6:12 am, pistacchio <[EMAIL PROTECTED]> wrote:
> hi! i'm a php user and a python programmer. i'd love to use python for
> my server side needs but i can't seem to find what i'm looking for. for
> most of my php work i use mysql and tinyButStrong
> (http://www.tinybutstrong.com) which is a very lightweight template
> engine that offers powerful functionalities. you insert TBS tags in web
> pages like:
>
>  [var.x] 
>
> and it replaces [var.x] with the value of global variable x. it also
> makes blocks (and nested blocks) easy to implement:
>
>  [blk1;block=begin] [blk1.val]
> [blk1;block=end] 
>
> in the previous code it cycles throu all the values of the array blk1.
>
> it does many more things, like htlm escaping, url and js encoding etc,
> conditional displaying etc, but it is not more confusing that inserting
> pieces of code into the HTML (aka: littering the code and kissing
> goodbye to the code/presentation separation). it comes in the form of a
> single file with a single class that you can easily include in the code
> and go.
>
> now, i've searched the net and it seems full of python-based frameworks
> for doing server side scripting and templating, but none that suits my
> needs.
>
>     1. i like writing code and i like control. i mean, open up the
> simplest text editor and write in it. i don't want something that is
> command-line driven or that writes code for me like ">>>
> makePagesFromThisDatabase()".
>     2. i want something very lightweight. i don't want dozen of options,
> pre-made blogging parts ecc. i just need a good non invasive template
> engine and the basic functions for server side scripting, like session
> managing, request parsing, functions to manipulate html code (encodings etc)
>     3. i don't want to beg my hosting provider to install the libraries.
> a simple include file should do the work.
>     4. object oriented programming is not required (better: i prefer
> plain old procedural programming).
>
> any help? thanks in advance

Did you look at TurboGears or Django? TG uses Kid in the 1.x series
and Genshi in 2.x (I think) for templating purposes. There's also
Cheetah, one of the more powerful Python templating engines out there.

http://genshi.edgewall.org/
http://www.kid-templating.org/
http://www.cheetahtemplate.org/
http://turbogears.org/

Maybe those links will get you going.

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


Re: Learning question...

2008-05-07 Thread swapsun
On May 7, 8:36 am, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] wrote:
> > Any idea why the following program does not work? I was learning IO on
> > Python and the following generates a TypeError: range() integer end
> > argument expected, got str.
> > I am a beginner.
>
> Because raw_input does return you as string which you need explicitly
> convert to a number, e.g. doing
>
> i = int(input)
>
> Diez

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


Re: Learning question...

2008-05-07 Thread swapsun
On May 7, 8:42 am, Thomas Woelz <[EMAIL PROTECTED]> wrote:
> On 7 maio, 09:25, [EMAIL PROTECTED] wrote:
>
> > Any idea why the following program does not work? I was learning IO on
> > Python and the following generates a TypeError: range() integer end
> > argument expected, got str.
> > I am a beginner.
>
> > 
> > # print input name (str k), j times using raw_input
>
> > def hello():
> >     j=raw_input("Please type in the number of times you want to print
> > ")
> >     k=raw_input("Please type in your name ")
>
>     # add this:
>     j = int(j)
>
> >     printname(j,k)
>
> > def printname(j,k):
> >           for i in range(j):
> >                 print ("Hello %s" % k)
> > 
>
> theres too much whitespace in the printname function, try to stick
> with 4 spaces (and no tabs) for each block

Thanks very much for the advice. Will follow...
--
http://mail.python.org/mailman/listinfo/python-list


Re: Can't drag and drop onto .py in Windows XP?

2008-05-07 Thread Roger Upole

Sizer wrote:
>I have several python utils that look at sys.argv to get a list of
> filenames to process and mangle the files in various ways. If I have a
> bar.bat file in Windows XP then I can just drag foo.avi onto bar.bat and
> bar.bat gets called with foo.avi as an argument, everyone's happy. But if 
> I
> have a bar.py (or .pyw) and try to drag and drop foo.avi to it, I get a 
> big
> NO cursor and nothing happens.
>
> Now I can work around this by creating a _bar.bat and having the _bar.bat
> call bar.pyw with the filenames it was passed (this is obviously
> ridiculous). Or I can create a shortcut which has the target of
>   c:\python25\pythonw.exe c:\mybar\bar.pyw
> and that works, but makes telling people how to install my utilities on
> their computer a pain in the rear. It's just a little weird that I can't
> just drag and drop file names onto .pyw or .py files. Am I missing
> something here?
>
> Thanks for any help.

You can register a DropHandler for the Python file class.
Put this in a .reg file and merge it into the registry:

REGEDIT4

[HKEY_CLASSES_ROOT\Python.File\shellex\DropHandler]
@="{86C86720-42A0-1069-A2E8-08002B30309D}"


  Roger



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


Re: loading folder list from my mailbox in python

2008-05-07 Thread Mike Driscoll
On May 7, 1:15 am, [EMAIL PROTECTED] wrote:
> Hey everyone,
> I want to print the folder list of my mailbox using python (IMAP4), and
> with hierarchy, i.e. it should print all the names of the folders of my
> mailbox and the folders within them.
> Can anyone please help me with this.

Without knowing the backend, it's mostly a shot in the dark. Oh well.
I did some Google-Fu (which you would be wise to learn) and found the
following:

http://www.devshed.com/c/a/Python/Python-Email-Libraries-part-2-IMAP/
http://www.example-code.com/python/imap.asp
http://pypi.python.org/pypi/imap-utils/0.3
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52299

I think at least one of those will get you started. If you're talking
about communicating with Exchange, then you may have to use some win32
or ctypes methods.

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


Re: open filename with spaces in path

2008-05-07 Thread A.T.Hofkamp
On 2008-05-07, Chris <[EMAIL PROTECTED]> wrote:
 os.chdir('C:\temp\my test')
> Traceback (most recent call last):
>   File "", line 1, in 
> WindowsError: [Error 123] The filename, directory name, or volume
> label syntax is incorrect: 'C:\temp\\my test'

Python strings have \ escapes, such as \t, \n etc. Above you try to go to

C:emp\my test

and you are lucky that \m is not something special.


Either escape your back slashes ("C:\\temp\\my test") or use raw strings
(r"C:\temp\my test").

Sincerely,
Albert
--
http://mail.python.org/mailman/listinfo/python-list


Re: PHP + TinyButStrong Python replacement

2008-05-07 Thread Diez B. Roggisch
pistacchio wrote:

> Mike Driscoll ha scritto:
>> On May 7, 6:12 am, pistacchio <[EMAIL PROTECTED]> wrote:
>>> hi! i'm a php user and a python programmer. i'd love to use python for
>>> my server side needs but i can't seem to find what i'm looking for. for
>>> most of my php work i use mysql and tinyButStrong
>>> (http://www.tinybutstrong.com) which is a very lightweight template
>>> engine that offers powerful functionalities. you insert TBS tags in web
>>> pages like:
>>>
>>>  [var.x] 
>>>
>>> and it replaces [var.x] with the value of global variable x. it also
>>> makes blocks (and nested blocks) easy to implement:
>>>
>>>  [blk1;block=begin] [blk1.val]
>>> [blk1;block=end] 
>>>
>>> in the previous code it cycles throu all the values of the array blk1.
>>>
>>> it does many more things, like htlm escaping, url and js encoding etc,
>>> conditional displaying etc, but it is not more confusing that inserting
>>> pieces of code into the HTML (aka: littering the code and kissing
>>> goodbye to the code/presentation separation). it comes in the form of a
>>> single file with a single class that you can easily include in the code
>>> and go.
>>>
>>> now, i've searched the net and it seems full of python-based frameworks
>>> for doing server side scripting and templating, but none that suits my
>>> needs.
>>>
>>> 1. i like writing code and i like control. i mean, open up the
>>> simplest text editor and write in it. i don't want something that is
>>> command-line driven or that writes code for me like ">>>
>>> makePagesFromThisDatabase()".
>>> 2. i want something very lightweight. i don't want dozen of options,
>>> pre-made blogging parts ecc. i just need a good non invasive template
>>> engine and the basic functions for server side scripting, like session
>>> managing, request parsing, functions to manipulate html code (encodings
>>> etc)
>>> 3. i don't want to beg my hosting provider to install the libraries.
>>> a simple include file should do the work.
>>> 4. object oriented programming is not required (better: i prefer
>>> plain old procedural programming).
>>>
>>> any help? thanks in advance
>> 
> 
> hi, thanks for replaying
> 
>> Did you look at TurboGears or Django? TG uses Kid in the 1.x series
>> and Genshi in 2.x (I think) for templating purposes. There's also
>> Cheetah, one of the more powerful Python templating engines out there.
>> 
> 
> django is exacly the kind of giant i'm trying to avoid
> 
>> http://genshi.edgewall.org/
> 
> the first lines of the tutorial read:
> "First, make sure you have CherryPy 3.0.x installed"
> Now, cherrypy is something that is not properly "include a file and get
> going!"
>> http://www.kid-templating.org/
> 
> kid seems to have a non-linear approach, but i may give it a try
> 
>> http://www.cheetahtemplate.org/
> 
> cheetah was something that i already considered using. have i to
> "install" it or can i just import it?

You will need to install any of these. It is part of how python is designed.
Extendability comes with a price-tag.

 I don't know for sure, but I guess the cherrypy-requirement of genshi is
more for the tutorial, not for the templating itself.

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


Re: saving a webpage's links to the hard disk

2008-05-07 Thread Diez B. Roggisch
Jetus wrote:

> On May 4, 7:22 am, [EMAIL PROTECTED] wrote:
>> On May 4, 12:33 am, "Gabriel Genellina" <[EMAIL PROTECTED]>
>> wrote:
>>
>> > En Sun, 04 May 2008 01:33:45 -0300, Jetus <[EMAIL PROTECTED]>
>> > escribió:
>>
>> > > Is there a good place to look to see where I can find some code that
>> > > will help me to save webpage's links to the local drive, after I have
>> > > used urllib2 to retrieve the page?
>> > > Many times I have to view these pages when I do not have access to
>> > > the internet.
>>
>> > Don't reinvent the wheel and use wgethttp://en.wikipedia.org/wiki/Wget
>>
>> > --
>> > Gabriel Genellina
>>
>> A lot of the functionality is already present.
>>
>> import urllib
>> urllib.urlretrieve( 'http://python.org/', 'main.htm' )
>> from htmllib import HTMLParser
>> from formatter import NullFormatter
>> parser= HTMLParser( NullFormatter( ) )
>> parser.feed( open( 'main.htm' ).read( ) )
>> import urlparse
>> for a in parser.anchorlist:
>> print urlparse.urljoin( 'http://python.org/', a )
>>
>> Output snipped:
>>
>> ...http://python.org/psf/http://python.org/dev/http://python.org/links/http://python.org/download/releases/2.5.2http://docs.python.org/http://python.org/ftp/python/2.5.2/python-2.5.2.msi
>> ...
> 
> How can I modify or add to the above code, so that the file references
> are saved to specified local directories, AND the saved webpage makes
> reference to the new saved files in the respective directories?
> Thanks for your help in advance.

how about you *try* to do so - and if you have actual problems, you come
back and ask for help? Alternatively, there's always guru.com

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

Re: PHP + TinyButStrong Python replacement

2008-05-07 Thread pistacchio

Diez B. Roggisch ha scritto:

pistacchio wrote:


Mike Driscoll ha scritto:

On May 7, 6:12 am, pistacchio <[EMAIL PROTECTED]> wrote:

hi! i'm a php user and a python programmer. i'd love to use python for
my server side needs but i can't seem to find what i'm looking for. for
most of my php work i use mysql and tinyButStrong
(http://www.tinybutstrong.com) which is a very lightweight template
engine that offers powerful functionalities. you insert TBS tags in web
pages like:

 [var.x] 

and it replaces [var.x] with the value of global variable x. it also
makes blocks (and nested blocks) easy to implement:

 [blk1;block=begin] [blk1.val]
[blk1;block=end] 

in the previous code it cycles throu all the values of the array blk1.

it does many more things, like htlm escaping, url and js encoding etc,
conditional displaying etc, but it is not more confusing that inserting
pieces of code into the HTML (aka: littering the code and kissing
goodbye to the code/presentation separation). it comes in the form of a
single file with a single class that you can easily include in the code
and go.

now, i've searched the net and it seems full of python-based frameworks
for doing server side scripting and templating, but none that suits my
needs.

1. i like writing code and i like control. i mean, open up the
simplest text editor and write in it. i don't want something that is
command-line driven or that writes code for me like ">>>
makePagesFromThisDatabase()".
2. i want something very lightweight. i don't want dozen of options,
pre-made blogging parts ecc. i just need a good non invasive template
engine and the basic functions for server side scripting, like session
managing, request parsing, functions to manipulate html code (encodings
etc)
3. i don't want to beg my hosting provider to install the libraries.
a simple include file should do the work.
4. object oriented programming is not required (better: i prefer
plain old procedural programming).

any help? thanks in advance

hi, thanks for replaying


Did you look at TurboGears or Django? TG uses Kid in the 1.x series
and Genshi in 2.x (I think) for templating purposes. There's also
Cheetah, one of the more powerful Python templating engines out there.


django is exacly the kind of giant i'm trying to avoid


http://genshi.edgewall.org/

the first lines of the tutorial read:
"First, make sure you have CherryPy 3.0.x installed"
Now, cherrypy is something that is not properly "include a file and get
going!"

http://www.kid-templating.org/

kid seems to have a non-linear approach, but i may give it a try


http://www.cheetahtemplate.org/

cheetah was something that i already considered using. have i to
"install" it or can i just import it?


You will need to install any of these. It is part of how python is designed.
Extendability comes with a price-tag.



well, the problema is exacly that i'm looking for a python module, not 
for a python library.

most of the tasks i need are just:
1. on the shoulders of the existing standard cgi modules, automate an 
render easier the handling of things such as sessions and requests
2. on the shoulders of the existing standard regex module, have a simple 
but complete templating engine and html-related encoder

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


Re: Why don't generators execute until first yield?

2008-05-07 Thread castironpi
On May 7, 7:37 am, Marco Mariani <[EMAIL PROTECTED]> wrote:
> Duncan Booth wrote:
> > Perhaps if you'd copied all of my code (including the decorator that was
> > the whole point of it)...
>
> Sure, I missed the point. Python's > symbols become quoting levels and
> mess up messages.
>
> Anyway, I would loathe to start execution of a generator before starting
> to iterate through it. Especially when generators are passed around.
> The current behavior makes perfect sense.

Question:

>>> def f( ):
... print 0
... while 1:
... yield 1
...
>>> g= f( )
>>> g.next( )
0
1
>>> g.next( )
1
>>> g.next( )
1

This might fit the bill:

>>> def dropfirst( h ):
... h.next( )
... return h
...
>>> g= dropfirst( f( ) )
0
>>> g.next( )
1
>>> g.next( )
1
>>> g.next( )
1

However as dropfirst is dropping a value, both caller -and- cally have
to designate a/the exception.  Hold generators are better "first-
dropped", and you hold 'next' inherently causes side effects.  @greedy
(from earlier) frees the caller of a responsibility/obligation.

What can follow without a lead?

The definitions may lean harder on the 'generation' as prior to the
'next': generators inherently don't cause side effects.

Or hold, first-dropped is no exception:

>>> special= object( )
>>> def f( ):
... print 0
... yield special
... while 1:
... yield 1
...
>>> g= f( )
>>> g.next( )
0

>>> g.next( )
1
>>> g.next( )
1
>>> g.next( )
1
--
http://mail.python.org/mailman/listinfo/python-list


Re: PHP + TinyButStrong Python replacement

2008-05-07 Thread pistacchio

Mike Driscoll ha scritto:

On May 7, 6:12 am, pistacchio <[EMAIL PROTECTED]> wrote:

hi! i'm a php user and a python programmer. i'd love to use python for
my server side needs but i can't seem to find what i'm looking for. for
most of my php work i use mysql and tinyButStrong
(http://www.tinybutstrong.com) which is a very lightweight template
engine that offers powerful functionalities. you insert TBS tags in web
pages like:

 [var.x] 

and it replaces [var.x] with the value of global variable x. it also
makes blocks (and nested blocks) easy to implement:

 [blk1;block=begin] [blk1.val]
[blk1;block=end] 

in the previous code it cycles throu all the values of the array blk1.

it does many more things, like htlm escaping, url and js encoding etc,
conditional displaying etc, but it is not more confusing that inserting
pieces of code into the HTML (aka: littering the code and kissing
goodbye to the code/presentation separation). it comes in the form of a
single file with a single class that you can easily include in the code
and go.

now, i've searched the net and it seems full of python-based frameworks
for doing server side scripting and templating, but none that suits my
needs.

1. i like writing code and i like control. i mean, open up the
simplest text editor and write in it. i don't want something that is
command-line driven or that writes code for me like ">>>
makePagesFromThisDatabase()".
2. i want something very lightweight. i don't want dozen of options,
pre-made blogging parts ecc. i just need a good non invasive template
engine and the basic functions for server side scripting, like session
managing, request parsing, functions to manipulate html code (encodings etc)
3. i don't want to beg my hosting provider to install the libraries.
a simple include file should do the work.
4. object oriented programming is not required (better: i prefer
plain old procedural programming).

any help? thanks in advance




hi, thanks for replaying


Did you look at TurboGears or Django? TG uses Kid in the 1.x series
and Genshi in 2.x (I think) for templating purposes. There's also
Cheetah, one of the more powerful Python templating engines out there.



django is exacly the kind of giant i'm trying to avoid


http://genshi.edgewall.org/


the first lines of the tutorial read:
"First, make sure you have CherryPy 3.0.x installed"
Now, cherrypy is something that is not properly "include a file and get 
going!"



http://www.kid-templating.org/


kid seems to have a non-linear approach, but i may give it a try


http://www.cheetahtemplate.org/


cheetah was something that i already considered using. have i to 
"install" it or can i just import it?



http://turbogears.org/


same problem as with django!



Maybe those links will get you going.

Mike

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


Re: open filename with spaces in path

2008-05-07 Thread Chris
On May 7, 3:25 pm, "A.T.Hofkamp" <[EMAIL PROTECTED]> wrote:
> On 2008-05-07, Chris <[EMAIL PROTECTED]> wrote:
>
>  os.chdir('C:\temp\my test')
> > Traceback (most recent call last):
> >   File "", line 1, in 
> > WindowsError: [Error 123] The filename, directory name, or volume
> > label syntax is incorrect: 'C:\temp\\my test'
>
> Python strings have \ escapes, such as \t, \n etc. Above you try to go to
>
> C:emp\my test
>
> and you are lucky that \m is not something special.
>
> Either escape your back slashes ("C:\\temp\\my test") or use raw strings
> (r"C:\temp\my test").
>
> Sincerely,
> Albert

My personal preference is using backslashes, if it's something quick
or if it's something that will be sitting on a server in a dark corner
for a long time to just use os.path.join.  I've had neither of those 2
break on me. ;)
--
http://mail.python.org/mailman/listinfo/python-list


Re: PHP + TinyButStrong Python replacement

2008-05-07 Thread George Sakkis
On May 7, 9:40 am, pistacchio <[EMAIL PROTECTED]> wrote:

> Diez B. Roggisch ha scritto:
>
>
>
> > pistacchio wrote:
>
> >> Mike Driscoll ha scritto:
> >>> On May 7, 6:12 am, pistacchio <[EMAIL PROTECTED]> wrote:
>  hi! i'm a php user and a python programmer. i'd love to use python for
>  my server side needs but i can't seem to find what i'm looking for. for
>  most of my php work i use mysql and tinyButStrong
>  (http://www.tinybutstrong.com) which is a very lightweight template
>  engine that offers powerful functionalities. you insert TBS tags in web
>  pages like:
>
>   [var.x] 
>
>  and it replaces [var.x] with the value of global variable x. it also
>  makes blocks (and nested blocks) easy to implement:
>
>   [blk1;block=begin] [blk1.val]
>  [blk1;block=end] 
>
>  in the previous code it cycles throu all the values of the array blk1.
>
>  it does many more things, like htlm escaping, url and js encoding etc,
>  conditional displaying etc, but it is not more confusing that inserting
>  pieces of code into the HTML (aka: littering the code and kissing
>  goodbye to the code/presentation separation). it comes in the form of a
>  single file with a single class that you can easily include in the code
>  and go.
>
>  now, i've searched the net and it seems full of python-based frameworks
>  for doing server side scripting and templating, but none that suits my
>  needs.
>
>      1. i like writing code and i like control. i mean, open up the
>  simplest text editor and write in it. i don't want something that is
>  command-line driven or that writes code for me like ">>>
>  makePagesFromThisDatabase()".
>      2. i want something very lightweight. i don't want dozen of options,
>  pre-made blogging parts ecc. i just need a good non invasive template
>  engine and the basic functions for server side scripting, like session
>  managing, request parsing, functions to manipulate html code (encodings
>  etc)
>      3. i don't want to beg my hosting provider to install the libraries.
>  a simple include file should do the work.
>      4. object oriented programming is not required (better: i prefer
>  plain old procedural programming).
>
>  any help? thanks in advance
> >> hi, thanks for replaying
>
> >>> Did you look at TurboGears or Django? TG uses Kid in the 1.x series
> >>> and Genshi in 2.x (I think) for templating purposes. There's also
> >>> Cheetah, one of the more powerful Python templating engines out there.
>
> >> django is exacly the kind of giant i'm trying to avoid
>
> >>>http://genshi.edgewall.org/
> >> the first lines of the tutorial read:
> >> "First, make sure you have CherryPy 3.0.x installed"
> >> Now, cherrypy is something that is not properly "include a file and get
> >> going!"
> >>>http://www.kid-templating.org/
> >> kid seems to have a non-linear approach, but i may give it a try
>
> >>>http://www.cheetahtemplate.org/
> >> cheetah was something that i already considered using. have i to
> >> "install" it or can i just import it?
>
> > You will need to install any of these. It is part of how python is designed.
> > Extendability comes with a price-tag.
>
> well, the problema is exacly that i'm looking for a python module, not
> for a python library.

What does it matter if it's a single file or a dozen under a package ?
"Installation" for pure Python packages can be as simple as copying
the package under any directory in your PYTHONPATH.

Check out Mako (http://www.makotemplates.org/), it's pretty powerful
and fast.

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


Re: Generate labels for a multi-level outline

2008-05-07 Thread castironpi
'''
On May 6, 4:43 pm, [EMAIL PROTECTED] honoring:

>>> a.next( )
( "I", )
>>> a.throw( up )
( "I", "A" )
>>> a.next( )
( "I", "B" )
>>> a.next( )
( "I", "C" )
>>> a.throw( down )
( "II", )
'''

#funny declaration
class up( Exception ): pass
class down( Exception ): pass

def outline( ):
stack= [ 1 ]
while 1:
try:
yield stack
stack[ -1 ]+= 1
except up:
stack.append( 1 )
except down:
stack.pop( -1 )
stack[ -1 ]+= 1

a= outline( )
print a.next( )
print a.throw( up )
print a.next( )
print a.next( )
print a.throw( down )
print a.throw( up )
print a.throw( up )
print a.next( )
print a.next( )
print a.throw( down )

##output:

[1]
[1, 1]
[1, 2]
[1, 3]
[2]
[2, 1]
[2, 1, 1]
[2, 1, 2]
[2, 1, 3]
[2, 2]

##

cf.

formatter.NullFormatter.format_counter
formatter.NullFormatter.format_letter
formatter.NullFormatter.format_roman
--
http://mail.python.org/mailman/listinfo/python-list


comparing dictionaries

2008-05-07 Thread brad
I want to compare two dicts that should have identical info just in a 
different data structure. The first dict's contents look like this. It 
is authoritative... I know for sure it has the correct key value pairs:


{'001' : '01'}

The second dict's contents are like this with a tuple instead of a 
string for the key:


{('This is one', '001'): '01'}

Pseudo Code:
for key, value in first_dict.iteritems():
  # How do I do the following line?
  if key not in second_dict or if it is, but has has the wrong value, 
then let me know


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


What is the purpose of ptyhon in Windows

2008-05-07 Thread [EMAIL PROTECTED]
hi All,
I have no idea why I need to learn a new scripting language,
nothing much to the sytnax,
I need to understand what could be the prupose of another scripting
language

Cna you please help me with this,
Is there a possibilty to work on bigger projects with Python
--
http://mail.python.org/mailman/listinfo/python-list


Pydev 1.3.16 Released

2008-05-07 Thread Fabio Zadrozny
Hi All,

Pydev and Pydev Extensions 1.3.16 have been released

Details on Pydev Extensions: http://www.fabioz.com/pydev
Details on Pydev: http://pydev.sf.net
Details on its development: http://pydev.blogspot.com

Release Highlights in Pydev Extensions:
-

* Code Analysis: __path__ Not correctly found on some situations.
* Local rename (ctrl+2+r): Positions correctly ordered for tabbing.


Release Highlights in Pydev:
--

* Interactive console: help() works
* Interactive console: context information showing in completions
* Interactive console: backspace will also delete the selected text
* Interactive console: ESC does not close the console when in floating
mode anymore
* Code completion: calltips context info correctly made 'bold'
* Code completion: variables starting with '_' do not come in import *
* Code completion: can be requested for external files (containing system info)
* Code completion: fixed recursion condition
* Code completion: egg file distributed with dll that has a source
module with the same name only with a __bootstrap__ method now loads
the dll instead of the source module (e.g.: numpy egg)
* Debugger: Step over/Step return can now execute with untraced frames
(much faster)
* Debugger: Problem when handling thread that had no context traced
and was directly removed.
* Launching: F9 will reuse an existing launch instead of creating a
new one every time
* Launching: The default launch with Ctrl+F11 will not ask again for
the launch associated with a file (for new launches -- old launches
should be deleted)
* Project Explorer: fixed integration problems with CDT (and others)
* Launch: console encoding passed as environment variable (no longer
written to the install location)
* More templates for "surround with" (Ctrl+1)
* Previous/next method could match 'class' and 'def' on invalid location
* Outline: Assign with multiple targets is recognized
* Bug fix for pydev package explorer when refreshed element parent was null



What is PyDev?
---

PyDev is a plugin that enables users to use Eclipse for Python and
Jython development -- making Eclipse a first class Python IDE -- It
comes with many goodies such as code completion, syntax highlighting,
syntax analysis, refactor, debug and many others.


Cheers,

-- 
Fabio Zadrozny
--
Software Developer

ESSS - Engineering Simulation and Scientific Software
http://www.esss.com.br

Pydev Extensions
http://www.fabioz.com/pydev

Pydev - Python Development Enviroment for Eclipse
http://pydev.sf.net
http://pydev.blogspot.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: comparing dictionaries

2008-05-07 Thread cokofreedom
On May 7, 4:08 pm, brad <[EMAIL PROTECTED]> wrote:
> I want to compare two dicts that should have identical info just in a
> different data structure. The first dict's contents look like this. It
> is authoritative... I know for sure it has the correct key value pairs:
>
> {'001' : '01'}
>
> The second dict's contents are like this with a tuple instead of a
> string for the key:
>
> {('This is one', '001'): '01'}
>
> Pseudo Code:
> for key, value in first_dict.iteritems():
># How do I do the following line?
>if key not in second_dict or if it is, but has has the wrong value,
> then let me know

Well

for k, v in first_dict.items():
  if k not in second_dict or k in second_dict and k[v] !=
second_dict[k]:
let you know?
--
http://mail.python.org/mailman/listinfo/python-list


Re: PHP + TinyButStrong Python replacement

2008-05-07 Thread pistacchio

George Sakkis ha scritto:

On May 7, 9:40 am, pistacchio <[EMAIL PROTECTED]> wrote:


Diez B. Roggisch ha scritto:




pistacchio wrote:

Mike Driscoll ha scritto:

On May 7, 6:12 am, pistacchio <[EMAIL PROTECTED]> wrote:

hi! i'm a php user and a python programmer. i'd love to use python for
my server side needs but i can't seem to find what i'm looking for. for
most of my php work i use mysql and tinyButStrong
(http://www.tinybutstrong.com) which is a very lightweight template
engine that offers powerful functionalities. you insert TBS tags in web
pages like:
 [var.x] 
and it replaces [var.x] with the value of global variable x. it also
makes blocks (and nested blocks) easy to implement:
 [blk1;block=begin] [blk1.val]
[blk1;block=end] 
in the previous code it cycles throu all the values of the array blk1.
it does many more things, like htlm escaping, url and js encoding etc,
conditional displaying etc, but it is not more confusing that inserting
pieces of code into the HTML (aka: littering the code and kissing
goodbye to the code/presentation separation). it comes in the form of a
single file with a single class that you can easily include in the code
and go.
now, i've searched the net and it seems full of python-based frameworks
for doing server side scripting and templating, but none that suits my
needs.
1. i like writing code and i like control. i mean, open up the
simplest text editor and write in it. i don't want something that is
command-line driven or that writes code for me like ">>>
makePagesFromThisDatabase()".
2. i want something very lightweight. i don't want dozen of options,
pre-made blogging parts ecc. i just need a good non invasive template
engine and the basic functions for server side scripting, like session
managing, request parsing, functions to manipulate html code (encodings
etc)
3. i don't want to beg my hosting provider to install the libraries.
a simple include file should do the work.
4. object oriented programming is not required (better: i prefer
plain old procedural programming).
any help? thanks in advance

hi, thanks for replaying

Did you look at TurboGears or Django? TG uses Kid in the 1.x series
and Genshi in 2.x (I think) for templating purposes. There's also
Cheetah, one of the more powerful Python templating engines out there.

django is exacly the kind of giant i'm trying to avoid

http://genshi.edgewall.org/

the first lines of the tutorial read:
"First, make sure you have CherryPy 3.0.x installed"
Now, cherrypy is something that is not properly "include a file and get
going!"

http://www.kid-templating.org/

kid seems to have a non-linear approach, but i may give it a try

http://www.cheetahtemplate.org/

cheetah was something that i already considered using. have i to
"install" it or can i just import it?

You will need to install any of these. It is part of how python is designed.
Extendability comes with a price-tag.

well, the problema is exacly that i'm looking for a python module, not
for a python library.


What does it matter if it's a single file or a dozen under a package ?
"Installation" for pure Python packages can be as simple as copying
the package under any directory in your PYTHONPATH.



well, it doesn't matter if it's a single file or a package, but it 
_does_ matter if you have to put them under the path where python is 
installed because, in a typical shared web hosting environment (such the 
one that i use) you don't have access to system directories.



Check out Mako (http://www.makotemplates.org/), it's pretty powerful
and fast.


woudl you suggest mako over cheetah?



George

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


Re: What is the purpose of ptyhon in Windows

2008-05-07 Thread cokofreedom
On May 7, 4:08 pm, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]>
wrote:
> hi All,
> I have no idea why I need to learn a new scripting language,
> nothing much to the sytnax,
> I need to understand what could be the prupose of another scripting
> language
>
> Cna you please help me with this,
> Is there a possibilty to work on bigger projects with Python

Answer, reasons to learn another scripting language;
It provides different techniques to problems,
It is eaiser and clearer to write with a strong community to aid
developers,
Problems can be scaled,
There are a lot of high scale Python projects.

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


Re: Scanning through Windows registry...

2008-05-07 Thread Tim Golden

Mike Driscoll wrote:

On May 7, 4:45 am, Tim Golden <[EMAIL PROTECTED]> wrote:

In a spirit of being helpful... :)


[... snip registry walker ...]


This is pretty cool stuff, Tim. Of course, it would also seriously
screw up some programs if you decided to replace the wrong phrase.
Just a word of warning to the OP: be sure to make a backup of the
registry before doing something like this. Trying to fix a messed up
registry from the command line is not a fun way to spend the
afternoon.


Good point, Mike. In a spirit of being even more helpful... the _winreg
module includes the functions SaveKey and LoadKey so as a crude
backup mechanism, you could do this:


import time
import _winreg
import win32api
import win32security

#
# You need to have SeBackupPrivilege enabled for this to work
#
priv_flags = win32security.TOKEN_ADJUST_PRIVILEGES | win32security.TOKEN_QUERY
hToken = win32security.OpenProcessToken (win32api.GetCurrentProcess (), 
priv_flags)
privilege_id = win32security.LookupPrivilegeValue (None, "SeBackupPrivilege")
win32security.AdjustTokenPrivileges (hToken, 0, [(privilege_id, 
win32security.SE_PRIVILEGE_ENABLED)])

root = _winreg.OpenKey (_winreg.HKEY_LOCAL_MACHINE, r"Software\Python\TEST")
#
# This will fail if the file already exists so make it uniqueish
#
_winreg.SaveKey (root, "c:/temp/HKLM_Software_Python-%s.reg" %  time.strftime 
("%Y%m%d-%H%M%S"))



Note that the file which this creates is *not* the same as a .reg file which the 
File > Export menu
option provides from within the registry editor. (In fact, I shouldn't really 
have called it .reg; call
it something else). It can be reloaded by the _winreg.LoadKey function -- which I notice is incorrectly 
named RegLoadKey in the docs after the underlying API call. The docs note that SeRestorePrivilege is 
required for this action, the counterpart to SeBackupPrivilege.


TJG

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


Re: comparing dictionaries

2008-05-07 Thread Carsten Haese

brad wrote:
I want to compare two dicts that should have identical info just in a 
different data structure. The first dict's contents look like this. It 
is authoritative... I know for sure it has the correct key value pairs:


{'001' : '01'}

The second dict's contents are like this with a tuple instead of a 
string for the key:


{('This is one', '001'): '01'}


It looks like extracting key[1] from each key of the second dictionary 
should yield the keys of the first dictionary. If that is the case, then 
the following should do it:


d1 = {'001':'01', '002':'02'}
d2 = {('This is one', '001'): '01', ('This is two', '002'): '02'}

if d1 == dict( zip( (k[1] for k in d2.keys()), d2.values() ) ):
print "They're 'equal'."

HTH,

--
Carsten Haese
http://informixdb.sourceforge.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: Are rank noobs tolerated, here?

2008-05-07 Thread notbob
On 2008-05-06, hdante <[EMAIL PROTECTED]> wrote:

>  When you have a problem with your code, always post here the complete
> code and a complete execution. For example:

I'll keep this example.  Thnx.


>  /--\  glued
> |  bruce   | --> 42
>  \--/
>
>  When you use a stamp, it returns what it's glued on:
>
> >>> bruce = 42  # glue a stamp
> >>> print bruce # use the stamp
>  42

>  'bruce' is a string (notice the quotes). In this case bruce is glued
> to 'bruce':
>
>  /--\  glued
> |  bruce   | --> 'bruce'
>  \--/

The light is dawning.  

>  Stupid. Not really. :-) I'd rather say that the problem is the book.

Well, me too, of course.  ;)  

> The book is just another introduction to programming. There's no
> special attempt to make the reader learn to think like a computer
> scientist.

Apparently, and I understand.  It's hard for someone who is very
knowledgable on a subject to remain in "explain it like they're 5 yrs old"
mode.  It's tedious and time consuming.

>> How am I supposed to get the original def to work?  I've yet to figure out

>  file myfile.py:
> ---
> def print_twice(bruce):
>   print bruce, bruce
>
> print_twice('bruce')
> print_twice(2)
> ---
>
> execution:
> ---
> $ python myfile.py
> bruce bruce
> 2 2

BINGO!  (and it worked (after I got the indents right))

>  Finally, you don't understand something, ask again.

Thank you.  I really do appreciate your taking the time to break it down
so completely.  I found another python book (A Byte of Python) that keeps it
simple enough for me.  I'm not really a programmer, but I decided to do
something to challenge this old geezer brain and figured this would keep it
awake.  

I'd also like to thank all you other folks who responded.  I got some good
info and tips from all of you.  

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


Re: PHP + TinyButStrong Python replacement

2008-05-07 Thread python
Pistacchio,

Templite
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496702

A light-weight (~40 lines), fully functional, general purpose templating
engine, allowing you to embed python code directly into your text. This
engine is suitable for any templating (not only HTML/XML), and is
minimal (40 lines of code!) and fast (all preprocessing is done in
"compile time")

Quote: "Very nice. That's just the right amount of markup for embedding
Python into html documents."

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


Re: Scanning through Windows registry...

2008-05-07 Thread Mike Driscoll
On May 7, 9:19 am, Tim Golden <[EMAIL PROTECTED]> wrote:
> Mike Driscoll wrote:
> > On May 7, 4:45 am, Tim Golden <[EMAIL PROTECTED]> wrote:
> >> In a spirit of being helpful... :)
>
> [... snip registry walker ...]
>
> > This is pretty cool stuff, Tim. Of course, it would also seriously
> > screw up some programs if you decided to replace the wrong phrase.
> > Just a word of warning to the OP: be sure to make a backup of the
> > registry before doing something like this. Trying to fix a messed up
> > registry from the command line is not a fun way to spend the
> > afternoon.
>
> Good point, Mike. In a spirit of being even more helpful... the _winreg
> module includes the functions SaveKey and LoadKey so as a crude
> backup mechanism, you could do this:
>
> 
> import time
> import _winreg
> import win32api
> import win32security
>
> #
> # You need to have SeBackupPrivilege enabled for this to work
> #
> priv_flags = win32security.TOKEN_ADJUST_PRIVILEGES | win32security.TOKEN_QUERY
> hToken = win32security.OpenProcessToken (win32api.GetCurrentProcess (), 
> priv_flags)
> privilege_id = win32security.LookupPrivilegeValue (None, "SeBackupPrivilege")
> win32security.AdjustTokenPrivileges (hToken, 0, [(privilege_id, 
> win32security.SE_PRIVILEGE_ENABLED)])
>
> root = _winreg.OpenKey (_winreg.HKEY_LOCAL_MACHINE, r"Software\Python\TEST")
> #
> # This will fail if the file already exists so make it uniqueish
> #
> _winreg.SaveKey (root, "c:/temp/HKLM_Software_Python-%s.reg" %  time.strftime 
> ("%Y%m%d-%H%M%S"))
>
> 
>
> Note that the file which this creates is *not* the same as a .reg file which 
> the File > Export menu
> option provides from within the registry editor. (In fact, I shouldn't really 
> have called it .reg; call
> it something else). It can be reloaded by the _winreg.LoadKey function -- 
> which I notice is incorrectly
> named RegLoadKey in the docs after the underlying API call. The docs note 
> that SeRestorePrivilege is
> required for this action, the counterpart to SeBackupPrivilege.
>
> TJG

Wow! Talk about going above and beyond the call of tutoring! I still
don't know how you found out how to do all these neat Windows tricks,
but I'll be filing them away for future reference.

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


Re: What is the purpose of ptyhon in Windows

2008-05-07 Thread Mike Driscoll
On May 7, 9:08 am, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]>
wrote:
> hi All,
> I have no idea why I need to learn a new scripting language,
> nothing much to the sytnax,
> I need to understand what could be the prupose of another scripting
> language
>
> Cna you please help me with this,
> Is there a possibilty to work on bigger projects with Python

There are lots of bigger projects to work on. Check out Spambayes, the
original bittorrent, or Zope for some of the more well known ones.

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


listening on TCP port

2008-05-07 Thread petr . poupa
Hello,
is there anybody who has experience with listening on TCP port with
python? I am looking for anything codes, tutorials,... .
Thanks for any information
--
http://mail.python.org/mailman/listinfo/python-list


Re: python vs. grep

2008-05-07 Thread Pop User

Anton Slesarev wrote:


But I have some problem with writing performance grep analog.



I don't think you can ever catch grep.  Searching is its only purpose in 
life and its very good at it.  You may be able to come closer, this 
thread relates.


http://groups.google.com/group/comp.lang.python/browse_thread/thread/2f564523f476840a/d9476da5d7a9e466

This relates to the speed of re.  If you don't need regex don't use re. 
 If you do need re an alternate re library might be useful but you 
aren't going to catch grep.



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


Re: Why don't generators execute until first yield?

2008-05-07 Thread Diez B. Roggisch
> Now to the main point. When a generator function is run, it immediately
> returns a generator, and it does not run any code inside the generator.
> Not until generator.next() is called is any code inside the generator
> executed, giving it traditional lazy evaluation semantics. Why don't
> generators follow the usual eager evaluation semantics of Python and
> immediately execute up until right before the first yield instead?
> Giving generators special case semantics for no good reason is a really
> bad idea, so I'm very curious if there is a good reason for it being
> this way. With the current semantics it means that errors can pop up at
> unexpected times rather than the code failing fast.

The semantics of a generator are very clear: on .next(), run until the next
yield is reached and then return the yielded value. Plus of course the
dealing with StopIteration-stuff.

Your scenario would introduce a special-case for the first run, making it
necessary to keep additional state around (possibly introducing GC-issues
on the way), just for the sake of it. And violate the lazyness a generator
is all about. Think of a situation like this:

def g():
while True:
   yield time.time()

Obviously you want to yield the time at the moment of .next() being called.
Not something stored from ages ago. If anything that setups the generator
shall be done immediatly, it's easy enough:

def g():
   first_result = time.time()
   def _g():
  yield first_result
  while True:
 yield time.time()
   return _()

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


Re: listening on TCP port

2008-05-07 Thread Jean-Paul Calderone

On Wed, 7 May 2008 08:03:35 -0700 (PDT), [EMAIL PROTECTED] wrote:

Hello,
is there anybody who has experience with listening on TCP port with
python? I am looking for anything codes, tutorials,... .
Thanks for any information


Take a look at

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

which gives a brief overview of writing TCP servers with Twisted.

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


Re: What is the purpose of ptyhon in Windows

2008-05-07 Thread WolfgangZ

[EMAIL PROTECTED] schrieb:

hi All,
I have no idea why I need to learn a new scripting language,
nothing much to the sytnax,
I need to understand what could be the prupose of another scripting
language

Cna you please help me with this,
Is there a possibilty to work on bigger projects with Python
--
http://mail.python.org/mailman/listinfo/python-list

At least I'm living in a free country and nobody forces me to learn 
python. So I don't fully understand why you HAVE TO learn it. When your 
problems can be solved in a different programming language than you 
should be free to use whatever you like. And also why should it be 
forbidden to create a new programming language? Diversity and 
competition is usually not bad.


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


Re: Problem parsing SOAP envelope with ElementTree

2008-05-07 Thread Zvi
On May 7, 1:12 am, Waldemar Osuch <[EMAIL PROTECTED]> wrote:
Thanks a lot :)
P.S. It was a complete code, I didn't write anything else.
--
http://mail.python.org/mailman/listinfo/python-list


Re: FreeBSD KeyboardInterrupt not captured

2008-05-07 Thread Rhamphoryncus
On May 7, 5:00 am, [EMAIL PROTECTED] wrote:
> Hi Guys,
>
> during testing of my project on FreeBSD I've discovered stange
> 'feature' of time.sleep(). It works if single thread is running, but
> when multi-threaded, the SIGINT signal seems not to be handled in same
> way.
>
> I've found three discussion about similar behavior with os.system()
> but so far none of the suggested patches worked.
>
> I've limited test to following code:
>
> import time
> import sys
> import threading
>
> class MyThread(threading.Thread):
> def __init__(self):
> super(MyThread, self).__init__()
> self.start()
>
> def run(self):
> while True:
> try:
> time.sleep(10)
> except KeyboardInterrupt:
> print 'thread keyboard interrupt'
>
> def main():
> my = MyThread()
>
> while True:
> try:
> time.sleep(5)
> except KeyboardInterrupt:
> print 'got it'
>
> if __name__ == '__main__':
> main()
>
> Any suggestions?

Python doesn't support interrupting non-main threads with a signal.
You have to use something else you can manually end, like a Condition
with a timeout or a poll of a fd with a timeout.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Am I missing something with Python not having interfaces?

2008-05-07 Thread Bjoern Schliessmann
jmDesktop wrote:

> Studying OOP and noticed that Python does not have Interfaces. 

By "OOP", you mean "Java", right? 8)

> Is that correct?  Is my schooling for nought on these OOP concepts
> if I use Python.  Am I losing something if I don't use
> the "typical" oop constructs found in other languages (Java, C#
> come to mind.)  

AFAIK, Interfaces weren't "typical" before Java. CMIIW.

BTW, Zope has interfaces. Not sure if it's exactly the same.

Regards,


Björn

-- 
BOFH excuse #424:

operation failed because: there is no message for this error (#1014)

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


Idea for P3K

2008-05-07 Thread M�ta-MCI (MVP)

Hi!

print become a function ; OK

I thought: and why the affection (=) would not become, also, a function?
Examples:
   a = 123return 123
   b,c = 543.21, "LOL"return  (543.21, "LOL")



@-salutations

Michel Claveau

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


Re: listening on TCP port

2008-05-07 Thread Grant Edwards
On 2008-05-07, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:

> is there anybody who has experience with listening on TCP port
> with python? I am looking for anything codes, tutorials,... .


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

-- 
Grant Edwards   grante Yow! With YOU, I can be
  at   MYSELF ...  We don't NEED
   visi.comDan Rather ...
--
http://mail.python.org/mailman/listinfo/python-list


Re: What is the purpose of ptyhon in Windows

2008-05-07 Thread Grant Edwards
On 2008-05-07, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:

> I have no idea why I need to learn a new scripting language,
> nothing much to the sytnax, I need to understand what could be
> the prupose of another scripting language

Python is a general purpose programming language like Java,
Smalltalk, Pascal, etc.

Its purpose is to allow a user to quickly write readable and
easily maintained programs.

> Cna you please help me with this,

Only you know whether/why you need to learn something.

> Is there a possibilty to work on bigger projects with Python

Yes.

-- 
Grant Edwards   grante Yow! Now I am depressed ...
  at   
   visi.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: What is the purpose of ptyhon in Windows

2008-05-07 Thread Max Erickson
WolfgangZ <[EMAIL PROTECTED]> wrote:

> [EMAIL PROTECTED] schrieb:
>> hi All,
>> http://mail.python.org/mailman/listinfo/python-list
>> 
> At least I'm living in a free country and nobody forces me to
> learn python. So I don't fully understand why you HAVE TO learn
> it. When your problems can be solved in a different programming
> language than you should be free to use whatever you like. And
> also why should it be forbidden to create a new programming
> language? Diversity and competition is usually not bad.
> 
> --
> http://mail.python.org/mailman/listinfo/python-list
> 

I imagine that there is some English as a second language getting 
involved and the intent of the question was more like "What is 
python useful for on Windows?", which has pretty much the same 
meaning but is open to a slightly friendlier interpretation(i.e., 
tell me how I can use python instead of tell me why I should use 
python).

The other question might be more like "I already know VBS, what do I 
gain by learning python?".

(the answers could be "lots of things, including full applications" 
and "among other things, you can use it on other platforms, and you 
might prefer the syntax".)


max

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


letter frequency counter / your thoughts..

2008-05-07 Thread umpsumps
Hello,

Here is my code for a letter frequency counter.  It seems bloated to
me and any suggestions of what would be a better way (keep in my mind
I'm a beginner) would be greatly appreciated..

def valsort(x):
res = []
for key, value in x.items():
res.append((value, key))
return res

def mostfreq(strng):
dic = {}
for letter in strng:
if letter not in dic:
dic.setdefault(letter, 1)
else:
dic[letter] += 1
newd = dic.items()
getvals = valsort(newd)
getvals.sort()
length = len(getvals)
return getvals[length - 3 : length]

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


Re: License selection for free software

2008-05-07 Thread Carl Banks
On May 7, 3:51 am, Paul Rubin  wrote:
> Carl Banks <[EMAIL PROTECTED]> writes:
> > Nonsense.  They could be more than willing to contribute their
> > patches, but aren't willing to accept the GPL's limitation to being
> > used only in open source packages.
>
> Oh, I see what you mean--I'm considering any derived work to be a
> patch, which is maybe an overbroad use of that term.  If they are
> willing to contribute their patches in that sense, the GPL shouldn't
> be a problem.  If they want to just send back small scraps of
> improvement while incorporating the GPL'd program into a closed
> program, the GPL is doing its job if it prevents that.

I think what I said is applicable to derived works, if the idea is to
derive another non-open-source work in turn.

I.e., someone might be motived to create a derived work of some code
with the expectation of using it in their non-open-source project, but
if it's GPLed they can't do that, so they probably wouldn't bother.


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


Re: letter frequency counter / your thoughts..

2008-05-07 Thread Paul Melis

[EMAIL PROTECTED] wrote:

Here is my code for a letter frequency counter.  It seems bloated to
me and any suggestions of what would be a better way (keep in my mind
I'm a beginner) would be greatly appreciated..


Not bad for a beginner I think :)


def valsort(x):
res = []
for key, value in x.items():
res.append((value, key))
return res

def mostfreq(strng):
dic = {}
for letter in strng:
if letter not in dic:
dic.setdefault(letter, 1)
else:
dic[letter] += 1
newd = dic.items()
getvals = valsort(newd)
getvals.sort()
length = len(getvals)
return getvals[length - 3 : length]

thanks much!!


Slightly shorter:

def mostfreq(strng):
dic = {}
for letter in strng:
if letter not in dic:
dic[letter] = 0
dic[letter] += 1
# Swap letter, count here as we want to sort on count first
getvals = [(pair[1],pair[0]) for pair in dic.iteritems()]
getvals.sort()
return getvals[-3:]

I'm not sure if  you wanted the function mostfreq to return the 3 most 
frequent letters of the first 3 letters? It seems to do the latter. The 
code above uses the former, i.e. letters with highest frequency.


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


Re: License selection for free software

2008-05-07 Thread Ville M. Vainio
Paul Boddie <[EMAIL PROTECTED]> writes:


> original licence as well. Now, I did leave a fair amount of
> information about the heritage of the code, so that anyone who is
> scared of the LGPL could just go and get the original work, but that

I doubt anyone is really afraid of LGPL. The only problem with LGPL is
that of static vs. dynamic linking, and that is only a problem in
platforms without dynamic linker (rarity these days).


> You can almost never just "grab the code from somewhere without having
> to think about [the] license" since even permissive licences typically
> have a list of conditions that must be observed. Certainly, they

Yeah, but you don't have to "worry" about license - just have the
license text in source code, or a text file in binary distribution.
--
http://mail.python.org/mailman/listinfo/python-list


Re: License selection for free software

2008-05-07 Thread Carl Banks
On May 7, 6:56 am, Paul Boddie <[EMAIL PROTECTED]> wrote:
> On 6 Mai, 19:22, [EMAIL PROTECTED] (Ville M. Vainio) wrote:
> > I don't think BSD/MIT like license really annoys anyone. Think python
> > here ;-)
>
> As some have pointed out, it can discourage people from contributing.
> I've said many times before that some companies might not contribute
> to a permissively licensed project because their competitors could
> leverage the benefit in proprietary software, and I consider Linux and
> the involvement of companies like IBM to be a reasonable example of
> this.

That IBM and other companies are involved with Linux is an example of
companies that are willing to get involved with GPL; it says nothing
about whether those companies would be more, less, or un- willing to
also get involved with more permissive licenses.

IBM is also involved with Apache, which does have a permissive
license.


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


Re: letter frequency counter / your thoughts..

2008-05-07 Thread castironpi
On May 7, 12:30 pm, Paul Melis <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] wrote:
> > Here is my code for a letter frequency counter.  It seems bloated to
> > me and any suggestions of what would be a better way (keep in my mind
> > I'm a beginner) would be greatly appreciated..
>
> Not bad for a beginner I think :)
>
>
>
>
>
> > def valsort(x):
> >    res = []
> >    for key, value in x.items():
> >            res.append((value, key))
> >    return res
>
> > def mostfreq(strng):
> >    dic = {}
> >    for letter in strng:
> >            if letter not in dic:
> >                    dic.setdefault(letter, 1)
> >            else:
> >                    dic[letter] += 1
> >    newd = dic.items()
> >    getvals = valsort(newd)
> >    getvals.sort()
> >    length = len(getvals)
> >    return getvals[length - 3 : length]
>
> > thanks much!!
>
> Slightly shorter:
>
> def mostfreq(strng):
>      dic = {}
>      for letter in strng:
>          if letter not in dic:
>              dic[letter] = 0
>          dic[letter] += 1
>      # Swap letter, count here as we want to sort on count first
>      getvals = [(pair[1],pair[0]) for pair in dic.iteritems()]
>      getvals.sort()
>      return getvals[-3:]
>
> I'm not sure if  you wanted the function mostfreq to return the 3 most
> frequent letters of the first 3 letters? It seems to do the latter. The
> code above uses the former, i.e. letters with highest frequency.
>
> Paul- Hide quoted text -
>
> - Show quoted text -

I think I'd try to get a deque on disk.  Constant indexing.  Store
disk addresses in b-trees.  How long does 'less than' take?  Is a
sector small, and what's inside?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Generate labels for a multi-level outline

2008-05-07 Thread castironpi
On May 7, 9:07 am, [EMAIL PROTECTED] wrote:
> '''
> On May 6, 4:43 pm, [EMAIL PROTECTED] honoring:
>
> >>> a.next( )
> ( "I", )
> >>> a.throw( up )
> ( "I", "A" )
> >>> a.next( )
> ( "I", "B" )
> >>> a.next( )
> ( "I", "C" )
> >>> a.throw( down )
>
> ( "II", )
> '''
>
> #funny declaration
> class up( Exception ): pass
> class down( Exception ): pass
>
> def outline( ):
>     stack= [ 1 ]
>     while 1:
>         try:
>             yield stack
>             stack[ -1 ]+= 1
>         except up:
>             stack.append( 1 )
>         except down:
>             stack.pop( -1 )
>             stack[ -1 ]+= 1
>
> a= outline( )
> print a.next( )
> print a.throw( up )
> print a.next( )
> print a.next( )
> print a.throw( down )
> print a.throw( up )
> print a.throw( up )
> print a.next( )
> print a.next( )
> print a.throw( down )
>
> ##output:
>
> [1]
> [1, 1]
> [1, 2]
> [1, 3]
> [2]
> [2, 1]
> [2, 1, 1]
> [2, 1, 2]
> [2, 1, 3]
> [2, 2]
>
> ##
>
> cf.
>
> formatter.NullFormatter.format_counter
> formatter.NullFormatter.format_letter
> formatter.NullFormatter.format_roman

One execution of Python 3a4 included in built-ins.

Python 3.0
 win32
Type "help
>>> next
>>

Do you want send and throw in it too?
--
http://mail.python.org/mailman/listinfo/python-list


Re: comparing dictionaries

2008-05-07 Thread Arnaud Delobelle
brad <[EMAIL PROTECTED]> writes:

> I want to compare two dicts that should have identical info just in a
> different data structure. The first dict's contents look like this. It
> is authoritative... I know for sure it has the correct key value
> pairs:
>
> {'001' : '01'}

-> refdict

>
> The second dict's contents are like this with a tuple instead of a
> string for the key:
>
> {('This is one', '001'): '01'}

-> multidict

>
> Pseudo Code:
> for key, value in first_dict.iteritems():
>   # How do I do the following line?
>   if key not in second_dict or if it is, but has has the wrong value,
> then let me know

I think it's best to iterate over items of the second dictionary
first.  I am assuming that a key can be repeated in the second
dictionary, otherwise it could be a bit simpler:

missing_keys = set(first_dict)
for keys, val in second_dict.iteritems():
for key in keys:
missing_keys.discard(key)
if first_dict.get(key, val) != val:
print "wrong value for", key, 'in', keys
if missing_keys:
print 'some keys are missing:', ',',join(remaining) 

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


Re: Idea for P3K

2008-05-07 Thread Arnaud Delobelle
"Méta-MCI (MVP)" <[EMAIL PROTECTED]> writes:

> Hi!
>
> print become a function ; OK
>
> I thought: and why the affection (=) would not become, also, a function?
> Examples:
>a = 123return 123
>b,c = 543.21, "LOL"return  (543.21, "LOL")

Do you mean a = 3 would become an *expression* ?

For one thing, it wouldn't fit with the Python's function call syntax:

f(4, x=2)

currently means that f is called with first positional argument equal
to 4 and named argument 'x' equal to 2.

Moreover, it seems to me utterly unpythonic (and I don't often feel
like using this word!).  Binding a name to a new value is something
that needs to be clearly visible in the code flow, not hidden within
an expression

E.g.

f(3, 4 + (x=2), 5)

has the side-effect that x is now bound to 2, but it is only apparent
if one closely scrutinises the code.

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


Re: letter frequency counter / your thoughts..

2008-05-07 Thread Arnaud Delobelle
[EMAIL PROTECTED] writes:

> Hello,
>
> Here is my code for a letter frequency counter.  It seems bloated to
> me and any suggestions of what would be a better way (keep in my mind
> I'm a beginner) would be greatly appreciated..
>
> def valsort(x):
>   res = []
>   for key, value in x.items():
>   res.append((value, key))
>   return res
>
> def mostfreq(strng):
>   dic = {}
>   for letter in strng:
>   if letter not in dic:
>   dic.setdefault(letter, 1)
>   else:
>   dic[letter] += 1
>   newd = dic.items()
>   getvals = valsort(newd)
>   getvals.sort()
>   length = len(getvals)
>   return getvals[length - 3 : length]
>
> thanks much!!

I won't comment on the algorithm, but I think you should try to find
better names for your variables.  In the snippet above you have x,
res, dic, newd, length, getvals which don't give much of a clue as to
what they are used for.

e.g.

* dic = {}
We know it's a dict, but a dict of what?

* newd = dic.items()
Sounds like 'new dictionary', but obviously isn'tas it is a list 
of key,value pairs.

* length = len(getvals)
Again, we know it's a length, but the length of what?

HTH

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


Re: letter frequency counter / your thoughts..

2008-05-07 Thread Ian Kelly
On Wed, May 7, 2008 at 11:30 AM, Paul Melis <[EMAIL PROTECTED]> wrote:
> dic = {}
> for letter in strng:
> if letter not in dic:
> dic[letter] = 0
> dic[letter] += 1

As a further refinement, you could use the defaultdict class from the
collections module:

   dic = defaultdict(int)
   for letter in strng:
   dic[letter] += 1
--
http://mail.python.org/mailman/listinfo/python-list


Re: Generate labels for a multi-level outline (THANK-YOU!)

2008-05-07 Thread python
Castironpi and Dennis,

WOW! Thank you very much for your examples!!!

I wasn't trolling for free development, just whether such a library
existed and/or design ideas (basic object or generator).

I had started to develop my own solution which was much more complicated
(re: ugly) than your 2 very elegant approaches.

Its interesting to compare your two very different approaches. I will to
spend some more time studying your techniques before I choose a final
approach.

Thank you both again. I'm learning a lot of Python by studying your
examples! :)

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


Re: Bad form to access a *private variable* like _foo?

2008-05-07 Thread [EMAIL PROTECTED]
On May 6, 3:27 am, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:

> There are other ways. For example,
>
> sqlobject.sqlhub.threadingLocal.connection
>
> if your system is using multiple threads correctly. Generally speaking,
> sqlhub could/should be used.

That's actually quite involved.  You must first get a reference to a
PackageHub object, then invoke connectionToURI, etc.  lots of steps!

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


Re: letter frequency counter / your thoughts..

2008-05-07 Thread castironpi
On May 7, 1:31 pm, "Ian Kelly" <[EMAIL PROTECTED]> wrote:
> On Wed, May 7, 2008 at 11:30 AM, Paul Melis <[EMAIL PROTECTED]> wrote:
> >     dic = {}
> >     for letter in strng:
> >         if letter not in dic:
> >             dic[letter] = 0
> >         dic[letter] += 1
>
> As a further refinement, you could use the defaultdict class from the
> collections module:
>
>    dic = defaultdict(int)
>        for letter in strng:
>            dic[letter] += 1

Sounds like novel flow of control.
--
http://mail.python.org/mailman/listinfo/python-list


Re: PHP + TinyButStrong Python replacement

2008-05-07 Thread Terry Reedy

"pistacchio" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]

| well, it doesn't matter if it's a single file or a package, but it
| _does_ matter if you have to put them under the path where python is
| installed because, in a typical shared web hosting environment (such the
| one that i use) you don't have access to system directories.

When you do an import, the *first* place the interpreter looks is the 
*current* directory, which usually is the directory containing the main 
file.  That is because the first entry in sys.path is ''.  So put 
'template.py' in the same directory as my_web_code.py.  If necessary, one 
can add an entry to the beginning of sys.path.

No need to touch the site-packages directory.  The only reason to put 
something there is to make modules available to any code in any directory 
without putting a copy in each directory containing python files.

tjr




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


Re: Am I missing something with Python not having interfaces?

2008-05-07 Thread [EMAIL PROTECTED]
On 7 mai, 18:05, Bjoern Schliessmann  wrote:
> jmDesktop wrote:
> > Studying OOP and noticed that Python does not have Interfaces.
>
> By "OOP", you mean "Java", right? 8)
>
> > Is that correct?  Is my schooling for nought on these OOP concepts
> > if I use Python.  Am I losing something if I don't use
> > the "typical" oop constructs found in other languages (Java, C#
> > come to mind.)
>
> AFAIK, Interfaces weren't "typical" before Java. CMIIW.
>
> BTW, Zope has interfaces. Not sure if it's exactly the same.
>
It isn't.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Idea for P3K

2008-05-07 Thread M�ta-MCI (MVP)

Hi!


I don't often feel like using this word


Look at languages like OCAML or F #

@-salutations
--
Michel Claveau

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


Re: Learning question...

2008-05-07 Thread Terry Reedy

<[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
| Any idea why the following program does not work? I was learning IO on
| Python and the following generates a TypeError: range() integer end
| argument expected, got str.
| I am a beginner.
|
| 
| # print input name (str k), j times using raw_input
|
| def hello():
|j=raw_input("Please type in the number of times you want to print
| ")
|k=raw_input("Please type in your name ")
|printname(j,k)
|
| def printname(j,k):
|  for i in range(j):
|print ("Hello %s" % k)

For future debugging, use print to find out what values you actually have.
print j,k #before printname()
would have shown you that j is a string.
Also use the type() function as needed.
And do read the Lib Ref sections on builting functions and types.

tjr





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


Re: Am I missing something with Python not having interfaces?

2008-05-07 Thread Daniel Marcel Eichler
Am Dienstag 06 Mai 2008 16:07:01 schrieb Mike Driscoll:

> If so, then it looks like an Interface is a generic class with method
> stubs. You can do that with Python just as easily by creating empty
> methods with just the "pass" keyword. 

Well, no. It's a litte different. Interfaces force to implement methods. 
Simple inheritance with method-stubs can't garantee that a specific 
method is reimplementat in a sub-class. Interfaces work at 
compile-time, while method-stubs raise at their first call, so in worst 
case, never (when the developer is available). 

> Since it's just a construct to implement polymorphism, I don't think
> you'll lose anything. However, Python does not require you to re-
> implement every method of the class it is inheriting from. 

That's the point. Interfaces garantee that a duck is a duck, an not only 
a chicken that quack. 

> You can just override those that you want and leave the others alone.

Not always desirable. But often enough ;)
--
http://mail.python.org/mailman/listinfo/python-list


  1   2   >