Re: open office in another language?

2012-01-10 Thread 88888 Dihedral
I remembered that the open office was started to promote java long time ago by 
Sun
selling work stations. 

But the project ended to be practical. 
-- 
http://mail.python.org/mailman/listinfo/python-list


how to put code on the google app and run it

2012-01-10 Thread contro opinion
there is a simple code,which can run locally ,and get three csv  file in
c:/
#coding:utf-8
import urllib
import re
import os
exchange=['NASDAQ','NYSE','AMEX']
for down in exchange:
myfile=open('c:/'+down,'w')
url='
http://www.nasdaq.com/screening/companies-by-industry.aspx?exchange='+down+'&render=download
'
file=urllib.urlopen(url).read()
myfile.write(file)
print 'ok',down
myfile.close()

i want to upload it onto my  google app (i have one google app account)and
let it run on 4 o'clock  (with cron) ,and  let the downloaded data on my
google app,
how to do ?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie: Looking for code review on my first Python project.

2012-01-10 Thread Ben Finney
Terry Reedy  writes:

> I would too, but if you prefer the indentation, just leave out the
> '+'s and let Python do the catenation when compiling:

Or use a trimple quoted string, with indentation in the source, and use
Python's batteries to manage it at runtime. Best of both worlds
http://stackoverflow.com/questions/2504411/proper-indentation-for-python-multiline-strings/2504454#2504454>.

-- 
 \ “I have an answering machine in my car. It says, ‘I'm home now. |
  `\  But leave a message and I'll call when I'm out.’” —Steven Wright |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: cx_Freeze ImportError, how do I debug this

2012-01-10 Thread Jeffrey Britton
On Jan 10, 8:21 pm, Jeffrey Britton  wrote:
> I am building a standalone Windows executable using cx_Freeze.
> The resulting executable will not run and writes the following error
> to the console.
>
> ImportError: could not import gobject (error was: 'No module named
> gobject')
>
> The project using the gtk libraries for Cairo and Pango on Windows.
> The program runs fine when run with Python.
> I have tried copying anything that cx_Freeze may have missed from the
> gtk installation under the Python directory.
>
> My question is, is there a method to debug this, that can tell me more
> about what is going on?
>
> The executable directory already contains
> _gobject.pyd
> libgobject-2.0-0.dll
> libcairo-gobject-2.dll
> and a bunch of other stuff.
>
> I can type
> import gobject
> in the Python shell and that works.

I just realized that I can import just Cairo and build and
executable.  However, a test script with simply
import Pango
print 'hello'
fails.
This time I tried building with PyInstaller and I get the same error
about not being able to load gobject.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Ctypes compatibility

2012-01-10 Thread Alec Taylor
Use size_t

http://en.wikipedia.org/wiki/C_data_types#Size_and_pointer_difference_types

On Wed, Jan 11, 2012 at 2:20 PM, Evan Driscoll  wrote:
> Might as well ask another question of the list.
>
> I've written a ctypes-based Python wrapper around the 'readdir'
> function. (I want access to the dt_type field of the result, without
> calling stat().)
>
> However, it feels very... fragile. What happens on a different *nix
> which uses a different size of integers? Is Linux even consistent
> between 32 and 64 bits? (That's a rhetorical question.) What happens on
> a different *nix with the fields in a different order, or without a
> dt_type field?
>
> It somehow feels wrong that you get way less help with this than you
> would get even from C. Is that just how it is with ctypes? Or is there
> some way around it? I'm sort of tempted to write a C module whose sole
> purpose is to wrap readdir...
>
> Evan
>
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Lumberjack Song

2012-01-10 Thread pyotr filipivich
Tom Zych  on Mon, 28 Feb 2011 05:26:35 -0500
typed in comp.lang.python  the following:
>We all like computers here. No doubt many of us like computer games.
>And most of us will be at least somewhat familiar with Monty Python.
>Therefore, I present (drum roll)...
>
>http://www.youtube.com/watch?v=Zh-zL-rhUuU
>
>(For the Runescape fans out there, this should be quite hilarious.
>Possibly not as much for those unfamiliar with Runescape...)

Look for the version in German.

Viel Spass.

tschus
pyotr

--  
APL is a mistake, carried through to perfection.  It is the language of the
future for the programming techniques of the past: it creates a new generation
of coding bums.
-- Edsger W. Dijkstra, SIGPLAN Notices, Volume 17, Number 5
-- 
http://mail.python.org/mailman/listinfo/python-list


cx_Freeze ImportError, how do I debug this

2012-01-10 Thread Jeffrey Britton
I am building a standalone Windows executable using cx_Freeze.
The resulting executable will not run and writes the following error
to the console.

ImportError: could not import gobject (error was: 'No module named
gobject')

The project using the gtk libraries for Cairo and Pango on Windows.
The program runs fine when run with Python.
I have tried copying anything that cx_Freeze may have missed from the
gtk installation under the Python directory.

My question is, is there a method to debug this, that can tell me more
about what is going on?

The executable directory already contains
_gobject.pyd
libgobject-2.0-0.dll
libcairo-gobject-2.dll
and a bunch of other stuff.

I can type
import gobject
in the Python shell and that works.

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


Re: Newbie: Looking for code review on my first Python project.

2012-01-10 Thread Steven D'Aprano
On Tue, 10 Jan 2012 22:59:23 -0500, Terry Reedy wrote:

> On 1/10/2012 8:43 PM, Chris Angelico wrote:
> 
>> about = "Built by Walter Hurry using Python and wxPython,\n" + \
>>  "with wxGlade to generate the code for the GUI elements.\n" +
>>  \ "Phil Lewis' get_iplayer does the real work.\n\n" + \
>>  "Version 1.05: January 10, 2012"
>>
>> I'd do this with a triple-quoted string:
>>
>> about = """Built by Walter Hurry using Python and wxPython, with
>> wxGlade to generate the code for the GUI elements. Phil Lewis'
>> get_iplayer does the real work.
> 
> I would too, but if you prefer the indentation, just leave out the '+'s
> and let Python do the catenation when compiling:
>  >>> s = "abc\n" \
>  "def\n"\
>  "ghi"
>  >>> s
> 'abc\ndef\nghi'

Actually, in recent Pythons (2.5 or better, I believe) the peephole 
optimizer will do the concatenation at compile time even if you leave the 
+ signs in, provided that the parts are all literals.


>>> from dis import dis
>>> dis(compile(r's = "a\n" + "b\n"', '', 'single'))
  1   0 LOAD_CONST   3 ('a\nb\n')
  3 STORE_NAME   0 (s)
  6 LOAD_CONST   2 (None)
  9 RETURN_VALUE


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


Re: Newbie: Looking for code review on my first Python project.

2012-01-10 Thread Terry Reedy

On 1/10/2012 8:43 PM, Chris Angelico wrote:


about = "Built by Walter Hurry using Python and wxPython,\n" + \
 "with wxGlade to generate the code for the GUI elements.\n" + \
 "Phil Lewis' get_iplayer does the real work.\n\n" + \
 "Version 1.05: January 10, 2012"

I'd do this with a triple-quoted string:

about = """Built by Walter Hurry using Python and wxPython,
with wxGlade to generate the code for the GUI elements.
Phil Lewis' get_iplayer does the real work.


I would too, but if you prefer the indentation, just leave out the '+'s 
and let Python do the catenation when compiling:

>>> s = "abc\n" \
"def\n"\
"ghi"
>>> s
'abc\ndef\nghi'

--
Terry Jan Reedy

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


Re: UnicodeEncodeError in compile

2012-01-10 Thread Terry Reedy

On 1/10/2012 3:08 AM, Terry Reedy wrote:

On 1/9/2012 11:24 PM, pyscrip...@gmail.com wrote:

Using python 3.2 in Windows 7 I am getting the following:


compile('pass', r'c:\temp\工具\module1.py', 'exec')


Is this a filename that could be an actual, valid filename on your system?


UnicodeEncodeError: 'mbcs' codec can't encode characters in position
0--1: invalid character

Can anybody explain why the compile statement tries to convert the
unicode filename using mbcs?


Good question. I believe this holdover from 2.x should be deleted.
I argued that in http://bugs.python.org/issue10114
(which was about a different problem) and now, directly, in
http://bugs.python.org/issue13758

If you (or anyone) can make a better argument for the requested change, 
or for also changing compile on *nix, than I did, please do so.


--
Terry Jan Reedy



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


Ctypes compatibility

2012-01-10 Thread Evan Driscoll
Might as well ask another question of the list.

I've written a ctypes-based Python wrapper around the 'readdir'
function. (I want access to the dt_type field of the result, without
calling stat().)

However, it feels very... fragile. What happens on a different *nix
which uses a different size of integers? Is Linux even consistent
between 32 and 64 bits? (That's a rhetorical question.) What happens on
a different *nix with the fields in a different order, or without a
dt_type field?

It somehow feels wrong that you get way less help with this than you
would get even from C. Is that just how it is with ctypes? Or is there
some way around it? I'm sort of tempted to write a C module whose sole
purpose is to wrap readdir...

Evan




signature.asc
Description: OpenPGP digital signature
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: replacing __dict__ with an OrderedDict

2012-01-10 Thread Roy Smith
In article ,
 Lie Ryan  wrote:

> >> All serious database has rollback feature when they're available to
> >> quickly revert database state in the setUp/cleanUp phase.
> >
> > I guess MongoDB is not a serious database?
> 
> I guess there are always those oddball cases, but if you choose MongoDB 
> then you already know the consequences that it couldn't be as easily 
> unit-tested. And in any case, it is generally a bad idea to unittest 
> with a database that contains 100 million items, that's for performance 
> testing. So your point is?

My point is that in the real world, what is practical and efficient and 
sound business is not always what is theoretically correct.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie: Looking for code review on my first Python project.

2012-01-10 Thread Ben Finney
Chris Angelico  writes:

> On Wed, Jan 11, 2012 at 10:44 AM, HoneyMonster
>  wrote:
> > Hi,
> >
> > I'm new to Python and recently completed my first project. I used
> > wxPython with wxGlade to generate the GUI bits.The application seems to
> > work well, but I am entirely self-taught, so have undoubtedly committed a
> > number of howlers in terms of style, design, standards, best practice and
> > so forth.
>
> Welcome!
>
> Ian has already offered some excellent tips, so I'll not repeat him.
>
>
> log = os.environ['HOME'] + "/log/bbc.log"
> log = os.environ['HOMEPATH'] + "\\log\\bbc.log"
>
> Python on Windows will support / for paths

Even better, you don't need to worry about what separator to use::

top_dir = os.environ['HOME']
log_filepath = os.path.join(top_dir, "log", "bbc.log")

> I'd do this with a triple-quoted string:
>
> about = """Built by Walter Hurry using Python and wxPython,
> with wxGlade to generate the code for the GUI elements.
> Phil Lewis' get_iplayer does the real work.
>
> Version 1.05: January 10, 2012"""

Which you can get indented nicely in the source, and strip off the
indentation at run-time:

import textwrap

about = textwrap.dedent("""\
Built by Walter Hurry using Python and wxPython,
with wxGlade to generate the code for the GUI elements.
Phil Lewis' get_iplayer does the real work.

Version 1.05: January 10, 2012
""")

> self.add = self.file.AppendItem(wx.MenuItem(self.file,
> wx.NewId(), "&Add to Queue", "Add a programme to the queue (for
> download later)", wx.ITEM_NORMAL))

Which is a whole lot more readable using the recommendations in PEP 8::

self.add = self.file.AppendItem(
wx.MenuItem(
self.file, wx.NewId(), "&Add to Queue",
"Add a programme to the queue (for download later)",
wx.ITEM_NORMAL))

-- 
 \   “I distrust those people who know so well what God wants them |
  `\to do to their fellows, because it always coincides with their |
_o__)  own desires.” —Susan Brownell Anthony, 1896 |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: your feedback to my first project please

2012-01-10 Thread Terry Reedy

On 1/10/2012 9:06 AM, Jean-Michel Pichavant wrote:


- I quite dislike your avg method which does more than averaging, it
also inserts a value and removes another modifying the object in place.
It could be very confusing for someone reading your code. Fortunately,
you have documented it, that makes it acceptable. Why don't you make avg
only averaging. Surely you can use the add method right before.


Or use a better name, like running_average or run_mean (if that is what 
it is doing).


--
Terry Jan Reedy

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


Re: Newbie: Looking for code review on my first Python project.

2012-01-10 Thread Terry Reedy

On 1/10/2012 8:17 PM, Ian Kelly wrote:

On Tue, Jan 10, 2012 at 4:44 PM, HoneyMonster  wrote:

Hi,

I'm new to Python and recently completed my first project. I used
wxPython with wxGlade to generate the GUI bits.The application seems to
work well, but I am entirely self-taught, so have undoubtedly committed a
number of howlers in terms of style, design, standards, best practice and
so forth.

Is there any kind soul here who would be willing to take a look at the
code and offer comments?  The code is at:



Okay, here goes. :-)


Nice review. Though OP used and you wrote about wx, when I get deeper 
into the IDLE code, I will look to see whether tkinter/idle resource 
provide context managers (if not, try to add) and whether idle is using 
them. (I won't be surprised if answers are often no and no.)


--
Terry Jan Reedy

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


Re: Newbie: Looking for code review on my first Python project.

2012-01-10 Thread Chris Angelico
On Wed, Jan 11, 2012 at 10:44 AM, HoneyMonster
 wrote:
> Hi,
>
> I'm new to Python and recently completed my first project. I used
> wxPython with wxGlade to generate the GUI bits.The application seems to
> work well, but I am entirely self-taught, so have undoubtedly committed a
> number of howlers in terms of style, design, standards, best practice and
> so forth.

Welcome!

Ian has already offered some excellent tips, so I'll not repeat him.


log = os.environ['HOME'] + "/log/bbc.log"
log = os.environ['HOMEPATH'] + "\\log\\bbc.log"

Python on Windows will support / for paths; I'd then break out the
HOME / HOMEPATH check into a separate variable (eg 'basepath'), and
then only that and icondir would need to be in the 'if Linux' block.


about = "Built by Walter Hurry using Python and wxPython,\n" + \
"with wxGlade to generate the code for the GUI elements.\n" + \
"Phil Lewis' get_iplayer does the real work.\n\n" + \
"Version 1.05: January 10, 2012"

I'd do this with a triple-quoted string:

about = """Built by Walter Hurry using Python and wxPython,
with wxGlade to generate the code for the GUI elements.
Phil Lewis' get_iplayer does the real work.

Version 1.05: January 10, 2012"""


# Configure the logging
# Generate a list for the PVR queue

Comments like this aren't much use, although the second would be a
good place to expand "PVR".

# We only want the PID at the start if the line, and
it is always 8 bytes

Much more useful :)


self.add = wx.MenuItem(self.file, wx.NewId(), "&Add to Queue",
"Add a programme to the queue (for download later)", wx.ITEM_NORMAL)
self.file.AppendItem(self.add)

I don't have/use wxpython so I can't say for sure, but I think
AppendItem returns the item appended. This allows you to avoid
repeating yourself:

self.add = self.file.AppendItem(wx.MenuItem(self.file,
wx.NewId(), "&Add to Queue", "Add a programme to the queue (for
download later)", wx.ITEM_NORMAL))

This prevents mismatching assignment and append, when you copy/paste/edit etc.

Decent bit of code. I've seen far worse... and not from new programmers :)

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


Introspecting optparse/argparse objects

2012-01-10 Thread Evan Driscoll
I'd like to be able to be able to define options and then look at the
lists. (For a concrete idea of a use case, suppose that it did not
directly support the --help option and I wanted to write code that took
its place.) Unfortunately, there doesn't seem to be any public API for
doing this.

Even if I were to do something like
options = [ make_option(...), make_option(...) ]
(using optparse) and could thus get a handle on the Option objects,
there doesn't seem to be a public API for retrieving stuff like the
actual options (though available via opt._short_opts and opt._long_opts).

This means that either I need to write my own wrappers around options,
option groups, and perhaps even an option parser, or I have to dig into
_variables _that _are _not _part _of _the _public _api. Both of those
choices are distasteful.

So,
1) Did I miss anything?
2) Is there some particular reason that this API *isn't* provided, and
if I asked for it I might get it in a future version?

Evan




signature.asc
Description: OpenPGP digital signature
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to install lxml in window xp?

2012-01-10 Thread alex23
On Jan 9, 8:19 pm, Stefan Behnel  wrote:
> Note that lxml currently lacks binary Windows builds for its latest
> releases. There are eggs for the original 2.3 release, though.

Christoph Gohlke provides a fairly up-to-date set of Python packaged
binaries for Windows 32- & 64-bit.

There are lxml packages for Python 2.6 to 3.2, and 2.5 for 32-bit
only.

http://www.lfd.uci.edu/~gohlke/pythonlibs/#lxml

This is a fantastic resource that more Windows-based Python devs
should know about.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie: Looking for code review on my first Python project.

2012-01-10 Thread Ian Kelly
On Tue, Jan 10, 2012 at 4:44 PM, HoneyMonster  wrote:
> Hi,
>
> I'm new to Python and recently completed my first project. I used
> wxPython with wxGlade to generate the GUI bits.The application seems to
> work well, but I am entirely self-taught, so have undoubtedly committed a
> number of howlers in terms of style, design, standards, best practice and
> so forth.
>
> Is there any kind soul here who would be willing to take a look at the
> code and offer comments?  The code is at:
> 

Okay, here goes. :-)

# Globals
Title = 0
Episode = 1
Categories = 2
Channel = 3
PID = 4
Index = 5

The recommended PEP-8 style for names of constants is ALL_CAPS.  Also,
if you just have a simple enumeration like this, you can avoid setting
specific values, which might otherwise lead to the temptation to use
the values in some places instead of the constant names.  Just tell
your program how to generate them, and let it do the work:

TITLE, EPISODE, CATEGORIES, CHANNEL, PID, INDEX = range(6)

=

# Error handling: Log to file, show message and abort
def ProcessError(text):
logging.exception(text)
dlg = wx.MessageDialog(None, text + " " + str(sys.exc_info()[1]) + \
   "\nSee " + log + " for details.", "BBC Programmes", \
   wx.ICON_ERROR|wx.OK)
dlg.ShowModal()
dlg.Destroy()
sys.exit()

In the more recent versions of wxPython, which I assume you're using,
dialogs provide context managers to handle their destruction.  The
above would become:

def process_error(text):
logging.exception(text)
with wx.MessageDialog(...) as dlg:
dlg.ShowModal()
sys.exit()

The value of the context manager is that its __exit__ method (which
destroys the dialog) is guaranteed to be called when the with block
exits, even if an exception is raised inside of it.  You'll note I
also renamed the function using the PEP-8 style for functions.
Another comment here is that the text of the dialog is a good
candidate for Python's string formatting feature.  Instead of:

text + " " + str(sys.exc_info()[1]) + "\nSee " + log + " for details."

do:

"{} {}\nSee {} for details.".format(text, sys.exc_info()[1], log)

which is more legible and also avoids doing multiple string concatenations.

=

class clsUtils():

The parentheses are redundant; this is equivalent to "class
clsUtils:".  Note that in Python 2.x, classes defined without a base
class are old-style classes by default, which have been removed in
Python 3.  It's recommended that you use new-style classes in your
code unless you have a good reason not to.  You can accomplish this by
inheriting from object explicitly:

class Utils(object):

Note I also converted the class name to the PEP-8 CapWords convention
for classes, and I dropped the redundant 'cls' prefix.

My other comment on this class is that it has no state, and no methods
apart from __init__.  You apparently only instantiate it in order to
execute the __init__ method, which seems to initialize some global
variables rather than initializing the class instance.  If you don't
plan on interacting with the Utils instance as an object, then this
would make more sense as a function.

=

def OnDescription(self, event): # wxGlade: MyFrame.
wx.BeginBusyCursor()
if Linux:
wx.Yield()
pos = self.TopGrid.GetGridCursorRow()
TitleEp = self.Prettify(recs[pos][Title], recs[pos][Episode])
self.TopFrame_statusbar.SetStatusText("Retrieving description
for " + TitleEp)
info = subprocess.check_output("get_iplayer --info " +
str(recs[pos][Index]), shell=True)
info = str.splitlines(info, False)
for line in info:
if line[:5] == "desc:":
info = line[16:]
break
wx.EndBusyCursor()
...

The BusyCursor is another resource that provides a context manager.
You can use it like this:

def on_description(self, event): # wxGlade: MyFrame.
with wx.BusyCursor():
...

This is a good idea since if an exception is raised in the middle of
the method, the mouse pointer won't end up stuck as an hourglass.
Also note that I once again meddled with the naming style to conform
with PEP-8, this time for the method name.

Further, this line:

info = str.splitlines(info, False)

could be written simply as:

info = info.splitlines(False)

=

def OnIdle(self, event):
# Instantiate the other classes here, then hand over to TopFrame
if self.first_time:
self.first_time = False
...

An idle event handler is the wrong paradigm here.  Idle events are for
background computation that you need to do regularly whenever the
application becomes idle.  For the simpler case of a one-time function
call that should not run until after the event loop has started, use
the wx.CallAfter() function.

=

I don't have any more specific observations.  The onl

Re: LibreOffice with Python

2012-01-10 Thread Ben Finney
Terry Reedy  writes:

> Are there any links for that?
[…]
> Do you have any idea how to get the importable modules?

Those will have to be exercises for someone with more need than I of
hacking on an office suite. I have no experience with that.

-- 
 \“Your [government] representative owes you, not his industry |
  `\   only, but his judgment; and he betrays, instead of serving you, |
_o__)if he sacrifices it to your opinion.” —Edmund Burke, 1774 |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: UnicodeEncodeError in compile

2012-01-10 Thread Terry Reedy

On 1/10/2012 8:43 AM, jmfauth wrote:

D:\>c:\python32\python.exe
Python 3.2.2 (default, Sep  4 2011, 09:51:08) [MSC v.1500 32 bit
(Intel)] on win
32
Type "help", "copyright", "credits" or "license" for more information.

'\u5de5'.encode('utf-8')

b'\xe5\xb7\xa5'

'\u5de5'.encode('mbcs')

Traceback (most recent call last):
   File "", line 1, in
UnicodeEncodeError: 'mbcs' codec can't encode characters in position
0--1: inval
id character



D:\>c:\python27\python.exe
Python 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit
(Intel)] on win
32
Type "help", "copyright", "credits" or "license" for more information.

u'\u5de5'.encode('utf-8')

'\xe5\xb7\xa5'

u'\u5de5'.encode('mbcs')

'?'


mbcs encodes according to the current codepage. Only the chinese 
codepage(s) can encode the chinese char. So the unicode error is correct 
and 2.7 has a bug in that it is doing "errors='replace'" when it 
supposedly is doing "errors='strict'". The Py3 fix was done in

http://bugs.python.org/issue850997
2.7 was intentionally left alone because of back-compatibility 
considerations. (None of this addresses the OP's question.)


--
Terry Jan Reedy

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


Re: LibreOffice with Python

2012-01-10 Thread Terry Reedy

On 1/10/2012 5:29 PM, Ben Finney wrote:


LibreOffice supports scripting with several languages, including Python
http://help.libreoffice.org/Common/Scripting>.


So that page says. But it only tells how to attach a Python script once 
writen, not how to write one that will do anything. Are there any links 
for that?



Extensions can also be written in Python, using the UNO runtime API
http://api.libreoffice.org/>.


The one Python example imports Python wrappers for the API. Do you have 
any idea how to get the importable modules?


--
Terry Jan Reedy

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


Newbie: Looking for code review on my first Python project.

2012-01-10 Thread HoneyMonster
Hi,

I'm new to Python and recently completed my first project. I used
wxPython with wxGlade to generate the GUI bits.The application seems to
work well, but I am entirely self-taught, so have undoubtedly committed a
number of howlers in terms of style, design, standards, best practice and
so forth.

Is there any kind soul here who would be willing to take a look at the
code and offer comments?  The code is at:


Thanks

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


Re: An "alternative" to Learning Perl

2012-01-10 Thread Sebastian Rooks
On Mon, 9 Jan 2012 00:55:22 -0300, Sean Wolfe 
wrote:

>kindle? ipad? tablet?

I'm interested in books, not files ... 
(seriously, now ... I don't have any of those devices)

>also there is python programming for the absolute beginner, which is
>agreat book but it's pretty beginner. But well written. At least
>Iliked 
>it.http://www.amazon.com/Python-Programming-Absolute-Beginner-3rd/dp/1435455002
>Also byte of python ... I think there's a hardcover version you can
>buyhttp://www.swaroopch.com/buybook/

I think I saw that second one somewhere already. I'll check out the
first link, also. Thanks!

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


Re: Calling a variable inside a function of another class

2012-01-10 Thread Terry Reedy



Yigit Turgut wrote:

class test(test1):

def __init__(self, device):
.
.
.
def _something(self, x=1)
self.dt = data


if __name__ == "__main__":
test.something.dt ???

I am trying to call a variable located in a function of a class


dt is an attribute of an instance of the class.
  t = test() # create instance
  t._something() # call method that assigns attribute to t
  t.dt  # is not the value of dt for t

--
Terry Jan Reedy

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


LibreOffice with Python (was: open office in another language?)

2012-01-10 Thread Ben Finney
Sean Wolfe  writes:

> I'm a somewhat-satisfied openoffice.org user.

You may know about the change of focus in recent months to LibreOffice
https://www.libreoffice.org/>. The Document Foundation is where the
majority of the project's institutional knowledge, development effort,
open collaboration, and all actual released software over the last year
now reside.

> I mean it works, but if it weren't in Java I'd be doing some of my own
> tweaking. But since it's in Java I stay away... no likey.

LibreOffice supports scripting with several languages, including Python
http://help.libreoffice.org/Common/Scripting>.

Extensions can also be written in Python, using the UNO runtime API
http://api.libreoffice.org/>.

-- 
 \   “Pinky, are you pondering what I'm pondering?” “Well, I think |
  `\   so, Brain, but ‘apply North Pole’ to what?” —_Pinky and The |
_o__)   Brain_ |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: open office in another language?

2012-01-10 Thread Sean Wolfe
On Tue, Jan 10, 2012 at 6:53 PM, Nelle Varoquaux
 wrote:
> Small nitpick: Openoffice.org (and LibreOffice) has in fact very little
> java. The core of it is written in C++, so if you ever want to extend it
> (unlikely), you won't be dealing with java code.
>

hmm I didn't know this, nice to know. Yes, C++ is still enough
overhead that I wouldn't want to try extending it ... I bet the code
is a whole lot to try and grok.

It would be nice to have an office suite in a newer language that is
easier to tinker with.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: I look for a tool like webalizer in python language

2012-01-10 Thread Chris Angelico
On Wed, Jan 11, 2012 at 2:24 AM, Stéphane Klein  wrote:
> Hi,
>
> I wonder if there are a tool like webalizer in python language.
> (http://en.wikipedia.org/wiki/Webalizer).
>
> I would like to do some patch in webalizer, but I don't want to spend too
> many time to do that in C language. In Python I can do this patch in few
> minute.
>
> Do you know a tool like this in Python ?

I use AWStats for my sites; it's not Python but Perl, but at least it
is a scripting language.

You won't find "Webalizer-in-Python" anywhere; whatever analyzer you
find will have different features. So just grab any one, give it a
shot, and see how you like it!

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


Re: open office in another language?

2012-01-10 Thread Nelle Varoquaux
On 10 January 2012 22:43, Sean Wolfe  wrote:

> I'm a somewhat-satisfied openoffice.org user. I mean it works, but if
> it weren't in Java I'd be doing some of my own tweaking. But since
> it's in Java I stay away... no likey.
>

Small nitpick: Openoffice.org (and LibreOffice) has in fact very little
java. The core of it is written in C++, so if you ever want to extend it
(unlikely), you won't be dealing with java code.

Has there been any talk of doing another similar office suite, or
> maybe just writer + spreadsheet, in a better language eg python? I
> expect it's a huge undertaking but ... thought I'd ask around at
> least.


>
> --
> A musician must make music, an artist must paint, a poet must write,
> if he is to be ultimately at peace with himself.
> - Abraham Maslow
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


open office in another language?

2012-01-10 Thread Sean Wolfe
I'm a somewhat-satisfied openoffice.org user. I mean it works, but if
it weren't in Java I'd be doing some of my own tweaking. But since
it's in Java I stay away... no likey.

Has there been any talk of doing another similar office suite, or
maybe just writer + spreadsheet, in a better language eg python? I
expect it's a huge undertaking but ... thought I'd ask around at
least.


-- 
A musician must make music, an artist must paint, a poet must write,
if he is to be ultimately at peace with himself.
- Abraham Maslow
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: generating unique set of dicts from a list of dicts

2012-01-10 Thread Dave Angel

On 01/10/2012 03:24 PM, bruce wrote:


Since dict_hash returns a string, which is immutable, you can now use
a dictionary to find the unique elements:

uniques_map = {}
for d in list_of_dicts:
 uniques[dict_hash(d)] = d
unique_dicts = uniques_map.values()


*** not sure what the "uniqes" is, or what/how it should be defined
Don't know about the rest of the message, but I think there's a typo in 
the above fragment.  On the third line, it should be uniques_map, not 
uniques that you're adding an item to.


And unless you have a really long (and strong) hash, you still have to 
check for actually equal.  In otherwords, the above solution will throw 
out a dict that happens to have the same hash as one already in the 
uniques_map.


Do you trust the  "equals" method  for your dicts ?  If not, that's your 
first problem.  If you do, then you can simply do


unique_dicts = []
for d in list_of_dicts:
 if d not in unique_dicts:
   unique_dicts.append(d)

Do it, then decide if performance is inadequate.  Only then  should you 
worry about faster methods, especially if the faster method is broken.




--

DaveA

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


generating unique set of dicts from a list of dicts

2012-01-10 Thread bruce
trying to figure out how to generate a unique set of dicts from a
json/list of dicts.

initial list :::
[{"pStart1a": 
{"termVal":"1122","termMenu":"CLASS_SRCH_WRK2_STRM","instVal":"OSUSI",
"instMenu":"CLASS_SRCH_WRK2_INSTITUTION","goBtn":"CLASS_SRCH_WRK2_SSR_PB_SRCH",
"pagechk":"CLASS_SRCH_WRK2_SSR_PB_SRCH","nPage":"CLASS_SRCH_WRK2_SSR_PB_CLASS_SRCH"},
"pSearch1a":
{"chk":"CLASS_SRCH_WRK2_MON","srchbtn":"DERIVED_CLSRCH_SSR_EXPAND_COLLAPS"}},
 {"pStart1":""},
 
{"pStart1a":{"termVal":"1122","termMenu":"CLASS_SRCH_WRK2_STRM","instVal":"OSUSI",
 "instMenu":"CLASS_SRCH_WRK2_INSTITUTION","goBtn":"CLASS_SRCH_WRK2_SSR_PB_SRCH",
 
"pagechk":"CLASS_SRCH_WRK2_SSR_PB_SRCH","nPage":"CLASS_SRCH_WRK2_SSR_PB_CLASS_SRCH"},
 "pSearch1a":
 {"chk":"CLASS_SRCH_WRK2_MON","srchbtn":"DERIVED_CLSRCH_SSR_EXPAND_COLLAPS"}},
 {"pStart1":""}]



As an exmple, the following is the test list:

[{"pStart1a": 
{"termVal":"1122","termMenu":"CLASS_SRCH_WRK2_STRM","instVal":"OSUSI",
"instMenu":"CLASS_SRCH_WRK2_INSTITUTION","goBtn":"CLASS_SRCH_WRK2_SSR_PB_SRCH",
"pagechk":"CLASS_SRCH_WRK2_SSR_PB_SRCH","nPage":"CLASS_SRCH_WRK2_SSR_PB_CLASS_SRCH"},
"pSearch1a":
{"chk":"CLASS_SRCH_WRK2_MON","srchbtn":"DERIVED_CLSRCH_SSR_EXPAND_COLLAPS"}},
 {"pStart1":""},
 
{"pStart1a":{"termVal":"1122","termMenu":"CLASS_SRCH_WRK2_STRM","instVal":"OSUSI",
 "instMenu":"CLASS_SRCH_WRK2_INSTITUTION","goBtn":"CLASS_SRCH_WRK2_SSR_PB_SRCH",
 
"pagechk":"CLASS_SRCH_WRK2_SSR_PB_SRCH","nPage":"CLASS_SRCH_WRK2_SSR_PB_CLASS_SRCH"},
 "pSearch1a":
 {"chk":"CLASS_SRCH_WRK2_MON","srchbtn":"DERIVED_CLSRCH_SSR_EXPAND_COLLAPS"}},
 {"pStart1":""}]

Trying to get the following, list of unique dicts, so there aren't
duplicate dicts.
 Searched various sites/SO.. and still have a mental block.

[
  {"pStart1a":
  {"termVal":"1122","termMenu":"CLASS_SRCH_WRK2_STRM","instVal":"OSUSI",
   
"instMenu":"CLASS_SRCH_WRK2_INSTITUTION","goBtn":"CLASS_SRCH_WRK2_SSR_PB_SRCH",
   
pagechk":"CLASS_SRCH_WRK2_SSR_PB_SRCH","nPage":"CLASS_SRCH_WRK2_SSR_PB_CLASS_SRCH"},
  "pSearch1a":
  {"chk":"CLASS_SRCH_WRK2_MON","srchbtn":"DERIVED_CLSRCH_SSR_EXPAND_COLLAPS"}},
  {"pStart1":""}]

I was considering iterating through the initial list, copying each
dict into a new list, and doing a basic comparison, adding the next
dict if it's not in the new list.. is there another/better way?

posted this to StackOverflow as well.  
http://stackoverflow.com/questions/8808286/simplifying-a-json-list-to-the-unique-dict-items
 <<<

There was a potential soln that I couldn't understand.


-
The simplest approach -- using list(set(your_list_of_dicts)) won't
work because Python dictionaries are mutable and not hashable (that
is, they don't implement __hash__). This is because Python can't
guarantee that the hash of a dictionary won't change after you insert
it into a set or dict.

However, in your case, since you (don't seem to be) modifying the data
at all, you can compute your own hash, and use this along with a
dictionary to relatively easily find the unique JSON objects without
having to do a full recursive comparison of each dictionary to the
others.

First, we need a function to compute a hash of the dictionary. Rather
than trying to build our own hash function, let's use one of the
built-in ones from hashlib:

def dict_hash(d):
out = hashlib.md5()
for key, value in d.iteritems():
out.update(unicode(key))
out.update(unicode(value))
return out.hexdigest()

(Note that this relies on unicode(...) for each of your values
returning something unique -- if you have custom classes in the
dictionaries whose __unicode__ returns something like "MyClass
instance", this will fail or will require modification. Also, in your
example, your dictionaries are flat, but I'll leave it as an exercise
to the reader how to expand this solution to work with dictionaries
that contain other dicts or lists.)

Since dict_hash returns a string, which is immutable, you can now use
a dictionary to find the unique elements:

uniques_map = {}
for d in list_of_dicts:
uniques[dict_hash(d)] = d
unique_dicts = uniques_map.values()

*** not sure what the "uniqes" is, or what/how it should be defined


thoughts/comments are welcome

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


Re: Unclear about verbose regex syntax (excaping whitespace)

2012-01-10 Thread Tim Chase

On 01/10/12 10:49, Roy Smith wrote:

The docs for re.VERBOSE say, "Whitespace within the pattern is
ignored, except when [...] preceded by an unescaped
backslash".  It's unclear exactly what that means.  If my
pattern is:



is the second space considered to be preceded by a backslash,
and thus taken literally, or does the backslash only apply to
the first?  I suspect the latter, but it's somewhat
ambiguous.


You're right (easily testable) in your suspicions that the second 
space is ignored in this case.  I suppose the documentation could 
be tweaked to read "immediately preceded".


-tkc




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


Re: replacing __dict__ with an OrderedDict

2012-01-10 Thread Ulrich Eckhardt

Am 10.01.2012 13:31, schrieb Lie Ryan:

While it is possible to replace __dict__ with OrderedDict and it is
possible to reorder the test, those are not his original problem, and
the optimal solution to his original problem differs from the optimal
solution to what he think he will need.


Oh, and you know what is optimal in his environment? You really think 
you know better what to do based on the little information provided?




I had said this before and I'm saying it again: the problem is a test
result displaying issue, not testing order issue.


There are good reasons for not reordering the results of the tests that 
would be sacrificed by reordering them afterwards.



If you'd just step off your high horse you might actually learn 
something instead of just pissing people off.


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


Re: Help with python-list archives

2012-01-10 Thread Anssi Saari
Ian Kelly  writes:

> Probably nobody has noticed it until now.  It seems to be a quirk of
> the archive files that they are double-gzipped...

Interesting, but I don't think the files are actually double-gzipped. If
I download
http://mail.python.org/pipermail/python-list/2012-January.txt.gz with
wget in Cygwin or Unix, the file is 226753 bytes and singly gzipped.

However, if I download the same file with Firefox in Windows, then it's
226782 bytes and double gzipped. So maybe it's something in the browser
or server setup?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: replacing __dict__ with an OrderedDict

2012-01-10 Thread Tim Wintle
On Tue, 2012-01-10 at 09:05 -0500, Roy Smith wrote:
> 
> I guess MongoDB is not a serious database? 

That's opening up a can of worms ;)


... anyway, cassandra is far better.

Tim

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


Unclear about verbose regex syntax (excaping whitespace)

2012-01-10 Thread Roy Smith
The docs for re.VERBOSE say, "Whitespace within the pattern is ignored, except 
when [...] preceded by an unescaped backslash".  It's unclear exactly what that 
means.  If my pattern is:



is the second space considered to be preceded by a backslash, and thus taken 
literally, or does the backslash only apply to the first ?  I suspect 
the latter, but it's somewhat ambiguous.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: codecs in a chroot / without fs access

2012-01-10 Thread K Richard Pixley

On 1/9/12 16:41 , Philipp Hagemeister wrote:

I want to forbid my application to access the filesystem. The easiest
way seems to be chrooting and droping privileges. However, surprisingly,
python loads the codecs from the filesystem on-demand, which makes my
program crash:


import os
os.getuid()

0

os.chroot('/tmp')
''.decode('raw-unicode-escape')

Traceback (most recent call last):
   File "", line 1, in

(Interestingly, Python goes looking for the literal file "" in
sys.path. Wonder what happens if I touch
/usr/lib/python2.7/dist-packages/).

Is there a neat way to solve this problem, i.e. have access to all
codecs in a chroot?


The traditional solution is to copy the data you want to make available 
into the subdirectory tree that will be used as the target of the chroot.



If not, I'd love to have a function codecs.preload_all() that does what
my workaround does:

import codecs,glob,os.path
encs = [os.path.splitext(os.path.basename(f))[0]
 for f in glob.glob('/usr/lib/python*/encodings/*.py')]
for e in encs:
   try:
 codecs.lookup(e)
   except LookupError:
 pass # __init__.py or something


enumerate /usr/lib/python.*/encodings/*.py and call codecs.lookup for
every os.path.splitext(os.path.basename(filename))[0]

Dou you see any problem with this design?


Only the timing.  If you're using the shell level chroot(1) program then 
you're already chroot'd before this can execute.  If you're using 
os.chroot, then:


a) you're unix specific
b) your program must initially run as root
c) you have to drop privilege yourself rather than letting something 
like chroot(1) handle it.


As alternatives, you might consider building a root file system in a 
file and mounting it separately on a read-only basis.  You can chroot 
into that without much worry of how it will affect your regular file system.


With btrfs as root, you can create snapshots and chroot into those.  You 
can even mount them separately, read-only if you like, before chrooting. 
 The advantage of this approach is that the chroot target is built 
"automatically" in the sense that it's a direct clone of your underlying 
root file system, without allowing anything in the underlying root file 
system to be altered.  Files can be changed, but since btrfs is 
copy-on-write, only the files in the snapshot will be changed.


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


Re: Perplexed by the behavior of import

2012-01-10 Thread Peter Otten
Rod Kosloski wrote:

> I'm perlexed by an apparent inconsistency in the behavior of the import
> statement.
> 
> First, the files. There is a simple package, pkg, containing two files:
> mod.py and util.py, and a stand-alone module also named util.py:
> 
>*** ./pkg/__init__.py ***
>from mod import *
>*** ./pkg/mod.py ***
>M = 8
>*** ./pkg/util.py ***
>V = 0
>*** ./util.py ***
>from pkg import *
>from pkg.util import *
>U = 0
> 
> Next, the Python session:
> 
>Python 2.6.4 (r264:75706, Dec 13 2009, 19:46:11)
>[GCC 4.2.1 (Apple Inc. build 5646) (dot 1)] on darwin
>Type "help", "copyright", "credits" or "license" for more information.
>>>> import util
>>>> globals()
>{'__builtins__': , '__name__':
>{'__main__',
> '__doc__': None 'util': ,
> '__package__': None}
>>>> from pkg import *
>>>> globals()
>{'__builtins__': , 'M': 8,
>{'__package__':
> None, 'util': , '__name__':
> '__main__', '__doc__': None,
> 'mod': }
> 
> Compare the output of the two globals() statements:
> Variable util's value has changed from 
> to 
> 
> What's happening to util?
> 
> OK, maybe pkg.util replaces the original util because of the pkg import
> statement. 

That's indeed what happens.

> But then, what about the following:
> 
>Python 2.6.4 (r264:75706, Dec 13 2009, 19:46:11)
>[GCC 4.2.1 (Apple Inc. build 5646) (dot 1)] on darwin
>Type "help", "copyright", "credits" or "license" for more information.
>>>> util = 0
>>>> globals()
>{'__builtins__': , '__name__':
>{'__main__',
> '__doc__': None, 'util': 0, '__package__': None}
>>>> from pkg import *
>>>> globals()
>{'__builtins__': , 'M': 8,
>{'__package__':
> None, 'util': 0, '__name__': '__main__', '__doc__': None, 'mod':
> }
>>>>
> 
> Now the value of util is unchanged across the pkg import statement.
> 
> Why the difference?

As long as you haven't imported the pkg.util module there isn't an "util" 
variable in the pkg namespace:

$ python -c 'import pkg; print "util" in vars(pkg); import pkg.util; print 
"util" in vars(pkg)'
False
True

Or, sticking closer to your example:

$ python -c 'util = 0; from pkg import *; print util'
0
$ python -c 'util = 0; import pkg.util; from pkg import *; print util'



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


Re: codecs in a chroot / without fs access

2012-01-10 Thread Miki Tebeka
Another option is to copy the data to the a location under the new chroot and 
register a new lookup functions 
(http://docs.python.org/library/codecs.html#codecs.register). This way you can 
save some memory.
-- 
http://mail.python.org/mailman/listinfo/python-list


Perplexed by the behavior of import

2012-01-10 Thread Rod Kosloski
I'm perlexed by an apparent inconsistency in the behavior of the import
statement.

First, the files. There is a simple package, pkg, containing two files: mod.py
and util.py, and a stand-alone module also named util.py:

   *** ./pkg/__init__.py ***
   from mod import *
   *** ./pkg/mod.py ***
   M = 8
   *** ./pkg/util.py ***
   V = 0
   *** ./util.py ***
   from pkg import *
   from pkg.util import *
   U = 0

Next, the Python session:

   Python 2.6.4 (r264:75706, Dec 13 2009, 19:46:11)
   [GCC 4.2.1 (Apple Inc. build 5646) (dot 1)] on darwin
   Type "help", "copyright", "credits" or "license" for more information.
   >>> import util
   >>> globals()
   {'__builtins__': , '__name__': '__main__',
'__doc__': None 'util': , '__package__':
None}
   >>> from pkg import *
   >>> globals()
   {'__builtins__': , 'M': 8, '__package__':
None, 'util': , '__name__':
'__main__', '__doc__': None,
'mod': }

Compare the output of the two globals() statements:
Variable util's value has changed from  to


What's happening to util?

OK, maybe pkg.util replaces the original util because of the pkg import
statement. But then, what about the following:

   Python 2.6.4 (r264:75706, Dec 13 2009, 19:46:11)
   [GCC 4.2.1 (Apple Inc. build 5646) (dot 1)] on darwin
   Type "help", "copyright", "credits" or "license" for more information.
   >>> util = 0
   >>> globals()
   {'__builtins__': , '__name__': '__main__',
'__doc__': None, 'util': 0, '__package__': None}
   >>> from pkg import *
   >>> globals()
   {'__builtins__': , 'M': 8, '__package__':
None, 'util': 0, '__name__': '__main__', '__doc__': None, 'mod': }
   >>>

Now the value of util is unchanged across the pkg import statement.

Why the difference?

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


Re: replacing __dict__ with an OrderedDict

2012-01-10 Thread Lie Ryan

On 01/11/2012 01:05 AM, Roy Smith wrote:

In article,
  Lie Ryan  wrote:


On 01/10/2012 12:05 PM, Roy Smith wrote:

Somewhat more seriously, let's say you wanted to do test queries against
a database with 100 million records in it.  You could rebuild the
database from scratch for each test, but doing so might take hours per
test.  Sometimes, real life is just*so*  inconvenient.


All serious database has rollback feature when they're available to
quickly revert database state in the setUp/cleanUp phase.


I guess MongoDB is not a serious database?


I guess there are always those oddball cases, but if you choose MongoDB 
then you already know the consequences that it couldn't be as easily 
unit-tested. And in any case, it is generally a bad idea to unittest 
with a database that contains 100 million items, that's for performance 
testing. So your point is?


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


Re: your feedback to my first project please

2012-01-10 Thread patr...@bierans.de
> Jean-Michel wrote: Module names should be lowercase

You're right. I was too lazy and just copied the class name. I will keep
that in mind for the future. ;)

> Jean-Michel wrote: I quite dislike your avg method which does more than
> averaging, it also inserts a value and removes another modifying the
> object in place. It could be very confusing for someone reading your code.
> Fortunately, you have documented it, that makes it acceptable. Why don't
> you make avg only averaging. Surely you can use the add method right before.

Hm. It is (in most cases) only used in that way... So because I am lazy I
thought it might be a good idea. But If I make add() return self I could do
chaining, can't I?

p.e.:
as = AverageStack(10)
avg = as.add(12).avg()

Would that be better?

> Jean-Michel wrote: A very important information is mising from your
> documentation : the type of the parameters. [...] PEP 257

True. I'm still struggling here how to do it. I'd like to write the types
into the signature of the method (like in Java) or use some other way like
in javadoc. """@param name type description""" Writing it into the docstring
as plain text is not very appealing to me. Any concrete tipps or examples?
 
TIA,
Patrick 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Explanation about for

2012-01-10 Thread Thomas Rachel

Am 10.01.2012 12:37 schrieb Νικόλαος Κούρας:


So that means that

for host, hits, agent, date in dataset:

is:

for host, hits, agent, date in  (foo,7,IE6,1/1/11)

and then:

for host, hits, agent, date in  (bar,42,Firefox,2/2/10)

and then:

for host, hits, agent, date in  (baz,4,Chrome,3/3/09)


No.

As said, dataset is the whole result set. For now, you can see it as a 
list of all rows (which you get if you do l=list(dataset)).


Let's assume you have your data in a list now, which is equivalent 
concerning the iteration.


Then you have something like

dataset = [
('foo',7,'IE6','1/1/11'),
('bar',42,'Firefox','2/2/10'),
('baz',4,'Chrome','3/3/09')
]


Doing

for row in dataset: print row

is equivalent to

row = ('foo',7,'IE6','1/1/11')
print row

row = ('bar',42,'Firefox','2/2/10')
print row

row = ('baz',4,'Chrome','3/3/09')
print row



Doing

for a, b, c, d in dataset:
do_funny_stuff(a, d, c, b)

is

a, b, c, d = ('foo',7,'IE6','1/1/11');
# which is the same as
# a = 'foo'; b = 7; c = 'IE6'; d = '1/1/11';
do_funny_stuff(a, d, c, b)

a, b, c, d = ('bar',42,'Firefox','2/2/10')
do_funny_stuff(a, d, c, b)

a, b, c, d = ('baz',4,'Chrome','3/3/09')
do_funny_stuff(a, d, c, b)


The "body" of the for suite is executed once for each element.

You have read already

http://docs.python.org/tutorial/controlflow.html#for-statements
http://docs.python.org/library/stdtypes.html#iterator-types

?


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


Re: Explanation about for

2012-01-10 Thread Nick Dokos
Νικόλαος Κούρας  wrote:

> On 10 Ιαν, 03:11, Ian Kelly  wrote:
> > 2012/1/9 Íéêüëáïò Êïýñáò :
> >
> > > if the MySQL query was:
> >
> > > cursor.execute( '''SELECT host, hits, agent, date FROM visitors WHERE pin 
> > > =
> > > %s ORDER BY date DESC''', pin )
> >
> > > can you help me imagine how the mysql database cursor that holds the query
> > > results would look like? I must somehow visualize it in order to 
> > > understand
> > > it!
> >
> > You can think of it as a pointer, traversing over one row of the
> > result set at a time.  Hopefully this will come out legibly:
> >
> > ---
> > | HOST | HITS | AGENT | DATE |
> > ---            -
> > | foo     | 7       | IE6       | 1/1/11 |   <   | cursor |
> > ---            -
> > | bar     | 42     | Firefox  | 2/2/10 |
> > ---
> > | baz    | 4       | Chrome | 3/3/09 |
> > 
> 
> Database cursor is the pointer that iterates over the result set one
> row at a time?
> I though that it was the name we give to the whole mysql result set
> returned my cursor.execute.
> 
> >
> >
> > > Also what happend if the query was:
> > > cursor.execute( '''SELECT host FROM visitors") ?
> >
> > > the result would have to be something likelike?
> >
> > > -
> > > |somehost1|
> > > -
> > > |somehost2|
> > > -
> > > |somehost3|
> > > -
> > > .
> > > .
> > > |somehost n|
> > > -
> >
> > > So what values host, hits, agent, date would have in 'for host, hits, 
> > > agent,
> > > date in
> > >  dataset' ? Every row has one string how can that be split in 4?
> >
> > Why don't you try it and see what happens?  But to spare you the
> > suspense, you would get:
> >
> > ValueError: need more than 1 value to unpack
> >
> > Because you can't unpack a 1-length tuple into four variables.  The
> > code assumes that the query is selecting exactly 4 columns.
> 
> 
> ---
> | HOST| HITS| AGENT | DATE |
> ---
> | foo | 7   | IE6   | 1/1/11 |
> ---
> | bar | 42  | Firefox   | 2/2/10 |
> ---
> | baz | 4   | Chrome| 3/3/09 |
> ---
> 
> In this line:
> for host, hits, agent, date in dataset:
> 
> 'dataset' is one of the rows of the mysql result or the whole mysql
> result set like the table above?
> 
> I still have trouble understanding this line :(

You can think of it as a list of tuples. Forget about cursors and
databases for now. If l is a list [1, 2, 3, 4] you iterate over it like
this:

for x in l:
  print x

and you get each element of the list[fn:1]. Similarly if l is a list of tuples
l = [(1, 2, 3, 4), (5, 6, 7, 8), (9, 10, 11, 12)] you can iterate over the
list:

for x in l:
  print x

In this case, x is going to be (1,2,3,4) the first time through the loop, 
(5,6,7,8)
the second time and so on. You can break each x apart within the loop:

for x in l:
  t1, t2, t3, t4 = x
  print x, t1, t2, t3, t4

or you can break it apart like this - it's essentially the same thing:

for t1, t2, t3, t4 in l:
  print t1, t2, t3, t4

You have been encouraged repeatedly to try these things interactively:
please do so with the above examples and all will become clear.

Going back to cursors and databases: you *can* think of 'dataset' as
being a list of tuples - a list of all the query results, but with one
proviso. The difference when you use a cursor is that `dataset' may
be a lazy list (an "iterator"): instead of the whole set of results
being in memory at the same time, the system will take care of doing
whatever is necessary to get more of the results when it needs them. But
the behavior is the *same* in the sense that the output that you get is
the same (you will only see differences if you are keeping an eye on how
much memory and how much time your program is using).

Nick

Footnotes:

[fn:1] ... and, no, you *can't express* this as
"the first time it is

for x in 1:
  ...

and the second time it is

for x in 2:
  ...

" as you asked in another email. That's arrant nonsense: x takes
successive values in the list l for every iteration of the for
loop. This is elementary Python (nay, elementary programming, period).
-- 
http://mail.python.org/mailman/listinfo/python-list


I look for a tool like webalizer in python language

2012-01-10 Thread Stéphane Klein

Hi,

I wonder if there are a tool like webalizer in python language. 
(http://en.wikipedia.org/wiki/Webalizer).


I would like to do some patch in webalizer, but I don't want to spend 
too many time to do that in C language. In Python I can do this patch in 
few minute.


Do you know a tool like this in Python ?

Thanks for your help.

Regards,
Stéphane
--
Stéphane Klein 
blog: http://stephane-klein.info
Twitter: http://twitter.com/klein_stephane
pro: http://www.is-webdesign.com

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


Re: C-API: Pass a tuple to a method of a class

2012-01-10 Thread pasparis


Hi StephenThanks for examining and advise a solution. Before testing CPython I wanted to run this very simple think to send a tuple to a method of a python class.I have succeeded in sending a tuple (declared exactly the same way as I do in the code) to a method written in a python filebut as soon as you put the method in a class and try to send a tuple it doesn't work(get a run failed message)I don't send 3 arguments, it's a mistake from me to code that way,it leads to misunderstanding, it's 3 items in one tuple (declared args), 3 is just chosen by sample, it has to be dynamic later to send a series of data in a tuple.I modifed the code and try to do this thing: (again it works when the method doesn't belong to a class and this what is very "strange" for me) and it's still doesn't work  // WE pass a tuple  pTuple = PyTuple_New(10);  if (pTuple == NULL) {    Py_DECREF(pTuple);    cout << "Can't build argument list for method call\n";  }    PyObject  *py_argument;    for (int i = 0 ; i < 10 ; i++ ) { py_argument = PyFloat_FromDouble(5.*(double)i); PyTuple_SetItem(pTuple, i, py_argument);  }    args = Py_BuildValue("(O)", pTuple);  if (args == NULL) {    Py_DECREF(args);    error("Can't build argument list for class instance");  }    // Call our object method with arguments   ret = PyEval_CallObject(method,args);
 Message d'origine 
De : paspa...@noos.fr
À : python-list@python.org
Objet : C-API: Pass a tuple to a method of a class
Date : 10/01/2012 11:57:38 CET

HelloI am trying to pass a tuple to a method of a class from C++ to Python. I get a Run Failed from the execution. thanks for help/suggestionsthe code is the following:Python Code:class cVector:  def __init__(self,msg):    self.value = msg  def ComputeNorm(self,vecData):    #don't use vecData for instance    result = 12.    return(result)C++ Code ://instances. farenheit will hold our return value   PyObject *ret, *mymod, *pclass, *method, *args, *object;  float retValue;  Py_Initialize();  //PySys_SetPath("/home/pascal/projPytCpp/proj1");  PySys_SetPath(".");    // Module  mymod = PyImport_ImportModule("mModule8");  if (mymod == NULL){    cout << "Can't Open a module:\n" ;    Py_DECREF(mymod);  }    // Class  pclass = PyObject_GetAttrString(mymod, "cVector");  if (pclass == NULL) {    Py_DECREF(pclass);    cout << "Can't find class\n";  }    // Parameters/Values  args = Py_BuildValue("(f)", 100.0);  if (args == NULL) {    Py_DECREF(args);    cout << "Can't build argument list for class instance\n";  }    // Object with parameter/value  object = PyEval_CallObject(pclass, args);  if (object == NULL) {    Py_DECREF(object);    cout << "Can't create object instance:\n";  }    // Decrement the argument counter as we'll be using this again   Py_DECREF(args);    // Get the object method - note we use the object as the object  // from which we access the attribute by name, not the class   method = PyObject_GetAttrString(object, "ComputeNorm");  if (method == NULL) {    Py_DECREF(method);    cout << "Can't find method\n";  }    // Decrement the counter for our object, since we now just need  // the method reference   Py_DECREF(object);  // Build our argument list - an empty tuple because there aren't  // any arguments     cout << "Prepare the Tuple:\n" ;  // WE pass a tuple  args = PyTuple_New( 3 );  if (args == NULL) {    Py_DECREF(args);    cout << "Can't build argument list for method call\n";  }    PyObject  *py_argument;  // 1st argument   py_argument = PyFloat_FromDouble(5.);  PyTuple_SetItem(args, 0, py_argument);   // 2nd argument   py_argument = PyFloat_FromDouble(10.);  PyTuple_SetItem(args, 1, py_argument);    // 3nd argument   py_argument = PyFloat_FromDouble(15.);  PyTuple_SetItem(args, 2, py_argument);    cout << "Before the Exec:\n" ;  // Call our object method with arguments   //ret = PyEval_CallObject(method,args);  ret = PyObject_CallObject(method,args);  if (ret == NULL) {    Py_DECREF(ret);    cout << "Couldn't call method\n";  }    // Convert the return value back into a C variable and display it   PyArg_Parse(ret, "f", &retValue);  printf("Farenheit: %f\n", retValue);  // Kill the remaining objects we don't need   Py_DECREF(method);  Py_DECREF(ret);  // Close off the interpreter and terminate   Py_Finalize();  


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


Re: replacing __dict__ with an OrderedDict

2012-01-10 Thread Roy Smith
In article ,
 Lie Ryan  wrote:

> On 01/10/2012 12:05 PM, Roy Smith wrote:
> > Somewhat more seriously, let's say you wanted to do test queries against
> > a database with 100 million records in it.  You could rebuild the
> > database from scratch for each test, but doing so might take hours per
> > test.  Sometimes, real life is just*so*  inconvenient.
> 
> All serious database has rollback feature when they're available to 
> quickly revert database state in the setUp/cleanUp phase.

I guess MongoDB is not a serious database?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: your feedback to my first project please

2012-01-10 Thread Jean-Michel Pichavant

patr...@bierans.de wrote:

Thanks for the feedback!

I took the time reading and understanding it and to let it getting into my
bones. And I also lost time on reading more of this freaky and interesting
documentation and was testing a lot of different stuff with my enviroment.

My current code can be seen here if you are interested:

http://pastebin.com/3fz6qm9z  #AverageStack.py
http://pastebin.com/tUSGs3gb  #TestAverageStack.py

Here are my replies to your time consuming and informative replies ;)


  

D'Arcy wrote: [code examples]



Python has some really interesting tricks I have not seen in php.
For example: self._data = [default] * dim  - That's nice. :)
And allowing the getter to also set a value was a nice idea.
I meant: def avg(self, value=None)
Thanks for that! :)

But I will keep some of my underscores for "private" attributes and methods.
And I googled: "dim" was basic. I know too many languages and start mixing
the keywords - shame on me. ;)


  

D'Arcy and Peter wrote: [about writing testcases]



Good Eye: I wrote the tests after coding - I know that this is the wrong way.
I just wanted to start coding and after some time I decided that I shoud have
some test cases. This is no real TDD - true. ;) I'll do that right next time.


  

Peter wrote: You must be doing it [writing test cases] wrong.



After thinking about it: Yupp. You are right. Having written tests to check
"private" attributes really hurts one's pride. ;)


  

Peter wrote: You need "from __future__ import division"



Thanks for pointing me to it. I really would have fallen for it!


  

Peter wrote: assert False, " %s, %s ?" % ("red", "yellow")



Can you do that with a.avg() instead of a string like "red"?


TIA,
Patrick


PS:

  

gene wrote: [plain text emails]



Thanks for pointing me to that. But it was the mistake of my webmailer. I am
well aware of the etiquette of mailing lists. (As you can see my mail was
wordwrapped accordingly.)

But I will not blame you for full quoting my html email... *cough* ;-P  


I hope I can get my webmailer to go for plain text email. The option is set
but does not seam to apply. ?

import unittest
from AverageStack import AverageStack


- Module names should be lowercase (look at unittest). You can read 
http://www.python.org/dev/peps/pep-0008/ for details
- I quite dislike your avg method which does more than averaging, it 
also inserts a value and removes another modifying the object in place. 
It could be very confusing for someone reading your code. Fortunately, 
you have documented it, that makes it acceptable. Why don't you make avg 
only averaging. Surely you can use the add method right before.
- A very important information is mising from your documentation : the 
type of the parameters. Someone using your API must know which type is 
allowed. Replace "value" by "value (int)" for example.
- Another way to improve your documenation : read PEP 257 
http://www.python.org/dev/peps/pep-0257/ and try to follow these rules. 
For instance, don't write """Adds value to the stack" but """Add the 
given value (int) to the stack.""" (I would remove the internal pointer 
reference, since it's internal, the end user do not need to know about it).
- Since you write documentation (good habit :o) )  you may want to look 
at doc generators like epydoc http://epydoc.sourceforge.net/ and start 
familiarizing with any markup language (epydoc, reStructuredText ... 
your pick)


JM


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


Re: C-API: Pass a tuple to a method of a class

2012-01-10 Thread Stefan Behnel
[cleaned up top-posted citation order to make the replies readable]

刘振海, 10.01.2012 14:24:
> 2012/1/10 Stefan Behnel
>> """
>> # in module "gluecode.pyx" (or whatever you want to name it)
>>
>> import mModule8
>>
>> cdef api float compute_norm(float init_value, float x, float y, float z):
>>vec = mModule8.cVector(init_value)
>>return vec.ComputeNorm( (x,y,z) )
>> """

I just noticed that this swallows exceptions. It should have one of the
"except" declarations at the end of the signature to enable proper
exception signalling to the calling C/C++ code.

http://docs.cython.org/src/userguide/language_basics.html#error-return-values


> I have been using Cython for a period of time. But I can not find a
> description for the "api" key word in Cython documents

I admit that searching for "api" isn't really helpful here, but at least
the page on "interfacing with external C code" shouldn't be all that hard
to find in the given context. It contains this section:

http://docs.cython.org/src/userguide/external_C_code.html#using-cython-declarations-from-c

Stefan

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


Re: UnicodeEncodeError in compile

2012-01-10 Thread jmfauth
On 10 jan, 13:28, jmfauth  wrote:

Addendum, Python console ("dos box")

D:\>c:\python32\python.exe
Python 3.2.2 (default, Sep  4 2011, 09:51:08) [MSC v.1500 32 bit
(Intel)] on win
32
Type "help", "copyright", "credits" or "license" for more information.
>>> '\u5de5'.encode('utf-8')
b'\xe5\xb7\xa5'
>>> '\u5de5'.encode('mbcs')
Traceback (most recent call last):
  File "", line 1, in 
UnicodeEncodeError: 'mbcs' codec can't encode characters in position
0--1: inval
id character
>>> ^Z


D:\>c:\python27\python.exe
Python 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit
(Intel)] on win
32
Type "help", "copyright", "credits" or "license" for more information.
>>> u'\u5de5'.encode('utf-8')
'\xe5\xb7\xa5'
>>> u'\u5de5'.encode('mbcs')
'?'
>>> ^Z


D:\>

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


Re: Explanation about for

2012-01-10 Thread Frank Millman

" ??"  wrote in message 
news:afd612b7-2366-40be-badf-13c97655f...@o12g2000vbd.googlegroups.com...
>
> So that means that
>
> for host, hits, agent, date in dataset:
>
> is:
>
> for host, hits, agent, date in  (foo,7,IE6,1/1/11)
>
> and then:
>
> for host, hits, agent, date in  (bar,42,Firefox,2/2/10)
>
> and then:
>
> for host, hits, agent, date in  (baz,4,Chrome,3/3/09)
>
>
> So 'dataset' is one row at each time?
> but we said that 'dataset' represent the whole result set.
> So isnt it wrong iam substituting it with one line per time only?

No. 'for host, hits, agent, date in dataset:' is equivalent to -

for row in dataset:  # iterate over the cursor, return a single row (tuple) 
for each iteration
   host, hits, agent, date = row  # unpack the tuple and assign the elements 
to their own names

For the first iteration, row is the tuple ('foo', 7, 'IE6', '1/1/11')
For the next iteration, row is the tuple ('bar', 42, 'Firefox', '2/2/10')
For the next iteration, row is the tuple ('baz', 4, 'Chrome', '3/3/09')

The original line uses a python technique that combines these two lines into 
one.

HTH

Frank Millman



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


Re: C-API: Pass a tuple to a method of a class

2012-01-10 Thread 刘振海
Hi,
I have been using Cython for a period of time.
But I can not find a description for the "api" key word in Cython documents

cdef api float compute_norm(float init_value, float x, float y, float z):

Can you explain it a little bit? Thanks!

Regards,
Liu Zhenhai

2012/1/10 Stefan Behnel 

> Hi again,
>
> just as a little teaser, to make it clear that I'm not joking, here's your
> code below translated into Cython.
>
> Stefan Behnel, 10.01.2012 13:33:
> > paspa...@noos.fr, 10.01.2012 11:57:
> >> the code is the following:
> > [...]
> >> // Class
> >> pclass = PyObject_GetAttrString(mymod, "cVector");
> >> if (pclass == NULL) {
> >> Py_DECREF(pclass);
> >> cout << "Can't find class\n";
> >> }
> >>
> >> // Parameters/Values
> >> args = Py_BuildValue("(f)", 100.0);
> >> if (args == NULL) {
> >> Py_DECREF(args);
> >> cout << "Can't build argument list for class instance\n";
> >> }
> >>
> >> // Object with parameter/value
> >> object = PyEval_CallObject(pclass, args);
> >> if (object == NULL) {
> >> Py_DECREF(object);
> >> cout << "Can't create object instance:\n";
> >> }
> >>
> >> // Decrement the argument counter as we'll be using this again
> >> Py_DECREF(args);
> >>
> >> // Get the object method - note we use the object as the object
> >> // from which we access the attribute by name, not the class
> >> method = PyObject_GetAttrString(object, "ComputeNorm");
> >> if (method == NULL) {
> >> Py_DECREF(method);
> >> cout << "Can't find method\n";
> >> }
> >>
> >> // Decrement the counter for our object, since we now just need
> >> // the method reference
> >> Py_DECREF(object);
> >>
> >> // Build our argument list - an empty tuple because there aren't
> >> // any arguments
> >>
> >> cout << "Prepare the Tuple:\n" ;
> >> // WE pass a tuple
> >> args = PyTuple_New( 3 );
> >> if (args == NULL) {
> >> Py_DECREF(args);
> >> cout << "Can't build argument list for method call\n";
> >> }
> >>
> >> PyObject *py_argument;
> >> // 1st argument
> >> py_argument = PyFloat_FromDouble(5.);
> >> PyTuple_SetItem(args, 0, py_argument);
> >>
> >> // 2nd argument
> >> py_argument = PyFloat_FromDouble(10.);
> >> PyTuple_SetItem(args, 1, py_argument);
> >>
> >> // 3nd argument
> >> py_argument = PyFloat_FromDouble(15.);
> >> PyTuple_SetItem(args, 2, py_argument);
> >>
> >> cout << "Before the Exec:\n" ;
> >> // Call our object method with arguments
> >> //ret = PyEval_CallObject(method,args);
> >> ret = PyObject_CallObject(method,args);
> >
> > Note that you are calling the method with three arguments here. It
> appears
> > that what you want is *one* argument instead, which happens to be a
> tuple.
> > So you need to wrap it in another tuple for calling. As I said, Cython
> will
> > do that for you.
>
> And here's the Cython code:
>
> """
> # in module "gluecode.pyx" (or whatever you want to name it)
>
> import mModule8
>
> cdef api float compute_norm(float init_value, float x, float y, float z):
>vec = mModule8.cVector(init_value)
>return vec.ComputeNorm( (x,y,z) )
> """
>
> At least, that's what I read from your C code above. I'm assuming here that
> your program is using C or C++, and that you want to embed a CPython
> runtime in it and be able to execute Python code through it. The above
> "compute_norm()" function is exported (as a C function) by the "gluecode"
> module which you can import in your C/C++ code (as you did already).
>
> Note also that the Cython code above is substantially more efficient than
> your implementation, because it uses faster type conversions and interned
> Python names for looking up the class and its method.
>
> Stefan
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python philosophical question - strong vs duck typing

2012-01-10 Thread Lie Ryan

On 01/09/2012 04:35 PM, John Nagle wrote:

A type-inferring compiler has to analyze the whole program at
once, because the type of a function's arguments is determined
by its callers. This is slow. The alternative is to guess
what the type of something is likely to be, compile code at
run time, and be prepared to back out a bad guess. This
requires a very complex system, but that's how PyPy does it.
Performance does not seem to reach Shed Skin levels.


With a smart enough compiler, JIT compiler can actually be faster than 
compile-time optimizations; the reason being that different people might 
use the same code differently. For example, say we have a function that 
takes an array of numbers which can be integer or float or a mix of 
integers and floats. A compile-time optimizer cannot optimize this 
function safely; but a run-time optimizer might notice that a certain 
user only ever use the function with an array of integers and generate 
an optimized code for that particular case.


Profile-guided optimizations (PGO) can do something similar, but then it 
means a single program will have to have twenty different binaries for 
twenty different use cases; or a very large binary that contains code 
optimized for every possible thing.


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


Re: C-API: Pass a tuple to a method of a class

2012-01-10 Thread Stefan Behnel
Hi again,

just as a little teaser, to make it clear that I'm not joking, here's your
code below translated into Cython.

Stefan Behnel, 10.01.2012 13:33:
> paspa...@noos.fr, 10.01.2012 11:57:
>> the code is the following:
> [...]
>> // Class
>> pclass = PyObject_GetAttrString(mymod, "cVector");
>> if (pclass == NULL) {
>> Py_DECREF(pclass);
>> cout << "Can't find class\n";
>> }
>>
>> // Parameters/Values
>> args = Py_BuildValue("(f)", 100.0);
>> if (args == NULL) {
>> Py_DECREF(args);
>> cout << "Can't build argument list for class instance\n";
>> }
>>
>> // Object with parameter/value
>> object = PyEval_CallObject(pclass, args);
>> if (object == NULL) {
>> Py_DECREF(object);
>> cout << "Can't create object instance:\n";
>> }
>>
>> // Decrement the argument counter as we'll be using this again
>> Py_DECREF(args);
>>
>> // Get the object method - note we use the object as the object
>> // from which we access the attribute by name, not the class
>> method = PyObject_GetAttrString(object, "ComputeNorm");
>> if (method == NULL) {
>> Py_DECREF(method);
>> cout << "Can't find method\n";
>> }
>>
>> // Decrement the counter for our object, since we now just need
>> // the method reference
>> Py_DECREF(object);
>>
>> // Build our argument list - an empty tuple because there aren't
>> // any arguments
>>
>> cout << "Prepare the Tuple:\n" ;
>> // WE pass a tuple
>> args = PyTuple_New( 3 );
>> if (args == NULL) {
>> Py_DECREF(args);
>> cout << "Can't build argument list for method call\n";
>> }
>>
>> PyObject *py_argument;
>> // 1st argument
>> py_argument = PyFloat_FromDouble(5.);
>> PyTuple_SetItem(args, 0, py_argument);
>>
>> // 2nd argument
>> py_argument = PyFloat_FromDouble(10.);
>> PyTuple_SetItem(args, 1, py_argument);
>>
>> // 3nd argument
>> py_argument = PyFloat_FromDouble(15.);
>> PyTuple_SetItem(args, 2, py_argument);
>>
>> cout << "Before the Exec:\n" ;
>> // Call our object method with arguments
>> //ret = PyEval_CallObject(method,args);
>> ret = PyObject_CallObject(method,args);
> 
> Note that you are calling the method with three arguments here. It appears
> that what you want is *one* argument instead, which happens to be a tuple.
> So you need to wrap it in another tuple for calling. As I said, Cython will
> do that for you.

And here's the Cython code:

"""
# in module "gluecode.pyx" (or whatever you want to name it)

import mModule8

cdef api float compute_norm(float init_value, float x, float y, float z):
vec = mModule8.cVector(init_value)
return vec.ComputeNorm( (x,y,z) )
"""

At least, that's what I read from your C code above. I'm assuming here that
your program is using C or C++, and that you want to embed a CPython
runtime in it and be able to execute Python code through it. The above
"compute_norm()" function is exported (as a C function) by the "gluecode"
module which you can import in your C/C++ code (as you did already).

Note also that the Cython code above is substantially more efficient than
your implementation, because it uses faster type conversions and interned
Python names for looking up the class and its method.

Stefan

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


Re: Explanation about for

2012-01-10 Thread Jussi Piitulainen
Νικόλαος Κούρας writes:

> So that means that
> 
> for host, hits, agent, date in dataset:
> 
> is:
> 
> for host, hits, agent, date in  (foo,7,IE6,1/1/11)
> 
> and then:
> 
> for host, hits, agent, date in  (bar,42,Firefox,2/2/10)
> 
> and then:
> 
> for host, hits, agent, date in  (baz,4,Chrome,3/3/09)
> 
> 
> So 'dataset' is one row at each time?
> but we said that 'dataset' represent the whole result set.
> So isnt it wrong iam substituting it with one line per time only?

Forget the database and meditate on simpler examples like this:

>>> xy = zip("abc", "123")
>>> for x, y in xy: print(x, y)
... 
('a', '1')
('b', '2')
('c', '3')
>>> for x, y in xy: print(xy)
... 
[('a', '1'), ('b', '2'), ('c', '3')]
[('a', '1'), ('b', '2'), ('c', '3')]
[('a', '1'), ('b', '2'), ('c', '3')]
>>> 

Or, for that matter, even simpler examples like this:

>>> bag = "abc"
>>> for x in bag: print(x)
... 
a
b
c
>>> for x in bag: print(bag)
... 
abc
abc
abc
>>> 

And this:

>>> a, b, c = bag
>>> a, b, c
('a', 'b', 'c')
>>> bag
'abc'
>>> 

Go to the Python command line and try things out.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: replacing __dict__ with an OrderedDict

2012-01-10 Thread Lie Ryan

On 01/10/2012 03:59 AM, Ulrich Eckhardt wrote:



There is another dependency and that I'd call a logical dependency. This
occurs when e.g. test X tests for an API presence and test Y tests the
API behaviour. In other words, Y has no chance to succeed if X already
failed. Unfortunately, there is no way to express this relation, there
is no "@unittest.depends(test_X)" to decorate test_Y with (Not yet!).


The skipIf decorator exists precisely for this purpose. Generally, 
testing availability of resources (like existence of an API) should be 
done outside of the testing code. In other words, test_X should never be 
a test in the first place, it should be part of the setting up of the 
tests; the tests themselves should be completely independent of each other.


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


Re: C-API: Pass a tuple to a method of a class

2012-01-10 Thread Stefan Behnel
Hi!

paspa...@noos.fr, 10.01.2012 11:57:
> I am trying to pass a tuple to a method of a class from C++ to Python. I get 
> a 
> Run Failed from the execution.
> thanks for help/suggestions

My *suggestion* is to use Cython instead of writing the glue code yourself.
There are several bugs and lots of inefficient data conversions in your
code below, which are clearly due to your lack of experience with CPython's
C-API. The good thing is that you don't need that experience if you use
Cython, because it will take care of all those details for you.


> the code is the following:
> 
> Python Code:
> 
> class cVector:
> def __init__(self,msg):
> self.value = msg
> def ComputeNorm(self,vecData):
> #don't use vecData for instance
> result = 12.
> return(result)

Please take care to properly format your code when you post it here. The
best way to do that is to post plain text messages.


> C++ Code :
> //instances. farenheit will hold our return value
> PyObject *ret, *mymod, *pclass, *method, *args, *object;
> float retValue;
> 
> Py_Initialize();
> //PySys_SetPath("/home/pascal/projPytCpp/proj1");
> PySys_SetPath(".");
> 
> // Module
> mymod = PyImport_ImportModule("mModule8");
> if (mymod == NULL){
> cout << "Can't Open a module:\n" ;
> Py_DECREF(mymod);

Note that Py_DECREF(null) will crash.

It looks like you are embedding Python here. Basically, the code up to this
point is all you really have to do. You can leave the rest to Cython,
especially the class instantiation and usage parts look much nicer in
Python syntax than in C-API code.


> // Class
> pclass = PyObject_GetAttrString(mymod, "cVector");
> if (pclass == NULL) {
> Py_DECREF(pclass);
> cout << "Can't find class\n";
> }
> 
> // Parameters/Values
> args = Py_BuildValue("(f)", 100.0);
> if (args == NULL) {
> Py_DECREF(args);
> cout << "Can't build argument list for class instance\n";
> }
> 
> // Object with parameter/value
> object = PyEval_CallObject(pclass, args);
> if (object == NULL) {
> Py_DECREF(object);
> cout << "Can't create object instance:\n";
> }
> 
> // Decrement the argument counter as we'll be using this again
> Py_DECREF(args);
> 
> // Get the object method - note we use the object as the object
> // from which we access the attribute by name, not the class
> method = PyObject_GetAttrString(object, "ComputeNorm");
> if (method == NULL) {
> Py_DECREF(method);
> cout << "Can't find method\n";
> }
> 
> // Decrement the counter for our object, since we now just need
> // the method reference
> Py_DECREF(object);
> 
> // Build our argument list - an empty tuple because there aren't
> // any arguments
> 
> cout << "Prepare the Tuple:\n" ;
> // WE pass a tuple
> args = PyTuple_New( 3 );
> if (args == NULL) {
> Py_DECREF(args);
> cout << "Can't build argument list for method call\n";
> }
> 
> PyObject *py_argument;
> // 1st argument
> py_argument = PyFloat_FromDouble(5.);
> PyTuple_SetItem(args, 0, py_argument);
> 
> // 2nd argument
> py_argument = PyFloat_FromDouble(10.);
> PyTuple_SetItem(args, 1, py_argument);
> 
> // 3nd argument
> py_argument = PyFloat_FromDouble(15.);
> PyTuple_SetItem(args, 2, py_argument);
> 
> cout << "Before the Exec:\n" ;
> // Call our object method with arguments
> //ret = PyEval_CallObject(method,args);
> ret = PyObject_CallObject(method,args);

Note that you are calling the method with three arguments here. It appears
that what you want is *one* argument instead, which happens to be a tuple.
So you need to wrap it in another tuple for calling. As I said, Cython will
do that for you.


> // Convert the return value back into a C variable and display it
> PyArg_Parse(ret, "f", &retValue);
> printf("Farenheit: %f\n", retValue);
> // Kill the remaining objects we don't need
> Py_DECREF(method);
> Py_DECREF(ret);
> // Close off the interpreter and terminate
> Py_Finalize();

That part is ok again.

Stefan

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


Re: replacing __dict__ with an OrderedDict

2012-01-10 Thread Lie Ryan

On 01/10/2012 12:16 AM, Ulrich Eckhardt wrote:

Am 09.01.2012 13:10, schrieb Lie Ryan:

I was just suggesting that what the OP thinks he wants is quite
likely not what he actually wants.


Rest assured that the OP has a rather good idea of what he wants and
why, the latter being something you don't know, because he never
bothered to explain it and you never asked. Please don't think he's an
idiot just because he wants something that doesn't make sense to you.


The OP explained the "why" clearly in his first post, he wanted to see 
his test results ordered in a certain way to make debugging easier, to 
quote the OP:


"""
... I just want to take the first test that fails and analyse that 
instead of guessing the point to start debugging from the N failed tests.

"""

and then he goes on concluding that he need to reorder the tests itself 
and to replace __dict__ with OrderedDict. While it is possible to 
replace __dict__ with OrderedDict and it is possible to reorder the 
test, those are not his original problem, and the optimal solution to 
his original problem differs from the optimal solution to what he think 
he will need.


I had said this before and I'm saying it again: the problem is a test 
result displaying issue, not testing order issue.


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


Re: UnicodeEncodeError in compile

2012-01-10 Thread jmfauth
On 10 jan, 11:53, 8 Dihedral  wrote:
> Terry Reedy於 2012年1月10日星期二UTC+8下午4時08分40秒寫道:
>
>
> > I get the same error running 3.2.2 under IDLE but not when pasting into
> > Command Prompt. However, Command Prompt may be cheating by replacing the
> > Chinese chars with '??' upon pasting, so that Python never gets them --
> > whereas they appear just fine in IDLE.
>
> > --


Tested with *my* Windows GUI interactive intepreters.

It seems to me there is a problem with the mbcs codec.

>>> hex(ord('工'))
'0x5de5'
>>> '\u5de5'
'工'
>>> '\u5de5'.encode('mbcs')
Traceback (most recent call last):
  File "", line 1, in 
UnicodeEncodeError: 'mbcs' codec can't encode characters in position
0--1: invalid character
>>> '\u5de5'.encode('utf-8')
b'\xe5\xb7\xa5'
>>> '\u5de5'.encode('utf-32-be')
b'\x00\x00]\xe5'
>>> sys.version
'3.2.2 (default, Sep  4 2011, 09:51:08) [MSC v.1500 32 bit (Intel)]'
>>> '\u5de5'.encode('mbcs', 'replace')
b'?'

--

>>> u'\u5de5'.encode('mbcs', 'replace')
'?'
>>> repr(u'\u5de5'.encode('utf-8'))
"'\\xe5\\xb7\\xa5'"
>>> repr(u'\u5de5'.encode('utf-32-be'))
"'\\x00\\x00]\\xe5'"
>>> sys.version
'2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)]'


jmf


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


Re: replacing __dict__ with an OrderedDict

2012-01-10 Thread Lie Ryan

On 01/10/2012 12:05 PM, Roy Smith wrote:

Somewhat more seriously, let's say you wanted to do test queries against
a database with 100 million records in it.  You could rebuild the
database from scratch for each test, but doing so might take hours per
test.  Sometimes, real life is just*so*  inconvenient.


All serious database has rollback feature when they're available to 
quickly revert database state in the setUp/cleanUp phase.


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


Re: Explanation about for

2012-01-10 Thread Νικόλαος Κούρας
On 10 Ιαν, 12:57, Thomas Rachel  wrote:
> Am 10.01.2012 10:02 schrieb Νικόλαος Κούρας:
>
> > ---
> > | HOST    | HITS    | AGENT     | DATE |
> > ---
> > | foo     | 7       | IE6       | 1/1/11 |
> > ---
> > | bar     | 42      | Firefox   | 2/2/10 |
> > ---
> > | baz     | 4       | Chrome    | 3/3/09 |
> > ---
>
> > In this line:
> > for host, hits, agent, date in dataset:
>
> > 'dataset' is one of the rows of the mysql result or the whole mysql
> > result set like the table above?
>
> dataset is a cursor, representing the whole result set.
>
> Iterating over it produces one row at each iteration step:
>
> for row in dataset:
>      ...
>
> As each row consists of 4 fields, one iteration result is a tuple of 4
> elements.
>
> In this case,
>
> for host, hits, agent, date in dataset:

So that means that

for host, hits, agent, date in dataset:

is:

for host, hits, agent, date in  (foo,7,IE6,1/1/11)

and then:

for host, hits, agent, date in  (bar,42,Firefox,2/2/10)

and then:

for host, hits, agent, date in  (baz,4,Chrome,3/3/09)


So 'dataset' is one row at each time?
but we said that 'dataset' represent the whole result set.
So isnt it wrong iam substituting it with one line per time only?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Explanation about for

2012-01-10 Thread Νικόλαος Κούρας
On 10 Ιαν, 12:57, Thomas Rachel  wrote:
> Am 10.01.2012 10:02 schrieb Νικόλαος Κούρας:
>
> > ---
> > | HOST    | HITS    | AGENT     | DATE |
> > ---
> > | foo     | 7       | IE6       | 1/1/11 |
> > ---
> > | bar     | 42      | Firefox   | 2/2/10 |
> > ---
> > | baz     | 4       | Chrome    | 3/3/09 |
> > ---
>
> > In this line:
> > for host, hits, agent, date in dataset:
>
> > 'dataset' is one of the rows of the mysql result or the whole mysql
> > result set like the table above?
>
> dataset is a cursor, representing the whole result set.
>
> Iterating over it produces one row at each iteration step:
>
> for row in dataset:
>      ...
>
> As each row consists of 4 fields, one iteration result is a tuple of 4
> elements.
>
> In this case,
>
> for host, hits, agent, date in dataset:

So that means that

for host, hits, agent, date in dataset:

is:

for host, hits, agent, date in  (foo,7,IE6,1/1/11)

and then:

for host, hits, agent, date in  (bar,42,Firefox,2/2/10)

and then:

for host, hits, agent, date in  (baz,4,Chrome,3/3/09)


So 'dataset' is one row at each time?
but we said that 'dataset' represent the whole result set.
So isnt it wrong iam substituting it with one line per time only?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Explanation about for

2012-01-10 Thread Thomas Rachel

Am 10.01.2012 10:02 schrieb Νικόλαος Κούρας:

---
| HOST| HITS| AGENT | DATE |
---
| foo | 7   | IE6   | 1/1/11 |
---
| bar | 42  | Firefox   | 2/2/10 |
---
| baz | 4   | Chrome| 3/3/09 |
---

In this line:
for host, hits, agent, date in dataset:

'dataset' is one of the rows of the mysql result or the whole mysql
result set like the table above?


dataset is a cursor, representing the whole result set.

Iterating over it produces one row at each iteration step:

for row in dataset:
...

As each row consists of 4 fields, one iteration result is a tuple of 4 
elements.


In this case,

for host, hits, agent, date in dataset:

is shorthand for

for anyunusedvariablename in dataset: # take complete row
host, hits, agent, date = anyunusedvariablename # tuple unpacking
del anyunusedvariablename # remove traces

exept that the said variable isn't created.


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


Re: Calling a variable inside a function of another class

2012-01-10 Thread Jean-Michel Pichavant

Yigit Turgut wrote:

class test(test1):

def __init__(self, device):
  .
  .
  .
def _something(self, x=1)
 self.dt = data


if __name__ == "__main__":
 test.something.dt ???

I am trying to call a variable located in a function of a class from
main but couldn't succeed.Any ideas?
  


if __name__ == "__main__":
 aTest = test(whateverdevice)
 print aTest.dt

Some advices:

- a common practice in python is to name classes in CamelCase ( read 
http://www.python.org/dev/peps/pep-0008/ )
- if dt is a shortcut for data, it's a bad one.
- default values are for loosers, they should be used only to keep backward 
compatibility (personal opinion, a lot of ppl would disagree)
- "call" is usually reserved for method and function, or any callable object in 
python. What you're trying to do is to reference an object, not calling it.

JM

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


C-API: Pass a tuple to a method of a class

2012-01-10 Thread pasparis


HelloI am trying to pass a tuple to a method of a class from C++ to Python. I get a Run Failed from the execution. thanks for help/suggestionsthe code is the following:Python Code:class cVector:  def __init__(self,msg):    self.value = msg  def ComputeNorm(self,vecData):    #don't use vecData for instance    result = 12.    return(result)C++ Code ://instances. farenheit will hold our return value   PyObject *ret, *mymod, *pclass, *method, *args, *object;  float retValue;  Py_Initialize();  //PySys_SetPath("/home/pascal/projPytCpp/proj1");  PySys_SetPath(".");    // Module  mymod = PyImport_ImportModule("mModule8");  if (mymod == NULL){    cout << "Can't Open a module:\n" ;    Py_DECREF(mymod);  }    // Class  pclass = PyObject_GetAttrString(mymod, "cVector");  if (pclass == NULL) {    Py_DECREF(pclass);    cout << "Can't find class\n";  }    // Parameters/Values  args = Py_BuildValue("(f)", 100.0);  if (args == NULL) {    Py_DECREF(args);    cout << "Can't build argument list for class instance\n";  }    // Object with parameter/value  object = PyEval_CallObject(pclass, args);  if (object == NULL) {    Py_DECREF(object);    cout << "Can't create object instance:\n";  }    // Decrement the argument counter as we'll be using this again   Py_DECREF(args);    // Get the object method - note we use the object as the object  // from which we access the attribute by name, not the class   method = PyObject_GetAttrString(object, "ComputeNorm");  if (method == NULL) {    Py_DECREF(method);    cout << "Can't find method\n";  }    // Decrement the counter for our object, since we now just need  // the method reference   Py_DECREF(object);  // Build our argument list - an empty tuple because there aren't  // any arguments     cout << "Prepare the Tuple:\n" ;  // WE pass a tuple  args = PyTuple_New( 3 );  if (args == NULL) {    Py_DECREF(args);    cout << "Can't build argument list for method call\n";  }    PyObject  *py_argument;  // 1st argument   py_argument = PyFloat_FromDouble(5.);  PyTuple_SetItem(args, 0, py_argument);   // 2nd argument   py_argument = PyFloat_FromDouble(10.);  PyTuple_SetItem(args, 1, py_argument);    // 3nd argument   py_argument = PyFloat_FromDouble(15.);  PyTuple_SetItem(args, 2, py_argument);    cout << "Before the Exec:\n" ;  // Call our object method with arguments   //ret = PyEval_CallObject(method,args);  ret = PyObject_CallObject(method,args);  if (ret == NULL) {    Py_DECREF(ret);    cout << "Couldn't call method\n";  }    // Convert the return value back into a C variable and display it   PyArg_Parse(ret, "f", &retValue);  printf("Farenheit: %f\n", retValue);  // Kill the remaining objects we don't need   Py_DECREF(method);  Py_DECREF(ret);  // Close off the interpreter and terminate   Py_Finalize();  


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


Re: UnicodeEncodeError in compile

2012-01-10 Thread 88888 Dihedral
Terry Reedy於 2012年1月10日星期二UTC+8下午4時08分40秒寫道:
> On 1/9/2012 11:24 PM, pyscr...@gmail.com wrote:
> > Using python 3.2 in Windows 7 I am getting the following:
> >
> >>> compile('pass', r'c:\temp\工具\module1.py', 'exec')
> > UnicodeEncodeError: 'mbcs' codec can't encode characters in position 0--1: 
> > invalid character
> >
> > Can anybody explain why the compile statement tries to convert the unicode 
> > filename using mbcs?  I know that sys.getfilesystemencoding returns 'mbcs' 
> > in Windows, but I thought that this is not used when unicode file names are 
> > provided.
> 
> I get the same error running 3.2.2 under IDLE but not when pasting into 
> Command Prompt. However, Command Prompt may be cheating by replacing the 
> Chinese chars with '??' upon pasting, so that Python never gets them -- 
> whereas they appear just fine in IDLE.
> 
> -- 
> Terry Jan Reedy

Thank you about the trick. 
Use some wildcat pattern to get the name.py compiled to pwc in some 
directory with utf-8 encoded chars. 

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


Re: UnicodeEncodeError in compile

2012-01-10 Thread jmfauth
1) If I copy/paste these CJK chars from Google Groups in two of my
interactive
interpreters (no "dos/cmd console"), I have no problem.

>>> import unicodedata as ud
>>> ud.name('工')
'CJK UNIFIED IDEOGRAPH-5DE5'
>>> ud.name('具')
'CJK UNIFIED IDEOGRAPH-5177'
>>> hex(ord(('工')))
'0x5de5'
>>> hex(ord('具'))
'0x5177'
>>>

2) It semms the mbcs codec has some difficulties with
these chars.

>>> '\u5de5'.encode('mbcs')
Traceback (most recent call last):
  File "", line 1, in 
UnicodeEncodeError: 'mbcs' codec can't encode characters in position
0--1: invalid character
>>> '\u5de5'.encode('utf-8')
b'\xe5\xb7\xa5'
>>> '\u5de5'.encode('utf-32-be')
b'\x00\x00]\xe5'

3) On the usage of mbcs in files IO interaction --> core devs.

My conclusion.
The bottle neck is on the mbcs side.

jmf

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


Re: Explanation about for

2012-01-10 Thread Νικόλαος Κούρας
On 10 Ιαν, 03:11, Ian Kelly  wrote:
> 2012/1/9 Íéêüëáïò Êïýñáò :
>
> > if the MySQL query was:
>
> > cursor.execute( '''SELECT host, hits, agent, date FROM visitors WHERE pin =
> > %s ORDER BY date DESC''', pin )
>
> > can you help me imagine how the mysql database cursor that holds the query
> > results would look like? I must somehow visualize it in order to understand
> > it!
>
> You can think of it as a pointer, traversing over one row of the
> result set at a time.  Hopefully this will come out legibly:
>
> ---
> | HOST | HITS | AGENT | DATE |
> ---            -
> | foo     | 7       | IE6       | 1/1/11 |   <   | cursor |
> ---            -
> | bar     | 42     | Firefox  | 2/2/10 |
> ---
> | baz    | 4       | Chrome | 3/3/09 |
> 

Database cursor is the pointer that iterates over the result set one
row at a time?
I though that it was the name we give to the whole mysql result set
returned my cursor.execute.

>
>
> > Also what happend if the query was:
> > cursor.execute( '''SELECT host FROM visitors") ?
>
> > the result would have to be something likelike?
>
> > -
> > |somehost1|
> > -
> > |somehost2|
> > -
> > |somehost3|
> > -
> > .
> > .
> > |somehost n|
> > -
>
> > So what values host, hits, agent, date would have in 'for host, hits, agent,
> > date in
> >  dataset' ? Every row has one string how can that be split in 4?
>
> Why don't you try it and see what happens?  But to spare you the
> suspense, you would get:
>
> ValueError: need more than 1 value to unpack
>
> Because you can't unpack a 1-length tuple into four variables.  The
> code assumes that the query is selecting exactly 4 columns.


---
| HOST| HITS| AGENT | DATE |
---
| foo | 7   | IE6   | 1/1/11 |
---
| bar | 42  | Firefox   | 2/2/10 |
---
| baz | 4   | Chrome| 3/3/09 |
---

In this line:
for host, hits, agent, date in dataset:

'dataset' is one of the rows of the mysql result or the whole mysql
result set like the table above?

I still have trouble understanding this line :(
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Getting involved

2012-01-10 Thread moijes12
On Jan 7, 4:13 pm, Chris Angelico  wrote:
> On Sat, Jan 7, 2012 at 9:59 PM, Sophie Sperner  
> wrote:
> > Could you please list me 2 or 3 projects in Python and/or Java which
> > are currently active (vivid) and useful?
>
> Easiest way to find a project to join would be to go to SourceForge,
> Google Code, GitHub, BitBucket, or any other large hosting facility,
> and browse the project list. Soon as you find one that makes you go
> "That is SO COOL!", start reading their bugtracker. There's always
> something to play with!
>
> ChrisA

Try out at TwistedMatrix. You can start by fixing some easy tickets.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: UnicodeEncodeError in compile

2012-01-10 Thread Terry Reedy

On 1/9/2012 11:24 PM, pyscrip...@gmail.com wrote:

Using python 3.2 in Windows 7 I am getting the following:


compile('pass', r'c:\temp\工具\module1.py', 'exec')

UnicodeEncodeError: 'mbcs' codec can't encode characters in position 0--1: 
invalid character

Can anybody explain why the compile statement tries to convert the unicode 
filename using mbcs?  I know that sys.getfilesystemencoding returns 'mbcs' in 
Windows, but I thought that this is not used when unicode file names are 
provided.


I get the same error running 3.2.2 under IDLE but not when pasting into 
Command Prompt. However, Command Prompt may be cheating by replacing the 
Chinese chars with '??' upon pasting, so that Python never gets them -- 
whereas they appear just fine in IDLE.


--
Terry Jan Reedy


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