Re: Little Q: how to print a variable's name, not its value?

2005-03-31 Thread Duncan Booth
[EMAIL PROTECTED] wrote:

 But surely if you create an integer object and assign it a value, e.g.
 a = 3,
 why shouldn't Python be able to tell you something like the following:
 name(a)   'a'
 ?

But why should it return 'a' and not one of these?

tokenize.tok_name[3]
token.tok_name[3]
sre_parse.OPCODES['any_all']
sre_parse.CHCODES['category_not_space']
sre_parse.ATCODES['at_boundary']
sre_constants.OPCODES['any_all']
sre_constants.CHCODES['category_not_space']
sre_constants.ATCODES['at_boundary']
sre_compile.OPCODES['any_all']
sre_compile.CHCODES['category_not_space']
sre_compile.ATCODES['at_boundary']
opcode.opmap['ROT_THREE']
encodings.cp437.encoding_map[3]
encodings.cp437.decoding_map[3]
encodings.cp1252.encoding_map[3]
encodings.cp1252.decoding_map[3]
dis.opmap['ROT_THREE']
tokenize.STRING
token.STRING
stat.ST_NLINK
os.P_NOWAITO
nt.P_NOWAITO
locale.LC_MONETARY
imp.C_EXTENSION
_locale.LC_MONETARY

The important thing is that not only do these variables all have the value 
3, they all have the *same* value 3. That monstrous code I posted behaves a 
little differently if you give it a number such as 101:

 x = 101
 for s in varname.object_info(101):
...   print s
...
anonymous [EMAIL PROTECTED][0]

The variable 'x' is ignored because it contains a different 101, the only 
thing in the system using the specific 101 that was passed to object_info 
is the tuple used to contain the constants for the executing code. Asking 
for object_info(x) will indeed return only one string '__main__.x'.

The key here is to understand the difference between languages like C where 
a variable is a container used to store a value and Python where variables 
are simply the binding of names to objects.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Little Q: how to print a variable's name, not its value?

2005-03-31 Thread Bengt Richter
On 30 Mar 2005 21:56:06 -0800, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote:

my god, I've created a monster!

Maybe I should restate my original problem. Actually, the word
'problem' is too strong. I had a little curiosity about whether I could
write a couple of lines of code more succinctly, or more pythonically.
  I didn't realize that this would trigger a discussion about mixing
data and objects - though I can see the danger if you get into some
situations. Hopefully mine is not one of those.

Restating:  I'm doing some debugging of some code.  I want to print out
the value of two variables whose names are known.  Let's call them
myTime and myPlace.

#debug:
if self.debug:
   print myTime = %s, myPlace = %s % (myTime, myPlace)

Notice that I had to type the variable's name once as an object, and
once as the string representation of that object, i.e. the object's
name.
I wondered whether it might not be possible to do something like this:
if self.debug:
   print %s = %s % ( name(myTime), myTime )
where 'name' is the method or trick I'm after.
Why isn't name(myTime) just 'myTime' ?
Which of the possible aliases would you like, if that's what you're looking for?



Anyway, if you just want a way of generating the string 'x = the value of x' 
without
typing 'x' twice, you can use a custom mapping class and a __getitem__ method to
do the work. E.g.,

  class ShowEq(dict):
 ... def __getitem__(self, name):
 ... return '%s = %r'%(name, self.get(name, 'UNDEF!!'))
 ...

Some variables
  a,b = 'eigh', 'bee'

print them, using an instance of the mapping initialized with vars() which is 
the local namespace

  print '%(a)s, %(b)s, %(ShowEq)s' % ShowEq(vars())
 a = 'eigh', b = 'bee', ShowEq = class '__main__.ShowEq'


Which does something like

print %(myTime)s = %s % ( name(myTime), myTime )

I've forgotten who first did this, but I think it was before you could subclass 
dict ;-)
  
Creating a dictionary is already more work than it's worth, not to
mention some of the more involved solutions.   I'm left to conclude
that it's not possible to do what I wanted with Python.  If that's the
case, so be it and I'll move on to explore other curiosities.
Sometimes it's hard to get across exactly what it is you want, so don't give up 
until
you're sure you're being understood ;-)

But surely if you create an integer object and assign it a value, e.g.
The way you use those words makes me wonder: assign _it_?? Which 'it'?
The integer object in this is created from the right hand side of the '='.
Assignment is attaching a name tag (with the name from the left on it) to the
object with sufficient sewing thread to reach a bulletin board where you tack 
up the tag.
A bare name is tacked on the local bulletin board (name space). The integer 
object is nameless
in itself. And the name is not the object. The name just leads to the object -- 
until the lead
is cut and tied to something else (rebound), or the tag is taken off the 
bulletin board (deleted),
at which time the object may have other names from the same or other bulletin 
boards (or container
binding sites) attached to it. If there's nothing connected, the object goes in 
the garbage.

a = 3,
why shouldn't Python be able to tell you something like the following:
name(a)   'a'
Because there is in general no unique 'a' associated with the object that has 
already been looked
up and is being passed by reference to name(). What should you get for name(7)? 
There might be no name.
 
To get an idea, try to write a C routine to do it, being passed a pointer to a 
memory location
allocated with malloc. What name should it return? How should it find a name?

If you are willing to prefix your names with the name of a special namespace 
whenever you refer to them,
so it would be name(ns.a)  'a', that could be be done. You can do about 
anything through descriptor
magic and overriding __get/setattr/ibute__ and spell things in a way that 
totally abuses
the design intents of Python ;-)

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


Re: Little Q: how to print a variable's name, not its value?

2005-03-31 Thread Bill Mill
On 31 Mar 2005 08:13:30 GMT, Duncan Booth [EMAIL PROTECTED] wrote:
 [EMAIL PROTECTED] wrote:
 
  But surely if you create an integer object and assign it a value, e.g.
  a = 3,
  why shouldn't Python be able to tell you something like the following:
  name(a)   'a'
  ?
 
 But why should it return 'a' and not one of these?

Because the python interpreter certainly knows the name of all the
variables used in a python program. So, a name() function as discussed
here should return the name of the exact variable passed in as input,
not any variable which refers to the value 3 (which is of course
constant). We're imagining a new function, not discussing yours.
.
 
 The key here is to understand the difference between languages like C where
 a variable is a container used to store a value and Python where variables
 are simply the binding of names to objects.

I don't see any technical barrier to implementing a name() function,
except that either the current CPython doesn't allow this particular
reflection from python, or it's difficult to do. Just because a
variable is simply a name binding doesn't mean Python couldn't return
the name of the binding.

I'm not definitely saying that I *want* an easy name() function -
there's a lot of potential for abuse - but I would at least like to
see it accomplished before I decide whether I like it or not.

Peace
Bill Mill
bill.mill at gmail.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Little Q: how to print a variable's name, not its value?

2005-03-31 Thread Aaron Bingham
Stewart Midwinter [EMAIL PROTECTED] writes:

[snip]

 Taking this idea a little further, I'd like to build a 'variable
 inspector' for my GUI app, so that I don't have to resort to debug
 statements.  Instead, I could pop open a window that lists every
 variable that has an expected None, string, int or float value, and
 select any one in order to see its value at that time.  I believe your
 method would be useful in that situation as well, no?

For that, I would suggest taking a look at Komodo
(http://www.activestate.com/Products/Komodo/) and its remote debugging
functionality, instead of building your own tool.  There may be other
IDEs that provide equivalent functionality, but I am not familiar with
them.

Regards,

-- 

Aaron Bingham
Software Engineer
Cenix BioScience GmbH


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


Re: UnicodeEncodeError in string conversion

2005-03-31 Thread Serge Orlov

Maurice LING wrote:
 Hi,

 I'm working on a script that searches a public database and retrives
 results using SOAP interface. However, it seems that the results may
 contains unicodes. When I try to pump the results into Firebird
database
 using kinterbasdb module, some results will give me a
 UnicodeEncodeError. From what I've gathered, it looks like the
 conversion from the results from SOAP interface to string results in
the
 error.

 Is there any way to get thru this?

Have you read this FAQ entry:
http://kinterbasdb.sourceforge.net/dist_docs/usage.html#faq_fep_unicode
??

  Serge.

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


Re: Formated String in optparse

2005-03-31 Thread Peter Otten
Norbert Thek wrote:

 Is there an easy way to convince optparse to accept newline in the
 helpstring? and more importand also in the 'desc' string. I tried
 everything
 (from the os.linesep) to \n, \r,  \r\n, ...

The official way (write your own Formatter class) is a bit tedious indeed.
Here's a hack that seems to work:

import textwrap
import optparse

class TextWrapper:
@staticmethod
def wrap(text, width=70, **kw):
result = []
for line in text.split(\n):
result.extend(textwrap.wrap(line, width, **kw))
return result
@staticmethod
def fill(text, width=70, **kw):
result = []
for line in text.split(\n):
result.append(textwrap.fill(line, width, **kw))
return \n.join(result)
  

optparse.textwrap = TextWrapper()

parser = optparse.OptionParser(description=\
einsamer nie als im august
erfuellungsstunde im gelaende
die roten und die goldenen braende
doch wo ist deiner gaerten lust
)

parser.add_option(-x, --example, help=\
die seen hell die himmel weich
die aecker rein und glaenzen leise
doch wo sind sieg und siegsbeweise \
aus dem von dir vertretenen reich \
wo alles sich durch glueck)

parser.print_help()

You should probably replace the \n literals with os.linesep.

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


Re: LD_LIBRARY_PATH - how to set?

2005-03-31 Thread Roman Yakovenko
On 31 Mar 2005 00:51:21 -0800, Serge Orlov [EMAIL PROTECTED] wrote:
 Roman Yakovenko wrote:
  Hi. I have small problem. I need to load extension module that
 depends
  on shared library. Before actually importing module I tried to edit
  os.environ or to call directly to os.putenv without any success -
  shared library was not found. I tried to search the Internet for the
  answer. The only approach I saw was to set LD_LIBRARY_PATH before
  invoking python script. I don't like this solution.
 
 Looks like it's glibc linker inflexibility:
 http://hathawaymix.org/Weblog/2004-12-30
 
 There is no provision for modifying the library search path once your
 program has started.
 

Thanks, well small script around my program will make the trick. I
think I have no other choise.

 Python does update enviromental variables if you change os.environ or
 call os.putenv, but the linker ignores the changes.
   Serge.
 
 --
 http://mail.python.org/mailman/listinfo/python-list

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


Re: PIL

2005-03-31 Thread Denis S. Otkidach
On Wed, 30 Mar 2005 08:33:44 -0800 (PST) suresh mathi wrote:

SM All 3 images that i try to paste are having a
SM transparent background.
SM When i try to open the image and paste the background
SM becomes black. I masked the black areas but still the
SM shape is not that clear.

I had similar problems and solved them using some tricks with
image.info['transparency'] and image.palette.  Unfortunately I can't
find this example, so if you succeed please post solution here.

-- 
Denis S. Otkidach
http://www.python.ru/  [ru]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Secure scripts variables

2005-03-31 Thread Paul Rubin
Florian Lindner [EMAIL PROTECTED] writes:
 AFAIK scripts can't be setuid? Can you tell me what you mean and how to do
 it?

Actually it looks like Linux doesn't support setuid scripts.  I
thought the feature had been restored.  There is a well-known security
hole but there are workarounds for it and some of the BSD-derived
Unixes implement those.  And there is a special hack for Perl that
uses an accessory setuid C program to run setuid Perl scripts--maybe
something like it could be written for Python.

Anyway, the simple workaround is to write a simple C wrapper that
invokes the Python interpreter on your script.  Make sure to use a
complete path to specify where your script is.  From the perlsec
documentation:

#define REAL_PATH /path/to/script
main(ac, av)
char **av;
{
execv(REAL_PATH, av);
}

Compile this wrapper into a binary executable and then make it rather
than your script setuid or setgid.

http://supportweb.cs.bham.ac.uk/documentation/perl5/pod/perlsec.html

You have to be very careful writing these scripts since there are all
kinds of errors you can make.  Perl's taint checking feature helps
catch a lot of those and it would be good if Python had something
similar.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Formated String in optparse

2005-03-31 Thread MyHaz
If you haven't looked into it, you may like the way class
OptionParser() makes the help text for you.


- Haz

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


Re: Formated String in optparse

2005-03-31 Thread Peter Otten
MyHaz wrote:

 If you haven't looked into it, you may like the way class
 OptionParser() makes the help text for you.

What do you mean?

To clarify: OptionParser's help message in the default format is


usage: discard_newline.py [options]

einsamer nie als im august erfuellungsstunde im gelaende die roten und die
goldenen braende doch wo ist deiner gaerten lust

options:
  -h, --helpshow this help message and exit
  -x EXAMPLE, --example=EXAMPLE
die seen hell die himmel weich die aecker rein und
glaenzen leise doch wo sind sieg und siegsbeweise
aus
dem von dir vertretenen reich wo alles sich durch
glueck



whereas that same OptionParser with the tweaked optparse.textwrap (my
TextWrapper instance replacing the textwrap module from the standard
library) will output


usage: preserve_newline.py [options]

einsamer nie als im august
erfuellungsstunde im gelaende
die roten und die goldenen braende
doch wo ist deiner gaerten lust


options:
  -h, --helpshow this help message and exit
  -x EXAMPLE, --example=EXAMPLE
die seen hell die himmel weich
die aecker rein und glaenzen leise
doch wo sind sieg und siegsbeweise aus dem von dir
vertretenen reich wo alles sich durch glueck


I guess that both poets in residence and limmerickistas will prefer the
latter form :-)

Peter


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


Re: [Tkinter] LONG POST ALERT: Setting application icon on Linux

2005-03-31 Thread Tim Jarman
Jeff Epler wrote:

 I have written a rather hackish extension to use NET_WM_ICON to set
 full-color icons in Tkinter apps.  You can read about it here:
 http://craie.unpy.net/aether/index.cgi/software/01112237744
 you'll probably need to take a look at the EWMH spec, too.  If KDE
 supports NET_WM_ICON, this may work for you (but you'll have to convert
 your image manually to the format required for NET_WM_ICON)
 
 Best of luck!  Unfortunately, the code is not supported.
 
 Jeff

Thanks very much for the link! I'll take a look.

Tim J

-- 
Website: www DOT jarmania FULLSTOP com
-- 
http://mail.python.org/mailman/listinfo/python-list


property and virtuality

2005-03-31 Thread Laszlo Zsolt Nagy
My problem is about properties and the virtuality of the methods. I 
would like to create a property whose get and set methods
are virtual. I had the same problems in Delphi before and the solution 
was the same. I created a private _get method and a public
get method. The former one will call the latter. The same stands for 
_set and set. Here is an example below:

class C1(object):
   def namechanged(self):
   Called after the name of the component has been changed.
   pass
   def getname(self):
   Returns the name of the component.
  
   You can override this method to provide generated component 
names.
   return self._name
   def setname(self,name):
   Set the name of the component.
  
   You can override this method to programatically control 
component name changes.
   
   self._name = name
   self.namechanged()
   def _getname(self):
   Internal method, do not use
   return self.getname()
   def _setname(self,name):
   Internal method, do not use
   self.setname(name)
   name = property(_getname,_setname,Name)

class C2(C1):
   def getname(self):
   return lala
class C3(C1):
   def _getname(self):
   return lala
   name = property(_getname,None,Name)
c1 = C1()
c2 = C2()
c3 = C3()
c1.name = 'Test1'
c2.name = 'Test2'
c3.name = 'Test3'
print c1.name # This will print 'Test1'
print c2.name # This will print 'lala'
print c3.name # This will print 'lala'
print C3.name is C1.name # False
I cannot override C2._getname instead, because c2.name would print 
'Test2 instead of lala. Clearly, the property stores a reference to the 
get and set methods and it is not possible to have it use the new 
methods.  Creating a new property is the worst - need to duplicate code 
and also C3.name is C1.name returns False. :-) It is not a big problem 
because I found the solution just I wonder if there is a better way to 
virtualize property get/set functions.


--
_
 Laszlo Nagy  web: http://designasign.biz
 IT Consultantmail: [EMAIL PROTECTED]
Python forever!
--
http://mail.python.org/mailman/listinfo/python-list


no module named fcntl

2005-03-31 Thread Prakash A



Hello All,

  I new user to 
python. I am using a product called FSH, some of its parts are implemented in 
Python. This is like a ssh to run a command on remote machine. First time while 
runningthe fsh there was on.

 # 
fshd
  Traceback 
(most recent call last):   File 
"/usr/bin/in.fshd", line 6, in ?  import 
infshd   File 
"/home/pra/fsh/1.2/Fileset/share/fsh/infshd.py", line 19, in 
?  import fcntl 
 ImportError: No module named fcntl
 
  I solved this 
problem. This error is because, fcntl.sl is unable load and the user has no 
permission to execute the library. After changing the permission for the shared 
library, it works.

  But again the 
problem arises after some time, with out no change.

  This 
time

  # fshd -l 
user localhost
  [EMAIL PROTECTED] password:
  Traceback 
(most recent call last):   File 
"/usr/bin/in.fshd", line 6, in ?  import 
infshd   File 
"/home/pra/fsh/1.2/Fileset/share/fsh/infshd.py", line 19, in 
?  import fcntl 
 ImportError: No module named fcntl

  Pls. suggest 
me any solution. Pls. forgive me if it is already discussed.


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

Re: How To Do It Faster?!?

2005-03-31 Thread Laszlo Zsolt Nagy
[EMAIL PROTECTED] wrote:
Hello NG,
 in my application, I use os.walk() to walk on a BIG directory. I need
to retrieve the files, in each sub-directory, that are owned by a
particular user. Noting that I am on Windows (2000 or XP), this is what I
do:
for root, dirs, files in os.walk(MyBIGDirectory):
   a = os.popen(dir /q /-c /a-d  + root).read().split()
 


Does anyone know if there is a faster way to do this job?
 

You can use the stat module to get attributes like last modification 
date, uid, gid etc. The documentation of the stat module has a nice 
example. Probably it will be faster because you are running an external 
program (well, dir may be resident but still the OS needs to create a 
new shell and interpret the parameters on every invocation).
If the speed is the same, you may still want to use the stat module because:

- it is platform independent
- it is independent of any external program (for example, the DIR 
command can change in the future)

Best,
Laci
--
_
 Laszlo Nagy  web: http://designasign.biz
 IT Consultantmail: [EMAIL PROTECTED]
Python forever!
--
http://mail.python.org/mailman/listinfo/python-list


Re: property and virtuality

2005-03-31 Thread Diez B. Roggisch
 I cannot override C2._getname instead, because c2.name would print
 'Test2 instead of lala. Clearly, the property stores a reference to the
 get and set methods and it is not possible to have it use the new
 methods.  Creating a new property is the worst - need to duplicate code
 and also C3.name is C1.name returns False. :-) It is not a big problem
 because I found the solution just I wonder if there is a better way to
 virtualize property get/set functions.

I'm not aware of possibility that works as you first expected. You yourself
explained why.

But _maybe_ you can use lambda here - that creates the layer  of indirection
one needs.

foo = property(lambda self: self.get_foo(), lamda self,v: self.set_foo(v))

On second thoughts, a metaclass _might_ help here - but it would be rather
elaborate: look in the baseclasses for properties that have getters and
setters of the same name as some methods in the current class, and replace
them, or  create a new property with them (I'm not sure if descriptors
allow changing their get/set/del methods). I'm not 100% sure if and how
good that works (a quick hack would be easy, but to ship around the cliffs
of multiple inheritance requires more careful navigation I fear...)

-- 
Regards,

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


Re: LD_LIBRARY_PATH - how to set?

2005-03-31 Thread Joal Heagney
Roman Yakovenko wrote:
Thanks for help. But it is not exactly solution I am looking for. I
would like to do it from python script. For example
update_env() #- this function will change LD_LIBRARY_PATH
import extension_that_depends_on_shared_library
Roman
On Mar 31, 2005 9:35 AM, John Abel [EMAIL PROTECTED] wrote:
With Solaris 8+ you would use the command crle, with Linux
(RedHat/SuSE/Mandrake) you need to add the relevant directories
/etc/ld.so.conf and run ldconfig.  I've not got a Debian box to hand, so
I can't say if it matches, but that should give you a pointer.

I think I should have permissions to do it. (more over users of my
scripts should have permissions )
Yep. Unfortunatly if you don't have access to the /etc/ld.so.conf file, 
the only option left is your wrapper script idea. (By the way, have you 
actually tested to see if setting the LD_LIBRARY_PATH actually works? If 
not, you're really up the creek.)

If the script is in shell, you could use something like:
(Dotted lines denote start and end of script, not actual script content)
---
#!/bin/sh
if ! echo ${LD_LIBRARY_PATH} | /bin/fgrep -q /path/to/your/library then
export LD_LIBRARY_PATH=$oldpath:/path/to/your/library
fi
wrapped program $*
---
This will check to see if your library path is in the LD_LIBRARY_PATH, 
set it if it's not, and then run your wrapped program, passing it the 
arguments that the wrapper script was called by.

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


Re: LD_LIBRARY_PATH - how to set?

2005-03-31 Thread Joal Heagney
Joal Heagney wrote:
Roman Yakovenko wrote:
Thanks for help. But it is not exactly solution I am looking for. I
would like to do it from python script. For example
update_env() #- this function will change LD_LIBRARY_PATH
import extension_that_depends_on_shared_library
Roman
On Mar 31, 2005 9:35 AM, John Abel [EMAIL PROTECTED] wrote:
With Solaris 8+ you would use the command crle, with Linux
(RedHat/SuSE/Mandrake) you need to add the relevant directories
/etc/ld.so.conf and run ldconfig.  I've not got a Debian box to hand, so
I can't say if it matches, but that should give you a pointer.

I think I should have permissions to do it. (more over users of my
scripts should have permissions )

Yep. Unfortunatly if you don't have access to the /etc/ld.so.conf file, 
the only option left is your wrapper script idea. (By the way, have you 
actually tested to see if setting the LD_LIBRARY_PATH actually works? If 
not, you're really up the creek.)

If the script is in shell, you could use something like:
(Dotted lines denote start and end of script, not actual script content)
---
#!/bin/sh
if ! echo ${LD_LIBRARY_PATH} | /bin/fgrep -q /path/to/your/library then
export LD_LIBRARY_PATH=$oldpath:/path/to/your/library
fi
wrapped program $*
---
This will check to see if your library path is in the LD_LIBRARY_PATH, 
set it if it's not, and then run your wrapped program, passing it the 
arguments that the wrapper script was called by.

Joal
Aaaaggg. Too long since I've programmed in script. Plus it 
doesn't help changing your mind about implementation halfway through. 
The script should read something like this:

---
#!/bin/sh
if ! echo ${LD_LIBRARY_PATH} | /bin/fgrep -q /path/to/your/library
then
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/path/to/your/library
fi
wrapped program $*
---
Sorry about that.
pretending-like-a-cat-that-he-didn't-just-do-something-stupid'ly yours,
Joal
--
http://mail.python.org/mailman/listinfo/python-list


Re: math - need divisors algorithm

2005-03-31 Thread Joal Heagney
Ed Suominen wrote:
Philp Smith wrote:

Hi
Does anyone have suggested code for a compact, efficient, elegant, most of
all pythonic routine to produce a list of all the proper divisors of an
integer (given a list of prime factors/powers)

Is this compact enough? :-)
def properDivisors(N):
return [x for x in range(1,N-2) if not divmod(N,x)[1]]
---
Ed Suominen
Registered Patent Agent
Open-Source Software Author (yes, both...)
Web Site: http://www.eepatents.com
I tried this out, (Python 2.3) and ran into the situation where neither 
xrange or range won't accept anything other than an int. (To quote the 
bards, 53487861112345 is RIGHT out.) I was wondering how others 
would deal with this situation?

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


Error

2005-03-31 Thread Bounced mail
The original message was received at Thu, 31 Mar 2005 14:40:33 +0200 from 
python.org [34.34.108.175]

- The following addresses had permanent fatal errors -
python-list@python.org

- Transcript of the session follows -
... while talking to 136.158.179.151:
 DATA
 400-aturner; -RMS-E-CRE, ACP file create failed
 400-aturner; -SYSTEM-F-EXDISKQUOTA, disk quota exceeded
 400

  Virus Warning Message 
The virus W32/[EMAIL PROTECTED] was detected in the attachment message.pif. The 
attached File message.pif has
been removed. For questions please contact the Helpdesk.

Er is een virus W32/[EMAIL PROTECTED] gevonden in de attachement/bijlage 
message.pif. De message.pif is verwijderd.
Voor meer informatie raadpleeg de speciale FAQ onder Customer Services - 
Helpdesk op www.upc.nl.

Un virus W32/[EMAIL PROTECTED] a été détecté dans le fichier inclus 
message.pif.  Le fichier message.pif est
enlevé. Pour toutes questions cliquez sur le lien ci-dessous.

Er is een virus W32/[EMAIL PROTECTED] gevonden in de bijlage message.pif. De 
bijlage message.pif is verwijderd.
Voor vragen kunt u klikken op de link hieronder.

Et virus W32/[EMAIL PROTECTED] har blitt oppdaget i et vedlegg. Vedlegget 
message.pif har blitt fjernet. Har du
spørsmål ber vi deg klikke på linken under. 

Ett virus W32/[EMAIL PROTECTED] hittades i den bifogade filen message.pif. 
Filen message.pif har förstörts. För
mer information klicka på nedanstående länk.

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

Re: LD_LIBRARY_PATH - how to set?

2005-03-31 Thread Antoon Pardon
Op 2005-03-31, Joal Heagney schreef [EMAIL PROTECTED]:
 Joal Heagney wrote:
 Roman Yakovenko wrote:
 
 Thanks for help. But it is not exactly solution I am looking for. I
 would like to do it from python script. For example

 update_env() #- this function will change LD_LIBRARY_PATH
 import extension_that_depends_on_shared_library

 Roman

 On Mar 31, 2005 9:35 AM, John Abel [EMAIL PROTECTED] wrote:

 With Solaris 8+ you would use the command crle, with Linux
 (RedHat/SuSE/Mandrake) you need to add the relevant directories
 /etc/ld.so.conf and run ldconfig.  I've not got a Debian box to hand, so
 I can't say if it matches, but that should give you a pointer.



 I think I should have permissions to do it. (more over users of my
 scripts should have permissions )
 
 
 Yep. Unfortunatly if you don't have access to the /etc/ld.so.conf file, 
 the only option left is your wrapper script idea. (By the way, have you 
 actually tested to see if setting the LD_LIBRARY_PATH actually works? If 
 not, you're really up the creek.)
 
 If the script is in shell, you could use something like:
 
 (Dotted lines denote start and end of script, not actual script content)
 ---
 #!/bin/sh
 if ! echo ${LD_LIBRARY_PATH} | /bin/fgrep -q /path/to/your/library then
 export LD_LIBRARY_PATH=$oldpath:/path/to/your/library
 fi
 wrapped program $*
 ---
 
 This will check to see if your library path is in the LD_LIBRARY_PATH, 
 set it if it's not, and then run your wrapped program, passing it the 
 arguments that the wrapper script was called by.
 
 Joal

 Aaaaggg. Too long since I've programmed in script. Plus it 
 doesn't help changing your mind about implementation halfway through. 
 The script should read something like this:

 ---
 #!/bin/sh
 if ! echo ${LD_LIBRARY_PATH} | /bin/fgrep -q /path/to/your/library
 then
   export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/path/to/your/library
 fi
wrapped program $*
 ---

And you should change that last line to:

  wrapped program $@


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


How To Do It Faster?!?

2005-03-31 Thread andrea . gavana
Hello NG,

  in my application, I use os.walk() to walk on a BIG directory. I need
to retrieve the files, in each sub-directory, that are owned by a
particular user. Noting that I am on Windows (2000 or XP), this is what I
do:

for root, dirs, files in os.walk(MyBIGDirectory):

a = os.popen(dir /q /-c /a-d  + root).read().split()

# Retrieve all files owners
user = a[18::20]

# Retrieve all the last modification dates  hours
date = a[15::20]
hours = a[16::20]

# Retrieve all the filenames
name = a[19::20]

# Retrieve all the files sizes
size = a[17::20]

# Loop throu all files owners to see if they belong
# to that particular owner (a string)
for util in user:
if util.find(owner) = 0:
DO SOME PROCESSING

Does anyone know if there is a faster way to do this job?

Thanks to you all.

Andrea.

--
 Message for the recipient only, if received in error, please notify the
sender and read http://www.eni.it/disclaimer/


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


Re: property and virtuality

2005-03-31 Thread Laszlo Zsolt Nagy

I'm not aware of possibility that works as you first expected. You yourself
explained why.
But _maybe_ you can use lambda here - that creates the layer  of indirection
one needs.
foo = property(lambda self: self.get_foo(), lamda self,v: self.set_foo(v))
 

Great. I'll think about this and decide which is better - lamba or 
private functions. Lambda seems much
shorter but it is not as clear why it is there. :-)

On second thoughts, a metaclass _might_ help here - but it would be rather
elaborate: look in the baseclasses for properties that have getters and
setters of the same name as some methods in the current class, and replace
them, or  create a new property with them (I'm not sure if descriptors
allow changing their get/set/del methods). I'm not 100% sure if and how
good that works (a quick hack would be easy, but to ship around the cliffs
of multiple inheritance requires more careful navigation I fear...)
 

Yes, I feel the same. Using a metaclass could be a small help but rather 
elaborate and probably much slower.
Thank you for your help.

--
_
 Laszlo Nagy  web: http://designasign.biz
 IT Consultantmail: [EMAIL PROTECTED]
Python forever!
--
http://mail.python.org/mailman/listinfo/python-list


Rif: Re: How To Do It Faster?!?

2005-03-31 Thread andrea . gavana

Hello Lazslo  NG,

You can use the stat module to get attributes like last modification
date, uid, gid etc. The documentation of the stat module has a nice
example. Probably it will be faster because you are running an external
program (well, dir may be resident but still the OS needs to create a
new shell and interpret the parameters on every invocation).

Unfortunately, on Windows it does not seem to work very well:


 st = os.stat('MyFile.txt')
 print st.st_uid
0

I don't think my user ID is 0...

While with the OS dos command I get:

userid: \\ENI\ag12905

Am I missing something on the stat module? I'm running Python 2.3.4.

Thanks a lot.

Andrea.



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


hex string into binary format?

2005-03-31 Thread Tertius Cronje
Hi, 

How do I get a hexvalued string to a format recognized for binary
calculation?


import binascii
s1 = '1C46BE3D9F6AA820'
s2 = '8667B5236D89CD46'

i1 = binascii.unhexlify(s1)
i2 = binascii.unhexlify(s2)
x = i1 ^i2

TypeError: unsupported operand type(s) for ^: 'str' and 'str'

Many TIA
T
--
http://mail.python.org/mailman/listinfo/python-list


Generating RTF with Python

2005-03-31 Thread Andreas Jung
Hi,
does anyone know of a high-level solution to produce RTF from Python 
(something similar to
Reportlab for producing PDF)?

Thanks,
Andreas

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

RE: Generating RTF with Python

2005-03-31 Thread Tertius Cronje
I'll use http://www.tug.org/ or a smaller solution
http://lout.sourceforge.net/ together with one of many Python template
solutions to generate to generate reports.

HTH
T

 -Original Message-
 From: [EMAIL PROTECTED]

[mailto:[EMAIL PROTECTED]
On
 Behalf Of Andreas Jung
 Sent: Thursday, March 31, 2005 4:02 PM
 To: python-list@python.org
 Subject: Generating RTF with Python
 
 Hi,
 
 does anyone know of a high-level solution to produce RTF from Python
 (something similar to
 Reportlab for producing PDF)?
 
 Thanks,
 Andreas
--
http://mail.python.org/mailman/listinfo/python-list


Re: How To Do It Faster?!?

2005-03-31 Thread Max Erickson
I don't quite understand what your program is doing. The user=a[18::20]
looks really fragile/specific to a directory to me. Try something like
this:

 a=os.popen(dir /s /q /-c /a-d  + root).read().splitlines()

Should give you the dir output split into lines, for every file below
root(notice that I added '/s' to the dir command). There will be some
extra lines in a that aren't about specific files...

 a[0]
' Volume in drive C has no label.'

but the files should be there.

 len(a)
232

To get a list containing files owned by a specific user, do something
like:
 files=[line.split()[-1] for line in a if owner in line]
 len(files)
118

This is throwing away directory information, but using os.walk()
instead of the /s switch to dir should work, if you need it...

max

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


Re: Making a DLL with python?

2005-03-31 Thread Gerald Klix
I think you can, as long as you have a C-Compiler available.
I used pyrex to embedd python into a Linux PAM-Module and
i used C-Types to embbed Python into a Windows DLL. With hindsight, the 
pyrex solution was much fatser to develop and less complicated.

Pyrex provides an example.
Ctypes: http://starship.python.net/crew/theller/ctypes/
Pyrex: http://www.cosc.canterbury.ac.nz/~greg/python/Pyrex/
Feel free to ask, if you need a more complex example,
than the one, that comes with pyrex.
HTH,
Gerald
Larry Bates schrieb:
I don't think you can make a .DLL (but someone else might).
Why can't you use a COM server?  MS seems to have written
some pretty sophisticated software using COM objects.
Almost all languages can dispatch a COM object easily.
-Larry
[EMAIL PROTECTED] wrote:
Can I use python to make a regular Windows DLL that will be called from
other programs?
I know I can use the win32 extensions to make a COM server, but I need
a straight DLL.
Regards,
Phillip

Phillip Piper
A man's life does not consist in the abundance of his possessions
--
GPG-Key: http://keyserver.veridis.com:11371/search?q=0xA140D634
--
http://mail.python.org/mailman/listinfo/python-list


AttributeError: 'module' object has no attribute 'setdefaulttimeout'

2005-03-31 Thread adrian
I get those errors when I run:
 /usr/local/bin/SquidClamAV_Redirector.py -c
/etc/squid/SquidClamAV_Redirector.conf

##
Traceback (most recent call last):
  File /usr/local/bin/SquidClamAV_Redirector.py, line 573, in ?
redirector = SquidClamAV_Redirector(config)
  File /usr/local/bin/SquidClamAV_Redirector.py, line 145, in
__init__
   self.__start_urlhandler__()
  File /usr/local/bin/SquidClamAV_Redirector.py, line 454, in
__start_urlhandler__
urllib.socket.setdefaulttimeout(self.timeout)
AttributeError: 'module' object has no attribute 'setdefaulttimeout'
#

the line that is the problem looks like this:

#
urllib.socket.setdefaulttimeout(self.timeout)
#

from the global sintax:

##
def __start_urlhandler__(self):
 create the urlhandler object 
# set timeout
urllib.socket.setdefaulttimeout(self.timeout)
self.urlhandler = urllib.URLopener()
if self.proxy != {}:
self.urlhandler.proxies = self.proxy
self.urlhandler.addheaders  = [('User-agent',
ModuleName + ' ' + str(version))]

##

can you give me a hint with this matter?

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


Re: Recording Video with Python

2005-03-31 Thread Diez B. Roggisch
[EMAIL PROTECTED] wrote:

 Is there a video module so that I can write a Linux Python script to
 record video coming over USB video cams?

You can open the device and read the images - I've done that before. No
module needed. But I don't remember how things worked - just download the
source for a simple viewer like gcqam and look at what they are doing.

 
 What about these side-thoughts:
 
 * What about recording multiple streams over multiple USB ports? (Think
 in the context of a security system.)

No deal, open several devices.
 * What about lossy compression?

Won't be doable in python in reasonable time - but there might be modules
available for that, or at least libs you can wrap. Make your name honor...

 * What about recording only time slices?

Just wait the appropriate interval
 
 * How would you provide real-time video to a security guard, but then
 only write time-sliced, lossy compression to disk, saving disk space
 yet providing something very suitable for a security guard to watch
 live?

Hrm - just _do_ it? But the problems are not on the python side - how is
your guard going to retrieve the images, which bandwidth can he use and so
on.

Basically it boils down to 

 - do the infrastructure and application functionality in python
 - delegate the compression to some c-backend

Network and IO performance _shouldn't_ be too much of a concern using
python, as it uses the underlying system's calls for that. But in the end,
use a profiler :)
-- 
Regards,

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


Re: Making a DLL with python?

2005-03-31 Thread Diez B. Roggisch
[EMAIL PROTECTED] wrote:

 Can I use python to make a regular Windows DLL that will be called from
 other programs?
 
 I know I can use the win32 extensions to make a COM server, but I need
 a straight DLL.

Maybe elmer is what you need - no own experiences though.

http://www.python.org/moin/elmer
-- 
Regards,

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


Re: AttributeError: 'module' object has no attribute 'setdefaulttimeout'

2005-03-31 Thread Peter Otten
adrian wrote:

 urllib.socket.setdefaulttimeout(self.timeout)
 AttributeError: 'module' object has no attribute 'setdefaulttimeout'

socket.setdefaulttimeout() was added in Python 2.3. You need to upgrade.

Peter


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


(no subject)

2005-03-31 Thread python-list-bounces+archive=mail-archive . com
#! rnews 1066
Newsgroups: comp.lang.python
Path: 
news.xs4all.nl!newsspool.news.xs4all.nl!transit.news.xs4all.nl!news-spur1.maxwell.syr.edu!news.maxwell.syr.edu!nntp.abs.net!attws2!ip.att.net!NetNews1!xyzzy!nntp
From: Harry George [EMAIL PROTECTED]
Subject: Re: hex string into binary format?
X-Nntp-Posting-Host: cola2.ca.boeing.com
Content-Type: text/plain; charset=us-ascii
Message-ID: [EMAIL PROTECTED]
User-Agent: Gnus/5.09 (Gnus v5.9.0) Emacs/21.3
Lines: 28
Sender: [EMAIL PROTECTED]
Organization: The Boeing Company
References: [EMAIL PROTECTED]
Mime-Version: 1.0
Date: Thu, 31 Mar 2005 14:58:03 GMT
Xref: news.xs4all.nl comp.lang.python:370100

Tertius Cronje [EMAIL PROTECTED] writes:

 Hi, 
 
 How do I get a hexvalued string to a format recognized for binary
 calculation?
 
 
 import binascii
 s1 = '1C46BE3D9F6AA820'
 s2 = '8667B5236D89CD46'
 
 i1 = binascii.unhexlify(s1)
 i2 = binascii.unhexlify(s2)
 x = i1 ^i2
 
   TypeError: unsupported operand type(s) for ^: 'str' and 'str'
 
 Many TIA
 T

i1=int(s1,16)
i2=int(s2,16)

-- 
[EMAIL PROTECTED]
6-6M21 BCA CompArch Design Engineering
Phone: (425) 294-4718
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Generating RTF with Python

2005-03-31 Thread Axel Straschil
Hello!

 does anyone know of a high-level solution to produce RTF from Python=20
 (something similar to
 Reportlab for producing PDF)?

Spend hours of googeling and searching, also in this NG, about two
months ago. My conclusion is: On windwos, maybe you can include some
hacks with dll's, under linux, linux support for generating rtf is none,
and so is python's.

My workaround was: 
http://www.research.att.com/sw/download/
This includes an html2rtf converter, which I access from python via
popen and temporary files. Not high-level, not very sexy ... ;-(

Lg,
AXEL.
-- 
Aber naja, ich bin eher der Forentyp. Wolfibolfi's outing in 
http://www.informatik-forum.at/showpost.php?p=206342postcount=10
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: hex string into binary format?

2005-03-31 Thread Peter Hansen
Tertius Cronje wrote:
How do I get a hexvalued string to a format recognized for binary
calculation?
import binascii
s1 = '1C46BE3D9F6AA820'
s2 = '8667B5236D89CD46'
i1 = binascii.unhexlify(s1)
i2 = binascii.unhexlify(s2)
Try this instead:
i1 = long(s1, 16)
i2 = long(s2, 16)
x = i1 ^i2
--
http://mail.python.org/mailman/listinfo/python-list


Re: tkinter destroy()

2005-03-31 Thread max(01)*
[EMAIL PROTECTED] wrote:
Your app seems to give the right state values only if you select 'Freni
a posto'.   But I see you recognize that with your 'FIXME' note.
also the app seems to have too many variables and widgets defined as
self objects.  That isn't necessary unless they will be used outside
the method they were created in (which labels and buttons usually
aren't), so all you are doing is using up more memory than necessary.
very good advice. i'll try to follow it (i am a newbie, you see...)
Reading the code with Italian names adds a little difficulty in
understanding your code (non parlo italiano ma si parlo espagnol),
i am trying to write an introductory article for an italian audience, 
you see... next time i'll try to translate the names (i was a bit in a 
hurry, sorry ;-)

but
I'm left feeling that your app is more complicated than it needs to be
- unless I'm missing something.  What you are doing is just showing how
you can capture the state of the checkbuttons for use elsewhere, right?
And also, that the state in the 2nd window should be live, so that it
updates with the change in value in the 1st window? 
precisely.
 And just a matter
of personal taste, but splitting up widget configuration over many
lines for me impedes readiblity and makes the code look like java or
c++ : surely not what we want?
right... :-)
I also think you could get away with no frames in your initial window,
at least if you use grid() instead of pack().  
as a matter of personal taste i prefer pack(), unless special reasons 
for doing differently. i like better to give general structure 
(hyerarchically) to the gui than hardcoding the appearance.

Also your three state
variables could be members of a list, so you don't have to have
separate constructors for each of them.
ok...
Anyway here's a version of your app that makes use of a 'for' statement
to draw the labels and checkbuttons, so it's only half as long as your
original app.  It also does the right thing - the key pont you were
missing was to use a 'textvariable' argument in defining your label
widgets in the 2nd window.
cheers
Stewart in Calgary
i am going to study it thoroughly. thanks a lot.
bye
macs
--
http://mail.python.org/mailman/listinfo/python-list


Re: redundant imports

2005-03-31 Thread Peter Hansen
max(01)* wrote:
this leads me to another question. since *.pyc files are automatically 
created the first time an import statement in executed on a given 
module, i guess that if i ship a program with modules for use in a 
directory where the user has no write privileges then i must ship the 
*.pyc files along too. right?
Not required except for performance reasons.  If the .pyc
files don't exist, the .py files are recompiled and the
resulting bytecode is simply held in memory and not cached
and the next startup will recompile all over again.
Note also that the main file (the one invoke from the
command line) is never cached in a .pyc...
-Peter
--
http://mail.python.org/mailman/listinfo/python-list


Re: PyParsing module or HTMLParser

2005-03-31 Thread Paul McGuire
Yes, drop me a note if you get stuck.

-- Paul
base64.decodestring('cHRtY2dAYXVzdGluLnJyLmNvbQ==')

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


ANN: PyDev 0.9.2 released

2005-03-31 Thread Fabio Zadrozny
Hi All,
PyDev - Python IDE (Python development enviroment for Eclipse) version 
0.9.2 has just been released.

Check the homepage (http://pydev.sourceforge.net/) for more details.
Regards,
Fabio Zadrozny
--
Software Developer
ESSS - Engineering Simulation and Scientific Software
www.esss.com.br
PyDev - Python Development Enviroment for Eclipse
pydev.sf.net
pydev.blogspot.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: problem running the cgi module

2005-03-31 Thread Kent Johnson
chris patton wrote:
Hi everyone. I'm trying to code an HTML file on my computer to make it
work with the cgi module. For some reason I can't get it running. This
is my HTML script:
--
form method=post action=C:\chris_on_c\hacking\formprinter.py
bifont size=50HOWDY!/font/b/ibrbr
input type=text name=name size=50 value=brbr
input type=submit name=send value=submit
/form
You don't seem to be using a web server at all here - the form action is a file path, not a URL. So 
the browser is just going to the file system to get the .py file.

You can make a simple CGI server by
- create a directory caled cgi-bin
- put formprinter.py into it
- change the form action to action=/cgi-bin/formprinter.py
- Open a dos console to the directory containing the cgi-bin directory
- run the command python -c import CGIHTTPServer; CGIHTTPServer.test()
(Don't do this with Python 2.4, it is broken - use 2.3 or 2.4.1)
Kent
--
And here is the python program it's supposed to run with,
formprinter.py:
--
import cgi, cgitb
cgitb.enable()
form = cgi.FieldStorage()
print 'font size=12%s/fontbr' % form['name']
--
Whenever I press submit on the HTML document, it returns the code for
formprinter.py. Can someone tell me what I'm doing wrong?
-Thanks for any help!
--
http://mail.python.org/mailman/listinfo/python-list


Re: Generating RTF with Python

2005-03-31 Thread Max M
Axel Straschil wrote:
Hello!

does anyone know of a high-level solution to produce RTF from Python=20
(something similar to
Reportlab for producing PDF)?
Spend hours of googeling and searching, also in this NG, about two
months ago. My conclusion is: On windwos, maybe you can include some
hacks with dll's, under linux, linux support for generating rtf is none,
and so is python's.
My workaround was: 
http://www.research.att.com/sw/download/
This includes an html2rtf converter, which I access from python via
popen and temporary files. Not high-level, not very sexy ... ;-(

I looked at this a while ago, which might be a starter.
http://pyrtf.sourceforge.net/
--
hilsen/regards Max M, Denmark
http://www.mxm.dk/
IT's Mad Science
--
http://mail.python.org/mailman/listinfo/python-list


Re: Access denied calling FireEvent in Python

2005-03-31 Thread calfdog
Regarding the call to FireEvent:

I still do not understand why you could call fi­reEvent('onchange')
and now it you have to call Fi­reEvent('onchange') to avoid the
Access denied message

In Ruby or Perl you still call fi­reEvent('onchange') it has not
changed and you do not get the access denied error.

If anyone has any helpful information regarding this it would be great.

Rob


[EMAIL PROTECTED] wrote:
 Found that you have to call FireEvent a different way in the News IE
 and  sp2
 Instead of:

 ie.Document.forms[0].campus.fi­reEvent('onchange')

 if needs to be changed to:
 ie.Document.forms[0].campus.Fi­reEvent('onchange')


 RLM



 [EMAIL PROTECTED] wrote:
  Hello,
 
  Does anyone know a workaround for calling fireEvent.
  With the latest from Microsoft OS XP2 and Hot fixes to
  IE it now gives an access denied error in Python when called.
 
  Here is what I am trying to do:
  Set the campus listbox value and theb call fire event, such as in
 the
  code below.  I get an access denied error.
 
  example code:
  ie = DispatchEx('InternetExplorer.Application')
 
  # Some code to navigate to the site, wait till doc is not busy and
#
  ReadyState is complete...blah..blah...
 
  ie.Document.forms[0].campus.value = '200'
  ie.Document.forms[0].campus.fireEvent('onchange')
 
  HTML code:
  select style=font-size: 10 name=campus onChange=if
  (this.options[this.selectedIndex].value != 0)
  populate(this.options[this.selectedIndex].value)
  option value=0Select a campus
  option value=200Norman Campus
  option value=501Advanced Programs
  option value=502Liberal Studies
  option value=504Academic Programs (CAFE)
  option value=505OU Tulsa/select
 
 
  If you call:
  fireEvent('onchange')
  fireEvent('onclick')
  fireEvent('onFocus') etc... You will get an Access Denied
 
  This only happens with either the newer version of IE and XP2.
  I was able to call the exact same code with XP1 and Win2000 Pro
  and it work fine. So something has changed with I.E. and is not
being
  handled in Python.
 
 
  example code:
  ie.Document.forms[0].campus.fireEvent('onchange')
 
  Trace:
   File
 

C:\Python23\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py,
  line 310, in RunScript
  exec codeObject in __main__.__dict__
File C:\QA\Tools\cPAMIE150\oCScript2.py, line 24, in ?
  ie2.Document.forms[0].campus.fireEvent('onchange')
File C:\Python23\Lib\site-packages\win32com\client\dynamic.py,
 line
  165, in __call__
  return
 

self._get_good_object_(self._oleobj_.Invoke(*allArgs),self._olerepr_.defaultDispatchName,None)
  com_error: (-2147024891, 'Access is denied.', None, None)
  
  Help would be much appreciated!!
  
  RLM

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


Re: AttributeError: 'module' object has no attribute 'setdefaulttimeout'

2005-03-31 Thread infidel
That just means the urllib.socket module doesn't have any function
named setdefaulttimeout in it.

It appears there might be something wrong with your socket module as
mine has it:

py import urllib
py f = urllib.socket.setdefaulttimeout
py f
built-in function setdefaulttimeout

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


A question about the use of PyArg_Parse function

2005-03-31 Thread Barak Azulay




Hi,

I hope I'm writing to the 
rightplace. 
In case I'm out of place 
can you please refer to the right direction.


I have a question about the 
correct way to use PyArg_Parse API function.
I'm writing a C module to 
be called from python code (ver 2.3.4)
In one of the function I 
have to cast the parameter into char *

It looks like 
this:

PyObject* myfunc (PyObject 
*self, PyObject *args){char * myparam;if 
(!PyArg_Parse(args, "(s)", myparam)){
 
.
}
...
}

I have a few 
questions:

1. is this the correct way 
to cast PyObject into char* 
 I have tried the PyArg_ParseTuple but 
for some reason didn't succeed.
2. Is the pointer above 
(myparam) is alocated by this call? ( I guess it is since the 
adress changed before and after the call)
3. Who is releasing 
this memory ?


I tried looking into 
the code , and will continue to.

I hope you'll be 
able to help me.

thanks 
anyway.

_ 
Barak Azulay 

Software Development - Team Leader 
Sphera - 
Web Hosting Automation 
Office: 972-3-9008236 
Mobile: 972-54-7773040 Email:[EMAIL PROTECTED] 
_ 



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

Re: property and virtuality

2005-03-31 Thread Steven Bethard
Laszlo Zsolt Nagy wrote:
My problem is about properties and the virtuality of the methods. I 
would like to create a property whose get and set methods
are virtual.
Perhaps you want to roll your own VirtualProperty descriptor?  Here's 
one based off the property implementation in Raymond Hettinger's How-To 
Guide for Descriptors[1]:

py class VirtualProperty(object):
... def __init__(self, getname=None, setname=None, delname=None,
...  doc=None):
... self.getname = getname
... self.setname = setname
... self.delname = delname
... self.__doc__ = doc
... def __get__(self, obj, type=None):
... if obj is None:
... return self
... if self.getname is None:
... raise AttributeError('unreadable attribute')
... try:
... fget = getattr(obj, self.getname)
... except AttributeError:
... raise TypeError('%s object does not have a %s method' %
... (type(obj).__name__, self.getname))
... return fget()
... def __set__(self, obj, value):
... if self.setname is None:
... raise AttributeError(can't set attribute)
... try:
... fset = getattr(obj, self.setname)
... except AttributeError:
... raise TypeError('%s object does not have a %s method' %
... (type(obj).__name__, self.setname))
... fset(value)
... def __delete__(self, obj):
... if self.delname is None:
... raise AttributeError(can't delete attribute)
... try:
... fdel = getattr(obj, self.delname)
... except AttributeError:
... raise TypeError('%s object does not have a %s method' %
... (type(obj).__name__, self.delname))
... fdel()
...
py class C(object):
... def getx(self):
... return 'C'
... x = VirtualProperty('getx', 'setx', 'delx')
...
py class D(C):
... def getx(self):
... try:
... return self._x
... except AttributeError:
... return 'D'
... def setx(self, x):
... self._x = x
...
py c = C()
py c.x
'C'
py c.x = 1
Traceback (most recent call last):
  File interactive input, line 1, in ?
  File interactive input, line 24, in __set__
TypeError: C object does not have a setx method
py del c.x
Traceback (most recent call last):
  File interactive input, line 1, in ?
  File interactive input, line 33, in __delete__
TypeError: C object does not have a delx method
py d = D()
py d.x
'D'
py d.x = 1
py d.x
1
py del d.x
Traceback (most recent call last):
  File interactive input, line 1, in ?
  File interactive input, line 33, in __delete__
TypeError: D object does not have a delx method
STeVe
[1] http://users.rcn.com/python/download/Descriptor.htm
--
http://mail.python.org/mailman/listinfo/python-list


Re: returning a list: IndexError

2005-03-31 Thread Steven Bethard
[EMAIL PROTECTED] wrote:
Thats right. I wanted c1 and c2 to retrieve the values returned by t1
and t2 . Values for t1 and t2 could be anything. Also tbl is global.
Then you need to return t1 and t2 in test, e.g.:
py import numarray as na
py tbl = na.zeros((32, 16))
py def test():
... t1 = 0x0
... t2 = 0x1
... return t1, t2, tbl[t1, t2]
...
py def get_value():
... c1, c2, data = test()
... print tbl[c1, c2]
...
py get_value()
0
Just as an element of any other container doesn't know what index it's 
stored at, values in a numarray array don't either.  If you want to deal 
with indices, you need to either pass them around instead (or in 
addition to) the values, or you need to search the whole array each time 
for similar objects and see what indices they're at.  The first approach 
is probably preferred in most cases.

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


Problem with national characters

2005-03-31 Thread Leif B. Kristensen
I'm developing a routine that will parse user input. For simplicity, I'm
converting the entire input string to upper case. One of the words that
will have special meaning for the parser is the word før, (before in
English). However, this word is not recognized. A test in the
interactive shell reveals this:

[EMAIL PROTECTED] leif $ python
Python 2.3.4 (#1, Feb  7 2005, 21:31:38)
[GCC 3.3.5  (Gentoo Linux 3.3.5-r1, ssp-3.3.2-3, pie-8.7.7.1)] on linux2
Type help, copyright, credits or license for more information.
 'før'.upper()
'F\xf8R'
 'FØR'
'F\xd8R'


In Windows, the result is slightly different, but no better:

C:\Python23python
ActivePython 2.3.2 Build 232 (ActiveState Corp.) based on
Python 2.3.2 (#49, Nov 13 2003, 10:34:54) [MSC v.1200 32 bit (Intel)] on
win32
Type help, copyright, credits or license for more information.
 'før'.upper()
'F\x9bR'
 'FØR'
'F\x9dR'


Is there a way around this problem? My character set in Linux is
ISO-8859-1. In Windows 2000 it should be the equivavent Latin-1, though
I'm not sure about which character set the command shell is using.
-- 
Leif Biberg Kristensen
http://solumslekt.org/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Generating RTF with Python

2005-03-31 Thread Axel Straschil
Hello!

 I looked at this a while ago, which might be a starter.
 http://pyrtf.sourceforge.net/

Don't remember why I didn't spent much time on that. Sombody has
experience with pyrtf on an production project (is it stable ;-))

Lg,
AXEL.
-- 
Aber naja, ich bin eher der Forentyp. Wolfibolfi's outing in 
http://www.informatik-forum.at/showpost.php?p=206342postcount=10
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: urllib.urlretireve problem

2005-03-31 Thread Ritesh Raj Sarraf
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

Diez B. Roggisch wrote:

 You could for instance try and see what kind of result you got using the
 unix file command - it will tell you that you received a html file, not a
 deb.
 
 Or check the mimetype returned - its text/html in the error case of yours,
 and most probably something like application/octet-stream otherwise.
 

Using the unix file command is not possible at all. The whole goal of the
program is to help people get their packages downloaded from some other
(high speed) machine which could be running Windows/Mac OSX/Linux et
cetera. That is why I'm sticking strictly to python libraries.

The second suggestion sounds good. I'll look into that.

Thanks,

rrs
- -- 
Ritesh Raj Sarraf
RESEARCHUT -- http://www.researchut.com
Gnupg Key ID: 04F130BC
Stealing logic from one person is plagiarism, stealing from many is
research.
-BEGIN PGP SIGNATURE-
Version: GnuPG v1.2.5 (GNU/Linux)

iD8DBQFCTDhV4Rhi6gTxMLwRAi2BAJ4zp7IsQNMZ1zqpF/hGUAjUyYwKigCeKaqO
FbGuuFOIHawZ8y/ICf87wOI=
=btA5
-END PGP SIGNATURE-

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


split an iteration

2005-03-31 Thread Robin Becker
This function from texlib in oedipus.sf.net is a real cpu hog and I determined 
to see if it could be optimized.

def add_active_node(self, active_nodes, node):
Add a node to the active node list.
The node is added so that the list of active nodes is always
sorted by line number, and so that the set of (position, line,
fitness_class) tuples has no repeated values.

index = 0
# Find the first index at which the active node's line number
# is equal to or greater than the line for 'node'.  This gives
# us the insertion point.
while (index  len(active_nodes) and
   active_nodes[index].line  node.line):
index = index + 1
insert_index = index
# Check if there's a node with the same line number and
# position and fitness.  This lets us ensure that the list of
# active nodes always has unique (line, position, fitness)
# values.
while (index  len(active_nodes) and
   active_nodes[index].line == node.line):
if (active_nodes[index].fitness_class == node.fitness_class and
active_nodes[index].position == node.position):
# A match, so just return without adding the node
return
index = index + 1
active_nodes.insert(insert_index, node)
I determined that len was being called a large number of times so did a first 
rewrite as (minus comments)

def add_active_node(self, active_nodes, node):
index = 0
nan = len(active_nodes)
node_line = node.line
node_fitness_class = node.fitness_class
node_position = node.position
while index  nan and active_nodes[index].linenode_line:
index += 1
insert_index = index
while indexnan and active_nodes[index].line==node_line:
if (active_nodes[index].fitness_class==node_fitness_class and
active_nodes[index].position==node_position):
return
index += 1
active_nodes.insert(insert_index, node)
which gives a good speedup even so I decided to eliminate the index += 1 in the 
first while loop which results in

def add_active_node(self, active_nodes, node):
nan = len(active_nodes)
node_line = node.line
node_fitness_class = node.fitness_class
node_position = node.position
insert_index = nan
for index, a in enumerate(active_nodes):
if a.line=node_line:
insert_index = index
break
index = insert_index
while indexnan and active_nodes[index].line==node_line:
if (active_nodes[index].fitness_class==node_fitness_class and
active_nodes[index].position==node_position):
return
index += 1
active_nodes.insert(insert_index, node)
and this change also results in a significant speedup and is I believe is still 
equivalent. I'm not sure exactly why this is faster than the while loop, but it is.

However, it seems harder to get the same speedup for the last while loop; that 
loop is probably not such a problem so it's not terribly important.

Is there a fast way to get enumerate to operate over a slice of an iterable?
--
Robin Becker
--
http://mail.python.org/mailman/listinfo/python-list


Re: Turn of globals in a function?

2005-03-31 Thread Ron_Adam
On Thu, 31 Mar 2005 16:28:15 +1200, Greg Ewing
[EMAIL PROTECTED] wrote:

Oren Tirosh wrote:
 def noglobals(f):
 .   import new
 .   return new.function(
 .   f.func_code, 
 .   {'__builtins__':__builtins__},
 .   f.func_name, 
 .   f.func_defaults, 
 .   f.func_closure
 .   )

Be aware that this will render the function incapable
of seeing *any* globals at all, including other
functions and classes defined in the same module --
which you may find rather inconvenient!


Developing this idea further... 

This allows a programmer to specify what globals to allow read and or
writes.


Cheers, 
Ron


#---start---
# useglobals.py


A function to specify what globals and builtins
a function may access.
Author: Ronald Adam


def useglobals(rw_globals=None, r_globals=None, builtins=True):
#import dis
import sys
write_list = []
read_list = []
if rw_globals != None:
rw_globals = rw_globals.replace(' ','')
write_list = rw_globals.split(',')
if r_globals != None:
r_globals = r_globals.replace(' ','')
read_list = r_globals.split(',')
if builtins == True:
read_list.extend(dir(__builtins__))
elif builtins != None:
builtins = builtins.replace(' ','')
read_list.extend(builtins.split(','))
# Add own name to read list.
read_list.append(sys._getframe(0).f_code.co_name)
read_list.extend(write_list)
#print read_list, write_list
names = sys._getframe(1).f_code.co_names
code = sys._getframe(1).f_code.co_code
#print dis.disassemble(sys._getframe(1).f_code)
i = 0
while i  len(code):
#print ord(code[i])
op = ord(code[i])
if op == 116:   # dis.opmap['LOAD_GLOBAL']
oparg = ord(code[i+1]) + ord(code[i+2]) * 256
if str(names[oparg]) not in read_list:
raise NameError, read from global name %s, detected
% names[oparg]
elif op == 97:  # dis.opmap['STORE_GLOBAL']
oparg = ord(code[i+1]) + ord(code[i+2]) * 256
if names[oparg] not in write_list:
raise NameError, write to global name %s, detected %
names[oparg]
if op = 90:# dis.HAVE_ARGUMENT
i += 3  # Not sure if this is always the same?
else:
i += 1


if __name__ == '__main__':

Test useglobals() function. Change values to test
for error catching.


def a():
useglobals(rw_globals='x', r_globals='y,b')
# This function can read or write 'x',
# Can read 'y', and function 'b',
# and can access all builtins.
global x
y = 5
x += y
x = b(x)
return x

def b(g):
useglobals('','y,c','int')
# This function can only read 'y' and
# function 'c' in globals, and can
# only access 'int' in builtins.
g = g+y
c(int(g))
return g

def c(w):
useglobals(builtins=None)
# This function has no builtins or globals.
w = w**2
return w

y = 4
x = 5
z = 6
print a(),x,y,z

#---end---

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


ANN: ActivePython 2.4.1 build 245 is available

2005-03-31 Thread Trent Mick
I'm pleased to announce that ActivePython 2.4.1 build 245 is now
available from:

 http://www.ActiveState.com/Products/ActivePython

ActivePython 2.4.1.245 is a bug-fix release matching the recent core
Python 2.4.1 release. ActivePython builds for Linux, Solaris and
Windows are available.

We welcome any and all feedback to:
[EMAIL PROTECTED]
Please file bugs against ActivePython at:
http://bugs.ActiveState.com/ActivePython


What is ActivePython?
-

ActivePython is ActiveState's quality-assured binary build of Python.
Builds for Windows, Linux and Solaris and made freely available.

ActivePython includes the Python core and core extensions (zlib 1.2.1,
bzip2 1.0.2, bsddb 4.2.52, Tk 8.4.9, and Tix 8.1.4). On Windows,
ActivePython includes the PyWin32 suite of Windows tools developed by
Mark Hammond, including bindings to the Win32 API and Windows COM, the
Pythonwin IDE, and more.

ActivePython also includes a wealth of Python documentation, including:
- the core Python docs
- Andrew Kuchling's What's New in Python series
- the Non-Programmer's Tutorial for Python
- Mark Pilgrim's excellent Dive into Python, and
- a snapshot of the Python FAQs, HOWTOs and PEPs.

An online version of the docs can be found here:
http://aspn.activestate.com/ASPN/docs/ActivePython/2.4/welcome.html
In particular the Release Notes:
http://aspn.activestate.com/ASPN/docs/ActivePython/2.4/relnotes.html
and the Installation Guide:
http://aspn.activestate.com/ASPN/docs/ActivePython/2.4/installnotes.html

Extra Bits
--

ActivePython releases also include the following packages:

- a Windows debug package: debug-built binaries for ActivePython
  users building debug versions of their binary Python extensions
- ActivePython24.chm: an MS compiled help collection of the full
  ActivePython documentation set. Linux users of applications such as
  xCHM might find this useful. This package is installed by default on
  Windows.

These packages are available from:
 ftp://ftp.activestate.com/ActivePython/etc/

On behalf of the team at ActiveState,
Thanks, and enjoy!

-- 
Trent Mick
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: AttributeError: 'module' object has no attribute 'setdefaulttimeout'

2005-03-31 Thread Steve Holden
Peter Otten wrote:
adrian wrote:

urllib.socket.setdefaulttimeout(self.timeout)
AttributeError: 'module' object has no attribute 'setdefaulttimeout'

socket.setdefaulttimeout() was added in Python 2.3. You need to upgrade.
Peter

Alternatively you might still be ablet o get Tom O'Malley's 
tiemoutsocket module, which I used in several applications until 2.3 
integrated the functionality.

regards
 Steve
--
Steve Holden+1 703 861 4237  +1 800 494 3119
Holden Web LLC http://www.holdenweb.com/
Python Web Programming  http://pydish.holdenweb.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Little Q: how to print a variable's name, not its value?

2005-03-31 Thread Ron_Adam
On 30 Mar 2005 08:43:17 GMT, Duncan Booth
[EMAIL PROTECTED] wrote:

Here is a rough attempt at printing the names of a variable. It will pick
up several names where appropriate, but deliberately doesn't attempt to
get all possible names (as you say, that could result in endless loops).
In particular, for the Fred=5/John=8/Winner=8 example it will only find
one of John or Winner since it only picks at most one match from each dict 
or list. It doesn't yet manage to correctly lookup attributes (e.g. slots) 
when they aren't stored in a __dict__, nor does the output distinguish
between dictionary keys and values (so encodings.cp437.encoding_map[8]
below actually refers to the key not the value).


Here's what I've been working on.  It still has some glitches in it
but I think it has potential as a instructional/diagnostict tool

I'm going to repost this with the source as it's own topic, maybe it
can be developed further.  :)

Cheers,
Ron



IDLE 1.1.1c1   No Subprocess 
 from pnames import pnames
 pnames()
[globals]
 __builtins__ -- module 
 __doc__ -- docstring 
 __file__ -- C:\Python24\Lib\idlelib\idle.pyw 
 __name__ -- __main__ 
 idlelib -- module 
 pnames -- function 
Paused
 John = 8
 Fred = 6
 Winner = John
 players = [John, Fred]
 pnames()
[globals]
 __builtins__ -- module 
 __doc__ -- docstring 
 __file__ -- C:\Python24\Lib\idlelib\idle.pyw 
 __name__ -- __main__ 
 Fred -- 6 
 idlelib -- module 
 John -- 8 
 players -- [8, 6] 
 pnames -- function 
 Winner -- 8 
Paused

Both winner and John point to the litteral '8', but since the number
'8' can never be changed, it doesn't matter,  but you can look up the
number '8' and find both John and Winner, but changing one, doesn't
change the other.


 John = 9
 pnames()
[globals]
 __builtins__ -- module 
 __doc__ -- docstring 
 __file__ -- C:\Python24\Lib\idlelib\idle.pyw 
 __name__ -- __main__ 
 Fred -- 6 
 idlelib -- module 
 John -- 9 
 players -- [8, 6] 
 pnames -- function 
 Winner -- 8 
Paused

Winner didn't change it's value.


 scores = players
 pnames()
[globals]
 __builtins__ -- module 
 __doc__ -- docstring 
 __file__ -- C:\Python24\Lib\idlelib\idle.pyw 
 __name__ -- __main__ 
 Fred -- 6 
 idlelib -- module 
 John -- 9 
 players -- [8, 6] -- scores
 pnames -- function 
 scores -- [8, 6] -- players
 Winner -- 8 
Paused
 

Here, players and scores are both mutable, changeing them will change
the other and so it shows that the list [8,6] has more than one name.


Cheers,
Ron

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


Re: split an iteration

2005-03-31 Thread Peter Otten
Robin Becker wrote:

 Is there a fast way to get enumerate to operate over a slice of an
 iterable?

I think you don't need that here:

e = enumerate(active_nodes)
for insert_index, a in e:
# ...

for index, a in e:
# ...

Peter

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


Printing Varable Names Tool.. Feedback requested.

2005-03-31 Thread Ron_Adam

Hi, Sometimes it just helps to see what's going on, so I've been
trying to write a tool to examine what names are pointing to what
objects in the current scope.  

This still has some glitches, like not working in winpython or the
command line, I get a 'stack not deep enough' error.  I haven't tested
it on linux yet either.  It could be something with my python
install.(?)

Anyway, here's the source with an example output.  I'm still not sure
what to call it.  Pnames stands for printnames, but if you think of
something better let me know.  

Some things I think will be good is shortening long output such as
lists and dictionaries to '[...]'  or '[:] or a few chars at the
beginning and end with '...' in the middle. I think it's important to
keep the output short and readable.

Any suggestions would be apreciated. :)

Ron


IDLE 1.1.1c1   No Subprocess 
 
[globals]
 __builtins__ -- module 
 __doc__ -- docstring 
 __file__ -- C:\Python24\Lib\idlelib\idle.pyw 
 __main__ -- module 
 __name__ -- __main__ 
 g -- 45 
 glist -- ['a changed', 'list'] -- test2:a
 h -- 45 
 idlelib -- module 
 pnames -- function 
 sys -- module 
 test1 -- function 
 test2 -- function 
 test2.at1 -- [True] -- test2:aaa
[test1]
 t -- ['altered'] -- test2:w
[locals:test2]
 a -- ['a changed', 'list'] -- globals:glist
 aaa -- [True] -- globals:test2.at1
 w -- ['altered'] -- test1:t
Paused
 



#---start---

# pnames.py

A utility to print the value of variables for
debugging purposes.

To use: import prnames and insert prnames.prnames()
in the program where you want to examin names.
Pressing any key will continue.

Author: Ronald Adam


import sys
if __name__ is not '__main__':
import __main__   

def pnames():

View 

objdict = {}# Collect references to object.
namelist = []   # List of names and values by frame.
n = 1
name = None
while name!= 'runcode':
# Move up in the frames to gather name data.
# until the application global frame is reached.
name = sys._getframe(n).f_code.co_name
if name != 'runcode': # This keeps it out of idle's name
space.
namelst = [name,[]]
namespace = sys._getframe(n).f_locals
keys = namespace.keys()
# Get all the names in this frame.
for k in keys:
try:
trash = objdict[id(namespace[k])][name]
except:
try:
objdict[id(namespace[k])][name]=[k]
except:
objdict[id(namespace[k])]={name:[k]}
else:
objdict[id(namespace[k])][name].append(k)
namelst[1].append((k,namespace[k],id(namespace[k])))
#namelist.append(namelst)
#try:
attribs = None
try:
attribs = namespace[k].func_dict
except:
pass
if attribs:
for att in attribs:
attname = k+'.'+att
try:
trash = objdict[id(attribs[att])][attname]
except:
try:

objdict[id(attribs[att])][name]=[attname]
except:

objdict[id(attribs[att])]={name:[attname]}
else:

objdict[id(attribs[att])][name].append(attname)

namelst[1].append((attname,attribs[att],id(attribs[att])))
namelist.append(namelst)

n += 1
# Now print what we collected.
namelist.reverse()  #  Reverse it so we have globals at the
top.
tab = 0
for gname, group in namelist:
# Sort it.
def sortnocase(stringlist): 
tupleList = [(x[0].lower(), x) for x in stringlist]
tupleList.sort()
return [x[1] for x in tupleList]
group = sortnocase(group)
if gname == chr(63):# Idle uses this as name as
app-globals.
gname = 'globals'
if gname == namelist[-1:][0][0]:
gname = 'locals:'+gname # Indicate locals group.
print '%s[%s]'%(''*tab, gname)
tab += 1

for name, obj, objid in group:
# Print the varable name
print ''*tab,name,'--',

# Remove  replace a lot of clutter as we print it.
# List other names pointing to mutable objects.
if name == '__doc__':
obj = 'docstring'
if 'module' in str(obj):# These remove clutter
obj = 'module'# More probably needs to be
if 'function' in str(obj):  # done here.
obj = 'function'

# Print the object
print obj,

# Print the other 

Re: hiding a frame in tkinter

2005-03-31 Thread faramarz yari
thanks
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Printing Varable Names Tool.. Feedback requested.

2005-03-31 Thread Ron_Adam
On Thu, 31 Mar 2005 18:37:53 GMT, Ron_Adam [EMAIL PROTECTED]
wrote:


Hi, Sometimes it just helps to see what's going on, so I've been
trying to write a tool to examine what names are pointing to what
objects in the current scope.  

This still has some glitches, like not working in winpython or the
command line, I get a 'stack not deep enough' error.  I haven't tested
it on linux yet either.  It could be something with my python
install.(?)



Here's the error I'm getting from the python command window.



C:\ron\rondev\pythonmodspython
Python 2.4.1 (#65, Mar 30 2005, 09:13:57) [MSC v.1310 32 bit (Intel)]
on win32
Type help, copyright, credits or license for more information.
 import pnames
 pnames.pnames()
Traceback (most recent call last):
  File stdin, line 1, in ?
  File pnames.py, line 28, in pnames
name = sys._getframe(n).f_code.co_name
ValueError: call stack is not deep enough


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


Re: problem running the cgi module

2005-03-31 Thread chris patton
Thanks alot. This helps tremendously

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


How To Do It Faster?!?

2005-03-31 Thread andrea_gavana
Hello max  NG,

I don't quite understand what your program is doing. The user=a[18::20]
looks really fragile/specific to a directory to me.

I corrected it to user=a[18::5][:-2], it was my mistake. However, that command
is NOT specific to a particular directory. You can try to whatever directory
or net resource mounted on your system. It works.

 a=os.popen(dir /s /q /-c /a-d  + root).read().splitlines()

Mhm... have you tried this command on a BIG directory? On your C: drive
for example? I had to kill Python after having issued that command because
it ate up all my CPU (1GB) for a quite long time. There simply are too many
files/information to retrieve in a single command.
In my first mail, I said I have to work with a BIG directory (more than
1 TB) and I need to retrieve information when they become available (I put
this info on a wxPython ListCtrl). This is why I have chosen os.walk() and
that command (that runs on a separate thread wrt the ListCtrl).
It does NOT run faster than your command (probably my solution is slower),
but I can get information on every directory I scan, while with your command
I have to wait a long time to process the results, plus the user can not
interact with the results already found.

To get a list containing files owned by a specific user, do something like:
 files=[line.split()[-1] for line in a if owner in line]

I will try this solution also.

Thanks NG for your useful suggestions.

Andrea.

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


Stylistic question about inheritance

2005-03-31 Thread Andrew Koenig
Suppose I want to define a class hierarchy that represents expressions, for 
use in a compiler or something similar.

We might imagine various kinds of expressions, classified by their top-level 
operator (if any).  So, an expression might be a primary (which, in turn, 
might be a variable or a constant), a unary expression (i.e. the result of 
applying a unary operator to an expression), a binary expression, and so on.

If I were solving such a problem in C++, I would define a base class for all 
expressions, then derive the various kinds of expression classes from that 
base class.  However, I would not anticipate ever creating objects of the 
base class, so I would make it abstract.

In Python, I can imagine doing the same thing:

class Expr(object):
pass

class UnaryExpr(Expr):
# ...

class BinaryExpr(Expr):
# ...

and so on.  However, although I don't have a choice in C++ about having a 
base class--you can't use dynamic binding without it--in Python I do have 
that choice.  That is, I don't need to have the base class at all unless I 
want to have some operations that are common to all derived classes.

Of course, there are reasons to have a base class anyway.  For example, I 
might want it so that type queries such as isinstance(foo, Expr) work.  My 
question is: Are there other reasons to create a base class when I don't 
really need it right now?


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


Change between Python 2.3 and 2.4 under WinXP

2005-03-31 Thread Franz Steinhäusler
Hello,

My second question from my last post (PyQt on Python 2.4), I think, is
a little got under (i have installed both Python 2.3 and Python 2.4)

Is there any possibility under WinXP, to alterntate quickly 
(with batch file or similary) between python23 and python24.


Many thanks,
-- 
Franz Steinhäusler

DrPython (Project Developer) 
http://mitglied.lycos.de/drpython/
-- 
http://mail.python.org/mailman/listinfo/python-list


Controling the ALU

2005-03-31 Thread Cesar Andres Roldan Garcia
Hi

How can I control an ALU from a PC using Python?

Thanks!


Hola...

Como puedo controlar la ALU de un PC usando Pyhton?

Gracias!

-- 
Atentamente,

Cesar Andres Roldan Garcia
Presidente Comunidad Académica Microsoft Javeriana
Teléfono: 300 8169857
Cali - Colombia
--
http://mail.python.org/mailman/listinfo/python-list


Re: Stylistic question about inheritance

2005-03-31 Thread Carl Banks

Andrew Koenig wrote:
[snip]
 Of course, there are reasons to have a base class anyway.  For
example, I
 might want it so that type queries such as isinstance(foo, Expr)
work.  My
 question is: Are there other reasons to create a base class when I
don't
 really need it right now?

Well, Python seems to get along fine without the ability to do
isinstance(foo,file_like_object); probably better off in the end for
it.  So I'd say you should generally not do it.  Inheritence is for
when different classes need to share functionality.


-- 
CARL BANKS

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


Re: Stylistic question about inheritance

2005-03-31 Thread Martin v. Löwis
Andrew Koenig wrote:
Of course, there are reasons to have a base class anyway.  For example, I 
might want it so that type queries such as isinstance(foo, Expr) work.  My 
question is: Are there other reasons to create a base class when I don't 
really need it right now?
You would normally try to avoid type queries, and rely on virtual
methods instead, if possible. It seems likely for the application
that code can be shared across different subclasses, for example,
you might be able to define
def Expr:
  def __str__(self):
return '%s(%s)' % (self.__class__.__name__,
   , .join(map(str, self.operands()))
requiring you only to implement .operands() in the subclasses.
If you can anticipate such common code, it is easier to add
a base class right away. If you cannot think of a specific
use case, there is little point in having a common base class.
Regards,
Martin
--
http://mail.python.org/mailman/listinfo/python-list


Re: Stylistic question about inheritance

2005-03-31 Thread Lonnie Princehouse
If you try this sort of inheritance, I'd recommend writing down the
formal grammar before you start writing classes.  Don't try to define
the grammar through the inheritance hierarchy; it's too easy to
accidentally build a hierarchy that can't be translated into a
single-pass-parsable grammar...

I usually skip the inheritance and make everything an instance of the
same class, e.g.

class ASTNode(object): ...

class Stmt(ASTNode): ...
class Expr(ASTNode): ...
class UnaryExpr(ASTNode): ...
class BinaryExpr(ASTNode): ...

or you could dynamically generate classes with inheritance based on a
grammar definition

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


Re: Stylistic question about inheritance

2005-03-31 Thread Andrew Koenig
Carl Banks [EMAIL PROTECTED] wrote in message 
news:[EMAIL PROTECTED]

 Well, Python seems to get along fine without the ability to do
 isinstance(foo,file_like_object); probably better off in the end for
 it.  So I'd say you should generally not do it.  Inheritence is for
 when different classes need to share functionality.

That's really the question:  Is it for when they need to share 
functionality, or when they are conceptually related in ways that might lead 
to shared functionality later?


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


Re: Stylistic question about inheritance

2005-03-31 Thread Andrew Koenig
Martin v. Löwis [EMAIL PROTECTED] wrote in message 
news:[EMAIL PROTECTED]

 You would normally try to avoid type queries, and rely on virtual
 methods instead, if possible.

Of course.

 It seems likely for the application
 that code can be shared across different subclasses, for example,
 you might be able to define

 def Expr:
   def __str__(self):
 return '%s(%s)' % (self.__class__.__name__,
, .join(map(str, self.operands()))

 requiring you only to implement .operands() in the subclasses.

Indeed.

 If you can anticipate such common code, it is easier to add
 a base class right away. If you cannot think of a specific
 use case, there is little point in having a common base class.

So, for example, you don't think it's worth including the base class as a 
way of indicating future intent?


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


Re: Change between Python 2.3 and 2.4 under WinXP

2005-03-31 Thread Martin v. Löwis
Franz Steinhäusler wrote:
Is there any possibility under WinXP, to alterntate quickly 
(with batch file or similary) between python23 and python24.
No need to change between them. Just install them both, and
select which one to use on a per-invocation base. I.e. do
c:\python23\python.exe foo.py
c:\python24\python.exe foo.py
If you are concerned that the .py association changes, you
have two options:
1. manually edit the registry. Under HKEY_CLASSES_ROOT,
   find Python.File (or Python.NoConFile), then shell\open\command,
   and switch between paths.
2. install 2.4 and/or 2.3 under different user accounts, on
   a per-user basis (rather than the per-machine basis), and
   switch users. One of the installations can be per-machine,
   as per-user settings override the machine settings for the
   user.
Regards,
Martin
--
http://mail.python.org/mailman/listinfo/python-list


Re: Stylistic question about inheritance

2005-03-31 Thread Andrew Koenig
Lonnie Princehouse [EMAIL PROTECTED] wrote in message 
news:[EMAIL PROTECTED]

 If you try this sort of inheritance, I'd recommend writing down the
 formal grammar before you start writing classes.  Don't try to define
 the grammar through the inheritance hierarchy; it's too easy to
 accidentally build a hierarchy that can't be translated into a
 single-pass-parsable grammar...

Understood.  I was using expression trees as a contrived example, and really 
want to know about the Python community's stylistic preferences for defing 
such hierarchies that don't absolutely need a root.

 I usually skip the inheritance and make everything an instance of the
 same class, e.g.

 class ASTNode(object): ...

 class Stmt(ASTNode): ...
 class Expr(ASTNode): ...
 class UnaryExpr(ASTNode): ...
 class BinaryExpr(ASTNode): ...

Eh?  There's still inheritance here: Everything is derived from ASTNode.  I 
understand that there is a separate design issue whether to make the 
hierarchy deep or shallow, but it's still a hierarchy.



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


Re: Stylistic question about inheritance

2005-03-31 Thread Irmen de Jong
Andrew Koenig wrote:
 Lonnie Princehouse [EMAIL PROTECTED] wrote in message 
 news:[EMAIL PROTECTED]
 
 
If you try this sort of inheritance, I'd recommend writing down the
formal grammar before you start writing classes.  Don't try to define
the grammar through the inheritance hierarchy; it's too easy to
accidentally build a hierarchy that can't be translated into a
single-pass-parsable grammar...
 
 
 Understood.  I was using expression trees as a contrived example, and really 
 want to know about the Python community's stylistic preferences for defing 
 such hierarchies that don't absolutely need a root.

I have used empty or near-empty base classes to be some sort of
class 'tag' for the derived classes.
Much like Java's Serializable interface; it adds nothing on
a functional level but you can check if a class has a 'tag'
by checking if it is an instance of the base class.
I don't know if this is good style in Python but I tend
to use it sometimes (probably because I do Java at work ;-)

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


Re: Controling the ALU

2005-03-31 Thread Grant Edwards
On 2005-03-31, Cesar Andres Roldan Garcia [EMAIL PROTECTED] wrote:

 How can I control an ALU from a PC using Python?

The ALU is buried pretty deep in the CPU.  The ALU is part of
what is actually executing the instructions that _are_ Python.

-- 
Grant Edwards   grante Yow!  VICARIOUSLY
  at   experience some reason
   visi.comto LIVE!!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Stylistic question about inheritance

2005-03-31 Thread Donn Cave
In article 
[EMAIL PROTECTED],
 Andrew Koenig [EMAIL PROTECTED] wrote:

 Carl Banks [EMAIL PROTECTED] wrote in message 
 news:[EMAIL PROTECTED]
 
  Well, Python seems to get along fine without the ability to do
  isinstance(foo,file_like_object); probably better off in the end for
  it.  So I'd say you should generally not do it.  Inheritence is for
  when different classes need to share functionality.
 
 That's really the question:  Is it for when they need to share 
 functionality, or when they are conceptually related in ways that might lead 
 to shared functionality later?

No -- inheritance is for implementation, not to express conceptual
relationship.

   Donn Cave, [EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: IMAP4.search by message-id ?

2005-03-31 Thread Sean Dodsworth
Tony Meyer wrote:

 Can anyone tell me how to get a message's number from the message-id
 using IMAP4.search?
 I've tried this:
 resp, items = server.search(None, 'HEADER',
 'Message-id', msgID) but it gives me a 'bogus search criteria' error
 
 import imaplib
 i = imaplib.IMAP4(mail.example.com)
 i.login(username, password)
 [...]
 i.select()
 [...]
 i.search(None, '(HEADER Message-ID
 [EMAIL PROTECTED])')
 ('OK', ['4'])
 i.logout()
 [...]
 
 =Tony.Meyer

Thank Tony...works fine now
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Change between Python 2.3 and 2.4 under WinXP

2005-03-31 Thread Peter Hansen
Martin v. Löwis wrote:
Franz Steinhäusler wrote:
Is there any possibility under WinXP, to alterntate quickly (with 
batch file or similary) between python23 and python24.

If you are concerned that the .py association changes, you
have two options:
1. manually edit the registry. Under HKEY_CLASSES_ROOT,
   find Python.File (or Python.NoConFile), then shell\open\command,
   and switch between paths.
Or even quicker: write a batch file that calls the
ftype command to change the registry setting.
(I believe changes made with ftype are persistent,
but haven't tested.)
Use ftype /? at a prompt to learn more, and try
assoc .py and ftype Python.File to learn more specifically
about what these do for Python.
-Peter
--
http://mail.python.org/mailman/listinfo/python-list


Re: Stylistic question about inheritance

2005-03-31 Thread Stefan Seefeld
Andrew Koenig wrote:
Of course, there are reasons to have a base class anyway.  For example, I 
might want it so that type queries such as isinstance(foo, Expr) work.  My 
question is: Are there other reasons to create a base class when I don't 
really need it right now?
Coming from C++ myself, I still prefer to use inheritance even if Python
doesn't force me to do it. It's simply a matter of mapping the conceptual
model to the actual design/implementation, if ever possible.
Regards,
Stefan
--
http://mail.python.org/mailman/listinfo/python-list


(no subject)

2005-03-31 Thread python-list-bounces+archive=mail-archive . com
#! rnews 1765
Newsgroups: comp.lang.python
Path: 
news.xs4all.nl!newsspool.news.xs4all.nl!transit.news.xs4all.nl!195.241.76.212.MISMATCH!transit1.news.tiscali.nl!tiscali!transit0.news.tiscali.nl!tudelft.nl!130.161.131.117.MISMATCH!tudelft.nl!newsfeed.multikabel.nl!gatel-ffm!gatel-ffm!proxad.net!proxad.net!newsread.com!news-xfer.newsread.com!nntp.abs.net!attws2!ip.att.net!NetNews1!xyzzy!nntp
From: Harry George [EMAIL PROTECTED]
Subject: Re: Generating RTF with Python
X-Nntp-Posting-Host: cola2.ca.boeing.com
Content-Type: text/plain; charset=us-ascii
Message-ID: [EMAIL PROTECTED]
User-Agent: Gnus/5.09 (Gnus v5.9.0) Emacs/21.3
Lines: 37
Sender: [EMAIL PROTECTED]
Organization: The Boeing Company
References: [EMAIL PROTECTED] [EMAIL PROTECTED]
Mime-Version: 1.0
Date: Thu, 31 Mar 2005 20:56:42 GMT
Xref: news.xs4all.nl comp.lang.python:370154

Axel Straschil [EMAIL PROTECTED] writes:

 Hello!
 
  does anyone know of a high-level solution to produce RTF from Python=20
  (something similar to
  Reportlab for producing PDF)?
 
 Spend hours of googeling and searching, also in this NG, about two
 months ago. My conclusion is: On windwos, maybe you can include some
 hacks with dll's, under linux, linux support for generating rtf is none,
 and so is python's.
 
 My workaround was: 
 http://www.research.att.com/sw/download/
 This includes an html2rtf converter, which I access from python via
 popen and temporary files. Not high-level, not very sexy ... ;-(
 
 Lg,
 AXEL.
 -- 
 Aber naja, ich bin eher der Forentyp. Wolfibolfi's outing in 
 http://www.informatik-forum.at/showpost.php?p=206342postcount=10

I generate docbook and convert that to rtf.  I generate the docbook
from my pdx markup:

http://www.seanet.com/~hgg9140/comp/index.html#L007

If you go this route, your python code is actually writing pdx, and
you need a 2 step conversion (pdx2docbook.py, then openjade for the
xml-to-rtf step).

-- 
[EMAIL PROTECTED] 
6-6M21 BCA CompArch Design Engineering
Phone: (425) 294-4718
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Stylistic question about inheritance

2005-03-31 Thread Martin v. Löwis
Andrew Koenig wrote:
So, for example, you don't think it's worth including the base class as a 
way of indicating future intent?
No. In this respect, I believe in XP: refactor when the need comes up,
but not before.
Regards,
Martin
--
http://mail.python.org/mailman/listinfo/python-list


Re: Stylistic question about inheritance

2005-03-31 Thread Bengt Richter
On Thu, 31 Mar 2005 20:24:08 GMT, Andrew Koenig [EMAIL PROTECTED] wrote:

Martin v. Löwis [EMAIL PROTECTED] wrote in message 
news:[EMAIL PROTECTED]

 You would normally try to avoid type queries, and rely on virtual
 methods instead, if possible.

Of course.

 It seems likely for the application
 that code can be shared across different subclasses, for example,
 you might be able to define

 def Expr:
   def __str__(self):
 return '%s(%s)' % (self.__class__.__name__,
, .join(map(str, self.operands()))

 requiring you only to implement .operands() in the subclasses.

Indeed.

 If you can anticipate such common code, it is easier to add
 a base class right away. If you cannot think of a specific
 use case, there is little point in having a common base class.

So, for example, you don't think it's worth including the base class as a 
way of indicating future intent?

If the intent is pretty sure of implementation, I guess it will save some
editing to include it at the start (unless you intended to define old-style 
classes
and factor the base class inheritance revisions into some global metaclass hack 
later
(not even really sure that's reliably possible, but pretty sure it would not be 
the
best style ;-) BTW 2.5 may let you mod classes by prefixing a decorator instead 
of
editing the first line. Not sure about the style/semantics tradeoffs there.

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


Re: Controling the ALU

2005-03-31 Thread Michael Spencer
Grant Edwards wrote:
On 2005-03-31, Cesar Andres Roldan Garcia [EMAIL PROTECTED] wrote:

How can I control an ALU from a PC using Python?

The ALU is buried pretty deep in the CPU.  The ALU is part of
what is actually executing the instructions that _are_ Python.
Maybe:
  from __builtin__ import int as ALU
  ALU.__add__(3,4)
 7
Sorry ;-)
Michael
--
http://mail.python.org/mailman/listinfo/python-list


Re: split an iteration

2005-03-31 Thread Raymond Hettinger
[Robin Becker]
 This function from texlib in oedipus.sf.net is a real cpu hog and I determined
 to see if it could be optimized.

 def add_active_node(self, active_nodes, node):
  Add a node to the active node list.
  The node is added so that the list of active nodes is always
  sorted by line number, and so that the set of (position, line,
  fitness_class) tuples has no repeated values.
  

If you can change the data structure to be an actual list of tuples, then the
bisect module can be used directly:

insert_index = bisect.bisect_left(active_nodes, node)
if active_nodes[insert_index] == node:
return# avoid creating a duplicate entry
active_nodes.insert(insert_index, node)

If the data structure cannot be changed to tuples, then try adding a custom
compare operation to the node class:

def __cmp__(self, other):
return cmp((self.line, self.position, self.fitness_class),
   (other.line, other.position, other.fitness_class))



  insert_index = nan
  for index, a in enumerate(active_nodes):
  if a.line=node_line:
  insert_index = index
  break
  index = insert_index

This loop can be squeezed a bit more using itertools.imap() and
operator.attrgetter() for the attribute lookup:

for index, aline in enumerate(imap(attrgetter('line'), active_nodes):
if aline  node_line:
. . .



 Is there a fast way to get enumerate to operate over a slice of an iterable?

enumerate(s) is the same as izip(count(), s).
So, to start from position i, write:

for index, value in izip(count(i), s[i:]):
 . . .

That being said, your best bet is to eliminate the initial linear search which
is likely consuming most of the clock cycles.

Also, I noticed that the code does not reference self.  Accordingly, it is a
good candidate for being a staticmethod or standalone function.



Raymond Hettinger


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


Re: Problem with national characters

2005-03-31 Thread david . tolpin

 Is there a way around this problem?

put

import sys
sys.setdefaultencoding('UTF-8')

into sitecustomize.py in the top level of your PYTHONPATH .

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


Re: redundant imports

2005-03-31 Thread Steve Holden
Peter Hansen wrote:
max(01)* wrote:
this leads me to another question. since *.pyc files are automatically 
created the first time an import statement in executed on a given 
module, i guess that if i ship a program with modules for use in a 
directory where the user has no write privileges then i must ship the 
*.pyc files along too. right?

Not required except for performance reasons.  If the .pyc
files don't exist, the .py files are recompiled and the
resulting bytecode is simply held in memory and not cached
and the next startup will recompile all over again.
Note also that the main file (the one invoke from the
command line) is never cached in a .pyc...
-Peter
Also, beware that you ship the right .pyc files - they are 
version-dependent, so shipping 2.3 binaries to a 2.4 user will actually 
cause a small slow-down, since the interpreter will have to check the 
.pyc's for the correct magic number before ignoring them.

regards
 Steve
--
Steve Holden+1 703 861 4237  +1 800 494 3119
Holden Web LLC http://www.holdenweb.com/
Python Web Programming  http://pydish.holdenweb.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Problem with national characters

2005-03-31 Thread Leif B. Kristensen
[EMAIL PROTECTED] wrote:

 put
 
 import sys
 sys.setdefaultencoding('UTF-8')
 
 into sitecustomize.py in the top level of your PYTHONPATH .

Uh ... it doesn't seem like I've got PYTHONPATH defined on my system in
the first place:

[EMAIL PROTECTED] leif $ env |grep -i python
PYTHONDOCS=/usr/share/doc/python-docs-2.3.4/html

I ran this small snippet that I found after a search on Gentoo-forums:

 import sys
 import string
 path_list = sys.path
 for eachPath in path_list: print eachPath
...

/usr/lib/python23.zip
/usr/lib/python2.3
/usr/lib/python2.3/plat-linux2
/usr/lib/python2.3/lib-tk
/usr/lib/python2.3/lib-dynload
/usr/lib/portage/pym
/usr/lib/python2.3/site-packages
/usr/lib/python2.3/site-packages/gtk-2.0
   

What should my PYTHONPATH look like, and where do you suggest to put the
sitecustomize.py file? 
-- 
Leif Biberg Kristensen
http://solumslekt.org/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Stylistic question about inheritance

2005-03-31 Thread Lonnie Princehouse
Well, that's true, but I meant to convey that no grammatical entity is
the base class of another entity, so it's a flat inheritance tree in
that respect.  ASTNode would not be something that the parser would
know anything about.

I guess that's sort of moot if your expression trees are just a
contrived example; in that case, I'd say that how deep you want your
inheritance hierarchy to be depends entirely on how your program wants
to use it.

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


mod_python and zope

2005-03-31 Thread David Bear
I will be running zope, and I would also like to run mod_python. The problem
arised when zope wants a threaded version of python and mod_python wants
no_threads.

I've been searching the mod_python site for pointers on how to install two
instances of python, then configuring mod_python to use the non-thread
instance. Haven't found anything yet.

I'd appreciate any pointers the group may have as to how to install two
pythons on the system -- and freely switch between a threaded and non-threaded
version.  I know I can do this with pythonpath or/and python home but I'm not
really good at experimenting without destroying things. 

--
David Bear
phone:  480-965-8257
fax:480-965-9189
College of Public Programs/ASU
Wilson Hall 232
Tempe, AZ 85287-0803
 Beware the IP portfolio, everyone will be suspect of trespassing
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: split an iteration

2005-03-31 Thread Robin Becker
Peter Otten wrote:
Robin Becker wrote:

Is there a fast way to get enumerate to operate over a slice of an
iterable?

I think you don't need that here:
e = enumerate(active_nodes)
for insert_index, a in e:
# ...
for index, a in e:
# ...
Peter
I tried your solution, but I think we miss the split element
eg for
 e = enumerate([0,1,2,3,4,5])
 for i,a in e:
... if a==3: break
...
 for i,a in e:
... print i,a
...
4 4
5 5

I think the second loop needs to start at 3 ie the split needs to be 
start, limit semantics

It would be nice to be able to fix it with a move back method.
--
Robin Becker
--
http://mail.python.org/mailman/listinfo/python-list


Re: Problem with national characters

2005-03-31 Thread Leif B. Kristensen
 [EMAIL PROTECTED] wrote:
 
 put
 
 import sys
 sys.setdefaultencoding('UTF-8')
 
 into sitecustomize.py in the top level of your PYTHONPATH .

I found out of it, sort of. Now I've got a PYTHONPATH that points to my
home directory, and followed your instructions. The first time I got an
error message due to a typo. I corrected it, and now Python starts
without an error message. But it didn't solve my problem with the
uppercase Ø at all. Is there something else I have to do?
-- 
Leif Biberg Kristensen
http://solumslekt.org/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Change between Python 2.3 and 2.4 under WinXP

2005-03-31 Thread Cappy2112

Do you really think this is a safe solution?
How do you deal with features that are in new 2.4, but you invoke it
with the exe from 2.3?

The imports have to be handled as well, and the dlls, and the libs too

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


Re: Numarray newbie question

2005-03-31 Thread Colin J. Williams
ChinStrap wrote:
I know there are probably alternatives for this with the standard
library, but I think that would kill the speed I get with numarray:
Say I have two 2-dimensional numarrays (x_mat and y_mat, say), and a
function f(x,y) that I would like to evaluate at every index.
Basically I want to be able to say f(x_mat,y_mat) and have it return a
numarray with the same shape and element wise evaluation of f.  I know,
I want a ufunc, but they look scary to write my own. Are there any
functions that do this? Or is writing ufuncs easier than it seems?
Thanks,
-Chris Neff
numarray has a fixed set of ufuncs.  Section 5.1 of the docs.
Section 5.3 points to a method for writing the f(i, j).
Unfortunately, it appears to require that f be written in C and assumes 
that the user operating system has a compiler, which windows, in 
general, does not.

It would be good if f could be written in Python.
Colin W.
--
http://mail.python.org/mailman/listinfo/python-list


Re: split an iteration

2005-03-31 Thread Robin Becker
Raymond Hettinger wrote:
[Robin Becker]
This function from texlib in oedipus.sf.net is a real cpu hog and I determined
to see if it could be optimized.
def add_active_node(self, active_nodes, node):
Add a node to the active node list.
The node is added so that the list of active nodes is always
sorted by line number, and so that the set of (position, line,
fitness_class) tuples has no repeated values.


If you can change the data structure to be an actual list of tuples, then the
bisect module can be used directly:
This is a way forward and I think is doable. The original Knuth algo 
used only global integer arrays. The actual insert point depends on the 
line attribute only which would be the first tuple element. So 
apparently we always insert non-identical line breaks at the beginning 
of their line group; I think we can do the insert check and then a bit 
of checking to find the actual insert point using bisect_right handwave 
handwave.


insert_index = bisect.bisect_left(active_nodes, node)
if active_nodes[insert_index] == node:
return# avoid creating a duplicate entry
active_nodes.insert(insert_index, node)
If the data structure cannot be changed to tuples, then try adding a custom
compare operation to the node class:
def __cmp__(self, other):
return cmp((self.line, self.position, self.fitness_class),
   (other.line, other.position, other.fitness_class))


insert_index = nan
for index, a in enumerate(active_nodes):
if a.line=node_line:
insert_index = index
break
index = insert_index

This loop can be squeezed a bit more using itertools.imap() and
operator.attrgetter() for the attribute lookup:
for index, aline in enumerate(imap(attrgetter('line'), active_nodes):
if aline  node_line:
. . .


Is there a fast way to get enumerate to operate over a slice of an iterable?

enumerate(s) is the same as izip(count(), s).
So, to start from position i, write:
for index, value in izip(count(i), s[i:]):
 . . .
That being said, your best bet is to eliminate the initial linear search which
is likely consuming most of the clock cycles.
Also, I noticed that the code does not reference self.  Accordingly, it is a
good candidate for being a staticmethod or standalone function.

Raymond Hettinger


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


assignments - want a PEP

2005-03-31 Thread Kay Schluehr
From time to time I still use my old Mathematica system. The
Mathematica language has some nice properties. The one I like best is
the possibility to create symbols from nothing. Translated into the
Python realm following creations are possible:

 a
a

That's it. Just make an 'a' as a pure symbol. The reason for those
symbols is late evaluation. Most of the time an expression should be
transformed and simplified before it is finally evaluated using
concrete numbers or other stuff. I tried to mimic this in Python using
a Symbol() class:

 a = Symbol()
 a
a

So 'a' would be a Symbol object that is represented by the name a not
by the standard format information that tells us that a is some member
of class Symbol(). Starting with Symbol() subclsses of Symbol() e.g
Expr() could overload operators like __add__, __mul__ etc. in order to
create new symbolic objects:

 a,b = Expr(),Expr()
 (a+b)/c
a+b
---
 c

The availability of Symbol() would make it easy to create a Computer
Algebra System ( CAS ) in Python, just using standard Python operators.

Unfortunately it is not possible to implement Symbol() in an elegant
way. Symbol() has to retrieve somehow it's own name from the
environment where the name is created, but no assignment/name binding
event is accessible to Python objects.

I want to propose making name binding accessible by introducing an
__assign__ method which is called, whenever an object is bound to a
name. By default the __assign__ method does nothing at all but can be
implemented by custom classes.

def __assign__(self,own_name):
# do somtehing with me and my name

Instead of changing the behaviour of the current assignment operator
= one could think about introduction of a new assignment := that is
connected to the __assign__ method of custom classes if available.

What do You think?

Regards,
Kay

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


Re: assignments - want a PEP

2005-03-31 Thread Paul Rubin
Kay Schluehr [EMAIL PROTECTED] writes:
  a = Symbol()
  a
 a

Use 

  a = Symbol('a') 

instead and it should solve most of the problems you mention.  What's
supposed to happen anyway, in your proposal, after

  a = Symbol()
  b = a
  print b

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


System bell

2005-03-31 Thread Baza
Am I right in thinking that print \a should sound the system, 'bell'?

B
--  
Computer says, 'no'


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


Re: Problem with national characters

2005-03-31 Thread Leif B. Kristensen
Leif B. Kristensen skrev:

Is there something else I have to do?

Please forgive me for talking with myself here :-) I should have looked
up Unicode in Learning Python before I asked. This seems to work:

 u'før'.upper()
u'F\xd8R'
 u'FØR'
u'F\xd8R'
 'FØR'
'F\xd8R'

So far, so good. Note that the Unicode representation of the uppercase
version is identical to the default. But when I try the builtin
function unicode(), weird things happen:

 s='FØR'
 s
'F\xd8R'
 unicode(s)
Traceback (most recent call last):
  File stdin, line 1, in ?
UnicodeDecodeError: 'utf8' codec can't decode bytes in position 1-2:
invalid data

The ActivePython 2.3.2 doesn't even seem to understand the 'u' prefix.
So even if I can get this to work on my own Linux machine, it hardly
looks like a portable solution.

Seems like the solution is to keep away from letters above ASCII-127,
like we've done since the dawn of computing ...
-- 
Leif Biberg Kristensen
http://solumslekt.org/
-- 
http://mail.python.org/mailman/listinfo/python-list


assignments - want a PEP

2005-03-31 Thread Kay Schluehr
From time to time I still use my old Mathematica system. The
Mathematica language has some nice properties. The one I like best is
the possibility to create symbols from nothing. Translated into the
Python realm following creations are possible:

 a
a

That's it. Just make an 'a' as a pure symbol. The reason for those
symbols is late evaluation. Most of the time an expression should be
transformed and simplified before it is finally evaluated using
concrete numbers or other stuff. I tried to mimic this in Python using
a Symbol() class:

 a = Symbol()
 a
a

So 'a' would be a Symbol object that is represented by the name a not
by the standard format information that tells us that a is some member
of class Symbol(). Starting with Symbol() subclsses of Symbol() e.g
Expr() could overload operators like __add__, __mul__ etc. in order to
create new symbolic objects:

 a,b = Expr(),Expr()
 (a+b)/c
a+b
---
 c

The availability of Symbol() would make it easy to create a Computer
Algebra System ( CAS ) in Python, just using standard Python operators.

Unfortunately it is not possible to implement Symbol() in an elegant
way. Symbol() has to retrieve somehow it's own name from the
environment where the name is created, but no assignment/name binding
event is accessible to Python objects.

I want to propose making name binding accessible by introducing an
__assign__ method which is called, whenever an object is bound to a
name. By default the __assign__ method does nothing at all but can be
implemented by custom classes.

def __assign__(self,own_name):
# do somtehing with me and my name

Instead of changing the behaviour of the current assignment operator
= one could think about introduction of a new assignment := that is
connected to the __assign__ method of custom classes if available.

What do You think?

Regards,
Kay

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


Re: Problem with national characters

2005-03-31 Thread Max M
Leif B. Kristensen wrote:
Is there a way around this problem? My character set in Linux is
ISO-8859-1. In Windows 2000 it should be the equivavent Latin-1, though
I'm not sure about which character set the command shell is using.
The unicode methods seems to do it correctly. So you can decode your 
strings as unicode, do the transfom, and encode it back as latin1.

print repr('før'.decode('latin-1').upper().encode('latin-1')) #
'F\xd8R'
print repr('FØR'.decode('latin-1').encode('latin-1'))
'F\xd8R'
--
hilsen/regards Max M, Denmark
http://www.mxm.dk/
IT's Mad Science
--
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie Shell Editor Question

2005-03-31 Thread Scott David Daniels
Tim Roberts wrote:
Kash [EMAIL PROTECTED] wrote:
...However when I start idle and run a program from it; I get the
following types of errors
Idle is already running the python interpreter.  You don't need to start
another copy.  It is just like you had typed python at a command line.
If you want to run a script in a file, you have to use the IDLE menu to do
so.  I don't know IDLE, but it's probably something like File-Run.
Just in case that's not enough of a clue:
ctrl-O to open the file with a file chooser dialog
F5 to run the currently open file.
Or, if you like to click:
File - Open (choose file)
Run - Run Module
--Scott David Daniels
[EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list


Re: Making a DLL with python?

2005-03-31 Thread alex23
Larry Bates wrote:
 Almost all languages can dispatch a COM object easily.

Being stuck using VBScript at work, I kind of poked around COM creation
one day and was surprised to find that it's possible to just drop
python script directly into COM objects. Five minutes later and I was
finally using real dicts  lists in VBScript :)

-alex23

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


  1   2   >