Re: How does python call OS?

2008-09-14 Thread Steven D'Aprano
On Sat, 13 Sep 2008 23:51:39 -0700, Siegfried Heintze wrote:

> I see the next sub-chapter on wxWindows for python and the previous
> sub-chapter on TK. This is looking a lot like other scripting languages
> (such as perl and groovy and even java). Can python call anything
> directly or does someone have to write a DLL in C/C++ that calls the
> function first? Thanks!


I'm not sure I understand your question correctly, but Python can call 
external programs in a number of ways. I believe the "best" way to do so 
is with the subprocess module.



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


recursion gotcha?

2008-09-14 Thread cnb
this recursive definition of sum thrumped me, is this some sort of
gotcha or am I just braindead today?
and yes i know this is easy a a for x in xs acc += x or just using the
builtin.

def suma(xs, acc=0):
if len(xs) == 0:
acc
else:
suma(xs[1:], acc+xs[0])

it returns none.



def summa(xs):
if not xs:
0
else:
xs[0]+summa(xs[1:])


Traceback (most recent call last):
  File "", line 1, in 
summa([1,2,3,4,5])
  File "", line 5, in summa
xs[0]+summa(xs[1:])
  File "", line 5, in summa
xs[0]+summa(xs[1:])
  File "", line 5, in summa
xs[0]+summa(xs[1:])
  File "", line 5, in summa
xs[0]+summa(xs[1:])
  File "", line 5, in summa
xs[0]+summa(xs[1:])
TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to emit Cyrillic and Chinese via unicode from console mode?

2008-09-14 Thread rs387
On Sep 14, 2:03 am, "Siegfried Heintze" <[EMAIL PROTECTED]> wrote:
> Can someone point me to an example of a little program that emits non-ascii
> Unicode characters (Russian or Chinese perhaps)?

The following doesn't quite work, but I'll post it anyway since it
actually ends up printing the characters. Perhaps someone can point
out what causes the exception at the end?

The important thing is to set the console codepage to 65001, which is
UTF-8. This lets you output utf8-encoded text and see the Unicode
chars displayed.



import sys
import encodings.utf_8
import win32console

sys.stdout = encodings.utf_8.StreamWriter(sys.stdout)

win32console.SetConsoleCP(65001)
win32console.SetConsoleOutputCP(65001)

s = "English: ok\n"
s += u'Russian: \u0420\u0443\u0441\u0441\u043a\u0438\u0439\n'
s += u'Greek: \u03bc\u03b5\u03b3\u03b1\u03bb\u03cd
\u03c4\u03b5\u03c1\u03b7\n'

print s



If redirected to file, all is well, this prints everything properly in
UTF-8. If ran on the console, this also prints everything correctly,
but then throws a mysterious exception:

English: ok
Russian: Русский
Greek: μεγαλύτερη
Traceback (most recent call last):
  File "I:\Temp\utf8console.py", line 18, in 
print s
  File "C:\Progs\Python25\lib\codecs.py", line 304, in write
self.stream.write(data)
IOError: [Errno 0] Error

Any ideas?

Roman

P.S. This really ought to Just Work in this day and age, and do so
without all those 65001/utf8 incantations. Pity that it doesn't. Sigh.
--
http://mail.python.org/mailman/listinfo/python-list

Re: recursion gotcha?

2008-09-14 Thread Marco Bizzarri
On Sun, Sep 14, 2008 at 10:01 AM, cnb <[EMAIL PROTECTED]> wrote:
> this recursive definition of sum thrumped me, is this some sort of
> gotcha or am I just braindead today?
> and yes i know this is easy a a for x in xs acc += x or just using the
> builtin.
>
> def suma(xs, acc=0):
>if len(xs) == 0:
>acc
>else:
>suma(xs[1:], acc+xs[0])

You're just missing the "return" statements?

def suma(xs, acc=0):
   if len(xs) == 0:
  return acc
   else:
  return suma(xs[1:], acc+xs[0])


Regards
Marco
-- 
Marco Bizzarri
http://notenotturne.blogspot.com/
http://iliveinpisa.blogspot.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: recursion gotcha?

2008-09-14 Thread rs387
On Sep 14, 9:01 am, cnb <[EMAIL PROTECTED]> wrote:
> def suma(xs, acc=0):
>         if len(xs) == 0:
>                 acc
>         else:
>                 suma(xs[1:], acc+xs[0])
>
> it returns none.

Yep, that's because there is no "return" statement anywhere. Python
doesn't return expressions "by default", like functional languages do,
so where you say "suma(xs[1:], acc+xs[0])" this just calls itself and
returns nothing.

Try this:

def suma(xs, acc=0):
if len(xs) == 0:
return acc
else:
return suma(xs[1:], acc+xs[0])

print suma([1, 2, 3, 4, 5])

(prints 15)

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


Re: recursion gotcha?

2008-09-14 Thread Marco Bizzarri
On Sun, Sep 14, 2008 at 10:08 AM, Marco Bizzarri
<[EMAIL PROTECTED]> wrote:
> On Sun, Sep 14, 2008 at 10:01 AM, cnb <[EMAIL PROTECTED]> wrote:
>> this recursive definition of sum thrumped me, is this some sort of
>> gotcha or am I just braindead today?
>> and yes i know this is easy a a for x in xs acc += x or just using the
>> builtin.
>>
>> def suma(xs, acc=0):
>>if len(xs) == 0:
>>acc
>>else:
>>suma(xs[1:], acc+xs[0])
>
> You're just missing the "return" statements?
>
> def suma(xs, acc=0):
>   if len(xs) == 0:
>  return acc
>   else:
>  return suma(xs[1:], acc+xs[0])
>
>

Besides: you can avoid the "acc" parameter:

def suma(xs):
if len(xs) == 0:
return 0
else:
return xs[0] + suma(xs[1:])

Regards
Marco


-- 
Marco Bizzarri
http://notenotturne.blogspot.com/
http://iliveinpisa.blogspot.com/
--
http://mail.python.org/mailman/listinfo/python-list


noob: subprocess clarification

2008-09-14 Thread moogyd
Hi,

I generally use csh scripts for generally scripting (controlling
simulations). Basically the script processing options, generates the
command line, executes it and then processes the results.

I would usually use the -f option on the shebang line to ensure that
the environment from the current shell is used.

i.e. #!/bin/csh -f

How do I acheive this in python?

I have been looking at the

import subprocess as sub
p = sub.Popen(['echo $PATH'],shell=True).wait()

This *seems* to do what I want (in that the path looks correct), but I
don't really understand the documentation.

Can somebody please clarify what the shell=True does, and whether I am
using it correctly.

Thanks,

Steven



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


Re: recursion gotcha?

2008-09-14 Thread Arnaud Delobelle
On Sep 14, 9:44 am, "Marco Bizzarri" <[EMAIL PROTECTED]> wrote:
> On Sun, Sep 14, 2008 at 10:08 AM, Marco Bizzarri
>
>
>
> <[EMAIL PROTECTED]> wrote:
> > On Sun, Sep 14, 2008 at 10:01 AM, cnb <[EMAIL PROTECTED]> wrote:
> >> this recursive definition of sum thrumped me, is this some sort of
> >> gotcha or am I just braindead today?
> >> and yes i know this is easy a a for x in xs acc += x or just using the
> >> builtin.
>
> >> def suma(xs, acc=0):
> >>        if len(xs) == 0:
> >>                acc
> >>        else:
> >>                suma(xs[1:], acc+xs[0])
>
> > You're just missing the "return" statements?
>
> > def suma(xs, acc=0):
> >       if len(xs) == 0:
> >              return acc
> >       else:
> >              return suma(xs[1:], acc+xs[0])
>
> Besides: you can avoid the "acc" parameter:
>
> def suma(xs):
>     if len(xs) == 0:
>         return 0
>     else:
>         return xs[0] + suma(xs[1:])
>

I think the OP tried to make it tail-recursive, which of course has no
benefit in Python.  In fact it looks like a Scheme implementation of
sum translated literally to Python.

In Python this algorithm is expressed naturally as:

def suma(xs):
acc = 0
for x in xs:
acc += x
return acc

--
Arnaud

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


Function getting a reference to its own module

2008-09-14 Thread Steven D'Aprano
I have a function that needs a reference to the module object it is 
defined in. (For the reason why, if you care, see the thread "doctest not 
seeing any of my doc tests" from a week ago.) I know of two ways to deal 
with this problem, both of which feel unsatisfactory to me. Assume the 
name of the module is "Mod", then I can do either of these:

def foo():
import Mod
process(Mod)

Disadvantage: If I change the name of the module, I have to remember to 
change the name of the module reference in foo() twice.


def foo():
modname = foo.__module__
module = __import__(modname)
process(module)

Disadvantage: if I change the name of the function, I have to remember to 
change the reference to itself, but at least both changes are right next 
to each other.

Assume that changing the function name or the module name are both 
equally likely/unlikely.

Which do other people prefer? Which seems "better" to you? Are there any 
other alternatives?



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


Re: recursion gotcha?

2008-09-14 Thread Boris Borcic

cnb wrote:

this recursive definition of sum thrumped me, is this some sort of
gotcha or am I just braindead today?
and yes i know this is easy a a for x in xs acc += x or just using the
builtin.

def suma(xs, acc=0):
if len(xs) == 0:
acc
else:
suma(xs[1:], acc+xs[0])

it returns none.


Without return statement, the only recursive solution is a lambda expr :

>>> suma = lambda xs : xs[0]+suma(xs[1:]) if xs else 0

>>> suma(range(101))
5050

Note that suma(xs[1:]) implies copying the remainder of xs, what in turn makes 
the time grow quadratically with the length of xs. So instead of passing a 
superfluous acc second variable, you could pass an index into the list, eg


def suma(xs,pos=0) :
if pos>=len(xs) :
   return 0
else :
   return xs[pos]+suma(xs,pos+1)

Cheers, BB

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


Re: Function getting a reference to its own module

2008-09-14 Thread Arnaud Delobelle
On Sep 14, 10:29 am, Steven D'Aprano <[EMAIL PROTECTED]
cybersource.com.au> wrote:
> I have a function that needs a reference to the module object it is
> defined in. (For the reason why, if you care, see the thread "doctest not
> seeing any of my doc tests" from a week ago.) I know of two ways to deal
> with this problem, both of which feel unsatisfactory to me. Assume the
> name of the module is "Mod", then I can do either of these:
>
> def foo():
>     import Mod
>     process(Mod)
>
> Disadvantage: If I change the name of the module, I have to remember to
> change the name of the module reference in foo() twice.
>
> def foo():
>     modname = foo.__module__
>     module = __import__(modname)
>     process(module)
>
> Disadvantage: if I change the name of the function, I have to remember to
> change the reference to itself, but at least both changes are right next
> to each other.
>
> Assume that changing the function name or the module name are both
> equally likely/unlikely.
>
> Which do other people prefer? Which seems "better" to you? Are there any
> other alternatives?

What about something like:

sys.modules[__name__] ?

--
Arnaud

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


Re: noob: subprocess clarification

2008-09-14 Thread Chris Rebert
On Sun, Sep 14, 2008 at 2:29 AM,  <[EMAIL PROTECTED]> wrote:
> Hi,
>
> I generally use csh scripts for generally scripting (controlling
> simulations). Basically the script processing options, generates the
> command line, executes it and then processes the results.
>
> I would usually use the -f option on the shebang line to ensure that
> the environment from the current shell is used.
>
> i.e. #!/bin/csh -f

According to my copy of the csh manpage:

−f   The shell ignores˜/.tcshrc, and thus starts faster.

So, if I understand correctly, this really just ensures that the rc
file isn't run again, thus preventing any environment vars from being
re-initialized and clobbered.
Since Python isn't (conventionally) a unix shell, this sort of thing
isn't an issue and using the current shell environment is the default
behavior. You don't need to do anything special.

>
> How do I acheive this in python?
>
> I have been looking at the
>
> import subprocess as sub
> p = sub.Popen(['echo $PATH'],shell=True).wait()
>
> This *seems* to do what I want (in that the path looks correct), but I
> don't really understand the documentation.
>
> Can somebody please clarify what the shell=True does, and whether I am
> using it correctly.

Basically, I think it runs the command string through the shell (i.e.
sh), thus causing shell syntax (e.g. $variables) to be interpreted. In
this particular case, $PATH is interpolated with the value of the PATH
environment variable.

You can also access environment variables using os.environ, for example:

import os
print os.environ['PATH']

Regards,
Chris

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

-- 
Follow the path of the Iguana...
http://rebertia.com
--
http://mail.python.org/mailman/listinfo/python-list

Re: Windows / Tkinter - problem with grid - not able to place widgets at desired places

2008-09-14 Thread Francesco Bochicchio
Il Mon, 18 Aug 2008 12:15:10 +0100, dudeja.rajat ha scritto:


>>Hi,
>>
>>I'm learning Python and Tkinter. I've started programming in Eclipse
>>with PyDev. I'm intending to create a GUI. I'm not able to understand
>>the Grid manager perhaps because there is quite a less documentation
>>available for it on the net.
>>
>>My desired GUI is attached in the mail. Although I've tried writing a
>>class module for this GUI but I'm not able to set all things right in
>>the GUI. The Biggest problem seems to be with the Grid Manager in terms
>>how it divides a window in Rows / columns. etc. I'm not able to place
>>none of the widgets correctly in the GUI.
>>
>>For your convenience, I'm attaching this code also as myModule1.py .
>>Please some one review it and help create me this GUI.
>>

Uhm, I don't think you should use the grid manager to obtain a window 
like that. The grid manager is for equally distributing widgets both 
horizontally and vertically. 
And I'm not sure that you can realize that window look with Tkinter.
You could get close by horizontally packing each widget row in a frame 
and then vertically packing the frames in the window. But the look will be
quite different than your target. If you are not satisfied with that I
suggest you move to other toolkits which have more complex geometry 
managers than .pack and .grid.

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


Re: How to emit Cyrillic and Chinese via unicode from console mode?

2008-09-14 Thread Gertjan Klein
rs387 wrote:

>sys.stdout = encodings.utf_8.StreamWriter(sys.stdout)
>
>win32console.SetConsoleCP(65001)
>win32console.SetConsoleOutputCP(65001)

[...]

>If redirected to file, all is well, this prints everything properly in
>UTF-8. If ran on the console, this also prints everything correctly,
>but then throws a mysterious exception:

Interesting. On my system (Windows XP) the console codepage does not
change, and hence the characters don't print properly (I get some of the
CP437 line drawing characters, for example). I have never been able to
convince windows to assume/support UTF-8 encoding in the console,
programatically or otherwise. :(

Gertjan.

-- 
Gertjan Klein <[EMAIL PROTECTED]>
--
http://mail.python.org/mailman/listinfo/python-list


Why some blog entries at MSN Space support rss feed while others don't?

2008-09-14 Thread liuyuprc
Not sure if this is the place this question should even be raised, but
I am deeply troubled by this problem for days. I am now desperate.
When i tried to add the blogs at MSN Space of my friends' to google
reader, some of them don't support rss feed, so i cannot add them. You
guys have any idea how to enable RSS at one's blog entry so it can be
subscribed?

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


PyMarshal Commands crash on Windows

2008-09-14 Thread spammaster . 10 . webmaster
Hi!

Can anyone help me with this issue?

int main (int argc, char * const argv[]) {
Py_Initialize();

FILE* fp = fopen("/Users/test/Desktop/123.pyc","wb");
PyCodeObject* op = (PyCodeObject*)Py_CompileString("import sys
\nprint 'hello'","",Py_file_input);
PyMarshal_WriteObjectToFile((PyObject *)op, fp,
Py_MARSHAL_VERSION);

Py_Finalize();

return 0;
}

This Code crashs on Windows, and I can't explain why. I want to
convert a PyCodeObject to a PyObject and save it to the harddisk.
PyMarshal_ReadObjectFromFile(FILE *P) crashs too if I want to read a
byte-compiled object.


Thank your for your help.

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


Re: Why some blog entries at MSN Space support rss feed while others don't?

2008-09-14 Thread Fredrik Lundh

liuyuprc wrote:


Not sure if this is the place this question should even be raised


it isn't.

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


Re: How to emit Cyrillic and Chinese via unicode from console mode?

2008-09-14 Thread rs387
On Sep 14, 11:51 am, Gertjan Klein <[EMAIL PROTECTED]> wrote:
> Interesting. On my system (Windows XP) the console codepage does not
> change, and hence the characters don't print properly (I get some of the
> CP437 line drawing characters, for example). I have never been able to
> convince windows to assume/support UTF-8 encoding in the console,
> programatically or otherwise. :(

I found that a useful test is to create a directory whose name
contains chars from various languages, then run "cmd" and see if "dir"
displays them correctly. This worked fine for me in WinXP, even though
my system locale is Russian. Would be interesting to know if you can
get the console to display international chars this way.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Stuck connection in Python 3.0b2 http.server

2008-09-14 Thread Fredrik Lundh

rs387 wrote:


I've encountered a weird issue when migrating a web server to Python 3
- the browser would wait forever without showing a page, displaying
"Transferring data" in the status bar. I tracked it down to a
reference cycle in my BaseHTTPRequestHandler descendant - one of the
attributes stored a dict of methods. Removing the cycle made the
problem go away.

In Python 2.5.2 the code works fine either way.

Here's a minimal example which runs in both 2.5 and 3.0 - to see stuck
connections run as-is in 3.0 and navigate to http://localhost:8123; to
fix this comment out "self.dummy = self" (alternatively reset
self.dummy = None at the end of the __init__ method).

Am I doing it wrong, or is this a bug?


it's weird enough to deserve an issue over at http://bugs.python.org/, 
at least.


it'd probably be a good idea to test this on 2.6rc as well.



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


Re: testing if another instance of a script is already running

2008-09-14 Thread skip

Aaron> Would it suffice to call 'os.open' with flags= _O_CREAT| _O_EXCL
Aaron> ?  Would that be platform-independent?

I suspect it would be platform-independent but not NFS-safe.  (The other
solutions in lockfile might have NFS problems as well.  In any case,
lockfile provides a bit more functionality as well, including timeouts and
the ability to break locks.

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


Re: How to emit Cyrillic and Chinese via unicode from console mode?

2008-09-14 Thread pataphor
On Sun, 14 Sep 2008 01:02:39 -0700 (PDT)
rs387 <[EMAIL PROTECTED]> wrote:

> On Sep 14, 2:03 am, "Siegfried Heintze" <[EMAIL PROTECTED]> wrote:
> > Can someone point me to an example of a little program that emits
> > non-ascii Unicode characters (Russian or Chinese perhaps)?
> 
> The following doesn't quite work, but I'll post it anyway since it
> actually ends up printing the characters. 

That's more like it! Just answer with whatever one has. Here's another
gem:

from Tkinter import *
from collections import deque

def byn(x,n =5 ):
L = deque(x)
R = []
while L:
R.append(L.popleft())
if len(R) == n:
yield ''.join(R)
R = []
if R:
yield ''.join(R)

root = Tk()
start = int('16A6',16)
end = int('16F0',16)
g = (unichr(i) for i in xrange(start, end+1))
L = byn(g,16)
s = '\n'.join(L)
w = Label(root, text=s,font = ("freemono","80"))
w.pack()

root.mainloop()

P.

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

Re: Windows / Tkinter - problem with grid - not able to place widgets at desired places

2008-09-14 Thread Guilherme Polo
On Sun, Sep 14, 2008 at 7:32 AM, Francesco Bochicchio
<[EMAIL PROTECTED]> wrote:
> Il Mon, 18 Aug 2008 12:15:10 +0100, dudeja.rajat ha scritto:
>
>
>>>Hi,
>>>
>>>I'm learning Python and Tkinter. I've started programming in Eclipse
>>>with PyDev. I'm intending to create a GUI. I'm not able to understand
>>>the Grid manager perhaps because there is quite a less documentation
>>>available for it on the net.
>>>
>>>My desired GUI is attached in the mail. Although I've tried writing a
>>>class module for this GUI but I'm not able to set all things right in
>>>the GUI. The Biggest problem seems to be with the Grid Manager in terms
>>>how it divides a window in Rows / columns. etc. I'm not able to place
>>>none of the widgets correctly in the GUI.
>>>
>>>For your convenience, I'm attaching this code also as myModule1.py .
>>>Please some one review it and help create me this GUI.
>>>
>
> Uhm, I don't think you should use the grid manager to obtain a window
> like that. The grid manager is for equally distributing widgets both
> horizontally and vertically.
> And I'm not sure that you can realize that window look with Tkinter.

Yes you can.

> You could get close by horizontally packing each widget row in a frame
> and then vertically packing the frames in the window. But the look will be
> quite different than your target. If you are not satisfied with that I
> suggest you move to other toolkits which have more complex geometry
> managers than .pack and .grid.

Uhm.. I'm sure it is more a question of learning how to use them properly.
The following code should be very close to the original request,
depending on the tk version some minor modifications may be needed.

from Tkinter import Tk, Button, Checkbutton, Label, Entry, Frame

class App:
def __init__(self, master):
column0_padx = 24
row_pady = 36

#Label 1
lbl_testcase_exec = Label(master, text="Test case execution",
  wraplength=100, anchor='w', justify='left')
lbl_results_cmp = Label(master, text="Results comparison",
wraplength=100, justify='left')
lbl_tolerance = Label(master, text="Tolerance (5%)", wraplength=100)
testcase_exec = Checkbutton(master)
results_cmp = Checkbutton(master)
tolerance = Entry(master, width=4)
lbl_analysis = Label(master, text="Analysis Library")
analysis_lib = Entry(master, width=30)

lbl_testcase_exec.grid(row=0, column=2, padx=20, pady=12, sticky='w')
lbl_results_cmp.grid(row=0, column=3, pady=12, sticky='w')
lbl_tolerance.grid(row=0, column=4, padx=20, pady=12, sticky='wn')
lbl_analysis.grid(row=1, column=0, sticky='w', padx=column0_padx)
analysis_lib.grid(row=1, column=1, sticky='w')
testcase_exec.grid(row=1, column=2, padx=20, sticky='w')
results_cmp.grid(row=1, column=3, sticky='w')
tolerance.grid(row=1, column=4, padx=20, sticky='w')

#Label 2
lbl_ref_analysis = Label(
master, text="Reference Analysis Libary Version",
wraplength=150, justify='left', pady=row_pady)
ref_analysis_lib = Entry(master, width=30)
lbl_ref_analysis.grid(row=2, column=0, sticky='w', padx=column0_padx)
ref_analysis_lib.grid(row=2, column=1, sticky='w')

# version
lbl_version = Label(master, text="Version under Test")
version = Label(master, text="vA.B.C.D")
lbl_version.grid(row=3, column=0, sticky='w', padx=column0_padx)
version.grid(row=3, column=1, sticky='w')

# test all
lbl_testall = Label(master, text="Test All")
testall = Checkbutton(master)
lbl_testall.grid(row=4, column=0, pady=row_pady, padx=column0_padx,
 sticky='w')
testall.grid(row=4, column=1, sticky='w')

# buttons
bottom_frame = Frame(master)
bottom_frame.grid(row=5, column=1, columnspan=3, sticky='w')

btn_start = Button(bottom_frame, text = "Go", width=7)
btn_start.pack(side='left')
btn_commit = Button(bottom_frame, text="Commit", width=7)
btn_commit.pack(side='left', padx=80)
btn_exit = Button(bottom_frame, text="Exit", width=7)
btn_exit.pack(side='left')


root = Tk()
root.title("Test Automation")
root.minsize(800, 400)
app = App(root)
root.mainloop()

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



-- 
-- Guilherme H. Polo Goncalves
--
http://mail.python.org/mailman/listinfo/python-list


Re: cjson 1.0.5 keyword argument

2008-09-14 Thread Guilherme Polo
On Sun, Sep 14, 2008 at 10:33 AM, Clodoaldo <[EMAIL PROTECTED]> wrote:
> I have installed cjson 1.05 in Fedora 8 (python 2.5.1).
>
> The cjson home page shows a keyword argument "encoding".
> http://python.cx.hu/python-cjson/
>

The latest python-cjson on that page is 1.0.3, which accepts keywords
for the encode function. python-cjson 1.0.5 no longer accepts.

> When i use it i get an error:
>
 cjson.encode('é', encoding='utf8')
> Traceback (most recent call last):
>  File "", line 1, in 
> TypeError: encode() takes no keyword arguments
>
> What am i missing? There is no mail list for cjson.

Try doing cjson.encode('é'.decode('utf-8')) instead.

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



-- 
-- Guilherme H. Polo Goncalves
--
http://mail.python.org/mailman/listinfo/python-list


Re: cjson 1.0.5 keyword argument

2008-09-14 Thread Clodoaldo
On Sep 14, 10:33 am, Clodoaldo <[EMAIL PROTECTED]> wrote:
> I have installed cjson 1.05 in Fedora 8 (python 2.5.1).
>
> The cjson home page shows a keyword argument 
> "encoding".http://python.cx.hu/python-cjson/
>
> When i use it i get an error:
>
> >>> cjson.encode('é', encoding='utf8')
>
> Traceback (most recent call last):
>  File "", line 1, in 
> TypeError: encode() takes no keyword arguments
>
> What am i missing? There is no mail list for cjson.

The problem is the package from Fedora 8. When i install from source
it works.

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


Re: cjson 1.0.5 keyword argument

2008-09-14 Thread Clodoaldo
On Sep 14, 11:45 am, "Guilherme Polo" <[EMAIL PROTECTED]> wrote:
> On Sun, Sep 14, 2008 at 10:33 AM, Clodoaldo <[EMAIL PROTECTED]> wrote:
> > I have installed cjson 1.05 in Fedora 8 (python 2.5.1).
>
> > The cjson home page shows a keyword argument "encoding".
> >http://python.cx.hu/python-cjson/
>
> The latest python-cjson on that page is 1.0.3, which accepts keywords
> for the encode function. python-cjson 1.0.5 no longer accepts.
>
> > When i use it i get an error:
>
>  cjson.encode('é', encoding='utf8')
> > Traceback (most recent call last):
> >  File "", line 1, in 
> > TypeError: encode() takes no keyword arguments
>
> > What am i missing? There is no mail list for cjson.
>
> Try doing cjson.encode('é'.decode('utf-8')) instead.

I had tried decoding first and it worked but my database is utf-8 so i
don't want that extra step.

BTW i have already found the problem as the other post shows.

Thanks, Clodoaldo

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


Is there any nice way to unpack a list of unknown size??

2008-09-14 Thread srinivasan srinivas
I want to do something like below:

1. first, second, third, *rest = foo

 2. for (a,b,c,*rest) in list_of_lists:

Please suggest.

Thanks,
Srini


  Bring your gang together. Do your thing. Find your favourite Yahoo! group 
at http://in.promos.yahoo.com/groups/
--
http://mail.python.org/mailman/listinfo/python-list


Re: How does python call OS?

2008-09-14 Thread Gary Herron

Siegfried Heintze wrote:
I just finished reading a chapter in "Python Programming on Win32" and tried 
out the pythonwin scribble application. I'm not sure if I got it right 
because I could not open a new document. I tried to download the source code 
as referenced in the chm file but it is corrupted. I cut and pasted from my 
softcopy of the book.


I see the next sub-chapter on wxWindows for python and the previous 
sub-chapter on TK. This is looking a lot like other scripting languages 
(such as perl and groovy and even java). Can python call anything directly 
or does someone have to write a DLL in C/C++ that calls the function first?

Thanks!
Siegfried


See the ctypes module for a method of calling any C callable function in 
and DLL.


Gary Herron

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


Re: How does python call OS?

2008-09-14 Thread Grant Edwards
On 2008-09-14, Siegfried Heintze <[EMAIL PROTECTED]> wrote:
> I just finished reading a chapter in "Python Programming on Win32" and tried 
> out the pythonwin scribble application. I'm not sure if I got it right 
> because I could not open a new document. I tried to download the source code 
> as referenced in the chm file but it is corrupted. I cut and pasted from my 
> softcopy of the book.
>
> I see the next sub-chapter on wxWindows for python and the
> previous sub-chapter on TK. This is looking a lot like other
> scripting languages (such as perl and groovy and even java).
> Can python call anything directly

No.  For example, I don't believe there's any way for standard
C-Python to make system calls on Linux.  [Thought ISTR that
somebody has written an extension module that doess that.]

> or does someone have to write a DLL in C/C++ that calls the
> function first?

Can you be more explicit?  What sort of "function" are you
talking about?

As for calling functions in libraries, the library doesn't have
to be in C/C++.  Python can make library calls written in any
language (Fortran, Ada, Pascal, etc.) as long as the language
uses a supportted API.  Python can also execute external
programs.

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


Re: cjson 1.0.5 keyword argument

2008-09-14 Thread Guilherme Polo
On Sun, Sep 14, 2008 at 11:50 AM, Clodoaldo <[EMAIL PROTECTED]> wrote:
> On Sep 14, 11:45 am, "Guilherme Polo" <[EMAIL PROTECTED]> wrote:
>> On Sun, Sep 14, 2008 at 10:33 AM, Clodoaldo <[EMAIL PROTECTED]> wrote:
>> > I have installed cjson 1.05 in Fedora 8 (python 2.5.1).
>>
>> > The cjson home page shows a keyword argument "encoding".
>> >http://python.cx.hu/python-cjson/
>>
>> The latest python-cjson on that page is 1.0.3, which accepts keywords
>> for the encode function. python-cjson 1.0.5 no longer accepts.
>>
>> > When i use it i get an error:
>>
>>  cjson.encode('é', encoding='utf8')
>> > Traceback (most recent call last):
>> >  File "", line 1, in 
>> > TypeError: encode() takes no keyword arguments
>>
>> > What am i missing? There is no mail list for cjson.
>>
>> Try doing cjson.encode('é'.decode('utf-8')) instead.
>
> I had tried decoding first and it worked but my database is utf-8 so i
> don't want that extra step.

I'm not sure about this "extra step" you are talking about. When you
do cjson.encode('é', encoding='utf-8') (supposing you are using
python-cjson 1.0.3) it will actually end up doing the same as
cjson.encode('é'.decode('utf-8'))

>
> BTW i have already found the problem as the other post shows.

Then you didn't install python-cjson 1.0.5, it was probably 1.0.3 like
I said in my other post.

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



-- 
-- Guilherme H. Polo Goncalves
--
http://mail.python.org/mailman/listinfo/python-list


Re: Is there any nice way to unpack a list of unknown size??

2008-09-14 Thread Gary Herron

srinivasan srinivas wrote:

I want to do something like below:

1. first, second, third, *rest = foo
  


Python 3.0 has exactly this feature.  No current Python 2.x version has it.

Gary Herron


 2. for (a,b,c,*rest) in list_of_lists:

Please suggest.

Thanks,
Srini


  Bring your gang together. Do your thing. Find your favourite Yahoo! group 
at http://in.promos.yahoo.com/groups/
--
http://mail.python.org/mailman/listinfo/python-list
  


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


Re: how to exclude specific things when pickling?

2008-09-14 Thread Michael Palmer
On Sep 14, 10:53 am, "inhahe" <[EMAIL PROTECTED]> wrote:
> If I gather correctly pickling an object will pickle its entire hierarchy,
> but what if there are certain types of objects anywhere within the hierarchy
> that I don't want included in the serialization?  What do I do to exclude
> them?   Thanks.

If your class defines a  __getstate__ method, it is expected to return
the pickled state of the entire class. You can for example del those
items from self.__dict__ that you don't want pickled and then return
dumps(self).
--
http://mail.python.org/mailman/listinfo/python-list


Re: PyMarshal Commands crash on Windows

2008-09-14 Thread spammaster . 10 . webmaster
Hi! Please remember, that the script crashs on Line
PyMarshal_WriteObjectToFile. :-(
--
http://mail.python.org/mailman/listinfo/python-list


How to marshal objects to readable files?

2008-09-14 Thread nielinjie

Hi list:
I just want to marshal objects (instance of custom classes)to a human 
*READABEL *file/string, and also, I want unmarshal it back. in xml 
format or any other format.

Any advice? Which lib should I use?
Thanks a lot.


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


Re: Function getting a reference to its own module

2008-09-14 Thread Aaron "Castironpi" Brady
On Sep 14, 4:43 am, Arnaud Delobelle <[EMAIL PROTECTED]> wrote:
> On Sep 14, 10:29 am, Steven D'Aprano <[EMAIL PROTECTED]
>
>
>
> cybersource.com.au> wrote:
> > I have a function that needs a reference to the module object it is
> > defined in. (For the reason why, if you care, see the thread "doctest not
> > seeing any of my doc tests" from a week ago.) I know of two ways to deal
> > with this problem, both of which feel unsatisfactory to me. Assume the
> > name of the module is "Mod", then I can do either of these:
>
> > def foo():
> >     import Mod
> >     process(Mod)
>
> > Disadvantage: If I change the name of the module, I have to remember to
> > change the name of the module reference in foo() twice.
>
> > def foo():
> >     modname = foo.__module__
> >     module = __import__(modname)
> >     process(module)
>
> > Disadvantage: if I change the name of the function, I have to remember to
> > change the reference to itself, but at least both changes are right next
> > to each other.
>
> > Assume that changing the function name or the module name are both
> > equally likely/unlikely.
>
> > Which do other people prefer? Which seems "better" to you? Are there any
> > other alternatives?
>
> What about something like:
>
>     sys.modules[__name__] ?
>
> --
> Arnaud

You're just worried about changing the module's name in the future.
So use a global variable or function that you only have to change
once.

def Mod_mod( ):
   import Mod as Mod #<-- only one change needed
   return Mod

def foo( ):
   process( Mod_mod( ) )
--
http://mail.python.org/mailman/listinfo/python-list


Re: max(), sum(), next()

2008-09-14 Thread Odalrick
[EMAIL PROTECTED] wrote in news:240454f2-14ee-496a-9078-1abbf80a4e64
@m45g2000hsb.googlegroups.com:

> castironpi:
>> For max and min, why can't you just add your argument to the set
>> itself?
> 
> Sometimes that can be done, but in many other situations it's less
> easy, like in the example I have shown in my first post:
> 
> max((fun(x) for x in iterable if predicate(x)))
> 
> There are some ways to add the max there, for example using an
> itertools.chain to chan the default value to the end of the iterable,
> but most of the time I just write a for loop.

Is there any problem with:
max(initial_value, *(fun(x) for x in iterable if predicate(x) ) )

?

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


Re: ctypes: Get full contents of character array

2008-09-14 Thread overdrigzed
On Sep 13, 6:45 am, "Aaron \"Castironpi\" Brady"
<[EMAIL PROTECTED]> wrote:
> On Sep 12, 6:38 pm, [EMAIL PROTECTED] wrote:
>
>
>
>
>
>
>
> > Hello!
>
> > I wanted to get the full contents of a character array stored in a
> > struct, i.e.
> > _fields_ = [...("array", c_char * 12)...]
> > however,ctypesseems to try to return struct.array as a Python string
> > rather than a character array, and stops as soon as it encounters a
> > null within the character array.
>
> > I ended up having to define a dummy struct
> > class dummystruct(Structure):
> >     _fields_ = []
>
> > and declare array as:
> > ("array", dummystruct)
>
> > then use string_at(byref(struct.array), 12).
>
> > Is this really the best way of doing it? Is there no better way to
> > work aroundctypes'guess what you want' behaviour?
>
> > Thanks in advance,
> > Rodrigo
>
> Rodrigo,
>
> If you have the option to change your declaration to c_byte* 12, you
> have more options.  This example prints the null character you wanted.
>
> fromctypesimport *
> import struct
> class S( Structure ):
>     _fields_= [
>         ( 'array', c_byte* 12 )
>     ]
> s= S()
>
> #initialize
> struct.pack_into( '7s', s.array, 0, 'abc\x00def' )
>
> #prototype and call PyString_FromStringAndSize
> prototype= PYFUNCTYPE( py_object, POINTER( c_byte ), c_size_t )
> PyString_FromStringAndSize= prototype( ( "PyString_FromStringAndSize",
> pythonapi ) )
> x= PyString_FromStringAndSize( s.array, 12 )
> print repr( x )
>
> #prototype and call PyString_FromString for contrast
> prototype= PYFUNCTYPE( py_object, POINTER( c_byte ) )
> PyString_FromString= prototype( ( "PyString_FromString", pythonapi ) )
> x= PyString_FromString( s.array )
> print repr( x )
>
> /Output:
>
> 'abc\x00def\x00\x00\x00\x00\x00'
> 'abc'

Great - and thank you for replying so fast! I found that [chr(x) for x
in struct.array] with array as a c_byte * 12 did what I needed.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Is there any nice way to unpack a list of unknown size??

2008-09-14 Thread Arnaud Delobelle
On Sep 14, 4:08 pm, Gary Herron <[EMAIL PROTECTED]> wrote:
> srinivasan srinivas wrote:
> > I want to do something like below:
>
> > 1. first, second, third, *rest = foo
>
> Python 3.0 has exactly this feature.  No current Python 2.x version has it.
>
> Gary Herron
>
> >  2. for (a,b,c,*rest) in list_of_lists:
>
> > Please suggest.
>
> > Thanks,
> > Srini
>
> >       Bring your gang together. Do your thing. Find your favourite Yahoo! 
> > group athttp://in.promos.yahoo.com/groups/
> > --
> >http://mail.python.org/mailman/listinfo/python-list

In python >= 2.4, you can define a function like this:

def truncate(iterable, n=1):
iterator = iter(iterable)
for i in iterator:
if n == 0:
yield iterator
return
yield i
n -= 1

>>> a, b, c, tail = truncate([1,2,3,4,5,6], 3)
>>> a
1
>>> b
2
>>> c
3
>>> tail

>>> list(tail)
[5, 6]

--
Arnaud


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


Re: How to emit Cyrillic and Chinese via unicode from console mode?

2008-09-14 Thread Martin v. Löwis
> Can someone point me to an example of a little program that emits non-ascii 
> Unicode characters (Russian or Chinese perhaps)? The unicode 
> Russian/Cyrillic alphabet starts at 0x410. Is this possible to do in a 
> console mode program? If not, I guess I would want to use pywin32 to create 
> a window and a message pump and display it there. I anticipate using pywin32 
> for some other function calls.

It also depends on your console. On Linux, with an UTF-8
capable-and-enabled console,

py> print u"\u0413"
Г

work just fine.

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

Re: How to marshal objects to readable files?

2008-09-14 Thread Aaron "Castironpi" Brady
On Sep 14, 10:28 am, nielinjie <[EMAIL PROTECTED]> wrote:
> Hi list:
> I just want to marshal objects (instance of custom classes)to a human
> *READABEL *file/string, and also, I want unmarshal it back. in xml
> format or any other format.
> Any advice? Which lib should I use?
> Thanks a lot.

Nielinjie,

There is no generic way; an object can contain a reference to another
object.

You can get started with ob.__dict__ as follows:

>>> class A: pass
...
>>> a= A()
>>> a.b= 0
>>> a.c= 'abc'
>>> a.__dict__
{'c': 'abc', 'b': 0}

But the only way TMK (to my knowledge) to retrieve the contents is
eval, which is very hackish.

The PyYAML package produces the following (continued):

>>> b= A()
>>> b.d= 'efg'
>>> b.e= 1.2
>>> a.d= b
>>> b.parent= a
>>> print yaml.dump( a )
&id001 !!python/object:__main__.A
b: 0
c: abc
d: !!python/object:__main__.A
  d: efg
  e: 1.2
  parent: *id001

>>> print yaml.dump( b )
&id001 !!python/object:__main__.A
d: efg
e: 1.2
parent: !!python/object:__main__.A
  b: 0
  c: abc
  d: *id001
>>> yaml.load( yaml.dump( a ) )
<__main__.A instance at 0x00D098A0>
>>> _.__dict__
{'c': 'abc', 'b': 0, 'd': <__main__.A instance at 0x00D09788>}

It caches IDs to reference circular references, and writes nested
objects in place.  As you can see, you don't need to dump both 'a' and
'b'; 'a' contains 'b' already.  You do need the types of the objects
already living in the same namespace as when you stored them.

If it's not human readable enough for your use, please write an
example of what you want your output to look like.  Abstract is ok.

PyYAML is available at http://pyyaml.org/ .  Download from
http://pyyaml.org/wiki/PyYAML .  I've only skimmed it though.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Function getting a reference to its own module

2008-09-14 Thread Arnaud Delobelle
On Sep 14, 5:10 pm, "Aaron \"Castironpi\" Brady"
<[EMAIL PROTECTED]> wrote:
> On Sep 14, 4:43 am, Arnaud Delobelle <[EMAIL PROTECTED]> wrote:
>
>
>
> > On Sep 14, 10:29 am, Steven D'Aprano <[EMAIL PROTECTED]
>
> > cybersource.com.au> wrote:
> > > I have a function that needs a reference to the module object it is
> > > defined in. (For the reason why, if you care, see the thread "doctest not
> > > seeing any of my doc tests" from a week ago.) I know of two ways to deal
> > > with this problem, both of which feel unsatisfactory to me. Assume the
> > > name of the module is "Mod", then I can do either of these:
>
> > > def foo():
> > >     import Mod
> > >     process(Mod)
>
> > > Disadvantage: If I change the name of the module, I have to remember to
> > > change the name of the module reference in foo() twice.
>
> > > def foo():
> > >     modname = foo.__module__
> > >     module = __import__(modname)
> > >     process(module)
>
> > > Disadvantage: if I change the name of the function, I have to remember to
> > > change the reference to itself, but at least both changes are right next
> > > to each other.
>
> > > Assume that changing the function name or the module name are both
> > > equally likely/unlikely.
>
> > > Which do other people prefer? Which seems "better" to you? Are there any
> > > other alternatives?
>
> > What about something like:
>
> >     sys.modules[__name__] ?
>
> > --
> > Arnaud
>
> You're just worried about changing the module's name in the future.
> So use a global variable or function that you only have to change
> once.
>
> def Mod_mod( ):
>    import Mod as Mod #<-- only one change needed
>    return Mod
>
> def foo( ):
>    process( Mod_mod( ) )

Or:

import ModuleName as this_module

def foo():
process(this_module)

--
Arnaud

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


Re: PyGUI as a standard GUI API for Python?

2008-09-14 Thread David Trem
On 10 sep, 20:36, Fred Pacquier <[EMAIL PROTECTED]> wrote:
> Todd Whiteman <[EMAIL PROTECTED]> said :
>
> > Personally, I believe XULRunner has a lot to offer for Python GUI
> > development, I'm currently finishing up some documentation steps to show
> > off how to use it specifically for Python (I'll post it to this list
> > when it's finished).
>
> That would be really nice !
>
> I've long been curious about the potential of XUL+Python, but put off by
> the lack of leads to follow up, and not having time to do the digging
> myself...
>
> TIA,
> fp

I will also like to see such documentation as soon as possible.
To me, XUL+python really looks like what could be my prefered solution
for multiplatform GUI for my python program.
I'm really impatient and hope a strong and motivated community could
set up arrond such XUL+python project.

All the best,

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


Re: PyGUI as a standard GUI API for Python?

2008-09-14 Thread David Trem
On 10 sep, 20:36, Fred Pacquier <[EMAIL PROTECTED]> wrote:
> Todd Whiteman <[EMAIL PROTECTED]> said :
>
> > Personally, I believe XULRunner has a lot to offer for Python GUI
> > development, I'm currently finishing up some documentation steps to show
> > off how to use it specifically for Python (I'll post it to this list
> > when it's finished).
>
> That would be really nice !
>
> I've long been curious about the potential of XUL+Python, but put off by
> the lack of leads to follow up, and not having time to do the digging
> myself...
>
> TIA,
> fp

I will also like to see such documentation as soon as possible.
To me, XUL+python really looks like what could be my prefered solution
for multiplatform GUI for my python program.
I'm really impatient and hope a strong and motivated community could
set up arrond such XUL+python project.

All the best,

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


Re: Is there any nice way to unpack a list of unknown size??

2008-09-14 Thread Tim Chase

I want to do something like below:
1. first, second, third, *rest = foo


Python 3.0 has exactly this feature.  No current Python 2.x version has it.


I asked something similar[1] on c.l.p a while back and Diez 
Roggisch gave this nice workaround/hack[2]


It's a bit ugly in the implementation (sniffing the stack), but 
elegant in the use, doing exactly what I needed.


It doesn't accommodate the "rest" portion that you reference, but 
allows for arbitrary unpacking into a fixed-length tuple.


-tkc


[1]
http://mail.python.org/pipermail/python-list/2006-May/381386.html

[2]
http://mail.python.org/pipermail/python-list/2006-May/381399.html




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


Re: PyMarshal Commands crash on Windows

2008-09-14 Thread Gabriel Genellina
En Sun, 14 Sep 2008 08:28:01 -0300,  
<[EMAIL PROTECTED]> escribió:



int main (int argc, char * const argv[]) {
Py_Initialize();

FILE* fp = fopen("/Users/test/Desktop/123.pyc","wb");
PyCodeObject* op = (PyCodeObject*)Py_CompileString("import sys
\nprint 'hello'","",Py_file_input);
PyMarshal_WriteObjectToFile((PyObject *)op, fp,
Py_MARSHAL_VERSION);

Py_Finalize();

return 0;
}

This Code crashs on Windows, and I can't explain why. I want to
convert a PyCodeObject to a PyObject and save it to the harddisk.
PyMarshal_ReadObjectFromFile(FILE *P) crashs too if I want to read a
byte-compiled object.


Your code should check every operation for errors. fopen may return NULL,  
Py_CompileString may fail and return NULL, PyMarshal_xxx might fail  
(although it's not documented).


Why "123.pyc"? Do you want to generate a compiled module? Use the  
py_compile standard module instead (or write equivalent C code, or see how  
import.c does that)


--
Gabriel Genellina

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


Re: Is there any nice way to unpack a list of unknown size??

2008-09-14 Thread Fredrik Lundh

srinivasan srinivas wrote:


I want to do something like below:

1. first, second, third, *rest = foo

 2. for (a,b,c,*rest) in list_of_lists:


update to Python 3.0 (as others have pointed out), or just do

first, second, third = foo[:3]
rest = foo[3:]

for item in list_of_lists:
a, b, c = item[:3]
rest = item[3:]
...

and move on to more interesting parts of your program.



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


Re: Abstract class

2008-09-14 Thread Stephen Horne
On Sun, 14 Sep 2008 18:03:23 +0200, Mr.SpOOn <[EMAIL PROTECTED]>
wrote:

>I have to manage many elements of music such as notes, intervals,
>scales, chords and so on. All these elements share properties and
>behavior, so what I want to do is an abstract class "Note" and other
>subclasses, for example "NaturalNote", "FlatNote", "SharpNote" etc.

First off, one approach in Python is to not have a base class at all.
You don't need a base class just to implement a shared interface,
basically. If it walks like a duck and quacks like a duck, you can
usually treat it like a duck, as I think the Ruby crowd say.

Second, it's possible to overdo object orientation, which is probably
Roy Smiths point.

Sometimes, the easiest thing to do is to use a simple integer
representation of your values. With dates, you'd probably use a Julian
day number. That's what spreadsheets usually do, for instance.

With music notes, you'd probably use the note numbers that MIDI uses.

http://www.harmony-central.com/MIDI/Doc/table2.html

You can always extend the range beyond those notes that MIDI supports
if needed.

Doing this means you can switch octaves or transpose using simple
additions or subtractions, for instance. Notes can be decoded using
rounded integer division to find the octave number and the
remainder/modulo % operator (plus maybe a look-up table) to identify
the note.

Use // for integer division (rounded toward -infinity IIRC) or you
risk problems going from Python 2 to Python 3 - the semantics for the
/ division operator are changing. Up until now it would round integer
divisions, but in future it will be considered a "true" non-rounding
division.

This may not work, though, if you aren't working with the
even-tempered scale (if I got that right). There are times when
C-sharp is not the same as D-flat, as MIDI assumes.

You may want to wrap the value in a class, but as far as possible all
your calculations would be based on the integers. Chords might be
represented using either a list or a set - my Python's a little rusty
ATM but IIRC there's a set type based on a dictionary. If you're a
bit-twiddling fan, you might even use a bitvector approach (I don't
think theres a specialised set-of-unsigned-integers bit-vector class
in the library, but I could be wrong). But for most purposes, you'd
probably want the spec. for the chord - "C major" rather than "C, E,
G".

In situations like this, it's sometimes useful to have simple
functions in a module, or else a 'tool' class (which works on the
values, but only encapsulates the tools own state). You can still wrap
the values in a class with a common interface. The point of this is
that it's relatively easy to share functionality when you implement
some value-wrapper classes in several different ways - e.g. note-set
chords vs. specification-based chords, note-number representations vs.
string representations, etc.

That is, in object oriented theory, the object manipulates itself -
but that doesn't always work so well in practice, especially for
functions that deal with two or more objects. As in the real world, a
tool sometimes works better. And if the tool doesn't need any state,
it may as well be a single procedure/function in a module rather than
a class.

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


Re: PyMarshal Commands crash on Windows

2008-09-14 Thread spammaster . 10 . webmaster
Hi!

I shortened the quode. Everything should be all right and nothing is a
NULL Pointer.
What about PyMarshal_ReadObjectFromFile(FILE* p), this crashs too :-/
hm...

the problem is, on mac everything is all right..

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


Re: Python platform.

2008-09-14 Thread primeq
On Sep 11, 8:56 am, "[EMAIL PROTECTED]"
<[EMAIL PROTECTED]> wrote:
> Hello all;
>
> I wonder if there is a platform written in python. The equivalent of
> the Netbeans platformhttp://platform.netbeans.org/in the Python
> world. Do you know such a thing?
>
> Thanks a lot.
>
> Jonathan.

Check out Eric (http://www.die-offenbachs.de/eric/) - it's not as
solid as Netbeans (way lower funding, fewer developers by a large
margin), but it works fine. Better still you have the source at your
fingertips when you're using it - it's written in Python.

Personally I have not had much success with the Windows version, but
the Linux version works out of the box for me.
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to marshal objects to readable files?

2008-09-14 Thread Gabriel Genellina
En Sun, 14 Sep 2008 15:09:52 -0300, Aaron "Castironpi" Brady  
<[EMAIL PROTECTED]> escribió:



On Sep 14, 10:28 am, nielinjie <[EMAIL PROTECTED]> wrote:

Hi list:
I just want to marshal objects (instance of custom classes)to a human
*READABEL *file/string, and also, I want unmarshal it back. in xml
format or any other format.
Any advice? Which lib should I use?


The PyYAML package produces the following (continued):


print yaml.dump( a )

&id001 !!python/object:__main__.A
b: 0
c: abc
d: !!python/object:__main__.A
  d: efg
  e: 1.2
  parent: *id001



JSON is another format, much simpler and probably more suited for human  
reading. But it is somewhat limited on what it can represent. There are a  
few Python implementations, maybe the most used is simplejson, which comes  
bundled with Python 2.6 as the json module.


--
Gabriel Genellina

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


Re: Matching horizontal white space

2008-09-14 Thread Ben Finney
[EMAIL PROTECTED] writes:

> multipleSpaces = re.compile(u'\\h+')
> 
> importantTextString = '\n  \n  \n \t\t  '
> importantTextString = multipleSpaces.sub("M", importantTextString)

Please get into the habit of following the Python coding style guide
http://www.python.org/dev/peps/pep-0008>.

For literal strings that you expect to contain backslashes, it's often
clearer to use the "raw" string syntax:

multiple_spaces = re.compile(ur'\h+')

> I would have expected consecutive spaces and tabs to be replaced by
> M

Why, what leads you to expect that? Your regular expression doesn't
specify spaces or tabs. It specifies "the character 'h', one or more
times".

For "space or tab", specify a character class of space and tab:

>>> multiple_spaces = re.compile(u'[\t ]+')
>>> important_text_string = u'\n  \n  \n \t\t  '
>>> multiple_spaces.sub("M", important_text_string)
u'\nM\nM\nM'


You probably want to read the documentation for the Python 're' module
http://www.python.org/doc/lib/module-re>. This is standard
practice when using any unfamiliar module from the standard library.

-- 
 \   “If you do not trust the source do not use this program.” |
  `\—Microsoft Vista security dialogue |
_o__)  |
Ben Finney
--
http://mail.python.org/mailman/listinfo/python-list

Re: Good programming style

2008-09-14 Thread Grant Edwards
On 2008-09-14, Ben Finney <[EMAIL PROTECTED]> wrote:
> Astley Le Jasper <[EMAIL PROTECTED]> writes:
>
>> Is it best to have it all in one script or split it into per
>> site scripts that can then be called by a manager script? If
>> everything is in one script would you have per site functions
>> to extract the data or generic function that contain vary
>> slightly depending on the site, for example
>> 
>> import firstSiteScript
>> import secondSiteScript
>
> First: each of these things you're importing is a "module" in
> Python. A script is what I prefer, for clarity, to call a
> "program": it's intended to be executed independently as the
> top level of execution.
>
> Second: please do yourself a favour and drop the camelCaseNames.
> Follow PEP 8 http://www.python.org/dev/peps/pep-0008> for style
> and naming in your Python code.

If he finds camelcase more readable and easier to type (as do
I), how is switching to underscores "doing himself a favor"?

I'm generally in favor of using a consistent naming style
throughout a project, but I don't see why the naming style used
in my source code should be subject to somebody else's
arbitrary standard.

When it comes to writing code intended for the standard library
in the main Python distribution, I would certainly defer to the
existing standard as defined in PEP 8.  However, I don't see
any reason that style should be imposed on all everybody else.

-- 
Grant

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


Re: Recognizing the email package

2008-09-14 Thread Marcus.CM

Hi,

Actually i think its the email package that needs to be "redefined", 
using lazyimporter is a bad decision and a lousy one.

Even py2exe could not handle it correctly.

Marcus.

Wingware Support wrote:

Marcus.CM wrote:
Is there any reason why the IDE cant recognize the uppercase 
attribute names of the email package but its the recommended naming .


This is due to the email package using LazyImporter objects to 
dynamically assign names at runtime in ways that the Wing source 
analyzer doesn't understand.  We'll try to fix this in future Wing 
versions.


Thanks,

John




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


Re: Good programming style

2008-09-14 Thread Sean DiZazzo
On Sep 14, 7:10 pm, Grant Edwards <[EMAIL PROTECTED]> wrote:
> On 2008-09-15, Ben Finney <[EMAIL PROTECTED]> wrote:
>
>
>
> > Grant Edwards <[EMAIL PROTECTED]> writes:
> >> On 2008-09-14, Ben Finney <[EMAIL PROTECTED]> wrote:
>
> >>> Second: please do yourself a favour and drop the
> >>> camelCaseNames. Follow PEP 8
> >>> http://www.python.org/dev/peps/pep-0008> for style and
> >>> naming in your Python code.
>
> >> If he finds camelcase more readable and easier to type (as do
> >> I), how is switching to underscores "doing himself a favor"?
>
> >> I'm generally in favor of using a consistent naming style
> >> throughout a project, but I don't see why the naming style
> >> used in my source code should be subject to somebody else's
> >> arbitrary standard.
>
> > Because the code we write rarely stays isolated from other
> > code. There is an existing convention,
>
> There are many existing conventions.
>
> > and it's better to pick a (sufficiently sane) style convention
> > and stick to it than argue about what the convention should
> > be.
>
> I suppose if everybody agreed to pick one, and all the source
> code in the world was changed to meet it, that would "a good
> thing".  It just seems like a goal so unrealistic as to make it
> a bit of an overstatement to tell people they're better off
> following convention X than following convention Y.
>
> When packages as significant as wxPython use naming conventions
> other than PEP 8, I find it hard to make a case that the PEP 8
> naming convention is any better than any other.
>
> >> When it comes to writing code intended for the standard
> >> library in the main Python distribution, I would certainly
> >> defer to the existing standard as defined in PEP 8.  However,
> >> I don't see any reason that style should be imposed on all
> >> everybody else.
>
> > Who's imposing? I'm saying it's a good idea for everyone to do
> > it, and going so far as to say that one is doing oneself a
> > favour by following the convention. I have no more power than
> > you to "impose" convention on anyone.
>
> My apologies -- "impose" was too strong a word to use.
>
> If we were starting from scratch and there was no extant source
> code in the world, then it would make sense to encourage
> everybody to pick one convention. [I still think it would be
> rather quixotic.] But, there are so many projects out there
> with naming conventions other than PEP 8, that I don't see how
> there's an advantage to picking one over another (except for
> the obvious also-rans like "all upper case, no vowels, and a
> maximum length of 6 characters").
>
> I'll agree that sticking with a single convention within a
> project is definitely a good thing.
>
> I'm personally aware of mixed/camel-case projects from 25+
> years ago, so I'm afraid PEP 8 came along a bit too late...
>
> --
> Grant

+1

CamelCase FTW!

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


Re: RELEASED Python 2.6rc1

2008-09-14 Thread Mensanator
On Sep 12, 8:28�pm, Barry Warsaw <[EMAIL PROTECTED]> wrote:
> -BEGIN PGP SIGNED MESSAGE-
> Hash: SHA1
>
> On behalf of the Python development team and the Python community, I �
> am happy to announce the first release candidate for Python 2.6.
>
> This is a release candidate, so while it is not suitable for �
> production environments, we strongly encourage you to download the �
> release and test it on your software. �We expect only critical bugs to �
> be fixed between now and the final 2.6 release, still scheduled for �
> October 1st, 2008. �There is one more release candidate planned for �
> September 17th.
>
> You might notice that unlike earlier releases, we are /not/ releasing �
> Python 3.0rc1 at this time. �It was decided that 3.0 still needs time �
> to resolve open issues and that we would not hold up the 2.6 release �
> for this. �We feel that Python 2.6 is nearly ready for its final �
> release.
>
> If you find things broken or incorrect, please submit bug reports at
>
> � � �http://bugs.python.org
>
> For more information and downloadable distributions, see the Python �
> 2.6 website:
>
> � �http://www.python.org/download/releases/2.6/
>
> (Note that the Windows installers will be uploaded shortly.)

About this Vista note on that page:


Vista Note
Administrators installing Python for all users on Windows Vista
either
need to be logged in as Administrator, or use the runas command, as
in:

runas /user:Administrator "msiexec /i \.msi"


I couldn't get Idle to run until Python was installed this way, so it
appears to be required even for a single user.

And I know that Windows operation is not Python's responsibility,
but couldn't you point out casually that, by default, the
Administrator
account is disabled in Vista. And the above won't work until you find
out how to enable the Administrator (an easy Google search).

>
> See PEP 361 for release schedule details:
>
> � � �http://www.python.org/dev/peps/pep-0361/
>
> Enjoy,
> - -Barry
>
> Barry Warsaw
> [EMAIL PROTECTED]
> Python 2.6/3.0 Release Manager
> (on behalf of the entire python-dev team)
>
> -BEGIN PGP SIGNATURE-
> Version: GnuPG v1.4.9 (Darwin)
>
> iQCVAwUBSMsXV3EjvBPtnXfVAQJFsgP9GxZYQocbDTd0Z/0yEjpHfZ/FTd8y83jV
> 5JouO07lB8XtLawnWB9hF8sUrCuBVog5He3mLVUPDmlyn30qvjYWMG2J6zW0yYMX
> yZdjUyUmta0IMCsXe7YXj369xebh4nWuwG4tDygly4donA7GYPXAlxI48MmyDJxw
> 1v07LM4Dttw=
> =Nd3s
> -END PGP SIGNATURE-

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

Re: Good programming style

2008-09-14 Thread Ben Finney
Adelle Hartley <[EMAIL PROTECTED]> writes:

> I'm looking at porting a library that was written for COM and .Net
> to work as a Python module, and was wondering whether it would be
> better to stick to the library's current naming convention so that
> the API is as similar as possible on each platform, or to adopt a
> "when in Rome..." policy and follow the "most mainstream" naming
> pattern for each platform/language.

I think it's more important for Python library APIs to comply with the
Python coding guidelines (as specified in PEP 8) than to comply with
standards in other languages.

The Python library you're implementing isn't being used in those other
languages, so the conventions of other languages have little
relevance. It's being used in Python code, so it should mesh well with
PEP 8 compliant code — by having the API itself comply with PEP 8.

-- 
 \  “When cryptography is outlawed, bayl bhgynjf jvyy unir |
  `\  cevinpl.” —Anonymous |
_o__)  |
Ben Finney
--
http://mail.python.org/mailman/listinfo/python-list

Re: Unable to see os.environ['COLUMNS']

2008-09-14 Thread Grant Edwards
On 2008-09-13, Tim Chase <[EMAIL PROTECTED]> wrote:
> Not sure what's going on here and hoping for some insight:
>
>[EMAIL PROTECTED]:~$ echo $COLUMNS
>129
>[EMAIL PROTECTED]:~$ python2.5
>Python 2.5.2 (r252:60911, May 28 2008, 08:35:32)
>[GCC 4.2.4 (Debian 4.2.4-1)] on linux2
>Type "help", "copyright", "credits" or "license" for more 
> information.
>>>> import os
>>>> os.environ.get('COLUMNS')
>>>>  'COLUMNS' in os.environ
>False
>
> I can coerce it by using
>
>[EMAIL PROTECTED]:~$ COLUMNS=$COLUMNS python2.5
>Python 2.5.2 (r252:60911, May 28 2008, 08:35:32)
> [GCC 4.2.4 (Debian 4.2.4-1)] on linux2
>Type "help", "copyright", "credits" or "license" for more 
> information.
>>>> import os
>>>> 'COLUMNS' in os.environ
>True
>
> However, this seems hokey to me.
>
> FWIW, this is in Bash on Debian.

In bash (and other descendants of the Bourne shell), there are
two types of environment variables: 1) local variables that are
not passed on to child processes and 2) exported variables that
_are_ passed on to children.

By default, when a variable is created it is local and will not
be inherited by sub-processes.

> What's the best way to read what seems to be a
> pseudo-environment variable?

You can't.  You need to export the variable in the parent shell
before it exec's the child:

$ echo $COLUMNS
80

$ python -c "import os; print os.environ['COLUMNS']"
Traceback (most recent call last):
  File "", line 1, in 
  File "/usr/lib/python2.5/UserDict.py", line 22, in __getitem__
raise KeyError(key)
KeyError: 'COLUMNS'

$ export COLUMNS

$ python -c "import os; print os.environ['COLUMNS']"
80


Now, on to the question you're about to ask:

Q: How do I find out how big my terminal is from a Python
   program?

A: You use the TIOCGWINSZ ioctl call on the terminal's file
   descriptor:

>>> import sys,fcntl,termios,struct
>>> data = fcntl.ioctl(sys.stdout.fileno(), termios.TIOCGWINSZ, '1234')
>>> struct.unpack('hh',data)
(24, 80)

There's a more detailed explanation here (including an
explanation of what the third parameter to ioctl() does, and
how you detect changes in the window size):

  http://mail.python.org/pipermail/python-list/2006-February/365710.html

There's also chance that you'd be better off just using ncurses or
newt for screen management, but that's another post.

-- 
Grant




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


Re: Good programming style

2008-09-14 Thread Ben Finney
Astley Le Jasper <[EMAIL PROTECTED]> writes:

> Is it best to have it all in one script or split it into per site
> scripts that can then be called by a manager script? If everything
> is in one script would you have per site functions to extract the
> data or generic function that contain vary slightly depending on the
> site, for example
> 
> import firstSiteScript
> import secondSiteScript

First: each of these things you're importing is a "module" in Python.
A script is what I prefer, for clarity, to call a "program": it's
intended to be executed independently as the top level of execution.

Second: please do yourself a favour and drop the camelCaseNames.
Follow PEP 8 http://www.python.org/dev/peps/pep-0008> for style
and naming in your Python code.

> firstsitedata = firstSiteScript.getData('search_str)
> secondsitedata = secondSiteScript.getData('search_str)
> etc etc

I'm presuming that there will be large areas of common functionality
between these different sites. On that basis, it's prbably best to
treat the differences as differences of *configuration* where
possible, instead of having separate modules for the entire site.

You might like to look at a web framework which gathers much of this
functionality together for you, and provides flexible ways to define
different sites in terms of those common elements
http://wiki.python.org/moin/WebFrameworks>.

-- 
 \   “Following fashion and the status quo is easy. Thinking about |
  `\your users' lives and creating something practical is much |
_o__)harder.” —Ryan Singer, 2008-07-09 |
Ben Finney
--
http://mail.python.org/mailman/listinfo/python-list

Re: Good programming style

2008-09-14 Thread Ben Finney
Grant Edwards <[EMAIL PROTECTED]> writes:

> On 2008-09-14, Ben Finney <[EMAIL PROTECTED]> wrote:
> > Second: please do yourself a favour and drop the camelCaseNames.
> > Follow PEP 8 http://www.python.org/dev/peps/pep-0008> for style
> > and naming in your Python code.
> 
> If he finds camelcase more readable and easier to type (as do
> I), how is switching to underscores "doing himself a favor"?
> 
> I'm generally in favor of using a consistent naming style
> throughout a project, but I don't see why the naming style used
> in my source code should be subject to somebody else's
> arbitrary standard.

Because the code we write rarely stays isolated from other code. There
is an existing convention, and it's better to pick a (sufficiently
sane) style convention and stick to it than argue about what the
convention should be.

> When it comes to writing code intended for the standard library
> in the main Python distribution, I would certainly defer to the
> existing standard as defined in PEP 8.  However, I don't see
> any reason that style should be imposed on all everybody else.

Who's imposing? I'm saying it's a good idea for everyone to do it, and
going so far as to say that one is doing oneself a favour by following
the convention. I have no more power than you to "impose" convention
on anyone.

-- 
 \  “‘Did you sleep well?’ ‘No, I made a couple of mistakes.’” |
  `\—Steven Wright |
_o__)  |
Ben Finney
--
http://mail.python.org/mailman/listinfo/python-list