Re: Pystemmer 1.0.1 installation problem in Linux

2008-03-27 Thread Jason Scheirer
On Mar 27, 8:40 am, mungkol <[EMAIL PROTECTED]> wrote:
> Dear all,
>
> I am a newbie to Python community. For my project, I tried to install
> Pystemmer 1.0.1 (http://snowball.tartarus.org/wrappers/
> PyStemmer-1.0.1.tar.gz) on my linux ubuntu 7.10 machine but
> unsuccessful. It produced the following error:
>
> running install
> running build
> running build_ext
> building 'Stemmer' extension
> gcc -pthread -fno-strict-aliasing -DNDEBUG -g -O2 -Wall -Wstrict-
> prototypes -fPIC -Isrc -Ilibstemmer_c/include -I/usr/include/python2.5
> -c libstemmer_c/src_c/stem_ISO_8859_1_danish.c -o build/temp.linux-
> i686-2.5/libstemmer_c/src_c/stem_ISO_8859_1_danish.o
> In file included from /usr/lib/gcc/i486-linux-gnu/4.1.3/include/
> syslimits.h:7,
>  from /usr/lib/gcc/i486-linux-gnu/4.1.3/include/
> limits.h:11,
>  from libstemmer_c/src_c/../runtime/header.h:2,
>  from libstemmer_c/src_c/stem_ISO_8859_1_danish.c:4:
> /usr/lib/gcc/i486-linux-gnu/4.1.3/include/limits.h:122:61: error:
> limits.h: No such file or directory
> error: command 'gcc' failed with exit status 1
>
> Did anyone experience this before?
>
> Any comment/suggestion is highly appreciated.
>
> Thank you.
>
> Best regards,
>
> Supheakmungkol

This is a system configuration issue, not a Python issue: you seem to
be missing a header file. First, make sure it exists ( /usr/lib/gcc/
i486-linux-gnu/4.1.3/include/limits.h ) and that you have permission
to read it. If it's there, just sudo chmod a+r it and see if that
helps. Also try installing Ubuntu's standard essential build tools
( sudo apt-get update && sudo apt-get install build-essential ) and
see if that helps
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Time problem (again)

2008-03-27 Thread Jason Scheirer
On Mar 27, 12:17 pm, "Fabio Durieux Lopes" <[EMAIL PROTECTED]>
wrote:
>Hi,
>
>I'm recreating a date-time based on a string and I have a problem
> when daylight savings time is set (I'm off by 1). So today I forced
> my computer into daylight savings time and debugged it again, but
> this time I noticed something strange.
>
>This is the documentation from python library reference section
> 6.10:
>
> 6.10 time -- Time access and conversions
> ...
> daylight
> Nonzero if a DST timezone is defined.
> ...
>
> And this is what I debugged:
> -> fileTimeInSecs = time.mktime(time.strptime(timeString,
> "%Y%m%d%H%M"))
> (Pdb) p timeString
> '200803271643'
> (Pdb) n> /home/salsa/Projects/TimBR_CDR/fileSync/
>
> fileSynchronizer.py(50)passFilesOlderThan()
> -> print time.daylight
> (Pdb)
> 0
>
>  See how 'print time.daylight' resulted in '0'? Shouldn't it be Non-
> zero? Do I have to set something for it to use DST?
>
>  Also, is this the right list to send questions?

The Python datetime module's handling of time zones is completely,
entirely deficient -- the tzinfo class is just a skeleton and
therefore useless. Install something that will give you fully
implemented time zones like at http://pytz.sourceforge.net/ and try
again -- pulling a tzinfo from this module and doing
datetime_instance.replace(tzinfo=tzinfo_object_for_timezone) on your
datetime instance parsed from the string will result in far more
predictable behavior and probably get everything behaving as you
expect.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: spawning pyhon apps...

2009-01-09 Thread Jason Scheirer
On Jan 9, 3:43 pm, "bruce"  wrote:
> hi jason
>
> forgive me... but in your sample:
>         my_popenobjects = [subprocess.Popen("foo.py", "--filename=file
>         %i.txt"%x) for x in xrange(10)]
> are you spawning 'foo.py' 10 times? that can't be right!
> so just what is "foo.py" used for? what am i missing...
>
> it looks like the my_popenobjects array is iterated through to check the
> statuscode. is the statuscode the value that would be returned from a child
> python script via something like "return(2)"
>
> i've seen mention of os.waitpid(..) does this play into waiting for child
> processes to complete, or determine if they've terminated??
>
> thanks
>
> -Original Message-
> From: [email protected]
>
> [mailto:[email protected]]on Behalf
> Of Jason Scheirer
> Sent: Friday, January 09, 2009 3:19 PM
> To: [email protected]
> Subject: Re: spawning pyhon apps...
>
> On Jan 9, 2:47 pm, "bruce"  wrote:
> > hi...
>
> > toying with an idea.. trying to figure out a good/best way to spawn
> multiple
> > python scripts from a parent python app. i'm trying to figure out how to
> > determine when all child apps have completed, or to possibly determine if
> > any of the child processes have died/halted..
>
> > parent app
> >  spawn child1
> >  spawn child2
> >  spawn child3
> >  .
> >  .
> >  .
> >  spawn childn
>
> > do i iterate through a os.waitpid(pid) for each pid of the child processes
> i
> > create?
>
> > is there another approach? code samples/tutorial...??
>
> > i've seen various approaches via google, but not just what i'm looking
> for..
>
> > thanks
>
> Investigate the subprocess module, you probably want Popen objects.
> You can do a poll loop like
>
> my_popenobjects = [subprocess.Popen("foo.py", "--filename=file
> %i.txt"%x) for x in xrange(10)]
>
> while any(popenobject.returncode is None for popenobject in
> my_popenobjects):
>   time.sleep(0.25)
>
> If your tasks are more like function calls and less like shell
> scripts, then investigate writing your python as an importable module
> and use the multiprocessing module, which will do threading/
> subprocessing for you.
> --http://mail.python.org/mailman/listinfo/python-list
>
>

Correction: statuscode is wrong. It's returncode.

Foo.py is the hypothetical Python script you want to run in a
subprocess. In this example, I have an external shell script named
foo.py, and I am indeed spawning 10 copies of it, each with a second
argument that varies (foo.py --filename=file0.txt, foo.py --
filename=file1.txt, ... foo.py --filename=file9.txt). You don't need
os.waitpid() with a Popen object, there is a Popen.wait() method you
can call which will accomplish the exact same thing. I'm polling the
Popen.returncode for each process' return code (which is the numeric
code a process returns when it finishes, like sys.exit(x) or return,
or gives None if it's not done yet. What this sample is doing is
opening 10 copies of the script and running them in parallel, if you
want to run it is serial then you can do a simple for loop and .wait()
on each:

for cmd in ('a', 'b', 'c'):
  sp = subprocess.Popen(cmd)
  sp.wait()
  print "Command %r completed with status %i" % (cmd, sp.returncode)

I'm still not 100% sure what you're trying to accomplish. What is the
exact problem you are wishing to solve?
--
http://mail.python.org/mailman/listinfo/python-list


Re: spawning pyhon apps...

2009-01-09 Thread Jason Scheirer
On Jan 9, 4:07 pm, "bruce"  wrote:
> thanks jason
>
> or i could also, simply iterate through a loop of the names of the "child
> processes" i want to spawn, using the names in the subprocess.popen, and
> then proceeding with the rest of your example..
>
> question though... if i have a child app that's hanging.. how do i kill it.
>
> or is this getting into the aspect of using interprocess pipes, where if the
> parent isn't getting a 'live ping' via the pipe back from the child after a
> certain amount of time... it could kill the child...
>
> thoughts/comments...
>
> thanks
>
> -Original Message-
> From: [email protected]
>
> [mailto:[email protected]]on Behalf
> Of Jason Scheirer
> Sent: Friday, January 09, 2009 3:59 PM
> To: [email protected]
> Subject: Re: spawning pyhon apps...
>
> On Jan 9, 3:43 pm, "bruce"  wrote:
> > hi jason
>
> > forgive me... but in your sample:
> >         my_popenobjects = [subprocess.Popen("foo.py", "--filename=file
> >         %i.txt"%x) for x in xrange(10)]
> > are you spawning 'foo.py' 10 times? that can't be right!
> > so just what is "foo.py" used for? what am i missing...
>
> > it looks like the my_popenobjects array is iterated through to check the
> > statuscode. is the statuscode the value that would be returned from a
> child
> > python script via something like "return(2)"
>
> > i've seen mention of os.waitpid(..) does this play into waiting for child
> > processes to complete, or determine if they've terminated??
>
> > thanks
>
> > -Original Message-
> > From: [email protected]
>
> > [mailto:[email protected]]on Behalf
> > Of Jason Scheirer
> > Sent: Friday, January 09, 2009 3:19 PM
> > To: [email protected]
> > Subject: Re: spawning pyhon apps...
>
> > On Jan 9, 2:47 pm, "bruce"  wrote:
> > > hi...
>
> > > toying with an idea.. trying to figure out a good/best way to spawn
> > multiple
> > > python scripts from a parent python app. i'm trying to figure out how to
> > > determine when all child apps have completed, or to possibly determine
> if
> > > any of the child processes have died/halted..
>
> > > parent app
> > >  spawn child1
> > >  spawn child2
> > >  spawn child3
> > >  .
> > >  .
> > >  .
> > >  spawn childn
>
> > > do i iterate through a os.waitpid(pid) for each pid of the child
> processes
> > i
> > > create?
>
> > > is there another approach? code samples/tutorial...??
>
> > > i've seen various approaches via google, but not just what i'm looking
> > for..
>
> > > thanks
>
> > Investigate the subprocess module, you probably want Popen objects.
> > You can do a poll loop like
>
> > my_popenobjects = [subprocess.Popen("foo.py", "--filename=file
> > %i.txt"%x) for x in xrange(10)]
>
> > while any(popenobject.returncode is None for popenobject in
> > my_popenobjects):
> >   time.sleep(0.25)
>
> > If your tasks are more like function calls and less like shell
> > scripts, then investigate writing your python as an importable module
> > and use the multiprocessing module, which will do threading/
> > subprocessing for you.
> > --http://mail.python.org/mailman/listinfo/python-list
>
> Correction: statuscode is wrong. It's returncode.
>
> Foo.py is the hypothetical Python script you want to run in a
> subprocess. In this example, I have an external shell script named
> foo.py, and I am indeed spawning 10 copies of it, each with a second
> argument that varies (foo.py --filename=file0.txt, foo.py --
> filename=file1.txt, ... foo.py --filename=file9.txt). You don't need
> os.waitpid() with a Popen object, there is a Popen.wait() method you
> can call which will accomplish the exact same thing. I'm polling the
> Popen.returncode for each process' return code (which is the numeric
> code a process returns when it finishes, like sys.exit(x) or return,
> or gives None if it's not done yet. What this sample is doing is
> opening 10 copies of the script and running them in parallel, if you
> want to run it is serial then you can do a simple for loop and .wait()
> on each:
>
> for cmd in ('a', 'b', 'c'):
>   sp = subprocess.Popen(cmd)
>   sp.wait()
>   print "Command %r completed with status %i" % (cmd, sp.returncode)
>
> I'm still not 100% sure what you're trying to accomplish. What is the
> exact problem you are wishing to solve?
> --http://mail.python.org/mailman/listinfo/python-list
>
>

Yes, so to open your processes you can loop over a list of commands
and create new subprocess.Popen(cmd) objects for each.

Everything is explained:

http://docs.python.org/library/subprocess.html#popen-objects

You can do .terminate() to kill a process that may be hanging, you can
get the .stdout and poll on its .read() to see if it's still putting
anything out to the console.
--
http://mail.python.org/mailman/listinfo/python-list


Re: the name of a method

2009-01-15 Thread Jason Scheirer
On Jan 15, 8:37 am, "Diez B. Roggisch"  wrote:
> [email protected] wrote:
> > Hello,
>
> > I have a Class:
>
> > class myClass:
> >     def __init__(self):
> >         # do something
> >         print "name of class = " +  self.__class__.__name__
>
> >     def myMethod(self):
> >         # do something
> >         print "name of method = " + "myMethod"
> >         return
>
> >     ...
>
> > I print the name of the class with self.__class__.__name__ in
> > __init__.
> > I want to print also in every method of myClass the name of the
> > method.
> > How can I get the name? I would not like to write e.g. "myMethod". Is
> > there a variable like self.__class__.__name__ for this?
> > Thanks for your hints, Thomas
>
> This can be done by inspecting the stackframes. Look into the module
> inspect. This has also been discussed very often on this list, stackframe &
> inspect should be good searchterms.
>
> However, if what you are after is logging, you should take a look into the
> logging module. it has many advantages over simple print-statements, and
> amongst other things allows you to print out the enclosing callable name
> when invoked ala
>
> logger.debug("Some message.")
>
> I strongly recommend using that. And at least you can of course peek into
> the logging module's source to see how the extract that information.
>
> Diez

I agree, this should not be done. However, sometimes it's useful to
see the parameter values:

import inspect
import logging
import sys
def log_fn():
logging.debug("%s%s" % (
sys._getframe().f_back.f_code.co_name,
inspect.formatargvalues(*inspect.getargvalues(sys._getframe
().f_back

logging.getLogger().setLevel(0)
def hello_there(x, y, z, *a):
 log_fn()
 return 1+x

>>> hello_there(1, 'a', 'b', 5, 6, 7, 8, 9)
DEBUG:root:hello_there(x=1, y='a', z='b', *a=(5, 6, 7, 8, 9))

It can be done, but usually you want to actually trace through with
the debugger.
--
http://mail.python.org/mailman/listinfo/python-list


Re: is None vs. == None

2009-01-23 Thread Jason Scheirer
On Jan 23, 12:48 pm, Roger  wrote:
> > And, just for completeness, the "is" test is canonical precisely because
> > the interpreter guarantees there is only ever one object of type None,
> > so an identity test is always appropriate. Even the copy module doesn't
> > create copies ...
>
> Does the interpreter guarantee the same for False and True bools?

Yes. I know that there are the PyObject* structs defined for you
Py_True, Py_False and Py_None in the C level. Confusingly enough, the
integers -5 through 257 are also singletons where the is test will
work, but any int out of that range will not.

>>> def copy_id(x):
... id1, id2 = id(x), id(copy.deepcopy(x))
... print "Equal: %x %s %x" % (id1, ('==' if id1 == id2 else '!
='), id2)
...
...
>>> copy_id(a())
Equal: a8fc90 != f32370
>>> copy_id(1)
Equal: 9559c8 == 9559c8
>>> copy_id(None)
Equal: 1e1da9f0 == 1e1da9f0
>>> copy_id(True)
Equal: 1e1c5ec4 == 1e1c5ec4
>>> copy_id(False)
Equal: 1e1c5eb8 == 1e1c5eb8
>>> copy_id("Hello")
Equal: 1058840 == 1058840
>>> copy_id([])
Equal: 1067030 != 10673f0

... large equal integers are not identical in memory location ...

In [34]: x = 19591
In [35]: y = 19590+1
In [36]: id(x), id(y)
Out[36]: (17937008, 17936588)

... but small ones are ...

In [40]: x = 2
In [41]: y = 1+1
In [42]: id(x), id(y)
Out[42]: (9787836, 9787836)
--
http://mail.python.org/mailman/listinfo/python-list


Re: What is wrong in my list comprehension?

2009-02-02 Thread Jason Scheirer
On Feb 1, 3:37 am, Peter Otten <[email protected]> wrote:
> Hussein B wrote:
> > Hey,
> > I have a log file that doesn't contain the word "Haskell" at all, I'm
> > just trying to do a little performance comparison:
> > ++
> > from datetime import time, timedelta, datetime
> > start = datetime.now()
> > print start
> > lines = [line for line in file('/media/sda4/Servers/Apache/
> > Tomcat-6.0.14/logs/catalina.out') if line.find('Haskell')]
> > print 'Number of lines contains "Haskell" = ' +  str(len(lines))
> > end = datetime.now()
> > print end
> > ++
> > Well, the script is returning the whole file's lines number !!
> > What is wrong in my logic?
> > Thanks.
>
> """
> find(...)
>     S.find(sub [,start [,end]]) -> int
>
>     Return the lowest index in S where substring sub is found,
>     such that sub is contained within s[start:end].  Optional
>     arguments start and end are interpreted as in slice notation.
>
>     Return -1 on failure.
> """
>
> a.find(b) returns -1 if b is no found. -1 evaluates to True in a boolean
> context.
>
> Use
>
> [line for line in open(...) if line.find("Haskell") != -1]
>
> or, better
>
> [line for line in open(...) if "Haskell" in line]
>
> to get the expected result.
>
> Peter

Or better, group them together in a generator:

sum(line for line in open(...) if "Haskell" in line)

and avoid allocating a new list with every line that contains Haskell
in it.

http://www.python.org/dev/peps/pep-0289/
--
http://mail.python.org/mailman/listinfo/python-list


Re: A little bit else I would like to discuss

2009-02-12 Thread Jason Scheirer
On Feb 12, 12:04 pm, azrael  wrote:
> Sometimes I really get confused when looking out for a modul for some
> kind of need. Sometimes I get frightened when I get the resaults. 8
> wraper for this, 7 wrapers for that, 10 modules for anything. Between
> them are maybe some kind of small differences, but to work with any of
> the modules, I have to spend 10 hours of reading the help, If there is
> any at all.
>
> I think that there should be a list on python.org of supported or
> sugested modules for some need. For example Database access. Or GUI
> Building. It is a complete pain in the ass. Let's face the true, TK is
> out of date. There should be another one used and appended to the
> standard Python Library. One that plays well with other platforms. And
> if it does't, let's make it play better.
>
> Why will Microsoft's products kick the ass of open source. Because
> anyone does what he wants. Let's say There are 5 GUI libraries
> competing against each other. Think about it what could these 5 teams
> acomplish if they would work together. Or maybe a framework for RAD
> GUI devbelopment. after 10 years of python, there is still not one
> application for GUI Building that can beat Visual Studio.
>
> Anyone I talk to says: "Oh my god, Python and GUI"
>
> There are a dozen of modules that should be, if you ask me, be
> implemented into Python. Like NumPy, SciPY, PIL. A lot of people I
> talk to, are using them. But everyone has to download them manually
> and hope that if someone is using their code, has also installed the
> needed modules.
>
> My solution would be:
> Let's make an announcement on Python.org. something like this.
>
> We need Ideas for creating the a standard library in Python for Image
> processing. Tell  us your problem. What do you think which feature
> should be implemented. Which transformation, which algorithm.
> Make a vote. This should be that not.
>
> But how to start something like that. Anyone that sees a problem that
> should be solved, becomes the project leader. Find the best Ideas and
> make a good library.
>
> It's is very good that people have a choice. But why not make some
> standards. I know that there is already a standard python library, But
> why not extending it. classify the standard library into subcategories
> like Networking, DataBase, Computation, ..
>
> One other thing. I am not looking for war on groups. I just would like
> to discuss some things that drive me crazy while using Python.
>
> This group has a lot of members. not to mention every Python Forum.
> Why not using this number of people and accomplish something great. If
> anyone of us would write 10 line of good code, it would result a very
> great and powerfull environment.

Now hold on here, Microsoft has a pretty schizophrenic opinion on GUIs
itself. Over the years you've had direct Win32 calls, the MFC
libraries, then WinForms and later WPF on .NET. If I were a C++/C#
developer new to Windows, which one should I go with? Or how about I
want to be cross-platform and start looking into Fox or QT or even
GTK?

The only difference between this and the number of Python GUIs is that
your version of Visual Studio sticks around for a few years. You could
standardize on a single version of the GUI you're using (say, WX) and
declare it to have a 5 year lifespan in your organization, install QT
builder and use that, or any of a large number of options. Don't
expect other people to make the decision for you, though, as an open
source environment brings about a plurality of options. Python has a
far broader scope as a tool for all kinds of tasks than a GUI-Centric
Microsoft development environment, and assuming every Python developer
wants to focus on making Python a vehicle of platform-specific GUIs
for producing shrink-wrapped software is a little off base.

> Anyone I talk to says: "Oh my god, Python and GUI"

Have these people needed to spend much time getting to know any one
GUI environment? They all suck in every language at first, then the
Stockholm syndrome sets in and it's not so bad.

The problem here also is that there have been attempts to get
something going that sputtered and failed (a sort of anygui module).
It's relatively easy to standardize on how to talk to a relational
database (that PEP is nice and solid), but looking at a grand unified
way of talking to so many different paradigms of GUI library, writing
bindings, testing, etc. is a much larger, less sensical beast. The
cross-platform UIs like Swing or QT all feel slightly out-of-place on
many systems because the interface elements and design decisions are
different from platform to platform.

If you want a platform-integrated GUI, use Glade/GTK/Python or QT
Designer/Python in Linux, XCode/Interface Builder/PyObjC in OSX, and
even consider IronPython and the .Net GUI stuff on Windows. Heck, I've
done some Swing and Jython and it was not as bad as writing Swing in
Java.

Might I also suggest that if you are struggling to make a proper GUI

Re: Upgrading standard library module

2009-02-13 Thread Jason Scheirer
On Feb 13, 12:42 pm, Bryan  wrote:
> I have a Python v2.5.2 server running and I found some undesirable
> behavior in the xmlrpclib module that is included with that version of
> Python.  The xmlrpclib version that is included with Python 2.6
> changes the behavior for the better.  I nervous about upgrading my
> Python install to 2.6 on this server because I remember reading in the
> docs of a library I use that it targets the 2.5 branch.  What is the
> best way to only upgrade the xmlrpclib in my 2.5 install?
>
> Also, have you all had problems with libraries not specifying which
> Python version they target?  I can't find a requirements for the
> formencode library.  It is kind of scary upgrading my Python server
> install without being sure all my libraries will work.  Experiences??
>
> Bryan

Python has always been pretty backwards-compatible and has a nice
roadmap for upgrades (with new languages features living in __future__
for a version or so before they're in the main version). With the
exception of 2.X->3, you can usually assume that any pure-Python
modules written for 2.x will work in 2.(x+1), and assuming they don't
issue any warnings, also in 2.(x+2).

What behavior, exactly, do you not like in xmlrpclib? Diffing the 2.5
and 2.6, only significant differences I see are checks for True/False
as builtins left over from pre-2.4 and some datetime handling.
--
http://mail.python.org/mailman/listinfo/python-list


Re: error while importing os

2009-02-15 Thread Jason Scheirer
On Feb 15, 12:38 pm, karan  wrote:
> Hi,
>
> Iam new to python i see the following when iam in the python shell and
> i try to import os,though i can import the sys and sys.path does
> contain the path to the python binary or the folder where the python
> binaries reside:
>
> Traceback (most recent call last):
>   File "", line 1, in ?
>   File "C:\Perf\qa\test\build\vmqa\python\python-2.4.1-as\lib\os.py",
> line 683, in ?
>     import copy_reg as _copy_reg
>   File "C:\Perf\qa\test\build\vmqa\python\python-2.4.1-as\lib
> \copy_reg.py", line 7, in ?
>     from types import ClassType as _ClassType
> ImportError: dynamic module does not define init function (inittypes)
>
> I have the added the path to the Python which contain the python
> binaries,DLLs to the PYTHONPATH.
>
> Let me know what might be the reason for getting this error.
>
> Thanks.

Looks like you have an errant dynamic library -- look for types.pyd on
your pythonpath and make sure the right one is getting imported.
--
http://mail.python.org/mailman/listinfo/python-list


Re: flexible find and replace ?

2009-02-16 Thread Jason Scheirer
On Feb 16, 12:10 pm, OdarR  wrote:
> Hi guys,
>
> how would you do a clever find and replace, where the value replacing
> the tag
> is changing on each occurence ?
>
> "...TAGTAGTAG..TAG."
>
> is replaced by this :
>
> "...REPL01REPL02REPL03..REPL04..."
>
> A better and clever method than this snippet should exist I hope :
>
> counter = 1
> while 'TAG' in mystring:
>     mystring=mystring.replace('TAG', 'REPL'+str(counter), 1)
>     counter+=1
>     ...
>
> (the find is always re-starting at the string beginning, this is not
> efficient.
>
> any ideas ? thanks,
>
> Olivier

You could split on the string and interleave your new string in
between:

In [1]: def replmaker():
   ...: index = 0
   ...: while True:
   ...: index += 1
   ...: yield "REPL%02i"%index
   ...:

In [2]: def spliton(string, tag="TAG", sepgen=replmaker):
   ...: repl_iter = sepgen()
   ...: strlist = string.split(tag)
   ...: length = len(strlist)
   ...: for index, item in enumerate(strlist):
   ...: yield item
   ...: if index < length - 1:
   ...: yield repl_iter.next()
   ...:

In [3]: ''.join(spliton
("...TAGTAGTAG..TAG." ))
Out[3]:
'...REPL01REPL02REPL03..REPL04.'
--
http://mail.python.org/mailman/listinfo/python-list


Re: wxPython and Croatian characters

2009-02-16 Thread Jason Scheirer
On Feb 16, 10:58 am, [email protected] wrote:
> Hello,
>
> I have problem with configuring my wxPython script to work with
> Croatian characters like:  ð,¹,¾,è,æ.
> Here is my simple script without wxPython (this script works):
>
>       # -*- coding: utf-8 -*-
>       s = "hello normal string ð¹¾æè"
>       print s
>
> ..here is my snippet with wxPython:
>
>     text = wx.StaticText(self, -1,"Matièni broj",(0,100)) # in this
> example,we have character "è"
>
> ...when I run this text, it looks something like:  "Mati",some weird
> characters ,and "ni"
>
> Regards,
> John

You may be using an ANSI build of wxWidgets instead of a unicode one.
Make sure to enable Unicode when you run ./configure, or if in
Windows, uninstall and download the win32-unicode version of the
wxPython you want.
--
http://mail.python.org/mailman/listinfo/python-list


Re: initialized list: strange behavior

2008-11-24 Thread Jason Scheirer
On Nov 24, 10:34 pm, [EMAIL PROTECTED] wrote:
> Hi Python experts! Please explain this behavior:
>
> >>> nn=3*[[]]
> >>> nn
> [[], [], []]
> >>> mm=[[],[],[]]
> >>> mm
>
> [[], [], []]
>
> Up till now, 'mm' and 'nn' look the same, right? Nope!
>
> >>> mm[1].append(17)
> >>> mm
> [[], [17], []]
> >>> nn[1].append(17)
> >>> nn
>
> [[17], [17], [17]]
>
> ???
>
> Python 2.5 Win XP
>
> Thanks!

You're creating three references to the same list with the
multiplication operator. You can easily get the same behavior because
of similar mechanics in a more common scenario:

In [1]: a = []

In [2]: b = a

In [3]: a, b
Out[3]: ([], [])

In [4]: a.append(100)

In [5]: a, b
Out[5]: ([100], [100])

Python is pass-by-reference, not pass-by-value.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Is it possible (and wise) to extend the None-type ?

2008-11-26 Thread Jason Scheirer
On Nov 26, 11:40 am, Terry Reedy <[EMAIL PROTECTED]> wrote:
> Stef Mientki wrote:
> > hello,
>
> > I've the idea that I always have a lot of useless code in my programs,
> > like the next example.
>
> >  def _On_Menu_File_Open ( self, event = None ):
> >    if event :
> >     event.Skip ()
>
> > instead of
>
> >  def _O
>
> > So I would like to extend the None-type (if that's possible),
> > with a dummy Skip() method.
>
> def Skipper(object):
>      def Skip(): pass
> skipper = Skipper()
>
> def _On_Menu_File_Open ( self, event = skipper ):
>     event.Skip ()
>
> etc.

I think this methods works best, but quite frankly, if a method is
only two lines long, then you've likely got a code smell and no amount
of over-design is going to cover for it.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Multiple Versions of Python on Windows XP

2008-12-02 Thread Jason Scheirer
On Dec 1, 4:49 pm, "Colin J. Williams" <[EMAIL PROTECTED]> wrote:
> Could anyone please point me to
> documentation on the way the msi
> installer handles multiple versions eg.
> Python 2.5, 2.6 and 3.0?
>
> What changes are made to the registry?
>
> Is there some way to specify a default
> version in such a way that it can be
> changed as necessary?
>
> PyScripter uses an option to select a
> version eg.
>
> C:\Program
> Files\PyScripter\PyScripter.exe --python26
>
> but I'm having some trouble with it when
> I attempt edit a python file from the
> Windows Explorer.
>
> I would appreciate any information.
>
> Colin W.

Some more factoids that may be of use:

1. The last Python you install will take over all the file
associations, start menu stuff, etc.
2. You can enumerate over the Pythons you have installed in \
\HKEY_LOCAL_MACHINE\Software\Python\PythonCore\
3. If you silently install a Python PACKAGE made with distutils'
bdist_msi, it will by default install to the latest Python version it
finds (2.6 > 2.5 > 2.4 > 2.3)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Overriding a method at the instance level on a subclass of a builtin type

2008-12-03 Thread Jason Scheirer
On Dec 2, 6:13 pm, Aaron Brady <[EMAIL PROTECTED]> wrote:
> On Dec 2, 6:58 pm, "Zac Burns" <[EMAIL PROTECTED]> wrote:
>
>
>
> > Sorry for the long subject.
>
> > I'm trying to create a subclass dictionary that runs extra init code
> > on the first __getitem__ call. However, the performance of __getitem__
> > is quite important - so I'm trying in the subclassed __getitem__
> > method to first run some code and then patch in the original dict
> > method for the instance to avoid even the check to see if the init
> > code has been run. Various recipes using instancemethod and the like
> > have failed me.
>
> > Curiously if __slots__ is not specified no error occurs when setting
> > self.__getitem__ but the function is not overriden. If __slots__ is
> > ['__getitem__'] however it complains that __getitem__ is read only. I
> > do not understand that behavior.
>
> > --
> > Zachary Burns
> > (407)590-4814
> > Aim - Zac256FL
> > Production Engineer (Digital Overlord)
> > Zindagi Games
>
> That sounds like the State Pattern, from GoF.  
> http://en.wikipedia.org/wiki/State_pattern
>
> I like the idea of 'renaming', not redefining, but reassigning methods
> at different points during an object's lifetime.  I often wish I had
> more experience with it, and more docs talked about it.
>
> It's hard on memory usage, since each instance has its own function
> attribute, even if there's still only one instance of the function.
> Without it, the function attribute is just looked up on the class.
>
> Not thoroughly tested:
>
> >>> class A:
>
> ...     def methA( self ):
> ...             print 'methA'
> ...             self.meth= self.methB
> ...     meth= methA
> ...     def methB( self ):
> ...             print 'methB'
> ...>>> a= A()
> >>> a.meth()
> methA
> >>> a.meth()
>
> methB

The problem with using this this pattern in the way that you've
specified is that you have a potential memory leak/object lifetime
issue. Assigning a bound method of an instance (which itself holds a
reference to self) to another attribute in that same instance creates
a kind of circular dependency that I have discovered can trip up the
GC more often than not.

You can subclass it as easily:

class dictsubclass(dict):
def __getitem__(self, keyname):
if not hasattr(self, '_run_once'):
self.special_code_to_run_once()
self._run_once = True
return super(self, dict).__getitem__(keyname)

If that extra ~16 bytes associated with the subclass is really a
problem:

class dictsubclass(dict):
def __getitem__(self, keyname):
self.special_code_to_run_once()
self.__class__ = dict
return super(self, dict).__getitem__(keyname)

But I don't think that's a good idea at all.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python is slow

2008-12-10 Thread Jason Scheirer
On Dec 10, 10:42 am, cm_gui <[EMAIL PROTECTED]> wrote:
> http://blog.kowalczyk.info/blog/2008/07/05/why-google-should-sponsor-...
>
> I fully agree with Krzysztof Kowalczyk .
> Can't they build a faster VM for Python since they love the language
> so much?
>
> Python is SLOW.    And I am not comparing it with compiled languages
> like C.
> Python is even slower than PHP!
>
> Just go to any Python website and you will know.
> An example is:http://www2.ljworld.com/
> And this site is created by the creators of Django!
>
> And it is not just this Python site that is slow. There are many many
> Python sites which are very slow. And please don’t say that it could
> be the web hosting or the server which is slow — because when so many
> Python sites are slower than PHP sites, it couldn’t be the web
> hosting.   Also, Zope/Plone is even slower.
>
> Python is slow. Very slow.

I have two responses, and could not decide which one to post. Then I
figured I could just do both.

--

Response 1:

You have stumbled on to our plot! We use Python because we hate
getting things done and love nothing more than waiting for things to
complete, because that means more time to drink coffee. Python is a
hoax pushed on the world by the Vast Conspiracy Of People Who Actually
Never Get Anything Done But Enjoy Watching Things Scroll By Very
Slowly While Drinking Coffee.

--

Response 2:

Are you new to Python and frustrated with it? Is that where this is
coming from? If so, I am sorry that Python is so hard.

You can use Jython and get the Java VM or IronPython and get the CLR
VM. There's an immediate fix there for your objections to the CPython
VM. You could investigate getting some higher performance code going
using Stackless. Or move to event-based coding in Twisted and avoid
lots of while loop spins and locking/threading mischief and the other
things that come with network-bound programming like web development.
The PyPy project is also writing a fast Python intepreter with
multiple code output options. Or you can also profile your existing
code and optimize. Or integrate NumPy and Psyco into your efforts. And
you have the advantage of writing C extensions where it makes sense if
you're using CPython -- it's relatively easy and has resulted in fewer
than a dozen fatalities over the course of its existence. There are
options galore here, and 'Python' is actually a large, diverse
ecosystem. Web development is one thing Python does, but is not its
specialized purpose. PHP is a collection of tragic mistakes that
masquerades as a scripting language for the web.

I'd like to see some data on the response times of sites running
various Python web frameworks against each other and versus sites in
other languages. I'm also curious about the perception of speed versus
actual speed here -- if a site pushes 125k of page data a second at a
constant rate or pushes it all in 125k chunks in one second intervals,
the first is going to 'feel' faster initially even though both will
finish transferring the data at the same time and have identical page
load times. And if you're dealing with massive amounts of static
content (javascript frameworks, css, etc) that only needs to go over
the wire one then yeah, the page is going to be slow ON FIRST LOAD but
from then on have 90% of what it needs in local cache, so subsequent
page loads will be smaller and faster. That appears to be the case
with ljworld, at least.
--
http://mail.python.org/mailman/listinfo/python-list


Re: newbie question: if var1 == var2:

2008-12-11 Thread Jason Scheirer
On Dec 11, 3:49 pm, John Machin  wrote:
> On Dec 12, 10:31 am, "Rhodri James" 
> wrote:
>
>
>
> > On Thu, 11 Dec 2008 19:49:23 -, Steve Holden   
> > wrote:
>
> > > Kirk Strauser wrote:
> > >> At 2008-11-29T04:02:11Z, Mel  writes:
>
> > >>> You could try
>
> > >>> for item in fname:
> > >>>     item = item.strip()
>
> > >> This is one case where I really miss Perl's "chomp" function.  It  
> > >> removes a
> > >> trailing newline and nothing else, so you don't have to worry about  
> > >> losing
> > >> leading or trailing spaces if those are important to you.
>
> > > ... and it's so hard to write
>
> > >      item = item[:-1]
>
> > Tsk.  That would be "chop".  "chomp" would be
>
> >      if item[-1] == '\n':
> >          item = item[:-1]
>
> Better:
> if item and item[-1] == '\n':
>     return item[:-1]
> return item

Best:

return item \
   if not (item and item.endswith('\n')) \
   else item[:-1]

Though really you should be using item.rstrip()
--
http://mail.python.org/mailman/listinfo/python-list


Re: AIM client code for Python?

2008-12-16 Thread Jason Scheirer
On Dec 16, 9:54 am, Joe Strout  wrote:
> I'd like to write an AIM bot in Python.  I found and tried
> , but it doesn't work for me:
>
> Connecting...
> Traceback (most recent call last):
>    File "aimbot-1.py", line 17, in 
>      bot.go()
>    File "/Users/jstrout/Documents/Python-Dev/AIMbot/toc.py", line 62,  
> in go
>      self.process_loop()
>    File "/Users/jstrout/Documents/Python-Dev/AIMbot/toc.py", line 156,  
> in process_loop
>      event = self.recv_event()
>    File "/Users/jstrout/Documents/Python-Dev/AIMbot/toc.py", line 230,  
> in recv_event
>      dtemp = self._socket.recv(buflen - len(data))
> socket.error: (54, 'Connection reset by peer')
>
> I wrote to the author a week ago, but never got a reply.  It could be  
> as simple as changing the server addresses in toc.py, currently:
>
> TOC_SERV_AUTH = ("login.oscar.aol.com", 2 )
> TOC_SERV = ( "toc.oscar.aol.com", 9898 )
>
> ...but I don't understand AIM well enough to know the correct values  
> (and was rather hoping that I wouldn't have to).
>
> Does anyone know how to get Py-TOC to work, or have another Python TOC  
> implementation to suggest?
>
> Thanks,
> - Joe

What I did once to get a bot working was to use Pidgin, and
communicate with the instance of Pidgin over D-Bus. This has the happy
side effect of making the bot multi-protocol and handling all the
connection drop issues and the like, as well as allowing for you to
intervene in conversations.

class HookForAccount(object):
def __init__(self, usernames=None):
if usernames is not None:
if isinstance(usernames, basestring):
usernames = [usernames]
usernames = set([x.lower() for x in usernames])
bus = dbus.SessionBus()
obj = bus.get_object("im.pidgin.purple.PurpleService",
"/im/pidgin/purple/PurpleObject")
self.purple = dbus.Interface(obj,
"im.pidgin.purple.PurpleInterface")
self.accountids = set()
for account in self.purple.PurpleAccountsGetAllActive():
if usernames is None or
self.purple.PurpleAccountGetUsername(account).lower() in usernames:
print self.purple.PurpleAccountGetUsername(account)
self.accountids.add(account)
bus.add_signal_receiver(self.got_im,
dbus_interface="im.pidgin.purple.PurpleInterface",
signal_name="ReceivedImMsg")

def got_im(self, code, screenname, message, conversation_id,
flags):
time.sleep(1.75)
self.purple.PurpleConvImSend(self.purple.PurpleConvIm
(conversation_id),
"HELLO!")

if __name__ == "__main__":
logging.getLogger().setLevel(0)
dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
HookForAccount(sys.argv[1:] or None)
loop = gobject.MainLoop()
loop.run()
--
http://mail.python.org/mailman/listinfo/python-list


Re: WinMerge--B/W Shading of Printed Copy to Show Differences?

2008-12-16 Thread Jason Scheirer
On Dec 16, 3:56 pm, "W. eWatson"  wrote:
> Is there a way to highlight differences between the two files when printing
> in b/w? Help suggests there may be some texturing, but all I see is color
> choices.
> --
>                                 W. eWatson
>
>               (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time)
>                Obz Site:  39° 15' 7" N, 121° 2' 32" W, 2700 feet
>
>                      Web Page: 

WinMerge is written in C++ and not even remotely related to Python.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Is this pythonic?

2008-12-18 Thread Jason Scheirer
On Dec 18, 8:45 am, [email protected] wrote:
> On Dec 18, 11:08 am, [email protected] wrote:
>
> > x.validate_output(x.find_text(x.match_filename
> > (x.determine_filename_pattern(datetime.datetime.now()
>
> > Is it even good programming form?
>
> Lisp and Scheme programmers love that style. You can tell by the
> number of parentheses :-). In Python people usually use an
> intermediate variable to break things up a bit but the amount of
> acceptable nesting is a matter of personal style.

I'd say it's fine but breaking up the statement once or twice is a
good idea just because if one of the function calls in this nested
thing throws an exception, a smaller statement with fewer calls makes
for a far more readable traceback. And I hope that this whole
statement all lives inside of a method in the same x class, or is a
higher-level class that makes use of this behavior? If not, you may
want to consider doing so.

class X(object):
  @property
  def todays_filepattern(self):
  return self.match_filename(
  self.determine_filename_pattern(
   datetime.datetime.now()))
  def validate_todays_files(self):
 return self.validate_output(self.find_text
(self.todays_filepattern))
--
http://mail.python.org/mailman/listinfo/python-list


Re: spawning pyhon apps...

2009-01-09 Thread Jason Scheirer
On Jan 9, 2:47 pm, "bruce"  wrote:
> hi...
>
> toying with an idea.. trying to figure out a good/best way to spawn multiple
> python scripts from a parent python app. i'm trying to figure out how to
> determine when all child apps have completed, or to possibly determine if
> any of the child processes have died/halted..
>
> parent app
>  spawn child1
>  spawn child2
>  spawn child3
>  .
>  .
>  .
>  spawn childn
>
> do i iterate through a os.waitpid(pid) for each pid of the child processes i
> create?
>
> is there another approach? code samples/tutorial...??
>
> i've seen various approaches via google, but not just what i'm looking for..
>
> thanks

Investigate the subprocess module, you probably want Popen objects.
You can do a poll loop like

my_popenobjects = [subprocess.Popen("foo.py", "--filename=file
%i.txt"%x) for x in xrange(10)]

while any(popenobject.statuscode is None for popenobject in
my_popenobjects):
  time.sleep(0.25)

If your tasks are more like function calls and less like shell
scripts, then investigate writing your python as an importable module
and use the multiprocessing module, which will do threading/
subprocessing for you.
--
http://mail.python.org/mailman/listinfo/python-list


Re: how can we send keys to keyboard

2008-10-07 Thread Jason Scheirer
On Oct 7, 9:28 am, mhangman <[EMAIL PROTECTED]> wrote:
> On 7 Ekim, 18:57, Mike Driscoll <[EMAIL PROTECTED]> wrote:
>
>
>
> > On Oct 7, 10:42 am, mhangman <[EMAIL PROTECTED]> wrote:
>
> > > On 7 Ekim, 18:34, Mike Driscoll <[EMAIL PROTECTED]> wrote:
>
> > > > On Oct 7, 10:13 am, mhangman <[EMAIL PROTECTED]> wrote:
>
> > > > > how can we send keys to keyboard? i want to write a script that will
> > > > > push keyboard buttons and do what i want. its for a macro prog. there
> > > > > are some kinds at c++ and at java. for example actools prog. but i
> > > > > want to this in python...
>
> > > > > note:im not talking about print a key im talking about use it from its
> > > > > device
> > > > > please help
>
> > > > If I understand you correctly, you're probably wanting something like
> > > > SendKeys:
>
> > > >http://pypi.python.org/pypi/SendKeys/0.3
>
> > > > Unfortunately, this is for Windows only (as far as I can tell). But
> > > > you didn't say what OS you were using, so maybe this will work.
>
> > > > Mike
>
> > > ty mike but it use a c++ module with it. cant we find python/made
> > > module?
> > > or donno..
>
> > > bdw: OS windows, linux doesnt matter just let me learn this
>
> > What difference does it make if it includes a c file (it's not C++)?
> > Python itself relies on C code too for some of it's fastest bits. The
> > "xrange" builtin is one good example. Besides, I think learning C/C++
> > would be a good idea for any Python programmer that wants to get truly
> > proficient in his snake charming.
>
> > Mike
>
> ty mike,
> im just looking for other ways which can improve my style,information.
> i read some java stuff some c++ some c# and c about this work. but can
> python do this whiout include any of this?
> need to learn, thanks for helping

You definitely need SendKeys, and you definitely need to talk to
Windows through some C library. It doesn't matter which bridge you
use, but your code is going to touch something written in C eventually
to accomplish this.

Check out this example: http://code.activestate.com/recipes/65107/

The pywin32 libraries are pretty much a must if you're working in
Windows and Python regardless.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Safe eval of insecure strings containing Python data structures?

2008-10-09 Thread Jason Scheirer
On Oct 9, 9:01 am, Paul Rubin  wrote:
> Lie Ryan <[EMAIL PROTECTED]> writes:
> > in python 2.6, ast.literal_eval may be used to replace eval() for
> > literals.
>
> What happens on literal_eval('[1]*9') ?

The documentation clearly states that it will fail to evaluate and
raise a ValueError because there is an operation in the statement. 5*5
is NOT the literal 25, it is the equivalent to operator.mul(5, 5), and
the same is true to []*x
--
http://mail.python.org/mailman/listinfo/python-list


Re: replace mothod for only one object but not for a class

2008-10-14 Thread Jason Scheirer
On Oct 14, 11:20 am, George Sakkis <[EMAIL PROTECTED]> wrote:
> On Oct 14, 1:50 pm, hofer <[EMAIL PROTECTED]> wrote:
>
>
>
> > Hi,
>
> > I have multiple objects all belonging to the same class
> >  (which I didn't implement and whose code I don't want to modify)
>
> > Now I'd like to change one method for one object only (after it has
> > been created) without adding any overhead
> > to the call of the other object's methods.
>
> > Is this possible?
>
> > Example
> > # This is NOT what I'd like to do
> > # as it overwrites the method for all objects of this class
> > o1 = aclass()
> > o2 = aclass()
> > # call original method
> > o1.method()
> > o2.method()
> > # overwrite the method for the entire class
> > aclass.method = mymethod
> > o1.method() # now new method
> > o2.method() # now new method
>
> > ### What doesn't work, but what I'd like to do
> > o1 = aclass()
> > o2 = aclass()
> > # call original method
> > o1.method()
> > o2.method()
> > # overwrite the method for the entire class
> > o1.method = mymethod
> > o1.method() # now new method
> > o2.method() # still old method
>
> > thanks for any pointers.
>
> Please post the actual code that doesn't work. The following works as
> expected:
>
>     >>> class A(object):
>     ...     def foo(self): return 'Original'
>     ...
>     >>> a = A()
>     >>> b = A()
>     >>> a.foo()
>     'Original'
>     >>> b.foo()
>     'Original'
>     >>> b.foo = lambda: 'Modified'
>     >>> a.foo()
>     'Original'
>     >>> b.foo()
>     'Modified'
>
> HTH,
> George

What you're doing is called monkeypatching. I consider it dangerous,
but to each his own. Python's metaprogramming facilities can handle
it.

The lambda approach can leak, I've had garbage collection issues when
shuffling around bound methods (my objects weren't being collected
when expected, basically). The partial approach is cool, too, but it
won't reliably work with things like __getattr__ and __setattr__,
which I also learned the hard way. The probable best way of going
about it is to define a new class that implements your one method, and
use some on-the-fly magic to create a NEW class that inherits from
both your monkeypatch class and your current instance's class:

In [2]: class main_implementation(object):
   ...: def a(self):
   ...: print 'a'
   ...: def b(self, argb='b'):
   ...: print 'B says %r' % argb
   ...:
   ...:

In [6]: class new_implementation_of_a(object):
   ...: def a(self):
   ...: print "This is a new implementation of A"
   ...:
   ...:

In [7]: mymain = main_implementation()

In [8]: mymain.a()
a

In [9]: mymain.__class__ = type(mymain.__class__.__name__+'MODIFIED',
(new_implementation_of_a, mymain.__class__), {})

In [10]: mymain
Out[10]: <__main__.main_implementationMODIFIED object at 0x0137EA50>

In [11]: mymain.a()
This is a new implementation of A

In [12]: mymain.b()
B says 'b'

The magic here occurs when you create a new class on-the-fly using the
type() built-in function and assign it to the instance's __class__
attribute.

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


Re: Does python is suitable for enterprise cluster management?

2008-11-17 Thread Jason Scheirer
On Nov 16, 8:56 am, Asaf Hayman <[EMAIL PROTECTED]> wrote:
> Is anyone familiar or aware of a successful enterprise class project
> in Python to control and monitor a cluster of computers?
>
> As a part of a bigger project my company needs to build a cluster
> management system. The aim of the system is to control and synchronize
> applications. Namely, a central management will get events from the
> remote applications and from a user and will react with commands to
> the applications.
> Existing tools don’t fit our requirements, so we will have to write it
> ourselves.
> We are currently pondering which programming language will best suite
> us. The two major contenders are Python and Java.
>
> Some requirements:
> 1. Cluster size is about 100 nodes. Only few applications per node.
> 2. Database interface.
> 3. Rate of messages: Few hundred messages per second at peak time.
> 4. External web application for control (only few users)
> 5. RPC between the management system to application written in c.
> 6. The whole system will run within a LAN, and the required
> responsiveness latency should be no more than 1sec.
>
> There are probably some more requirements which are common for cluster
> management systems.
>
> We are currently looking for success stories of a similar projects
> done in Python. It will be great if someone could point me to a
> success story. It will be even better if I could talk with someone
> which was involved in such a project.
>
> Thanks,
> Asaf

Not sure if http://pypi.python.org/pypi/Fabric/0.0.3 is what you need
or not; maybe that in concert with Nagios.
--
http://mail.python.org/mailman/listinfo/python-list


Re: python vs smalltalk 80

2008-11-19 Thread Jason Scheirer
On Nov 18, 10:53 pm, gavino <[EMAIL PROTECTED]> wrote:
> python vs smalltalk 80
>
> which is nicer?

I thought this was comp.lang.colorforth. WHAT IS GOING ON?
--
http://mail.python.org/mailman/listinfo/python-list


Re: pdftk

2009-02-24 Thread Jason Scheirer
On Feb 24, 12:43 pm, JB  wrote:
> Reimar Bauer a écrit :
>
> > Hi
>
> > Does one know about a python interface to pdftk?
> > Or something similar which can be used to fill a form by fdf data.
>
> everyday i use :
>
> import os
> os.system("pdftk.exe source.pdf fill_form data.fdf output output.pdf
> flatten")
>
> and BIM
>
> ;)

Reportlab will let you use an existing PDF as a template, letting you
use its text layout routines to overly your data on the existing page
and output a new document.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Does Paramiko 1.7.2 and 1.6.4 work with CentOS 4

2009-02-24 Thread Jason Scheirer
On Feb 25, 12:55 am, Shah Sultan Alam  wrote:
> Hi Groups,
>  Can you please help me on the following...
>
> 1. Does Paramiko 1.7.2 and 1.6.4 work with CentOS 4
>
> 2. If yes, what is the exact 'yum' command to install paramiko on CentOS 4?
> I have tried all possible ones without success.
>
>         yum install paramiko
>         yum install python-paramiko(with and without version numbers)
>         python-paramiko.noarch
>
> Installing it without yum throws dependency problems which are never
> ending : starting with python-crypto and python(abi) - which I am
> unable to find.
>
> Is there any change that has to be made to the yum repository to point
> it to look in a different place?
>
> 3. Alternatively, I also have apt-get on the CentOS box - can you tell
> me some repos that I can add for apt-get as well?
>
> Regds
> Shah

This may be a question better directed at the CentOS mailing list as I
doubt anyone here is a CentOS package maintainer for paramiko. You're
going to need to build it yourself if it's not in yum. Make sure you
have the python development headers installed, and issue the commands:

wget http://www.lag.net/paramiko/download/paramiko-1.7.4.tar.gz
tar xzf paramiko-1.7.4.tar.gz
cd paramiko-1.7.4
python setup.py build
su -c "python setup.py install"

Alternately, you can issue

python setup.py bdist_rpm

to get an RPM you can install on other machines as well (it will show
up in the ./dist/ directory relative to setup.py). Good luck.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Looking for tips on running Python version 2.6 and 3.0 together on same *WINDOWS* machine

2009-02-24 Thread Jason Scheirer
On Feb 24, 9:20 pm, "Martin v. Löwis"  wrote:
> > It's easy - the registry isn't used except to associate files. The
> > associations are made with the most-recently-installed version.
>
> > I currently have 2.4, 2.5, 2.6 and 3.0 on my Windows machine.
>
> In addition, at install time, there is the choice of not creating
> associations (i.e. links what interpreter should be invoked if you
> double-click a .py file, and what version of IDLE should start
> when you select Edit from the context menu).
>
> So if you install 2.6 first, then 3.0, but deselect the installation
> of associations, 2.6 will continue to be associated with the
> .py, .pyw, and .pyc extensions.
>
> Regards,
> Martin

Technically not true. Python DOES use the registry, but it's per-
version and isolated from each other. Each installs some configuration
data in HKEY_LOCAL_MACHINE\\Software\Python\PythonCore\MAJOR.MINOR, so
you'll have stuff in HKLM\\Software\Python\PythonCore\2.6 and HKLM\
\Software\Python\PythonCore\3.0. And yes, this DOES mean you can't
have 2.6 and 2.6.1 cleanly installed on the machine at the same time.

As long as you keep your .py and .pyw files associated with the
preferred Python interpreter (2.6 I'm assuming) and EXPLICTLY call C:
\Python30\Python.exe when you want to run on 3.0, you're golden.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Are there any python libraries/packages like Juicer/Sprockets/bundle_fu?

2009-03-04 Thread Jason Scheirer
On Mar 4, 1:22 am, Phillip B Oldham  wrote:
> Hi all.
>
> Just wondering whether there are any libraries for python like ruby's
> Juicer[1], Sprocets[2], or bundle_fu[3]?
>
> Thanks!
>
> [1]http://www.cjohansen.no/en/ruby/juicer_a_css_and_javascript_packaging...
> [2]http://getsprockets.com/
> [3]http://code.google.com/p/bundle-fu/

Do you have a reason for needing the same thing implemented in Python,
or are the options in Ruby enough?

http://pypi.python.org/pypi/JSTools/0.1b
You may also be able to extract what you need from
http://pypi.python.org/pypi/TGCombine/1.0.4
--
http://mail.python.org/mailman/listinfo/python-list


Re: Can Python do shopping cart?

2009-03-05 Thread Jason Scheirer
On Mar 5, 2:30 pm, Muddy Coder  wrote:
> Hi Folks,
>
> I know PHP can do shopping cart, such as Zen Cart. I wonder can Python
> do such a thing? Thanks!
>
> Muddy Coder

http://www.satchmoproject.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Can Python do shopping cart?

2009-03-06 Thread Jason Scheirer
On Mar 6, 1:19 am, Lie Ryan  wrote:
> Muddy Coder wrote:
> > Hi Folks,
>
> > I know PHP can do shopping cart, such as Zen Cart. I wonder can Python
> > do such a thing? Thanks!
>
> > Muddy Coder
>
> Python is Turing Complete

"Python is Turing complete" is c.l.p's equivalent to Godwin's law.
>From here on in the thread every post is going to end with "I hate the
GIL why can't get just get rid of it" just for the sake of
completeness.
--
http://mail.python.org/mailman/listinfo/python-list


Re: ipython / vs \ in readline on MS Windows (and ipython help grepper)

2009-03-12 Thread Jason Scheirer
On Mar 10, 3:34 pm, bdb112  wrote:
> Q1/ I run a standard python ditribution with ipython and readline
> under cygwin.  The tab filename completion works fine in the OS (bash
> shell) as expected, and tab filename completion at the ipython command
> line works, but with MS style path separators (backslash: run examples
> \test.py) which the run command itself interprets unix style
> ERROR: File `examplestest.py` not found.
>
> Also Q2/ can I "less" or "grep" the output from help(my_fun)
>
> Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit
> (Intel)]
> IPython 0.8.4 -- An enhanced Interactive Python.

Cygwin does not magically change the platform you are on, the fact
that you are on Windows is hard-coded into the Python.exe binary. Look
for references to os.path.sep in IPython. Windows does let you use
forward slashes as path separators, though, so I am not entirely sure
what your issue is.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Jython on Google AppEngine.

2009-04-09 Thread Jason Scheirer
On Apr 9, 9:12 am, Alan Kennedy  wrote:
> Hi all,
>
> You may be interested to know that you can now run jython 2.2 out of
> the box on Google AppEngine, thanks to their new java support.
>
> A patch is required for jython 2.5, but we will be folding this in
> before the jython 2.5 RC release over the next few weeks.
>
> More details here
>
> http://jython.xhaus.com
>
> Regards,
>
> Alan.

Finally! A way to run Python on App Engine!
--
http://mail.python.org/mailman/listinfo/python-list


Re: calculate field in ARCGIS

2009-04-09 Thread Jason Scheirer
On Apr 9, 12:55 pm, Chris Rebert  wrote:
> On Thu, Apr 9, 2009 at 12:42 PM, Lydia  wrote:
> > Hi Python users,
>
> > I ran into a problem with python coding in ARCGIS. Does anybody have the
> > experience in dealing with this?
>
> > I need to calculate NEWFIELD based on OLDFIELD under condition: if  OLDFIELD
> > == 0 then return string "B" otherwise return "".
>
> > codeblock = "def codefun(code): if code == 0: return \"B\" else: return \"\"
> > "
>
> > gp.CalculateField_management("INFILE", "OLDFIELD", "codefun(!NEWFIELD!",
> > "PYTHON", codeblock)
> > I got error:
>
> > RuntimeError:
> > exceptions.SyntaxError: invalid syntax (line 1)
> > Failed to execute (CalculateField).
>
> Might I recommend you try using the multiline equivalent (assuming
> ArcGIS supports C-style escape sequences):
>
> codeblock = "def codefun(code):\n\tif code == 0:\n\t\treturn
> \"B\"\n\telse:\n\t\treturn \"\" "
>
> Cheers,
> Chris
>
> --
> I have a blog:http://blog.rebertia.com

Looks like an error in your code:

gp.CalculateField_management("INFILE", "OLDFIELD", "codefun(!
NEWFIELD!", "PYTHON", codeblock)

Should be:

gp.CalculateField_management("INFILE", "OLDFIELD", "codefun(!
NEWFIELD!)", "PYTHON", codeblock)

Or you could fold the function into the expression using the ternary
and get rid of your code block param:

gp.CalculateField_management("INFILE", "OLDFIELD", "'B' if !OLDFIELD!
== 0 else ''", "PYTHON")
--
http://mail.python.org/mailman/listinfo/python-list


Re: Can I import from a directory that starts with a dot (.) ?

2009-04-13 Thread Jason Scheirer
On Apr 13, 5:51 pm, Matthew Wilson  wrote:
> I want to have .foo directory that contains some python code.  I can't
> figure out how to import code from that .foo directory.  Is this even
> possible?
>
> TIA
>
> Matt

Yes, but it's not a particularly recommended thing to do as it is
CRAZY. You can get to it from the imp module's functions:

import imp
# Loads a file/dir named .foo or .foo.py on the sys.path, giving it
the overloaded name of foo in sys.modules
imp.load_module('foo', *imp.find_module('.foo'))
# Grab the module into the local namespace, it's been imported in the
system but not here yet
import foo

Seriously. Crazy. It looks strange and hard because it is in no way a
use case that anyone expects you to have. But it's possible.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Using Python after a few years of Ruby

2009-04-14 Thread Jason Scheirer
On Apr 14, 12:01 am, [email protected] wrote:
> Although I'm not 100% new to Python, most of my experience using high-
> level languages is with Ruby. I had a job doing Rails web development
> a little ways back and I really enjoyed it. At my current workplace
> though, we're looking at using Python and I'm trying to get back into
> the Python "groove" as it were.
>
> I've got plenty of materials to get me up to speed on the mechanics of
> the language, but I was wondering about the equivalent of some tools I
> was used to using in Ruby. If there's not anything that's a one-to-one
> equivalent I totally understand, I'm just looking for some pointers
> here to get me started. :)
>
> 1) Rake - is there an equivalent of Rake? I've seen a bit about SCons,
> and it looks really nice, but it seems geared towards being a Make
> replacement for C/C++ rather than something that's used to work with
> Python itself. Is there anything like a Python build tool? (Or do I
> even need something like that? I haven't worked with any large Python
> systems, just little things here and there.)

paver, virtualenv, zc.buildout

> 2) Gems - I've seen a bit about Eggs, but they don't seem to have
> anywhere near the official status gems do for Ruby. Are there any
> "package management" things like this for Python, or do you usually
> just grab the code you need as-is?

easy_install or pip. Just like gems.

> 3) Web frameworks - yeah, I realize there are tons of these, but are
> TurboGears, Django, and Zope still the big ones? I've seen a lot about
> Pylons, is that a separate framework or is it a ... well, frame that
> other things are built on? (TG seems to be related to Pylons at a
> glance?)

Pylons is sort of a large collection of software related to web
development. Turbogears 2.0 builds on it. There is also CherryPy
(Turbogears 1.0 uses that). Django's still the big dog though.

> 4) Unit Test frameworks - If there's a behavioral test suite like
> RSpec that's be awesome, but I'd be happy to settle for a good, solid
> unit testing system.

nose, py.test

> Thanks for any advice!

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


Re: Serious Problem with Timezone

2008-05-19 Thread Jason Scheirer
On May 19, 3:02 pm, T-u-N-i-X <[EMAIL PROTECTED]> wrote:
> Hey There,
>
> I'm a django developer and working on a project right now.. Last week
> I just discovered a new problem in Python.. Here's what I do..
>
> [01:00] ([EMAIL PROTECTED] ~)$ date
> Sal May 20 01:00:10 EEST 2008
> [01:00] ([EMAIL PROTECTED] ~)$ python
> Python 2.5.2 (r252:60911, Feb 23 2008, 21:20:32)
> [GCC 4.2.3] on linux2
> Type "help", "copyright", "credits" or "license" for more information.>>> 
> from datetime import datetime
> >>> datetime.now()
>
> datetime.datetime(2008, 5, 20, 1, 0, 21, 131804)>>> import os
> >>> os.environ["TZ"] = "Europe/Istanbul"
> >>> datetime.now()
>
> datetime.datetime(2008, 5, 19, 22, 0, 38, 578438)
>
>
>
> It's 01:00 in Istanbul now and Python shows 22:00 on 19th of May if I
> set the TZ environment variable.. Django sets that variable
> automatically so I'm having problems with scheduled posts..
>
> I controlled my system's BIOS time.. It was wrong before, so I just
> corrected it.. I set the time to UTC on Linux.. What else can I do ?

You may want to investigate the datetime.astimezone() method, as well
as getting comfortable with using tzinfo objects. Check out
http://pypi.python.org/pypi/pytz/ for a module that can give you the
tz objects you want. Also useful is datetime.utcnow()* and
datetime.replace(tzinfo=other_tzinfo), which will give you that same
time but not 'smartly' try to adjust the components in the datetime
object.

I've found datetime.utcnow() is a little temperamental (bad tzinfo is
assigned by default, making it impossible to do conversions) and you
still need to do datetime.utcnow().replace(tzinfo=utctz) to get it to
behave well.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python is slow

2008-05-22 Thread Jason Scheirer
On May 22, 9:14 am, cm_gui <[EMAIL PROTECTED]> wrote:
> Python is slow.    Almost all of the web applications written in
> Python are slow.   Zope/Plone is slow, sloow, so very slooow.  Even
> Google Apps is not faster.   Neither is Youtube.
> Facebook and Wikipedia (Mediawiki), written in PHP, are so much faster
> than Python.
> Okay, they probably use caching or some code compilation -- but Google
> Apps and those Zope sites probably also use caching.
>
> I've yet to see a web application written in Python which is really
> fast.

This post is a troll written by someone who has already made up their
mind. I really don't recommend trying to argue here. I've written
plenty of fast, fast Python and there are countless Python processes
on servers out there that is not only fast but transparently so.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Do this as a list comprehension?

2008-06-09 Thread Jason Scheirer
On Jun 9, 7:06 am, Ricardo Aráoz <[EMAIL PROTECTED]> wrote:
> Mensanator wrote:
> > On Jun 6, 1:40 pm, The Pythonista <[EMAIL PROTECTED]> wrote:
> >> On Thu, 05 Jun 2008 23:42:07 -0400, John Salerno wrote:
> >>> Is it possible to write a list comprehension for this so as to produce a
> >>> list of two-item tuples?
> >>> base_scores = range(8, 19)
> >>> score_costs = [0, 1, 1, 1, 1, 1, 1, 2, 2, 3, 3] print zip(base_scores,
> >>> score_costs)
> >> score_costs = [(base_scores[i], score_costs[i]) for i in range (len
> >> (base_scores))]
>
> > What happens if your iterables aren't the same length?
>
> >> But, I'd rather just use zip. :-)
>
> > And with zip() you won't get an error, but it won't be correct,
> > either.
>
> Wouldn't it be nice to have leftZip(), rightZip(), and fullZip() for
> when the lists have different lengths? The final tuples for a leftZip
> could be in the form (value, ) and for right zip (, value) (though I
> think this last tuple is not allowed in python's syntax, we might define
> a "Null" or "Empty" name to act as a place holder in the resulting tuples).

You can go

zip(xrange(9, 100L), [0, 1, 1, 1, 1, 1, 1, 2, 2, 3, 3])

since xrange DOES NOT return a list but a constant-memory iterable.

Also, there is itertools for adding default values after you fall off
the end of a list.

>>> import itertools
>>> zip(xrange(100), itertools.chain([0, 1, 1, 1, 1, 1, 1, 2, 2, 3, 3], 
>>> itertools.cycle([None])))

Whose output is:

[(0, 0), (1, 1), (2, 1), (3, 1), (4, 1), (5, 1), (6, 1), (7, 2), (8,
2), (9, 3), (10, 3), (11, None), (12, None), (13, None), (14, None),
(15, None), (16, None), (17, None), (18, None), (19, None), (20,
None), (21, None), (22, None), (23, None), (24, None), (25, None),
(26, None), (27, None), (28, None), (29, None), (30, None), (31,
None), (32, None), (33, None), (34, None), (35, None), (36, None),
(37, None), (38, None), (39, None), (40, None), (41, None), (42,
None), (43, None), (44, None), (45, None), (46, None), (47, None),
(48, None), (49, None), (50, None), (51, None), (52, None), (53,
None), (54, None), (55, None), (56, None), (57, None), (58, None),
(59, None), (60, None), (61, None), (62, None), (63, None), (64,
None), (65, None), (66, None), (67, None), (68, None), (69, None),
(70, None), (71, None), (72, None), (73, None), (74, None), (75,
None), (76, None), (77, None), (78, None), (79, None), (80, None),
(81, None), (82, None), (83, None), (84, None), (85, None), (86,
None), (87, None), (88, None), (89, None), (90, None), (91, None),
(92, None), (93, None), (94, None), (95, None), (96, None), (97,
None), (98, None), (99, None)]
--
http://mail.python.org/mailman/listinfo/python-list


Re: Iterate creating variables?

2008-06-13 Thread Jason Scheirer
On Jun 13, 8:11 am, [EMAIL PROTECTED] wrote:
> I have twenty-five checkboxes I need to create (don't ask):
>
> self.checkbox1 = ...
> self.checkbox2 = ...
> .
> .
> .
> self.checkbox25 = ...
>
> Right now, my code has 25 lines in it, one for each checkbox, since
> these are all variables.
>
> Is there a way to write a loop so that I can have fewer lines of code
> but still keep the variables?
>
> I've tried:
>
> for o in xrange(25):
>     self.checkbox[o] = ...
>
> which didn't work, and
>
> for o in xrange(25):
>     self.checkbox[''%d'%(o)] = ...
>
> which also didn't work.
>
> Both give the error message: "Attribute error: Main.App has no
> attribute "checkbox"", which clearly indicates that I'm not keeping
> the "variability" aspect I want.
>
> Is there a way?
>
> I appreciate any and all answers!
>
> Thanks!

for x in xrange(1, 26):
  setattr(self, 'checkbox_%i' % x, ...)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Was the move to Python 2.0 as big a deal?

2008-06-14 Thread Jason Scheirer
On Jun 14, 9:35 am, John Salerno <[EMAIL PROTECTED]> wrote:
> Just curious if people put up any resistance to 2.0 like some people do
> for 3.0. Was it as big of a change in the language, or was the
> transition smoother? It seems silly for anyone to say they would prefer
> to stick with 1.x versions at this point, so perhaps we'll get there
> with 3.0 eventually too.
>
> Anyway, I'm just trying to figure out if the whole "I don't like 3.0"
> mentality (of some people, not all of course) is merely a result of it
> still being new and not even released yet, and will completely go away
> after a year or two; or if there really are such drastic changes that
> people won't want to adopt it at all.

A lot of the bigger changes and warts that have emerged in the past
decade or so of the 2.0 series (text encoding madness anyone?) have
been tabled until the 3.0 transition, so any compatibility breaks for
the sake of fixing inconsistencies and ugliness in Python have been
accruing and are finally being applied in 3.0. The 1.5->2.0 transition
was a little strange, but I think a large reason that it was less
painful was because the language was younger, less established and had
far fewer people programming in it (and correspondingly smaller
codebases) to transition over.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Combining music or video files?

2008-06-15 Thread Jason Scheirer
On Jun 15, 7:53 pm, John Salerno <[EMAIL PROTECTED]> wrote:
> Before I try this and destroy my computer :) I just wanted to see if
> this would even work at all. Is it possible to read a binary file such
> as an mp3 or an avi, put its contents into a new file, then read another
> such file and append its contents to this same new file as well, thereby
> making, for example, a single long video instead of two smaller ones?
>
> Thanks.

This works with basic mpeg videos, but pretty much nothing else.
You're going to need some video editing software.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Please explain Python "__whatever__" construct.

2008-06-16 Thread Jason Scheirer
On Jun 16, 2:56 pm, [EMAIL PROTECTED] wrote:
> After a couple of weeks studying Python, I already have a few useful
> scripts, including one that downloads 1500 Yahoo stock quotes in 6
> seconds. However, many things are puzzling to me. I keep on seeing
> things like "__main__" in scripts.  A more obscure example would be
> "__add__" used in string concatenation. For example, I can use "Hello
> "+"world (or just "Hello" "world") to join those two words. But I can
> also use "Hello ".__add__("world"). When and why would I ever use
> "__main__" or the many other "__whatever__" constructs?

http://docs.python.org/lib/genindex.html#letter-_
--
http://mail.python.org/mailman/listinfo/python-list


Re: Porn Addiction

2008-06-25 Thread Jason Scheirer
On Jun 24, 5:24 pm, [EMAIL PROTECTED] wrote:
> Help, I'm addicted to porn. I've been downloading porn online and
> masturbating to it for a few years... Lately it's gotten even worse, I
> spend hours and hours surfing and masturbating to it. It's taking over
> my life and ruining everything.. I even missed days from work because
> of this addiction.
>
> I'm going to the porn as a way to avoid unwanted feelings or
> procrastination and then it just takes over.
>
> What can I do to end this horrible addiction?
>
> -Hugh

Obviously porn is awesome and an integral part of your life, you
spambot (and your responding stormbot friends).

The only solution is PETABYTES OF PORN. TERRIBLE TERRIBLE PORN.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Help me optimize my feed script.

2008-06-26 Thread Jason Scheirer
On Jun 26, 12:30 pm, [EMAIL PROTECTED] wrote:
> I wrote my own feed reader using feedparser.py but it takes about 14
> seconds to process 7 feeds (on a windows box), which seems slow on my
> DSL line. Does anyone see how I can optimize the script below? Thanks
> in advance, Bill
>
> # UTF-8
> import feedparser
>
> rss = [
> 'http://feeds.feedburner.com/typepad/alleyinsider/
> silicon_alley_insider',
> 'http://www.techmeme.com/index.xml',
> 'http://feeds.feedburner.com/slate-97504',
> 'http://rss.cnn.com/rss/money_mostpopular.rss',
> 'http://rss.news.yahoo.com/rss/tech',
> 'http://www.aldaily.com/rss/rss.xml',
> 'http://ezralevant.com/atom.xml'
> ]
> s = '\n\nC:/x/test.htm\n'
>
> s += '\n'\
>      'h3{margin:10px 0 0 0;padding:0}\n'\
>      'a.x{color:black}'\
>      'p{margin:5px 0 0 0;padding:0}'\
>      '\n'
>
> s += '\n\n\n'
>
> for url in rss:
>         d = feedparser.parse(url)
>         title = d.feed.title
>         link = d.feed.link
>         s += '\n'+ title +'\n'
>         # aldaily.com has weird feed
>         if link.find('aldaily.com') != -1:
>                 description = d.entries[0].description
>                 s += description + '\n'
>         for x in range(0,3):
>                 if link.find('aldaily.com') != -1:
>                         continue
>                 title = d.entries[x].title
>                 link = d.entries[x].link
>                 s += ''+ title +'\n'
>
> s += '\n\n'
>
> f = open('c:/scripts/myFeeds.htm', 'w')
> f.write(s)
> f.close
>
> print
> print 'myFeeds.htm written'

I can 100% guarantee you that the extended run time is network I/O
bound. Investigate using a thread pool to load the feeds in parallel.
Some code you might be able to shim in:

# Extra imports
import threading
import Queue

# Function that fetches and pushes
def parse_and_put(url, queue_):
  parsed_feed = feedparser.parse(url)
  queue_.put(parsed_feed)

# Set up some variables
my_queue = Queue.Queue()
threads = []

# Set up a thread for fetching each URL
for url in rss:
  url_thread = threading.Thread(target=parse_and_put, name=url,
args=(url, my_queue))
  threads.append(url_thread)
  url_thread.setDaemonic(False)
  url_thread.start()

# Wait for threads to finish
for thread in threads:
  thread.join()

# Push the results into a list
feeds_list = []
while not my_queue.empty():
  feeds_list.append(my_queue.get())

# Do what you were doing before, replacing the for url in rss with for
d in feedS_list
for d in feeds_list:
title = d.feed.title
link = d.feed.link

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


Re: Use of the "is" statement

2008-06-27 Thread Jason Scheirer
On Jun 27, 8:38 am, Gary Herron <[EMAIL PROTECTED]> wrote:
> Joel Corbin wrote:
> > Hello,
>
> > I'm trying to clarify what exactly the behaviour of the is statement
> > is (or should be). Naturally, this has been nearly impossible to
> > google for, even using quotations... It is my impression that the is
> > statement should be equivalent to "==", at least on some level.
> > However, this equivalency seems to be inconsistent for reasons I can't
> > decipher. Out of the following 3 cases, only 2 return True. What is
> > the difference (and why is there one) in the third case?
>
> Comparing two numbers or strings with "is" is equivalent to asking if
> the two numbers or strings are stored in the same location in memory.  
> But since you have no control where values are stored when you bind them
> to a name, this is completely pointless.
>
> In
>   a=15
>   b=15
> it is implementation dependent whether the value 15 is stored once and
> refereed to twice, or stored twice.
>
> In short:  *never* use "is".
>
> (A longer answer can find some uses cases for "is", but stick with the
> short answer for now.)
>
> Gary Herron
>
>
>
> > Python 2.5.2
> > >>> 'string' is 'string'                   #simple assignment works
> > True
> > >>> s = 'string'      
> > >>> s is 'string'        
> > True
> > >>> def make_string():   return 'test'     #but function behaviour varies
> > >>> def arg_to_str(arg): return str(arg)
> > >>> make_string() is 'test'
> > True
> > >>> arg_to_string('works') is 'works'      # this works
> > True
> > >>> arg_to_string(15) is '15'              # but this doesnt
> > >>> arg_to_string(15) is arg_to_string(15) # nor this!
> > >>> arg_to_string(15)
> > '15'
> > >>> arg_to_string(15) == arg_to_string(15)
> > True
>
> > This became a problem when I was using file.tell() and again when
> > using a custom function. If I am using is in the wrong context, what
> > is the right one?
> > Joel
>
> > 
>
> > --
> >http://mail.python.org/mailman/listinfo/python-list

Is is identity, not equality. It's the equivalent of comparing two
pointers' addresses in C.

You can get the memory location of an object x in python using the
id() function, so remember the following:

a is b

IS THE SAME THING AS

id(a) == id(b)

The reason 'is' works for things like 'a is None' is because there is
only one None builtin in memory ever, all the variables assigned to
none merely point at it.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Django or TurboGears for a new project

2008-06-27 Thread Jason Scheirer
On Jun 27, 9:52 am, Kirk Strauser <[EMAIL PROTECTED]> wrote:
> We're looking to migrate a Zope site to Django, but before getting beyond
> the dreaming stage, I thought I'd see what others are doing these days.
>
> If you were going to start a fairly complex site today with lots of DB
> integration, would you begin with Django or TurboGears, or something else
> entirely?
>
> I'm more interested in social, rather than technical reasons (unless there's
> something you absolutely love or despise about one or the other).
> Popularity is actually a pretty big consideration because I'd like to work
> with an eager community who's doing cool new things.
>
> I know asking for comparisons like this is potentially flamebait-ish, but I
> really don't mean it that way.  It's just that I don't have a lot of friends
> in the industry in this particular development niche who I can ask for
> recommendations, and this seems like as good a place as any to find subject
> matter experts.
>
> Thanks,
> --
> Kirk Strauser
> The Day Companies

I've noticed I write a lot less code with TurboGears (as in my apps
are done faster and smaller), but you're going to find more Django
programmers and therefore a larger developer force and more recipes
online.
--
http://mail.python.org/mailman/listinfo/python-list


Re: "method involving two objects" is that possible in Python?

2008-06-27 Thread Jason Scheirer
On Jun 27, 2:41 pm, Kurda Yon <[EMAIL PROTECTED]> wrote:
> Hi,
>
> I just started to learn Python. I understood how one can create a
> class and define a method related with that class. According to my
> understanding every call of a methods is related with a specific
> object. For example, we have a method "length", than we call this
> method as the following "x.length()" or "y.length()" or "z.length()",
> where z, y, and z are objects of the class.
>
> I am wandering if it is possible to create a method which is related
> not with a single object (as in the previous example) but with a pare
> of objects. For example, I want to have a class for vectors, and I
> want to have a methods which calculate a dot product of two vectors.
> One of the possibilities is to use __mul__ and that I calculated dot
> product of "x" and "y" just as "x * y". However, I am wandering if I
> can declare a method in a way that allows me to calculate dot product
> as "dot(x,y)".
>
> Thank you in advance.

def dot(x, y):
  ...

class Vector:
  __mul__ = dot

or

class Vector:
  def __mul__(x, y):
 return dot(x, y)

You can refer to the function defined as dot, assuming dot(x, y)
returns some vector z. The first argument (x) will be bound to self in
either case in any Vector instance.
--
http://mail.python.org/mailman/listinfo/python-list


Re: GUI Programming by hand not code with Python Code

2008-07-06 Thread Jason Scheirer
On Jul 6, 7:33 pm, [EMAIL PROTECTED] wrote:
> Is their a program that lets you design a GUI by hand (like gambas)
> not by code (like wxpython) but the commands are in python?
>
> A program similar to gambas or vb
>
> Gambas with python code instead of gambas code would be perfect.
>
> Thanks in advance

Glade for GTK, wxGlade for wxPython.
--
http://mail.python.org/mailman/listinfo/python-list


Re: tkinter for my python program !!

2008-07-23 Thread Jason Scheirer
On Jul 23, 11:38 am, David <[EMAIL PROTECTED]> wrote:
> > Further, finally when i invoke the python program by
> > giving the necessary input file, i get the following
> > errors .
> > Does it have any relation with the python version installed ?
>
> yes
>
> > I am using Redhat 9.0
>
> You may want to install a current Linux distro.

I don't think this is a Python question at all, and Red Hat does offer
technical support.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Automatically fill in forms on line

2008-03-31 Thread Jason Scheirer
On Mar 31, 9:50 am, "Jackie Wang" <[EMAIL PROTECTED]> wrote:
> Dear all,
>
> I want to automatically complete the following task:
>
> 1. Go tohttp://www.ffiec.gov/Geocode/default.aspx;
> 2. Fill in an address in the form "Street Address:" . e.g. "1316 State
> Highway 102";
> 3. Fill in a ZIPcode in the form "Zip Code:" . e.g. "04609";
> 4. Click the bottom "search";
> 5. In the opened page, extract and save the number after "Tract Code".
> In the example, it will be "9659".
> 6. Repeat Step 1 with a new address.
>
> Can Python realize these steps? Can these steps be done witout
> openning and IE windows? Especially, I dont know how to write code for
> step 2, 4 and 5.
>
> Thank you!

You may also want to look at the Yahoo! maps API, which will also give
you geocoding with a much nicer interface:

http://www.yahooapis.com/maps/rest/V1/geocode.html

unless you specifically need to use the TeleAtlas data or the API
licensing is incompatible with the task at hand, I'd recommend using
that instead.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Automatically fill in forms on line

2008-03-31 Thread Jason Scheirer
On Mar 31, 10:35 am, Jason Scheirer <[EMAIL PROTECTED]> wrote:
> On Mar 31, 9:50 am, "Jackie Wang" <[EMAIL PROTECTED]> wrote:
>
>
>
> > Dear all,
>
> > I want to automatically complete the following task:
>
> > 1. Go tohttp://www.ffiec.gov/Geocode/default.aspx;
> > 2. Fill in an address in the form "Street Address:" . e.g. "1316 State
> > Highway 102";
> > 3. Fill in a ZIPcode in the form "Zip Code:" . e.g. "04609";
> > 4. Click the bottom "search";
> > 5. In the opened page, extract and save the number after "Tract Code".
> > In the example, it will be "9659".
> > 6. Repeat Step 1 with a new address.
>
> > Can Python realize these steps? Can these steps be done witout
> > openning and IE windows? Especially, I dont know how to write code for
> > step 2, 4 and 5.
>
> > Thank you!
>
> You may also want to look at the Yahoo! maps API, which will also give
> you geocoding with a much nicer interface:
>
> http://www.yahooapis.com/maps/rest/V1/geocode.html
>
> unless you specifically need to use the TeleAtlas data or the API
> licensing is incompatible with the task at hand, I'd recommend using
> that instead.

And as a follow up, check out the Python Geocoding Toolbox:
http://exogen.case.edu/projects/geopy/

It already has Yahoo! Geocoding API bindings, as well as Google Maps
geocidng bindings in a nice Pythonic interface.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: XML Parsing

2008-04-01 Thread Jason Scheirer
On Apr 1, 12:42 pm, Alok Kothari <[EMAIL PROTECTED]> wrote:
> Hello,
>   I am new to XML parsing.Could you kindly tell me whats the
> problem with the following code:
>
> import xml.dom.minidom
> import xml.parsers.expat
> document = """Lettermanis token>betterthan token>JayLeno"""
>
> # 3 handler functions
> def start_element(name, attrs):
> print 'Start element:', name, attrs
> def end_element(name):
> print 'End element:', name
> def char_data(data):
> print 'Character data:', repr(data)
>
> p = xml.parsers.expat.ParserCreate()
>
> p.StartElementHandler = start_element
> p.EndElementHandler = end_element
> p.CharacterDataHandler = char_data
> p.Parse(document, 1)
>
> OUTPUT:
>
> Start element: token {u'pos': u'nn'}
> Character data: u'Letterman'
> End element: token
>
> Traceback (most recent call last):
>   File "C:/Python25/Programs/eg.py", line 20, in 
> p.Parse(document, 1)
> ExpatError: junk after document element: line 1, column 33

Your XML is wrong. Don't put line breaks between .
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: object-relational mappers

2008-04-01 Thread Jason Scheirer
On Apr 1, 1:40 pm, Aaron Watters <[EMAIL PROTECTED]> wrote:
> I've been poking around the world of object-relational
> mappers and it inspired me to coin a corellary to the
> the famous quote on regular expressions:
>
> "You have objects and a database: that's 2 problems.
> So: get an object-relational mapper:
> now you have 2**3 problems."
>
> That is to say I feel that they all make me learn
> so much about the internals and features of the
> O-R mapper itself that I would be better off rolling
> my own queries on an as-needed basis without
> wasting so many brain cells.
>
> comments?
>
>-- Aaron Watters
>
> ===http://www.xfeedme.com/nucular/pydistro.py/go?FREETEXT=mild+exponenti...

You're going to have to learn how any of the OR mappers work to get
anything reasonable out of them, and you are going to need to commit
and invest the time to learn how one works. I would argue that you
should try making a prototype using one or two OR mappers (or just use
SQLAlchemy/Elixir and be done with it) with your existing database and
see which most efficiently does what you need it to. If you get to the
point where the queries are getting too complex to reasonably manage
as python code, then yeah, use raw SQL because that is what it's good
for. Most OR mappers will allow you to sprinkle in raw SQL as needed.

I think it's natural to be paralyzed by all the choices you have, but
just start writing some code and go from there.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Unicode conversion problem (codec can't decode)

2008-04-03 Thread Jason Scheirer
On Apr 3, 9:35 pm, "Eric S. Johansson" <[EMAIL PROTECTED]> wrote:
> I'm having a problem (Python 2.4) converting strings with random 8-bit
> characters into an escape form which is 7-bit clean for storage in a database.
> Here's an example:
>
> body = meta['mini_body'].encode('unicode-escape')
>
> when given an 8-bit string, (in meta['mini_body']), the code fragment above
> yields the error below.
>
> 'ascii' codec can't decode byte 0xe1 in position 13: ordinal not in range(128)
>
> the string that generates that error is:
>
> Reduce Whát You Owe by 50%. Get out of debt today!Reduuce Interest &
> |V|onthlyy Paymeñts Easy, we will show you how..Freee Quote in 10
> Min.http://www.freefromdebtin.net.cn
>
> I've read a lot of stuff about Unicode and Python and I'm pretty comfortable
> with how you can convert between different encoding types.  What I don't
> understand is how to go from a byte string with 8-bit characters to an encoded
> string where 8-bit characters are turned into  two character hexadecimal 
> sequences.
>
> I really don't care about the character set used.  I'm looking for a matched 
> set
> of operations that converts the string to a seven bits a form and back to its
> original form.  Since I need the ability to match a substring of the original
> text while the string is in it's encoded state, something like Unicode-escaped
> encoding would work well for me.  unfortunately, I am missing some knowledge
> about encoding and decoding.  I wish I knew what cjson was doing because it 
> does
> the right things for my project.  It takes strings or Unicode, stores 
> everything
> as Unicode and then returns everything as Unicode.  Quite frankly, I love to
> have my entire system run using Unicode strings but again, I missing some
> knowledge on how to force all of my modules to be Unicode by default
>
> any enlightenment would be most appreciated.
>
> ---eric
>
> --
> Speech-recognition in use.  It makes mistakes, I correct some.

ASCII is technically only the seven-bit characters, so the codec is
just being very 'correct'. One trick you may want to try is a
string.decode() before your encode using some 8-bit encoding, such as
latin-1:

body = meta['mini_body'].decode('latin-1').encode('unicode-escape')

The problem here is that you don't really ever know EXACTLY which
single-byte character set you're dealing with, so there's no guarantee
you're going to be translating the CORRECT sequence of bytes back and
forth -- for instance, the addition of the Euro symbol, which was
fairly recent, supplanting the place of the old generic 'currency'
character. There are libraries such as Mark Pilgrim's port of the
Mozilla character detection code ( http://chardet.feedparser.org/ ),
but from my experience it doesn't do differentiation between latin
sets well, it's better at detecting CJK character encodings. If you're
merely using some unicode file/database as a dumb store you plan to
eventually push back into a sequence of bytes, you may be well off
doing string.decode('some-random-encoding').encode('utf-8') when
pushing in and string.decode('utf-8').encode('some-random-encoding')
when getting it back out.

Another thing to consider is a lot of XML libraries will create
unicode string objects that ARE NOT REALLY UNICODE -- something that
bit me when using cElementTree is that if an XML file is in latin-*
without a declaration of it being in that charset, it will still
create unicode string instances, but with illegal characters in them.
This causes Python to lead you down the garden path until you try to
encode the string again. At that point, it will try to validate it and
throw that exception. I usually use an idiom like this:

def join_chars(x):
  def __dummy(*args, **kws):
 return ''.join(x(*args, **kws))
  return __dummy

@join_chars
def unidecode(unicode_string):
  for character in unicode_string:
try:
yield character.decode('utf-8').encode('utf-8')
except:
yield ord(character)

And pass all my potentially invalid 'unicode' strings through it,
giving an explicit try when encoding each character. It's slow, but
it's really the only quick, reproducible way I've found around the
problem.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie: How to pass a dictionary to a function?

2008-04-07 Thread Jason Scheirer
On Apr 7, 8:54 pm, BonusOnus <[EMAIL PROTECTED]> wrote:
> How do I pass a dictionary to a function as an argument?
>
> # Say I have a function foo...
> def foo (arg=[]):
> x = arg['name']
> y = arg['len']
>
> s = len (x)
>
> t = s + y
>
> return (s, t)
>
> # The dictionary:
>
> dict = {}
> dict['name'] = 'Joe Shmoe'
> dict['len'] = 44
>
> # I try to pass the dictionary as an argument to a
> # function
>
> len, string = foo (dict)
>
> # This bombs with 'TypeError: unpack non-sequence'
>
> What am I doing wrong with the dictionary?

You want to
return s, t
NOT return (s, t) -- this implicitly only returns ONE item
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Google App Engine

2008-04-08 Thread Jason Scheirer
On Apr 8, 7:50 pm, John Nagle <[EMAIL PROTECTED]> wrote:
> Duncan Booth wrote:
> > Google have announced a new service called 'Google App Engine' which may
> > be of interest to some of the people here
>
> OK, now we need a compatibility layer so you can move apps from
> Google App Engine to your own servers.  You don't want to be locked
> into a single vendor solution, especially when they reserve the right
> to start charging.
>
> Their data store uses a subset of SQL, so it's probably possible
> to write a conversion layer allowing use of MySQL.
>
> John Nagle

It supports Django, and more importantly, WSGI, so any 'framework' you
build on top of it should transfer out. Heck, you have a stand-alone
python script that comes with the developer kit for hosting your apps
on YOUR computer that you could port to use YOUR database and be done
with it. Write your own ORM or just some decent OO code for handling
data access so the database access layer can be swapped out and you
are golden. I really doubt getting away from the Googe App Engine is
going to be too terribly difficult for any intermediate Python
programmer, assuming good up-front application design.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: get array element

2008-04-10 Thread Jason Scheirer
On Apr 10, 10:22 am, "[EMAIL PROTECTED]"
<[EMAIL PROTECTED]> wrote:
> I have an array, and I would like to get the indice value.
>
> a = array([13,14,15,16])
>
> I would like something like a.getindice(15)
>
> If I want 15 it would return 2

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


Re: String Literal to Blob

2008-04-12 Thread Jason Scheirer
On Apr 12, 2:44 pm, Steve Holden <[EMAIL PROTECTED]> wrote:
> Victor Subervi wrote:
> > in line...
>
> > On Fri, Apr 11, 2008 at 2:05 PM, Steve Holden <[EMAIL PROTECTED]
> > > wrote:
>
> > Victor Subervi wrote:
> >  > I have worked on this many hours a day for two weeks. If there is an
> >  > easier way to do it, just take a minute or two and point it out. Have
> >  > you heard of the Law of Diminishing Returns? I have passed it
> > long ago.
> >  > I no longer want to waste time trying to guess at what you are
> > trying to
> >  > tell me.
> >  > Victor
>
> >  > On Fri, Apr 11, 2008 at 8:55 AM, Steve Holden
> > <[EMAIL PROTECTED] 
> >  > >> wrote:
> > Where you have
>
> > content = col_fields[0][14].tostring()
> > pic = "tmp" + str(i) + ".jpg"
> > img = open(pic, "w")
> > img.write(content)
> > print '' % pic
> > img.close()
>
> > instead write
>
> > print content
>
> > Like this, I presume?
>
> Yes. You might need to use content.tostring() - I am not familiar with
> MySQL blobs.
>
> > img = open(pic, "w")
> > img.write(content)
> > print ' > value="%s">' % pic
> > print content
> > #print '\n' % pic
> > Does not work _at_all LOL. You will recall, also, that you once gave me
> > a line similar to the one commented out (but without writing then
> > opening the file). THAT did not work, either. So now do you see why I am
> > frustrated??
>
> > Then browse to the URL this program serves and you will see the image
> > (assuming you are still sending the image/jpeg content type).
>
> > Well, as I mentioned before, I am sending text/html because the page,
> > like almost all web pages, has a whole lot more content than just
> > images. Or, perhaps you are suggesting I build my pages in frames, and
> > have a frame for every image. Unsightly!
>
> Dear Victor:
>
> If you cannot understand, after being told several times by different
> people, that pages with images in them are achieved by multiple HTTP
> requests, then there is little I can do to help you.
>
>
>
> > Once you
> > can see the image, THEN you can write a page that refers to it. Until
> > you start serving the image (NOT pseudo-html with image data embedded in
> >  it) nothing else will work.
>
> > My solution works just fine, thank you. It is inelegant. But it now
> > appears to me, and I dare say rather clearly, that this inelegance is
> > the fault of python itself. Perhaps this should be brought to Guido´s
> > attention.
> > Victor
>
> You can say it as clearly as you like, but if you say it too loudly you
> will make a laughing stock of yourself.
>
> You surely don't think that a language that supports Zope, TurboGears,
> Pylons and Django (to name but the first four that come to mind) is
> unsuitable for web programming?
>
> Please, do yourself a big favor and persist with this until you
> understand what you are doing wrong and how to serve dynamic images. It
> appears that the learning may be painful, but I guarantee it will be
> worthwhile.
>
> regards
>   Steve
> --
> Steve Holden+1 571 484 6266   +1 800 494 3119
> Holden Web LLC  http://www.holdenweb.com/

There _is_ a way to embed image data in HTML that is supported by
every major browser. It is ugly. Using the RFC 2397 (http://
www.ietf.org/rfc/rfc2397) spec for data URLs you could go

'' % base64.b64encode(image_data)

Obviously you need to import the base64 module somewhere in your code
and base64-encoded data is about a third larger than it would be
otherwise, so embedding anything particularly large is going to be a
huge pain and affect page load times pretty badly.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Easiest way to get started with WebApps?

2008-04-18 Thread Jason Scheirer
On Apr 18, 12:06 pm, [EMAIL PROTECTED] wrote:
> which is the easiest module to use to just get started with webapps
> quicklya nd starting getting things up and running, not advanced stuff
> just basic.

web.py is probably the most reasonable small webapp framework to get
going (it's a very small download and install, with little to no
configuration). It does lack a lot of features you may eventually want
and you will have to roll yourself, but I really strongly recommend it
if you already know something about web programming. I've had a lot of
success teaching newbie swith TurboGears, but that's pretty
heavyweight and every time you mention it everyone asks why you don't
just use Django or Pylons.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: py3k concerns. An example

2008-04-18 Thread Jason Scheirer
On Apr 18, 4:19 pm, Kay Schluehr <[EMAIL PROTECTED]> wrote:
> On 18 Apr., 23:09, Matimus <[EMAIL PROTECTED]> wrote:
>
> > The reason it doesn't work is that you are unpacking the dictionary
> > with **, and you have done nothing to define any keys or define a
> > length.
>
> This is a non-issue. The class derives from dict; it has all the
> desired attributes. It is also not a problem in particular because
> these properties are not requested by format ( at least not in the
> code I have examined which was admittedly just a critical section that
> caused the exception ).
>
> > Adding to that... don't worry about py3k. Nobody is forcing you to
> > switch. In fact, you are encouraged not to until you are comfortable.
> > Py3k won't _break_ your code. You wrote the code for Python 2.x use it
> > in 2.x. Python 2.x probably has a good 5-10 years remaining.
>
> These advices start to get annoying.
>
> Software hardly ever exists in isolation for the sake of the beauty of
> the algorithm but is supplementary to a large framework/engine/
> library. So if e.g. Django switches to 3 everyone who works with it
> has to switch sooner or later as well or lose track otherwise, no
> matter how long Python 1.5.2 or Python 2.5.2 or whatever version will
> be maintained. If Pythons code base becomes fragmented it will be
> harmful and affect almost everyones work.

This has happened before, though -- I remember the pain of moving to
2.0 from the 1.5 branch way back when, and it wasn't getting my 1.5
code to work in 2.0, it was being jealous of all the cool features of
2.0 that I had to wait to get. I was working in production with 1.5 in
2000 and all the libraries available for Python gradually stopped
supporting 1.5 to pick up interesting 2.0 features that actually made
them easier to work with, and new libraries all began to assume you
were using a 2.0+ Python version because that's what was current. By
2003-2004 everyone I knew had switched over to 2.0, but by then I had
had nearly 5 years to port my legacy 1.5 code to 2.0, take advantage
of the 2.0 version's features, and do plenty of testing of my 1.5
codebase in 2.0 before I switched my production systems over. Not to
mention the fact that plenty of warning was offered BEFORE 2.0 was
released and 1.5 was not abruptly ended, but gradually phased out
until only the teeniest far ends of the long tail were using it. The
2.6->3.0 process is going to be even less of a pain than the 1.5->2.0
conversion, which was not hard at all going forward into it. You may
not want to switch, but by the time you decide to it will be pretty
easy to move on -- the extreme opposite reality being your application
will be so frozen that both your Python version and your codebase will
be fossils, left to hum on completely unchanged on some forgotten
server like so much other legacy code.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What happened with python? messed strings?

2008-04-20 Thread Jason Scheirer
On Apr 20, 11:54 am, <[EMAIL PROTECTED]> wrote:
> Hi,
> I used extensively python and now I find this mess with strings,
> I can't even reproduce tutorial examples:>>> "apfel".encode('utf-8')  (it was 
> with umlaut)
>
>   File "", line 0
>
>     ^
> SyntaxError: 'ascii' codec can't decode byte 0xc4 in position 1:
> ordinal not in range(128)

Two things: Mark the character encoding of your file ( read
http://www.python.org/doc/2.3/whatsnew/section-encodings.html ), and
then if that doesn't work try to .decode('something') your string
first with the appropriate codec, then you get a unicode object for
free and you don't need the .encode('utf-8'). Also read the slides at
http://farmdev.com/talks/unicode/ for some good information about
unicode in Python.

>
> Is there any good guide to this mess of codecs and hell ?
>
> python should have stayed at version 1.5, every single 'improvement'
> has been a mess. But this is the definitive hell.

It's true -- decorators, the class/type cleanup, properties, -= and
+=, list comprehensions, generators, distutils, and all the new
modules in the standard library are completely, entirely useless.
Python SHOULD have stayed at 1.5.

>
> thanks!
>
> --
> SDF-EU Public Access UNIX System -http://sdf-eu.org


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


Re: Nested lists, simple though

2008-04-20 Thread Jason Scheirer
On Apr 20, 3:25 pm, Zethex <[EMAIL PROTECTED]> wrote:
> Im a bit new to python.  Anyway working on a little project of mine and i
> have nested lists
>
> ie
>
> Answer = [['computer', 'radeon', 'nvidia'], ['motherboard', 'asus']]
>
> and so forth..,
> Anyway the amount of [[]] do increase over time.  Im just wondering is there
> a simple way to add these together so they become 1 simple list, so it would
> be ['computer''asus'] etc without the nested list.  Its random the
> amount each time so i cant just go a[0]+a[1].
> Thank you if you can help
> --
> View this message in 
> context:http://www.nabble.com/Nested-lists%2C-simple-though-tp16799674p167996...
> Sent from the Python - python-list mailing list archive at Nabble.com.

The first idea that comes to mind is reduce(lambda x, y: x + y,
list_of_lists, [])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: about python

2008-04-22 Thread Jason Scheirer
On Apr 22, 7:50 pm, [EMAIL PROTECTED] wrote:
> How can python execute in browser?
>
> Mukul

Very carefully.


Alternately, applets/Jython.
--
http://mail.python.org/mailman/listinfo/python-list


Re: python-ldap - Operations Error

2008-04-23 Thread Jason Scheirer
On Apr 23, 5:16 pm, [EMAIL PROTECTED] wrote:
> Hello all, I am trying to integrate TurboGears with our Active
> Directory here at the office.  TurboGears aside, i cannot get this to
> work.  The simplest thing i can do to test this is:
>
> >>> import ldap
> >>> l = ldap.initialize("ldap://server.net";)
> >>> l.simple_bind(DN, "secret")
> 1
> >>> l.result(1)
> (97, [])
> >>> l.search("dc=server,dc=net", ldap.SCOPE_SUBTREE, "(sAMAccountName=user)")
>
> OPERATIONS_ERROR: {'info': ': LdapErr: DSID-0C090627, comment:
> In order to perform this operation a successful bind must be completed
> on the connection., data 0, vece', 'desc': 'Operations error'}
>
> The simple bind works fine and returns a result, when i get the
> result, it returns 97 meaning successful.  So there was a successful
> bind on the connection, right?  I'm really not sure where the problems
> lies.  Is it with the way im connecting or is it something to do with
> our AD server?
>
> Thanks

Seems more promising: http://tgolden.sc.sabren.com/python/active_directory.html

Also, same problem: 
http://groups.google.com/group/turbogears/browse_thread/thread/10fcd1f9e920d0a8

Also: http://peeved.org/blog/2007/11/20/

Google is pretty awesome when you paste in literal error strings.
--
http://mail.python.org/mailman/listinfo/python-list


Re: RPM of a Python program

2008-08-14 Thread Jason Scheirer
On Aug 13, 5:52 pm, Clay Hobbs <[EMAIL PROTECTED]> wrote:
> I want to make an RPM (Redhat Package Manager) file to install a Python
> program (not a module).  How is this done?  Does it use Distutils, or
> something completely different?  Thanks in advance.
>
> -- Ratfink

You first want to make sure your setup.py correctly references your
python scripts:

http://docs.python.org/dist/node11.html

The distutils package has a built-in bdist_rpm command that will
create an installable RPM:

http://docs.python.org/dist/module-distutils.command.bdistrpm.html

So instead of running

$ python setup.py install

as you usually do, you would execute

$ python setup.py bdist_rpm

and in the directory where setup.py lives you should have a dist/
directory with an .rpm file ready to go. That's the easy part, if you
have other related resource files, etc, you are going to need to study
up on how to properly get them specified in your setup.py with
distutils, but it's completely doable.
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to simulate packages?

2008-08-21 Thread Jason Scheirer
On Aug 21, 11:26 am, "Gabriel Genellina" <[EMAIL PROTECTED]>
wrote:
> En Thu, 21 Aug 2008 13:04:51 -0300, Daniel <[EMAIL PROTECTED]>  
> escribi :
>
> > I have a project that I've decided to split into packages in order to
> > organize my code better.  So what I have looks something like this
>
> > src
> >   -module1
> >     -mod1_file.py
> >   -module2
> >     -mod2_file.py
>
> > Everytime I run mod2_file.py I need to import mod1_file.py.  Right now
> > I'm using an ugly little thing to do my import (see below).  Isn't
> > there some python mechanism to handle packages?
>
> Sure - Python *has* packages, you don't have to "simulate" them.
> Readhttp://docs.python.org/tut/node8.html#SECTION00840
>
> --
> Gabriel Genellina

You can use relative imports, so in mod2_file.py you could

import ..module1.mod1_file as mod1

To pull in a dependent submodule. Also, I think you are thinking about
__init__.py?

package/
  __init__.py
  mod1/
mod1.py
  mod2/
mod2.py

And in your __init__.py you issue something like

import mod1
import mod2

if you need them loaded as soon as your package is imported, but you
may omit that and import piecemeal in your scripts as each one needs
functionality:

from mypackage.mod2 import just_this_one_function

Etc etc etc. But really if you only have a single Python file living
in each subdirectory, you are likely Doing It Wrong and your code
might just make more sense as:

package/
  __init__.py
  intuitively_named_submodule1.py
  intuitively_named_submodule2.py
  intuitively_named_submodule3.py

Where your intuitively named submodules are all logical groupings of
functionality. Remember that they don't ALL get imported right away,
in fact, only __init__.py is imported by default, so if that's missing
or doesn't import the other submodules by default, you have to
explicitly

import package.intuitively_named_submoduleN

each time you want to import a submodule.

Modules and packages: http://docs.python.org/tut/node8.html
Relative imports: http://www.python.org/dev/peps/pep-0328/
--
http://mail.python.org/mailman/listinfo/python-list


Re: setattr and getattr, when to use?

2008-08-22 Thread Jason Scheirer
On Aug 22, 8:50 pm, maestro <[EMAIL PROTECTED]> wrote:
> Why are these functions there? Is it somehow more idiomatic to use
> than to do obj.field ?
> Is there something you can with them that you can't by obj.field
> reference?

You can generate them dynamically from strings. In some cases you
don't know until runtime what attributes you want to pull:

def show_insides(obj):
  for attr in dir(obj):
print "Attribute %r: %r" % (attr, getattr(obj, attr))

class hello(object):
   a = 1
   b = 2

class goodbye(object):
   c = 1
   d = 500


print show_insides(hello)
(...15 builtins...)
Attribute 'a': 1
Attribute 'b': 2

print show_insides(goodbye)
(...15 builtins...)
Attribute 'c': 1
Attribute 'd': 500

In this case, you can see that we pull the attributes of an object
using dir(), which yields a list of strings, then pull each attribute
we discover.
--
http://mail.python.org/mailman/listinfo/python-list


Re: setattr and getattr, when to use?

2008-08-22 Thread Jason Scheirer
On Aug 22, 10:17 pm, Jason Scheirer <[EMAIL PROTECTED]> wrote:
> On Aug 22, 8:50 pm, maestro <[EMAIL PROTECTED]> wrote:
>
> > Why are these functions there? Is it somehow more idiomatic to use
> > than to do obj.field ?
> > Is there something you can with them that you can't by obj.field
> > reference?
>
> You can generate them dynamically from strings. In some cases you
> don't know until runtime what attributes you want to pull:
>
> def show_insides(obj):
>   for attr in dir(obj):
>     print "Attribute %r: %r" % (attr, getattr(obj, attr))
>
> class hello(object):
>    a = 1
>    b = 2
>
> class goodbye(object):
>    c = 1
>    d = 500
>
> print show_insides(hello)
> (...15 builtins...)
> Attribute 'a': 1
> Attribute 'b': 2
>
> print show_insides(goodbye)
> (...15 builtins...)
> Attribute 'c': 1
> Attribute 'd': 500
>
> In this case, you can see that we pull the attributes of an object
> using dir(), which yields a list of strings, then pull each attribute
> we discover.

Might I add: avoid doing this if you don't have to. obj.field is the
way to go about getting your object attributes 95% of the time. The 5%
of your time when you are doing metaprogramming or other abuses of the
object system are when you use get/setattr.
--
http://mail.python.org/mailman/listinfo/python-list


Re: List of modules available for import inside Python?

2008-08-28 Thread Jason Scheirer
On Aug 27, 11:04 pm, Fredrik Lundh <[EMAIL PROTECTED]> wrote:
> ssecorp wrote:
> > Is there a way to view all the modules I have available for import
> > from within Python?
> > Like writing in the interpreter:
> > import.modules
>
> there's a helper script in the 2.5 source code kit that locates all
> existing standard modules:
>
> http://svn.python.org/projects/python/tags/r252/Doc/tools/listmodules.py
>
> to get all modules, remove the for-loop that follows after the comment
> "get rid of site packages".
>
> also see:
>
> http://effbot.org/zone/listmodules-cgi.htm
>
> 

I like to direct new users to pydoc's built-in HTTP server:

import pydoc
pydoc.gui()
(then click the 'open browser' button)
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to check is something is a list or a dictionary or a string?

2008-08-29 Thread Jason Scheirer
On Aug 29, 9:16 am, [EMAIL PROTECTED] wrote:
> Hi,
>
> How to check if something is a list or a dictionary or just a string?
> Eg:
>
> for item in self.__libVerDict.itervalues():
>             self.cbAnalysisLibVersion(END, item)
>
> where __libVerDict is a dictionary that holds values as strings or
> lists. So now, when I iterate this dictionary I want to check whether
> the item is a list or just a string?
>
> Thanks,
> Rajat

type() and probably you want to import the types library as well.

In [1]: import types

In [2]: a = {1: {}, False: [], 'yes': False, None: 'HELLO'}

In [3]: a.values()
Out[3]: [[], {}, False, 'HELLO']

In [4]: [type(item) for item in a.itervalues()]
Out[4]: [, , , ]

In [6]: for item in a.itervalues():
   ...: if type(item) is types.BooleanType:
   ...: print "Boolean", item
   ...: elif type(item) is types.ListType:
   ...: print "List", item
   ...: elif type(item) is types.StringType:
   ...: print "String", item
   ...: else:
   ...: print "Some other type", type(item), ':', item
   ...:
   ...:
List []
Some other type  : {}
Boolean False
String HELLO
--
http://mail.python.org/mailman/listinfo/python-list


Re: path slashes cleaning

2008-09-04 Thread Jason Scheirer
On Sep 4, 6:32 am, "Francesco Guerrieri" <[EMAIL PROTECTED]>
wrote:
> On Thu, Sep 4, 2008 at 3:25 PM, Mathieu Prevot <[EMAIL PROTECTED]> wrote:
> > Hi,
>
> > for scripts that take arguments, I would like to remove the trailing
> > slash if it's present.
>
> > Is there something else than:
>
> > a='/usr/local/lib/'
> > if a[-1] == '/':
> >  a = list(a)
> >  a.pop()
> >  ''.join(a)
>
> > Thanks,
> > Mathieu
>
> a.rstrip('/') does the job.
>
> bye,
> Francesco

[1]: import os.path
[2]: os.path.normpath('/usr/bin')
'/usr/bin'
[3]: os.path.normpath('/usr/bin/')
'/usr/bin'

And on windows:
[1]: import os.path
[2]: os.path.normpath(r'c:\data')
'c:\\data'
[3]: os.path.normpath('c:\\data\\')
'c:\\data'

Use the functions provided in os.path.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Linq to Python

2008-09-23 Thread Jason Scheirer
On Sep 23, 7:48 am, hrishy <[EMAIL PROTECTED]> wrote:
> Hi
>
> Will LINQ be ported to Python ?
>
> regards
> Hrishy

I think this question is more appropriate to ask on an IronPython
development list -- LINQ is pretty solidly intertwined with .Net, and
so you'll likely want to look at the .Net implementation of Python.
--
http://mail.python.org/mailman/listinfo/python-list


Re: decent interactive python shell on MS Windows?

2008-10-01 Thread Jason Scheirer
On Oct 1, 9:53 am, [EMAIL PROTECTED] wrote:
> Hi everyone,
>
> After having used Python on Linux for some time, I now have to do
> Python coding on Windows. I am big fan of the interactive Python shell
> to test, eg, regexps.
>
> Is there an interactive Python shell on Windows that supports:
>
> - easy copy-pasting to/from an editor? (as opposed to the cumbersome
> "mark", "copy" and then "paste" sequence that any terminal on Windows
> seems forced to adopt)
>
> - readline-like command history (up/down for previous/next command,
> Ctr-R for searching, etc) ?
>
> I have tried the python.org shell (difficult copy-pasting),
> ActiveState's (no readline command history) and iPython (difficult
> copy-pasting). Do you know of any decent interactive python shell on
> Windows that comes close to the friendliness of the standard one on
> Linux?
>
> Thanks in advance
>
> James

Which is the 'standard' one you use on Linux? Are you unhappy with
Idle? It's there in your start menu under Python. You can also try
PythonWin's python interpreter, which is pretty nice, and PyCrust/
PyShell/etc, which come with the wxPython demo bundle.

Then you can move up to Komodo or the Wing IDE, which are more
comprehensive but not really nice for just the sort of regex-testing,
desktop calculator tasks where you want something up and running
quickly.
--
http://mail.python.org/mailman/listinfo/python-list


Re: index all instances by id - a memory leak?

2008-10-01 Thread Jason Scheirer
On Oct 1, 10:01 pm, Dan Barbus <[EMAIL PROTECTED]> wrote:
> On Oct 2, 7:54 am, Dan Barbus <[EMAIL PROTECTED]> wrote:
>
>
>
> >     def getItemById(id):
> >         return _itemsById[id]
>
> I just saw that this won't compile. Still, ignoring this, I thing the
> purpose of the code is pretty clear.
>
> Thanks for any feedback.

Check the weakref module, you can create a WeakValueDictionary which
will not increment the refcount of the value, and will return None
after it's been garbage collected.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Introspection

2010-01-06 Thread Jason Scheirer
On Jan 6, 8:38 am, Steven D'Aprano  wrote:
> On Wed, 06 Jan 2010 06:53:40 -0800, [email protected] wrote:
> > I'm looking for a way to make a list of string literals in a class.
>
> > Example:
>
> > class A:
> >    def method(self):
> >        print 'A','BC'
>
>  ExtractLiterals(A)
> > ['A','BC']
>
> > Is this possible? Can anyone point me in the right direction?
>
> class A:
>     def extract_literals(self):
>         return "A BC".split()
>     def method(self):
>         print self.extract_literals()
>
> a = A()
> a.extract_literals()
>
> --
> Steven

Slightly more robust than Miki's solution insofar as it doesn't
require the source to exist in a .py file:

import types
def extract_literals(klass):
for attr in (getattr(klass, item) for item in dir(klass)):
if isinstance(attr, types.MethodType):
for literal in attr.im_func.func_code.co_consts:
if isinstance(literal, basestring):
yield literal

class full_of_strings(object):
def a(self):
return "a", "b", "c"
def b(self):
"y", "z"

print list(extract_literals(full_of_strings))
['a', 'b', 'c', 'y', 'z']

print list(extract_literals(full_of_strings()))
['a', 'b', 'c', 'y', 'z']

Note that this is evil and should be avoided.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Manipulating pointers in C using ctypes

2010-01-08 Thread Jason Scheirer
On Jan 8, 7:37 am, Daniel Platz 
wrote:
> Hello!
>
> I have to ask a newbie question about manipulating pointers in C using
> ctypes. I have a C dll with two functions. The first one creates a
> pointer and returns it to python. The second one takes a pointer as an
> argument shows its address and the value at which it is pointing. This
> I have implemented using the following code
>
> ---  pointers.c 
> #include 
> #ifdef __cplusplus
> extern "C" {  // only need to export C interface if
>               // used by C++ source code
> using namespace std;
> #endif
>
> __declspec(dllexport) void* create()
> {
>         double number = 2.2;
>         double* ptr = &number;
>         printf("Pointer address \t %p \n", ptr);
>         printf("Value at pointer \t %f \n", ptr[0]);
>         return (void*) ptr;
>
> }
>
> __declspec(dllexport) int show(double* ptr)
> {
>         printf("Pointer address \t %p \n", ptr);
>         printf("Pointer value \t %f\n", *ptr);
>         *ptr = 2.4;
>         printf("New pointer value \t %f\n", *ptr);
>         return 0;
>
> }
>
> #ifdef __cplusplus}
>
> #endif
> 
>
> Please note that in the second function, the show function, I want to
> manipulate the value at which the pointer points.
> Now, I call this function from python with the following script.
>
> --- pointers.py --
> import ctypes as ct
>
> # Load dll
> pointers = ct.cdll.LoadLibrary('pointers.dll')
> getattr(pointers, 'create')
> getattr(pointers, 'show')
> pointers.create.restype = ct.c_void_p
>
> # Create pointer in C
> ptr = pointers.create()
>
> # Show pointer address and value
> print 'Adress returned to python ' +hex(ptr)
> pointers.show(ct.c_void_p(ptr))
> ---
>
> Calling this script gives me the following output:
>
> Pointer address          0021E508
> Value at pointer         2.20
> Adress returned to python 0x21e508
> Pointer address          0021E508
> Pointer value    0.00    (2.2 expected)
> New pointer value        2.40 (2.4 expected)
>
> But the script returns also an error.
>
> WindowsError: exception: access violation reading 0x4003
> WARNING: Failure executing file: 
>
> Another thing that I find strange is that the return value of
> pointers.create is actually an integer instead of an ct.c_void_p
> object.
>
> Moreover, I also tried to directly manipulate the address of the
> pointer given as an argument to pointers.show. But when it returns to
> python the pointer points still at the same address as before the
> function call.
>
> Can someone help me with this problem? I would be very glad about an
> answer.
>
> With kind regards,
>
> Daniel

try this:

__declspec(dllexport) void* create()
{
double* ptr = new double;
*ptr = 2.2;
printf("Pointer address \t %p \n", ptr);
printf("Value at pointer \t %f \n", ptr[0]);
return (void*) ptr;
}

Basically once you leave create() the address being used for number is
no longer valid. The other implication for this is you are going to
need a delete() function to free that memory you allocated for the
double as well.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Append to an Excel file

2010-01-09 Thread Jason Scheirer
On Jan 9, 12:30 am, pp  wrote:
> Hi All,
>
> How do I add a line to an existing file. This should append to the
> existing data in the excel file, which was saved previously.
>
> Thanks,
> PP

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


Re: Clarifications on compiling for Windows

2010-01-09 Thread Jason Scheirer
On Jan 7, 10:51 pm, Mensanator  wrote:
> On Jan 8, 12:19 am, peteshinners  wrote:
>
>
>
>
>
>
>
> > My presentation for Pycon is coming together, but I need to make sure
> > my information about compiling Python and Python extensions for
> > Windows is correct. I'm really only experienced with this on the Linux
> > side of things.
>
> > First of all, is the Windows FAQ fairly up to date? Should people be
> > referring to section 6 if they are going to build an application with
> > an embedded Python 
> > interpreter?http://www.python.org/doc/faq/windows/#how-can-i-embed-python-into-a-...
>
> > If I understand correctly, compiled extensions for Python on Windows
> > should match the compiler that was used to build the interpreter
> > itself? Is there a list somewhere that shows which version of msvc was
> > used to compile the recent Python binaries?
>
> > Thank you for feedback. I definitely want to make sure I have this
> > correct before telling anybody else?
>
> You aren't going to try it?

At a high level: YES. Avoid FILE* and you are golden on Windows. Works
like a charm.

MSVC 2008 works for 2.6 with the least effort (I strongly recommend
having it installed as that's what the build uses). If you have VS2008
you will have no problem whatsoever with setup.py install, even with C
extensions. I'd like to verify the same with earlier versions of VS
but I can't. MinGW works, too, but with slightly more effort: there
are some command line arguments you have to issue setup.py to know how
to use/where the MinGW compiler is.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: pythoncom.CoInitialize() not recognised in Eclipse

2010-03-28 Thread Jason Scheirer
On Mar 28, 7:14 pm, KB  wrote:
> Hi there,
>
> I have in the past used PythonWin to write python for COM, and
> switched to Eclipse.
>
> I am getting an error from the IDE saying it does not recognise
> CoInitialize():
>
> 
> import pythoncom
>
> pythoncom.CoInitialize()
> pythoncom.CoUninitialize()
> 
>
> (red X next to the two bottom lines saying: "Undefined variable from
> import: CoInitialize")
>
> If I open a PyDev/Python Console window in Eclipse, I can type the
> above, no errors, no problem.
>
> I tried removing my Python Interpreter and re-adding/re-building but
> no change.
>
> python 2.5.2
> eclipse 3.5.1
> pydev 1.5.0
>
> Thanks!

PyDev is probably only looking at functions/classes defined in Python
source files and not ones defined in C extensions.

To confirm, try typing this in the window:

import _ctypes
_ctypes._Pointer()

If it says that _ctypes._Pointer doesn't exist, then that's obviously
the problem.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python date time API

2010-04-26 Thread Jason Scheirer
On Apr 26, 8:21 am, rk  wrote:
> Hi,
>
>  I am python novice, trying to convert a boost::gregorian::date out to
> python using PyDateTime C-api interface. I was coring because the C-
> API failed to initialize. The error was:
>
> AttributeError: "module" object has not attribute datetime_CAPI
>
> As indicated by the error, a dir(datetime) gives me the following
> output.
>
> ['MAXYEAR', 'MINYEAR', '__doc__', '__file__', '__name__', 'date',
> 'datetime', 'time', 'timedelta', 'tzinfo']
>
> I am note sure why datetime_CAPI is missing? I would appreciate any
> input.
>
> Regards,
> Ramesh

You MUST use the PyDateTime_IMPORT; macro at the top ov EVERY scope in
which you are using the DateTime C API.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Parser

2010-05-02 Thread Jason Scheirer
On May 2, 12:54 pm, Andreas Löscher  wrote:
> Hi,
> I am looking for an easy to use parser. I am want to get an overview
> over parsing and want to try to get some information out of a C-Header
> file. Which parser would you recommend?
>
> Best,
> Andreas

Pyparsing: http://pyparsing.wikispaces.com/
I've abused the lexers built in to Pygments ( http://pygments.org/ ) a
few times to decent effect too.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: where are the program that are written in python?

2010-05-21 Thread Jason Scheirer
On May 21, 3:21 am, Deep_Feelings  wrote:
> python is not a new programming language ,it has been there for the
> last  15+ years or so ? right ?
>
> however by having a look at this pagehttp://wiki.python.org/moin/Applications
> i could not see many programs written in python (i will be interested
> more in COMMERCIAL programs written in python ). and to be honest ,i
> tried some of the programs in that list and all the programs that i
> tried either dead projects or so buggy !
>
> 1- where are the programs that is written in python ?
> 2- python is high productivity language : why there are no commercial
> programs written in python ?
>
> is python a valid practical programming language ?
> why it is not used in commercial software ?
>
> please don't mention programs where python was used as a glue ,those
> programs are not actually written in python.
>
> any help will be appreciated
>
> thank you

I write commercial software full-time in Python (well, mixed with C++)
at ESRI. I have been able to make a living developing in Python full
time at various places for the last 4 years. I can assure you that
there is plenty of commercial software out there that uses Python. The
reason you don't *see* it is because the development language for a
commercial product is a lot less important than the functionality of
the product, so "WRITTEN IN PYTHON" is likely not going to be a
bullet point on a marketing slide. And quite frankly, it should be a
trade secret for the companies enlightened enough to use it as their
language of choice because it is to productive that it provides a
competitive advantage.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: assign class variable in __init__

2010-06-08 Thread Jason Scheirer
On Jun 8, 9:37 am, Peter Otten <[email protected]> wrote:
> Ross Williamson wrote:
> > Hi Everyone,
>
> > Just a quick question - Is it possible to assign class variables in
> > the __init__() - i.e. somthing like:
>
> > def __init__(self,self.source = "test", self.length = 1)
>
> > rather than
>
> > def __init__(self,source = "test", length = 1):
>
> No. If you are just lazy, try
>
> >>> import sys
> >>> def update_self():
>
> ...     d = sys._getframe(1)
> ...     d = d.f_locals
> ...     self = d.pop("self")
> ...     for k, v in d.iteritems():
> ...             setattr(self, k, v)
> ...>>> class A(object):
>
> ...     def __init__(self, source="test", length=1):
> ...             update_self()
> ...     def __repr__(self):
> ...             return "A(source=%r, length=%r)" % (self.source,
> self.length)
> ...>>> A()
>
> A(source='test', length=1)>>> A(length=42)
>
> A(source='test', length=42)
>
> Personally, I prefer explicit assignments inside __init__().
>
> Peter

Or more simply

def __init__(self, source = "test", length = 1):
  for (k, v) in locals().iteritems():
if k != 'self':
  setattr(self, k, v)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: No trees in the stdlib?

2009-06-26 Thread Jason Scheirer
On Jun 25, 10:32 pm, [email protected] (Aahz) wrote:
> In article ,
> Tom Reed   wrote:
>
>
>
> >Why no trees in the standard library, if not as a built in? I searched
> >the archive but couldn't find a relevant discussion. Seems like a
> >glaring omission considering the batteries included philosophy,
> >particularly balanced binary search trees. No interest, no good
> >implementations, something other reason? Seems like a good fit for the
> >collections module. Can anyone shed some light?
>
> What do you want such a tree for?  Why are dicts and the bisect module
> inadequate?  Note that there are plenty of different tree implementations
> available from either PyPI or the Cookbook.
> --
> Aahz ([email protected])           <*>        http://www.pythoncraft.com/
>
> "as long as we like the same operating system, things are cool." --piranha

...And heapq is more-or-less an emulation of a tree structure in its
underlying model. I once wrote a binary sorted tree data structure for
Python in C. It performed anywhere from 15-40% worse than dicts. I
think with optimization it will only perform 10% worse than dicts at
best.

Oh hey maybe that is why trees aren't an emphasized part of the
standard. They are going to be much slower than the ultra-optimized
dicts already in the standard lib.
-- 
http://mail.python.org/mailman/listinfo/python-list