Re: spam

2008-07-14 Thread David Brown

rickman wrote:

spam


*Why* are you replying to spam messages like this?  The spam in c.a.e. 
usually costs me about 10-15 seconds a day pressing "K" for "kill 
thread" on my newsreader - but your bizarre new habit has cost me far 
more in trying to think out a rational explanation for your posts.

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


Re: Why is there no GUI-tools like this for Windows?

2008-07-14 Thread Martin Walsh
maestro wrote:
> I can just do the layout with my mouse and then there is a program
> that writes the code for me.
> GUI-programming is hard for no reason. One good program then forever
> easy...
> 
> Is there not something like this for Python/Windows? Is the Linux one
> only for ruby or for any language?
> 

I only watched a small part of the video so I'm making some assumptions
about it's content. But there is nothing preventing you from using the
same(/similar) toolchain on windows, which I believe would include
python, pygtk, the gtk+ runtime, and glade -- last I checked all have
windows binary distributions.

To quote the glade website
"""
The user interfaces designed in Glade are saved as XML, and by using the
libglade library these can be loaded by applications dynamically as needed.

By using libglade, Glade XML files can be used in numerous programming
languages including C, C++, Java, Perl, Python, C#, Pike, Ruby, Haskell,
Objective Caml and Scheme. Adding support for other languages is easy too.
"""

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


Re: Beginner Question : Iterators and zip

2008-07-14 Thread cokofreedom
>
> zip(*vec_list) will zip together all entries in vec_list
> Do be aware that zip stops on the shortest iterable.  So if vec[1] is
> shorter than vec[0] and matches otherwise, your output line will be
> truncated.  Or if vec[1] is longer and vec[0] matches as far as it goes,
> there will be no signal either.
>

Do note that from Python 3.0 there is another form of zip that will
read until all lists are exhausted, with the other being filled up
with a settable default value. Very useful!
--
http://mail.python.org/mailman/listinfo/python-list


Re: About wmi

2008-07-14 Thread patrol
On 7月14日, 下午12时29分, Larry Bates <[EMAIL PROTECTED]> wrote:
> patrol wrote:
> > On 7月13日, 下午10时26分, Larry Bates <[EMAIL PROTECTED]> wrote:
> >> patrol wrote:
> >>> I want to prevent some process from running. The code is in the
> >>> following. I  encounter some unexpected troubles.
> >>> Probelm1: This program cannot terminate "scrcons.exe" and
> >>> "FNPLicensingService.exe",which are system processes.
> >>> Problem2:After a while, this program will abort by error
> >>>   File "C:\Python25\lib\wmi.py", line 397, in __call__
> >>> handle_com_error (error_info)
> >>>   File "C:\Python25\lib\wmi.py", line 190, in handle_com_error raise
> >>> x_wmi, "\n".join (exception_string)
> >>> UnicodeDecodeError: 'ascii' codec can't decode byte 0xb7 in position
> >>> 14: ordinal not in range(128)
> >>> 
> >>> code
> >>> # -*- coding:utf-8 -*-
> >>> import pythoncom
> >>> import wmi
> >>> import threading
> >>> import time
> >>> from xml.dom.minidom import parse, parseString
> >>> class Info (threading.Thread):
> >>>def __init__ (self):
> >>>threading.Thread.__init__ (self)
> >>>def run (self):
> >>>print 'In Another Thread...'
> >>>pythoncom.CoInitialize ()
> >>>dom1 = parse('processTerminateList.xml')
> >>>config_element = 
> >>> dom1.getElementsByTagName("processTerminateList")
> >>> [0]
> >>>servers = config_element.getElementsByTagName("processName")
> >>>try:
> >>>c = wmi.WMI ()
> >>>for process in c.Win32_Process ():
> >>>for server in servers:
> >>>if process.name == 
> >>> getText(server.childNodes):
> >>>process.Terminate()
> >>>print process.name
> >>>process_watcher = c.Win32_Process.watch_for("creation")
> >>>while True:
> >>>new_process = process_watcher()
> >>>name =  new_process.Caption
> >>>print name
> >>>for server in servers:
> >>>if name == getText(server.childNodes):
> >>>new_process.Terminate()
> >>>finally:
> >>>pythoncom.CoUninitialize ()
> >>> def getText(nodelist):
> >>>rc = ""
> >>>for node in nodelist:
> >>>if node.nodeType == node.TEXT_NODE:
> >>>rc = rc + node.data
> >>>return rc
> >>> if __name__ == '__main__':
> >>>Info().start()
> >>> --
> >>> processTerminateList.xml-
> >>> 
> >>> 
> >>> scrcons.exe
> >>> TXPlatform.exe
> >>> mdm.exe
> >>> FNPLicensingService.exe
> >>> notepad.exe
> >>> uedit32.exe
> >>> 
> >> You should probably post this to comp.python.windows.  Tim Golden (author 
> >> of WMI
> >> interface) monitors that list religously (thanks Tim).
>
> >> -Larry- 隐藏被引用文字 -
>
> >> - 显示引用的文字 -
>
> > I cannot find comp.python.windows.What's the URL?
>
> http://news.gmane.org/gmane.comp.python.windows/cutoff=7565
>
> -Larry- 隐藏被引用文字 -
>
> - 显示引用的文字 -

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

Re: iterator clone

2008-07-14 Thread Yosifov Pavel
> `tee()` doesn't copy the iterator or its internal state but just caches
> it's results, so you can iterate over them again.  That makes only sense
> if you expect to use the two iterators in a way they don't get much out of
> sync.  If your usage pattern is "consume iterator 1 fully, and then
> re-iterate with iterator 2" `tee()` has no advantage over building a list
> of all results of the original iterator and iterate over that twice.
> `tee()` would be building this list anyway.

It's interesting and a concrete answer. Thanks a lot.

> Because it's often not possible without generating a list with all
> results, and the advantage of a low memory footprint is lost.
>
> Ciao,
> Marc 'BlackJack' Rintsch

Seems like "monada". But I think is possible to determine when there
is a bounded external state (side-effects) or not, may be is needed
some new class-protocol for it... or something else. Or another way:
iterators may be re-iterable always, but if programmer need to point
to the extra- (external) state, he has to raise some a special
exception in __iter)) method... OK, it's only fantasies about language
design :-)

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


Simple Image Cropper

2008-07-14 Thread Mr SZ
Hi,

I am designing a simple image cropper which simply takes an image and use PIL 
to do the cropping.Now in order to do the cropping I simply draw a rectangle on 
the image by dragging the mouse over the image.I then use button press and 
button release events to find the mouse postition and send across the tuple to 
PIL  .Everything works fine but what I need is a way to show the user a dotted 
rectangle as he drags across the mouse as in every other standard image 
editor.I have learnt that using gnomecanvas will do that but given my time 
constraints and the lack of a tutorial on pygtk ,I used gtk.image + event box 
to do the above.

Can someone point to using gnomecanvas in the following directions:
1.Load an image into the canvas from file as well as pixbuf.
2.Draw a dotted rectangle
3.Fire and capture mouse events
4.Use PIL 

I basically want to know about point 2. Also,will implementing cairo be easy on 
glade and pygtk?

Regards,
Abhishek

" life isn't heavy enough,it flies away and floats far above action"


  Start at the new Yahoo!7 for a better online experience. www.yahoo7.com.au--
http://mail.python.org/mailman/listinfo/python-list

Re: Dictionary bidirectional

2008-07-14 Thread Kless
But in my dictionary both keys and values are unique.

On Jul 14, 7:34 am, Dennis Lee Bieber <[EMAIL PROTECTED]> wrote:
> On Sun, 13 Jul 2008 16:21:11 -0700 (PDT), Kless
> <[EMAIL PROTECTED]> declaimed the following in comp.lang.python:
>
> > I need a dictionary where get the result from a 'key' (on left), but
> > also from a 'value' (on right), how to get it?
>
> > I know that dictionaries aren't bidirectional, but is there any way
> > without use two dictionaries?
>
>         Just out of curiosity... What do you expect to have returned from...
>
> aDict = { "one" : "two",
>                 "three" : "four",
>                 "What?" : "two"     }
>
> when looking for the value "two"?
>
>         In a dictionary, the /keys/ are unique... but the /values/ can be
> duplicates.
--
http://mail.python.org/mailman/listinfo/python-list


Re: while var, but var ==16 != true

2008-07-14 Thread John Machin
On Jul 14, 3:32 pm, Tim Roberts <[EMAIL PROTECTED]> wrote:
> maestro <[EMAIL PROTECTED]> wrote:
>
> >why does this work?  "while p" = "while p != 0" ? 1 is True and 0 is
> >false in python but other numbers have no boolean value so why doesnt
> >it abort.
>
> Because your statement is incorrect.  Everything has a boolean value in
> Python.  0, None, False, '' (empty string), [] (empty list), () (empty
> tuple), and {} (empty dictionary) all have a False value.  Everything else
> has a True value.

Not quite; for example:

>>> bool(set())
False
>>>

According to section 5.10 of the Reference Manual:
"""
In the context of Boolean operations, and also when expressions are
used by control flow statements, the following values are interpreted
as false: False, None, numeric zero of all types, and empty strings
and containers (including strings, tuples, lists, dictionaries, sets
and frozensets). All other values are interpreted as true.
"""

... and for the definition for what a user-written class needs to do,
see section 3.4.1:
"""
__nonzero__( self)

Called to implement truth value testing, and the built-in operation
bool(); should return False or True, or their integer equivalents 0 or
1. When this method is not defined, __len__() is called, if it is
defined (see below). If a class defines neither __len__() nor
__nonzero__(), all its instances are considered true.
"""

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


subprocess module

2008-07-14 Thread John Mechaniks
from subprocess import call
call(['ls', '-l'])

How do I get the result (not the exit status of the command) of "ls -
l" into a variable?
--
http://mail.python.org/mailman/listinfo/python-list


Re: subprocess module

2008-07-14 Thread Peter Otten
John Mechaniks wrote:

> from subprocess import call
> call(['ls', '-l'])
> 
> How do I get the result (not the exit status of the command) of "ls -
> l" into a variable?

output = subprocess.Popen(["ls", "-l"], stdout=subprocess.PIPE).stdout.read()

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


Re: Dictionary bidirectional

2008-07-14 Thread Ken Starks

Dennis Lee Bieber wrote:

On Sun, 13 Jul 2008 16:21:11 -0700 (PDT), Kless
<[EMAIL PROTECTED]> declaimed the following in comp.lang.python:


I need a dictionary where get the result from a 'key' (on left), but
also from a 'value' (on right), how to get it?

I know that dictionaries aren't bidirectional, but is there any way
without use two dictionaries?


Just out of curiosity... What do you expect to have returned from...

aDict = { "one" : "two",
"three" : "four",
"What?" : "two" }

when looking for the value "two"?

In a dictionary, the /keys/ are unique... but the /values/ can be
duplicates.


I wonder if anyone has implemented an 'equivalence class' class (for
finite sets) based on this.

Obviously the relation defined by
   k1~k2  iff D[k1] == D[k2]
does partition the set of all keys as an equivalence class.

So ... as a kind of inverse you could return a set, a subset of the
keys. How you would get a canonical representative of that set is
a different matter, of course. Unless, as in the OP's case, it is
a singleton set.

It would seem more efficient to do this when a key-value pair is
added or removed from the original dictionary rather than iterating
over all the keys each time you used it.


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


Re: Does omniORBpy 3.2 supports DII?

2008-07-14 Thread Duncan Grisby
In article <[EMAIL PROTECTED]>,
Ilan  <[EMAIL PROTECTED]> wrote:

>My apologies if this is not the correct forum for thses quiestions, by
>I'm rather new to python+CORBA
>
>Has anyone used omniORBpy as CORBA implementation? are there any
>drawbacks?

As omniORBpy's author, I'm biased, so I'll let other people answer
that...

>Does omniORBpy 3.2 supports the Dynamic Invocation Interface?

No, it doesn't. You can use Python's normal dynamic features to build
dynamic requests, though.

Cheers,

Duncan.

-- 
 -- Duncan Grisby --
  -- [EMAIL PROTECTED] --
   -- http://www.grisby.org --
--
http://mail.python.org/mailman/listinfo/python-list


Re: subprocess module

2008-07-14 Thread sukkopera
On 14 Lug, 10:34, Peter Otten <[EMAIL PROTECTED]> wrote:
> John Mechaniks wrote:
> > from subprocess import call
> > call(['ls', '-l'])
>
> > How do I get the result (not the exit status of the command) of "ls -
> > l" into a variable?
>
> output = subprocess.Popen(["ls", "-l"], stdout=subprocess.PIPE).stdout.read()
>
> Peter

Correct, but I would rather use Python's os.listdir() and/or
os.stat(). Executing a simple ls running a subprocess is overkill.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Moving to functional programming

2008-07-14 Thread James Fassett
On Jul 12, 12:18 am, George Sakkis <[EMAIL PROTECTED]> wrote:
> It relies on positional arguments, tuple unpacking and
> the signature of zip(),

It moreso relies on the fact that:

>>> t1 = (0,1,2,3)
>>> t2 = (7,6,5,4)
>>> [t1, t2] == zip(*zip(t1, t2))
True

This is mathematically true given the definition of zip. To me that is
very functional. Basically, unpacking a pair list into zip is the
canonical definition of unzipping the list (which is exactly my
intention).

> Second, it is less readable,

For a Python programmer - you are correct. For someone familiar with
the use of zip (as described above) - I wonder. Since I am new to this
I can't say for sure. If I posted the same code to a Haskell list or a
ML list would their opinion be the same?

> robust and efficient than the list comprehension.

I don't know the internals of how the Python interpreter treats list
comprehensions and zip but it seems reasonable to assume an extra list
is created for the zip approach.

However, in the limited functional code I have seen this is actually a
common practice. I would suppose in languages with lazy evaluation
this isn't a problem - but in Python it would be.

> The list comprehension is still the most pythonic approach though.

I agree that it is more Pythonic and preferable in this case.

Cheers,
James
--
http://mail.python.org/mailman/listinfo/python-list


Re: subprocess module

2008-07-14 Thread John Mechaniks
On Jul 14, 12:34 pm, Peter Otten <[EMAIL PROTECTED]> wrote:
> John Mechaniks wrote:
> > from subprocess import call
> > call(['ls', '-l'])
>
> > How do I get the result (not the exit status of the command) of "ls -
> > l" into a variable?
>
> output = subprocess.Popen(["ls", "-l"], stdout=subprocess.PIPE).stdout.read()
>
> Peter

Thanks Peter.

Just curious

What difference does the following code makes? What are the advantages
of the above method over this one?
output = subprocess.Popen(['ls', '-l'],
stdout=subprocess.PIPE).communicate()[0]

Also could someone show an example of using the optional input
argument for communicate()

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


Re: Simple Image Cropper

2008-07-14 Thread Victor Noagbodji
>Hi,
>
>I am designing a simple image cropper which simply takes an image and use PIL
> to do the cropping.Now in order to do the cropping I simply draw a rectangle 
> on
> the image by dragging the mouse over the image.I then use button press and
> button release events to find the mouse postition and send across the tuple 
> to PIL.
> Everything works fine but what I need is a way to show the user a dotted 
> rectangle
> as he drags across the mouse as in every other standard image editor. I have 
> learnt
> that using gnomecanvas will do that but given my time constraints and the 
> lack of a
> tutorial on pygtk ,I used gtk.image + event box to do the above.
>
>Can someone point to using gnomecanvas in the following directions:
>1.Load an image into the canvas from file as well as pixbuf.
>2.Draw a dotted rectangle
>3.Fire and capture mouse events
>4.Use PIL

>I basically want to know about point 2. Also,will implementing cairo be easy 
>on glade and pygtk?
>
>Regards,
>Abhishek

Hello,

first of all I have no knowledge of pygtk. But after some googling I
have found something that might help you:
http://trac.bjourne.webfactional.com/ GtkImageViewer. It also comes
with Python bindings.

For the crop functionality, check the docs:
http://trac.bjourne.webfactional.com/chrome/common/pygtkimageview-docs/
, there is a function ImageToolSelector
(http://trac.bjourne.webfactional.com/chrome/common/pygtkimageview-docs/gtkimageview.ImageToolSelector-class.html)
that can be customized to make an image cropper.

Well, I hope my little finding can help.

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


RPC Client acts like a server

2008-07-14 Thread Utku Altinkaya
Hello,

I need a client that connects to the server and answers remote calls.
Is there a way to dot that using sandart xmlrpclib ? Currently I am
using Remote Python Call library, but looking for alternative
solutions as well.

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


Do we have perl's Data::Dumper equivalent in Python??

2008-07-14 Thread srinivasan srinivas
Thanks,
Srini


  Bollywood, fun, friendship, sports and more. You name it, we have it on 
http://in.promos.yahoo.com/groups/bestofyahoo/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Need help in writing up a Python Syntax checker

2008-07-14 Thread Kay Schluehr
On 14 Jul., 08:22, Kinokunya <[EMAIL PROTECTED]> wrote:
> Hi guys,
>
> My group and I will be working on our final year project, the scope to
> do a program/web-based application similar areas of functionalities
> like the PyLint and PyChecker; a Python syntax checker. We have no
> Python background, equipped only with some knowledge of Java and Dot
> net.

Python doesn't need a syntax checker. Syntax is checked by the parser
and the parser is exposed to the user by means of the parser module.
What you probably mean are *semantical* checks which are typical for
compilers: e.g. whether names are used with prior assignments of
values that cause runtime exceptions. These issues are in fact covered
by PyLint and PyChecker.

> We did some research on PyLint and found out that there are 2 common
> modules that PyLint & PyChecker are using, namely logilab-astng and
> logilab-common. I'm not really sure what these 2 modules are for.
>
> Quoted from the offical site,
>
> The aim of this module (logilab-astng) is to provide a common base
> representation of python source code
>
> We're not really sure what they meant by common base representation of
> source codes.

Just switch to \Scripts\  in your Vista installation

and type `easy_install pylint`. This shall install PyLint in the
directory

   \lib\site-packages

Additionally a pylint.bat file is placed in the \Scripts
\ directory.

Type `pylint --help` and you get more information about the
functionality of PyLint.


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


Re: importing from .pyd

2008-07-14 Thread Kay Schluehr
On 14 Jul., 06:03, moijes12 <[EMAIL PROTECTED]> wrote:
> hi
>
> there is a .pyd file present in the same folder as the script abc.py
> by the name foo.pyd .I don't have foo.py .In the script abc.py I try
>
> import foo
>
> Error i get is
> ImportError: DLL load failed: The specified module could not be found.

It looks like the module that was accessed is either corrupt
( unavailable entry point ) or it contains dependencies to other
modules which are not available.

At least the latter can be checked without access to the source using
the DependencyWalker:

http://www.dependencywalker.com/

Notice that the message clearly indicates that Python found the module
but failed to load it i.e. performing a LoadLibrary() which yielded a
NULL pointer.
--
http://mail.python.org/mailman/listinfo/python-list


Re: About wmi

2008-07-14 Thread Tim Golden

Larry Bates wrote:

patrol wrote:

I want to prevent some process from running. The code is in the
following. I  encounter some unexpected troubles.
Probelm1: This program cannot terminate "scrcons.exe" and
"FNPLicensingService.exe",which are system processes.
Problem2:After a while, this program will abort by error
  File "C:\Python25\lib\wmi.py", line 397, in __call__
handle_com_error (error_info)
  File "C:\Python25\lib\wmi.py", line 190, in handle_com_error raise
x_wmi, "\n".join (exception_string)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xb7 in position
14: ordinal not in range(128)


[... snip code ...]

You should probably post this to comp.python.windows.  Tim Golden 
(author of WMI interface) monitors that list religously (thanks Tim).



Actually, I follow this one pretty much, too. I've just been a bit busy
these last few days. And still am, so this answer will be short :)


1) I'm not sure if WMI can be forced to close down system processes,
but if it can it's probably by means of specifying one or more
privileges when you connect. Try looking in the WMI newsgroups
for a more general (non-Python) answer to this and I'll happily
explain how to apply it in a Python context.

2) I can't quite see from this traceback where the problem
arises. Have you snipped the traceback at all, or was that
all there was? Can you narrow the thing down to a short
snippet of code which I'm likely to be able to run independently,
please?

Sorry for the haste.

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


a module.pth question

2008-07-14 Thread oyster
My py24 is installed in h:\python24
I installed pyglet(http://pyglet.org/) in
H:\pure_pylib\Multimedia\pyglet-1.0\, if I do
[code]
>>> import sys
>>> sys.path.append(r'H:\pure_pylib\Multimedia\pyglet-1.0')
>>> import pyglet
[/code]
it is ok.

but if I created h:\pure_pylib\pyglet.pth file, which containts
[code]
Multimedia\pyglet-1.0
[/code]

then
[code]
>>> import sys
>>> sys.path.append(r'h:\pure_pylib')
>>> import pyglet
Traceback (most recent call last):
  File "", line 1, in ?
ImportError: No module named pyglet
>>>
[/code]

what is wrong with it? and How to fix it? thanks in advance
--
http://mail.python.org/mailman/listinfo/python-list


Re: Dictionary bidirectional

2008-07-14 Thread bearophileHUGS
Larry Bates:
> The only case where it would be faster would be if most of the keys were NOT 
> in
> the dictionary (rather odd use case).  Otherwise I believe you will find the
> first way quicker as the exceptions are infrequent.

I have written a small benchmark:

from random import shuffle

def test1(data, to_delete):
for item in to_delete:
try:
del data[item]
except KeyError:
pass

def test2(data, to_delete):
for item in to_delete:
if item in data:
del data[item]

N = 100
M = 2 * N

data = dict.fromkeys(xrange(N), 0)
to_delete = range(M)
shuffle(to_delete)

from timeit import default_timer as clock
t = clock()
#test1(data, to_delete) # 2.4 s
test2(data, to_delete) # 0.8 s
print round(clock() - t, 2), "s"

It creates a dictionary of the first million integers, and then tries
to delete the first two million of integers. So about 1/2 numbers are
present to be deleted. In this situation the version with the try-
except seems about 3 times slower than the other.

Bye,
bearophile
--
http://mail.python.org/mailman/listinfo/python-list


Re: Dictionary bidirectional

2008-07-14 Thread Kless
Akathorn Greyhat sent me by email the next solution, which althought
isn't generic it works well:

-
You could make your own class for that, maybe something like


#

class MyCoolDictionary(dict):
def __init__(self, *args, **kargs):
dict.__init__(self, *args, **kargs)

def __getitem__(self, item):
try:
return dict.__getitem__(self, item)

except KeyError:
keys=[]
for i in dictio.keys():
if dictio[i]==item:
keys.append(i)
return keys

dictio=MyCoolDictionary({"a" : 1, "b" : 2, "c" : 2})
print dictio["a"]
print dictio["b"]
print dictio[1]
print dictio[2]
#

The output of this code is:
1
2
['a']
['c', 'b']

Note that it isn't finish, maybe you'll need to make some kind of test
before adding a new value because with this code one value can have
multiple keys, and I have fixed it by returning a list of keys instead
a single value. It's up to you =)

I'm sorry of my poor english =(

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


Re: Dictionary bidirectional

2008-07-14 Thread Impotent Verse
If keys and values are unique you could do this...

--

# Left  : Right
roman = { "One" : "I",
  "Two" : "II",
  "Three"   : "III",
  "Four": "IV",
  "Five": "V",
  "Six" : "VI",
  "Seven"   : "VII",
  "Eight"   : "VIII",
  "Nine": "IX",
  "Ten" : "X" }

left, right = zip( *roman.items() )
left = list(left)
right = list(right)

print left[ right.index("VIII") ]

--

... result is "Eight".

Hmmm! zip returns tuples, which need to be turned into lists to do
much with. Maybe not the best solution in this case.

Verse.

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


Python beginner, unicode encode/decode Q

2008-07-14 Thread anonymous
1 Objective to write little programs to help me learn German.  See code
after numbered comments. //Thanks in advance for any direction or
suggestions.

tk

2  Want keyboard answer input, for example:  
 
answer_str  = raw_input(' Enter answer > ') Herr  Üü

[ I keyboard in the following characters Herr Üü ]
print answer_str
Output on screen is > Herr Üü

3   history 1 and 2  code run interactively under Debian Linux Python
2.4 and interactively under windows98, first edition IDLE, Python 2.3.5
and it works.

4  history 3 and 4 code run from within a .py file produce different
output from example in book.
 
5 want to operate under Debian Linux but because the program failed
under Linux when I tried to run the code from a file in Linux Python, I
thougt I should fire up the win98 Idle/python program and try it to see
if ran there but it failed, too from within a file.

6 The sample code is from page 108-109 of:   "Python for Dummies"
  It says in the book:  "Python's file objects and StringIO objects
don't support raw Unicode; the usual workaround is to encode Unicode as
UTF-8 before saving it to a file or stringIO object.   
The sample code from the book is French as indicate here but trying
German produces the same result.

7 I have searched the net under all the keywords but this is as close as
I get to accomplishing my task.  I suspect I may not be understanding: 
StringIO objects don't support raw Unicode, but I don't know.


#_*_ coding: utf-8 _*_

# code run under linux debian  interactively from a terminal and works 

print " u'Libert\u00e9' "

# y = raw_input('Enter >')  commented out

y = u'Lbert\u00e9'
y.encode('utf-8')
q = y.encode('utf-8')
q.decode('utf-8')
print q.decode('utf-8')

history 1 works and here is the screen copy of interactive

 >>> y = raw_input ('>')
 >Libert\xc3\xa9
 >>> q = 'Libert\xc3\xa9'
 >>> q.decode('utf-8')
u'Libert\xe9'
 >>> print q
Liberté
 >>>

[  screen output is next line ]

Lberté



history 2 
# code run under win98, first edition, within IDLE interactively and
succeeded in produce correct results. 


# y = raw_input('Enter >')  commented out

y = u'Lbert\u00e9'
y.encode('utf-8')
q = y.encode('utf-8')
q.decode('utf-8')
print q.decode('utf-8')

history 1 works and here is the screen copy of interactive

 >>> y = raw_input ('>')
 >Libert\xc3\xa9
 >>> q = 'Libert\xc3\xa9'
 >>> q.decode('utf-8')
u'Libert\xe9'
 >>> print q
Liberté
 >>>

[  screen output is next line ]

Lberté




# history 3

# this code is run from within idle on win98 and inside a python file.  
#  The code DOES NOT produce the proper outout. 

#_*_ coding: utf-8 _*_

# print "u'Libert\u00e9'"  printed to screen

y = raw_input('Enter >') 

# y = u'Lbert\u00e9' commented out
 
y.encode('utf-8')
q = y.encode('utf-8')
q.decode('utf-8')
print q.decode('utf-8')

# output is  on the lines  below was produced on the screen after run

enter u'Libert\u00e9' on screen to copy into into y string 
Enter >u'Libert\u00e9'

u'Libert\u00e9'

The code DOES NOT produce Liberté but instead produce u'Libert\u00e9'

# history 4

# this code is run from within terminal on Debian linux   inside a
python file.  
# The code does not produce proper outout but produces the same output
as run on
# windows. 

#_*_ coding: utf-8 _*_

print "u'Libert\u00e9'"  printed to screen

y = raw_input('Enter >') 

# y = u'Lbert\u00e9' commented out

y.encode('utf-8')
q = y.encode('utf-8')
q.decode('utf-8')
print q.decode('utf-8')

# output is  on the lines  below was produced on the screen after run

enter u'Libert\u00e9' on screen to copy into into y string 
Enter >u'Libert\u00e9'
u'Libert\u00e9'

The code DID NOT produce Liberté but instead produce u'Libert\u00e9'
--
http://mail.python.org/mailman/listinfo/python-list


BootCampArama Final Reminder

2008-07-14 Thread Chris Calloway
Final reminder, we're in the last two weeks of open registration for  
PyCamp, Plone Boot Camp, and Advanced Plone Boot Camp:


http://trizpug.org/boot-camp/2008/

Registration is now open for:

PyCamp: Python Boot Camp, August 4 - 8

Plone Boot Camp: Customizing Plone, July 28 - August 1

Advanced Plone Boot Camp: Plone 3 Techniques, August 4 - 7

All of these take place on the campus of the University of North  
Carolina at Chapel Hill in state of the art high tech classrooms, with  
free mass transit, low-cost accommodations with free wireless, and  
convenient dining options.


Plone Boot Camp is taught by Joel Burton, twice chair of the Plone  
Foundation. Joel has logged more the 200 days at the head of Plone  
classrooms on four continents. See plonebootcamps.com for dozens of  
testimonials from Joel's students.


PyCamp is taught by Chris Calloway, facilitator for TriZPUG and  
application analyst for the Southeast Coastal Ocean Observing System.  
Chris has developed PyCamp for over 1500 hours on behalf of Python  
user groups. Early bird registration runs through June 30. So register  
today!


PyCamp is TriZPUG's Python Boot Camp, which takes a programmer  
familiar with basic programming concepts to the status of Python  
developer with one week of training. If you have previous scripting or  
programming experience and want to step into Python programming as  
quickly and painlessly as possible, this boot camp is for you. PyCamp  
is also the perfect follow-on to Plone Boot Camp: Customizing Plone  
the previous week.


At Plone Boot Camp: Customizing Plone you will learn the essentials  
you need to build your Plone site and deploy it. This course is the  
most popular in the Plone world--for a good reason: it teaches you  
practical skills in a friendly, hands-on format. This bootcamp is  
aimed at:

* people with HTML or web design experience
* people with some or no Python experience
* people with some or no Zope/Plone experience
It covers using Plone, customizing, and deploying Plone sites.

At Advanced Plone Boot Camp: Plone 3 Techniques you will learn to  
build a site using the best practices of Plone 3 as well as advance  
your skills in scripting and developing for Plone. The course covers  
the new technologies in Plone 3.0 and 3.1intended for site integrators  
and developers: our new portlet infrastructure, viewlets, versioning,  
and a friendly introduction to Zope 3 component architecture. Now,  
updated for Plone 3.1! The course is intended for people who have  
experience with the basics of Plone site development and HTML/CSS. It  
will cover what you need to know to take advantage of these new  
technologies in Plone 3.


For more information contact: [EMAIL PROTECTED]

--
Sincerely,
Chris Calloway
http://www.secoora.org
office: 332 Chapman Hall   phone: (919) 599-3530
mail: Campus Box #3300, UNC-CH, Chapel Hill, NC 27599 
--

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


Re: a module.pth question

2008-07-14 Thread Mike Driscoll
On Jul 14, 6:26 am, oyster <[EMAIL PROTECTED]> wrote:
> My py24 is installed in h:\python24
> I installed pyglet(http://pyglet.org/) in
> H:\pure_pylib\Multimedia\pyglet-1.0\, if I do
> [code]>>> import sys
> >>> sys.path.append(r'H:\pure_pylib\Multimedia\pyglet-1.0')
> >>> import pyglet
>
> [/code]
> it is ok.
>
> but if I created h:\pure_pylib\pyglet.pth file, which containts
> [code]
> Multimedia\pyglet-1.0
> [/code]
>
> then
> [code]>>> import sys
> >>> sys.path.append(r'h:\pure_pylib')
> >>> import pyglet
>
> Traceback (most recent call last):
>   File "", line 1, in ?
> ImportError: No module named pyglet
>
> [/code]
>
> what is wrong with it? and How to fix it? thanks in advance

I looked in my easy_install.pth and it looks like it should be:

.\Multimedia\pyglet-1.0

But I don't really see any reason not to do it the way you were
earlier with the full path name. Besides, you should be able to
install pyglet to your site-packages folder. Or you could use buildout
if you're just testing modules and you don't want to screw up your
namespace.

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


Re: How to package a logging.config file?

2008-07-14 Thread Vinay Sajip
On Jul 14, 1:21 am, Matthew Wilson <[EMAIL PROTECTED]> wrote:
> I'm working on a package that uses the standard libraryloggingmodule
> along with a .cfg file.
>
> In my code, I uselogging.config.fileConfig('/home/matt/mypackage/matt.cfg') 
> to load in
> theloggingconfig file.
>
> However, it seems really obvious to me that this won't work when I share
> this package with others.
>
> I can't figure out what path to use when I load my .cfg file.
>
> Any ideas?
>
> Matt

Is your package a library or an application? If it's a library, you
should avoid configuring logging using a config file - this is because
logging configuration is process-wide, and if multiple libraries use
fileConfig to configure their logging, you may get unexpected results.

If it's an application, then Larry's advice is good.

Regards,


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


Turbogear installing error.

2008-07-14 Thread CL (Ciu Loeng) Lam
HI,there:
I get the errors below when installing the Turebogear,could anyone help me ?
Thanks in advance.

error: Not a recognized archive type: c:\docume~1\admini~1\locals~1\
temp\easy_in
stall-y2znne\PasteScript-1.6.3.tar.gz
--
http://mail.python.org/mailman/listinfo/python-list

trying to use sax for a very basic first xml parser

2008-07-14 Thread manu
Hi,

I need to parse xml files for the Blender Game Engine. ATM I am trying
to get this script running in the BGE. This is my first script and I
dont have much experience programming...

import xml.sax

class PnmlHandler(xml.sax.ContentHandler):
def __init__(self):
self.inPlace=0

def startElement(self, name, attrs):
if name != "place": return
if attrs.getLength()==0: return

print 'Starting element:', name
print "attrs:", attrs.keys()
id = attrs.get("id", None)
print "id:", id

if name == "place":
self.inPlace=1

def endElement(self, name):
if name == "place":
self.inPlace=0



parser = xml.sax.make_parser()
parser.setContentHandler(PnmlHandler())
parser.parse(open("bpm.pnml","r"))

this works in the IDLE ide. Output:

Starting element: place
attrs: [u'id']
id: p9723441
Starting element: place
attrs: [u'id']
id: p26811937
Starting element: place
attrs: [u'id']
id: p24278422[/code]

but when I copy the script into blender and run it I get:

[code]Compiled with Python version 2.5.
Checking for installed Python... got it!
Traceback (most recent call last):
  File "Text", line 27, in 
  File "H:\Python25\lib\xml\sax\__init__.py", line 93, in make_parser
raise SAXReaderNotAvailable("No parsers found", None)
xml.sax._exceptions.SAXReaderNotAvailable: No parsers found[/code]

Its probably a stupid question but thanks anyway!
--
http://mail.python.org/mailman/listinfo/python-list


Re: logging via SocketHandler and TCPserver

2008-07-14 Thread Vinay Sajip
On Jul 13, 9:25 pm, Larry Bates <[EMAIL PROTECTED]> wrote:
> Every time I look at theloggingmodule (up until now) I've given up and
> continue to use my home-grown logger that I've been using for years.   I'm not
> giving up this time ;-)
>
> I find that I REALLY need to be able to monitor LOTS of running
> programs/processes and thought it would be nice to have them use 
> SocketHandlerloggingand then I would write TCPServer to accept the log 
> messages for
> real-time monitoring.  I Googled (is that now a verb?) for several hours and
> came up with some code that I've turned in to something that works, but I 
> can't
> figure out how to disconnect the server once it is connected  The goal is to 
> be
> able to start TCPServer, monitor the log messages sent via SocketHandler 
> logger,
> disconnect, and move to the next application.  Eventually I would like to 
> wrap a
> GUI around all of this for monitoring a complex web application.
>
> Everything works, it just appears that I get into the while loop in
> LogRecordStreamHandler.handle and it never breaks out (until I kill the 
> client).
> I can't seem to do anything with the LogRecordSocketReceiver.abort attribute 
> to
> make it quit.
>
> I'm sure it is something simple (stupid?), but I've spent about 4 hours and 
> I'm
> not getting anywhere.
>
> Thanks in advance for any assistance.
>
> Regards,
> Larry
>
> Below is my code:
>
> import sys
> import time
> importlogging
>
> if sys.argv[1] == 'client':
>  importlogging.config
>
>  logging.config.fileConfig("logging.conf")
>
>  #create logger
>  logger =logging.getLogger("VESconsole")
>
>  while 1:
>  logger.debug("debug message")
>  logger.info("info message")
>  logger.warn("warn message")
>  logger.error("error message")
>  logger.critical("critical message")
>  time.sleep(2)
>
> elif sys.argv[1] == 'server':
>  import cPickle
>  importlogging.handlers
>  import SocketServer
>  import struct
>  import signal
>
>  class LogRecordStreamHandler(SocketServer.StreamRequestHandler):
>  """Handler for a streamingloggingrequest.
>
>  This basically logs the record using whateverloggingpolicy is
>  configured locally.
>  """
>
>  def handle(self):
>  """
>  Handle multiple requests - each expected to be a 4-byte length,
>  followed by the LogRecord in pickle format. Logs the record
>  according to whatever policy is configured locally.
>  """
>  while 1:
>  chunk = self.connection.recv(4)
>  if len(chunk) < 4:
>  break
>
>  slen = struct.unpack(">L", chunk)[0]
>  chunk = self.connection.recv(slen)
>  while len(chunk) < slen:
>  chunk = chunk + self.connection.recv(slen - len(chunk))
>
>  obj = self.unPickle(chunk)
>  record =logging.makeLogRecord(obj)
>  self.handleLogRecord(record)
>
>  def unPickle(self, data):
>  return cPickle.loads(data)
>
>  def handleLogRecord(self, record):
>  t = time.strftime('%a, %d %b %y %H:%M:%S',
>time.localtime(record.created))
>
>  print "%s %s" % (t, record.getMessage())
>
>  class LogRecordSocketReceiver(SocketServer.ThreadingTCPServer):
>  """simple TCP socket-basedloggingreceiver suitable for testing.
>  """
>
>  allow_reuse_address = 1
>
>  def __init__(self, host='localhost',
>   port=logging.handlers.DEFAULT_TCP_LOGGING_PORT,
>   handler=LogRecordStreamHandler):
>
>  SocketServer.ThreadingTCPServer.__init__(self,
>   (host, port),
>   handler)
>  self.abort = 0
>  self.timeout = 1
>  self.logname = None
>
>  def serve_until_stopped(self):
>  import select
>  abort = 0
>  while not abort:
>  rd, wr, ex = select.select([self.socket.fileno()],
> [], [],
> self.timeout)
>  if rd:
>  self.handle_request()
>
>  abort = self.abort
>
>  print "serve_until_stopped exiting"
>
>  #
>  # Start ThreadingTCPServer instance to accept SocketHandler log
>  # messages from client.
>  #
>  tcpserver = LogRecordSocketReceiver()
>  print "Starting ThreadingTCPServer..."
>  tcpserver.serve_until_stopped()
>
> '''
> #-logging.conf-
> [loggers]
> keys=root
>
> [handlers]
> keys=socketHandler
>
> [formatters]
> keys=simpleFormatter
>
> [logger_root]
> level=DEBUG
> handlers=soc

Re: Dictionary bidirectional

2008-07-14 Thread Akathorn Greyhat
This is a better version of the class that I sen't you, now it raises a
KeyError when you try to insert a value that is already in


class MyCoolDictionary(dict):
def __init__(self, *args, **kargs):
dict.__init__(self, *args, **kargs)

def __setitem__(self, *args, **kargs):
for i in dictio.values():
if args[0]==i or args[1]==i:
raise KeyError, 'Value already exists'

dict.__setitem__(self, *args, **kargs)

def __getitem__(self, item):
try:
return dict.__getitem__(self, item)

except KeyError:
keys=[]
for i in dictio.keys():
if dictio[i]==item:
keys.append(i)
if not keys:
raise KeyError, 'Can\'t found key or value "' + str(item) +
'"'
return keys


Feel free to change anything you want or need

Regards,
Akathorn Greyhat


2008/7/14 Kless <[EMAIL PROTECTED]>:

> I need a dictionary where get the result from a 'key' (on left), but
> also from a 'value' (on right), how to get it?
>
> I know that dictionaries aren't bidirectional, but is there any way
> without use two dictionaries?
>
>
> Thanks in advance!
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list

Re: Dictionary bidirectional

2008-07-14 Thread Gerry
If keys and values are unique, maybe just store both in the same
dictionary:

   mydict[a] = b
   mydict[b] = a

   ...

   Gerry

On Jul 14, 8:31 am, Impotent Verse <[EMAIL PROTECTED]> wrote:
> If keys and values are unique you could do this...
>
> --
>
> #         Left      : Right
> roman = { "One"     : "I",
>           "Two"     : "II",
>           "Three"   : "III",
>           "Four"    : "IV",
>           "Five"    : "V",
>           "Six"     : "VI",
>           "Seven"   : "VII",
>           "Eight"   : "VIII",
>           "Nine"    : "IX",
>           "Ten"     : "X" }
>
> left, right = zip( *roman.items() )
> left = list(left)
> right = list(right)
>
> print left[ right.index("VIII") ]
>
> --
>
> ... result is "Eight".
>
> Hmmm! zip returns tuples, which need to be turned into lists to do
> much with. Maybe not the best solution in this case.
>
> Verse.

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


Re: Beginner Question : Iterators and zip

2008-07-14 Thread moogyd
On 13 Jul, 19:49, Terry Reedy <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] wrote:
> > What is this *lis operation called? I am having trouble finding any
> > reference to it in the python docs or the book learning python.
>
> One might call this argument unpacking, but
> Language Manual / Expressions / Primaries / Calls
> simply calls it *expression syntax.
> "If the syntax *expression appears in the function call, expression must
> evaluate to a sequence. Elements from this sequence are treated as if
> they were additional positional arguments; if there are positional
> arguments x1,...,*xN* , and expression evaluates to a sequence
> y1,...,*yM*, this is equivalent to a call with M+N positional arguments
> x1,...,*xN*,*y1*,...,*yM*."
>
> See Compound Statements / Function definitions for the mirror syntax in
> definitions.
>
> tjr

Thanks,

It's starting to make sense :-)

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


new python podcast

2008-07-14 Thread [EMAIL PROTECTED]
http://www.podango.com/tag/python

I just started to play with this and I wanted to know if there is any
interest in this sort of thing now that the last (maybe I should say
most proliffic) python podcaster has stopped being active..  I would
also be intrested in knowing if there is a particular bit rate that
people are after...  first episode is an intro to the panda python
setup.. mostly from the manual..
--
http://mail.python.org/mailman/listinfo/python-list


Re: Converting from local -> UTC

2008-07-14 Thread Keith Hughitt
On Jul 12, 12:52 am, "Gabriel Genellina" <[EMAIL PROTECTED]>
wrote:
> En Fri, 11 Jul 2008 15:42:37 -0300, Keith Hughitt  
> <[EMAIL PROTECTED]> escribi�:
>
> > I am having a little trouble figuring out how to convert a python
> > datetime to UTC. I have a UTC date (e.g. 2008-07-11 00:00:00). I would
> > like to create a UTC date so that when I send it to MySQL (which
> > treats all dates at local dates by default), it will already have
> > incorporated the proper UTC offset. I've tried looking through the
> > docshttp://python.active-venture.com/lib/datetime-datetime.html), but
> > have not had any luck.
>
> You have to use a "timezone aware" datetime object. If all you want is to  
> store an UTC date, the tzinfo demo classes that you can find in the Python  
> docs at  may be enough.
> A more complete implementation is at 
>
> If you pass a "timezone aware" datetime object as a SQL parameter, the  
> database should store it correctly (but I don't have a MySQL instance at  
> hand to test it)
>
> --
> Gabriel Genellina

Thanks for advice Gabriel. I downloaded the tzinfo demo class, saved
it as
UTC.py and imported it. I'm still not exactly sure how to use it
though. It looks like
the file already creates an instance of the UTC tzinfo class (line 20:
"utc = UTC()"),
however, when I try to test it out in the interpreter, it cannot be
found. I'm new
to python, and there is probably something obvious I'm missing, but do
you have any ideas?
Here is what I'm attempting:

 output begin =

Python 2.5.2 (r252:60911, Apr 21 2008, 11:12:42)
[GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import datetime, UTC
>>> t = datetime.datetime(2008, 7, 14, 00, 00, 00, UTC())
Traceback (most recent call last):
  File "", line 1, in 
TypeError: 'module' object is not callable
>>> utc
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'utc' is not defined

>>> utc = UTC()
Traceback (most recent call last):
  File "", line 1, in 
TypeError: 'module' object is not callable
>>>

 output begin =

Any ideas?

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

screencapture with PIL question

2008-07-14 Thread greg
I am able to use the PIL module to capture a screen or specific
window.  My problem is when capturing a window (on windows XP) I can
only capture the "visible" portion of the window.  Is there any way to
capture the entire window?  specifically the scrolled portion of a
window that is not visible on the screen.

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


Is it possible to create "network conneciton" on windows system?

2008-07-14 Thread Evan
Hello,

one of my PC is window system, and in "control panel -> Network
Connections", I can see some network connections such as PPPOE or VPN
which I created by click "create a new connection".

My question is, is it possible to create a new connection by using
Python script? which means I do not want to use Window UI (via
"control panel"),  if it is possible, I can save so many time to
create various network connection when I want to do testing in the
lab.

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


Re: screencapture with PIL question

2008-07-14 Thread Matimus
On Jul 14, 8:11 am, greg <[EMAIL PROTECTED]> wrote:
> Is there any way to capture the entire window?  specifically
> the scrolled portion of a window that is _not_visible_on_the_screen_.

I don't think there is. That is why it is called a _screen_ capture.

Matt


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


Re: Do we have perl's Data::Dumper equivalent in Python??

2008-07-14 Thread oj
On Jul 14, 11:41 am, srinivasan srinivas <[EMAIL PROTECTED]>
wrote:
> Thanks,
> Srini
>
>       Bollywood, fun, friendship, sports and more. You name it, we have it 
> onhttp://in.promos.yahoo.com/groups/bestofyahoo/

You might have more luck asking for help if you explained what Perl's
Data::Dumper actually does, instead of expecting people to either just
know, or to go and look it up.

In particular, what functionality of Data::Dumper is it you are
looking for?

For a user friendly representation of a python data structure, look at
pprint:
http://docs.python.org/lib/module-pprint.html

For a string representing a data structure that can be eval'd to get
the structure back again, look at the built-in repr()

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


Re: Python beginner, unicode encode/decode Q

2008-07-14 Thread MRAB
On Jul 14, 1:51 pm, anonymous <[EMAIL PROTECTED]> wrote:
> 1 Objective to write little programs to help me learn German.  See code
> after numbered comments. //Thanks in advance for any direction or
> suggestions.
>
> tk
>
> 2  Want keyboard answer input, for example:  
>
> answer_str  = raw_input(' Enter answer > ') Herr  Üü
>
> [ I keyboard in the following characters Herr Üü ]
> print answer_str
> Output on screen is > Herr Üü
>
> 3   history 1 and 2  code run interactively under Debian Linux Python
> 2.4 and interactively under windows98, first edition IDLE, Python 2.3.5
> and it works.
>
> 4  history 3 and 4 code run from within a .py file produce different
> output from example in book.
>
> 5 want to operate under Debian Linux but because the program failed
> under Linux when I tried to run the code from a file in Linux Python, I
> thougt I should fire up the win98 Idle/python program and try it to see
> if ran there but it failed, too from within a file.
>
> 6 The sample code is from page 108-109 of:   "Python for Dummies"
>       It says in the book:  "Python's file objects and StringIO objects
> don't support raw Unicode; the usual workaround is to encode Unicode as
> UTF-8 before saving it to a file or stringIO object.  
> The sample code from the book is French as indicate here but trying
> German produces the same result.
>
> 7 I have searched the net under all the keywords but this is as close as
> I get to accomplishing my task.  I suspect I may not be understanding:
> StringIO objects don't support raw Unicode, but I don't know.
>
> #_*_ coding: utf-8 _*_
>
> # code run under linux debian  interactively from a terminal and works
>
> print " u'Libert\u00e9' "
>
> # y = raw_input('Enter >')  commented out
>
> y = u'Lbert\u00e9'
> y.encode('utf-8')
> q = y.encode('utf-8')
> q.decode('utf-8')
> print q.decode('utf-8')
>
> history 1 works and here is the screen copy of interactive
>
>  >>> y = raw_input ('>')
>  >Libert\xc3\xa9
>  >>> q = 'Libert\xc3\xa9'
>  >>> q.decode('utf-8')
> u'Libert\xe9'
>  >>> print q
> Liberté
>  >>>
>
> [  screen output is next line ]
>
> Lberté
>
> history 2
> # code run under win98, first edition, within IDLE interactively and
> succeeded in produce correct results.
>
> # y = raw_input('Enter >')  commented out
>
> y = u'Lbert\u00e9'
> y.encode('utf-8')
> q = y.encode('utf-8')
> q.decode('utf-8')
> print q.decode('utf-8')
>
> history 1 works and here is the screen copy of interactive
>
>  >>> y = raw_input ('>')
>  >Libert\xc3\xa9
>  >>> q = 'Libert\xc3\xa9'
>  >>> q.decode('utf-8')
> u'Libert\xe9'
>  >>> print q
> Liberté
>  >>>
>
> [  screen output is next line ]
>
> Lberté
>
> # history 3
>
> # this code is run from within idle on win98 and inside a python file.  
> #  The code DOES NOT produce the proper outout.
>
> #_*_ coding: utf-8 _*_
>
> # print "u'Libert\u00e9'"  printed to screen
>
> y = raw_input('Enter >')
>
> # y = u'Lbert\u00e9' commented out
>
> y.encode('utf-8')
> q = y.encode('utf-8')
> q.decode('utf-8')
> print q.decode('utf-8')
>
> # output is  on the lines  below was produced on the screen after run
>
> enter u'Libert\u00e9' on screen to copy into into y string
> Enter >u'Libert\u00e9'
>
> u'Libert\u00e9'
>
> The code DOES NOT produce Liberté but instead produce u'Libert\u00e9'
>
> # history 4
>
> # this code is run from within terminal on Debian linux   inside a
> python file.  
> # The code does not produce proper outout but produces the same output
> as run on
> # windows.
>
> #_*_ coding: utf-8 _*_
>
> print "u'Libert\u00e9'"  printed to screen
>
> y = raw_input('Enter >')
>
> # y = u'Lbert\u00e9' commented out
>
> y.encode('utf-8')
> q = y.encode('utf-8')
> q.decode('utf-8')
> print q.decode('utf-8')
>
> # output is  on the lines  below was produced on the screen after run
>
> enter u'Libert\u00e9' on screen to copy into into y string
> Enter >u'Libert\u00e9'
> u'Libert\u00e9'
>
> The code DID NOT produce Liberté but instead produce u'Libert\u00e9'

raw_input returns what you entered. You entered u'Libert\u00e9' so
that's what was printed out.

If you want to be able to enter escape sequences like \u00e9 and have
them decoded to the appropriate character then you must do something
like this:

# The code
text = raw_input('Enter >')
decoded_text = text.decode("unicode-escape")
print decoded_text


# The output
Enter >Libert\u00e9
Liberté

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


Re: subprocess module

2008-07-14 Thread Peter Otten
John Mechaniks wrote:

> On Jul 14, 12:34 pm, Peter Otten <[EMAIL PROTECTED]> wrote:
>> John Mechaniks wrote:
>> > from subprocess import call
>> > call(['ls', '-l'])
>>
>> > How do I get the result (not the exit status of the command) of "ls -
>> > l" into a variable?
>>
>> output = subprocess.Popen(["ls", "-l"],
>> stdout=subprocess.PIPE).stdout.read()

> What difference does the following code makes? What are the advantages
> of the above method over this one?

> output = subprocess.Popen(['ls', '-l'],
> stdout=subprocess.PIPE).communicate()[0]

Hm, I chose it because it looks cleaner. Looking into the source
Popen.communicate() seems to do the following:

output = p._fo_read_no_intr(p.stdout)  
p.wait()

So there are two differences in this case

- communicate() waits for the subprocess to terminate.
- stdout.read() is retried if an EINTR occurs (Not sure when this would
happen).

> Also could someone show an example of using the optional input
> argument for communicate()

http://blog.doughellmann.com/2007/07/pymotw-subprocess.html

I didn't read it myself, but Doug Hellmann's articles are usually quite
good.

Peter 

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

About the slot declaration decorator in PyQt4

2008-07-14 Thread Bighead
I remember when I did UI Design in PyQt4 for the first time, I found a
manual. In it, no "connect" was used. Instead, an OO approach is
applied, new UI classes inherit from old ones, and all the slot
functions are automatically connected to some signals, using a
decorator. In the __init__ function of our newly written class,
"connect" is not invoked.

I like this style...

Unfortunately, I cannot find that manual now So anyone have read
something like that before? If so, could you tell me where can I find
that manual please? Thank you :)
--
http://mail.python.org/mailman/listinfo/python-list


Using McMillan Installer, PyInstall or py2exe cross-platform?

2008-07-14 Thread Hartmut Goebel

Hi,

has anybody used McMillan Installer, PyInstall or py2exe cross-platform?

I have a Windows partition with Python installed there, so this would 
"only" required working on a different directory and for a different OS.
Since I'm working on Linux, it's awful to boot Windows each time I want 
to build a new release.


Any hint in this area?

--
Schönen Gruß - Regards
Hartmut Goebel

Goebel Consult
Spezialist für IT-Sicherheit in komplexen Umgebungen
http://www.goebel-consult.de
--
http://mail.python.org/mailman/listinfo/python-list


Re: screencapture with PIL question

2008-07-14 Thread Casey
On Jul 14, 11:11 am, greg <[EMAIL PROTECTED]> wrote:
> I am able to use the PIL module to capture a screen or specific
> window.  My problem is when capturing a window (on windows XP) I can
> only capture the "visible" portion of the window.  Is there any way to
> capture the entire window?  specifically the scrolled portion of a
> window that is not visible on the screen.
>
> Thanks for any help.

You might want to check out
http://wiki.wxpython.org/index.cgi/WorkingWithImages#head-e962ac20ad55c25bc069523cd7e0246068110233
.
wxPython supports different types of device contexts including
wx.ClientDC (the client area of a window), wx.WindowDC (a specific
window), and wx.ScreenDC (anywhere or everywhere on the underlying
screen).
--
http://mail.python.org/mailman/listinfo/python-list


Re: Determining when a file has finished copying

2008-07-14 Thread Ethan Furman

Sean DiZazzo wrote:

On Jul 9, 5:34 pm, keith <[EMAIL PROTECTED]> wrote:


-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1



Ethan Furman wrote:


writeson wrote:


Guys,



Thanks for your replies, they are helpful. I should have included in
my initial question that I don't have as much control over the program
that writes (pgm-W) as I'd like. Otherwise, the write to a different
filename and then rename solution would work great. There's no way to
tell from the os.stat() methods to tell when the file is finished
being copied? I ran some test programs, one of which continously
copies big files from one directory to another, and another that
continously does a glob.glob("*.pdf") on those files and looks at the
st_atime and st_mtime parts of the return value of os.stat(filename).


From that experiment it looks like st_atime and st_mtime equal each


other until the file has finished being copied. Nothing in the
documentation about st_atime or st_mtime leads me to think this is
true, it's just my observations about the two test programs I've
described.



Any thoughts? Thanks!
Doug



The solution my team has used is to monitor the file size.  If the file
has stopped growing for x amount of time (we use 45 seconds) the file is
done copying.  Not elegant, but it works.
--
Ethan


Also I think that matching the md5sums may work.  Just set up so that it
checks the copy's md5sum every couple of seconds (or whatever time
interval you want) and matches against the original's.  When they match
copying's done. I haven't actually tried this but think it may work.
Any more experienced programmers out there let me know if this is
unworkable please.
K
-BEGIN PGP SIGNATURE-
Version: GnuPG v1.4.6 (GNU/Linux)
Comment: Using GnuPG with Mozilla -http://enigmail.mozdev.org

iD8DBQFIdVkX8vmNfzrLpqoRAsJ2AKCp8wMz93Vz8y9K+MDSP33kH/WHngCgl/wM
qTFBfyIEGhu/dNSQzeRrwYQ=
=Xvjq
-END PGP SIGNATURE-



I use a combination of both the os.stat() on filesize, and md5.
Checking md5s works, but it can take a long time on big files.  To fix
that, I wrote a simple  sparse md5 sum generator.  It takes a small
number bytes from various areas of the file, and creates an md5 by
combining all the sections. This is, in fact, the only solution I have
come up with for watching a folder for windows copys.

The filesize solution doesn't work when a user copies into the watch
folder using drag and drop on Windows because it allocates all the
attributes of the file before any data is written.  The filesize will
always show the full size of the file.

~Sean


Good info, Sean, thanks.  One more option may be to attempt to rename 
the file -- if it's still open for copying, that will fail; success 
indicates the copy is done.  Of course, as Larry Bates pointed out, this 
could fail if the copy is followed by a re-open and appending. 
Hopefully that's not an issue for the OP.

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


Re: Using McMillan Installer, PyInstall or py2exe cross-platform?

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

> has anybody used McMillan Installer, PyInstall or py2exe cross-platform?

I know that py2exe doesn't work "cross-platform".  I'd be very
surprised if the the others do.

> I have a Windows partition with Python installed there, so
> this would "only" required working on a different directory
> and for a different OS. Since I'm working on Linux, it's awful
> to boot Windows each time I want to build a new release.
>
> Any hint in this area?

You can run Windows on a VM like Qemu and use that to build
distribution packages.  You still have to "boot windows", but
at least you don't have to shut down Linux...

-- 
Grant Edwards   grante Yow! Here I am at the flea
  at   market but nobody is buying
   visi.commy urine sample bottles ...
--
http://mail.python.org/mailman/listinfo/python-list


Re: Determining when a file has finished copying

2008-07-14 Thread Michiel Overtoom
Ethan wrote:

> One more option may be to attempt to rename 
> the file -- if it's still open for copying, that will fail; 
> success indicates the copy is done.  

Caveat -- this is dependent on the operating system!

Windows will indeed not allow you to rename or delete a file that's still
open for writing by another process, at least not when the file is on a
local NTFS filesystem, but don't count on this on Unix or networked
filesystems.  There you can easily rename, move or delete a filename from a
directory whilst other processes still write to it. After all, a directory
is nothing else than a list of filenames which map to certain inodes.

Greetings,

-- 
"The ability of the OSS process to collect and harness
the collective IQ of thousands of individuals across
the Internet is simply amazing." - Vinod Vallopillil
http://www.catb.org/~esr/halloween/halloween4.html

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


Re: Moving to functional programming

2008-07-14 Thread [EMAIL PROTECTED]
On 14 juil, 11:51, James Fassett <[EMAIL PROTECTED]> wrote:
> On Jul 12, 12:18 am, George Sakkis <[EMAIL PROTECTED]> wrote:
>
> > It relies on positional arguments, tuple unpacking and
> > the signature of zip(),
>
> It moreso relies on the fact that:
>
> >>> t1 = (0,1,2,3)
> >>> t2 = (7,6,5,4)
> >>> [t1, t2] == zip(*zip(t1, t2))
>
> True
>
> This is mathematically true given the definition of zip. To me that is
> very functional. Basically, unpacking a pair list into zip is the
> canonical definition of unzipping the list (which is exactly my
> intention).
>
> > Second, it is less readable,
>
> For a Python programmer - you are correct. For someone familiar with
> the use of zip (as described above) - I wonder. Since I am new to this
> I can't say for sure. If I posted the same code to a Haskell list or a
> ML list would their opinion be the same?

You might find interesting than Python's list comprehensions were
stolen from Haskell then !-)

> > robust and efficient than the list comprehension.
>
> I don't know the internals of how the Python interpreter treats list
> comprehensions

According to a post on the pypy team's blog, mostly as sugar candy for
the procedural version (IOW: the generated byte-code will be roughly
equivalent).

> and zip but it seems reasonable to assume an extra list
> is created for the zip approach.
>
> However, in the limited functional code I have seen this is actually a
> common practice. I would suppose in languages with lazy evaluation
> this isn't a problem - but in Python it would be.

Python has some kind of lazy evaluation too - look for yield,
generator expressions, iterators, and the itertools package.

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


RE: How to package a logging.config file?

2008-07-14 Thread Younger Wang
I had the similar question and my solution is: 

default_config = os.path.join(os.getcwd(), "log.config")

def get_logger(name, config_file=None):
if config_file:
logging.config.fileConfig(config_file)
else:
logging.basicConfig(level=logging.INFO,
format='%(levelname)s %(module)s:%(lineno)d:
%(message)s')

return logging.getLogger(name)

I had to make this helper function because calling logging.getLogger
will fail in an exception without configuring logging module. I wish it
is not like that.

BR
Younger Wang
-Original Message-
From: [EMAIL PROTECTED]
[mailto:[EMAIL PROTECTED] On
Behalf Of Matthew Wilson
Sent: Monday, July 14, 2008 8:21 AM
To: python-list@python.org
Subject: How to package a logging.config file?

I'm working on a package that uses the standard library logging module
along with a .cfg file.

In my code, I use
logging.config.fileConfig('/home/matt/mypackage/matt.cfg') to load in
the logging config file.

However, it seems really obvious to me that this won't work when I share
this package with others.

I can't figure out what path to use when I load my .cfg file.

Any ideas?

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


Re: iterator clone

2008-07-14 Thread [EMAIL PROTECTED]
On 13 juil, 12:05, Yosifov Pavel <[EMAIL PROTECTED]> wrote:
(snip)

> def cloneiter( it ):
> """return (clonable,clone)"""
> return tee(it)

This might as well be written as

cloneiter  = tee

Or yet better, just remove the above code and s/cloneiter/tee/g in the
remaining...

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


Unicode confusion

2008-07-14 Thread Tim Cook
Hi All,

I'm not clear on how to use the unicode module.

I need to be able to use certain characters such as the degree symbol
and the mu symbol, i.e.:
units = <"°">

if I say units=unicode("°").  I get 
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position 0:
ordinal not in range(128)

If I try x=unicode.decode(x,'utf-8'). I get
TypeError: descriptor 'decode' requires a 'unicode' object but received
a 'str'

What is the correct way to interpret these symbols that come to me as a
string?

Thanks,
Tim





-- 
**
Join the OSHIP project.  It is the standards based, open source
healthcare application platform in Python.
Home page: https://launchpad.net/oship/ 
Wiki: http://www.openehr.org/wiki/display/dev/Python+developer%27s+page 
**


signature.asc
Description: This is a digitally signed message part
--
http://mail.python.org/mailman/listinfo/python-list

Re: while var, but var ==16 != true

2008-07-14 Thread [EMAIL PROTECTED]
On 14 juil, 07:32, Tim Roberts <[EMAIL PROTECTED]> wrote:
(snip)
> Everything has a boolean value in
> Python.  0, None, False, '' (empty string), [] (empty list), () (empty
> tuple), and {} (empty dictionary) all have a False value.  Everything else
> has a True value.

Unless the author of the class specified it otherwise (implementing
the appropriate __magic_method__).

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


Re: subprocess module

2008-07-14 Thread John Mechaniks
On Jul 14, 7:44 pm, Peter Otten <[EMAIL PROTECTED]> wrote:
> John Mechaniks wrote:
> > On Jul 14, 12:34 pm, Peter Otten <[EMAIL PROTECTED]> wrote:
> >> John Mechaniks wrote:
> >> > from subprocess import call
> >> > call(['ls', '-l'])
>
> >> > How do I get the result (not the exit status of the command) of "ls -
> >> > l" into a variable?
>
> >> output = subprocess.Popen(["ls", "-l"],
> >> stdout=subprocess.PIPE).stdout.read()
> > What difference does the following code makes? What are the advantages
> > of the above method over this one?
> > output = subprocess.Popen(['ls', '-l'],
> > stdout=subprocess.PIPE).communicate()[0]
>
> Hm, I chose it because it looks cleaner. Looking into the source
> Popen.communicate() seems to do the following:
>
> output = p._fo_read_no_intr(p.stdout)  
> p.wait()            
>
> So there are two differences in this case
>
> - communicate() waits for the subprocess to terminate.
> - stdout.read() is retried if an EINTR occurs (Not sure when this would
> happen).
>
> > Also could someone show an example of using the optional input
> > argument for communicate()
>
> http://blog.doughellmann.com/2007/07/pymotw-subprocess.html
>
> I didn't read it myself, but Doug Hellmann's articles are usually quite
> good.
>
> Peter

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


Re: Unicode confusion

2008-07-14 Thread Jerry Hill
On Mon, Jul 14, 2008 at 12:40 PM, Tim Cook <[EMAIL PROTECTED]> wrote:
> if I say units=unicode("°").  I get
> UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position 0:
> ordinal not in range(128)
>
> If I try x=unicode.decode(x,'utf-8'). I get
> TypeError: descriptor 'decode' requires a 'unicode' object but received
> a 'str'
>
> What is the correct way to interpret these symbols that come to me as a
> string?

Part of it depends on where you're getting them from.  If they are in
your source code, just define them like this:

>>> units = u"°"
>>> print units
°
>>> print repr(units)
u'\xb0'

If they're coming from an external source, you have to know the
encoding they're being sent in.  Then you can decode them into
unicode, like this:

>>> units = "°"
>>> unicode_units = units.decode('Latin-1')
>>> print repr(unicode_units)
u'\xb0'
>>> print unicode_units
°

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

Re: Building a Python app with Mozilla

2008-07-14 Thread Trent Mick

Brian Quinlan wrote:
Most application logic in Komodo is implemented in Python, using the 
PyXPCOM bindings. The UI is implemented using XUL and JavaScript. The 
editor is Scintilla (C++).


../Komodo Edit.app/Contents/MacOS % find . -name "*.py" | xargs wc
...
...
126392  456858 4949602 total

This doesn't include the python code in the Python libraries themselves.


An interesting breakdown here:
  http://www.ohloh.net/projects/10861/analyses/latest

happybrowndog wrote:
> Is that why Komodo is so damned slow

Probably not, no. Pinpointing the reasons for slowness is often a lot 
more complicated. Particular slow points in any app/module -- especially 
pathologically slow things -- are more often algoritmic than a function 
of the language used. Komodo's use of Python is perhaps partially 
responsible for a slower startup time than might otherwise be possible 
-- but otherwise my experience in Komodo perf work has been algorithmic 
issues. Also, if Komodo hadn't been using Python for application logic 
since day one we probably wouldn't be much further than Notepad right 
now. :)


Cheers,
Trent (komodo developer)

--
Trent Mick
trentm at activestate.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: subprocess module

2008-07-14 Thread Sebastian "lunar" Wiesner
Peter Otten <[EMAIL PROTECTED]>:

> - communicate() waits for the subprocess to terminate.
> - stdout.read() is retried if an EINTR occurs (Not sure when this would
> happen).

EINTR happens, if the "read" syscall is interrupted by a signal handler. 
For instance, if a daemon handles SIGUSR to re-read its configuration, and
the user issues SIGUSR in exactly that very moment, the daemon wants to
read from a pipe, the read attempt would fail with EINTR.  Shouldn't happen
that often ...

-- 
Freedom is always the freedom of dissenters.
  (Rosa Luxemburg)
--
http://mail.python.org/mailman/listinfo/python-list


Re: About the slot declaration decorator in PyQt4

2008-07-14 Thread Sebastian "lunar" Wiesner
Bighead <[EMAIL PROTECTED]>:

> I remember when I did UI Design in PyQt4 for the first time, I found a
> manual. In it, no "connect" was used. Instead, an OO approach is
> applied, new UI classes inherit from old ones, and all the slot
> functions are automatically connected to some signals, using a
> decorator. In the __init__ function of our newly written class,
> "connect" is not invoked.
> 
> I like this style...
> 
> Unfortunately, I cannot find that manual now So anyone have read
> something like that before? If so, could you tell me where can I find
> that manual please? Thank you :)

I guess, you're referring to QtCore.pyqtSignature and
QtCore.QMetaObject.connectSlotsByName.

See
http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/pyqt4ref.html#the-qtcore-pyqtsignature-decorator

Especially "3.7.3   Connecting Slots By Name"

Hih 

-- 
Freedom is always the freedom of dissenters.
  (Rosa Luxemburg)
--
http://mail.python.org/mailman/listinfo/python-list


Re: trying to use sax for a very basic first xml parser

2008-07-14 Thread Miki
Hello,

> but when I copy the script into blender and run it I get:
>
> [code]Compiled with Python version 2.5.
> Checking for installed Python... got it!
> Traceback (most recent call last):
>   File "Text", line 27, in 
>   File "H:\Python25\lib\xml\sax\__init__.py", line 93, in make_parser
>     raise SAXReaderNotAvailable("No parsers found", None)
> xml.sax._exceptions.SAXReaderNotAvailable: No parsers found[/code]
Python is using an external library for SAX (expat IIRC).
I *guess* the Python that comes with Blender don't have this library.

> Its probably a stupid question but thanks anyway!
He who asks is a fool for five minutes, but he who does not ask
remains a fool forever.
- Chinese Proverb

HTH,
--
Miki <[EMAIL PROTECTED]>
http://pythonwise.blogspot.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: Moving to functional programming

2008-07-14 Thread Terry Reedy



James Fassett wrote:
 ...

robust and efficient than the list comprehension.


I don't know the internals of how the Python interpreter treats list
comprehensions and zip but it seems reasonable to assume an extra list
is created for the zip approach.


Minor times differences between this and that way of writing things tend 
to be version and even system dependent.  In 3.0, for instance, zip 
produces an iterator, not a list.  So it will be faster.  On the other 
hand, list comprehensions will be a bit slower to fix what many, 
including Guido, consider to be a slight design bug.


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


Re: trying to use sax for a very basic first xml parser

2008-07-14 Thread manu
On Jul 14, 8:14 pm, Miki <[EMAIL PROTECTED]> wrote:


> Python is using an external library for SAX (expat IIRC).
> I *guess* the Python that comes with Blender don't have this library.
>
I don't know... I didnt install any external libraries for sax. I
think python comes with a standard sax library.
And before I had python installed Blender said at startup:
"Compiled with Python version 2.5.
Checking for installed Python... No installed Python found.
Some scripts will not run. Continuing happily"

After installing Python 2.5.2 it now says:
"Compiled with Python version 2.5.
Checking for installed Python... got it!"
So I think it is using the installed Python.

Could it be that I have to install the same python version Blender was
compiled with?
--
http://mail.python.org/mailman/listinfo/python-list


Re: while var, but var ==16 != true

2008-07-14 Thread Jeffrey Froman
Tim Roberts wrote:

> Everything has a boolean value in
> Python.  0, None, False, '' (empty string), [] (empty list), () (empty
> tuple), and {} (empty dictionary) all have a False value.  Everything else
> has a True value.

Empty set objects also evaluate as false in a boolean context.


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

new itertools functions in Python 2.6

2008-07-14 Thread Mensanator
With the new functions added to itertools in Python 2.6,
I can finally get rid of this monstrosity:

def ooloop6(a, n, perm=True, repl=True):
  if (not repl) and (n>len(a)): return
  r0 = range(n)
  r1 = r0[1:]
  if perm and repl:  # ok
v = ','.join(['c%s' % i for i in r0])
f = ' '.join(['for c%s in a' % i for i in r0])
e = ''.join(["p = [''.join((",v,")) ",f,"]"])
exec e
return p
  if (not perm) and repl:# ok
v = ','.join(['c%s' % i for i in r0])
f = ' '.join(['for c%s in a' % i for i in r0])
i = ' and '.join(['(c%s>=c%s)' % (j,j-1) for j in r1])
e = ''.join(["p = [''.join((",v,")) ",f," if ",i,"]"])
exec e
return p
  if perm and (not repl):# ok
v = ','.join(['c%s' % i for i in r0])
f = ' '.join(['for c%s in a' % i for i in r0])
i = ' and '.join([' and '.join(['(c%s!=c%s)' % (j,k) for k in
range(j)]) for j in r1])
e = ''.join(["p = [''.join((",v,")) ",f," if ",i,"]"])
exec e
return p
  if (not perm) and (not repl):  # ok
v = ','.join(['c%s' % i for i in r0])
f = ' '.join(['for c%s in a' % i for i in r0])
i = ' and '.join(['(c%s>c%s)' % (j,j-1) for j in r1])
e = ''.join(["p = [''.join((",v,")) ",f," if ",i,"]"])
exec e
return p

If I use a single iterable with the repeat option,
the Carteisan Product will give me Permutaions With Replacement.

from itertools import *
from math import factorial as fac

s = 'abcde'
m = len(s)
n = 3

print 'For %d letters (%s) taken %d at a time:' % (m,s,n)
print ''

### Permutations with replacement m**n
###
print 'Permutations with replacement'
print '-'
p = [i for i in product('abcde',repeat=3)]
for i in p:
  print ''.join(i),
print
print
print 'actual words: %dm**n words: %d' % (len(p),m**n)
print

##  For 5 letters (abcde) taken 3 at a time:
##  
##  Permutations with replacement
##  -
##  aaa aab aac aad aae aba abb abc abd abe aca acb
##  acc acd ace ada adb adc add ade aea aeb aec aed
##  aee baa bab bac bad bae bba bbb bbc bbd bbe bca
##  bcb bcc bcd bce bda bdb bdc bdd bde bea beb bec
##  bed bee caa cab cac cad cae cba cbb cbc cbd cbe
##  cca ccb ccc ccd cce cda cdb cdc cdd cde cea ceb
##  cec ced cee daa dab dac dad dae dba dbb dbc dbd
##  dbe dca dcb dcc dcd dce dda ddb ddc ddd dde dea
##  deb dec ded dee eaa eab eac ead eae eba ebb ebc
##  ebd ebe eca ecb ecc ecd ece eda edb edc edd ede
##  eea eeb eec eed eee
##
##  actual words: 125m**n words: 125


So what does "permutaions" mean in itertools?
It actually means Permutions Without Replacement.

### Permutations without replacement m!/(m-n)!
###
print 'Permutations without replacement'
print ''
p = [i for i in permutations('abcde',3)]
for i in p:
  print ''.join(i),
print
print
print 'actual words: %dm!/(m-n)! words: %d' % (len(p),fac(m)/fac(m-
n))
print

##  Permutations without replacement
##  
##  abc abd abe acb acd ace adb adc ade aeb aec aed
##  bac bad bae bca bcd bce bda bdc bde bea bec bed
##  cab cad cae cba cbd cbe cda cdb cde cea ceb ced
##  dab dac dae dba dbc dbe dca dcb dce dea deb dec
##  eab eac ead eba ebc ebd eca ecb ecd eda edb edc
##
##  actual words: 60m!/(m-n)! words: 60


Not surprisingly, "combinations" actually means
Combinations Without Replacement.

### Combinations without replacement m!/(n!(m-n)!)
###
print 'Combinations without replacement'
print ''
p = [i for i in combinations('abcde',3)]
for i in p:
  print ''.join(i),
print
print
print 'actual words: %dm!/(n!(m-n)!) words: %d' % (len(p),fac(m)/
(fac(n)*factorial(m-n)))
print

##  Combinations without replacement
##  
##  abc abd abe acd ace ade bcd bce bde cde
##
##  actual words: 10m!/(n!(m-n)!) words: 10


Hmm...that's only three subsets of the Cartesian Product.
No Combinations With Replacement.

Although you can always filter the Cartesian Product to
get a subset.

# Combinations with replacement (m+n-1)!/(n!(m-1)!)
#
print 'Combinations with replacement'
print '-'
p = [i for i in ifilter(lambda x:
list(x)==sorted(x),product('abcde',repeat=3))]
for i in p:
  print ''.join(i),
print
print
print 'actual words: %d(m+n-1)!/(n!(m-1)!) words: %d' %
(len(p),fac(m+n-1)/(fac(n)*fac(m-1)))
print

##  Combinations with replacement
##  -
##  aaa aab aac aad aae abb abc abd abe acc acd ace
##  add ade aee bbb bbc bbd bbe bcc bcd bce bdd bde
##  bee ccc ccd cce cdd cde cee ddd dde dee eee
##
##  actual words: 35(m+n-1)!/(n!(m-1)!) words: 35


Although it works, it's somewhat slow as we have to iterate
over the entire Cartesian Product and the filter list(x)==sorted(x)
has got to be expensive (it's slower than the nested loop al

Re: Problems Returning an HTTP 200 Ok Message

2008-07-14 Thread samwyse
On Jul 10, 4:10 pm, Guy Davidson <[EMAIL PROTECTED]> wrote:

> I try to send the following message, using the socket.send() command:
>
> 'HTTP/1.1 200 OK\r\nDate: Thu, 10 July 2008 14:07:50 GMT\r\nServer:
> Apache/2.2.8 (Fedora)\r\nX-Powered-By: PHP/5.2.4\r\nContent-Length: 4\r
> \nConnection: close\r\nContent-Type: text/html; charset=UTF-8\r\n\r
> \n[0]\n'
>
> However, when I snoop on the packets in wireshark, here's what I see:
>
> HTTP/1.1 200 Ok:
>
> HTTP/1.1 200 OK
> Date: Wed, 09 July 2008 14:55:50 GMT
> Server: Apache/2.2.8 (Fedora)
> X-Powered-By:
>
> Continuation or non-HTTP traffic:
>
> PHP/5.2.4
> Content-Length: 4
> Connection: close
> Content-Type: text/html; charset=UTF-8
>
> [0]
>
> It splits into two packages, which the meter can't read, and the
> communication breaks down there.

OK, it looks like a single TCP segment is being sent by you (which is
consistent with only one socket.send() command being needed), but
something along the way to the meter is using an MTU (Maximum
Transmission Unit) of about 100 bytes, producing two IP datagrams.
How many hops are there between the PC and the meter?  Are you
sniffing on the same subnet as the PC, the meter, or somewhere in
between?  MTU is normally set to about 1500 (and MSS is generally
MTU-40), but you can generally change these values.

You should be able to set the do-not-fragment flag on your IP packets,
but that may cause them to get dropped instead of sent.  You could
also try setting a smaller ICP MSS (Maximum Segment Size), which the
meter might be able to assemble, even if it can't handle fragmented IP
datagrams.  Try 
http://www.cisco.com/en/US/tech/tk870/tk877/tk880/technologies_tech_note09186a008011a218.shtml#prob_desc
for more help.

You really need to get a networking guru involved if you want to go
down this path.  I used to be one, but that was years ago.  Or, you
can take Gabriel Genellina's advice and try coding smaller responses.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Problems Returning an HTTP 200 Ok Message

2008-07-14 Thread samwyse
On Jul 11, 3:46 am, "Gabriel Genellina" <[EMAIL PROTECTED]>
wrote:

> As Guy Davidson has already pointed out, this is a problem in the meter  
> TCP implementation, and you should ask the vendor to fix it.

That would have been me, not Guy.
--
http://mail.python.org/mailman/listinfo/python-list


Using Python To Launch Python

2008-07-14 Thread aha
Hello All,
  I have a situation where I can count on a Python installation being
available on a system, but I can't count on it being a version of
Python needed by my application.  Since my application has it's own
version of Python installed with it how should I use the system Python
to launch the version of Python that launches my Application.  Yes,
this is a convoluted process, but not all Pythons are built the
same :)

Right now I am leaning towards using exec to start a new process, but
I thought I would check to see if anyone else has had the need to
perform a task similar to this one.

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


Re: Using Python To Launch Python

2008-07-14 Thread Derek Martin
On Mon, Jul 14, 2008 at 02:01:04PM -0700, aha wrote:
> Since my application has it's own version of Python installed with
> it how should I use the system Python to launch the version of
> Python that launches my Application.  Yes, this is a convoluted
> process, but not all Pythons are built the same :)

/usr/local/bin/$APPNAME:

#!/bin/sh

INSTALLPATH=
PATH=$INSTALLPATH/bin:$PATH
exec $INSTALLPATH/bin/python $APPNAME "$@"

Doesn't get much simpler than that. :)  You can certainly do the
equivalent in Python... there's not much difference.  Slightly less
typing in bourne/bash shell, I guess...

-- 
Derek D. Martin
http://www.pizzashack.org/
GPG Key ID: 0x81CFE75D



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

Re: Using McMillan Installer, PyInstall or py2exe cross-platform?

2008-07-14 Thread Benjamin Kaplan
On Mon, Jul 14, 2008 at 12:02 PM, Hartmut Goebel <[EMAIL PROTECTED]>
wrote:

> Hi,
>
> has anybody used McMillan Installer, PyInstall or py2exe cross-platform?
>
> I have a Windows partition with Python installed there, so this would
> "only" required working on a different directory and for a different OS.
> Since I'm working on Linux, it's awful to boot Windows each time I want to
> build a new release.
>
> Any hint in this area?
>
> --
> Schönen Gruß - Regards
> Hartmut Goebel
>
> Goebel Consult
> Spezialist für IT-Sicherheit in komplexen Umgebungen
> http://www.goebel-consult.de
> --


I don't know if this will work, but you can try running them on Wine. I know
that python 2.5 works fine right now.

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

Re: Using Python To Launch Python

2008-07-14 Thread Mike Driscoll
On Jul 14, 4:01 pm, aha <[EMAIL PROTECTED]> wrote:
> Hello All,
>   I have a situation where I can count on a Python installation being
> available on a system, but I can't count on it being a version of
> Python needed by my application.  Since my application has it's own
> version of Python installed with it how should I use the system Python
> to launch the version of Python that launches my Application.  Yes,
> this is a convoluted process, but not all Pythons are built the
> same :)
>
> Right now I am leaning towards using exec to start a new process, but
> I thought I would check to see if anyone else has had the need to
> perform a task similar to this one.
>
> AHA

As an alternative, you may be able to use the subprocess module of
Python to do this too.

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


Python Tiddlywiki class

2008-07-14 Thread CracKPod
Hello, I wrote a Python class to interact with the TiddlyWiki. In case
you are interested you can find it on my blog:

http://crackpod.bplaced.net/

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


Re: Using Python To Launch Python

2008-07-14 Thread Ivan Ven Osdel
>Hello All,
>  I have a situation where I can count on a Python installation being
>available on a system, but I can't count on it being a version of
>Python needed by my application.  Since my application has it's own
>version of Python installed with it how should I use the system Python
>to launch the version of Python that launches my Application.  Yes,
>this is a convoluted process, but not all Pythons are built the
>same :)
>
>Right now I am leaning towards using exec to start a new process, but
>I thought I would check to see if anyone else has had the need to
>perform a task similar to this one.

>AHA

Simplest case:

>>> import os
>>> os.system("/path/to/your/python app.py")

Obviously things can be shortened by adding to the PATH.

Ivan Ven Osdel
Software Engineer
http://datasyncsuite.com

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


Bug when using with_statement with exec

2008-07-14 Thread Matimus
I think I'm going to create a new issue in Pythons issue database, but
I wanted to run it by the news group first. See if I can get any
useful feed back.

The following session demonstrates the issue:

Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit
(Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> exec "def foo():\nreturn 0" # no ending newline works fine
>>> foo()
0
>>> exec "def foo():\nreturn 1\n" # with an ending newline works fine
>>> foo()
1
>>> from __future__ import with_statement
>>> exec "def foo():\nreturn 2\n" # with an ending newline works fine
>>> foo()
2
>>> exec "def foo():\nreturn 3" # without an ending new line... breaks
Traceback (most recent call last):
  File "", line 1, in 
  File "", line 2
return 3
  ^
SyntaxError: invalid syntax



If I create a function by using exec on a string and _don't_ end the
string with a new-line it will work just fine unless I "from
__future__ import with_statement". I can imagine that it is probably a
good practice to always end function body's with a new-line, but the
requirement should be consistent and the syntax error text could be a
_little_ more descriptive (and flag something other than the 2nd to
last character). Note that you don't need to be in the interpreter to
reproduce this issue.

I searched python's issue database and didn't see anything similar to
this. If there is already an issue related to this, please point me to
it... or better yet, let me know how you found it.

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


Re: logging via SocketHandler and TCPserver

2008-07-14 Thread Larry Bates

Vinay Sajip wrote:

On Jul 13, 9:25 pm, Larry Bates <[EMAIL PROTECTED]> wrote:

Every time I look at theloggingmodule (up until now) I've given up and
continue to use my home-grown logger that I've been using for years.   I'm not
giving up this time ;-)

I find that I REALLY need to be able to monitor LOTS of running
programs/processes and thought it would be nice to have them use 
SocketHandlerloggingand then I would write TCPServer to accept the log messages 
for
real-time monitoring.  I Googled (is that now a verb?) for several hours and
came up with some code that I've turned in to something that works, but I can't
figure out how to disconnect the server once it is connected  The goal is to be
able to start TCPServer, monitor the log messages sent via SocketHandler logger,
disconnect, and move to the next application.  Eventually I would like to wrap a
GUI around all of this for monitoring a complex web application.

Everything works, it just appears that I get into the while loop in
LogRecordStreamHandler.handle and it never breaks out (until I kill the client).
I can't seem to do anything with the LogRecordSocketReceiver.abort attribute to
make it quit.

I'm sure it is something simple (stupid?), but I've spent about 4 hours and I'm
not getting anywhere.

Thanks in advance for any assistance.

Regards,
Larry

Below is my code:

import sys
import time
importlogging

if sys.argv[1] == 'client':
 importlogging.config

 logging.config.fileConfig("logging.conf")

 #create logger
 logger =logging.getLogger("VESconsole")

 while 1:
 logger.debug("debug message")
 logger.info("info message")
 logger.warn("warn message")
 logger.error("error message")
 logger.critical("critical message")
 time.sleep(2)

elif sys.argv[1] == 'server':
 import cPickle
 importlogging.handlers
 import SocketServer
 import struct
 import signal

 class LogRecordStreamHandler(SocketServer.StreamRequestHandler):
 """Handler for a streamingloggingrequest.

 This basically logs the record using whateverloggingpolicy is
 configured locally.
 """

 def handle(self):
 """
 Handle multiple requests - each expected to be a 4-byte length,
 followed by the LogRecord in pickle format. Logs the record
 according to whatever policy is configured locally.
 """
 while 1:
 chunk = self.connection.recv(4)
 if len(chunk) < 4:
 break

 slen = struct.unpack(">L", chunk)[0]
 chunk = self.connection.recv(slen)
 while len(chunk) < slen:
 chunk = chunk + self.connection.recv(slen - len(chunk))

 obj = self.unPickle(chunk)
 record =logging.makeLogRecord(obj)
 self.handleLogRecord(record)

 def unPickle(self, data):
 return cPickle.loads(data)

 def handleLogRecord(self, record):
 t = time.strftime('%a, %d %b %y %H:%M:%S',
   time.localtime(record.created))

 print "%s %s" % (t, record.getMessage())

 class LogRecordSocketReceiver(SocketServer.ThreadingTCPServer):
 """simple TCP socket-basedloggingreceiver suitable for testing.
 """

 allow_reuse_address = 1

 def __init__(self, host='localhost',
  port=logging.handlers.DEFAULT_TCP_LOGGING_PORT,
  handler=LogRecordStreamHandler):

 SocketServer.ThreadingTCPServer.__init__(self,
  (host, port),
  handler)
 self.abort = 0
 self.timeout = 1
 self.logname = None

 def serve_until_stopped(self):
 import select
 abort = 0
 while not abort:
 rd, wr, ex = select.select([self.socket.fileno()],
[], [],
self.timeout)
 if rd:
 self.handle_request()

 abort = self.abort

 print "serve_until_stopped exiting"

 #
 # Start ThreadingTCPServer instance to accept SocketHandler log
 # messages from client.
 #
 tcpserver = LogRecordSocketReceiver()
 print "Starting ThreadingTCPServer..."
 tcpserver.serve_until_stopped()

'''
#-logging.conf-
[loggers]
keys=root

[handlers]
keys=socketHandler

[formatters]
keys=simpleFormatter

[logger_root]
level=DEBUG
handlers=socketHandler

[handler_socketHandler]
class=handlers.SocketHandler
level=DEBUG
args=('localhost', handlers.DEFAULT_TCP_LOGGING_PORT)
host=localhost
port=DEFAULT_TCP_LOGGING_PORT

[formatter_simpleFormatter]
format=%(asctime)s - %(name)s - %(levelname)s - %(mess

Re: Is it possible to create "network conneciton" on windows system?

2008-07-14 Thread Larry Bates

Evan wrote:

Hello,

one of my PC is window system, and in "control panel -> Network
Connections", I can see some network connections such as PPPOE or VPN
which I created by click "create a new connection".

My question is, is it possible to create a new connection by using
Python script? which means I do not want to use Window UI (via
"control panel"),  if it is possible, I can save so many time to
create various network connection when I want to do testing in the
lab.

Thanks very much.
Evan


It is very likely that it is possible to do this.  Most control panel 
applications store the results of their GUI setup in the registry.  If you can 
determine what registry keys have been added/changed.  Here is an open source 
registry compare utility that might help:


https://sourceforge.net/projects/regshot

You can then use the _winreg module to make such changes on a new machine.

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


Re: Using Python To Launch Python

2008-07-14 Thread Larry Bates

aha wrote:

Hello All,
  I have a situation where I can count on a Python installation being
available on a system, but I can't count on it being a version of
Python needed by my application.  Since my application has it's own
version of Python installed with it how should I use the system Python
to launch the version of Python that launches my Application.  Yes,
this is a convoluted process, but not all Pythons are built the
same :)

Right now I am leaning towards using exec to start a new process, but
I thought I would check to see if anyone else has had the need to
perform a task similar to this one.

AHA


You didn't tell us what operating system, but if by chance it is Windows you 
should use py2exe to package up your program (along with the proper 
pythonXX.dll) into a distributable package.


On Linux, others have posted answers.

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


Re: Bug when using with_statement with exec

2008-07-14 Thread Jerry Hill
On Mon, Jul 14, 2008 at 6:00 PM, Matimus <[EMAIL PROTECTED]> wrote:
> If I create a function by using exec on a string and _don't_ end the
> string with a new-line it will work just fine unless I "from
> __future__ import with_statement".
[snip]
> I searched python's issue database and didn't see anything similar to
> this. If there is already an issue related to this, please point me to
> it... or better yet, let me know how you found it.

Possibly related to http://bugs.python.org/issue1184112, and/or
http://bugs.python.org/issue501622?

Since you asked, I found it by googling the words "python exec with
newline".  The second item was an email on Python-Dev with a similar
bug and referencing an issue id.  The comments on that issue led to
the other one.

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


Re: Why is there no GUI-tools like this for Windows?

2008-07-14 Thread name
It seems the video is showing glade, which is also available for wx
under the name wxglade, I do not know whether it's available for
Windows. I think it should work because it itself is written in
Python. I personally prefer to code my GUI myself, so I can do looping
stuff with it, but that is just me.
--
http://mail.python.org/mailman/listinfo/python-list


Method behavior for user-created class instances

2008-07-14 Thread crazychimp132
Greetings.

I am looking for a way to achieve method behavior for a class I
created. That is, it has a __call__ method,  so can be called like a
function. But I also want it to be treated as a method when it appears
in a class body.

Eg.

class foo:
def __call__(self, inst): pass

class bar:
meth = foo()

such that bar().meth() will not raise an exception for too few
arguments (because the inst argument in foo.__call__ is implicitly set
to the bar instance). I know this has to do with writing the __get__
method of foo, but I am wondering if there is perhaps some class I can
just inherit from to get the proper __get__, which behaves identically
to that of regular Python functions. The need for this arises out of
the implementation of a function decorator as a class.

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


Re: Using Python To Launch Python

2008-07-14 Thread Derek Martin
On Mon, Jul 14, 2008 at 05:40:43PM -0400, Aquil H. Abdullah wrote:
> You've hit the proverbial nail with the hammer.  The problem is that my
> application needs to run under both the Linux and Windows OSs, so while I
> would love to use a nice sh, csh, or bash shell script. My hands are tied
> because Windows does not provide such wonderful shells.

*Provides*, no... neither does it provide Python, for what that's
worth.  But you can certainly get it (bash):

  http://win-bash.sourceforge.net/

I suppose it's not worth installing just for this purpose though...
But you can provide with your application a DoS batch file that does
exactly the same thing (in addition to a shell script).  The user
would quite intuitively use whichever were appropriate, or follow your
provided directions otherwise.  Or, the equivalent in (hopefully
OS-agnostic) Python:

import os, sys

# I believe this gets the name of the root in all major OSes
def root_dir(path):
if os.path.dirname(path) == path:
return path
return (root_dir(os.path.dirname(path)))

appname = 
root = root_dir(os.getcwd())
install_path = os.path.join(root, "usr")
bin_path = os.path.join(install_path, "bin")
os.environ["PATH"] = bin_path + os.pathsep + os.environ["PATH"]
python_path = os.path.join(bin_path, "python")
args = sys.argv[1:]
args.insert(0, os.path.join(bin_path, appname))
args.insert(0, python_path)
args.insert(0, python_path)
os.execv(python_path, args)





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

Python ver of System.arraycopy() in Java

2008-07-14 Thread Jordan
I could seem to find a built in function that would serve the purpose
of System.arraycopy() in java.

I was able to accomplish it with something like this:

def arraycopy(source, sourcepos, dest, destpos, numelem):
dest[destpos:destpos+numelem] = source[sourcepos:sourcepos
+numelem]


is there a built in version, or better way of doing this...
--
http://mail.python.org/mailman/listinfo/python-list


Re: Is it possible to create "network conneciton" on windows system?

2008-07-14 Thread Evan
On Jul 15, 6:22 am, Larry Bates <[EMAIL PROTECTED]> wrote:
> Evan wrote:
> > Hello,
>
> > one of my PC is window system, and in "control panel ->Network
> >Connections", I can see somenetworkconnectionssuch as PPPOE or VPN
> > which I created by click "create a new connection".
>
> > My question is, is it possible to create a new connection by using
> > Python script? which means I do not want to use Window UI (via
> > "control panel"),  if it is possible, I can save so many time to
> > create variousnetworkconnection when I want to do testing in the
> > lab.
>
> > Thanks very much.
> > Evan
>
> It is very likely that it is possible to do this.  Most control panel
> applications store the results of their GUI setup in the registry.  If you can
> determine what registry keys have been added/changed.  Here is an open source
> registry compare utility that might help:
>
> https://sourceforge.net/projects/regshot
>
> You can then use the _winreg module to make such changes on a new machine.
>
> HTH,
> Larry


Thanks Larry,

The thing is, if I change the registry, I have to reboot the PC for
applying new configuration of system. Any idea to apply the changing
without reboot after modify registry?

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


Re: About the slot declaration decorator in PyQt4

2008-07-14 Thread Bighead
On Jul 15, 2:04 am, "Sebastian \"lunar\" Wiesner"
<[EMAIL PROTECTED]> wrote:
> Bighead <[EMAIL PROTECTED]>:
>
> > I remember when I did UI Design in PyQt4 for the first time, I found a
> > manual. In it, no "connect" was used. Instead, an OO approach is
> > applied, new UI classes inherit from old ones, and all the slot
> > functions are automatically connected to some signals, using a
> > decorator. In the __init__ function of our newly written class,
> > "connect" is not invoked.
>
> > I like this style...
>
> > Unfortunately, I cannot find that manual now So anyone have read
> > something like that before? If so, could you tell me where can I find
> > that manual please? Thank you :)
>
> I guess, you're referring to QtCore.pyqtSignature and
> QtCore.QMetaObject.connectSlotsByName.
>
> Seehttp://www.riverbankcomputing.co.uk/static/Docs/PyQt4/pyqt4ref.html#t...
>
> Especially "3.7.3   Connecting Slots By Name"
>
> Hih
>
> --
> Freedom is always the freedom of dissenters.
>   (Rosa Luxemburg)

Oh yes, that's it! connectSlotsByName. That is the reason I though Qt
was easy to use.

This will be much easier :) Thank you very much.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Method behavior for user-created class instances

2008-07-14 Thread Larry Bates

[EMAIL PROTECTED] wrote:

Greetings.

I am looking for a way to achieve method behavior for a class I
created. That is, it has a __call__ method,  so can be called like a
function. But I also want it to be treated as a method when it appears
in a class body.

Eg.

class foo:
def __call__(self, inst): pass

class bar:
meth = foo()

such that bar().meth() will not raise an exception for too few
arguments (because the inst argument in foo.__call__ is implicitly set
to the bar instance). I know this has to do with writing the __get__
method of foo, but I am wondering if there is perhaps some class I can
just inherit from to get the proper __get__, which behaves identically
to that of regular Python functions. The need for this arises out of
the implementation of a function decorator as a class.

Thanks.


While it is not clear "why" you would want this, I believe this works.
If not, take a look at staticmethods or classmethods, they might work for you.

>>> class foo(object):
... def __call__(self, inst):
... print "foo.__call__", inst
...

>>> class bar:
... def __init__(self):
... self.foo = foo()
... self.meth = self.foo.__call__
...
>>> b = bar()
>>> b.meth(1)
foo.__call__ 1

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


Re: Python Tiddlywiki class

2008-07-14 Thread David

CracKPod wrote:

Hello, I wrote a Python class to interact with the TiddlyWiki. In case
you are interested you can find it on my blog:

http://crackpod.bplaced.net/

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


  


Thank you :)

--
Powered by Gentoo GNU/LINUX
http://www.linuxcrazy.com

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


Re: About wmi

2008-07-14 Thread patrol
Hi,
> 1) I'm not sure if WMI can be forced to close down system processes,
> but if it can it's probably by means of specifying one or more
> privileges when you connect. Try looking in the WMI newsgroups
> for a more general (non-Python) answer to this and I'll happily
> explain how to apply it in a Python context.
I use VBS to kill these processes,the VBS cannot kill these either.

> 2) I can't quite see from this traceback where the problem
> arises. Have you snipped the traceback at all, or was that
> all there was? Can you narrow the thing down to a short
> snippet of code which I'm likely to be able to run independently,
> please?
import wmi
from time import sleep

c = wmi.WMI ()
process_watcher = c.Win32_Process.watch_for("creation")
while True:
new_process = process_watcher()
if new_process.Caption == 'notepad.exe':
print "start killing.."
sleep(5)
result = new_process.terminate()
print "killed"
We must start the notepad.exe manually, then (1) kill the notepad.exe
by this code.
(2)we kill the notepad.exe before this code manually. Both will result
in errors.
--
http://mail.python.org/mailman/listinfo/python-list


One step up from str.split()

2008-07-14 Thread Joel Koltner
I normally use str.split() for simple splitting of command line arguments, but 
I would like to support, e.g., long file names which-- under windows -- are 
typically provided as simple quoted string.  E.g.,

myapp --dosomething --loadthis "my file name.fil"

...and I'd like to get back a list wherein ListEntry[3]="my file name.fil" , 
but just running str.split() on the above string creates:

>>> ListEntry='myapp --dosomething --loadthis "my file name.fil"'
>>> ListEntry.split()
['myapp', '--dosomething', '--loadthis', '"my', 'file', 'name.fil"']

Is there an easy way to provide just this one small additional feature 
(keeping quoted names as a single entry) rather than going to a full-blown 
command-line argument parsing tool?  Even regular expressions seem like they'd 
probably be overkill here?  Or no?

Thanks,
---Joel


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


Re: One step up from str.split()

2008-07-14 Thread Matimus
On Jul 14, 6:33 pm, "Joel Koltner" <[EMAIL PROTECTED]>
wrote:
> I normally use str.split() for simple splitting of command line arguments, but
> I would like to support, e.g., long file names which-- under windows -- are
> typically provided as simple quoted string.  E.g.,
>
> myapp --dosomething --loadthis "my file name.fil"
>
> ...and I'd like to get back a list wherein ListEntry[3]="my file name.fil" ,
> but just running str.split() on the above string creates:
>
> >>> ListEntry='myapp --dosomething --loadthis "my file name.fil"'
> >>> ListEntry.split()
>
> ['myapp', '--dosomething', '--loadthis', '"my', 'file', 'name.fil"']
>
> Is there an easy way to provide just this one small additional feature
> (keeping quoted names as a single entry) rather than going to a full-blown
> command-line argument parsing tool?  Even regular expressions seem like they'd
> probably be overkill here?  Or no?
>
> Thanks,
> ---Joel

look at the shlex module:

>>> import shlex
>>> txt = 'myapp --dosomething --loadthis "my file name.fil"'
>>> shlex.split(txt)
['myapp', '--dosomething', '--loadthis', 'my file name.fil']

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


urllib2 http authentication/redirection/cookie issue

2008-07-14 Thread Neuberger, Sheldon N.
I have a tricky situation here with auth/redirection/cookies and I
think I am messing something up with the handler.

I am trying to open a site http://foo.example.com which redirects
(status 302) to https://bar.example.com/ where the dashes
represent lots of subdirectories and parameters.  This second site,
bar.example.com, is the site which requires authorization (status 401).
Upon authorization, the second site will give a cookie or two then
redirect (status 302) to the original site which will then load because
of the cookie. 

The problem is that when I run my code, I still get an HTTP 401
exception. Any help would be much appreciated.

Code and traceback follows.

Regards,
Sheldon Neuberger


--
cj = cookielib.LWPCookieJar()
cookie_handler = urllib2.HTTPCookieProcessor(cj)

passmgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
passmgr.add_password(None, 'https://bar.example.com',
   'username', 'password')
auth_handler = urllib2.HTTPBasicAuthHandler(passmgr)

opener = urllib2.build_opener(cookie_handler, auth_handler)
urllib2.install_opener(opener)

html = urllib2.urlopen('http://foo.example.com/qux/')

-

Traceback (most recent call last):
  File "dts.py", line 21, in 
html = urllib2.urlopen('http://foo.example.com/qux/')
  File "C:\Python25\lib\urllib2.py", line 124, in urlopen
return _opener.open(url, data)
  File "C:\Python25\lib\urllib2.py", line 387, in open
response = meth(req, response)
  File "C:\Python25\lib\urllib2.py", line 498, in http_response
'http', request, response, code, msg, hdrs)
  File "C:\Python25\lib\urllib2.py", line 419, in error
result = self._call_chain(*args)
  File "C:\Python25\lib\urllib2.py", line 360, in _call_chain
result = func(*args)
  File "C:\Python25\lib\urllib2.py", line 582, in http_error_302
return self.parent.open(new)
  File "C:\Python25\lib\urllib2.py", line 387, in open
response = meth(req, response)
  File "C:\Python25\lib\urllib2.py", line 498, in http_response
'http', request, response, code, msg, hdrs)
  File "C:\Python25\lib\urllib2.py", line 425, in error
return self._call_chain(*args)
  File "C:\Python25\lib\urllib2.py", line 360, in _call_chain
result = func(*args)
  File "C:\Python25\lib\urllib2.py", line 506, in http_error_default
raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 401: Unauthorized

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

Python pack and unpack question

2008-07-14 Thread joe shoemaker
If you have the following:

  data = unpack('>L', sock.recv(4))

Does this line of code means that incoming data is big endian and
unpack it to endianess of local machine? If local machine is little
endian, then big endian is automatically converted to little endian
format?

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


Re: One step up from str.split()

2008-07-14 Thread Timothy Grant
On Mon, Jul 14, 2008 at 6:33 PM, Joel Koltner <[EMAIL PROTECTED]>
wrote:

> I normally use str.split() for simple splitting of command line arguments,
> but
> I would like to support, e.g., long file names which-- under windows -- are
> typically provided as simple quoted string.  E.g.,
>
> myapp --dosomething --loadthis "my file name.fil"
>
> ...and I'd like to get back a list wherein ListEntry[3]="my file name.fil"
> ,
> but just running str.split() on the above string creates:
>
> >>> ListEntry='myapp --dosomething --loadthis "my file name.fil"'
> >>> ListEntry.split()
> ['myapp', '--dosomething', '--loadthis', '"my', 'file', 'name.fil"']
>
> Is there an easy way to provide just this one small additional feature
> (keeping quoted names as a single entry) rather than going to a full-blown
> command-line argument parsing tool?  Even regular expressions seem like
> they'd
> probably be overkill here?  Or no?
>
> Thanks,
> ---Joel



I've found that anytime I have more than one option on the command line,
optparse  is the way to go. It works very very well for every circumstance
I've been able to throw at it.

-- 
Stand Fast,
tjg. [Timothy Grant]
--
http://mail.python.org/mailman/listinfo/python-list

Re: Is it possible to create "network conneciton" on windows system?

2008-07-14 Thread Larry Bates

Evan wrote:

On Jul 15, 6:22 am, Larry Bates <[EMAIL PROTECTED]> wrote:

Evan wrote:

Hello,
one of my PC is window system, and in "control panel ->Network
Connections", I can see somenetworkconnectionssuch as PPPOE or VPN
which I created by click "create a new connection".
My question is, is it possible to create a new connection by using
Python script? which means I do not want to use Window UI (via
"control panel"),  if it is possible, I can save so many time to
create variousnetworkconnection when I want to do testing in the
lab.
Thanks very much.
Evan

It is very likely that it is possible to do this.  Most control panel
applications store the results of their GUI setup in the registry.  If you can
determine what registry keys have been added/changed.  Here is an open source
registry compare utility that might help:

https://sourceforge.net/projects/regshot

You can then use the _winreg module to make such changes on a new machine.

HTH,
Larry



Thanks Larry,

The thing is, if I change the registry, I have to reboot the PC for
applying new configuration of system. Any idea to apply the changing
without reboot after modify registry?

Thanks,


Not necessarily.  You can change the registry on-the-fly and any programs that 
aren't running at the time will pick up the changes when they are run.  If you 
can "Create a new connection" and have it work without rebooting, you can do it 
via the registry/Python in exactly the same way.


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


Re: Need help in writing up a Python Syntax checker

2008-07-14 Thread Kinokunya
On Jul 14, 6:48 pm, Kay Schluehr <[EMAIL PROTECTED]> wrote:
> On 14 Jul., 08:22, Kinokunya <[EMAIL PROTECTED]> wrote:
>
> > Hi guys,
>
> > My group and I will be working on our final year project, the scope to
> > do a program/web-based application similar areas of functionalities
> > like the PyLint and PyChecker; a Python syntax checker. We have no
> > Python background, equipped only with some knowledge of Java and Dot
> > net.
>
> Python doesn't need a syntax checker. Syntax is checked by the parser
> and the parser is exposed to the user by means of the parser module.
> What you probably mean are *semantical* checks which are typical for
> compilers: e.g. whether names are used with prior assignments of
> values that cause runtime exceptions. These issues are in fact covered
> by PyLint and PyChecker.
>
> > We did some research on PyLint and found out that there are 2 common
> > modules that PyLint & PyChecker are using, namely logilab-astng and
> > logilab-common. I'm not really sure what these 2 modules are for.
>
> > Quoted from the offical site,
>
> > The aim of this module (logilab-astng) is to provide a common base
> > representation of python source code
>
> > We're not really sure what they meant by common base representation of
> > source codes.
>
> Just switch to \Scripts\  in your Vista installation
>
> and type `easy_install pylint`. This shall install PyLint in the
> directory
>
>\lib\site-packages
>
> Additionally a pylint.bat file is placed in the \Scripts
> \ directory.
>
> Type `pylint --help` and you get more information about the
> functionality of PyLint.





Thanks for replying Kay Schluehr,

The topic of our project was to do a program/software similar to
PyLint and PyChecker, and the project scope does not require us to
compile the codes. I guess by that it means 'semantic' checks in this
case. Does that means we can make use of the parser module as
mentioned above for semantic syntax checking?

Our situation now is that we are torn between the programming
languages to go, Java, Jython or Python, with no definite direction to
start off our development. Any pointers would be appreciated.

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


Re: One step up from str.split()

2008-07-14 Thread Larry Bates

Joel Koltner wrote:
I normally use str.split() for simple splitting of command line arguments, but 
I would like to support, e.g., long file names which-- under windows -- are 
typically provided as simple quoted string.  E.g.,


myapp --dosomething --loadthis "my file name.fil"

...and I'd like to get back a list wherein ListEntry[3]="my file name.fil" , 
but just running str.split() on the above string creates:



ListEntry='myapp --dosomething --loadthis "my file name.fil"'
ListEntry.split()

['myapp', '--dosomething', '--loadthis', '"my', 'file', 'name.fil"']

Is there an easy way to provide just this one small additional feature 
(keeping quoted names as a single entry) rather than going to a full-blown 
command-line argument parsing tool?  Even regular expressions seem like they'd 
probably be overkill here?  Or no?


Thanks,
---Joel


Sounds like it is time to look at getopt Library module.  I handles these types 
of args lines.


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


Re: About wmi

2008-07-14 Thread patrol

Situation (1):
result = new_process.terminate()
TypeError: 'int' object is not callable

Situation (2):
result = new_process.terminate()
  File "C:\Python25\lib\wmi.py", line 494, in __getattr__
handle_com_error (error_info)
  File "C:\Python25\lib\wmi.py", line 190, in handle_com_error
raise x_wmi, "\n".join (exception_string)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xb7 in position
14: ordinal
 not in range(128)

BTW, My windows' languange is Chinese.
--
http://mail.python.org/mailman/listinfo/python-list


Re: One step up from str.split()

2008-07-14 Thread Joel Koltner
Thanks Matt, that looks like just what I want! 


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


Re: Determining when a file has finished copying

2008-07-14 Thread Ethan Furman

Michiel Overtoom wrote:

Ethan wrote:

One more option may be to attempt to rename 
the file -- if it's still open for copying, that will fail; 
success indicates the copy is done.  


Caveat -- this is dependent on the operating system!

Windows will indeed not allow you to rename or delete a file that's still
open for writing by another process, at least not when the file is on a
local NTFS filesystem, but don't count on this on Unix or networked
filesystems.  There you can easily rename, move or delete a filename from a
directory whilst other processes still write to it. After all, a directory
is nothing else than a list of filenames which map to certain inodes.


Very good point.  Thanks.
~Ethan
--
http://mail.python.org/mailman/listinfo/python-list


Re: a module.pth question

2008-07-14 Thread oyster
there are 2 reasons:
1. I use both py24 and py25, I don't like to install 2 copies of
pyglet, which is a pure python module and can be used by py24/25 at
the same time, thus I am not willing to put a module under
site-packages, instead I use a separate directory(h:\pure_pylib in my
case)

2. I also carry python on my U-disk, as you know the driver letter
assigned to it is not always same. so I can't use full path name

> -- 已转发邮件 --
> From: Mike Driscoll <[EMAIL PROTECTED]>
> To: python-list@python.org
> Date: Mon, 14 Jul 2008 06:12:25 -0700 (PDT)
> Subject: Re: a module.pth question
> On Jul 14, 6:26 am, oyster <[EMAIL PROTECTED]> wrote:
> > My py24 is installed in h:\python24
> > I installed pyglet(http://pyglet.org/) in
> > H:\pure_pylib\Multimedia\pyglet-1.0\, if I do
> > [code]>>> import sys
> > >>>
> sys.path.append(r'H:\pure_pylib\Multimedia\pyglet-1.0')
> > >>> import pyglet
> >
> > [/code]
> > it is ok.
> >
> > but if I created h:\pure_pylib\pyglet.pth file, which containts
> > [code]
> > Multimedia\pyglet-1.0
> > [/code]
> >
> > then
> > [code]>>> import sys
> > >>> sys.path.append(r'h:\pure_pylib')
> > >>> import pyglet
> >
> > Traceback (most recent call last):
> >   File "", line 1, in ?
> > ImportError: No module named pyglet
> >
> > [/code]
> >
> > what is wrong with it? and How to fix it? thanks in advance
>
> I looked in my easy_install.pth and it looks like it should be:
>
> .\Multimedia\pyglet-1.0
>
> But I don't really see any reason not to do it the way you were
> earlier with the full path name. Besides, you should be able to
> install pyglet to your site-packages folder. Or you could use buildout
> if you're just testing modules and you don't want to screw up your
> namespace.
>
> Mike
--
http://mail.python.org/mailman/listinfo/python-list

How to write a custom tracer/profiler?

2008-07-14 Thread [EMAIL PROTECTED]
Hi, all,

Just wanna look for some suggestions on how to appoarch this
problem...

I have some code ("main logic") which has a dependency on a library.
Let's call it DS. ("data source").

The main logic will issue a number of calls to the DS in order to get
the data it needs and then carry out some calculations.

I want to have a non-intrusive way to find out all the DS data
requested by the main logic.

One thing to note, the DS is a big, messy bit of code. So putting
logger everywhere within DS and main logic is not a reliably,
satisfactory solution.

I have thought about using somehting like aspect. But seems to me
there is no mature, widely-used aspect lib out there.

Another idea is: let's roll a custom tracer/profiler. Whenever any
method/attributes in the DS package are called, the return values will
be logged.

I have taken a quick look at profile.py in python 2.4, It seems sys
module will pass a frames to the profile class. Can I access the
return value of a function via these frame objects?

Cheers, Anthony
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python ver of System.arraycopy() in Java

2008-07-14 Thread Miki
Hello,

> I could seem to find a built in function that would serve the purpose
> of System.arraycopy() in java.
>
> I was able to accomplish it with something like this:
>
> def arraycopy(source, sourcepos, dest, destpos, numelem):
>     dest[destpos:destpos+numelem] = source[sourcepos:sourcepos
> +numelem]
>
> is there a built in version, or better way of doing this...
This *is* the built in way :)

HTH,
--
Miki <[EMAIL PROTECTED]>
http://pythonwise.blogspot.com


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


  1   2   >