Re: list comprehension question

2009-05-06 Thread alex23
On May 6, 2:10 pm, Steven D'Aprano
 wrote:
> It's precisely the indentation and colons (plus newlines) that makes
> nested for-loops easier to read than list-comps with multiple fors.
>
> You can get back *nearly* all the readability by splitting the list comp
> into multiple lines:

It was less the overall readability I was commenting on, and more the
claim that the listcomp required a 'back-and-forth' parsing to
understand. As you've reinforced, the listcomp can be readily
converted back to the multiple-line form by the inclusion of colons &
EOL markers, which means you can make as much sequential sense from a
listcomp as you can a for-loop.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Self function

2009-05-06 Thread Arnaud Delobelle
On May 5, 10:20 pm, Aaron Brady  wrote:
> def auto( f ):
>     def _inner( *ar, **kw ):
>         return f( _inner, *ar, **kw )
>     return _inner

Quoting myself near the start of this thread:

Here's an idea:
>>> def bindfunc(f):

... def boundf(*args, **kwargs):
... return f(boundf, *args, **kwargs)
... return boundf


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


Re: Code works fine except...

2009-05-06 Thread MRAB

John Yeung wrote:

On May 5, 11:37 pm, Ross  wrote:


On May 5, 10:33 am, MRAB  wrote:


Here's my approach (incomplete):

FYI... I was testing your code further and discovered a strange
outcome... when there are 16 people for 7 courts, every 7th
round your code produces 4 byes instead of the correct 2 byes.


Well, MRAB did say his was incomplete, and it's significantly shorter
and cleaner than mine.

Mine has even weirder-looking behavior at 16 players on 7 courts, but
I think it's because mine tries harder to keep things balanced.  After
a few rounds, the inequalities start to build up, and my routine picks
some people more often to "catch up", but it doesn't prevent the same
person from being scheduled for multiple matches the same week.  There
may also be other, more subtle ways mine is broken.

It also may be that the problem is inherently unsolvable for some
values.  (I'm still waiting for someone with sufficient math ability
to swoop in and either provide a way that works for all values, or
confirm that there are just some unavoidable pathological cases.)


I'm not sure that all the requirements can be met.

I have the feeling that if the number of rounds is restricted then the
difference between the minimum and maximum number of byes could be 2
because of the requirement that players shouldn't play each other more
than once, meaning that the players have to be shuffled around a bit, so
a player might play a week earlier or later than would otherwise be the
case.

If every possible combination is done (everyone plays everyone else)
then the number of byes would be the same for all, otherwise the
difference could be 2, not 1. I think! :-)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Cannot start a thread in atexit callback

2009-05-06 Thread Graham Dumpleton
On May 6, 3:18 pm, "Gabriel Genellina"  wrote:
> En Tue, 05 May 2009 23:52:25 -0300, Zac Burns  escribió:
>
> > It seems that one cannot start a thread in an atexit callback.
>
> > My use case is that I have a IO heavy callback that I want to run in a
> > thread so that other callbacks can finish while it's doing it's thing
> > to save on exit time.
>
> Try creating the thread when the program begins, but locked. And release  
> the lock when your programs is about to finish.

FWIW, from Python 2.5 (??) onwards, a shutdown of non daemonized
threads is performed as a separate step before atexit callbacks. Not
sure if other aspects of threading may be undone at that point and so
prevent startup of new ones.

The code in threading module which is called is:

class _MainThread(Thread):

...

def _exitfunc(self):
self._Thread__stop()
t = _pickSomeNonDaemonThread()
if t:
if __debug__:
self._note("%s: waiting for other threads", self)
while t:
t.join()
t = _pickSomeNonDaemonThread()
if __debug__:
self._note("%s: exiting", self)
self._Thread__delete()

_shutdown = _MainThread()._exitfunc

The call to this is done from WaitForThreadShutdown() in main.c. Which
is in turn called from Py_Main() just prior to calling Py_Finalize().

WaitForThreadShutdown();

Py_Finalize();

This is all different to older versions of Python which shutdown such
threads from an actual atexit handler. This caused various ordering
issues.

Anyway, the point of this is that it would need to be a daemonized
thread to begin with. :-)

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


Pybuez Client sending messages to j2me Server

2009-05-06 Thread CkurtM
I have a problem with recieving requests on j2me based bluetooth
server using RFCOMM. I can send messages from the j2me client to
python server, but cant receive from the python bluetooth client to
j2me server, it only connects but doesnt receive??.I can send copy of
code on request.
I'm using pybluez on python 2.6
and standard javax.bluetooth for the mobile interface. Any help wud be
welcome.
Thanks in advance.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Which one is best Python or Java for developing GUI applications?

2009-05-06 Thread Tim Rowe
2009/5/6 Dennis Lee Bieber :

> (the "near" is because I feel Ada is
> stricter than any other language)

Try SPARK -- it's Ada based, but /much/ stricter. It's just right for
some really critical stuff, but is no sort of an answer to "Which one
is best Python or Java for developing GUI"!

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


Re: thc v0.3 - txt to html converter - better code?

2009-05-06 Thread Richard Brodie

"Stefan Behnel"  wrote in message 
news:4a008996$0$31862$9b4e6...@newsspool3.arcor-online.net...

>language_map = {'English': 'EN', 'Deutsch': 'DE'}
>strict_or_transitional = {True: 'Transitional', False: 'Strict'}
>
># this will raise a KeyError for unknown languages
>language = language_map[ self.cmboBoxLang.currentText() ]
>
># this assumes that isChecked() returns True or False
>spec = strict_or_transitional[self.rdioBtnTransitional.isChecked()]
>
>doctype = '\n' % (
>spec, language)

Incidentally, the language in an HTML DOCTYPE refers to the language of the 
DTD, not
the document. It's never correct to use //DE in an HTML page, unless you have a 
custom
(German) DTD. So the code can be improved further by cutting that part out.

strict_or_transitional = {True: 'Transitional', False: 'Strict'}

# this assumes that isChecked() returns True or False
spec = strict_or_transitional[self.rdioBtnTransitional.isChecked()]

doctype = '\n' % spec


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


Re: desperately looking for a howto on running my wxPython app on Vista

2009-05-06 Thread Paul Sijben
Mike Driscoll wrote:
> 
> 
> Hmmm...I'm not familiar with that DLL, but a little googling seems to
> indicate that you may be able to get it off your installation CD:

it actually is there on my system. So this may be the red herring the
Dependency Walker FAQ is warning for

maybe I should leave this mess and revert to python 2.5

> 
> http://www.techimo.com/forum/applications-operating-systems/76550-winxp-msgina-dll-shlwapi-dll-problem.html
> 
> The link above gives the steps for XP, but Vista will probably be
> similar. I don't know for sure, but you may have to register the dll
> once you've got it copied back onto your machine.
> 
> Mike
--
http://mail.python.org/mailman/listinfo/python-list


Re: pyc files problem

2009-05-06 Thread Dave Angel

Gabriel Genellina wrote:
En Wed, 
06 May 2009 00:43:25 -0300, Mohamed Lrhazi  escribió:



My code sends a pointer to a Python function to a C library, using
ctypes module. When my program restarts, after a crash or normal
exit... it cannot start again without sigfaulting


Do you mean that, if you delete the .pyc files your program runs 
properly, but if you keep the .pyc files your program crashes?

That's very strange...


What is the proper way around this problem? other than adding code to
delete the cache files?


There is no "proper way around" the problem; it should not exist in 
the first place!


Have you read the note at the end of the "Callback" section in the 
ctypes documentation?

"""Important note for callback functions:

Make sure you keep references to CFUNCTYPE objects as long as they are 
used from C code. ctypes doesn't, and if you don't, they may be 
garbage collected, crashing your program when a callback is made."""


There is a ctypes-specific list: 
https://lists.sourceforge.net/lists/listinfo/ctypes-users


1) Is it true (as Gabriel asks) that deleting the .pyc files solves the 
problem?
2) If so, have you investigated to see which one of them gets 
corrupted?  This isn't necessarily the problem, it could also be timing, 
or related to the order of the memory allocation pool.
3) When you get the segment fault, what does you C debugger show?  
What's happening at the time of the crash?

4) Is either the C code or the Python code multithreaded?
5) Are you running it under a Python debugger?

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


Checking for required arguments when instantiating class.

2009-05-06 Thread Lacrima
Hello!

For example I have two classes:

>>> class First:
def __init__(self, *args, **kwargs):
pass

>>> class Second:
def __init__(self, somearg, *args, **kwargs):
self.somearg = somearg

How can I test that First class takes 1 required argument and Second
class takes no required arguments?
So that I could instantiate them in a for loop.

>>> a = [First, Second]
>>> for cls in a:
instance = cls()

Traceback (most recent call last):
  File "", line 2, in 
instance = cls()
TypeError: __init__() takes at least 2 arguments (1 given)

Of course, I can do like this:
>>> for cls in a:
try:
instance = cls()
except TypeError:
instance = cls('hello')

>>> print instance.somearg
hello

But what if I have to instantiate any class with 3 or 4 required
arguments? How can I do it?

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


Re: Checking for required arguments when instantiating class.

2009-05-06 Thread Lacrima
> >>> class First:
>
>         def __init__(self, *args, **kwargs):
>                 pass
>
> >>> class Second:
>
>         def __init__(self, somearg, *args, **kwargs):
>                 self.somearg = somearg
>
> How can I test that First class takes 1 required argument and Second
> class takes no required arguments?


Sorry, I have made a mistake. Of course, Second class takes 1 required
argument, not First.
--
http://mail.python.org/mailman/listinfo/python-list


Re: what's the best way to call a method of object without a guarantee of its existence

2009-05-06 Thread Marco Mariani

Leon wrote:


So I need to go back to the module including "parent" class
to define the objects that I maybe use in future as None,


You can assign them to a placeholder, with a method that always exists 
but does nothing.


class NullObject(object):
def method(self, *args, **kw):
pass



actually, the module including "parent' class works very well
without those definitions, from parent class's point of view,
those definitions are kind of noisy.


If you don't feel the need to define the instances there, maybe they 
don't belong to that class after all.



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


Re: Checking for required arguments when instantiating class.

2009-05-06 Thread Chris Rebert
On Wed, May 6, 2009 at 3:08 AM, Lacrima  wrote:
> Hello!
>
> For example I have two classes:
>
 class First:
>        def __init__(self, *args, **kwargs):
>                pass
>
 class Second:
>        def __init__(self, somearg, *args, **kwargs):
>                self.somearg = somearg
>
> How can I test that First class takes 1 required argument and Second
> class takes no required arguments?

import inspect
args, varargs, varkw, defaults = inspect.getargspec(klass)
num_args_reqd = len(args) - (0 if defaults is None else len(defaults))

However, it sounds like a code smell that you're instanciating unknown
classes that don't share a common constructor signature.

Cheers,
Chris
-- 
http://blog.rebertia.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: object query assigned variable name?

2009-05-06 Thread Sion Arrowsmith
John O'Hagan   wrote:
>I guess what I meant was that if I type:
>
>brian = Brian()
>
>in the python shell and then hit return, it seems to me that _somewhere_ (in 
>the interpreter? I have no idea how it's done) it must be written that the 
>new Brian object will later be assigned the name "brian", even as the process 
>of creating the instance begins. As you've just demonstrated, the actual 
>assignment occurs afterwards.

As far as CPython goes, the parser (presumably) knows, but the
bytecode interpreter doesn't (without looking ahead), and you
can't assume you've got anything more than the bytecode.

This is what I should've done in the first place:

>>> def f():
... messiah = Brian()
...
>>> import dis
>>> dis.dis(f)
  2   0 LOAD_GLOBAL  0 (Brian)
  3 CALL_FUNCTION0
  6 STORE_FAST   0 (messiah)
  9 LOAD_CONST   0 (None)
 12 RETURN_VALUE
>>>

So while the information might be there, I'm not sure how you
could make use of it without going into bytecodehacks territory.

-- 
\S

   under construction

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


Re: Checking for required arguments when instantiating class.

2009-05-06 Thread Lie Ryan

Lacrima wrote:

class First:

def __init__(self, *args, **kwargs):
pass


class Second:

def __init__(self, somearg, *args, **kwargs):
self.somearg = somearg

How can I test that First class takes 1 required argument and Second
class takes no required arguments?



Sorry, I have made a mistake. Of course, Second class takes 1 required
argument, not First.


Of course, it is possible to just try it one-by-one with a try block and 
a while loop (as long as your class/function doesn't rely/change on some 
global state (e.g. files, global variable, GUI, etc) while 
initializing/called), but if you really need that, there is something 
seriously wrong with the class/function design. You should check the 
help and determine how many and what are all the arguments meant.


In case you're wondering, this is how it would look like:

>>> def f0():
... print
...
>>> def f1(a):
... print a
...
>>> def f2(a, b):
... print a, b
...
>>> def f2a(a, b, *args, **kargs):
... print a, b, args, kargs
...
>>> import itertools
>>> funclist = [f0, f1, f2, f2a]
>>> for f in funclist:
... for i in itertools.count():
... try:
... f(*range(i))
... except TypeError:
... pass
... else:
... print 'Function %s takes %s required arguments' % 
(f.__name__, i)

... break
...

Function f0 takes 0 required arguments
0
Function f1 takes 1 required arguments
0 1
Function f2 takes 2 required arguments
0 1 () {}
Function f2a takes 2 required arguments
>>>
--
http://mail.python.org/mailman/listinfo/python-list


Re: Self function

2009-05-06 Thread Lie Ryan

Luis Zarrabeitia wrote:
Btw, is there any way to inject a name into a function's namespace? Following 
the python tradition, maybe we should try to create a more general solution!


How about a mechanism to pass arguments that are optional to accept?

So (in the general case) the caller can call a function with certain 
arguments, but unless the function explicitly accept it, the argument 
will be discarded.


With this, the injecting a local would simply be a case of adding an "I 
accept the argument" statement.



Sort of like this:

def func():
''' I reject '''
pass

func(@somearg='Feel free to accept this arg')

def func(@somearg):
''' I accept '''
print(somearg)

func(@somearg='Feel free to accept this arg')


Then on the case of injecting locals is simply by wrapping the function 
with a function that will inject various argument to the function and 
the function selectively choose which arguments they want to accept.


def needinfo(f):
# let's assume there is an inspect code here
func(@__name__=yournameis,
 @__call__=yourfunction,
 @__code__=yourcode,
 @__yoursub__=youryo,
 @__yourlim__=yoururso,
 @__yourina__=yournisk,
 @__yourlmes__=youridna,
 @__yoursage__=yourpped
)

@needinfo
def func(@__name__, @__call__):
print 'Hi, my name is %s and to call me press %s' % (__name__, 
__call__)


Does it sounds like a feature smell?
--
http://mail.python.org/mailman/listinfo/python-list


Re: object query assigned variable name?

2009-05-06 Thread Piet van Oostrum
> John O'Hagan  (JO) wrote:

>JO> I guess what I meant was that if I type:

>JO> brian = Brian()

>JO> in the python shell and then hit return, it seems to me that
>JO> _somewhere_ (in the interpreter? I have no idea how it's done) it
>JO> must be written that the new Brian object will later be assigned
>JO> the name "brian", even as the process of creating the instance
>JO> begins. As you've just demonstrated, the actual assignment occurs
>JO> afterwards.

No, that's not how it works. There is no `preparation' for the
assignment and there is no reason for it. Look at the generated
byte code for this Python code:

def test():
class Brian:
def __init__(self):
print "I'm Brian!"
brian = Brian()

2   0 LOAD_CONST   1 ('Brian')
  3 LOAD_CONST   3 (())
  6 LOAD_CONST   2 (", line 2>)
  9 MAKE_FUNCTION0
 12 CALL_FUNCTION0
 15 BUILD_CLASS 
 16 STORE_FAST   0 (Brian)

  5  19 LOAD_FAST0 (Brian)
 22 CALL_FUNCTION0
 25 STORE_FAST   1 (brian)
 28 LOAD_CONST   0 (None)
 31 RETURN_VALUE

You can see that the assignment (STORE_FAST) is done after the method
call (CALL_FUNCTION) and there is no reference to the variable name
before the call.

If you do a parallel assignment the relationship becomes even less:

brian, test = Brian(), 1

  5  19 LOAD_FAST0 (Brian)
 22 CALL_FUNCTION0
 25 LOAD_CONST   3 (1)
 28 ROT_TWO 
 29 STORE_FAST   1 (brian)
 32 STORE_FAST   2 (test)

-- 
Piet van Oostrum 
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: p...@vanoostrum.org
--
http://mail.python.org/mailman/listinfo/python-list


Re: Install Python 3.0 dmg to macos 10.5

2009-05-06 Thread Diez B. Roggisch
silverburgh wrote:

> Hi,
> 
> If I install python 3.0 dmg, will it wipe out the existing python
> installation on macos 10.5 (i don't know how the original python was
> installed ( i think it is version 2.5).

No. The original is under /System/Library/Frameworks/Python.framework (and
should be kept there & not touched), and other installs are
under /Library/Frameworks/Python.framework

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


Re: Checking for required arguments when instantiating class.

2009-05-06 Thread Piet van Oostrum
> Lacrima  (L) wrote:

>L> Hello!
>L> For example I have two classes:

> class First:
>L> def __init__(self, *args, **kwargs):
>L> pass

> class Second:
>L> def __init__(self, somearg, *args, **kwargs):
>L> self.somearg = somearg

>L> How can I test that First class takes 1 required argument and Second
>L> class takes no required arguments?
>L> So that I could instantiate them in a for loop.

> a = [First, Second]
> for cls in a:
>L> instance = cls()

>L> Traceback (most recent call last):
>L>   File "", line 2, in 
>L> instance = cls()
>L> TypeError: __init__() takes at least 2 arguments (1 given)

>L> Of course, I can do like this:
> for cls in a:
>L> try:
>L> instance = cls()
>L> except TypeError:
>L> instance = cls('hello')

> print instance.somearg
>L> hello

>L> But what if I have to instantiate any class with 3 or 4 required
>L> arguments? How can I do it?

cls.__init__.im_func.__code__.co_argcount

This will include self, so it will be 1 in First and 2 in Second.

However this is very dirty trickery and should not be recommended. It
may also change in future versions and other implementations of Python.

I think it would be cleaner to put a class attribute in the classes that
defines how they should be initialized (e.g. just the number of required
arguments or more specific information) or have a special factory method
for this use case.
-- 
Piet van Oostrum 
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: p...@vanoostrum.org
--
http://mail.python.org/mailman/listinfo/python-list


Re: Checking for required arguments when instantiating class.

2009-05-06 Thread Chris Rebert
On Wed, May 6, 2009 at 5:24 AM, Piet van Oostrum  wrote:
>> Lacrima  (L) wrote:
>
>>L> Hello!
>>L> For example I have two classes:
>
>> class First:
>>L>     def __init__(self, *args, **kwargs):
>>L>             pass
>
>> class Second:
>>L>     def __init__(self, somearg, *args, **kwargs):
>>L>             self.somearg = somearg
>
>>L> How can I test that First class takes 1 required argument and Second
>>L> class takes no required arguments?
>>L> So that I could instantiate them in a for loop.
>
>> a = [First, Second]
>> for cls in a:
>>L>     instance = cls()
>
>>L> Traceback (most recent call last):
>>L>   File "", line 2, in 
>>L>     instance = cls()
>>L> TypeError: __init__() takes at least 2 arguments (1 given)
>
>>L> Of course, I can do like this:
>> for cls in a:
>>L>     try:
>>L>             instance = cls()
>>L>     except TypeError:
>>L>             instance = cls('hello')
>
>> print instance.somearg
>>L> hello
>
>>L> But what if I have to instantiate any class with 3 or 4 required
>>L> arguments? How can I do it?
>
> cls.__init__.im_func.__code__.co_argcount
>
> This will include self, so it will be 1 in First and 2 in Second.

AFAICT, that would count non-required arguments too, which isn't
strictly what the OP requested.

> However this is very dirty trickery and should not be recommended. It
> may also change in future versions and other implementations of Python.

Very much agreed.

> I think it would be cleaner to put a class attribute in the classes that
> defines how they should be initialized (e.g. just the number of required
> arguments or more specific information) or have a special factory method
> for this use case.

Seconded. I'd recommend the latter personally, though it's impossible
to give a definitive answer without more context.

Cheers,
Chris
-- 
http://blog.rebertia.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: Self function

2009-05-06 Thread Aaron Brady
On May 6, 2:23 am, Arnaud Delobelle  wrote:
> On May 5, 10:20 pm, Aaron Brady  wrote:
>
> > def auto( f ):
> >     def _inner( *ar, **kw ):
> >         return f( _inner, *ar, **kw )
> >     return _inner
>
> Quoting myself near the start of this thread:
>
> Here's an idea:
>
> >>> def bindfunc(f):
>
> ...     def boundf(*args, **kwargs):
> ...         return f(boundf, *args, **kwargs)
> ...     return boundf
>
> --
> Arnaud

Yeah, but that was two days ago.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Self function

2009-05-06 Thread Aaron Brady
On May 6, 6:49 am, Lie Ryan  wrote:
> Luis Zarrabeitia wrote:
> > Btw, is there any way to inject a name into a function's namespace? 
> > Following
> > the python tradition, maybe we should try to create a more general solution!
>
> How about a mechanism to pass arguments that are optional to accept?
>
> So (in the general case) the caller can call a function with certain
> arguments, but unless the function explicitly accept it, the argument
> will be discarded.
>
> With this, the injecting a local would simply be a case of adding an "I
> accept the argument" statement.
snip

You could write a decorator to do that with the inspect module, or you
could just accept a keyword dict for extra as-desired args.
--
http://mail.python.org/mailman/listinfo/python-list


Re: object query assigned variable name?

2009-05-06 Thread Aaron Brady
On May 6, 12:56 am, John O'Hagan  wrote:
> On Tue, 5 May 2009, Sion Arrowsmith wrote:
> > John O'Hagan   wrote:
> > >I can see that it's tantalizing, though, because _somebody_ must know
> > > about the assignment; after all, we just executed it!
>
> > Except we haven't, if we're talking about reporting from the
>
> > object's __init__:
> > >>> class Brian:
>
> > ...     def __init__(self):
> > ...         print "I'm Brian!"
> > ...
>
> > >>> l = []
> > >>> l[1] = Brian()
>
> > I'm Brian!
> > Traceback (most recent call last):
> >   File "", line 1, in 
> > IndexError: list assignment index out of range
>
> > (Yeah, I know that's a setitem call not an assignment. Point stands.
> > It also demonstrates why the whole idea of "what name is a newly-
> > created object assigned to" is broken.)
>
> I guess what I meant was that if I type:
>
> brian = Brian()
>
> in the python shell and then hit return, it seems to me that _somewhere_ (in
> the interpreter? I have no idea how it's done) it must be written that the
> new Brian object will later be assigned the name "brian", even as the process
> of creating the instance begins. As you've just demonstrated, the actual
> assignment occurs afterwards.
>
> But even if this is true I'm guessing it'd be black magic to get to it.
>
> Regards,
>
> John

In principle, you can't get all the names an object is bound to, since
it might be a temporary value or member of a container at some time.
If it was in a dictionary, would you want its key?  Or sequence and
index?

Furthermore, we don't have a data structure for two-way lookup.
Sometimes you would want to lookup name by object, sometimes object by
name.

Lastly, it would make code significantly less readable .
--
http://mail.python.org/mailman/listinfo/python-list


Separate Windows versions of Python

2009-05-06 Thread OldGrantonian
I use Windows Vista Home Premium. I have Python 2.6 currently
installed. I'm not a techy.

I want to use "virtualenv". When I try to install the latest version
of virtualenv for Windows, I get the message that Python 2.5 is not
found.

How do I install Python 2.5 (or anything else except 2.6) so that I
use the correct version of Python at the correct time.

For example, do I need to edit the "path" variable each time that I
want to change versions from 2.5 to 2.6?
--
http://mail.python.org/mailman/listinfo/python-list


pyinstaller and logging

2009-05-06 Thread Mike
Pyinstaller seems to have a problem with logging ...

 I installed pyinstaller 1.3 - using it together with Python 2.6. I
used pyinstaller for a small project, the created .exe worked fine.
After some additional changes to my project I got strange run time
errors when running the .exe (but no problems when running the .py
file directly with the python interpreter). I stripped down my program
and tracked the problem down to the first log message being written.

So this is a stripped down version of the python script:

import logging
logging.basicConfig(level=logging.INFO,
format='%(asctime)-15s %(levelname)-8s %(message)
s',
datefmt='%Y-%m-%d %H:%M:%S',
filename="test1.log",
filemode='w')
print "written via print"
logging.info("written via logging")

when I start this from the python shell I am getting
   IDLE 2.6.2   No Subprocess 
   >>>
   written via print
   >>>
and test1.log contains
   2009-05-05 19:39:52 INFO written via logging
as expected.

When I start test1.exe I am getting

written via print
Traceback (most recent call last):
  File "", line 8, in 
  File "c:\dokumente und einstellungen\dieter\eigene dateien\collector
\v0r0m2\buildtest1\out1.pyz/logging", line 1451, in info
  File "c:\dokumente und einstellungen\dieter\eigene dateien\collector
\v0r0m2\buildtest1\out1.pyz/logging", line 1030, in info
  File "c:\dokumente und einstellungen\dieter\eigene dateien\collector
\v0r0m2\buildtest1\out1.pyz/logging", line 1142, in _log
  File "c:\dokumente und einstellungen\dieter\eigene dateien\collector
\v0r0m2\buildtest1\out1.pyz/logging", line 1117, in makeRecord
  File "c:\dokumente und einstellungen\dieter\eigene dateien\collector
\v0r0m2\buildtest1\out1.pyz/logging", line 272, in __init__
  File "C:\Programme\pyinstaller-1.3\iu.py", line 312, in importHook
mod = _self_doimport(nm, ctx, fqname)
  File "C:\Programme\pyinstaller-1.3\iu.py", line 398, in doimport
exec co in mod.__dict__
  File "c:\dokumente und einstellungen\dieter\eigene dateien\collector
\v0r0m2\buildtest1\out1.pyz/multiprocessing", line 83, in 
  File "C:\Programme\pyinstaller-1.3\iu.py", line 312, in importHook
mod = _self_doimport(nm, ctx, fqname)
  File "C:\Programme\pyinstaller-1.3\iu.py", line 382, in doimport
mod = director.getmod(nm)
  File "C:\Programme\pyinstaller-1.3\iu.py", line 215, in getmod
mod = owner.getmod(nm)
  File "C:\Programme\pyinstaller-1.3\iu.py", line 77, in getmod
mod = imp.load_module(nm, fp, attempt, (ext, mode, typ))
TypeError: importHook() takes at most 5 arguments (6 given)

What am I doing wrong?
--
http://mail.python.org/mailman/listinfo/python-list


Re: problem in using sendmail in multi thread

2009-05-06 Thread Jean-Paul Calderone

On Tue, 5 May 2009 22:17:35 -0700 (PDT), gganesh  wrote:

On May 5, 9:25 pm, Piet van Oostrum  wrote:

> gganesh  (g) wrote:
>g> hi,
>g> I'm a beginner in using Python script
>g> I'm trying to send mails using multi-thread
>g> I wrote
>g> FROM = 'ganeshx...@.com'
>g> # for more mail add';' the another mail id
>g> listTo = ['g@gmail.com', 'xxjango...@gmail.com',
>g> 'xx...@yahoo.co.in']
>g> SUBJECT = 'This is the subject'
>g> MSGBODY = 'This the body of the message '
>g> MAILSERVER = 'mail..com'
>g> port = 25
>g> username = 'x'
>g> password = 'x'
>g> # trim the strings of any leading or trailing spaces
>g> FROM = FROM.strip()
>g> SUBJECT = SUBJECT.strip()
>g> MSGBODY = MSGBODY.strip()
>g> MAILSERVER = MAILSERVER.strip()
>g> username = username.strip()
>g> password = password.strip()
>g> #Connect to server
>g> print 'Connecting to mail server ', MAILSERVER
>g> try:
>g>       s = smtplib.SMTP(MAILSERVER,port)

You can't have a single SMTP connection that's used in multiple threads.
That is what causes the error. Each thread should have its own SMTP
connection. So move this code (above and below) into the run() method.

>g>       print 'connected'
>g> #s.set_debuglevel(1)
>g> except:
>g>        print 'ERROR: Unable to connect to mail server', sys.exc_info  ()[0]
>g>        sys.exit(1)
>g> #login to server
>g> if password <> '':
>g>       print 'Logging into mail server'

I think this try except block should be inside the if statement, i.e.
indented 4 spaces.

>g> try:
>g>       s.login(username,password)
>g> except:
>g>       print 'ERROR: Unable to login to mail server', MAILSERVER
>g>       print 'Please recheck your password'
>g>       sys.exit(1)
>g> #--
>g> print "Starting Multi Thread Method"
>g> class MyThread(Thread):
>g>     def __init__(self, site, s, FROM, MSGBODY):
>g>         Thread.__init__(self)
>g>         self.site = site
>g>       self.s=s
>g>       self.FROM=FROM
>g>       self.MSGBODY=MSGBODY

You give the s (connection) here as a parameter, store it in self.s and
never use that attribute.

>g>     def run(self):
>g>       print "running for %s " %self.site
>g>       s.sendmail(self.FROM, self.site, self.MSGBODY)

Here you use the global s, not self.s

As I said above you should do the SMTP connection setup, including the
login, here, and store the connection either in self.s or in a local
variable s in the method. As you don't use the s in another method, I
think a local variable is better.

>g>       print "Emailed for  site %s" %self.site
>g> a= time.time()
>g> threads = []
>g> for site in listTo:
>g>     T = MyThread(site,s,FROM,MSGBODY)
>g>     threads.append(T)
>g>     T.start()
>g> for i in threads:
>g>     i.join()

Of course the next 2 lines should also be moved to run().

>g> s.quit()
>g> s.close()
>g> print "Took %s seconds" %str(time.time()-a)
>g> #-

--
Piet van Oostrum 
URL:http://pietvanoostrum.com[PGP 8DAE142BE17999C4]
Private email: p...@vanoostrum.org



Thanks Everyone By your guidance the code worked fine
I can send mails in multi threaded environment.
Is this only way to send mails concurrently  or any other method
aviable?


Here's another way:

   from twisted.mail.smtp import sendmail
   from twisted.internet import reactor
   from twisted.python.log import err

   MAILSERVER = ...
   listTo = [...]
   FROM = ...
   MSGBODY = ...

   done = sendmail(MAILSERVER, FROM, listTo, MSGBODY)
   done.addErrback(err)
   done.addCallback(lambda ignored: reactor.stop())
   reactor.run()

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


Control a process interactively (pexpect) and save data

2009-05-06 Thread Piotrek G.

Hi,

I'm trying to use something like pexpect.interact() but I want to save 
all my inputs and save all outputs from the process (/bin/sh Linux).
The main goal is to record all sequence of commands and responses in 
order to automatically generate pexpect script.


My script is like below so far, but I'm unable to print responses to 
stdout and save it to variables/files/whatever.


p = pexpect.spawn('/bin/sh')
print "PID: " + str(p.pid)
p.logfile = sys.stdout
while True:
if not p.isalive():
print "Not alive"
break
else:
print "Alive!"
p.flush()
bb = sys.stdin.readline()
p.sendline(bb)
sys.exit(0)

pexpect.interact() doesn't allow to save input and output.

I tried pipes but I've found that "Don't use a pipe to control another 
application..." - http://edgysoftware.com/doc/python-pexpect/doc/


I tried subprocess module but it didn't allow me to control /bin/sh as 
communicate() method do as follows
"Interact with process: Send data to stdin. Read data from stdout and 
stderr, until end-of-file is reached. Wait for process to terminate. The 
optional input argument should be a string to be sent to the child 
process, or None, if no data should be sent to the child."


So it "waits for process to terminate" and I'm unable to interact...

Any suggestions?

Oh, and by the way my script works with /bin/sh but doesn't work with 
/bin/bash. If I enter 'exit' sh exits, bash does not... Why?


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


Re: python docs for beginner programmer?

2009-05-06 Thread Aahz
In article <81f82d8c-80fa-4ba0-a402-3a8b5757a...@s16g2000vbp.googlegroups.com>,
Deep_Feelings   wrote:
>
>anyone did that ? learning from python docs straight away ?

Yes.  Admittedly that was ten years ago and the docs have improved some
since then
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

"It is easier to optimize correct code than to correct optimized code."
--Bill Harlan
--
http://mail.python.org/mailman/listinfo/python-list


Re: list comprehension question

2009-05-06 Thread Boris Borcic

Ross wrote:

If I have a list of tuples a = [(1,2), (3,4), (5,6)], and I want to
return a new list of each individual element in these tuples, I can do
it with a nested for loop but when I try to do it using the list
comprehension b = [j for j in i for i in a], my output is b =
[5,5,5,6,6,6] instead of the correct b = [1,2,3,4,5,6]. What am I
doing wrong?
--
http://mail.python.org/mailman/listinfo/python-list



just fyi, in python 2.6

list(itertools.chain.from_iterable(a))

would do it

in python 2.5

list(itertools.chain(*a))

would do it too, but I wouldn't try it with arbitrarily long a





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


Re: pyc files problem

2009-05-06 Thread Scott David Daniels

Dave Angel wrote:

Gabriel Genellina wrote: ...

06 May 2009 00:43:25 -0300, Mohamed Lrhazi  escribió:

My code sends a pointer to a Python function to a C library, using
ctypes module. When my program restarts, after a crash or normal
exit... it cannot start again without sigfaulting


Do you mean that, if you delete the .pyc files your program runs 
properly, but if you keep the .pyc files your program crashes?

That's very strange...


1) Is it true (as Gabriel asks) that deleting the .pyc files solves the 
problem?
2) If so, have you investigated to see which one of them gets 
corrupted?  This isn't necessarily the problem, it could also be timing, 
or related to the order of the memory allocation pool.
3) When you get the segment fault, what does you C debugger show?  
What's happening at the time of the crash?

4) Is either the C code or the Python code multithreaded?
5) Are you running it under a Python debugger?


Could this have to do with a manifest floating point constant
being a "Not A Number" or "Infinity"?  That is the last .pyc-
related problem I know about.

To the original poster:
Please give a _lot_ more detail about the full Python version,
OS type and version, and so on.  Otherwise, it becomes
tempting to say, "that is too bad, sorry you have troubles."
One way to isolate the problem (if it is, indeed .pyc-loading
related) is to delete individual .pyc files until you find the
suspect, then cut that one in pieces and re-isolate until you
have a small bit of code with the issue.  This is why we point
people to smart-questions(*) so often.

(*) http://www.catb.org/~esr/faqs/smart-questions.html

--Scott David Daniels
scott.dani...@acm.org
--
http://mail.python.org/mailman/listinfo/python-list


Re: python docs for beginner programmer?

2009-05-06 Thread Michele Simionato
On May 5, 10:37 pm, Deep_Feelings  wrote:
> that is good ,thank you
>
> anyone did that ? learning from python docs straight away ?

A lot of people did. I did, but I usually prefer reading user manuals
over books, and YMMV.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Separate Windows versions of Python

2009-05-06 Thread Scott David Daniels

OldGrantonian wrote:

I use Windows Vista Home Premium. I have Python 2.6 currently
installed. I'm not a techy.

I want to use "virtualenv". When I try to install the latest version
of virtualenv for Windows, I get the message that Python 2.5 is not
found.

How do I install Python 2.5 (or anything else except 2.6) so that I
use the correct version of Python at the correct time.

For example, do I need to edit the "path" variable each time that I
want to change versions from 2.5 to 2.6?


On windows, major versions (..., 2.5, 2.6, 2.7, , 3.0, 3.1,  ...)
can coexist quite successfully.  Find and run an installer for the
latest version  of 2.5 (2.5.4, I believe) on the Python download page.
That will make 2.5 your default Python.  To switch the easiest way
(for you) is uninstall the version of python you want to be the
default, then install it again (making it the last one installed).
This suggests keeping installer binaries for all version you are
using.  Note that the this uninstall-reinstall should not affect
you loaded Python packages that you have installed separately.
To simply run a python program with a different python (but not
change the default), open a command window (run program / cmd),
sometimes called a "terminal window" and use command:
C:\> C:\Python24\python program.py  # command line version
or
C:\> C:\Python24\pythonw program.pyw  # gui verson
You can also change shortcuts to refer to specific Python versions.

Of course, the different Python versions should also be available
on your start menu.

However, Starting with Python 2.6, if you want user-specific
installation, you can also create and put things in (for example),
C:\Documents and Settings\USER\Application Data\
Python\Python26\site-packages
where you replace USER with the user name in question.

If you are not planning to do a lot of switching, that might be
enough for you.  The base directory is also called %APPDATA% on
a command line or via os.path.expandvars.  Once you have created
this site-packages directory, Python 2.6 and later will use it to
find .pth, .py, .pyw, and .pyd files (as well as .pyc and .pyo
files).  You may find changing your personal site-packages directory
(and/or a .pth therein that you manipulate) will address the issues
that you are planning to solve with virtualenv.

Sorry for the long-winded answer.
--Scott David Daniels
scott.dani...@acm.org


in addition to the common site-packages directory on
--
http://mail.python.org/mailman/listinfo/python-list


Pyhton script to call another program

2009-05-06 Thread Ben Keshet

Hi,

I am trying to write a simple python script to manipulate files and call 
other programs.  I have a program installed (rocs) which I run using 
cygwin on my XP (but is not in python).  Can I run the pyhton script and 
then call the other program in the same script?


For example:
Python Code  # this line opens a file
Python Code  # this line splits the file into 4 different files
rocs  # this line calls the program 'rocs' to run on the newly formed files
Python Code # this line renames rocs output files and saves them in the 
right place.


Otherwise, I would have to write two scripts (before and after 'rocs'), 
and run the 3 scripts/programs separately. 

I am relatively new to python and don't know a lot about cygwin.  Please 
remember that if you try to answer me :) Thanks!

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


Re: Pyhton script to call another program

2009-05-06 Thread Diez B. Roggisch
Ben Keshet wrote:

> Hi,
> 
> I am trying to write a simple python script to manipulate files and call
> other programs.  I have a program installed (rocs) which I run using
> cygwin on my XP (but is not in python).  Can I run the pyhton script and
> then call the other program in the same script?
> 
> For example:
> Python Code  # this line opens a file
> Python Code  # this line splits the file into 4 different files
> rocs  # this line calls the program 'rocs' to run on the newly formed
> files Python Code # this line renames rocs output files and saves them in
> the right place.
> 
> Otherwise, I would have to write two scripts (before and after 'rocs'),
> and run the 3 scripts/programs separately.
> 
> I am relatively new to python and don't know a lot about cygwin.  Please
> remember that if you try to answer me :) Thanks!

Check out the module "subprocess" in the standard library documentation.
This will allow you to call other programs.

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


Re: pyinstaller and logging

2009-05-06 Thread Vinay Sajip
On May 6, 2:41 pm, Mike  wrote:
> Pyinstaller seems to have a problem withlogging...
>
>  I installed pyinstaller 1.3 - using it together with Python 2.6. I
> used pyinstaller for a small project, the created .exe worked fine.
> After some additional changes to my project I got strange run time
> errors when running the .exe (but no problems when running the .py
> file directly with the python interpreter). I stripped down my program
> and tracked the problem down to the first log message being written.
>
> So this is a stripped down version of the python script:
>
> importlogginglogging.basicConfig(level=logging.INFO,
> format='%(asctime)-15s %(levelname)-8s %(message)
> s',
> datefmt='%Y-%m-%d %H:%M:%S',
> filename="test1.log",
> filemode='w')
> print "written via print"logging.info("written vialogging")
>
> when I start this from the python shell I am getting
>IDLE 2.6.2   No Subprocess 
>>>>
>written via print
>>>>
> and test1.log contains
>2009-05-05 19:39:52 INFO written vialogging
> as expected.
>
> When I start test1.exe I am getting
>
> written via print
> Traceback (most recent call last):
>   File "", line 8, in 
>   File "c:\dokumente und einstellungen\dieter\eigene dateien\collector
> \v0r0m2\buildtest1\out1.pyz/logging", line 1451, in info
>   File "c:\dokumente und einstellungen\dieter\eigene dateien\collector
> \v0r0m2\buildtest1\out1.pyz/logging", line 1030, in info
>   File "c:\dokumente und einstellungen\dieter\eigene dateien\collector
> \v0r0m2\buildtest1\out1.pyz/logging", line 1142, in _log
>   File "c:\dokumente und einstellungen\dieter\eigene dateien\collector
> \v0r0m2\buildtest1\out1.pyz/logging", line 1117, in makeRecord
>   File "c:\dokumente und einstellungen\dieter\eigene dateien\collector
> \v0r0m2\buildtest1\out1.pyz/logging", line 272, in __init__
>   File "C:\Programme\pyinstaller-1.3\iu.py", line 312, in importHook
> mod = _self_doimport(nm, ctx, fqname)
>   File "C:\Programme\pyinstaller-1.3\iu.py", line 398, in doimport
> exec co in mod.__dict__
>   File "c:\dokumente und einstellungen\dieter\eigene dateien\collector
> \v0r0m2\buildtest1\out1.pyz/multiprocessing", line 83, in 
>   File "C:\Programme\pyinstaller-1.3\iu.py", line 312, in importHook
> mod = _self_doimport(nm, ctx, fqname)
>   File "C:\Programme\pyinstaller-1.3\iu.py", line 382, in doimport
> mod = director.getmod(nm)
>   File "C:\Programme\pyinstaller-1.3\iu.py", line 215, in getmod
> mod = owner.getmod(nm)
>   File "C:\Programme\pyinstaller-1.3\iu.py", line 77, in getmod
> mod = imp.load_module(nm, fp, attempt, (ext, mode, typ))
> TypeError: importHook() takes at most 5 arguments (6 given)
>
> What am I doing wrong?

Apparently, PyInstaller only supports versions of Python between 1.5
and 2.4:

http://www.pyinstaller.org/#Requirements

So, you are using it in an unsupported environment. I see you've cross-
posted this to the PyInstaller mailing list:

http://groups.google.com/group/PyInstaller

I hope someone on that list can help. An additional bit of information
from your traceback is that line 272 in 2.6's logging/__init__.py is
one that says "from multiprocessing import current_process". As this
line is only executed if logging.logMultiProcessing is set, you may be
able to work around by setting logging.logMultiProcessing to False in
your app initialisation. Of course, this might just result in a
failure somewhere else...

Regards,

Vinay Sajip


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


Re: thc v0.3 - txt to html converter - better code?

2009-05-06 Thread Florian Wollenschein

Richard Brodie wrote:
"Stefan Behnel"  wrote in message 
news:4a008996$0$31862$9b4e6...@newsspool3.arcor-online.net...



   language_map = {'English': 'EN', 'Deutsch': 'DE'}
   strict_or_transitional = {True: 'Transitional', False: 'Strict'}

   # this will raise a KeyError for unknown languages
   language = language_map[ self.cmboBoxLang.currentText() ]

   # this assumes that isChecked() returns True or False
   spec = strict_or_transitional[self.rdioBtnTransitional.isChecked()]

   doctype = '\n' % (
   spec, language)


Incidentally, the language in an HTML DOCTYPE refers to the language of the 
DTD, not
the document. It's never correct to use //DE in an HTML page, unless you have a 
custom
(German) DTD. So the code can be improved further by cutting that part out.

strict_or_transitional = {True: 'Transitional', False: 'Strict'}

# this assumes that isChecked() returns True or False
spec = strict_or_transitional[self.rdioBtnTransitional.isChecked()]

doctype = '\n' % spec





Yes, that's true. I missed that. Thanks for the information.
And many thanks to Stefan.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Separate Windows versions of Python

2009-05-06 Thread OldGrantonian
Many thanks for the very detailed answer :)

I will go ahead right now and implement all your suggestions.




On May 6, 4:35 pm, Scott David Daniels  wrote:
> OldGrantonian wrote:
> > I use Windows Vista Home Premium. I have Python 2.6 currently
> > installed. I'm not a techy.
>
> > I want to use "virtualenv". When I try to install the latest version
> > of virtualenv for Windows, I get the message that Python 2.5 is not
> > found.
>
> > How do I install Python 2.5 (or anything else except 2.6) so that I
> > use the correct version of Python at the correct time.
>
> > For example, do I need to edit the "path" variable each time that I
> > want to change versions from 2.5 to 2.6?
>
> On windows, major versions (..., 2.5, 2.6, 2.7, , 3.0, 3.1,  ...)
> can coexist quite successfully.  Find and run an installer for the
> latest version  of 2.5 (2.5.4, I believe) on the Python download page.
> That will make 2.5 your default Python.  To switch the easiest way
> (for you) is uninstall the version of python you want to be the
> default, then install it again (making it the last one installed).
> This suggests keeping installer binaries for all version you are
> using.  Note that the this uninstall-reinstall should not affect
> you loaded Python packages that you have installed separately.
> To simply run a python program with a different python (but not
> change the default), open a command window (run program / cmd),
> sometimes called a "terminal window" and use command:
>      C:\> C:\Python24\python program.py  # command line version
> or
>      C:\> C:\Python24\pythonw program.pyw  # gui verson
> You can also change shortcuts to refer to specific Python versions.
>
> Of course, the different Python versions should also be available
> on your start menu.
>
> However, Starting with Python 2.6, if you want user-specific
> installation, you can also create and put things in (for example),
>      C:\Documents and Settings\USER\Application Data\
>                              Python\Python26\site-packages
> where you replace USER with the user name in question.
>
> If you are not planning to do a lot of switching, that might be
> enough for you.  The base directory is also called %APPDATA% on
> a command line or via os.path.expandvars.  Once you have created
> this site-packages directory, Python 2.6 and later will use it to
> find .pth, .py, .pyw, and .pyd files (as well as .pyc and .pyo
> files).  You may find changing your personal site-packages directory
> (and/or a .pth therein that you manipulate) will address the issues
> that you are planning to solve with virtualenv.
>
> Sorry for the long-winded answer.
> --Scott David Daniels
> scott.dani...@acm.org
>
> in addition to the common site-packages directory on

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


Re: Problem with case insensitive volumes

2009-05-06 Thread spillz
On May 5, 10:24 pm, "Gabriel Genellina" 
wrote:
> I use this function on Windows to obtain the true case name of a file:

very nice. I think the python bindings to the gnome GIO library
*might* provide what I need on the linux side.
--
http://mail.python.org/mailman/listinfo/python-list


Re: pyinstaller and logging

2009-05-06 Thread Mike
On 6 Mai, 18:14, Vinay Sajip  wrote:
> On May 6, 2:41 pm, Mike  wrote:
>
>
>
> > Pyinstaller seems to have a problem withlogging...
>
> >  I installed pyinstaller 1.3 - using it together with Python 2.6. I
> > used pyinstaller for a small project, the created .exe worked fine.
> > After some additional changes to my project I got strange run time
> > errors when running the .exe (but no problems when running the .py
> > file directly with the python interpreter). I stripped down my program
> > and tracked the problem down to the first log message being written.
>
> > So this is a stripped down version of the python script:
>
> > importlogginglogging.basicConfig(level=logging.INFO,
> >                     format='%(asctime)-15s %(levelname)-8s %(message)
> > s',
> >                     datefmt='%Y-%m-%d %H:%M:%S',
> >                     filename="test1.log",
> >                     filemode='w')
> > print "written via print"logging.info("written vialogging")
>
> > when I start this from the python shell I am getting
> >            IDLE 2.6.2       No Subprocess 
>
> >            written via print
>
> > and test1.log contains
> >            2009-05-05 19:39:52 INFO     written vialogging
> > as expected.
>
> > When I start test1.exe I am getting
>
> > written via print
> > Traceback (most recent call last):
> >   File "", line 8, in 
> >   File "c:\dokumente und einstellungen\dieter\eigene dateien\collector
> > \v0r0m2\buildtest1\out1.pyz/logging", line 1451, in info
> >   File "c:\dokumente und einstellungen\dieter\eigene dateien\collector
> > \v0r0m2\buildtest1\out1.pyz/logging", line 1030, in info
> >   File "c:\dokumente und einstellungen\dieter\eigene dateien\collector
> > \v0r0m2\buildtest1\out1.pyz/logging", line 1142, in _log
> >   File "c:\dokumente und einstellungen\dieter\eigene dateien\collector
> > \v0r0m2\buildtest1\out1.pyz/logging", line 1117, in makeRecord
> >   File "c:\dokumente und einstellungen\dieter\eigene dateien\collector
> > \v0r0m2\buildtest1\out1.pyz/logging", line 272, in __init__
> >   File "C:\Programme\pyinstaller-1.3\iu.py", line 312, in importHook
> >     mod = _self_doimport(nm, ctx, fqname)
> >   File "C:\Programme\pyinstaller-1.3\iu.py", line 398, in doimport
> >     exec co in mod.__dict__
> >   File "c:\dokumente und einstellungen\dieter\eigene dateien\collector
> > \v0r0m2\buildtest1\out1.pyz/multiprocessing", line 83, in 
> >   File "C:\Programme\pyinstaller-1.3\iu.py", line 312, in importHook
> >     mod = _self_doimport(nm, ctx, fqname)
> >   File "C:\Programme\pyinstaller-1.3\iu.py", line 382, in doimport
> >     mod = director.getmod(nm)
> >   File "C:\Programme\pyinstaller-1.3\iu.py", line 215, in getmod
> >     mod = owner.getmod(nm)
> >   File "C:\Programme\pyinstaller-1.3\iu.py", line 77, in getmod
> >     mod = imp.load_module(nm, fp, attempt, (ext, mode, typ))
> > TypeError: importHook() takes at most 5 arguments (6 given)
>
> > What am I doing wrong?
>
> Apparently, PyInstaller only supports versions of Python between 1.5
> and 2.4:
>
> http://www.pyinstaller.org/#Requirements
>
> So, you are using it in an unsupported environment. I see you've cross-
> posted this to the PyInstaller mailing list:
>
> http://groups.google.com/group/PyInstaller
>
> I hope someone on that list can help. An additional bit of information
> from your traceback is that line 272 in 2.6's logging/__init__.py is
> one that says "from multiprocessing import current_process". As this
> line is only executed if logging.logMultiProcessing is set, you may be
> able to work around by setting logging.logMultiProcessing to False in
> your app initialisation. Of course, this might just result in a
> failure somewhere else...
>
> Regards,
>
> Vinay Sajip

Shame on me - I somehow skipped the requirement from pyinstaller just
supporting python between 1.5 and 2.4 ... - thanks for your help - I
was aware it is not supporting python 3.0 (I searched a tool
creating .exes for Python 3.0 in the first place). I googled around
and found some recommendations for pyinstaller, but with the
restriction "it is just supporting the latest version of 2.x but not
3.0 of python". I never double checked on the formal requirements on
the pyinstaller site... .

Your hint regarding logging.logMultiProcessing=False did not change
the problem. As I do not want to switch to python 2.4 I will have to
look for something else. I tried py2exe today, which seems to work
fine for my project (and officially supports python 2.6 ;-) ) - it is
able to create an exe file within a dist directory, but not a single
executable like pyinstaller is doing it. But this is fine enough for
me just now.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Pyhton script to call another program

2009-05-06 Thread norseman

Ben Keshet wrote:

Hi,

I am trying to write a simple python script to manipulate files and call 
other programs.  I have a program installed (rocs) which I run using 
cygwin on my XP (but is not in python).  Can I run the pyhton script and 
then call the other program in the same script?


For example:
Python Code  # this line opens a file
Python Code  # this line splits the file into 4 different files
rocs  # this line calls the program 'rocs' to run on the newly formed files
Python Code # this line renames rocs output files and saves them in the 
right place.


Otherwise, I would have to write two scripts (before and after 'rocs'), 
and run the 3 scripts/programs separately.
I am relatively new to python and don't know a lot about cygwin.  Please 
remember that if you try to answer me :) Thanks!

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


==
If you don't like a lot of typing that obscures the process,
take a look at the spawn family.


 processPython 2.5.2 (r252:60911, Mar  4 2008, 10:40:55)
[GCC 3.3.6] on linux2
Type "help", "copyright", "credits" or "license" for more information.

>>> import os
>>> AbWd = os.spawnlp( os.P_WAIT,"abiword","abiword","")

The P_WAIT stops python until the program (abiword in this case) 
completes.  The "" at the end are for tokens to be given to the program 
and yes - contrary to manual, the program MUST be there TWICE (complete 
with any path needed).


for windows this works:
(can't cut and paste from a dos box!###%*&!!!)

Python 2.5.1 ... on win32
>>> import os
>>> result = os.spawnl( os.P_WAIT, "d:\\winmcad\\mcad","")

Runs the program mcad. Returns to python when mcad exits.


Today: 20090506
Python ver as snippets show.
OS is Linux Slackware 10.2
OS is Windows XP Pro

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


Re: Copy & Paste in a Dos box (was: Pyhton script to call another program)

2009-05-06 Thread Tim Chase

for windows this works:
(can't cut and paste from a dos box!###%*&!!!)


Depending on how it was spawned, you can either right-click in 
the window and choose Mark/Paste (when marking, use  to 
terminate the selection; and selections are blockwise rectangular 
rather than linewise or characterwise).  Alternatively, if you 
click on the system menu (the icon in the title-bar with 
resize/minimize/maximize/close/help), there should be an Edit 
submenu with the same options within.


A pain, but at least feasible.

HTH,

-tkc




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


Re: Pyhton script to call another program

2009-05-06 Thread David
Il Wed, 06 May 2009 11:31:58 -0400, Ben Keshet ha scritto:

> Hi,
> 
> I am trying to write a simple python script to manipulate files and call 
> other programs.  I have a program installed (rocs) which I run using 
> cygwin on my XP (but is not in python).  Can I run the pyhton script and 
> then call the other program in the same script?

Look at the os.system function call.

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


hex(dummy)[2:] - issue...

2009-05-06 Thread Florian Wollenschein

Hi there,

I need some advice :-)
I'm using hex(dummy)[2:] to represent a color in hexadecimal format for 
the bgcolor in an html file. dummy is the color value in RGB of course...


Now, if there's an R, G or B value of zero, this command only prints one 
single 0 instead of two. What's wrong with the code?


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


IIR filter conversion routines for Python?

2009-05-06 Thread wzab
Hi,
I'm looking for procedures converting the IIR filters into cascade and/
or parallel forms. Something like dir2cas.m or dir2par.m known in the
Matlab/Octave world.
Unfortunately SciPy does not contain such functions.
If they are not available, I would be grateful for any hints helping
me to implement them myself.
--
TIA, BR,
WZab
--
http://mail.python.org/mailman/listinfo/python-list


Re: Copy & Paste in a Dos box (was: Pyhton script to call another program)

2009-05-06 Thread Shawn Milochik
On Wed, May 6, 2009 at 1:54 PM, Tim Chase  wrote:
>> for windows this works:
>> (can't cut and paste from a dos box!###%*&!!!)
>
> Depending on how it was spawned, you can either right-click in the window
> and choose Mark/Paste (when marking, use  to terminate the selection;
> and selections are blockwise rectangular rather than linewise or
> characterwise).  Alternatively, if you click on the system menu (the icon in
> the title-bar with resize/minimize/maximize/close/help), there should be an
> Edit submenu with the same options within.
>
> A pain, but at least feasible.


I know I'm coming to the conversation late, but here's what I do*:

1. Use Cygwin. (http://www.cygwin.com/)
2. Use PuttyCYG (http://code.google.com/p/puttycyg/)

That way, you can basically use PuTTY to shell into your Windows box.

Note: If you are familiar with the Linux command line, you will be in
love with this solution. If you're a Windows-only type, then be
forewarned that doing this will require you to type Unix/Linux
commands (for the most part) instead of DOS commands.

*Disclaimer: I use a Mac and Linux. This is my workaround when forced
to use Windows. Your environment preferences may vary.
--
http://mail.python.org/mailman/listinfo/python-list


Re: hex(dummy)[2:] - issue...

2009-05-06 Thread MRAB

Florian Wollenschein wrote:

Hi there,

I need some advice :-)
I'm using hex(dummy)[2:] to represent a color in hexadecimal format for 
the bgcolor in an html file. dummy is the color value in RGB of course...


Now, if there's an R, G or B value of zero, this command only prints one 
single 0 instead of two. What's wrong with the code?



hex() returns '0x' followed by no more digits than are necessary:

>>> hex(0xFF)
'0xff'
>>> hex(0xF)
'0xf'

Try "%02X" instead (it'll pad with leading zeros up to a width of 2):

>>> "%02X" % 0xFF
'FF'
>>> "%02X" % 0xF
'0F'

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


Re: Iphone Going 3G!

2009-05-06 Thread stermen

Notebooks stocks priced

http://rover.ebay.com/rover/1/711-53200-19255-0/1?type=3&campid=5336229480&toolid=10001&customid=&ext=notebook&satitle=notebook











"Shafiq"  ha scritto nel messaggio 
news:4908115...@news.tm.net.my...

apalah kau ni tak belajar ke bahasa menunjukkan bangsa
"news.tm.net.my"  wrote in message 
news:48df149...@news.tm.net.my...

relic wrote:

fizzi wrote:

For the Iphone lovers out there,


Wrong group. No weirdos here.

testtt





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


Parsing text

2009-05-06 Thread iainemsley
Hi,
I'm trying to write a fairly basic text parser to split up scenes and
acts in plays to put them into XML. I've managed to get the text split
into the blocks of scenes and acts and returned correctly but I'm
trying to refine this and get the relevant scene number when the split
is made but I keep getting an NoneType error trying to read the block
inside the for loop and nothing is being returned. I'd be grateful for
some suggestions as to how to get this working.

for scene in text.split('Scene'):
num = re.compile("^\s\[0-9, i{1,4}, v]", re.I)
textNum = num.match(scene)
if textNum:
print textNum
else:
print "No scene number"
m = 'http://mail.python.org/mailman/listinfo/python-list


Re: Copy & Paste in a Dos box (was: Pyhton script to call another program)

2009-05-06 Thread Grant Edwards
On 2009-05-06, Shawn Milochik  wrote:

> I know I'm coming to the conversation late, but here's what I do*:
>
> 1. Use Cygwin. (http://www.cygwin.com/)
> 2. Use PuttyCYG (http://code.google.com/p/puttycyg/)
>
> That way, you can basically use PuTTY to shell into your
> Windows box.

Better yet, set up sshd in your Cygwin install, and then use
whatever terminal you normally use on your Linux/MacOS box to
ssh into the Cygwin box.  When run that way, windows is almost
usable...

-- 
Grant Edwards   grante Yow! Oh, I get it!!
  at   "The BEACH goes on", huh,
   visi.comSONNY??
--
http://mail.python.org/mailman/listinfo/python-list


Re: Copy & Paste in a Dos box (was: Pyhton script to call another program)

2009-05-06 Thread Shawn Milochik
On Wed, May 6, 2009 at 2:39 PM, Grant Edwards  wrote:
> On 2009-05-06, Shawn Milochik  wrote:
>
>> I know I'm coming to the conversation late, but here's what I do*:
>>
>> 1. Use Cygwin. (http://www.cygwin.com/)
>> 2. Use PuttyCYG (http://code.google.com/p/puttycyg/)
>>
>> That way, you can basically use PuTTY to shell into your
>> Windows box.
>
> Better yet, set up sshd in your Cygwin install, and then use
> whatever terminal you normally use on your Linux/MacOS box to
> ssh into the Cygwin box.  When run that way, windows is almost
> usable...
>
> --
> Grant Edwards



True, but when I'm using Cygwin, that means I'm at work and don't have
a non-MS OS available. Of course I can open an ssh session to my home
machine for sanity (or kicking off a torrent download at home), but I
don't have a *nix-based OS at the day job. Lanching DSL embedded to
use the terminal seems a bit much. ^_^

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


Re: Parsing text

2009-05-06 Thread Shawn Milochik
On Wed, May 6, 2009 at 2:32 PM, iainemsley  wrote:
> Hi,
> I'm trying to write a fairly basic text parser to split up scenes and
> acts in plays to put them into XML. I've managed to get the text split
> into the blocks of scenes and acts and returned correctly but I'm
> trying to refine this and get the relevant scene number when the split
> is made but I keep getting an NoneType error trying to read the block
> inside the for loop and nothing is being returned. I'd be grateful for
> some suggestions as to how to get this working.
>
> for scene in text.split('Scene'):
>    num = re.compile("^\s\[0-9, i{1,4}, v]", re.I)
>    textNum = num.match(scene)
>    if textNum:
>        print textNum
>    else:
>        print "No scene number"
>    m = '%s' % (scene,)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Parsing text

2009-05-06 Thread Scott David Daniels

iainemsley wrote:

Hi,
I'm trying to write a fairly basic text parser to split up scenes and
acts in plays to put them into XML. I've managed to get the text split
into the blocks of scenes and acts and returned correctly but I'm
trying to refine this and get the relevant scene number when the split
is made but I keep getting an NoneType error trying to read the block
inside the for loop and nothing is being returned. I'd be grateful for
some suggestions as to how to get this working.

...(some code)...


You'll get a lot better help if you:
(1) Include enough code to run and encounter the problem.
Edit this down to something small (in the process,
you may discover what was wrong).
(2) Include actual sample data demonstrating the problem.
and (3) Cut and paste the _actual_ error message and traceback
from your output when running the sample code with the
sample data.
For extra points, identify the Python version you are using.

--Scott David Daniels
scott.dani...@acm.org
--
http://mail.python.org/mailman/listinfo/python-list


Re: Parsing text

2009-05-06 Thread MRAB

iainemsley wrote:

Hi,
I'm trying to write a fairly basic text parser to split up scenes and
acts in plays to put them into XML. I've managed to get the text split
into the blocks of scenes and acts and returned correctly but I'm
trying to refine this and get the relevant scene number when the split
is made but I keep getting an NoneType error trying to read the block
inside the for loop and nothing is being returned. I'd be grateful for
some suggestions as to how to get this working.

for scene in text.split('Scene'):
num = re.compile("^\s\[0-9, i{1,4}, v]", re.I)
textNum = num.match(scene)
if textNum:
print textNum
else:
print "No scene number"
m = '
The problem is with your regular expression. Unfortunately, I can't tell
what you're trying to match. Could you provide some examples of the
scene numbers?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Parsing text

2009-05-06 Thread Tim Chase

I'm trying to write a fairly basic text parser to split up scenes and
acts in plays to put them into XML. I've managed to get the text split
into the blocks of scenes and acts and returned correctly but I'm
trying to refine this and get the relevant scene number when the split
is made but I keep getting an NoneType error trying to read the block
inside the for loop and nothing is being returned. I'd be grateful for
some suggestions as to how to get this working.

for scene in text.split('Scene'):
num = re.compile("^\s\[0-9, i{1,4}, v]", re.I)


The first thing that occurs to me is that this should likely be a 
raw string to get those backslashes into the regexp.  Compare:


  print "^\s\[0-9, i{1,4}, v]"
  print r"^\s\[0-9, i{1,4}, v]"

Without an excerpt of the actual text (or at least the lead-in 
for each scene), it's hard to tell whether this regex finds what 
you expect.  It doesn't look like your regexp finds what you may 
think it does (it looks like you're using commas .


Just so you're aware, your split is a bit fragile too, in case 
any lines contain "Scene".  However, with a proper regexp, you 
can even use it to split the scenes *and* tag the scene-number. 
Something like


  >>> import re
  >>> s = """Scene [42]
  ... this is stuff in the 42nd scene
  ... Scene [IIV]
  ... stuff in the other scene
  ... """
  >>> r = re.compile(r"Scene\s+\[(\d+|[ivx]+)]", re.I)
  >>> r.split(s)[1:]
  ['42', '\nthis is stuff in the 42nd scene\n', 'IIV', '\nstuff 
in the other scene\n']

  >>> def grouper(iterable, groupby):
  ... iterable = iter(iterable)
  ... while True:
  ... yield [iterable.next() for _ in range(groupby)]
  ...

  >>> for scene, content in grouper(r.split(s)[1:], 2):
  ... print "%s%s" 
% (scene, content)

  ...
  42
  this is stuff in the 42nd scene
  
  IIV
  stuff in the other scene
  

Play accordingly.

-tkc




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


Re: Copy & Paste in a Dos box (was: Pyhton script to call another program)

2009-05-06 Thread Grant Edwards
On 2009-05-06, Shawn Milochik  wrote:

>>> That way, you can basically use PuTTY to shell into your
>>> Windows box.
>>
>> Better yet, set up sshd in your Cygwin install, and then use
>> whatever terminal you normally use on your Linux/MacOS box to
>> ssh into the Cygwin box. ??When run that way, windows is almost
>> usable...
>
>
>
> True, but when I'm using Cygwin, that means I'm at work and don't have
> a non-MS OS available.

Ouch.  That's too bad.  I spent a few months doing a project
for which the compiler was windows-only.  I found that doing
all of the editing, source-control, and testing on Linux and
sshing into a Cygwin box to do the "make" was minimally
painful.

> Of course I can open an ssh session to my home machine for
> sanity (or kicking off a torrent download at home), but I
> don't have a *nix-based OS at the day job. Lanching DSL
> embedded to use the terminal seems a bit much. ^_^

Probably so.

-- 
Grant Edwards   grante Yow! I want a VEGETARIAN
  at   BURRITO to go ... with
   visi.comEXTRA MSG!!
--
http://mail.python.org/mailman/listinfo/python-list


Re: Parsing text

2009-05-06 Thread Stefan Behnel
iainemsley wrote:
> for scene in text.split('Scene'):
> num = re.compile("^\s\[0-9, i{1,4}, v]", re.I)
> textNum = num.match(scene)

Not related to your problem, but to your code - I'd write this as follows:

match_scene_num = re.compile("^\s\[0-9, i{1,4}, v]", re.I).match

for scene_section in text.split('Scene'):
text_num = match_scene_num(scene_section)

This makes the code more readable and avoids unnecessary work inside the loop.

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


Re: Separate Windows versions of Python

2009-05-06 Thread Terry Reedy

Scott David Daniels wrote:


On windows, major versions (..., 2.5, 2.6, 2.7, , 3.0, 3.1,  ...)
can coexist quite successfully.  Find and run an installer for the
latest version  of 2.5 (2.5.4, I believe) on the Python download page.
That will make 2.5 your default Python. 


 believe the installer gives one the choice as to whether or not to 
make the new installation the default -- which is to say, the one 
registered with .py, etc, extensions.


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


Re: fcntl and siginfo_t in python

2009-05-06 Thread Philip
ma  gmail.com> writes:
> 
> Ok! So, I decided to write a C-extension instead of using ctypes...
> 
> This works beautifully. Now, I want to release this to the public, so
> I'm thinking of making a bit of code cleanup. Should I just pack the
> entire siginfo_t struct, right now I just use the fd, into a
> dictionary and pass it to the python callback handler function? Maybe
> there might be some more suggestions to what data structures to use,
> so I'm open right now to any of them.

Could we have a look at your working prototype?

Philip J. Tait
http://subarutelescope.org

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


Re: Copy & Paste in a Dos box (was: Pyhton script to call another program)

2009-05-06 Thread Mensanator
On May 6, 12:54 pm, Tim Chase  wrote:
> > for windows this works:
> > (can't cut and paste from a dos box!###%*&!!!)
>
> Depending on how it was spawned, you can either right-click in
> the window and choose Mark/Paste (when marking, use  to
> terminate the selection; and selections are blockwise rectangular
> rather than linewise or characterwise).  Alternatively, if you
> click on the system menu (the icon in the title-bar with
> resize/minimize/maximize/close/help), there should be an Edit
> submenu with the same options within.
>
> A pain, but at least feasible.

Less painful is to set the properties of the dos box:

Edit Options:
[x] Quick Edit mode

And when prompted, do "(.) modify shortcut that started this window"

After which, you can dispense with the menus (except when pasting),
just select the text and hit .

Makes a world of difference.

>
> HTH,
>
> -tkc

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


SQLObject 0.10.5

2009-05-06 Thread Oleg Broytmann
Hello!

I'm pleased to announce version 0.10.5, a minor bugfix release of 0.10 branch
of SQLObject.


What is SQLObject
=

SQLObject is an object-relational mapper.  Your database tables are described
as classes, and rows are instances of those classes.  SQLObject is meant to be
easy to use and quick to get started with.

SQLObject supports a number of backends: MySQL, PostgreSQL, SQLite,
Firebird, Sybase, MSSQL and MaxDB (also known as SAPDB).


Where is SQLObject
==

Site:
http://sqlobject.org

Development:
http://sqlobject.org/devel/

Mailing list:
https://lists.sourceforge.net/mailman/listinfo/sqlobject-discuss

Archives:
http://news.gmane.org/gmane.comp.python.sqlobject

Download:
http://cheeseshop.python.org/pypi/SQLObject/0.10.5

News and changes:
http://sqlobject.org/News.html


What's New
==

News since 0.10.4
-

* Another unicode-related patch for MySQL; required because different
  versions of MySQLdb require different handling::

   - MySQLdb < 1.2.1: only ascii
   - MySQLdb = 1.2.1: only unicode
   - MySQLdb > 1.2.1: both ascii and unicode

* Setup requires FormEncode version 1.1.1+.

* Fixed a minor bug - pass name to DecimalValidator.

* Fixed a bug in InheritableIteration - pass connection to child
  klass.select().

* sqlmeta.getColumns() becomes classmethod.

* A bug was fixed in PostgresConnection.columnsFromSchema() - foreign keys
  are now recognized and created as proper ForeignKey with correct
  column name and table name.

* Bugs in PostgresConnection and MSSQLConnection related to properties was
  fixed. A note for developers: from now on properties in DBConnection
  classes are forbidden as they don't work with Transaction -
  Transaction.__getattr__() cannot properly wrap 'self' so a property is
  called with wrong 'self'.

* Transaction instances now explicitly raises TypeError on close() -
  without this calling Transaction.close() calls connection.close() which
  is wrong.

* A bug in SQLiteConnection.columnsFromSchema() that led to an infinite
  loop was fixed.

For a more complete list, please see the news:
http://sqlobject.org/News.html

Oleg.
-- 
 Oleg Broytmannhttp://phd.pp.ru/p...@phd.pp.ru
   Programmers don't die, they just GOSUB without RETURN.
--
http://mail.python.org/mailman/listinfo/python-list


SQLObject 0.9.10

2009-05-06 Thread Oleg Broytmann
Hello!

I'm pleased to announce version 0.9.10, a minor bugfix release of 0.9 branch
of SQLObject.


What is SQLObject
=

SQLObject is an object-relational mapper.  Your database tables are described
as classes, and rows are instances of those classes.  SQLObject is meant to be
easy to use and quick to get started with.

SQLObject supports a number of backends: MySQL, PostgreSQL, SQLite,
Firebird, Sybase, MSSQL and MaxDB (also known as SAPDB).


Where is SQLObject
==

Site:
http://sqlobject.org

Development:
http://sqlobject.org/devel/

Mailing list:
https://lists.sourceforge.net/mailman/listinfo/sqlobject-discuss

Archives:
http://news.gmane.org/gmane.comp.python.sqlobject

Download:
http://cheeseshop.python.org/pypi/SQLObject/0.9.10

News and changes:
http://sqlobject.org/News.html


What's New
==

News since 0.9.9


* Another unicode-related patch for MySQL; required because different
  versions of MySQLdb require different handling::

   - MySQLdb < 1.2.1: only ascii
   - MySQLdb = 1.2.1: only unicode
   - MySQLdb > 1.2.1: both ascii and unicode

* Setup requires FormEncode version 1.1.1+.

* Fixed a minor bug - pass name to DecimalValidator.

* Fixed a bug in InheritableIteration - pass connection to child
  klass.select().

* A bug was fixed in PostgresConnection.columnsFromSchema() - foreign keys
  are now recognized and created as proper ForeignKey with correct
  column name and table name.

* Bugs in PostgresConnection and MSSQLConnection related to properties was
  fixed. A note for developers: from now on properties in DBConnection
  classes are forbidden as they don't work with Transaction -
  Transaction.__getattr__() cannot properly wrap 'self' so a property is
  called with wrong 'self'.

* Transaction instances now explicitly raises TypeError on close() -
  without this calling Transaction.close() calls connection.close() which
  is wrong.

* A bug in SQLiteConnection.columnsFromSchema() that led to an infinite
  loop was fixed.

For a more complete list, please see the news:
http://sqlobject.org/News.html

Oleg.
-- 
 Oleg Broytmannhttp://phd.pp.ru/p...@phd.pp.ru
   Programmers don't die, they just GOSUB without RETURN.
--
http://mail.python.org/mailman/listinfo/python-list


About ODFPY links

2009-05-06 Thread shruti surve
hey all,
 For my project, i am using ODFpy open office spreadsheets. I am creating
ledgers in python ie.ledger.py.  So when i run ledger.py, spreadsheet will
be opened in open office. since ledger is made of number of accounts, i am
creating multiple tables for all accounts in single spreadsheet. So, there
are number of tables in one spreadsheet.  Now i want create links in each
table of spreadsheet so that i can connect multiple tables. SO can anyone
please tell me how to create links in odfpy..
--
http://mail.python.org/mailman/listinfo/python-list


Re: Code works fine except...

2009-05-06 Thread John Yeung
On May 5, 10:49 am, Ross  wrote:
> I'm interested to see what you did. From your description,
> it sounds like I've tried what you've done, but when I
> implemented my version, it took minutes to evaluate for
> bigger numbers. If that isn't the case with yours, I'd be
> interested in seeing your implementation.

I don't know how big your "bigger numbers" are, but this should run in
a reasonable time.  It helps if you are using Python 2.6.  If not, you
should go on-line to the itertools docs to get the pure-Python
equivalent for itertools.combinations.

Since no matches are "thrown away", the byes are expressed simply as a
list of players that have to sit out for the week.

A couple of the lines are on the longish side, so beware of wrapping
from the browser/newsreader.

# Let's just try choosing from the possible combinations, each week
# scheduling those who have played the least or waited the longest.

import itertools

class Player(object):
def __init__(self, id):
self.id = id
self.played = []
self.latency = 0

def __str__(self):
str(self.id)

def __cmp__(self, other):
if len(self.played) != len(other.played):
return len(self.played) - len(other.played)
return other.latency - self.latency # select longer latency
first

def flattened(listOfLists):
return list(itertools.chain(*listOfLists))

def pairings(players):
idlist = range(players)
playerlist = [Player(i) for i in idlist]
matchlist = list(itertools.combinations(idlist, 2))
while matchlist:
found = False
playerlist.sort()
for i in range(players - 1):
for j in range(i + 1, players):
candidate = tuple(sorted((playerlist[i].id, playerlist
[j].id)))
if candidate in matchlist:
yield matchlist.pop(matchlist.index(candidate))
for p in playerlist:
if p.id == candidate[0]:
p.played.append(candidate[1])
p.latency = 0
elif p.id == candidate[1]:
p.played.append(candidate[0])
p.latency = 0
else:
p.latency += 1
found = True
break
if found: break

def schedule(players, weeks, courts):
playerlist = range(players)
matchlist = list(pairings(players))
cap = min(courts, players // 2)
start = 0
for week in range(weeks):
matches = matchlist[start:start + cap]
byes = set(playerlist) - set(flattened(matches))
print matches, list(byes)
start += cap
--
http://mail.python.org/mailman/listinfo/python-list


Re: list comprehension question

2009-05-06 Thread John Yeung
On May 5, 11:36 pm, alex23  wrote:

> Apart from the presence of 'item' at the beginning of the
> list comprehension as opposed to 'b.append(item)' at the
> end of the for-loop, how exactly does the listcomp force
> you to "bounce [..] back and forth" to follow the logic?

It's precisely the fact that the item is at the beginning which is the
main instigator of the bounce.  To tranlate

  [f(x) for x in a]

into a loop, you start in the middle, work your way toward the right,
then bounce back to the left.

I think some of us, perhaps subconsciously, get used to reading that
small chunk on the right, then bouncing left.  See enough small, flat
LCs, and we may be conditioned to think that the general rule is to
start with that small chunk on the right and bounce left.

When confronted with a long, nested LC then, some of us have the
instinct to read the rightmost chunk, then bounce left to the next-
rightmost chunk, etc.

Essentially, if you see [B A] over and over and over again, when
finally confronted with LCs of more "elements", it's not immediately
clear that the pattern of increasing nestedness is

  [B A] => [C A B] => [D A B C] => etc.

rather than

  [B A] => [C B A] => [D C B A] => etc.

Maybe we're wired wrong, but there are many of us who find the second
pattern more logical, which is why it is so easy for us to mess up the
order of the nesting in a more complex LC.

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


Re: list comprehension question

2009-05-06 Thread J Kenneth King
Emile van Sebille  writes:

> On 5/5/2009 9:15 AM J Kenneth King said...
>
>> List comprehensions can make a reader of your code apprehensive
>> because it can read like a run-on sentence and thus be difficult to
>> parse. The Python documentation discourages their use and I believe
>> for good reason.
>
> Can you provide a link for this?  I'd like to see specifically what's
> being discouraged, as I'd be surprised to find routine usage frowned
> upon.
>
> Emile

http://docs.python.org/tutorial/datastructures.html#nested-list-comprehensions


"If you’ve got the stomach for it, list comprehensions can be
nested. They are a powerful tool but – like all powerful tools – they
need to be used carefully, if at all."

and

"In real world, you should prefer builtin functions to complex flow
statements."
--
http://mail.python.org/mailman/listinfo/python-list


Re: list comprehension question

2009-05-06 Thread Roel Schroeven
John Yeung schreef:
> Essentially, if you see [B A] over and over and over again, when
> finally confronted with LCs of more "elements", it's not immediately
> clear that the pattern of increasing nestedness is
> 
>   [B A] => [C A B] => [D A B C] => etc.
> 
> rather than
> 
>   [B A] => [C B A] => [D C B A] => etc.
> 
> Maybe we're wired wrong, but there are many of us who find the second
> pattern more logical, which is why it is so easy for us to mess up the
> order of the nesting in a more complex LC.

Indeed, that is exactly the reason why I find it difficult to read
nested loop comprehensions, and why I almost never use them.

-- 
The saddest aspect of life right now is that science gathers knowledge
faster than society gathers wisdom.
  -- Isaac Asimov

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


[ANN] Completion of The Python Papers Volume 4 Issue 1

2009-05-06 Thread mauricel...@acm.org
Welcome to Issue 4 Volume 1 of The Python Papers. This marks our 4th
year in business. It is my pleasure to announce 4 improvements made to
The Python Papers Anthology.

Firstly, we had created a class of editorial members in our team – the
Editorial Reviewers (ER). This is in addition to the existing Editors-
in-Chief (EIC) and Associate Editors (AE). In the words of our revised
editorial policy, “ER is a tier of editors deemed to have in-depth
expertise knowledge in specialized areas. As members of the editorial
board, ERs are accorded editorial status but are generally not
involved in the strategic and routine operations of the periodicals
although their
expert opinions may be sought at the discretion of EIC.” To this
aspect, we are glad to have Jacob Kaplan-Moss (President, Django
Software Foundation; Partner, Revolution Systems, LLC; Co-BDFL,
Django) as our first ER. Welcome aboard.

Secondly, we had adopted a fast publication scheme. In the past,
accepted manuscripts will only be published on the release date in the
month of April, August and December each year. With the use of Open
Journal System, we are able to publish manuscripts as they are being
accepted. This means that the release date in the month of April,
August and December is now effectively our closing date for the issue.
For example, manuscripts accepted after April 2009 will be routed to
immediate publication in Volume 4 Issue 2. This is to being
information faster to our readers, rather than waiting for a few
months.

Thirdly, we announce a set of manuscript templates for our authors and
contributors for their manuscript preparation. As such, we had
revamped our website (http://www.pythonpapers.org) to reflect these
changes.

Lastly, we are glad to announce the launch of our 2nd publication
under The Python Papers Anthology – The Python Papers Source Codes
(ISSN 1836-621X). TPPSC, for short, is a collection of software and
source codes, usually associated with papers published in The Python
Papers and The Python Papers Monograph. These codes are refereed for
originality, accuracy, completeness, and lasting value. TPPSC will
act as a developers codebook of high-quality, peer-reviewed codes.
TPPSC is an annual publication using the same fast publication scheme.

We thank all our readers and contributors for their continued support.

Happy reading.

Maurice Ling
Co-EIC, TPPA
--
http://mail.python.org/mailman/listinfo/python-list


Re: Completion of The Python Papers Volume 4 Issue 1

2009-05-06 Thread Maurice Ling
My apologies.

It should be Volume 4 Issue 1 instead of Issue 4 Volume 1.

Thank you Scott for pointing this out.

Regards
Maurice

On May 6, 10:08 pm, "mauricel...@acm.org" 
wrote:
> Welcome to Issue 4 Volume 1 of The Python Papers. This marks our 4th
> year in business. It is my pleasure to announce 4 improvements made to
> The Python Papers Anthology.
>
> Firstly, we had created a class of editorial members in our team – the
> Editorial Reviewers (ER). This is in addition to the existing Editors-
> in-Chief (EIC) and Associate Editors (AE). In the words of our revised
> editorial policy, “ER is a tier of editors deemed to have in-depth
> expertise knowledge in specialized areas. As members of the editorial
> board, ERs are accorded editorial status but are generally not
> involved in the strategic and routine operations of the periodicals
> although their
> expert opinions may be sought at the discretion of EIC.” To this
> aspect, we are glad to have Jacob Kaplan-Moss (President, Django
> Software Foundation; Partner, Revolution Systems, LLC; Co-BDFL,
> Django) as our first ER. Welcome aboard.
>
> Secondly, we had adopted a fast publication scheme. In the past,
> accepted manuscripts will only be published on the release date in the
> month of April, August and December each year. With the use of Open
> Journal System, we are able to publish manuscripts as they are being
> accepted. This means that the release date in the month of April,
> August and December is now effectively our closing date for the issue.
> For example, manuscripts accepted after April 2009 will be routed to
> immediate publication in Volume 4 Issue 2. This is to being
> information faster to our readers, rather than waiting for a few
> months.
>
> Thirdly, we announce a set of manuscript templates for our authors and
> contributors for their manuscript preparation. As such, we had
> revamped our website (http://www.pythonpapers.org) to reflect these
> changes.
>
> Lastly, we are glad to announce the launch of our 2nd publication
> under The Python Papers Anthology – The Python Papers Source Codes
> (ISSN 1836-621X). TPPSC, for short, is a collection of software and
> source codes, usually associated with papers published in The Python
> Papers and The Python Papers Monograph. These codes are refereed for
> originality, accuracy, completeness, and lasting value. TPPSC will
> act as a developers codebook of high-quality, peer-reviewed codes.
> TPPSC is an annual publication using the same fast publication scheme.
>
> We thank all our readers and contributors for their continued support.
>
> Happy reading.
>
> Maurice Ling
> Co-EIC, TPPA

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


Re: Copy & Paste in a Dos box (was: Pyhton script to call another program)

2009-05-06 Thread Dave Angel

Tim Chase wrote:
> for 
windows this works:

(can't cut and paste from a dos box!###%*&!!!)


Depending on how it was spawned, you can either right-click in the 
window and choose Mark/Paste (when marking, use  to terminate 
the selection; and selections are blockwise rectangular rather than 
linewise or characterwise).  Alternatively, if you click on the system 
menu (the icon in the title-bar with 
resize/minimize/maximize/close/help), there should be an Edit submenu 
with the same options within.


A pain, but at least feasible.

HTH,

-tkc


Note that if you like copy/paste, you can turn on "Quick Edit" mode in 
your cmd.exe windows.  From that same System menu on your DOS box, 
choose "Defaults".  From the first tab that box, enable "Quick Edit" 
checkbox.   This will change the default for subsequent DOS boxes.  You 
can change it just for the current one by using Properties in the same 
system menu.



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


Re: Copy & Paste in a Dos box (was: Pyhton script to call another program)

2009-05-06 Thread Dave Angel



Mensanator wrote:



And when prompted, do "(.) modify shortcut that started this window"

After which, you can dispense with the menus (except when pasting),
just select the text and hit .

  
To paste into a DOS box, once Quick Edit is enabled, use Right-Click.  
They keystrokes will be sent to the command editor.  Note that the 
interpretation is rather literal, so be careful if copy/pasting more 
than one line, or a line that was wrapped.



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


Re: list comprehension question

2009-05-06 Thread Emile van Sebille

On 5/6/2009 6:48 AM J Kenneth King said...

Emile van Sebille  writes:

On 5/5/2009 9:15 AM J Kenneth King said...

 The Python documentation discourages their use and I believe
for good reason.

Can you provide a link for this?  I'd like to see specifically what's
being discouraged, as I'd be surprised to find routine usage frowned
upon.

http://docs.python.org/tutorial/datastructures.html#nested-list-comprehensions



Thanks.



"If you’ve got the stomach for it, list comprehensions can be
nested. They are a powerful tool but – like all powerful tools – they
need to be used carefully, if at all."


Yes, although this is in reference to nested list comprehensions.  Eg,

[xx for xx in [yy for yy in [zz for zz in iterable if z] if y] if x]

The section above on list comprehensions advocates their use saying:

"List comprehensions provide a concise way to create lists without 
resorting to use of map(), filter() and/or lambda. The resulting list 
definition tends often to be clearer than lists built using those 
constructs."


Emile

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


Re: Parsing text

2009-05-06 Thread Rhodri James
On Wed, 06 May 2009 19:32:28 +0100, iainemsley   
wrote:



Hi,
I'm trying to write a fairly basic text parser to split up scenes and
acts in plays to put them into XML. I've managed to get the text split
into the blocks of scenes and acts and returned correctly but I'm
trying to refine this and get the relevant scene number when the split
is made but I keep getting an NoneType error trying to read the block
inside the for loop and nothing is being returned. I'd be grateful for
some suggestions as to how to get this working.


With neither a sample of your data nor the traceback you get, this is
going to require some crystal ball work.  Assuming that all you've got
is running text, I should warn you now that getting this right is a
hard task.  Getting it apparently right and having it fall over in a
heap or badly mangle the text is, unfortunately, very easy.


for scene in text.split('Scene'):


Not a safe start.  This will split on the word "Scenery" as well, for
example, and doesn't guarantee you the start of a scene by a long way.


num = re.compile("^\s\[0-9, i{1,4}, v]", re.I)


This is almost certainly not going to do what you expect, because all
those backslashes in the string are going to get processed as escape
characters before the string is ever passed to re.compile.  Even if
you fix that (by doubling the backslashes or making it a raw string),
I sincerely doubt that this is the regular expression you want.  As
escaped, it matches in sequence:

  * the start of the string
  * a space, tab, newline or other whitespace character.  Just the one.
  * the literal string "[0-9, "
  * either "i" or "I" repeated between 1 and four times
  * the literal string ", "
  * either "v" or "V"
  * the literal string "]"

Assuming you didn't mean to escape the open square bracket doesn't help:

  * the start of the string
  * one whitespace character
  * one of the following characters: 0123456789,iI{}vV

Also, what the heck is this doing *inside* the for loop?


textNum = num.match(scene)


If you're using re.match(), the "^" on the regular expression is
redundant.


if textNum:
print textNum


textNum is the match object, so printing it won't tell you much.  In
particular, it isn't going to produce well-formed XML.


else:
print "No scene number"


Nor will this.


m = '

Missing close double quotes after 'scene'.


m += scene
m += '<\div>'
print m


I'm seeing nothing here that should produce an error message that
has anything to do with NoneType.  Any chance of (a) a more accurate
code sample, (b) the traceback, or (c) sample data?

--
Rhodri James *-* Wildebeeste Herder to the Masses
--
http://mail.python.org/mailman/listinfo/python-list


Re: Self function

2009-05-06 Thread Rhodri James
On Wed, 06 May 2009 04:59:59 +0100, Gabriel Genellina  
 wrote:


En Tue, 05 May 2009 22:35:08 -0300, Rhodri James  
 escribió:

On Tue, 05 May 2009 21:43:16 +0100,  wrote:

wolfram.hinde...:



It is easy to change all references of the function name, except for
those in the function body itself? That needs some explantation.


I can answer this. If I have a recursive function, I may want to
create a similar function, so I copy and paste it, to later modify the
copied version. Then to change its name I usually don't use a search &
rename of its name into its block of code because it's usually
useless. In non-recursive functions the name of the function is stated
only once, at the top.


I'm sorry, but while I'm mildly positive towards the proposal (and more
so towards Aaron's decorator), I don't buy this argument at all.  What
is broken about your editor's global search-and-replace function that
makes it "usually useless" for making these name changes?


It happened to me sometimes. If a module defines some functions, and it  
doesn't *use* them, why should I use a global search-and-replace to  
rename something? Modifying the "def" line should be enough - unless the  
function happens to be recursive.


So the answer to my question would be "nothing"?

It's the DRY principle in action, the same argument as when decorators  
where introduced: there should be no need to repeat the function name  
again and again.


Unless of course you're using it again and again, which you are.

--
Rhodri James *-* Wildebeeste Herder to the Masses
--
http://mail.python.org/mailman/listinfo/python-list


Re: fcntl and siginfo_t in python

2009-05-06 Thread ma

Sure, I'll send you the source files when I get a chance!

--Sent from my iPhone

On May 6, 2009, at 4:03 PM, Philip  wrote:


ma  gmail.com> writes:


Ok! So, I decided to write a C-extension instead of using ctypes...

This works beautifully. Now, I want to release this to the public, so
I'm thinking of making a bit of code cleanup. Should I just pack the
entire siginfo_t struct, right now I just use the fd, into a
dictionary and pass it to the python callback handler function? Maybe
there might be some more suggestions to what data structures to use,
so I'm open right now to any of them.


Could we have a look at your working prototype?

Philip J. Tait
http://subarutelescope.org

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

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


SimpleXMLRPCServer and creating a new object on for each new client request.

2009-05-06 Thread J
Hi list,

My goals is to have concurrent and separated client sessions using xmlrpc.
Initially my though was that SimpleXMLRPCServer was able to create a new
object instance for each incoming request.
But this doesn't appear to be the case, unless I'm overlooking something,
if so please point me out.

Concider following simplified code


#!/usr/bin/python

from SimpleXMLRPCServer import SimpleXMLRPCServer
from SimpleXMLRPCServer import SimpleXMLRPCRequestHandler
import random

# Restrict to a particular path.
class RequestHandler(SimpleXMLRPCRequestHandler):
rpc_paths = ('/RPC2',)

# Create a simple example class
class Randomizer:
def __init__(self):
self.random=random.randrange(0,10)
def show_random(self):
return self.random

# Create server
server = SimpleXMLRPCServer(("localhost",
8000),requestHandler=RequestHandler,allow_none=1)
server.register_introspection_functions()

server.register_instance(Randomizer())
server.serve_forever()



I start python interactively:
>>> import xmlrpclib
>>> session1=xmlrpclib.ServerProxy('http://localhost:8000')
>>> session2=xmlrpclib.ServerProxy('http://localhost:8000')
>>> print session1.show_random()
13930
>>> print session2.show_random()
13930
>>> 

I though that session1 and session2 would be 2 different Randomizer objects
each having a different result for self.random
But as the example shows this is not the case.
How can I solve this?

Thanks

Jelle

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


Re: call function of class instance with no assigned name?

2009-05-06 Thread Carl Banks
On May 5, 7:55 pm, Dave Angel  wrote:
> George Oliver wrote:
> > On May 5, 11:59 am, Dave Angel  wrote:
>
> >> 1) forget about getattr() unless you have hundreds of methods in your
> >> map.  The real question is why you need two maps. What good is the
> >> "command string" doing you?   Why not just map the keyvalues directly
> >> into function objects?
>
> > Thanks for the reply Dave. I understand your example and it's what I
> > originally used. Here is more detail on what I'm doing now, I hope
> > this will explain my question better.
>
> > In the game I'm writing the player, monsters, items and so on are
> > instances of class Thing, like:
>
> > class Thing(object):
> >     def __init__(self, x, y, name):
> >         self.x, self.y = x, y
> >         self.name = name
> >         self.brain = None
>
> > Some Things have an instance of class Brain attached. The Brain
> > instance has a list of handlers, like:
>
> > class Brain(object):
> >     def __init__(self):
> >         self.handlers = []
>
> > A handler class defines some functionality for the Brain. Each Brain
> > has an update method like this:
>
> > def update(self, arguments):
> >     for handler in self.handlers:
> >         handler.update(arguments)
>
> > So on each pass through the main game loop, it calls the update method
> > of all the brains in the game, which run their handler update methods
> > to change the state of the game.
>
> > A handler would be something like a key input handler. The key input
> > handler is defined separately from the command handler in the case I
> > want to use a different method of input, for example a mouse or
> > joystick.
>
> > In the dictionary of key inputs I could map each input directly to a
> > function. However there is no instance name I can call the function
> > on, as I create a thing, add a brain, and add handlers to the brain
> > like this:
>
> > player = Thing(26, 16, 'player')
> > player.brain = Brain()
> > player.brain.add_handlers(
> >                             commandHandler(player.brain, player),
> >                             keyboardHandler(player.brain),
> >                             fovHandler(player.brain))
>
> > So what I'm wondering is how to reference the instance in each brain's
> > list of handlers when I want to map something like a key input to a
> > command, or what a better way might be to structure the code.
>
>  >>
>
> >>player.brain.add_handlers(
> >>                            commandHandler(player.brain, player),
> >>                            keyboardHandler(player.brain),
> >>                            fovHandler(player.brain))
>
> You're executing commandHandler, and passing its return value into the
> add_handlers() method.  So commandHandler is a function, not a method,
> and what is its relationship to anything that actually processes commands?

It seems to be a factory function.


> Sorry, your pseudo-code is so far from real code that I can't figure out
> what you're doing.  So I guess I can't be any help till something else
> turns up to make it clearer.  Maybe it's just me.

I think it's you--and probably a lot of other people who haven't ever
written games.  No offense.  As someone who's written games before I
will tell you that George's pseudo-code is not far from real code.
His overall approach is fairly typical of how games handle input,
although there are some problems in the details.


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


Re: Copy & Paste in a Dos box (was: Pyhton script to call another program)

2009-05-06 Thread Mensanator
On May 6, 3:46 pm, Dave Angel  wrote:
> Mensanator wrote:
> > 
>
> > And when prompted, do "(.) modify shortcut that started this window"
>
> > After which, you can dispense with the menus (except when pasting),
> > just select the text and hit .
>
> To paste into a DOS box, once Quick Edit is enabled, use Right-Click.  
> They keystrokes will be sent to the command editor.  Note that the
> interpretation is rather literal, so be careful if copy/pasting more
> than one line, or a line that was wrapped.

Well I'll be dipped. Didn't know you could do that.

Of course, since I learned how to call programs from the
script and capture their StdOut, I don't have much call for
cut/paste from dos windows. Hopefully, I'll remember that the
next time I need it.
--
http://mail.python.org/mailman/listinfo/python-list


SimpleXMLRPCServer and creating a new object on for each new client request.

2009-05-06 Thread Jelle Smet
Hi list,

My goals is to have concurrent and separated client sessions using xmlrpc.
Initially my though was that SimpleXMLRPCServer was able to create a new
object instance for each incoming request.
But this doesn't appear to be the case, unless I'm overlooking something,
if so please point me out.

Concider following simplified code


#!/usr/bin/python

from SimpleXMLRPCServer import SimpleXMLRPCServer
from SimpleXMLRPCServer import SimpleXMLRPCRequestHandler
import random

# Restrict to a particular path.
class RequestHandler(SimpleXMLRPCRequestHandler):
rpc_paths = ('/RPC2',)

# Create a simple example class
class Randomizer:
def __init__(self):
self.random=random.randrange(0,10)
def show_random(self):
return self.random

# Create server
server = SimpleXMLRPCServer(("localhost",
8000),requestHandler=RequestHandler,allow_none=1)
server.register_introspection_functions()

server.register_instance(Randomizer())
server.serve_forever()



I start python interactively:
>>> import xmlrpclib
>>> session1=xmlrpclib.ServerProxy('http://localhost:8000')
>>> session2=xmlrpclib.ServerProxy('http://localhost:8000')
>>> print session1.show_random()
13930
>>> print session2.show_random()
13930
>>> 

I though that session1 and session2 would be 2 different Randomizer objects
each having a different result for self.random
But as the example shows this is not the case.
How can I solve this?

Thanks

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


Re: call function of class instance with no assigned name?

2009-05-06 Thread Carl Banks
On May 5, 12:17 pm, George Oliver  wrote:
> A handler would be something like a key input handler. The key input
> handler is defined separately from the command handler in the case I
> want to use a different method of input, for example a mouse or
> joystick.
>
> In the dictionary of key inputs I could map each input directly to a
> function. However there is no instance name I can call the function
> on, as I create a thing, add a brain, and add handlers to the brain
> like this:

What instance do you want to call the functions on?  This is the part
that confuses me.


> player = Thing(26, 16, 'player')
> player.brain = Brain()
> player.brain.add_handlers(
>                             commandHandler(player.brain, player),
>                             keyboardHandler(player.brain),
>                             fovHandler(player.brain))
>
> So what I'm wondering is how to reference the instance in each brain's
> list of handlers when I want to map something like a key input to a
> command, or what a better way might be to structure the code.


I'm going to guess that you want the keyboardHandler to call method of
commandHandler.  There's no reason for commandHandler to be a handler
at all then: keyboardHandler is already handling it.

So here is how I would change it:

player = Thing(26,16,'player')
player.brain = Brain()
responder = commandResponder(player.brain,player)
player.brain.add_handlers(
keyboardHandler(player.brain,responder),
joystickHandler(player.brain,responder),
fovHandler(player.brain),
)


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


Re: Code works fine except...

2009-05-06 Thread John Yeung
On May 6, 3:29 am, MRAB  wrote:

> I have the feeling that if the number of rounds is restricted then the
> difference between the minimum and maximum number of byes could be 2
> because of the requirement that players shouldn't play each other more
> than once, meaning that the players have to be shuffled around a bit, so
> a player might play a week earlier or later than would otherwise be the
> case.

This is the feeling that I am getting also.  All my efforts to keep
everything as balanced as possible at all times (to be ready for the
"season" to end suddenly at any time) result in messy jams that could
otherwise be alleviated if I allowed temporary imbalances, knowing
that there are more weeks later to make them up.

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


Python 2.6 worth the hassle?

2009-05-06 Thread Evan Kroske
I'm planning on learning Python, and I'd like to know which version to 
start with. I know that Python 3.0 isn't ready for production and it 
doesn't have enough libraries yet, so I thought I should learn Python 
2.6. Unfortunately, installing Python 2.6 on my Linux distro (Ubuntu 
Intrepid Ibex) has given me lots of complicated problems I really don't 
want to deal with.


My essential question is "Is Python 2.6 similar enough to Python 3.0 to 
justify its complexity of installation?" Upgrading to Jaunty is NOT an 
option 
(http://welcome2obscurity.blogspot.com/2009/05/jaunty-jackalope-released-vista-all.html).


Best regards,
Evan Kroske
Undecided Python Student
--
http://mail.python.org/mailman/listinfo/python-list


removing row from table. PyQT

2009-05-06 Thread Ani
I'm trying to remove the selected rows from the table,
but it's not working, i've tried many ways, don't know what I'm missing.

code below:


class MonitorUi(QWidget):

def __init__(self,parent = None):
QWidget.__init__(self,parent)

self._initalTable =
[["none","none","none"],["none","none","none"],["none","none","none"]]

self.lista=""
self.headerH =
["Id","UserName","Engine","Proj","FileToRender","StartFrame","EndFrame","Packets","Skip","Attr","Status"]

self.setWindowTitle("RenderMonitor")
self.setGeometry(150,150,1000,500)
self.setWindowIcon(QIcon('monkey.png'))


timer = QTimer(self)
self.ItemEdit = QLineEdit()
self.buttonRemove = QPushButton("remove")
self.buttonRende = QPushButton("Rende!")
self.tableWidget = QTableWidget(1000,11)



layoutH = QHBoxLayout()
layoutH.addWidget(self.ItemEdit)
#layoutH.addStretch(1)
layoutH.addWidget(self.buttonRemove)
layoutH.addWidget(self.buttonRende)

layoutV = QVBoxLayout()
layoutV.addLayout(layoutH)
layoutV.addWidget(self.tableWidget)


self.setLayout(layoutV)

self.connect(self.buttonRemove, SIGNAL("clicked()"), self.remove)
self.connect(self.buttonRende, SIGNAL("clicked()"),
self.MsgServerRender)


timer.start(1000)
QObject.connect(timer, SIGNAL("timeout()"), self.displayTable)



def setDataBridge(self,dataInst):
self.lista = dataInst

def clearTable(self):
self.tableWidget.clear()

def remove(self):
print "removendo da tabela"
#self.tableWidget.removeRow(self.tableView.selectedIndexes())
self.tableWidget.removeRow(self.tableWidget.selectedRows)
#self.mapper.toNext()
#self.tableView.selectRow(self.mapper.currentIndex())

def MsgServerRender(self):
sender = ClientMsgRender()
sender.sendTo("run")

def displayTable(self):

print "display table"
self.tableWidget.setHorizontalHeaderLabels(self.headerH)
self.headerV=[]
list2= self.lista.getInfo()

item = 0
linha = 0
while item < len(list2):

#self.tableWidget = QTableWidget(item,9)
self.headerV.append(("job" + str(item)))
elemento = 0
coluna = 0

while elemento < 11 :
str(list2[item][elemento])
NewTableitem = QTableWidgetItem(list2[item][elemento])
#NewTableitem.setFlags(Qt.ItemIsSelectable |
 Qt.ItemIsEnabled )#no editable item
#NewTableitem.setFlags(Qt.ItemIsEnabled )#no editable item
self.tableWidget.setItem(linha,coluna, NewTableitem)


elemento += 1
coluna += 1

item += 1
linha += 1

self.tableWidget.setVerticalHeaderLabels(self.headerV)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Self function

2009-05-06 Thread Luis Alberto Zarrabeitia Gomez

Quoting Rhodri James :

> >> I'm sorry, but while I'm mildly positive towards the proposal (and more
> >> so towards Aaron's decorator), I don't buy this argument at all.  What
> >> is broken about your editor's global search-and-replace function that
> >> makes it "usually useless" for making these name changes?
> >
> > It happened to me sometimes. If a module defines some functions, and it  
> > doesn't *use* them, why should I use a global search-and-replace to  
> > rename something? Modifying the "def" line should be enough - unless the  
> > function happens to be recursive.
> 
> So the answer to my question would be "nothing"?

Indeed, there is nothing broken with the search and replace feature of his
editor. When he is copying a non-recursive function, it is _useless_ to do a
search and replace. When he is copying a recursive function, it is _required_ to
do a search and replace.

So, the very same task requires you to either perform a task that will almost
always be useless (or even dangerous), or to read the source code to find out if
the function is recursive, so that you can use the search and replace only then.

(I know that the "problem" is present in almost all programming languages... but
that's not what is being discussed. Bearophile's concerns seem legitimate, and
you should not dismiss them so lightly just because there are ways to do more
work and hopefully avoid the problems. I'd say that the "problem" is even
aggravated in python, where the dynamic nature of the language makes it near to
impossible to build good refactoring tools) 

-- 
Luis Zarrabeitia
Facultad de Matemática y Computación, UH
http://profesores.matcom.uh.cu/~kyrie

-- 
Participe en Universidad 2010, del 8 al 12 de febrero de 2010
La Habana, Cuba 
http://www.universidad2010.cu

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


Re: Python 2.6 worth the hassle?

2009-05-06 Thread Terry Reedy

Evan Kroske wrote:
I'm planning on learning Python, and I'd like to know which version to 
start with. I know that Python 3.0 isn't ready for production and it 


3.1 will be. The first beta will be out very soon and 3.1 in less than 2 
months.



doesn't have enough libraries yet,


That will take longer.  I hope the improvement in 3.1 will inspire more 
conversions.


so I thought I should learn Python 2.6. Unfortunately, installing Python 2.6 on my Linux distro (Ubuntu 
Intrepid Ibex) has given me lots of complicated problems I really don't 
want to deal with.


My essential question is "Is Python 2.6 similar enough to Python 3.0 to 
justify its complexity of installation?" Upgrading to Jaunty is NOT an 
option 
(http://welcome2obscurity.blogspot.com/2009/05/jaunty-jackalope-released-vista-all.html). 


You could use 2.5 and write with an eye to the future.  Use 'object' or 
some derivative thereof as a base for all your classes.  Never use cmp() 
or .__cmp__().  Don't use string exceptions.  Look in 3.0 What's new for 
anything else to avoid.


tjr

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


Re: Copy & Paste in a Dos box

2009-05-06 Thread norseman

Shawn Milochik wrote:

On Wed, May 6, 2009 at 1:54 PM, Tim Chase  wrote:

for windows this works:
(can't cut and paste from a dos box!###%*&!!!)

Depending on how it was spawned, you can either right-click in the window
and choose Mark/Paste (when marking, use  to terminate the selection;
and selections are blockwise rectangular rather than linewise or
characterwise).  Alternatively, if you click on the system menu (the icon in
the title-bar with resize/minimize/maximize/close/help), there should be an
Edit submenu with the same options within.

A pain, but at least feasible.



I know I'm coming to the conversation late, but here's what I do*:

1. Use Cygwin. (http://www.cygwin.com/)
2. Use PuttyCYG (http://code.google.com/p/puttycyg/)

That way, you can basically use PuTTY to shell into your Windows box.

Note: If you are familiar with the Linux command line, you will be in
love with this solution. If you're a Windows-only type, then be
forewarned that doing this will require you to type Unix/Linux
commands (for the most part) instead of DOS commands.

*Disclaimer: I use a Mac and Linux. This is my workaround when forced
to use Windows. Your environment preferences may vary.
--
http://mail.python.org/mailman/listinfo/python-list

===

Nope and no thanks.

I'm talking about a Dos Box on Win XP Pro
For Tim - I get junk from somewhere else in the system.
I recognize it from hours and many open/close boxes ago, but it's not 
what I 'swiped".


For Shawn - why would I want to run synthesizers? Or any other ...
(There is nothing wrong with Cygwin, just not on everybody's system.
Didn't come with the package.)

I write in Linux and test on other peoples Window$
 ^
 Thunderbird did not mark 
that as a miss spelling?!!!  Three cheers for them!


Objective - stick with out of the box to get way less install problems.



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


Re: About ODFPY links

2009-05-06 Thread Terry Reedy

shruti surve wrote:

hey all,
 For my project, i am using ODFpy open office spreadsheets. I am 
creating ledgers in python ie.ledger.py .  So when 
i run ledger.py, spreadsheet will be opened in open office. since ledger 
is made of number of accounts, i am creating multiple tables for all 
accounts in single spreadsheet. So, there are number of tables in one 
spreadsheet.  Now i want create links in each table of spreadsheet so 
that i can connect multiple tables. SO can anyone please tell me how to 
create links in odfpy..


The general answer to such questions is to make a minimal doc in some 
ODF application such of OOo that has the desired feature, save, open the 
doc as a zip file (unless saved as xml) and extract the pieces as xml. 
Then find the text that represents that feature.  There is a close 
correspondance between the xml and the internal document object model 
created by odfpy (and OOo, etc).


In your case, make a spreadsheet with two table.  Give one one literal 
entry.  Give the other one entry that links to the first.  Then look in 
the xml to see how links are presented.  That should give a hint as to 
how to do the same in odfpy.  Then try to recreate the minimal doc with 
odfpy and look at the xml *it* produces.  If it looks similar enough, 
open with OOo to see what you get.


tjr

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


Re: Copy & Paste in a Dos box

2009-05-06 Thread norseman

Mensanator wrote:

On May 6, 12:54 pm, Tim Chase  wrote:

for windows this works:
(can't cut and paste from a dos box!###%*&!!!)

Depending on how it was spawned, you can either right-click in
the window and choose Mark/Paste (when marking, use  to
terminate the selection; and selections are blockwise rectangular
rather than linewise or characterwise).  Alternatively, if you
click on the system menu (the icon in the title-bar with
resize/minimize/maximize/close/help), there should be an Edit
submenu with the same options within.

A pain, but at least feasible.


Less painful is to set the properties of the dos box:

Edit Options:
[x] Quick Edit mode

And when prompted, do "(.) modify shortcut that started this window"

After which, you can dispense with the menus (except when pasting),
just select the text and hit .

Makes a world of difference.


HTH,

-tkc


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


===
On a straight box - that doesn't work either.
The select all does, but paste yanked something from hours ago.
Yes - set as stated, closed and used icon to open box.

MicroSoft still need to soften its hard head and join the 21st century.

I love the ease of Linux.

One thing we do get from using both OS's - our first release code is 
much more solid as a result.


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


Re: Python 2.6 worth the hassle?

2009-05-06 Thread Gary Herron

Evan Kroske wrote:
I'm planning on learning Python, and I'd like to know which version to 
start with. I know that Python 3.0 isn't ready for production and it 
doesn't have enough libraries yet, so I thought I should learn Python 
2.6. Unfortunately, installing Python 2.6 on my Linux distro (Ubuntu 
Intrepid Ibex) has given me lots of complicated problems I really 
don't want to deal with.


Just learn 2.5.  From the beginners point of view, 2.5 and 2.6 are 
virtually the same.  (If you work hard, you can find differences, but 
you did say you were a beginner -- so don't worry about the differences 
-- they are minor and evolutionary not revolutionary.)



Gary Herron




My essential question is "Is Python 2.6 similar enough to Python 3.0 
to justify its complexity of installation?" Upgrading to Jaunty is NOT 
an option 
(http://welcome2obscurity.blogspot.com/2009/05/jaunty-jackalope-released-vista-all.html). 



Best regards,
Evan Kroske
Undecided Python Student
--
http://mail.python.org/mailman/listinfo/python-list


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


Re: SimpleXMLRPCServer and creating a new object on for each new client request.

2009-05-06 Thread Martin P. Hellwig

Jelle Smet wrote:

Hi list,

My goals is to have concurrent and separated client sessions using xmlrpc.
Initially my though was that SimpleXMLRPCServer was able to create a new
object instance for each incoming request.
But this doesn't appear to be the case, unless I'm overlooking something,
if so please point me out.

Concider following simplified code



SimpleXMLRPCServer, is rather, well eh, simple and does not support 
sessions, which in an HTTP point of view makes sense (where XML-RPC is 
based on). So either build in some sort of session management or rewrite 
your functionality in such a ways that it isn't dependent on sessions 
(see my reimplementation after my sig).


--
MPH
http://blog.dcuktec.com
'If consumed, best digested with added seasoning to own preference.'

#! /usr/bin/env python
#'example reimplementation'
"XML RPC test"
import SocketServer
import SimpleXMLRPCServer
import random
import xmlrpclib
import threading


# Create a simple example class
class Randomizer(object):
"Randomizer Docstring"
def __init__(self):
self.random_number = None

def randomize(self):
"create a new random number"
self.random_number = random.randrange(0, 10)

def show_random(self):
"show_random Docstring"
self.randomize()
return(self.random_number)

class Server(SocketServer.ThreadingMixIn,
 SimpleXMLRPCServer.SimpleXMLRPCServer):
"Multi-threaded XML RPC Server"
# pylint: disable-msg=R0904
def __init__(self):
address = ('localhost', 8000)
SimpleXMLRPCServer.SimpleXMLRPCServer.__init__(self, address)
self.allow_none = True
self.register_instance(Randomizer())
self.register_function(self.shutdown_service)
self.register_introspection_functions()
# pylint: enable-msg=R0904

def shutdown_service(self):
"Stop server"
self.shutdown()


class Thread(threading.Thread):
"Run Server in a thread for testing purposes"
def run(self):
"Run the service"
service = Server()
service.serve_forever()

if __name__ == '__main__':
URL_PORT = 'http://localhost:8000'
TEST_THREAD = Thread()
TEST_THREAD.start()
SESSION1 = xmlrpclib.ServerProxy(URL_PORT)
SESSION2 = xmlrpclib.ServerProxy(URL_PORT)
print(SESSION1.show_random())
print(SESSION2.show_random())
SESSION_STOP = xmlrpclib.ServerProxy(URL_PORT)
SESSION_STOP.shutdown_service()
#'example reimplementation'
--
http://mail.python.org/mailman/listinfo/python-list


Re: Copy & Paste in a Dos box

2009-05-06 Thread MRAB

Mensanator wrote:

On May 6, 3:46 pm, Dave Angel  wrote:

Mensanator wrote:


And when prompted, do "(.) modify shortcut that started this window"
After which, you can dispense with the menus (except when pasting),
just select the text and hit .
To paste into a DOS box, once Quick Edit is enabled, use Right-Click.  
They keystrokes will be sent to the command editor.  Note that the

interpretation is rather literal, so be careful if copy/pasting more
than one line, or a line that was wrapped.


Well I'll be dipped. Didn't know you could do that.

Of course, since I learned how to call programs from the
script and capture their StdOut, I don't have much call for
cut/paste from dos windows. Hopefully, I'll remember that the
next time I need it.


That's new to me too!

You probably already know that if you drag-and-drop a file onto the
window you get its path.
--
http://mail.python.org/mailman/listinfo/python-list


Could this expression parser be more 'Pythonic'?

2009-05-06 Thread Amr
Hello all,

I've been spending the last few weeks learning Python, and I've just
started to use it to write a simple BASIC compiler. I'm writing a
mathematical expression parser and wrote a function that would take a
string and split it into high level tokens.

The code can be found at http://pastebin.com/f757252ec (have a look at
the function tokenize).

I was interested to see if the tokenize function could be written in a
better way, so as to make better use of the Python language and
libraries. One thing that sprung to mind was whether it would be a
good idea to perhaps take advantage of regular expressions. I had a
look at a few compiler sites and regexps seem to come into that role
quite a bit. I've only done a little work on regexps and they seem
very powerful, but can easily get out of control!

So, any suggestions as to how to make better use of the language
writing something like this?

Thanks,

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


Re: Copy & Paste in a Dos box

2009-05-06 Thread norseman

Dave Angel wrote:

Tim Chase wrote:
> for 
windows this works:

(can't cut and paste from a dos box!###%*&!!!)


Depending on how it was spawned, you can either right-click in the 
window and choose Mark/Paste (when marking, use  to terminate 
the selection; and selections are blockwise rectangular rather than 
linewise or characterwise).  Alternatively, if you click on the system 
menu (the icon in the title-bar with 
resize/minimize/maximize/close/help), there should be an Edit submenu 
with the same options within.


A pain, but at least feasible.

HTH,

-tkc


Note that if you like copy/paste, you can turn on "Quick Edit" mode in 
your cmd.exe windows.  From that same System menu on your DOS box, 
choose "Defaults".  From the first tab that box, enable "Quick Edit" 
checkbox.   This will change the default for subsequent DOS boxes.  You 
can change it just for the current one by using Properties in the same 
system menu.



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




HuMM - Dave's use of cmd.exe as different from Dos Box points out a 
miss name on my part. I should have said cmd.exe originally.


Yes - I use dosemu on Linux Slackware 10.2 with enlightenment 16.2 and 
swipe/paste works as it should. (Of course gpm is loaded. That's a must. :)


I have been cutting back. Used to have 6 keyboards going at once. (well 
in packet passing mode shall we say? When computers were slower. :) 
Down to two close by and two across the way. One Solaris, two Linux, one 
Win XP.  Gotta keep the Win machine nearby. It needs its daily crash. I 
have learned to stick to 'stock' setups or pay a heavy price at "show time".


I tried the settings again just now.
I did both Properties and Default and made sure they were set the same.
I did the --- for icon --- and killed the open box and clicked the icon 
and swiped and pasted to wordpad.  IT FINALLY WORKED!!!


Hadn't intended to start such a rash of dialog, but I benefited too!

Thanks guys!!!


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


Re: Copy & Paste in a Dos box

2009-05-06 Thread Mensanator
On May 6, 6:15 pm, MRAB  wrote:
> Mensanator wrote:
> > On May 6, 3:46 pm, Dave Angel  wrote:
> >> Mensanator wrote:
> >>> 
> >>> And when prompted, do "(.) modify shortcut that started this window"
> >>> After which, you can dispense with the menus (except when pasting),
> >>> just select the text and hit .
> >> To paste into a DOS box, once Quick Edit is enabled, use Right-Click.  
> >> They keystrokes will be sent to the command editor.  Note that the
> >> interpretation is rather literal, so be careful if copy/pasting more
> >> than one line, or a line that was wrapped.
>
> > Well I'll be dipped. Didn't know you could do that.
>
> > Of course, since I learned how to call programs from the
> > script and capture their StdOut, I don't have much call for
> > cut/paste from dos windows. Hopefully, I'll remember that the
> > next time I need it.
>
> That's new to me too!
>
> You probably already know that if you drag-and-drop a file onto the
> window you get its path.

Damn! I may just go back to using Python from the command prompt
instead of using IDLE.

On second thought, IDLE is way too useful for indenting, dedenting,
commenting and uncommenting blocks of code. Can't go back to using
Notepad.

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


Simple way of handling errors

2009-05-06 Thread TomF
As a relative newcomer to Python, I like it a lot but I'm dismayed at 
the difficulty of handling simple errors.  In Perl if you want to 
anticipate a file-not-found error you can simply do:


open($file)  or die("open($file): $!");

and you get an intelligible error message.  In Python, to get the same 
thing it appears you need at least:


try:
   f=open(file)
except IOError, err:
   print "open(%s): got %s" % (file, err.strerror)
   exit(-1)

Is there a simpler interface or idiom for handling such errors?  I 
appreciate that Python's exception handling is much more sophisticated 
but often I don't need it.


-Tom

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


How do I escape slashes the string formatting operator? (or: why is it behaving this way?)

2009-05-06 Thread Dustan
Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit
(Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> 'HELP!%(xyz)/' % {'xyz':' PLEASE! '}
Traceback (most recent call last):
  File "", line 1, in 
ValueError: unsupported format character '/' (0x2f) at index 11
>>>

It doesn't like the forward slash after the closed parentheses. I
don't know what it is expecting, but I need that slash there
(obviously this is a simplified example).

All help appreciated.
--
http://mail.python.org/mailman/listinfo/python-list


Re: How do I escape slashes the string formatting operator? (or: why is it behaving this way?)

2009-05-06 Thread marek . rocki
Dustan napisał(a):
> Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit
> (Intel)] on
> win32
> Type "help", "copyright", "credits" or "license" for more information.
> >>> 'HELP!%(xyz)/' % {'xyz':' PLEASE! '}
> Traceback (most recent call last):
> File "", line 1, in 
> ValueError: unsupported format character '/' (0x2f) at index 11
> >>>
>
> It doesn't like the forward slash after the closed parentheses. I
> don't know what it is expecting, but I need that slash there
> (obviously this is a simplified example).
>
> All help appreciated.

Strign formatting docs (http://docs.python.org/library/
stdtypes.html#string-formatting) say that specifying a conversion type
is mandatory. So you actually should write something like:
'HELP!%(xyz)s/' % {'xyz':' PLEASE! '}
--
http://mail.python.org/mailman/listinfo/python-list


Re: How do I escape slashes the string formatting operator? (or: why is it behaving this way?)

2009-05-06 Thread Dustan
On May 6, 6:51 pm, marek.ro...@wp.pl wrote:
> Dustan napisa³(a):
>
> > Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit
> > (Intel)] on
> > win32
> > Type "help", "copyright", "credits" or "license" for more information.
> > >>> 'HELP!%(xyz)/' % {'xyz':' PLEASE! '}
> > Traceback (most recent call last):
> > File "", line 1, in 
> > ValueError: unsupported format character '/' (0x2f) at index 11
>
> > It doesn't like the forward slash after the closed parentheses. I
> > don't know what it is expecting, but I need that slash there
> > (obviously this is a simplified example).
>
> > All help appreciated.
>
> Strign formatting docs (http://docs.python.org/library/
> stdtypes.html#string-formatting) say that specifying a conversion type
> is mandatory. So you actually should write something like:
> 'HELP!%(xyz)s/' % {'xyz':' PLEASE! '}

Thanks. That seems to have worked nicely.
--
http://mail.python.org/mailman/listinfo/python-list


Threading and GIL

2009-05-06 Thread googler . 1 . webmaster
Hi!

I have a big problem I can't solve and I hope anyone of you can help
me. I use the Python C API and in C++ I have a class which represets a
thread object, similiar to the thread class of the known Python Thread
class but with some needed additions so thats the reason why I have to
built my own. Well, this is the problem.

There is a method called Thread::End() which I can call in Python. But
now the End() Function waits until the "Main" Function of my C++ class
is done, but in this method I want to ensure the Global Interpreter
Lock but this is already locked by the Thread which executes the End()
command. So both is waiting and stops. The thread which calls the End
() method is waiting for the finish of the Main() method of the Thread
Class and the Main-Method in the other thread waits for the thread of
the End() command that this is done - welcome Deadlock.

Any suggestions what I have to do? Thank you veeery much for you help,
otherwise I become really crazy here because this is the first time I
have such a problem.


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


Re: Copy & Paste in a Dos box (was: Pyhton script to call another program)

2009-05-06 Thread Dave Angel

Mensanator wrote:

On May 6, 3:46 pm, Dave Angel  wrote:
  

Mensanator wrote:



  
And when prompted, do "(.) modify shortcut that started this window"
  
After which, you can dispense with the menus (except when pasting),

just select the text and hit .
  
To paste into a DOS box, once Quick Edit is enabled, use Right-Click.  
They keystrokes will be sent to the command editor.  Note that the

interpretation is rather literal, so be careful if copy/pasting more
than one line, or a line that was wrapped.



Well I'll be dipped. Didn't know you could do that.

Of course, since I learned how to call programs from the
script and capture their StdOut, I don't have much call for
cut/paste from dos windows. Hopefully, I'll remember that the
next time I need it.

  
As long as we're in Quick Edit mode, another trick is that you can 
double-click on a "word" in a DOS box to select it and copy to 
clipboard.  Obviously it isn't always the exact string you want, but 
sometimes it beats dragging the mouse over the text.



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


Re: Copy & Paste in a Dos box

2009-05-06 Thread Dave Angel

norseman wrote:


On a straight box - that doesn't work either.
The select all does, but paste yanked something from hours ago.


Once you have Quick Edit enabled, paste will work using right-click.  If 
it got something from hours ago, then that must be the last time you 
copied anything to the real clipboard.  Note that some applications use 
a private clipboard to give extra features (like multiple clipboxes).  
But I suspect your real problem is you thought you did a copy to the 
clipboard from the DOS box, and you did not.


When you drag the mouse over the box, you *select* text, but do not copy 
it to the clipboard.  That doesn't happen till your right-click.


Then *another* right-click without anything selected will insert that 
new text into the command line.


Try the following on a DOS box (after enabling Quick Edit).  
Double-click on a "word".  Then right click *twice* to get it to the 
command line.



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


  1   2   >