Re: Running a command line program and reading the result as it runs

2013-08-23 Thread Ian Simcock

Rob Wolfe wrote:

Ian Simcock  writes:

When file object is used in a for loop it works like an iterator
and then it uses a hidden read-ahead buffer.
It might cause this kind of blocking.
You can read more details here (description of method ``next``):
http://docs.python.org/lib/bltin-file-objects.html

So basically non-blocking loop might look like this:

while True:
 line = p.stdout.readline()
 if not line: break
 print line

HTH,
Rob



Thanks, but some further research seems to indicate that the problem is 
that the standard C libraries are probably buffering the output when the 
it's being redirected, so the problem is coming from the command line 
tool rather than the python code.


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


Re: Basic Python Query

2013-08-23 Thread Ulrich Eckhardt

Am 23.08.2013 05:28, schrieb Steven D'Aprano:

On Thu, 22 Aug 2013 13:54:14 +0200, Ulrich Eckhardt wrote:

When the Python object goes away, it doesn't necessarily affect
thethread or file it represents.

>

That's certainly not true with file objects. When the file object goes
out of scope, the underlying low-level file is closed.


Ahem, yes, but no: Calling close(fd) is not the same as destroying the 
file, I'm pretty sure it's still on my harddisk after that. That is also 
the difference to strings, where the Python object really is all there 
is to it. Similarly you can only customize the Python side of things 
with derivation, the other side will remain the same, apart from the 
data you write to the file or the code you run in the thread.


Steven, thank you for taking the time to read and consider what I wrote, 
it is appreciated!


Uli

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


Re: Using PyQT with QT Designer

2013-08-23 Thread Phil Thompson
On Thu, 22 Aug 2013 18:08:14 -0700 (PDT), tausc...@gmail.com wrote:
> On Thursday, August 22, 2013 3:26:17 AM UTC-5, Phil Thompson wrote:
> 
>> It looks like you aren't using a layout to arrange your widgets.
>> 
>> Explicitly specifying geometries is a bad idea.
>> 
>> 
>> 
>> Phil
> 
> Thanks.QT Designer uses set geometry

...only because you have told it to...

> and I'm totally lost as how to
> implement it. I've tried using a layout on the central widget. I've
tried
> specifically referencing the Ui_MainWindow in the window.py ui file...

You need to read up on how to use layouts in Designer. The generated .py
file will then do what you want automatically.

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


Re: PEPs should be included with the documentation download

2013-08-23 Thread Ned Deily
In article <7wvc2xkjvz@benfinney.id.au>,
 Ben Finney  wrote:
> Chris Angelico  writes:
> > Hence the question: How many people actually do use the downloaded
> > docs? Maybe it'd turn out to be quite high, but it's not an
> > unreasonable question.
> 
> I think it's an unreasonable question. What would you accept as an
> answer? Who could possibly be autoritative at estimating such a number?
> How would you choose between competing authorities and estimates?
> 
> It should be sufficient to realise that the reality of internet
> infrastructure in most countries makes it preferable – at least some of
> the time, for some significant, even if small, number of users – to read
> the documentation on local storage instead of on the internet.

In any case if you want to see this happen, someone needs to open an 
issue and make a case for it on the Python bug tracker.

-- 
 Ned Deily,
 n...@acm.org

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


Sergei Ivachev

2013-08-23 Thread sepatan
Maybe someone from the Python community tried to run Python (with a
possible set of standard library modules) under the Google Native Client
in browser?
 If you have a positive experience, can share?

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


Who run the Python for Google Native Client?

2013-08-23 Thread sepatan
Maybe someone from the Python community tried to run Python (with a
possible set of standard library modules) under the Google Native Client
in browser?
 If you have a positive experience, can share?

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


Re: PEPs should be included with the documentation download

2013-08-23 Thread Ben Finney
Ned Deily  writes:

> In article <7wvc2xkjvz@benfinney.id.au>,
>  Ben Finney  wrote:
> > Chris Angelico  writes:
> > > Hence the question: How many people actually do use the downloaded
> > > docs? Maybe it'd turn out to be quite high, but it's not an
> > > unreasonable question.
> > 
> > I think it's an unreasonable question [in this context].

> In any case if you want to see this happen, someone needs to open an 
> issue and make a case for it on the Python bug tracker.

Neither Chris nor I are proposing to have PEPs in the installed
documentation :-) You might want to respond directly to the original
post with that suggestion.

-- 
 \ “Men never do evil so completely and cheerfully as when they do |
  `\it from religious conviction.” —Blaise Pascal (1623–1662), |
_o__)   Pensées, #894. |
Ben Finney

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


Re: Running a command line program and reading the result as it runs

2013-08-23 Thread Gertjan Klein

Ian Simcock wrote:


When I use this code I can see that the Popen works, any code between
the Popen and the for will run straight away, but as soon as it gets to
the for and tries to read p.stdout the code blocks until the command
line program completes, then all of the lines are returned.

Does anyone know how to get the results of the program without it blocking?


I have tried your code with "ping google.com" as command and got the 
same results; apparently something buffers the output. The result is 
different when using Python 3.3: there, the lines are printed as they 
come in. This seems to indicate a bug in the Python 2.7 implementation.


There are some bug reports on bugs.python.org that may be related; see 
for example:


http://bugs.python.org/issue15532

I have been playing around a bit with the suggested approach of using 
the io library directly. I managed to get unbuffered output, but 
unfortunately the program hangs when the subprocess is done. It can't 
even be terminated with Control-C, I have to use task manager to kill 
python.exe.


Below is as far as I got; perhaps someone with more experience with 
pipes knows how to fix this.


Regards,
Gertjan.


#!/usr/bin/env python2.7
# coding: CP1252

from __future__ import print_function
import subprocess
import io, os

def main():
i, o = os.pipe()
piperead = io.open(i, 'rb', buffering=1)

p = subprocess.Popen(["ping", "google.com"],
  stdout=o,
  stderr=subprocess.PIPE,
  bufsize=0,
  shell=False)

for line in piperead:
print(line)

if __name__ == '__main__':
main()


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


Re: Running a command line program and reading the result as it runs

2013-08-23 Thread Antoon Pardon
Op 22-08-13 07:51, Ian Simcock schreef:
> Greetings all.
> 
> I'm using Python 2.7 under Windows and am trying to run a command line
> program and process the programs output as it is running. A number of
> web searches have indicated that the following code would work.
> 
> import subprocess
> 
> p = subprocess.Popen("D:\Python\Python27\Scripts\pip.exe list -o",
>  stdout=subprocess.PIPE,
>  stderr=subprocess.STDOUT,
>  bufsize=1,
>  universal_newlines=True,
>  shell=False)
> for line in p.stdout:
> print line
> 
> When I use this code I can see that the Popen works, any code between
> the Popen and the for will run straight away, but as soon as it gets to
> the for and tries to read p.stdout the code blocks until the command
> line program completes, then all of the lines are returned.
> 
> Does anyone know how to get the results of the program without it blocking?

Maybe the following can work?

Untested code:

from pty import openpty
from subprocess import Popen

master, slave = openpty()

p = Popen("D:\Python\Python27\Scripts\pip.exe list -o",
  stdout = slave,
  stderr = slave,
  stdin = slave,
  close_fds = True)

for line in master:
print line


The idea is to set a a pseudo terminal for pip so that the
system thinks pip is doing IO with a terminal and so the
IO will be line buffered. But all IO from pip will be available
through the master in your program.

-- 
Antoon Pardon

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


Re: Running a command line program and reading the result as it runs

2013-08-23 Thread Antoon Pardon
Op 23-08-13 11:53, Antoon Pardon schreef:
> Op 22-08-13 07:51, Ian Simcock schreef:
>> Greetings all.
>>
>> I'm using Python 2.7 under Windows and am trying to run a command line
>> program and process the programs output as it is running. A number of
>> web searches have indicated that the following code would work.
>>
>> import subprocess
>>
>> p = subprocess.Popen("D:\Python\Python27\Scripts\pip.exe list -o",
>>  stdout=subprocess.PIPE,
>>  stderr=subprocess.STDOUT,
>>  bufsize=1,
>>  universal_newlines=True,
>>  shell=False)
>> for line in p.stdout:
>> print line
>>
>> When I use this code I can see that the Popen works, any code between
>> the Popen and the for will run straight away, but as soon as it gets to
>> the for and tries to read p.stdout the code blocks until the command
>> line program completes, then all of the lines are returned.
>>
>> Does anyone know how to get the results of the program without it blocking?
> 
> Maybe the following can work?

Never mind. I had overlooked that using pty requires linux and you are
using windows.

-- 
Antoon Pardon

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


RE: Running a command line program and reading the result as it runs

2013-08-23 Thread Joseph L. Casale
> >> I'm using Python 2.7 under Windows and am trying to run a command line
> >> program and process the programs output as it is running. A number of
> >> web searches have indicated that the following code would work.
> >>
> >> import subprocess
> >>
> >> p = subprocess.Popen("D:\Python\Python27\Scripts\pip.exe list -o",
> >>  stdout=subprocess.PIPE,
> >>  stderr=subprocess.STDOUT,
> >>  bufsize=1,
> >>  universal_newlines=True,
> >>  shell=False)
> >> for line in p.stdout:
> >> print line
> >>
> >> When I use this code I can see that the Popen works, any code between
> >> the Popen and the for will run straight away, but as soon as it gets to
> >> the for and tries to read p.stdout the code blocks until the command
> >> line program completes, then all of the lines are returned.
> >>
> >> Does anyone know how to get the results of the program without it
> >> blocking?

Try this:

p = subprocess.Popen(args, stdout=subprocess.PIPE)
for line in p.stdout:
print(line)
p.wait()

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


Re: Running a command line program and reading the result as it runs

2013-08-23 Thread Peter Otten
Ian Simcock wrote:

> Greetings all.
> 
> I'm using Python 2.7 under Windows and am trying to run a command line
> program and process the programs output as it is running. A number of
> web searches have indicated that the following code would work.
> 
> import subprocess
> 
> p = subprocess.Popen("D:\Python\Python27\Scripts\pip.exe list -o",
>   stdout=subprocess.PIPE,
>   stderr=subprocess.STDOUT,
>   bufsize=1,
>   universal_newlines=True,
>   shell=False)
> for line in p.stdout:
>  print line
> 
> When I use this code I can see that the Popen works, any code between
> the Popen and the for will run straight away, but as soon as it gets to
> the for and tries to read p.stdout the code blocks until the command
> line program completes, then all of the lines are returned.
> 
> Does anyone know how to get the results of the program without it
> blocking?

The following works on my linux system:

import subprocess

p = subprocess.Popen(
["ping", "google.com"],
stdout=subprocess.PIPE)

instream = iter(p.stdout.readline, "")

for line in instream:
print line.rstrip()

I don't have Windows available to test, but if it works there, too, the 
problem is the internal buffer used by Python's implementation of file 
iteration rather than the OS.

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


Python variable as a string

2013-08-23 Thread Jake Angulo
Sorry this is a very basic question.

I have a list *var* which after some evaluation I need to refer to *var* as
a string.

Pseudocode:

var = ['a', 'b' , 'c' , 'd']
adict = dict(var='string', anothervar='anotherstring')
anotherdict = dict()
if :
anotherdict[akey] = adict['var']


Basically im evaluating the list *var*, and if true, i want to use *var* as
a string so that i can refer to a key-value pair in *adict *(whose key name
is also var for convenience).
*
*
Or maybe i should do things differently?

Any help and code will be appreciated!
-- 
http://mail.python.org/mailman/listinfo/python-list


What does sys.stdout.flush() do?

2013-08-23 Thread D. Xenakis
Somewhere i read..
sys.stdout.flush(): Flush on a file object pushes out all the data that has 
been buffered to that point.

Can someone post here a script example with sys.stdout.flush(), where in case i 
commented that i could understand what the difference really would be?

Whenever i try to remove that line (in scripts that i find online), i cant find 
any differences. I've just noticed that it is usually called right after 
sys.stdout.write(..) 
thx
-- 
http://mail.python.org/mailman/listinfo/python-list



Re: Running a command line program and reading the result as it runs

2013-08-23 Thread Gertjan Klein

Peter Otten wrote:


The following works on my linux system:

import subprocess

p = subprocess.Popen(
 ["ping", "google.com"],
 stdout=subprocess.PIPE)

instream = iter(p.stdout.readline, "")

for line in instream:
 print line.rstrip()

I don't have Windows available to test, but if it works there, too, the
problem is the internal buffer used by Python's implementation of file
iteration rather than the OS.


Excellent, that works on Windows as well. That conclusively proves that 
the buffering problem is in Python, not in the command that is executed. 
(Although that may happen, too, for some commends.)


Regards,
Gertjan.


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


Re: What does sys.stdout.flush() do?

2013-08-23 Thread Peter Otten
D. Xenakis wrote:

> Somewhere i read..
> sys.stdout.flush(): Flush on a file object pushes out all the data that
> has been buffered to that point.
> 
> Can someone post here a script example with sys.stdout.flush(), where in
> case i commented that i could understand what the difference really would
> be?
> 
> Whenever i try to remove that line (in scripts that i find online), i cant
> find any differences. I've just noticed that it is usually called right
> after sys.stdout.write(..) thx

Use time.sleep() to see the effects of (line) buffering. Type the following 
in your interactive interpreter and be enlightened ;)

>>> import sys, time
>>> for i in range(10):
... print i,
... time.sleep(.1)
... 
0 1 2 3 4 5 6 7 8 9
>>> for i in range(10):
... print i,
... sys.stdout.flush()
... time.sleep(.1)
... 
0 1 2 3 4 5 6 7 8 9


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


How to send broadcast IP address to network?

2013-08-23 Thread lightaiyee
I want to send a broadcast packet to all the computers connected to my home 
router. 

The following 2 lines of code do not work;
host="192.168.0.102"
s.connect((host, port))

Can someone advise?

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


Re: How to send broadcast IP address to network?

2013-08-23 Thread lightaiyee
Some typo mistake. 
Should be host="192.168.0.255", not "192.168.0.102"

On Friday, August 23, 2013 8:32:10 PM UTC+8, light...@gmail.com wrote:
> I want to send a broadcast packet to all the computers connected to my home 
> router. 
> 
> 
> 
> The following 2 lines of code do not work;
> 
> host="192.168.0.102"
> 
> s.connect((host, port))
> 
> 
> 
> Can someone advise?
> 
> 
> 
> Thank you.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Using PyQT with QT Designer

2013-08-23 Thread Michael Staggs
I tried that this morning and it destroyed my form. So, right now, that's
probably not what I'm looking for.

But, if you look at that picture, the app isn't resized to 800x600 like it
says in the ui file. The pixmaps aren't on the buttons like I set them up
in the ui file. It's not using the ui file at all. So, what's the point of
making a QT Designer file at all if it doesn't use it?

I'm guessing it CAN use it and there is just something I'm missing.

You may be right and I may not want to set the geometry in qt designer down
the road. But, right now I do and not only is it not getting that from the
ui fileit's not getting anything at all...even though I added all the
lines I thought I needed to.

If I decide to actually change the gui later, I'd like to be able to use QT
Designer to do so...design a layout and not really have to change my
program. As it stands, it's totally ignoring my ui file and I have to redo
all the work in the program. In which case, there's no point to using qt
designer at all.

I know I have to be missing something though there has to be a way to
use the work qt designer did.

Thanks
On Aug 23, 2013 2:39 AM, "Phil Thompson" 
wrote:

> On Thu, 22 Aug 2013 18:08:14 -0700 (PDT), tausc...@gmail.com wrote:
> > On Thursday, August 22, 2013 3:26:17 AM UTC-5, Phil Thompson wrote:
> >
> >> It looks like you aren't using a layout to arrange your widgets.
> >>
> >> Explicitly specifying geometries is a bad idea.
> >>
> >>
> >>
> >> Phil
> >
> > Thanks.QT Designer uses set geometry
>
> ...only because you have told it to...
>
> > and I'm totally lost as how to
> > implement it. I've tried using a layout on the central widget. I've
> tried
> > specifically referencing the Ui_MainWindow in the window.py ui file...
>
> You need to read up on how to use layouts in Designer. The generated .py
> file will then do what you want automatically.
>
> Phil
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to send broadcast IP address to network?

2013-08-23 Thread Neil Cerutti
On 2013-08-23, lightai...@gmail.com  wrote:
>> The following 2 lines of code do not work;
>> 
>> host="192.168.0.255"
>> host="192.168.0.102"
>> s.connect((host, port))

Traceback (most recent call last):
  File "", line 1, in 
NameError: name 's' is not defined

I bet that's not the same traceback you get. Furthermore, port
isn't defined either.

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


Re: PEPs should be included with the documentation download

2013-08-23 Thread Neil Cerutti
On 2013-08-23, Chris Angelico  wrote:
> I'm aware of that. However, I'm also aware that many people
> still read things online, even with a less-than-reliable
> internet connection. Hence the question: How many people
> actually do use the downloaded docs? Maybe it'd turn out to be
> quite high, but it's not an unreasonable question.

I use the compiled html/windows help and the integrated with the
interpreter html version of the Python docs, both downloaded and
installed for easy access.

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


Re: Python variable as a string

2013-08-23 Thread Neil Cerutti
On 2013-08-23, Jake Angulo  wrote:
> I have a list *var* which after some evaluation I need to refer
> to *var* as a string.

You must make a str version of var.

> Pseudocode:
>
> var = ['a', 'b' , 'c' , 'd']
> adict = dict(var='string', anothervar='anotherstring')
> anotherdict = dict()
> if :
> anotherdict[akey] = adict['var']

anotherdict[akey] = adict[str(var)]

Will actually work, though you might prefer:

anotherdict[akey] = adict[''.join(var)]

Try them out and see.

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


Re: Python variable as a string

2013-08-23 Thread Steven D'Aprano
On Fri, 23 Aug 2013 21:40:06 +1000, Jake Angulo wrote:

> Sorry this is a very basic question.

Not so much "basic" as confusing.

> I have a list *var* which after some evaluation I need to refer to *var*
> as a string.
> 
> Pseudocode:
> 
> var = ['a', 'b' , 'c' , 'd']
> adict = dict(var='string', anothervar='anotherstring')

This creates a dict with two keys, "var" and "anothervar". If you print 
it, you will get this:

{'var': 'string', 'anothervar': 'anotherstring'}

Is that what you intended? If not, what did you intend?


> anotherdict = dict()
> if :
> anotherdict[akey] = adict['var']

I don't understand what this code has to do with your question. Your 
explanation below doesn't seem to have anything to do with the code you 
show here. You don't evaluate the list var, or test it in a truth 
context. Apart from wrapping condition in angle brackets, for no reason I 
understand, the above is perfectly fine Python code (except, of course, 
condition and akey are undefined).


> Basically im evaluating the list *var*, and if true, i want to use *var*
> as a string so that i can refer to a key-value pair in *adict *(whose
> key name is also var for convenience).

I don't understand what you are trying to accomplish, but I have two 
guesses. If you want a string "var", just type "var" in quotation marks, 
like you do above.

If you want to use the *contents* of variable var as a string, just call 
the str() function on it:

py> alist = ['a', 'b' , 'c' , 'd']
py> key = str(alist)
py> adict={}
py> adict[key] = "whatever you like"
py> adict
{"['a', 'b', 'c', 'd']": 'whatever you like'}


Or if you prefer:

py> {key: "whatever"}
{"['a', 'b', 'c', 'd']": 'whatever'}


If you want something else, you'll need to explain more carefully what 
you want.


> Or maybe i should do things differently?

Possibly. What sort of things did you have in mind? :-)



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


Re: Running a command line program and reading the result as it runs

2013-08-23 Thread Grant Edwards
On 2013-08-22, Chris Angelico  wrote:
> On Fri, Aug 23, 2013 at 1:26 AM, Ian Simcock
> wrote:
>> Chris Angelico wrote:
>>>
>>> Is the program actually producing output progressively? I just tried
>>> your exact code with "dir /ad /s /b" and it worked fine, producing
>>> output while the dir was still spinning (obviously setting shell=True
>>> to make that work, but I don't think that'll make a difference). It
>>> may be that pip buffers its output. Is there a parameter to pip to
>>> make it pipe-compatible?
>>>
>>> ChrisA
>>>
>>
>> If I run pip in the command window I can see it's output appearing line by
>> line rather than on one block.
>>
>> I tried the code with the dir command but it's too fast for me to be sure if
>> it's working or not.
>>
>> I tried again using the command "ping google.com" instead since I know that
>> output's slowly and it something that everyone should have. In the command
>> window I can see that the output appears over time, but from python I get
>> nothing for a while and then suddenly get all the output in one rapid go.
>>
>>
>> Can you think of anything else I can look at?
>
> A lot of programs, when their output is not going to the console,
> will buffer output. It's more efficient for many purposes. With Unix
> utilities, there's often a parameter like --pipe or --unbuffered that
> says "please produce output line by line", but Windows ping doesn't
> have that - and so I'm seeing the same thing you are.

Another way this problem can be avoided on Unix is to connect the
slave end of a pty (instead of a pipe) to the command's stdout/stderr
and then read the command's output from the master end of the pty.
[On Unix, the buffering decision is based on whether stdout is a tty
device, not on whether it's the console.]

Dunno whether Windows has ptys or not.  They're a very simple, elegent
solution to a number of problems, so I'm guessing not. ;)

-- 
Grant Edwards   grant.b.edwardsYow! ... the MYSTERIANS are
  at   in here with my CORDUROY
  gmail.comSOAP DISH!!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What does sys.stdout.flush() do?

2013-08-23 Thread John Gordon
In  "D. Xenakis" 
 writes:

> Can someone post here a script example with sys.stdout.flush(), where in
> case i commented that i could understand what the difference really would
> be?

Depending what sys.stdout is connected to (a file, the screen, a pipe,
etc.), data doesn't necessarily get written right away.  In particular,
screen output often waits until it receives a newline before displaying
anything.

flush() makes sure it all gets written *right now*.

-- 
John Gordon   A is for Amy, who fell down the stairs
gor...@panix.com  B is for Basil, assaulted by bears
-- Edward Gorey, "The Gashlycrumb Tinies"

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


Re: Can a child access parent attributes if that child added post-hoc as an attribute to the parent?

2013-08-23 Thread Bitswapper
On Thursday, August 22, 2013 5:00:38 PM UTC-5, Bitswapper wrote:
> On Thursday, August 22, 2013 4:26:24 PM UTC-5, Prasad, Ramit wrote:
> 
> > Bitswapper wrote:
> 
> > 
> 
> > >
> 
> > 
> 
> > > So I have a parent and child class:
> 
> > 
> 
> > >
> 
> > 
> 
> > >
> 
> > 
> 
> > > class Map(object):
> 
> > 
> 
> > > def __init__(self, name=''):
> 
> > 
> 
> > > self.mapName = name
> 
> > 
> 
> > > self.rules = {}
> 
> > 
> 
> > >
> 
> > 
> 
> > > class Rule(Map):
> 
> > 
> 
> > > def __init__(self, number):
> 
> > 
> 
> > > Map.__init__(self)
> 
> > 
> 
> > > self.number = number
> 
> > 
> 
> > 
> 
> > 
> 
> > This means that rules will never have a name. I think you need
> 
> > 
> 
> >   def __init__(self, name='', number=None):
> 
> > 
> 
> >   Map.__init__(self, name)
> 
> > 
> 
> >   self.number = number
> 
> > 
> 
> > >
> 
> > 
> 
> > > def __repr__(self):
> 
> > 
> 
> > > return "Map " + self.mapName + " rule number " + str(self.number)
> 
> > 
> 
> > >
> 
> > 
> 
> > > if __name__ == "__main__":
> 
> > 
> 
> > >   map = Map("thismap")
> 
> > 
> 
> > >   rule = Rule(1)
> 
> > 
> 
> > >   map.rules[rule.number] = rule
> 
> > 
> 
> > >
> 
> > 
> 
> > >
> 
> > 
> 
> > >
> 
> > 
> 
> > > with the above:
> 
> > 
> 
> > > $ python -i inherit.py
> 
> > 
> 
> > > >>> map
> 
> > 
> 
> > > <__main__.Map object at 0xb7e889ec>
> 
> > 
> 
> > > >>> map.rules
> 
> > 
> 
> > > {1: Map  rule number 1}
> 
> > 
> 
> > > >>> map.rules[1]
> 
> > 
> 
> > > Map  rule number 1
> 
> > 
> 
> > > >>>
> 
> > 
> 
> > >
> 
> > 
> 
> > >
> 
> > 
> 
> > > I have tried adding:
> 
> > 
> 
> > >   map.rules[2] = Rule(2)
> 
> > 
> 
> > >
> 
> > 
> 
> > > but that still gets:
> 
> > 
> 
> > >
> 
> > 
> 
> > > $ python -i inherit.py
> 
> > 
> 
> > > >>> map.rules
> 
> > 
> 
> > > {1: Map  rule number 1, 2: Map  rule number 2}
> 
> > 
> 
> > > >>>
> 
> > 
> 
> > >
> 
> > 
> 
> > > and:
> 
> > 
> 
> > > map.rule = Rule(3)
> 
> > 
> 
> > >
> 
> > 
> 
> > > which also doesn't really get me what I'm looking for:
> 
> > 
> 
> > >
> 
> > 
> 
> > > >>> map.rules
> 
> > 
> 
> > > {1: Map  rule number 1, 2: Map  rule number 2}
> 
> > 
> 
> > > >>> map.rule
> 
> > 
> 
> > > Map  rule number 3
> 
> > 
> 
> > > >>>
> 
> > 
> 
> > >
> 
> > 
> 
> > >
> 
> > 
> 
> > > It seems to me what I'm trying to do is link an arbitrary child instance 
> > > to an arbitrary instance of a
> 
> > 
> 
> > > parent class, which in this case would be handy  Because I'd like to 
> > > populate a map with rules and
> 
> > 
> 
> > > print the rules including the parent map name for each rule.  I'm just 
> > > not sure how I would go about
> 
> > 
> 
> > > doing this in python.
> 
> > 
> 
> > >
> 
> > 
> 
> > > Any thoughts are welcome, and thanks in advance
> 
> > 
> 
> > 
> 
> > 
> 
> > I not sure what you mean by the above. Can you provide an example of what 
> > you want to occur and the output for it?
> 
> > 
> 
> 
> 
> I was thinking of:
> 
> 
> 
> map = Map('myMap')
> 
> map.rules[1] = Rule(1)
> 
> map.rules[2] = Rule(2)
> 
> 
> 
> >>> print map.rules[1]
> 
> >>> Map myMap rule number 1
> 
> >>> print map.rules[2]
> 
> >>> Map myMap rule number 2
> 
> >>>
> 
> >>> map.mapName = "newname"
> 
> >>> print map.rules[1]
> 
> >>> Map newname rule number 1
> 
> >>> print map.rules[2]
> 
> >>> Map newname rule number 2

Or rather:
 
 map = Map('myMap')
 map.rules[1] = Rule(1)
 map.rules[2] = Rule(2)
 
 
 
 >>> print map.rules[1]
 >>> Map myMap rule number 1
 >>> print map.rules[2]
 >>> Map myMap rule number 2
 >>>
 >>> map.mapName = "newname"
 >>> print map.rules[1]
 >>> Map newname rule number 1
 >>> print map.rules[2]
 >>> Map newname rule number 2
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to send broadcast IP address to network?

2013-08-23 Thread Chris Angelico
On Fri, Aug 23, 2013 at 10:32 PM,   wrote:
> I want to send a broadcast packet to all the computers connected to my home 
> router.
>
> The following 2 lines of code do not work;
> host="192.168.0.102"
> s.connect((host, port))
>
> Can someone advise?

You can't establish a TCP socket with a broadcast address. That just
doesn't work. Can you please show a whole lot more context so we can
see what's happening here? Thanks!

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


python interface to iMacros

2013-08-23 Thread inq1ltd
Python help,

I am running iMacros from linux/firefox 
and doing most of what I want.

But, there are times when I want to do 
something of the net and then back 
to the iMacros script.   

Are there any projects out there
that will connect python to imacros,
something on the order of pexpect?

There is a commercial version available
for $400.00 If I could justify the cost,
I would probably pay it.

jimonlinux
inqvista.com




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


How to add additional font face to Python 3.3.2 IDLE?

2013-08-23 Thread maildragons1
How can I add for example Droid Sans Mono to python 3.3.2 IDLE? I'm not very 
familliar with font faces, really.

Thank's!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Basic Python Query

2013-08-23 Thread Chris Angelico
On Fri, Aug 23, 2013 at 5:12 PM, Ulrich Eckhardt
 wrote:
> Am 23.08.2013 05:28, schrieb Steven D'Aprano:
>>
>> On Thu, 22 Aug 2013 13:54:14 +0200, Ulrich Eckhardt wrote:
>>>
>>> When the Python object goes away, it doesn't necessarily affect
>>> thethread or file it represents.
>>
>>
>> That's certainly not true with file objects. When the file object goes
>> out of scope, the underlying low-level file is closed.
>
>
> Ahem, yes, but no: Calling close(fd) is not the same as destroying the file,
> I'm pretty sure it's still on my harddisk after that. That is also the
> difference to strings, where the Python object really is all there is to it.
> Similarly you can only customize the Python side of things with derivation,
> the other side will remain the same, apart from the data you write to the
> file or the code you run in the thread.

The file object doesn't represent the file on the disk; it represents
the "open file", which is a thing that you can have a handle (file
descriptor) to. That "thing" is indeed destroyed when the file object
is __del__'d, though it's possible to dispose of it sooner than that:

>>> f = open("test","w")
>>> with f:
f.write("Hello, world!")

13
>>> f
<_io.TextIOWrapper name='test' mode='w' encoding='cp1252'>

f has been closed at this point, and if I now go to open it in another
application, Python won't hold any locks; but the object still exists.
However, the general expectation is that the file object and the
open-file in the OS will correspond.

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


Re: right adjusted strings containing umlauts

2013-08-23 Thread Kurt Mueller
Am 08.08.2013 18:37, schrieb Chris Angelico:
> On Thu, Aug 8, 2013 at 5:16 PM, Kurt Mueller
>  wrote:
>> Am 08.08.2013 17:44, schrieb Peter Otten:
>>> Kurt Mueller wrote:
 What do I do, when input_strings/output_list has other codings like
 iso-8859-1?
>>> You have to know the actual encoding. With that information it's easy:
>> output_list
>>> ['\xc3\xb6', '\xc3\xbc', 'i', 's', 'f']
>> encoding = "utf-8"
>> output_list = [s.decode(encoding) for s in output_list]
>> print output_list
>>> [u'\xf6', u'\xfc', u'i', u's', u'f']
>> How do I get to know the actual encoding?
>> I read from stdin. There can be different encondings.
>> Usually utf8 but also iso-8859-1/latin9 are to be expected.
>> But sys.stdin.encoding sais always 'None'.
> 
> If you can switch to Python 3, life becomes a LOT easier. The Python 3
> input() function (which does the same job as raw_input() from Python
> 2) returns a Unicode string, meaning that it takes care of encodings
> for you.

Because I cannot switch to Python 3 for now my life is not so easy:-)

For some text manipulation tasks I need a template to split lines
from stdin into a list of strings the way shlex.split() does it.
The encoding of the input can vary.
For further processing in Python I need the list of strings to be in unicode.

Here is template.py:

##
#!/usr/bin/env python
# vim: set fileencoding=utf-8 :
# split lines from stdin into a list of unicode strings
# Muk 2013-08-23
# Python 2.7.3

from __future__ import print_function
import sys
import shlex
import chardet

bool_cmnt = True  # shlex: skip comments
bool_posx = True  # shlex: posix mode (strings in quotes)

for inpt_line in sys.stdin:
print( 'inpt_line=' + repr( inpt_line ) )
enco_type = chardet.detect( inpt_line )[ 'encoding' ]   # 
{'encoding': 'EUC-JP', 'confidence': 0.99}
print( 'enco_type=' + repr( enco_type ) )
try:
strg_inpt = shlex.split( inpt_line, bool_cmnt, bool_posx, ) # shlex 
does not work on unicode
except Exception, errr: # usually 
'No closing quotation'
print( "error='%s' on inpt_line='%s'" % ( errr, inpt_line.rstrip(), ), 
file=sys.stderr, )
continue
print( 'strg_inpt=' + repr( strg_inpt ) )   # list of 
strings
strg_unic = [ strg.decode( enco_type ) for strg in strg_inpt ]  # decode 
the strings into unicode
print( 'strg_unic=' + repr( strg_unic ) )   # list of 
unicode strings
##

$ cat  | template.py


Comments are welcome.


TIA
-- 
Kurt Mueller
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Running a command line program and reading the result as it runs

2013-08-23 Thread random832
On Fri, Aug 23, 2013, at 7:14, Peter Otten wrote:
> The following works on my linux system:
> 
> instream = iter(p.stdout.readline, "")
> 
> for line in instream:
> print line.rstrip()
> 
> I don't have Windows available to test, but if it works there, too, the 
> problem is the internal buffer used by Python's implementation of file 
> iteration rather than the OS.

I can confirm this on Windows.

Doesn't this surprising difference between for line in
iter(f.readline,'') vs for line in f violate TOOWTDI? We're led to
believe from the documentation that iterating over a file does _not_
read lines into memory before returning them. It's not clear to me what
performance benefit can be gained from waiting when there is no more
data available, either.

I don't understand how it's even happening - from looking at the code,
it looks like next() just calls readline() once, no fancy buffering
specific to itself.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python variable as a string

2013-08-23 Thread Vlastimil Brom
2013/8/23 Jake Angulo :
> Sorry this is a very basic question.
>
> I have a list var which after some evaluation I need to refer to var as a
> string.
>
> Pseudocode:
>
> var = ['a', 'b' , 'c' , 'd']
> adict = dict(var='string', anothervar='anotherstring')
> anotherdict = dict()
> if :
> anotherdict[akey] = adict['var']
>
>
> Basically im evaluating the list var, and if true, i want to use var as a
> string so that i can refer to a key-value pair in adict (whose key name is
> also var for convenience).
>
> Or maybe i should do things differently?
>
> Any help and code will be appreciated!
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>


Hi,
if I understand correctly, you would like to achieve something like
the following [fictional shell session]:

>>> var = "a string variable named 'var'"
>>> some_magic_function(var)
'var'
>>>

is it the case?
I believe, it is not (easily and reliably) possible, and especially it
doesn't seem to be of any real use, I can think of.
cf. e.g. the discussion
http://stackoverflow.com/questions/2553354/how-to-get-a-variable-name-as-a-string-in-python

What is your use case, where you can't use the actual object
reference, but only the string? What name string should be retrieved
in case of multiple names referencing the same object?


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


Re: Python and mysql 3 tier programming

2013-08-23 Thread Jason Friedman
> System Debian Wheezy Linux
> Python 2.7
> Mysql 5.5.31
> Apache Server
>
> I am somewhat conversant with html, css, SQL, mysql, Apache and Debian
> Linux. Actually I have been using Debian for over 10 year. I spent over 5
> year, prior to retirement, programming database based applications in
> Foxpro. I can also struggle through Java Script. I am just starting to use
> python. I've started with development of a rather complicated document
> archiving system with about 5 different levels of users and over 100 years
> of documents. photos, etc. The database setup has gone smoothly and other
> than one trial web page I'm leaving that for later. Finally to the problem.
> Where does python start and mysql stored procedures stop and visa versa. I'm
> trying to stick to a 3 tier philosophy but am having trouble figuring out
> where the dividing line is between the two packages. Further python seems to
> like cursor tables a lot and Oracles Mysql 5.5 discourages their use. Are
> they talking about the same thing.
>
> My problem is mostly with the basic architecture of the system. I think I
> will be able to figure out the code. Also, any comments on the use of the
> Django framework for this project.

Hello Gary,
Is your primary goal to write code or is it to have available to you a
document archiving solution?
If the latter, you will probably save time by using an existing system
(e.g., Google Docs).
If the former, I have a few thoughts.
One, you should probably be using Python 3 rather than 2, I think the
command is "sudo aptitude install python3".
Two, I think of stored procedures as being good at manipulating data
really fast.  With a document management system most activity will be
retrieval rather than manipulation.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to add additional font face to Python 3.3.2 IDLE?

2013-08-23 Thread Terry Reedy

On 8/23/2013 11:49 AM, maildrago...@gmail.com wrote:

How can I add for example Droid Sans Mono to python 3.3.2 IDLE? I'm not very 
familliar with font faces, really.


I suspect that Idle just looks in the standard font directory of your 
system to make the list of available fonts that it displays in the 
Options dialog.  So I think that you just need to 'install' the font, 
whatever than means for your OS.


--
Terry Jan Reedy

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


Re: Running a command line program and reading the result as it runs

2013-08-23 Thread Peter Otten
random...@fastmail.us wrote:

> On Fri, Aug 23, 2013, at 7:14, Peter Otten wrote:
>> The following works on my linux system:
>> 
>> instream = iter(p.stdout.readline, "")
>> 
>> for line in instream:
>> print line.rstrip()
>> 
>> I don't have Windows available to test, but if it works there, too, the
>> problem is the internal buffer used by Python's implementation of file
>> iteration rather than the OS.
> 
> I can confirm this on Windows.
> 
> Doesn't this surprising difference between for line in
> iter(f.readline,'') vs for line in f violate TOOWTDI? We're led to
> believe from the documentation that iterating over a file does _not_
> read lines into memory before returning them. It's not clear to me what
> performance benefit can be gained from waiting when there is no more
> data available, either.
> 
> I don't understand how it's even happening - from looking at the code,
> it looks like next() just calls readline() once, no fancy buffering
> specific to itself.

Maybe you are looking in the wrong version?

For 2.x you can use the file_iternext() function as a starting point, see:

http://hg.python.org/cpython/file/1ea833ecaf5a/Objects/fileobject.c#l2316

Python 3 uses a different approach that allows you to mix iteration and 
readline():

$ python -c 'f = open("tmp.txt"); next(f); f.readline()'
Traceback (most recent call last):
  File "", line 1, in 
ValueError: Mixing iteration and read methods would lose data
$ python3 -c 'f = open("tmp.txt"); next(f); f.readline()'

The relevant code is likely in the Modules/_io/ directory. There is also

[New I/O] http://www.python.org/dev/peps/pep-3116/

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


Re: Using PyQT with QT Designer

2013-08-23 Thread Phil Thompson
On Fri, 23 Aug 2013 08:00:29 -0500, Michael Staggs 
wrote:
> I tried that this morning and it destroyed my form. So, right now,
that's
> probably not what I'm looking for.
> 
> But, if you look at that picture, the app isn't resized to 800x600 like
it
> says in the ui file. The pixmaps aren't on the buttons like I set them
up
> in the ui file. It's not using the ui file at all. So, what's the point
of
> making a QT Designer file at all if it doesn't use it?

pyuic4 uses it to generate the corresponding Python code. Any time you
change the .ui file with Designer you have to run pyuic4 again. You should
not modify the Python code that pyuic4 generates.

> I'm guessing it CAN use it and there is just something I'm missing.
> 
> You may be right and I may not want to set the geometry in qt designer
down
> the road. But, right now I do and not only is it not getting that from
the
> ui fileit's not getting anything at all...even though I added all
the
> lines I thought I needed to.
> 
> If I decide to actually change the gui later, I'd like to be able to use
QT
> Designer to do so...design a layout and not really have to change my
> program. As it stands, it's totally ignoring my ui file and I have to
redo
> all the work in the program. In which case, there's no point to using qt
> designer at all.
> 
> I know I have to be missing something though there has to be a way
to
> use the work qt designer did.

I strongly suggest you do some more reading about using Designer.

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


Re: Using PyQT with QT Designer

2013-08-23 Thread Michael Staggs
Right. I know that if I redesign it I have to run pyuic4 again and that I
shouldn't change that file...let qt designer do its job.

But, that's exactly what I'm having the problem with...incorporating the
file pyuic4 gave me... and why I posted here.

If you can point me towards something I need to read then by all means...
I'd be grateful. But, all the little tutorials I've found told me to do it
this way and obviously my program has no access to itit's not resizing
the window or doing anything the ui file states. So, I do know I'm doing
something wrong and doing something the little tutorials didn't account
for. So, I'm asking here.

Again, I'm just learning. I took the codecademy python course and started
trying to learn to build a media player...and haven't figured out how to
build the gui yet. If you or anyone else can point me to something that
would explain what I'm doing wrong, I'll read it from front to back. If
it's too advanced it will lose mebut I would like to learn to do this.
On Aug 23, 2013 12:17 PM, "Phil Thompson" 
wrote:

> On Fri, 23 Aug 2013 08:00:29 -0500, Michael Staggs 
> wrote:
> > I tried that this morning and it destroyed my form. So, right now,
> that's
> > probably not what I'm looking for.
> >
> > But, if you look at that picture, the app isn't resized to 800x600 like
> it
> > says in the ui file. The pixmaps aren't on the buttons like I set them
> up
> > in the ui file. It's not using the ui file at all. So, what's the point
> of
> > making a QT Designer file at all if it doesn't use it?
>
> pyuic4 uses it to generate the corresponding Python code. Any time you
> change the .ui file with Designer you have to run pyuic4 again. You should
> not modify the Python code that pyuic4 generates.
>
> > I'm guessing it CAN use it and there is just something I'm missing.
> >
> > You may be right and I may not want to set the geometry in qt designer
> down
> > the road. But, right now I do and not only is it not getting that from
> the
> > ui fileit's not getting anything at all...even though I added all
> the
> > lines I thought I needed to.
> >
> > If I decide to actually change the gui later, I'd like to be able to use
> QT
> > Designer to do so...design a layout and not really have to change my
> > program. As it stands, it's totally ignoring my ui file and I have to
> redo
> > all the work in the program. In which case, there's no point to using qt
> > designer at all.
> >
> > I know I have to be missing something though there has to be a way
> to
> > use the work qt designer did.
>
> I strongly suggest you do some more reading about using Designer.
>
> Phil
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Using PyQT with QT Designer

2013-08-23 Thread Phil Thompson
On Fri, 23 Aug 2013 12:30:41 -0500, Michael Staggs 
wrote:
> Right. I know that if I redesign it I have to run pyuic4 again and that
I
> shouldn't change that file...let qt designer do its job.
> 
> But, that's exactly what I'm having the problem with...incorporating the
> file pyuic4 gave me... and why I posted here.
> 
> If you can point me towards something I need to read then by all
means...
> I'd be grateful. But, all the little tutorials I've found told me to do
it
> this way and obviously my program has no access to itit's not
resizing
> the window or doing anything the ui file states. So, I do know I'm doing
> something wrong and doing something the little tutorials didn't account
> for. So, I'm asking here.
> 
> Again, I'm just learning. I took the codecademy python course and
started
> trying to learn to build a media player...and haven't figured out how to
> build the gui yet. If you or anyone else can point me to something that
> would explain what I'm doing wrong, I'll read it from front to back. If
> it's too advanced it will lose mebut I would like to learn to do
this.

http://qt-project.org/doc/qt-4.8/designer-manual.html

Designer has a preview option that creates your UI on the fly. The first
step would be to get it working as far as you can with that before you try
generating any Python code.

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


Re: Using PyQT with QT Designer

2013-08-23 Thread Michael Staggs
Thanks for the manual. I will look into it but all the examples are
probably c++. Ive tried zetcode and some of the other tutorials.

That's the problem though. It is exactly how I want it in designer. It's
perfect as it is in designer when I preview it. Here is a screenshot of the
preview: http://i.imgur.com/ULRolq8.png

The problem isn't that I can't design it in QT Designer. It is designed
just like I want it. The problem is, when I try to follow zetcode and other
tutorials about how to import and use my form as designed by qt designer
and run through pyuic4 it doesn't seem to even notice my ui file...and
certainly isnt acting on it.

I posted my code above where I was trying anything just to get it to use
that ui I designed in qt designer.so far to no avail
-- Forwarded message --
From: "Michael Staggs" 
Date: Aug 23, 2013 12:54 PM
Subject: Re: Using PyQT with QT Designer
To: "Phil Thompson" 
Cc:

Thanks for the manual. I will look into it but all the examples are
probably c++. Ive tried zetcode and some of the other tutorials.

That's the problem though. It is exactly how I want it in designer. It's
perfect as it is in designer when I preview it. Here is a screenshot of the
preview: http://i.imgur.com/ULRolq8.png

The problem isn't that I can't design it in QT Designer. It is designed
just like I want it. The problem is, when I try to follow zetcode and other
tutorials about how to import and use my form as designed by qt designer
and run through pyuic4 it doesn't seem to even notice my ui file...and
certainly isnt acting on it.

I posted my code above where I was trying anything just to get it to use
that ui I designed in qt designer.so far to no avail
On Aug 23, 2013 12:42 PM, "Phil Thompson" 
wrote:

> On Fri, 23 Aug 2013 12:30:41 -0500, Michael Staggs 
> wrote:
> > Right. I know that if I redesign it I have to run pyuic4 again and that
> I
> > shouldn't change that file...let qt designer do its job.
> >
> > But, that's exactly what I'm having the problem with...incorporating the
> > file pyuic4 gave me... and why I posted here.
> >
> > If you can point me towards something I need to read then by all
> means...
> > I'd be grateful. But, all the little tutorials I've found told me to do
> it
> > this way and obviously my program has no access to itit's not
> resizing
> > the window or doing anything the ui file states. So, I do know I'm doing
> > something wrong and doing something the little tutorials didn't account
> > for. So, I'm asking here.
> >
> > Again, I'm just learning. I took the codecademy python course and
> started
> > trying to learn to build a media player...and haven't figured out how to
> > build the gui yet. If you or anyone else can point me to something that
> > would explain what I'm doing wrong, I'll read it from front to back. If
> > it's too advanced it will lose mebut I would like to learn to do
> this.
>
> http://qt-project.org/doc/qt-4.8/designer-manual.html
>
> Designer has a preview option that creates your UI on the fly. The first
> step would be to get it working as far as you can with that before you try
> generating any Python code.
>
> Phil
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Using PyQT with QT Designer

2013-08-23 Thread Michael Staggs
Again thoughI'm finished with QT Designer. I have the finished product
I want exactly like I want it. But, as ive shown in the screenshots, I'm
doing exactly what ive seen in zetcode and other tutorials but It doesn't
seem to incorporate and act upon that ui file. The first thing you notice
is that it doesn't resize the main window to 800x600...which is one of the
first lines in the ui file.

I know whatever I'm doing wrong has to be a 1 or 2 line solution...just
something I should change a littlebut I dont know what that is
On Aug 23, 2013 12:42 PM, "Phil Thompson" 
wrote:

> On Fri, 23 Aug 2013 12:30:41 -0500, Michael Staggs 
> wrote:
> > Right. I know that if I redesign it I have to run pyuic4 again and that
> I
> > shouldn't change that file...let qt designer do its job.
> >
> > But, that's exactly what I'm having the problem with...incorporating the
> > file pyuic4 gave me... and why I posted here.
> >
> > If you can point me towards something I need to read then by all
> means...
> > I'd be grateful. But, all the little tutorials I've found told me to do
> it
> > this way and obviously my program has no access to itit's not
> resizing
> > the window or doing anything the ui file states. So, I do know I'm doing
> > something wrong and doing something the little tutorials didn't account
> > for. So, I'm asking here.
> >
> > Again, I'm just learning. I took the codecademy python course and
> started
> > trying to learn to build a media player...and haven't figured out how to
> > build the gui yet. If you or anyone else can point me to something that
> > would explain what I'm doing wrong, I'll read it from front to back. If
> > it's too advanced it will lose mebut I would like to learn to do
> this.
>
> http://qt-project.org/doc/qt-4.8/designer-manual.html
>
> Designer has a preview option that creates your UI on the fly. The first
> step would be to get it working as far as you can with that before you try
> generating any Python code.
>
> Phil
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can a child access parent attributes if that child added post-hoc as an attribute to the parent?

2013-08-23 Thread Bitswapper
On Thursday, August 22, 2013 4:59:17 PM UTC-5, Ian wrote:
> On Thu, Aug 22, 2013 at 3:26 PM, Prasad, Ramit
> 
> <> wrote:
> 
> > Bitswapper wrote:
> 
> >>
> 
> >> So I have a parent and child class:
> 
> >>
> 
> >>
> 
> >> class Map(object):
> 
> >> def __init__(self, name=''):
> 
> >> self.mapName = name
> 
> >> self.rules = {}
> 
> >>
> 
> >> class Rule(Map):
> 
> >> def __init__(self, number):
> 
> >> Map.__init__(self)
> 
> >> self.number = number
> 
> >
> 
> > This means that rules will never have a name. I think you need
> 
> >   def __init__(self, name='', number=None):
> 
> >   Map.__init__(self, name)
> 
> >   self.number = number
> 
> 
> 
> No, that's still wrong.  The OP talks abut maps having names, not
> 
> rules having names.  Unless a Rule is-a Map, which sounds unlikely,
> 
> Rule should not be inheriting from Map in the first place.
> 
> 
> 
> >> It seems to me what I'm trying to do is link an arbitrary child instance 
> >> to an arbitrary instance of a
> 
> >> parent class, which in this case would be handy  Because I'd like to 
> >> populate a map with rules and
> 
> >> print the rules including the parent map name for each rule.  I'm just not 
> >> sure how I would go about
> 
> >> doing this in python.
> 
> 
> 
> You'll need to keep a reference to the Map on each Rule instance.  So
> 
> instead of self.mapName you'll have self.map.mapName.  Your Rule class
> 
> should probably look something like this:
> 
> 
> 
> class Rule(object):
> 
> def __init__(self, map, number):
> 
> self.map = map
> 
> self.number = number
> 
> 
> 
> And then when you construct it you'll need to tell it what map it belongs to:
> 
> 
> 
> rule = Rule(map, 1)


Actually yea, that makes sense.  I was looking for a way for a child to 
'automagically' inherit parent instance-specific data via inheritance only by 
virtue of being a child of a parent instance.  What you're suggesting makes 
more sense.

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


Arpex Capital seleciona: Desenvolvedor Python / SP

2013-08-23 Thread zughumancapital
Arpex Capital seleciona para uma de suas empresas:

Desenvolvedor Python 

Objetivo geral da Posição: Desenvolver software estável e de primeira linha, 
que será incorporado à plataforma de WiFi mais moderna atualmente.
Responsabilidades: escrever software que rodará tanto no backend (Python) 
quanto no frontend (HTML5).

Pré-requisitos:
- Conhecimento em Python, MongoDB
- Cloud computing, BigData
- Pensamento lógico e analítico
- Capacidade de absorver tecnologias novas de forma constante

Deveres:
- Escrever software sólido em Python

Formação:
Irrelevante (não cobramos) 

Local de Trabalho: São Paulo/SP

A empresa oferece remuneração compatível com o mercado + Benefícios.
Os interessados deverão enviar o CV para kgar...@arpexcapital.com.br , 
mencionando no assunto Desenvolvedor Python. 


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


Re: Using PyQT with QT Designer

2013-08-23 Thread Dave Angel
Michael Staggs wrote:


>
> That's the problem though. It is exactly how I want it in designer. It's
> perfect as it is in designer when I preview it. Here is a screenshot of the
> preview: http://i.imgur.com/ULRolq8.png
>
> The problem isn't that I can't design it in QT Designer. It is designed
> just like I want it. The problem is, when I try to follow zetcode and other
> tutorials about how to import and use my form as designed by qt designer
> and run through pyuic4 it doesn't seem to even notice my ui file...and
> certainly isnt acting on it.
>

I don't know PyQT, so I've kept quiet so far...

You don't say what the name of the generated file is, but perhaps since
the source file was window.ui, the generated one is window.py

My guess is that when you do the

from window import Ui_MainWindow

it is finding some OTHER window.py file.

Have you tried simply adding an illegal line to the generated file, to
force the compiler to fail the import?  Once you're sure that it is
importing this particular file, you can remove such a line.

Could be that you have some other window.py file  (or window.pyc, or
whatever) and that it's finding that one.  Or it's finding some older
version of this one.



-- 
DaveA


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


Re: How to add additional font face to Python 3.3.2 IDLE?

2013-08-23 Thread maildragons1
23 август 2013, петък, 19:33:41 UTC+3, Terry Reedy написа:
> On 8/23/2013 11:49 AM, maildrago...@gmail.com wrote:
> 
> > How can I add for example Droid Sans Mono to python 3.3.2 IDLE? I'm not 
> > very familliar with font faces, really.
> 
> 
> 
> I suspect that Idle just looks in the standard font directory of your 
> 
> system to make the list of available fonts that it displays in the 
> 
> Options dialog.  So I think that you just need to 'install' the font, 
> 
> whatever than means for your OS.
> 
> 
> 
> -- 
> 
> Terry Jan Reedy

I searched a little on that topic and i found that this is actualy what the 
IDLE is doing.
Thanks Terry Jan !
-- 
http://mail.python.org/mailman/listinfo/python-list


can't get utf8 / unicode strings from embedded python

2013-08-23 Thread David M. Cotter
note everything works great if i use Ascii, but:

in my utf8-encoded script i have this:

>   print "frøânçïé"

in my embedded C++ i have this:

PyObject*   CPython_Script::print(PyObject *args)
{
PyObject*resultObjP = NULL;
const char  *utf8_strZ  = NULL;

if (PyArg_ParseTuple(args, "s", &utf8_strZ)) {
Log(utf8_strZ, false);

resultObjP = Py_None;
Py_INCREF(resultObjP);
}

return resultObjP;
}

Now, i know that my Log() can print utf8 (has for years, very well debugged)

but what it *actually* prints is this:

>   print "frøânçïé"
--> frøânçïé

another method i use looks like this:
>   kj_commands.menu("控件", "同步滑帧", "全局无滑帧")
or
>   kj_commands.menu(u"控件", u"同步滑帧", u"全局无滑帧")

and in my C++ i have:

SuperString ScPyObject::GetAs_String()
{
SuperString str;

if (PyUnicode_Check(i_objP)) {
#if 1
//  method 1
{
ScPyObject  
utf8Str(PyUnicode_AsUTF8String(i_objP));

str = utf8Str.GetAs_String();
}
#elif 0
//  method 2
{
UTF8Char*uniZ = (UTF8Char 
*)PyUnicode_AS_UNICODE(i_objP);

str.assign(&uniZ[0], 
&uniZ[PyUnicode_GET_DATA_SIZE(i_objP)], kCFStringEncodingUTF16);
}
#else
//  method 3
{
UTF32VeccharVec(32768); 
CF_ASSERT(sizeof(UTF32Vec::value_type) == sizeof(wchar_t));
PyUnicodeObject *uniObjP = (PyUnicodeObject 
*)(i_objP);
Py_ssize_t  
sizeL(PyUnicode_AsWideChar(uniObjP, (wchar_t *)&charVec[0], charVec.size()));

charVec.resize(sizeL);
charVec.push_back(0);
str.Set(SuperString(&charVec[0]));
}
#endif
} else {
str.Set(uc(PyString_AsString(i_objP)));
}

Log(str.utf8Z());

return str;
}


for the string, "控件", i get:
--> 控件

for the *unicode* string, u"控件", Methods 1, 2, and 3, i get the same thing:
--> 控件

okay so what am i doing wrong???
-- 
http://mail.python.org/mailman/listinfo/python-list


Setting the value of True

2013-08-23 Thread jeangawron
Python allows you set the value of True

>>> True = 1.3

Now this is consistent with the decision to let you set the
value of various builtin names.  But why is this case different:

>>> None = 1.3
  File "", line 1
SyntaxError: cannot assign to None

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


Re: Using PyQT with QT Designer

2013-08-23 Thread tausciam
Thank you. I just deleted all of them, reran pyuic4 on window.ui and 
regenerated window.py just to make sure. Unfortunately, I get the same problem.

I've got the GUI perfectly designed just like I want it in window.py... just 
can't figure out how to use it in my program.

On Friday, August 23, 2013 3:16:59 PM UTC-5, Dave Angel wrote:
> Michael Staggs wrote:
> 
> 
> 
> 
> 
> >
> 
> > That's the problem though. It is exactly how I want it in designer. It's
> 
> > perfect as it is in designer when I preview it. Here is a screenshot of the
> 
> > preview: http://i.imgur.com/ULRolq8.png
> 
> >
> 
> > The problem isn't that I can't design it in QT Designer. It is designed
> 
> > just like I want it. The problem is, when I try to follow zetcode and other
> 
> > tutorials about how to import and use my form as designed by qt designer
> 
> > and run through pyuic4 it doesn't seem to even notice my ui file...and
> 
> > certainly isnt acting on it.
> 
> >
> 
> 
> 
> I don't know PyQT, so I've kept quiet so far...
> 
> 
> 
> You don't say what the name of the generated file is, but perhaps since
> 
> the source file was window.ui, the generated one is window.py
> 
> 
> 
> My guess is that when you do the
> 
> 
> 
> from window import Ui_MainWindow
> 
> 
> 
> it is finding some OTHER window.py file.
> 
> 
> 
> Have you tried simply adding an illegal line to the generated file, to
> 
> force the compiler to fail the import?  Once you're sure that it is
> 
> importing this particular file, you can remove such a line.
> 
> 
> 
> Could be that you have some other window.py file  (or window.pyc, or
> 
> whatever) and that it's finding that one.  Or it's finding some older
> 
> version of this one.
> 
> 
> 
> 
> 
> 
> 
> -- 
> 
> DaveA

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


Re: Setting the value of True

2013-08-23 Thread Gary Herron

On 08/23/2013 04:38 PM, jeangaw...@gmail.com wrote:

Python allows you set the value of True


True = 1.3

Now this is consistent with the decision to let you set the
value of various builtin names.  But why is this case different:


None = 1.3

   File "", line 1
SyntaxError: cannot assign to None

Mark Gawron


Python3 fixes this inconsistency, by disallowing all such assignments.

They all raise an exception:
  SyntaxError: assignment to keyword


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


Re: Setting the value of True

2013-08-23 Thread Terry Reedy

On 8/23/2013 7:38 PM, jeangaw...@gmail.com wrote:

Python allows you set the value of True


Unqualified 'Python', used in the present tense, refers to the latest 
release or repository version.


>>> True = 1.3
SyntaxError: assignment to keyword


True = 1.3


Now this is consistent with the decision to let you set the
value of various builtin names.  But why is this case different:


None = 1.3

   File "", line 1
SyntaxError: cannot assign to None



--
Terry Jan Reedy

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


Re: Using PyQT with QT Designer

2013-08-23 Thread Lee Harr
> That's the problem though. It is exactly how I want it in designer. It's
> perfect as it is in designer when I preview it. Here is a screenshot of the
> preview: http://i.imgur.com/ULRolq8.png

That's not a preview. That's just the regular design view.
(you can tell by the little dots in the background)

You need to go to Form -> Preview... to see the actual preview.

That said...

1.) You may want to ask your question on the PyQt mailing list. Though
you are talking with the undisputed PyQt expert in Phil, there are more
people on the other list who are familiar with PyQt and who may be willing
to look more closely at your specific code.

2.) It may be that the examples you are looking at are not sufficient to
help you with the situation you are in. For instance, I've written several
programs using Designer and PyQt and I would recommend against
using the pyuic method.

When I first started with PyQt I also used pyuic and eventually I found
the PyQt4.uic method works better for me.

3.) Layouts. You have to use them with Qt or you're going to have a
bad time.

Looking at your design, I would do something like ...

- select the two buttons on the left and click "Lay Out Vertically"
- select the two large white boxes and click "Lay Out Vertically"
- put a vertical spacer underneath the red X button
- select the red button and the spacer and click "Lay Out Vertically"
- at this point you may need to resize and rearrange your three vertical
   layouts so that they don't overlap and are in approximately the positions
   that you want, then
- select the main window and click "Lay Out Horizontally"

Something along those lines would get you about to where you want
to be. The form may not look _exactly_ the way you have it there, but
it will be a more flexible design and nothing will be overlapping.  
  
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Using PyQT with QT Designer

2013-08-23 Thread tausciam
Thank you... I found my problem 

class MainWindow(QMainWindow, Ui_MainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.setupUi(self)

That seems to take care of it... if I comment out everything else, I get my 
pristine form 

I don't know if it's the super call or the setupuibut one of those was my 
godsend.

So, that is solved... I just have to figure out how to put things in the gui 
where I want thembut I think you're right at any rate. If I try to resize, 
it doesn't function like I thought it would. I will have to use layouts.. but 
at least now I am able to use the UI file that I created.

On Friday, August 23, 2013 7:35:53 PM UTC-5, Lee Harr wrote:
> > That's the problem though. It is exactly how I want it in designer. It's
> > perfect as it is in designer when I preview it. Here is a screenshot of the
> > preview: http://i.imgur.com/ULRolq8.png
> 
> That's not a preview. That's just the regular design view.
> (you can tell by the little dots in the background)
> 
> You need to go to Form -> Preview... to see the actual preview.
> 
> That said...
> 
> 1.) You may want to ask your question on the PyQt mailing list. Though
> you are talking with the undisputed PyQt expert in Phil, there are more
> people on the other list who are familiar with PyQt and who may be willing
> to look more closely at your specific code.
> 
> 2.) It may be that the examples you are looking at are not sufficient to
> help you with the situation you are in. For instance, I've written several
> programs using Designer and PyQt and I would recommend against
> using the pyuic method.
> 
> When I first started with PyQt I also used pyuic and eventually I found
> the PyQt4.uic method works better for me.
> 
> 3.) Layouts. You have to use them with Qt or you're going to have a
> bad time.
> 
> Looking at your design, I would do something like ...
> 
> - select the two buttons on the left and click "Lay Out Vertically"
> - select the two large white boxes and click "Lay Out Vertically"
> - put a vertical spacer underneath the red X button
> - select the red button and the spacer and click "Lay Out Vertically"
> - at this point you may need to resize and rearrange your three vertical
>    layouts so that they don't overlap and are in approximately the positions
>    that you want, then
> - select the main window and click "Lay Out Horizontally"
> 
> Something along those lines would get you about to where you want
> to be. The form may not look _exactly_ the way you have it there, but
> it will be a more flexible design and nothing will be overlapping.

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


Re: Setting the value of True

2013-08-23 Thread Steven D'Aprano
On Fri, 23 Aug 2013 16:38:43 -0700, jeangawron wrote:

> Python allows you set the value of True
> 
 True = 1.3

Only in older versions of Python. This is for historical reasons: True 
and False were added as built-ins relatively late in Python's history 
(2.2, I think) and so there is still old code that legitimately does this 
at the start of a module:

True = 1
False = not True

Hence, making True and False actual keywords could only occur in Python 
3, which was allowed to break backwards compatibility.

None, on the other hand, has always existed in Python. The very oldest 
versions way back in the mists of time allowed you to rebind None:

[steve@ando ~]$ python1.5
Python 1.5.2 (#1, Aug 27 2012, 09:09:18)  [GCC 4.1.2 20080704 (Red Hat 
4.1.2-52)] on linux2
Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
>>> None = 3
>>> None
3


but as that was considered a mistake, *and* it was considered unlikely to 
be any code in the wild that legitimately rebinds None, that was made a 
SyntaxError in Python 2.x.

As for why None, True and False are treated differently than built-ins, 
if I remember the reason why, it is because they are considered 
fundamental to the inner workings of Python, unlike mere builtins like 
len, map, etc. and therefore should be protected.



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


Re: can't get utf8 / unicode strings from embedded python

2013-08-23 Thread Steven D'Aprano
On Fri, 23 Aug 2013 13:49:23 -0700, David M. Cotter wrote:

> note everything works great if i use Ascii, but:
> 
> in my utf8-encoded script i have this:
> 
>>  print "frøânçïé"


I see you are using Python 2, in which case there are probably two or 
three errors being made here.

Firstly, in Python 2, the compiler assumes that the source code is 
encoded in ASCII, actually ASCII plus arbitrary bytes. Since your source 
code is *actually* UTF-8, the bytes in the file are:

70 72 69 6E 74 20 22 66 72 C3 B8 C3 A2 6E C3 A7 C3 AF C3 A9 22

But Python doesn't know the file is encoded in UTF-8, it thinks it is 
reading ASCII plus junk, so when it reads the file it parses those bytes 
into a line of code:

print "~"

where the ~ represents a bunch of 13 rubbish junk bytes. So that's 
the first problem to fix. You can fix this by adding an encoding cookie 
at the beginning of your module, in the first or second line:

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


The second problem is that even once you've fixed the source encoding, 
you're still not dealing with a proper Unicode string. In Python 2, you 
need to use u" ... " delimiters for Unicode, otherwise the results you 
get are completely arbitrary and depend on the encoding of your terminal. 
For example, if I set my terminal encoding to IBM-850, I get:

fr°Ônþ´Ú

from those bytes. If I set it to Central European ISO-8859-3 I get this:

frĝânçïé

Clearly not what I intended. So change the line of code to:

print u"frøânçïé"

Those two changes ought to fix the problem, but if they don't, try 
setting your terminal encoding to UTF-8 as well and see if that helps.


[...]
> but what it *actually* prints is this:
> 
>>  print "frøânçïé"
> --> frøânçïé

It's hard to say what *exactly* is happening here, because you don't 
explain how the python print statement somehow gets into your C++ Log 
code. Do I guess right that it catches stdout?

If so, then what I expect is happening is that Python has read in the 
source code of

print "~"

with ~ as a bunch of junk bytes, and then your terminal is displaying 
those junk bytes according to whatever encoding it happens to be using. 
Since you are seeing this:

frøânçïé

my guess is that you're using a Mac, and the encoding is set to the 
MacRoman encoding. Am I close?

To summarise:

* Add an encoding cookie, to tell Python to use UTF-8 when parsing your 
source file.

* Use a Unicode string u"frøânçïé".

* Consider setting your terminal to use UTF-8, otherwise it may not be 
able to print all the characters you would like.

* You may need to change the way data gets into your C++ Log function. If 
it expects bytes, you may need to use u"...".encode('utf-8') rather than 
just u"...". But since I don't understand how data is getting into your 
Log function, I can't be sure about this.


I think that is everything. Does that fix your problem?


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


Conversion Issue in Converting code of 2.7 to 3

2013-08-23 Thread shankha
Hi,
I am trying to run the following piece of code:

https://greyhat.gatech.edu/wiki/index.php?title=Java_Bytecode_Tutorial/Getting_Started

python Krakatau/assemble.py minimal.j.

The scripts are written for 2.7. I want to convert them to 3.3.

I am struck with the following error:

[]$ python Krakatau/assemble.py minimal.j
Traceback (most recent call last):
  File "Krakatau/assemble.py", line 4, in 
from Krakatau.assembler import tokenize, parse, assembler

  File "c:\tmp\ByteCode\Krakatau\Krakatau\assembler\tokenize.py", line
3, in 
from ..classfile import ClassFile
  File "c:\tmp\ByteCode\Krakatau\Krakatau\classfile.py", line 1, in 

from . import constant_pool, method, field
  File "c:\tmp\ByteCode\Krakatau\Krakatau\constant_pool.py", line 10
def decodeStr((s,)):
  ^
SyntaxError: invalid syntax



The code where this error originates from:

def decodeStr((s,)):
return s.replace('\xc0\x80','\0').decode('utf8'),



I looked at http://docs.python.org/3/whatsnew/3.0.html but I couldn't
figure out where

I am going wrong?


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


Re: Python script help

2013-08-23 Thread Piet van Oostrum
cool1...@gmail.com writes:

> Here are some scripts, how do I put them together to create the script
> I want? (to search a online document and download all the links in it)
> p.s: can I set a destination folder for the downloads?

You can use os.chdir to go to the desired folder.
>
> urllib.urlopen("http://";)
>
> possible_urls = re.findall(r'\S+:\S+', text)
>
> import urllib2
> response = urllib2.urlopen('http://www.example.com/')
> html = response.read()

If you insist on not using wget, here is a simple script with
BeautifulSoup (v4):


from bs4 import BeautifulSoup
from urllib2 import urlopen
from urlparse import urljoin
import os
import re

os.chdir('OUT')

def generate_filename(url):
url = re.sub('^[a-zA-Z0-9+.-]+:/*', '', url)
return url.replace('/', '_')

URL = "http://www.example.com/";
soup = BeautifulSoup(urlopen(URL).read())

links = soup.select('a[href]')
for link in links:
url = urljoin(URL, link['href'])
print url
html = urlopen(url).read()
fn = generate_filename(url)
with open(fn, 'wb') as outfile:
outfile.write(html)


You should add a more intelligent filename generator, filter out mail:
urls and possibly others and add exception handling for HTTP errors.
-- 
Piet van Oostrum 
WWW: http://pietvanoostrum.com/
PGP key: [8DAE142BE17999C4]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Conversion Issue in Converting code of 2.7 to 3

2013-08-23 Thread MRAB

On 24/08/2013 03:10, shankha wrote:

Hi,
I am trying to run the following piece of code:

https://greyhat.gatech.edu/wiki/index.php?title=Java_Bytecode_Tutorial/Getting_Started

python Krakatau/assemble.py minimal.j.

The scripts are written for 2.7. I want to convert them to 3.3.

I am struck with the following error:



[]$ python Krakatau/assemble.py minimal.j
Traceback (most recent call last):
   File "Krakatau/assemble.py", line 4, in 
 from Krakatau.assembler import tokenize, parse, assembler


   File "c:\tmp\ByteCode\Krakatau\Krakatau\assembler\tokenize.py", line 3, in 

 from ..classfile import ClassFile
   File "c:\tmp\ByteCode\Krakatau\Krakatau\classfile.py", line 1, in 


 from . import constant_pool, method, field
   File "c:\tmp\ByteCode\Krakatau\Krakatau\constant_pool.py", line 10
 def decodeStr((s,)):
   ^
SyntaxError: invalid syntax





The code where this error originates from:

def decodeStr((s,)):
 return s.replace('\xc0\x80','\0').decode('utf8'),



I looked athttp://docs.python.org/3/whatsnew/3.0.html  but I couldn't figure 
out where

I am going wrong?


Look here:

http://docs.python.org/3/whatsnew/3.0.html#changed-syntax

at the "Removed Syntax" section where it mentions PEP 3113.

A simple fix is:

def decodeStr(arg):
(s,) = arg
return s.replace('\xc0\x80','\0').decode('utf8'),

or:

def decodeStr(s):
return s[0].replace('\xc0\x80','\0').decode('utf8'),

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


Fast conversion of numbers to numerator/denominator pairs

2013-08-23 Thread Steven D'Aprano
I have a need to convert arbitrary non-complex numbers into numerator/
denominator pairs. Numbers could be ints, floats, Fractions or Decimals. 
For example:

2 => (2, 1)
0.25 => (1, 4)
Fraction(2, 3) => (2, 3)
Decimal("0.5") => (1, 2)


The first three cases are easy and fast:

# ints and Fractions
number.numerator, number.denominator

# floats are a little slower
number.as_integer_ratio()


But Decimals are unfortunately slower. MUCH slower, about 40 times slower 
than Fractions in Python 3.3:

tmp = Fraction.from_decimal(number)
(tmp.numerator, tmp.denominator)


This ends up being the bottleneck in my code: once you include the 
scaffolding code to select the right conversion method, processing a 
large list of Decimals is about fifty times slower than large lists of 
floats or fractions.

Is there a fast way to convert a Decimal into a pair of numbers numerator/
denominator? It *must* be exact, but it doesn't have to be simplest form. 
For example, Decimal("0.5") => (5, 10) would be okay, although (1, 2) 
would be preferred.


I've tried this function:

def convert(d):
sign, digits, exp = d.as_tuple()
num = int(''.join([str(digit) for digit in digits]))
if sign: num = -num
return num, 10**-exp


which is faster, but not fast enough. Any suggestions?


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


Exception Handling Practices / Patterns

2013-08-23 Thread snarf
Greetings,

As I tread through my journey of OO I am trying to determine if there is a good 
approach for exception handling within classes.

>From my readings and gatherings - it seems I have found a common theme, but I 
>am trying to solicit from the experts.

Here is what I have found (I may be restating the obvious so please forgive me 
in advance):

* Seems like exception handing within Classes is largely avoided and is 
typically only used when calling external libraries.
* Try/Except type statements seem to be used more within modules, main 
functions, wrapper scripts.
* Classes should be coded in a way that exceptions 
* Better to never write your own exceptions (unless you absolutely have to).
* Using Exception is typically a bad. More specific the better.
* Exceptions should never fail silently. (Should exceptions always be logged?)

Best site I have found for exceptions (hopefully this helps someone):
* http://c2.com/cgi/wiki?ExceptionPatterns


I'd be interested in hearing others thoughts on this topic with regards to best 
practices for when to use exceptions, and when to avoid using exceptions.

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


Re: can't get utf8 / unicode strings from embedded python

2013-08-23 Thread David M. Cotter
> I see you are using Python 2
correct

> Firstly, in Python 2, the compiler assumes that the source code is encoded in 
> ASCII
gar, i must have been looking at doc for v3, as i thought it was all assumed to 
be utf8

> # -*- coding: utf-8 -*- 
okay, did that, still no change

> you need to use u" ... " delimiters for Unicode, otherwise the results you 
> get are completely arbitrary and depend on the encoding of your terminal. 
okay, well, i'm on a mac, and not using "terminal" at all.  but if i were, it 
would be utf8
but it's still not flying :(

> For example, if I set my terminal encoding to IBM-850
okay how do you even do that?  this is not an interactive session, this is 
embedded python, within a C++ app, so there's no terminal.  

but that is a good question: all the docs say "default encoding" everywhere (as 
in "If string is a Unicode object, this function computes the default encoding 
of string and operates on that"), but fail to specify just HOW i can set the 
default encoding.  if i could just say "hey, default encoding is utf8", i think 
i'd be done?

> So change the line of code to: 
> print u"frøânçïé" 
okay, sure... 
but i get the exact same results

> Those two changes ought to fix the problem, but if they don't, try setting 
> your terminal encoding to UTF-8 as well
well, i'm not sure what you mean by that.  i don't have a terminal here.
i'm logging to a utf8 log file (when i print)


> but what it *actually* prints is this: 
> 
>print "frøânçïé" 
> --> frøânçïé 

>It's hard to say what *exactly* is happening here, because you don't explain 
>how the python print statement somehow gets into your C++ Log code. Do I guess 
>right that it catches stdout?
yes, i'm redirecting stdout to my own custom print class, and then from that 
function i call into my embedded C++ print function

>If so, then what I expect is happening is that Python has read in the source 
>code of 

>print "~" 

>with ~ as a bunch of junk bytes, and then your terminal is displaying 
>those junk bytes according to whatever encoding it happens to be using. 
>Since you are seeing this: 

>frøânçïé 

>my guess is that you're using a Mac, and the encoding is set to the MacRoman 
>encoding. Am I close?
you hit the nail on the head there, i think.  using that as a hint, i took this 
text "frøânçïé" and pasted that into a "macRoman" document, then 
*reinterpreted* it as UTF8, and voala: "frøânçïé"

so, it seems that i AM getting my utf8 bytes, but i'm getting them converted to 
macRoman.  huh?  where is macRoman specified, and how to i change that to utf8? 
 i think that's the missing golden ticket
-- 
http://mail.python.org/mailman/listinfo/python-list