Re: Python Embedding Thread

2008-07-21 Thread googler . 1 . webmaster
Hi!

Thank you very much for your answers. I have a menue with a script in
it.
So my app starts a new thread for each script.

So I would like to run two scripts all the same time. Could someone
give me a tip,
what I have to set in my code?

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


Re: string[i:j:k]

2008-07-21 Thread John McMonagle
konstantin wrote:

> 
> Thanks!
> It seems that negative step leads in reverse direction.
> But logic isn't completely clear for me.
 s = '123456789'
 s[::-2]
> '97531'
> 
> but
 s[:-1:-2]
> ''
> though I expected something like '8642'
> What did i missed?
> 
> --


You need to *start* at the second from last index:

s[-2::-2]

Regards,

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


Re: formatting list -> comma separated (slightly different)

2008-07-21 Thread Niklas Norrthon
On 9 Juli, 22:25, Michiel Overtoom <[EMAIL PROTECTED]> wrote:
> Paul & Robert wrote...
> > d = ["soep", "reeds", "ook"]
> >print ', '.join(d)
> > soep, reeds, ook
>
> I occasionally have a need for printing lists of items too, but in the form:
> "Butter, Cheese, Nuts and Bolts".  The last separator is the word 'and'
> instead of the comma. The clearest I could come up with in Python is below.
> I wonder if there is a more pythonic solution for this problem.  Maybe
> something recursive?

[snip]

> def pretty(f):
>     if len(f)==0: return ''
>     if len(f)==1: return f[0]
>     sepwithcommas=f[:-1]
>     sepwithand=f[-1]
>     s=', '.join(sepwithcommas)
>     if sepwithand:
>         s+=' and '+sepwithand
>     return s

def pretty(names):
return ' and '.join(', '.join(names).rsplit(', ', 1))


> friends=['Anne','Bob','Chris','Debbie','Eve','Fred']

print pretty(friends)
--
http://mail.python.org/mailman/listinfo/python-list


Web Page Construction in Python

2008-07-21 Thread SUBHABRATA
Dear Group,
I am getting some questions on doing Web Pages in Python.
I have some interactive codes in python for which I like to make web
pages.
I am trying to use kid.
Kid I learnt, and is easy, too.
My questions are:
i)  Am I going correct?
ii) Is there any language other than kid?
iii)The worked out examples of kid are not opening properly, is there
any other URL where I can see them.
iv) Can cgi scripting be done with kid?
If any one can spend time on my questions.
Best Regards,
Subhabrata.
--
http://mail.python.org/mailman/listinfo/python-list


Re: string[i:j:k]

2008-07-21 Thread Gary Herron

konstantin wrote:

On Jul 22, 9:18 am, alex23 <[EMAIL PROTECTED]> wrote:
  

On Jul 22, 3:10 pm, konstantin <[EMAIL PROTECTED]> wrote:



some_string[i:j:k]
What does it mean?
  

i = start position, j = end position, k = step size



s = "ABABABABABABAB"
s[0:6:2]
  

'AAA'


s = "ABCABCABCABCABC"
s[0:6:3]
  

'AA'

Hope this helps.

- alex23



Thanks!
It seems that negative step leads in reverse direction.
But logic isn't completely clear for me.
  

s = '123456789'
s[::-2]


'97531'

but
  

s[:-1:-2]



The slice s[:-1]
 means start at zero and go to n-1(where n-len(s))
 (it does not mean start at zero and go to -1)

So since the indexing is counting upward, the step size had better be 
positive.  Thus:

>>> s = '123456789'
>>> s[:-1:2]
'1357'
>>>


Gary Herron




''
though I expected something like '8642'
What did i missed?

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


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


Re: tail-rec decorator, well still blows the stack...

2008-07-21 Thread ssecorp
thanks i already have perfect iterative versions of fibonacci.
def fib(n):
a, b = 1, 0
while n:
a, b, n = b, a+b, n-1
return b


I know the example is not the way to write pythonic code, I was just
learning about decorators and then I saw this example and tried it
out.

but thanks now i understand why it didn't work.
--
http://mail.python.org/mailman/listinfo/python-list


Re: string[i:j:k]

2008-07-21 Thread konstantin
On Jul 22, 9:18 am, alex23 <[EMAIL PROTECTED]> wrote:
> On Jul 22, 3:10 pm, konstantin <[EMAIL PROTECTED]> wrote:
>
> > some_string[i:j:k]
> > What does it mean?
>
> i = start position, j = end position, k = step size
>
> >>> s = "ABABABABABABAB"
> >>> s[0:6:2]
> 'AAA'
> >>> s = "ABCABCABCABCABC"
> >>> s[0:6:3]
>
> 'AA'
>
> Hope this helps.
>
> - alex23

Thanks!
It seems that negative step leads in reverse direction.
But logic isn't completely clear for me.
>>> s = '123456789'
>>> s[::-2]
'97531'

but
>>> s[:-1:-2]
''
though I expected something like '8642'
What did i missed?

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


Re: proliferation of computer languages

2008-07-21 Thread Chris Rathman
I can't say that I see any particular point to the essay.  But I did
want to point out that Oz should not be considered part of the ML
family.  Aside from not being statically typed - a very central tenet
to ML, Oz is much more part of the Logic family of languages (Mercury,
Prolog, etc...).

On Jul 18, 12:17 pm, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote:
> Today, i took sometime to list some major or talked-about langs that
> arose in recent years.
>
> ML Family:
>
> * Oz�J. Concurrent. Multiparadigm.
> * Alice�J. Concurrent, ML derivative. Saarland University, Germany.
> * OCaml�J
> * F#�J. Microsoft's functional lang.

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

Re: Time Complexity of String Operations

2008-07-21 Thread Terry Reedy



youtoo wrote:

It has been extensively discussed the time complexity (quadratic) of
string concatenation (due to string's immutability).
But what is:

== the time complexity of string indexing? Is it constant?
== the time complexity of string slicing? Is it O(K) with K the
slice's length?

How are strings stored in Python? As arrays? As linked lists?


There is a Py wiki page on such issues.  A wiki search should find it.

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


Re: tail-rec decorator, well still blows the stack...

2008-07-21 Thread Terry Reedy



ssecorp wrote:

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496691

so I try it and when I run:
@Decorators.tail_recursion
def fibtr(n):
def fibt(a, b, n):
if n <= 1:
return b
else:
return fibt(b, a + b, n - 1)
if n == 0:
return 0
else:
return fibt(0, 1, n);

it still blows the stack. so what is the point? is it impossible to
get "real" tail-recursion in Python?


As you have used it, the decorator wraps the *outer* non-recursive 
function which is just called once anyway.  Useless.  Try wrapping fibt 
instead.


That said, this recipe significantly increases the running time by 
multiplying the number of function calls by about three.  I do not 
regard it as removing the recursion, but, rather, as making it indirect 
(via two other calls) so as to remove the unneeded stack frames (and the 
space problem) in between recursive calls.  Much simpler is the trivial 
rewrite with while to do 'in frame recursion', or iteration.  This also 
removes the need for outer and inner function.


rearrange fibt as

def fibt(a,b,n):
  if n > 1:
return fibt(b, a+b, n-1)
  else:
return b

and rewrite as

def fibi(a,b,n):
  while n > 1:
a,b,n = b,a+b,n-1
  return b

by directly binding the new arguments to the parameters.
Move the initialization inside the function (and delete the outer 
wrapper) to get


def fib(n):
  if n==0:
return 0
  else:
a,b = 0,1
while n > 1:
  a,b,n = b,a+b,n-1
return b

and even turn the induction back a step and simplify to

def fib(n):
  a,b = 1,0
  while n:
a,b,n = b,a+b,n-1
  return b

Why do some people fight writing efficient beautiful code like this that 
works with Python's design to instead write less efficient and uglier 
code that works against Python's design?


If you do not want function calls (and runtime name resolution), do not 
write them!


Terry Jan Reedy

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


Re: string[i:j:k]

2008-07-21 Thread alex23
On Jul 22, 3:10 pm, konstantin <[EMAIL PROTECTED]> wrote:
> some_string[i:j:k]
> What does it mean?

i = start position, j = end position, k = step size

>>> s = "ABABABABABABAB"
>>> s[0:6:2]
'AAA'
>>> s = "ABCABCABCABCABC"
>>> s[0:6:3]
'AA'

Hope this helps.

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


string[i:j:k]

2008-07-21 Thread konstantin
Hello,
I'm not a newbie in python, but recently faced a problem in simple
expression:
some_string[i:j:k]
What does it mean? I believe this  grammar (http://docs.python.org/ref/
slicings.html) describes the syntax. But I can't grasp it.
Thanks!
--
http://mail.python.org/mailman/listinfo/python-list


Re: Website Creation using Python

2008-07-21 Thread alex23
On Jul 22, 12:44 am, Amie <[EMAIL PROTECTED]> wrote:
> I would like some help on how to create a website using the python
> programming language.
> I've tried using enamel, but had some problems because I could not
> create html tables and intergrating it with python, like you use it
> when coding in php.

If you're familiar with the PHP approach and are planning on using
Apache, you might find mod_python and Python Server Pages more
accessible:

* http://en.wikipedia.org/wiki/Mod_python
* http://www.onlamp.com/pub/a/python/2004/02/26/python_server_pages.html

There are a *lot* of web frameworks for Python (I hadn't even heard of
Enamel prior to your post) which provide varying degrees of support
and ease of use, there's a nice overview here:

* http://wiki.python.org/moin/WebFrameworks

Django does seem to be leading in terms of popularity atm. Having
developed an application in TurboGears, I can testify that having a
large user base to draw support help from can be -very- handy.

Hope this helps.

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


Re: scanf in python

2008-07-21 Thread AMD

Robert Kern a écrit :

AMD wrote:

Hello,

I often need to parse strings which contain a mix of characters, 
integers and floats, the C-language scanf function is very practical 
for this purpose.
I've been looking for such a feature and I have been quite surprised 
to find that it has been discussed as far back as 2001 but never 
implemented.


The second Google hit is a pure Python implementation of scanf.

  http://hkn.eecs.berkeley.edu/~dyoo/python/scanf/



Hi Robert,

I had seen this pure python implementation, but it is not as fast or as 
elegant as would be an implementation written in C directly within 
python with no need for import.


Cheers,

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

Re: Time Complexity of String Operations

2008-07-21 Thread David Wahler
On Mon, Jul 21, 2008 at 10:31 PM, youtoo <[EMAIL PROTECTED]> wrote:
> It has been extensively discussed the time complexity (quadratic) of
> string concatenation (due to string's immutability).

Actually, it is roughly linear, at least for reasonable string lengths:

$ python -V
Python 2.5.2
$ python -mtimeit -s "n=1000; a='#'*n" "a+a"
100 loops, best of 3: 1 usec per loop
$ python -mtimeit -s "n=1; a='#'*n" "a+a"
10 loops, best of 3: 5.88 usec per loop
$ python -mtimeit -s "n=10; a='#'*n" "a+a"
1 loops, best of 3: 59.8 usec per loop

Repeatedly constructing a string by appending a constant number of
characters at a time, however, is quadratic in the final string length
(although VM optimizations may affect this).

> But what is:
>
> == the time complexity of string indexing? Is it constant?

Yes.

> == the time complexity of string slicing? Is it O(K) with K the
> slice's length?

I suspect so, since the time is dominated by the time taken to copy
the data into a new string object.

> How are strings stored in Python? As arrays? As linked lists?

Arrays; see Include/stringobject.h in the Python source distribution.

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


fromfile error on windows, not mac

2008-07-21 Thread jadamwil
Hello,
I am using the numpy fromfile function to read binary data from a file
on disk. The problem is that the program runs fine on a Mac, but gives
an error or warning on windows when trying to read the data. I use it
like this:

Signal = zeros((N, 16), dtype=float32)
for sample in range(0, N):
  # this function gets the next position in the file to seek to
  s = getFilePos(sample)

  # go to the correct location in the file; this IS checked to make
sure it is within the file
  mFile.seek(s)

  # read the 16 float32 values from the file
  D = fromfile(mFile, dtype=numpy.float32, 16)

  # save D in Signal
  Signal[sample, :] = D

This will fail when sample is ~4. If I change the range to (5,N),
skipping the "bad" file location, it will run fine for a few samples,
and then give another error. The message it gives is:
"16 items requested but only 7 read"

So D is a 7x1 vector, and the program dies when it tries to assign D
to the slice of Signal ("ValueError: shape mismatch: objects cannot be
broadcast to a single shape").

On windows, the Python version is 2.5.2, and the most recent numpy and
scipy are being used as well. I tried using Enthought, but it gave
this error as well, in addition to a c runtime error whenever I
imported scipy (which is another post topic...).

Any ideas on what might be causing this? Is there a way to debug the
fromfile function? And, remember, this works perfectly on a Mac. Would
compiling everything (python, scipy, numpy) potentially solve this?

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


Re: Python Embedding Thread

2008-07-21 Thread Jaimy Azle
"Benjamin" <[EMAIL PROTECTED]> wrote:

> Two threads should not be running through the Python VM concurrently
> in the same process. The GIL has to be held *any* time you use the
> Python API. When you want to release the GIL (to process something in
> C), use PY_BEGIN_ALLOW_THREADS and
> PY_END_ALLOW_THREADS around the
> places where threads can run.

I think he is trying to call python from thread, according to the 
documentation:

"Beginning with version 2.3, threads can now take advantage of the 
PyGILState_*() functions to do all of the above automatically."
 - http://docs.python.org/api/threads.html

I use it everywhere on my multithreaded server without problem.

Salam,

-Jaimy





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


Re: tail-rec decorator, well still blows the stack...

2008-07-21 Thread David Wahler
On Mon, Jul 21, 2008 at 10:01 PM, ssecorp <[EMAIL PROTECTED]> wrote:
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496691
>
> so I try it and when I run:
> @Decorators.tail_recursion
> def fibtr(n):
>def fibt(a, b, n):
>if n <= 1:
>return b
>else:
>return fibt(b, a + b, n - 1)
>if n == 0:
>return 0
>else:
>return fibt(0, 1, n);
>
> it still blows the stack. so what is the point? is it impossible to
> get "real" tail-recursion in Python?

Python does not perform tail-call elimination, and there are currently
no plans to make it do so. See
http://mail.python.org/pipermail/python-dev/2004-July/046171.html and
the ensuing discussion for an explanation.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python Written in C?

2008-07-21 Thread Larry Bates

Grant Edwards wrote:

On 2008-07-22, Larry Bates <[EMAIL PROTECTED]> wrote:


You talk about "writing it in assembly language for each MPU
chip".  Actually it is even better than that.  We now have
these modern inventions, called compilers that do that type of
work for us.  They translate high level instructions, not 
into assembler but into machine language.


Actually, all of the compilers I'm familiar with (gcc and a
handful of cross compilers for various microprocessors)
translate from high-level languages (e.g. C, C++) into
assembly, which is then assembled into relocatable object
files, which are then linked/loaded to produce machine
language.

I just learned something I did not know.  I was under the impression that they 
translated directly to machine code without ever actually generating Assembler 
text files.  Seems like a waste to generate the text and turn around run that 
through the assembler, but what do I know.  I guess that way the compiler can 
have pluggable assembler back-ends.


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


Re: Problem with Python Server Pages (PSP)

2008-07-21 Thread barun . saha04
On Jul 22, 5:18 am, Graham Dumpleton <[EMAIL PROTECTED]>
wrote:
> On Jul 21, 9:42 pm, [EMAIL PROTECTED] wrote:
>
>
>
>
>
> > Hi,
>
> > I am facing a very basic problem with PSP. I have installedmod_python
> > (in fedora Core 1), added the lines required for loading Python
> > modules and handling PSP pages. I have created a hello.psp page. But
> > when I try to view this hello.psp page, all Python code are getting
> > displayed.
>
> > The said page is stored at /var/www/html/psp/hello.psp. I guess this
> > is some configuration problem with Apache, but not able to figure out
> > the exact problem. I have tried putting those configuration lines for
> > psp in both httpd.conf and python.conf files. But still it is not
> > working.
>
> > The Python module (mod_python) is getting loaded. Because when I
> > telnet to my server, I can find that in the headers.
>
> > These are the versions of the softwares:
> > Apache: 2.0.47
> > Python: 2.2.3mod_python: 3.0.3
>
> > Thnaks for all your suggestions.
>
> What is the Apache configuration snippet you are using to enable
> mod_python and PSP file handling?
>
> Graham- Hide quoted text -
>
> - Show quoted text -

Hi Graham,

The configuration used in httpd.conf file looks like:

AddHandler .psp .psp_
PythonHandler modules/python
PythonDebug On

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


Re: Website Creation using Python

2008-07-21 Thread Larry Bates

Amie wrote:

Afternoon,

I would like some help on how to create a website using the python
programming language.
I've tried using enamel, but had some problems because I could not
create html tables and intergrating it with python, like you use it
when coding in php.

Any help would be appreciated.

Thanks


Python is not PHP.  Page generation is done differently.  You might take a look 
at Django's web framework:


http://www.djangoproject.com/

or

http://pylonshq.com/


WARNING - Python web frameworks are MUCH more powerful than just using PHP to 
place some dynamic content on a web page.  For many people, PHP will still be an 
easy to implement solution if your project isn't very complex.  As the 
complexity grows, the need for additional power and flexibility grows also.


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


Re: Python Written in C?

2008-07-21 Thread Grant Edwards
On 2008-07-22, Larry Bates <[EMAIL PROTECTED]> wrote:

> You talk about "writing it in assembly language for each MPU
> chip".  Actually it is even better than that.  We now have
> these modern inventions, called compilers that do that type of
> work for us.  They translate high level instructions, not 
> into assembler but into machine language.

Actually, all of the compilers I'm familiar with (gcc and a
handful of cross compilers for various microprocessors)
translate from high-level languages (e.g. C, C++) into
assembly, which is then assembled into relocatable object
files, which are then linked/loaded to produce machine
language.

-- 
Grant Edwards   grante Yow!  "DARK SHADOWS"
  at   is on!! Hey, I think
   visi.comthe VAMPIRE forgot his
   UMBRELLA!!
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python Written in C?

2008-07-21 Thread Larry Bates

[EMAIL PROTECTED] wrote:

I'm just learning about Python now and it sounds interesting. But I
just read (on the Wiki page) that mainstream Python was written in C.
That's what I was searching for: Python was written in what other
language?

See, my concern was something like: OK, if Python is so hot, then,
hopefully someone is writing it in assembly language for each MPU chip
out there. Otherwise, if, say, they've written it in C#, then it looks
like the REAL, generally useful language to learn is C# and Python is
akin to Visual Basic or something: a specialty languagewhereas
REAL WORLD programmers who want to be generally useful go and learn
C#.

So I was suspecting the Python compiler or interpreter is written in a
REAL language like C#. So, Wiki says it's written in C! It's almost as
if it were an intentional trick...write your own, new language in an
OLD, real world language that is passe. Compile it into executable
modules of course, so it is a real, working compiler, alright. But the
SOURCE is some old, high level language which no one wants to use
anymore! So now you've got a hot new language package and no one can
say "well, it is written in, the SOURCE code is written in, a REAL
language." No, it's not! The source is some outdated language and
compiler and no one is going to prefer learning THAT to learning your
hot new language!

I'm not dissing Python, here. Just noting that, if it is written in C,
that throws a curve at me in trying to balance the value of learning
Python vs. some other major language.


SPSS (was and may still be) written in Fortran and the Fortran compiler was 
written in C.  But NOBODY would suggest that you try to solve the problems that 
SPSS is used for in C.


You talk about "writing it in assembly language for each MPU chip".  Actually it 
is even better than that.  We now have these modern inventions, called compilers 
that do that type of work for us.  They translate high level instructions, not 
into assembler but into machine language.


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


Time Complexity of String Operations

2008-07-21 Thread youtoo
It has been extensively discussed the time complexity (quadratic) of
string concatenation (due to string's immutability).
But what is:

== the time complexity of string indexing? Is it constant?
== the time complexity of string slicing? Is it O(K) with K the
slice's length?

How are strings stored in Python? As arrays? As linked lists?

Thanks a lot!

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


Re: tail-rec decorator, well still blows the stack...

2008-07-21 Thread ssecorp
I my function not proper tail-recursion?


because this doesn't blow the stack:


#!/usr/bin/env python2.4
# This program shows off a python decorator(
# which implements tail call optimization. It
# does this by throwing an exception if it is
# it's own grandparent, and catching such
# exceptions to recall the stack.

import sys

class TailRecurseException:
  def __init__(self, args, kwargs):
self.args = args
self.kwargs = kwargs

def tail_call_optimized(g):
  """
  This function decorates a function with tail call
  optimization. It does this by throwing an exception
  if it is it's own grandparent, and catching such
  exceptions to fake the tail call optimization.

  This function fails if the decorated
  function recurses in a non-tail context.
  """
  def func(*args, **kwargs):
f = sys._getframe()
if f.f_back and f.f_back.f_back \
and f.f_back.f_back.f_code == f.f_code:
  raise TailRecurseException(args, kwargs)
else:
  while 1:
try:
  return g(*args, **kwargs)
except TailRecurseException, e:
  args = e.args
  kwargs = e.kwargs
  func.__doc__ = g.__doc__
  return func

@tail_call_optimized
def factorial(n, acc=1):
  "calculate a factorial"
  if n == 0:
return acc
  return factorial(n-1, n*acc)

print factorial(1)
# prints a big, big number,
# but doesn't hit the recursion limit.

@tail_call_optimized
def fib(i, current = 0, next = 1):
  if i == 0:
return current
  else:
return fib(i - 1, next, current + next)

print fib(1)
# also prints a big number,
# but doesn't hit the recursion limit.
--
http://mail.python.org/mailman/listinfo/python-list


tail-rec decorator, well still blows the stack...

2008-07-21 Thread ssecorp
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496691

so I try it and when I run:
@Decorators.tail_recursion
def fibtr(n):
def fibt(a, b, n):
if n <= 1:
return b
else:
return fibt(b, a + b, n - 1)
if n == 0:
return 0
else:
return fibt(0, 1, n);

it still blows the stack. so what is the point? is it impossible to
get "real" tail-recursion in Python?
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to install simplejson on WinXP

2008-07-21 Thread lookon
I just installed again to see the error message. But it worked OK now.
The problem was about compiling the c extension last time.

Fredrik Lundh wrote:
> lookon wrote:
>
> > I am new to python and had difficulty in installing simplejson on
> > WinXP...Could anyone help me? Thanks
>
> what did you try, and what happened when you tried that?
>
> 
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python Embedding Thread

2008-07-21 Thread Benjamin
On Jul 21, 6:56 am, [EMAIL PROTECTED] wrote:
> Hi :)
>
> I want to run Python in my app. That works still fine. But my app
> supports now Threads and I would like to know what to do, that it runs
> without problems.
>
> PyGILState_Release and PyGILState_Ensure should solve the problem
> right? Where do I have to put this two commands around? between each
> Command that increase, decrease a reference?

Two threads should not be running through the Python VM concurrently
in the same process. The GIL has to be held *any* time you use the
Python API. When you want to release the GIL (to process something in
C), use PY_BEGIN_ALLOW_THREADS and PY_END_ALLOW_THREADS around the
places where threads can run.
>
> Currently, this is a small code-snippet that represents the part of
> the code-execution:
>
>                                 PyObject *f_globals=NULL, *f_locals=NULL, 
> *mod=NULL, *rv=NULL;
>
>                                 mod = PyImport_ImportModule("__main__");
>                                 if (!mod)
>                                         return;
>
>                                 f_globals = PyModule_GetDict(mod);
>                                 f_locals = PyDict_New();
>                                 PyDict_Update(f_locals, f_globals);
>                                 if (!f_locals) {
>                                                 Py_DECREF(mod);
>                                                 PyErr_Print();
>                                                 return;
>                                 }
>
>                                 rv = PyRun_String(      , 
> Py_file_input, f_locals,
> f_locals);
>                                 if (!rv)
>                                         PyErr_Print();
>
>                                 Py_XDECREF(rv);
>                                 Py_DECREF(mod);
>                                 Py_DECREF(f_locals);
>                                 Py_DECREF(f_locals);
>
> Thanks a lot for your help :)

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


Re: Odd math related issue.

2008-07-21 Thread Dan Bishop
On Jul 21, 3:52 am, Fredrik Lundh <[EMAIL PROTECTED]> wrote:
> Robert Rawlins wrote:
> > I’ve got what seems to me to be a totally illogical math issue here
> > which I can’t figure out. Take a look at the following code:
>
> >         /self/.__logger.info(/"%i / %i"/ % (bytes_transferred,
> > /self/.__sessions[path].total_bytes))
>
> >         percentage = bytes_transferred /
> > /self/.__sessions[path].total_bytes * 100
>
> >         /self/.__logger.info(/"%i"/ % percentage)
>
> > Seems fairly straight forward, you would think. It takes two values and
> > calculates the percentage of one from the other, however, percentage
> > always comes back as ‘0’ for some reason, look at this log output.
>
> if you divide two integers, you'll get an integer back (in Python 2.X,
> at least).  quick fix:
>
>       percentage = bytes_transferred * 100 / total_bytes
>
> 

The most wonderful statement in the Python language is

from __future__ import division
--
http://mail.python.org/mailman/listinfo/python-list


Re: Pinging a machine from python

2008-07-21 Thread Prasanth
On May 26, 5:21 am, Zerge <[EMAIL PROTECTED]> wrote:
> On May 25, 11:13 am, Prasanth <[EMAIL PROTECTED]> wrote:
>
> > I tried pinging a machine from python using socket programming but
> > could not do it. Is there any module which we can use to ping the
> > machine < like net::ping in perl> or can you give me simple program.
>
> Import OS
> ip=192.168.1.1
> pingtext="ping "+ip+" -n 1"
> pingresult=os.popen(pingtext).readlines()
>
> "OS" gives you access to the command line of the operating system.

Thanks for the solution guys.

But the above program is giving the output as :

If we print pingresult it is giving the output as :

['\r\n', 'Pinging 0.168.1.1 with 32 bytes of data:\r\n', '\r\n',
'Request timed out.\r\n', '\r\n', 'Ping statistics for 0.168.1.1:\r
\n', 'Packets: Sent = 1, Received = 0, Lost = 1 (100% loss),\r\n']

my requirement is

IP address and whether the machine is pinging or not. we should not
display the above output. However we can do it by using regular
expression or there is any other way. Please suggest.

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


Re: Python Written in C?

2008-07-21 Thread bojannastic at googlemail
On Jul 20, 6:50 pm, [EMAIL PROTECTED] wrote:
> So I was suspecting the Python compiler or interpreter is written in a
> REAL language like C#. So, Wiki says it's written in C! It's almost as
> if it were an intentional trick...write your own, new language in an
> OLD, real world language that is passe. Compile it into executable
> modules of course, so it is a real, working compiler, alright. But the
> SOURCE is some old, high level language which no one wants to use
> anymore! So now you've got a hot new language package and no one can
> say "well, it is written in, the SOURCE code is written in, a REAL
> language." No, it's not! The source is some outdated language and
> compiler and no one is going to prefer learning THAT to learning your
> hot new language!

Young people these days...

I will just answer using one of old Microsoft's ads: "My compiler
compiled yours."


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


Re: Python Written in C?

2008-07-21 Thread Craig Allen
it's clear to me that the perfect language should exist a priori,
coming to being causa sui. Having to actually implement a language is
disgusting and unnatural.
--
http://mail.python.org/mailman/listinfo/python-list


RE: Python Written in C?

2008-07-21 Thread Delaney, Timothy (Tim)
Fredrik Lundh wrote:

> rynt wrote:
> 
>> You're either ---
>> A.  A Troll
>> B.  A young, immature programmer trying to show off or
>> C.  A total idiot.
> 
> you forgot the "All of the above" choice.

I read it as an inclusive "or".

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


Re: Python Written in C?

2008-07-21 Thread giveitawhril2008
On Jul 20, 9:18 pm, Michiel Overtoom <[EMAIL PROTECTED]> wrote:
.
>
> Many major text/word processing programs (Emacs, vi, MS-Word) are also
> written in C. Does that mean you should do all your text processing in C?

Well, actually, as a COBOL geezer I should not complain about Python.
Rumor had it that the COMPUTE statement in COBOL invoked FORTRAN
arithmetic modules. Yes, real programmers DO write in FORTRAN!

Frankly, I say screw not only object-oriented programming but
structured programming as well. I think someone should write a
compiler, "Revenge of BASIC." It would have good old REMs,
FOR...TO...NEXTs, GOSUBS, GOTOs, etc. Standard libraries of
subroutines, and/or Copy Libraries of source code, could handle
switching to new screens or forms, placement of objects, alteration of
characteristics of all these, detection of mouse and keyboard actions,
graphics, sound, placement of HTML code, EVERYTHING!

If anyone wants to write this compiler, they should probably do it in
Python. Make it open source, of course. I'm waiting!
--
http://mail.python.org/mailman/listinfo/python-list


Re: Problem with Python Server Pages (PSP)

2008-07-21 Thread Graham Dumpleton
On Jul 21, 9:42 pm, [EMAIL PROTECTED] wrote:
> Hi,
>
> I am facing a very basic problem with PSP. I have installedmod_python
> (in fedora Core 1), added the lines required for loading Python
> modules and handling PSP pages. I have created a hello.psp page. But
> when I try to view this hello.psp page, all Python code are getting
> displayed.
>
> The said page is stored at /var/www/html/psp/hello.psp. I guess this
> is some configuration problem with Apache, but not able to figure out
> the exact problem. I have tried putting those configuration lines for
> psp in both httpd.conf and python.conf files. But still it is not
> working.
>
> The Python module (mod_python) is getting loaded. Because when I
> telnet to my server, I can find that in the headers.
>
> These are the versions of the softwares:
> Apache: 2.0.47
> Python: 2.2.3mod_python: 3.0.3
>
> Thnaks for all your suggestions.

What is the Apache configuration snippet you are using to enable
mod_python and PSP file handling?

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


Re: Error importing modules with mod_python

2008-07-21 Thread Graham Dumpleton
On Jul 22, 3:30 am, Aaron Scott <[EMAIL PROTECTED]> wrote:
> I've installedmod_python, and everything seems to be working, but it
> fails when I try to import another file into the file that's actually
> producing the output. I have these lines at the top of index.py:
>
> frommod_pythonimport apache
> from storylab import *
>
> ... and in the directory where index.py resides (/htdocs/python/), I
> have a directory called "storylab". Inside that directory is
> __init__.py. When I try to execute /htdocs/python/index.py, I get the
> following error:
>
> ---
>
> MOD_PYTHONERROR
> ProcessId:      828
> Interpreter:    'localhost'
> ServerName:     'localhost'
> DocumentRoot:   'C:/htdocs'
> URI:            '/python/index.py'
> Location:       None
> Directory:      'C:/htdocs/python/'
> Filename:       'C:/htdocs/python/index.py'
> PathInfo:       ''
> Phase:          'PythonHandler'
> Handler:        'index'
>
> Traceback (most recent call last):
>
>   File "C:\Python25\lib\site-packages\mod_python\importer.py", line
> 1537, in HandlerDispatch
>     default=default_handler, arg=req, silent=hlist.silent)
>
>   File "C:\Python25\lib\site-packages\mod_python\importer.py", line
> 1202, in _process_target
>     module = import_module(module_name, path=path)
>
>   File "C:\Python25\lib\site-packages\mod_python\importer.py", line
> 296, in import_module
>     log, import_path)
>
>   File "C:\Python25\lib\site-packages\mod_python\importer.py", line
> 680, in import_module
>     execfile(file, module.__dict__)
>
>   File "C:\htdocs\python\index.py", line 2, in 
>     from storylab import *
>
> ImportError: No module named storylab
>
> ---
>
> What am I doing wrong? Any insight would be greatly appreciated.

You can't put Python packages in same directory as handler scripts
managed by mod_python. See documentation for import_module() in:

  http://www.modpython.org/live/current/doc-html/pyapi-apmeth.html

Graham


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


Re: scanf in python

2008-07-21 Thread Robert Kern

AMD wrote:

Hello,

I often need to parse strings which contain a mix of characters, 
integers and floats, the C-language scanf function is very practical for 
this purpose.
I've been looking for such a feature and I have been quite surprised to 
find that it has been discussed as far back as 2001 but never 
implemented.


The second Google hit is a pure Python implementation of scanf.

  http://hkn.eecs.berkeley.edu/~dyoo/python/scanf/

--
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth."
  -- Umberto Eco

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


Re: Converting List of String to Integer

2008-07-21 Thread Andrew Freeman

Samir wrote:

For my small list, I didn't notice a
discernible increase in speed, but I may have to try it with a larger
list size.
  


About speed, and memory consumption:
List comprehensions 
(http://docs.python.org/tut/node7.html#SECTION00714) are 
just shortcuts for for-loops. I do not believe there is any speed 
benefit. However, there are generators, they basically load one part of 
an iterator (a list in this case) at a time, this can greatly reduce 
memory usage.

Have a look at PEP 289:
http://www.python.org/dev/peps/pep-0289/

Here is the list comprehension as a generator (actually 2):
n = ((int(i) for i in k) for k in a)


Note, you can't just print a generator, it only computes something when 
needed:

>>> print n


You can, however iterate over it:

In [2]: for k in n:
  : for i in k:
  : print i,
  :
  :
1 2 3 4 5 6 7 8 9 0

In [3]: n = ((int(i) for i in k) for k in a)
In [49]: list(n)
Out[49]:
[,
,
,
]

Each sub-list is a generator too!
In [50]: n = ((int(i) for i in k) for k in a)
In [51]: for i in list(n): # list() converts the variable n to a list
  : list(i)
  :
  :
Out[51]: [1, 2]

Out[51]: [3]
Out[51]: [4, 5, 6]
Out[51]: [7, 8, 9, 0]


This is only going to make a difference if you were dealing with a 
*very* large data set. I thought I would show you even if you never user 
them, for learning purposes. Note: a generator is one way, redefine it 
every time you use it.

--
Andrew

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


Re: Python Written in C?

2008-07-21 Thread Tom Machinski
On Mon, Jul 21, 2008 at 3:53 PM, DaveM <[EMAIL PROTECTED]> wrote:

> On Mon, 21 Jul 2008 03:18:01 +0200, Michiel Overtoom <[EMAIL PROTECTED]>
> wrote:
>
>
> >Many major text/word processing programs (Emacs, vi, MS-Word) are also
> >written in C.
>
> I thought Emacs was written in Lisp.


Large parts of Emacs are indeed implemented in Emacs Lisp. There's are some
core functions implemented in C.

MS-Word, afaik, had very substantial parts written in Visual Basic.

Tom


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

Re: Python Written in C?

2008-07-21 Thread Teiresias
[EMAIL PROTECTED] writes:

> I'm just learning about Python now and it sounds interesting. But I
> just read (on the Wiki page) that mainstream Python was written in C.
> That's what I was searching for: Python was written in what other
> language?

Well, yes, the interpreter and a handful of the core modules are written in C.
However, most of Python -- especially the cool bits -- aren't written in
C.  They're written in ... Python!

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


Re: Converting List of String to Integer

2008-07-21 Thread Andrew Freeman

Samir wrote:

On Jul 21, 6:15 pm, Andrew Freeman <[EMAIL PROTECTED]> wrote:
  

Samir wrote:


On Jul 21, 3:20 pm, Gary Herron <[EMAIL PROTECTED]> wrote:
  

Samir wrote:


Hi Everyone,
  
I am relatively new to Python so please forgive me for what seems like

a basic question.
  
Assume that I have a list, a, composed of nested lists with string

representations of integers, such that
  
a = [['1', '2'], ['3'], ['4', '5', '6'], ['7', '8', '9', '0']]
  
I would like to convert this to a similar list, b, where the values

are represented by integers, such as
  
b = [[1, 2], [3], [4, 5, 6], [7, 8, 9, 0]]
  
I have unsuccessfully tried the following code:
  
n = []

for k in a:
n.append([int(v) for v in k])
print n
  
Does anyone know what I am doing wrong?
  
Thanks in advance.
  
Samir

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

You didn't tell us how it failed for you, so I can't guess what's wrong.

However, your code works for me:

 >>> a = [['1', '2'], ['3'], ['4', '5', '6'], ['7', '8', '9', '0']]

 >>> n = []
 >>> for k in a:
...n.append([int(v) for v in k])
...
 >>> print n
[[1, 2], [3], [4, 5, 6], [7, 8, 9, 0]]

(Although you seem to have confused variables b and n.)

Gary Herron- Hide quoted text -

- Show quoted text -


Hi Gary,
  
Thanks for your quick response (and sorry about mixing up b and n).

For some reason, the logic I posted seems to work ok while I'm using
the Python shell, but when used in my code, the program just hangs.
It never outputs the results.  Below is the code in its entirety.  Is
there a problem with my indendentation?
  
a = n = []

t = """
1 2
3
4 5 6
7 8 9 0
"""
  
d = t.split("\n")
  
for x in range(1,len(d)-1):

a.append(d[x].split(" "))
print a
  
for k in a:

n.append([int(v) for v in k])
  
print n
  
Thanks again.
  
Samir

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

I think this will work better, a sub-list comprehension of sorts:
n = [[int(i) for i in k] for k in a]

here is an ipython interactive session using it:
In [1]: a = n = []

In [2]: t = """
   ...: 1 2
   ...: 3
   ...: 4 5 6
   ...: 7 8 9 0
   ...: """

In [3]:

In [4]: d = t.split("\n")

In [5]: for x in range(1,len(d)-1):
   ...: a.append(d[x].split(" "))
   ...:
   ...:


In [6]: a
Out[6]: [['1', '2'], ['3'], ['4', '5', '6'], ['7', '8', '9', '0']]

In [7]: n = [[int(i) for i in k] for k in a]

In [8]: n
Out[8]: [[1, 2], [3], [4, 5, 6], [7, 8, 9, 0]]
--
Andrew- Hide quoted text -

- Show quoted text -



Andrew,

Thanks for the tip, though the syntax makes my head spin a bit in
trying to comprehend it.  For my small list, I didn't notice a
discernible increase in speed, but I may have to try it with a larger
list size.

Incidentally, I had never heard of iPython but from their web site, it
looks like an interesting tool.  I'll have to check it out.

Thanks.

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

If it helps look at this:

n = [[int(i) for i in k] for k in a]

like this:

n = []
for k in a:
   for i in k:
   n.append(int(i))

It is more verbose and easier to read and they both do exactly the same 
thing!


iPython is great, to install it you might try easy_install:
http://peak.telecommunity.com/DevCenter/EasyInstall

Then in a command line type:
easy_install ipython

Then, once it is complete, to use iPython type:
ipython

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


Re: Python Written in C?

2008-07-21 Thread Mensanator
On Jul 21, 8:26 am, Johannes Bauer <[EMAIL PROTECTED]> wrote:
> Mensanator schrieb:
>
> > You want cool?
> > THIS is cool:
>
> > j = ((invert(xyz[1]-xyz[0],xyz[1]**(k-1))*(xyz[1]**(k-1)-prev_gen[2]))
> > % xyz[1]**(k-1))/xyz[1]**(k-2)
>
> You call it cool, I call it NameError: name 'invert' is not defined.

It is when you do: from gmpy import *

That single line wasn't the whole program.

What's cool is that it IS a single line, that does answers
with >5 decimal digits without breaking a sweat. Sure, you
can use GMP with C (and I've done it). But it's nothing like
doing it in Python.

>
> Regards,
> Johannes
>
> --
> "Wer etwas kritisiert muss es noch lange nicht selber besser können. Es
> reicht zu wissen, daß andere es besser können und andere es auch
> besser machen um einen Vergleich zu bringen."     -     Wolfgang Gerber
>        in de.sci.electronics <[EMAIL PROTECTED]>

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


Re: Python Written in C?

2008-07-21 Thread DaveM
On Mon, 21 Jul 2008 03:18:01 +0200, Michiel Overtoom <[EMAIL PROTECTED]>
wrote:


>Many major text/word processing programs (Emacs, vi, MS-Word) are also
>written in C.

I thought Emacs was written in Lisp.

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


Re: Converting List of String to Integer

2008-07-21 Thread Samir
On Jul 21, 6:15 pm, Andrew Freeman <[EMAIL PROTECTED]> wrote:
> Samir wrote:
> > On Jul 21, 3:20 pm, Gary Herron <[EMAIL PROTECTED]> wrote:
>
> >> Samir wrote:
>
> >>> Hi Everyone,
>
> >>> I am relatively new to Python so please forgive me for what seems like
> >>> a basic question.
>
> >>> Assume that I have a list, a, composed of nested lists with string
> >>> representations of integers, such that
>
> >>> a = [['1', '2'], ['3'], ['4', '5', '6'], ['7', '8', '9', '0']]
>
> >>> I would like to convert this to a similar list, b, where the values
> >>> are represented by integers, such as
>
> >>> b = [[1, 2], [3], [4, 5, 6], [7, 8, 9, 0]]
>
> >>> I have unsuccessfully tried the following code:
>
> >>> n = []
> >>> for k in a:
> >>>     n.append([int(v) for v in k])
> >>> print n
>
> >>> Does anyone know what I am doing wrong?
>
> >>> Thanks in advance.
>
> >>> Samir
> >>> --
> >>>http://mail.python.org/mailman/listinfo/python-list
>
> >> You didn't tell us how it failed for you, so I can't guess what's wrong.
>
> >> However, your code works for me:
>
> >>  >>> a = [['1', '2'], ['3'], ['4', '5', '6'], ['7', '8', '9', '0']]
> >>  >>> n = []
> >>  >>> for k in a:
> >> ...    n.append([int(v) for v in k])
> >> ...
> >>  >>> print n
> >> [[1, 2], [3], [4, 5, 6], [7, 8, 9, 0]]
>
> >> (Although you seem to have confused variables b and n.)
>
> >> Gary Herron- Hide quoted text -
>
> >> - Show quoted text -
>
> > Hi Gary,
>
> > Thanks for your quick response (and sorry about mixing up b and n).
> > For some reason, the logic I posted seems to work ok while I'm using
> > the Python shell, but when used in my code, the program just hangs.
> > It never outputs the results.  Below is the code in its entirety.  Is
> > there a problem with my indendentation?
>
> > a = n = []
> > t = """
> > 1 2
> > 3
> > 4 5 6
> > 7 8 9 0
> > """
>
> > d = t.split("\n")
>
> > for x in range(1,len(d)-1):
> >     a.append(d[x].split(" "))
> > print a
>
> > for k in a:
> >     n.append([int(v) for v in k])
>
> > print n
>
> > Thanks again.
>
> > Samir
> > --
> >http://mail.python.org/mailman/listinfo/python-list
>
> I think this will work better, a sub-list comprehension of sorts:
> n = [[int(i) for i in k] for k in a]
>
> here is an ipython interactive session using it:
> In [1]: a = n = []
>
> In [2]: t = """
>    ...: 1 2
>    ...: 3
>    ...: 4 5 6
>    ...: 7 8 9 0
>    ...: """
>
> In [3]:
>
> In [4]: d = t.split("\n")
>
> In [5]: for x in range(1,len(d)-1):
>    ...:     a.append(d[x].split(" "))
>    ...:    
>    ...:    
>
> In [6]: a
> Out[6]: [['1', '2'], ['3'], ['4', '5', '6'], ['7', '8', '9', '0']]
>
> In [7]: n = [[int(i) for i in k] for k in a]
>
> In [8]: n
> Out[8]: [[1, 2], [3], [4, 5, 6], [7, 8, 9, 0]]
> --
> Andrew- Hide quoted text -
>
> - Show quoted text -

Andrew,

Thanks for the tip, though the syntax makes my head spin a bit in
trying to comprehend it.  For my small list, I didn't notice a
discernible increase in speed, but I may have to try it with a larger
list size.

Incidentally, I had never heard of iPython but from their web site, it
looks like an interesting tool.  I'll have to check it out.

Thanks.

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


Getting clear error messages with a Python templating system?

2008-07-21 Thread Tom Machinski
Hi there,

I'm developing web applications in Python, so I use a templating system to
produce HTML.

We're dealing with heavy traffic here, so my original choice was the fast
and efficient Cheetah. The main problem is that Cheetah doesn't provide
clear error messages. Even in the best cases, you only get some indication
of the nature of the error ("TypeError: 'str' object is not callable") but
you can't see the code where the error occurs. You can't even know the
approximate region of the template code where the problem originates.

So I tried another templating system, the newer and equally efficient Mako.
Again, same problem. It should be noted that both Cheetah and Mako compile
themselves to an intermediary Python file. This Python file is what's
actually running, so that's where the error originates. This is very
efficient, but also severely hinders debugging (see below for example of
what a very simple error on a very short Mako template generates).

So my question is: is there any way to get clear error messages with a
Python templating system?

I welcome both suggestion on how to get those with Cheetah (or Mako), and
suggestions about alternative templating systems that provide better error
messages.

Thanks,

Tom

-

# foo.mako:
hello ${data}

>>> print mako.template.Template(filename="foo.mako").render(data="world")
hello world

>>> print
mako.template.Template(filename="foo.mako").render(dataerr="world")
Traceback (most recent call last):
  File "", line 1, in 
  File
"/usr/lib/python2.5/site-packages/Mako-0.1.10-py2.5.egg/mako/template.py",
line 114, in render
return runtime._render(self, self.callable_, args, data)
  File
"/usr/lib/python2.5/site-packages/Mako-0.1.10-py2.5.egg/mako/runtime.py",
line 287, in _render
_render_context(template, callable_, context, *args,
**_kwargs_for_callable(callable_, data))
  File
"/usr/lib/python2.5/site-packages/Mako-0.1.10-py2.5.egg/mako/runtime.py",
line 304, in _render_context
_exec_template(inherit, lclcontext, args=args, kwargs=kwargs)
  File
"/usr/lib/python2.5/site-packages/Mako-0.1.10-py2.5.egg/mako/runtime.py",
line 337, in _exec_template
callable_(context, *args, **kwargs)
  File "foo_mako", line 19, in render_body
  File
"/usr/lib/python2.5/site-packages/Mako-0.1.10-py2.5.egg/mako/runtime.py",
line 91, in __str__
raise NameError("Undefined")
NameError: Undefined
--
http://mail.python.org/mailman/listinfo/python-list

Re: persistent deque (continued)

2008-07-21 Thread Raymond Hettinger
On Jul 21, 12:08 pm, castironpi <[EMAIL PROTECTED]> wrote:
> Some time ago, I was asking about the feasibility of a persistent
> deque, a double-ended queue.
>
> It runs into the typical space allocation problems.  

Try starting with a dict-based implementation of a double-ended queue
( http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/259179 )
and then replace the dict with a shelf.  Presto, you've got a
persistent deque.

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


Re: Converting List of String to Integer

2008-07-21 Thread Andrew Freeman

Samir wrote:

On Jul 21, 3:20 pm, Gary Herron <[EMAIL PROTECTED]> wrote:
  

Samir wrote:


Hi Everyone,
  
I am relatively new to Python so please forgive me for what seems like

a basic question.
  
Assume that I have a list, a, composed of nested lists with string

representations of integers, such that
  
a = [['1', '2'], ['3'], ['4', '5', '6'], ['7', '8', '9', '0']]
  
I would like to convert this to a similar list, b, where the values

are represented by integers, such as
  
b = [[1, 2], [3], [4, 5, 6], [7, 8, 9, 0]]
  
I have unsuccessfully tried the following code:
  
n = []

for k in a:
n.append([int(v) for v in k])
print n
  
Does anyone know what I am doing wrong?
  
Thanks in advance.
  
Samir

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

You didn't tell us how it failed for you, so I can't guess what's wrong.

However, your code works for me:

 >>> a = [['1', '2'], ['3'], ['4', '5', '6'], ['7', '8', '9', '0']]
 >>> n = []
 >>> for k in a:
...n.append([int(v) for v in k])
...
 >>> print n
[[1, 2], [3], [4, 5, 6], [7, 8, 9, 0]]

(Although you seem to have confused variables b and n.)

Gary Herron- Hide quoted text -

- Show quoted text -



Hi Gary,

Thanks for your quick response (and sorry about mixing up b and n).
For some reason, the logic I posted seems to work ok while I'm using
the Python shell, but when used in my code, the program just hangs.
It never outputs the results.  Below is the code in its entirety.  Is
there a problem with my indendentation?

a = n = []
t = """
1 2
3
4 5 6
7 8 9 0
"""

d = t.split("\n")

for x in range(1,len(d)-1):
a.append(d[x].split(" "))
print a

for k in a:
n.append([int(v) for v in k])

print n

Thanks again.

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

I think this will work better, a sub-list comprehension of sorts:
n = [[int(i) for i in k] for k in a]

here is an ipython interactive session using it:
In [1]: a = n = []

In [2]: t = """
  ...: 1 2
  ...: 3
  ...: 4 5 6
  ...: 7 8 9 0
  ...: """

In [3]:

In [4]: d = t.split("\n")

In [5]: for x in range(1,len(d)-1):
  ...: a.append(d[x].split(" "))
  ...:
  ...:


In [6]: a
Out[6]: [['1', '2'], ['3'], ['4', '5', '6'], ['7', '8', '9', '0']]

In [7]: n = [[int(i) for i in k] for k in a]

In [8]: n
Out[8]: [[1, 2], [3], [4, 5, 6], [7, 8, 9, 0]]
--
Andrew



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


Re: Python Written in C?

2008-07-21 Thread Terry Reedy



mk wrote:

Seriously, though, would there be any advantage in re-implementing 
Python in e.g. C++?


Considered and rejected by Guido and the CPython developer crew.
Anyone who wants C++Python is free to make one, just as people have done 
JavePython (Jython), C#Python, (IonPython), PythonPython (PyPy), and 
compiled-CPython (multiple).


Not that current implementation is bad, anything but, but if you're not 
careful, the fact that lists are implemented as C arrays can bite your 
rear from time to time (it recently bit mine while using lxml). Suppose 
C++ re-implementation used some other data structure (like linked list, 
possibly with twists like having an array containing pointers to 1st 
linked list elements to speed lookups up), which would be a bit slower 
on average perhaps, but it would behave better re deletion?


This is a data structure issue, not a language issue.  The tradeoffs for 
practical implementation include code-length, code-complexity, 
code-fragility, and ease of cross-platform compilation as well as 
classical time and space issues.


tjr

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


Re: Importing different versions of a module

2008-07-21 Thread Fredrik Lundh

mercado mercado wrote:

I have two versions of a script on my machine. One version is for new 
development and the other version is a production version.  This script 
imports a module from a different directory, and this module again has 
two versions (a development version and a production version).  What I 
want is for the development script to import the development module, and 
the production script to import the production module, without making 
any changes to the code in the script.


if you already have two different versions of the script, what stops you 
from making changes to them?


For example, suppose the development script is in ~/dev/rss.py, and the 
production script is in ~/prod/rss.py.  I want the dev version to import 
/usr/lib/python2.5/site-packages/lib_dev/parse.py, and the prod version 
to import usr/lib/python2.5/site-packages/lib_prod/parse.py.


cannot you just insert the appropriate directory in sys.path the first 
thing you do in the scripts?  e.g.


import os, sys

lib = "lib_dev" # change this for prod/rss.py

sys.path.insert(0,
os.path.join(
os.path.dirname(os.__file__), "site-packages", lib
))

import parse # picks the right one



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


Re: persistent deque (continued)

2008-07-21 Thread M.-A. Lemburg

On 2008-07-21 21:08, castironpi wrote:

Some time ago, I was asking about the feasibility of a persistent
deque, a double-ended queue.


You might want to have a look at mxBeeBase:

http://www.egenix.com/products/python/mxBase/mxBeeBase/

Using the integer index you could probably write an on-disk
dequeue.

The B*Tree indexes available in mxBeeBase keep the indexes sorted,
so you'd only have to keep incrementing the index as you add new
values and keep a record of the highest and lowest index currently
in use.

Details are left as exercise for the interested reader ;-)


It runs into the typical space allocation problems.  If you're storing
a pickle, you have to allocate and fragment the file you've opened,
since pickles can be variable-length strings; i.e. if the new data is
too long, blank out its entry, and grow the file.  If you're storing a
data-type, you lose Python's dynamic-type advantages, as well as its
long integers, as they can be any length.  If you change the object in
the deque, such as when using any mutable type, you have to update the
container too.

Does anyone have any experience storing pickles (I am aware of the
similarities to shelf) to a database?
Can the file system facilitate the variable-length string problem?
How feasible is a length-of-length - length - data solution to the
unbounded integer problem?
Is there any alternative to completely re-pickling a large (say 1k
pickled) object you only change slightly?
What other issues are there?
Is a hybrid-storage type possible, that stores the contents of its
Python-allocated memory block to disk, including reference count, even
if it's a lot slower?  The object could not contain any references to
objects not allocated on disk.

A first approach is for the file to look like this:

00 data 01 data 02
01 data 03 data 04
02 data 05 data 06

Append would add:

03 data 07 data 08

AppendLeft would add:

-01 data 09 data 0a

Pop would remove 03, PopLeft would remove -01.  You would need a
length-and-head index to make 'rotate' available.  Remove would run a
worst-case risk of renumbering half of the indices stored, plus a
rotate.
--
http://mail.python.org/mailman/listinfo/python-list


--
Marc-Andre Lemburg
eGenix.com

Professional Python Services directly from the Source  (#1, Jul 21 2008)
>>> Python/Zope Consulting and Support ...http://www.egenix.com/
>>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/
>>> mxODBC, mxDateTime, mxTextTools ...http://python.egenix.com/


 Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! 


   eGenix.com Software, Skills and Services GmbH  Pastor-Loeh-Str.48
D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg
   Registered at Amtsgericht Duesseldorf: HRB 46611
--
http://mail.python.org/mailman/listinfo/python-list


Re: Change PC to Win or Windows

2008-07-21 Thread Lie
On Mon, 2008-07-21 at 16:45 -0400, Derek Martin wrote:
> On Mon, Jul 21, 2008 at 12:32:00PM -0700, Lie wrote:
> > > The term "PC" is commonly used in English, in the United States
> > > and other English speaking countries, to mean a computer running
> > > Microsoft Windows.
> >
> > As far as I am aware, they're like that because most people aren't
> > even aware that there are other OSes than Microsoft Windows.
>
> You are missing two points.
>
> The first one:  It doesn't matter what the reasons are for the
> terminology to be common.  It only matters that it IS common.  It is;
> and it is therefore "correct" in the sense that it conveys a meaning
> to the overwhelming majority of English speakers, which is the
> intended one.
>
True, it doesn't actually matters, but it is a proof that it is
technically incorrect to apply PC JUST to Windows-based PC. It is
arguable whether the term should only be exclusively to IBM-PC or
whether the term should be expanded to include its clones. But I'm
against on using it just to refer Windows-based PC exclusively, since
it is neither Microsoft's marketing term nor a literal meaning
conveyed in the term.

> As for the question of whether or not it is appropriate to refer to
> Windows installations as "PC", it's as simple as that.  It is, by
> definition (via common usage).  That is what this thread is about.
>
Common usage isn't always correct. For example, a physicist would not
use weight when he meant mass. Although in daily use he might not care
much, but in technical environment doing so would embarrass him. In
this analogy, I consider download page for a software source code to
be a technical area.

> The reason why the world hasn't evolved to the two predictable cases
> > ("all kinds of microcomputers" or "IBM-PC and clones"), is what I'll
> > explain below.
>
> Your explanation is irrelevant to the argument of whether or not the
> term PC is an inappropriate term to describe a Windows installation,
> which is what this thread is about.  That is the premise put forth by
> the OP, and that is the notion to which I am responding.  It simply is
> not wrong or inappropriate in any sense; it is in fact correct,
> regardless of how the meaning or usage resulted, and regardless of any
> ADDITIONAL meanings the term may have.
>
> For what it's worth, your explanation is also WRONG; the term PC
> began to be popularly used in the United States to describe
> Intel-based Microsoft machines when there was a proliferation of other
> kinds of personal computers available to consumers.  When it was first
> used this way, the IBM PC was *NOT* the most popular personal computer...
> the Commodore 64 was.
>
True, but PC is IBM's marketing term, thus it originally belongs to
them. Nevertheless, it is NOT Window's marketing term and the literal
meaning of Personal Computer is in no way means Windows-based
computers ONLY.

> It dates from a time when the Commodore VIC-20
> and C64, Atari 400 and 800, Timex Sinclair, and other computers were
> all very popluar home machines.

But they aren't called PC, why? Because IBM hasn't invented the term.
Nowadays, they might be called as PC or not depending on which side
are you in: "PC as IBM-PC" or "PC as personal computer" (note the
lower case)

> The term probably originated primarily because IBM chose to name their
> computer the IBM PC, and because of Americans' predeliction to
> abbreviate everything that's more than 2 syllables. ;-)
>
> > > It wasn't something that Apple started; it's been used this way
> > > in increasingly common usage for at least 20 years, although
> > > exactly what combination of hardware and software was being
> > > refered to as a "PC" has evolved over that timeframe.
> >
> > Apple popularizes the term by explicit marketing,
>
> And here is the last point you are missing: Apple does no such
> thing.

They did, by using the term PC to refer to other computers. IF they
have used the term "Regular PC", noone would have complained, it's
just like an apple farmer advertising his "Super Apples" and calls
other apples "Regular Apples", there would be nothing wrong about it.
But there is this specific apple farmer who advertised his apple as
"Orange" and calls other apples as "Apples", which makes a problem
since "Orange" is just a different variants of apple, and is still an
apple. This kind of advertising Apple (the computer company) used is
misleading, since it implied that their PC is not a PC.

> They are only using a term in a way that has previously been
> popularized by the computer industry as a whole, and its market (i.e.
> consumers, predominantly American consumers historically) for
> *DECADES*.

> If I'm not mistaken, their ad campaign mentioning PCs is
> less than 10 years old (though I can't quickly find any references as
> to the date). The popularization of the term PC to refer to
> Intel-compatible machines running Microsoft OSes PREDATES APPLE'S AD
> CAMPAIGN BY OVER 10 YEARS.

When did I say that Appl

Re: Python Written in C?

2008-07-21 Thread Terry Reedy



Fredrik Lundh wrote:

rynt wrote:


You're either ---
A.  A Troll
B.  A young, immature programmer trying to show off
or
C.  A total idiot.


you forgot the "All of the above" choice.


Or Aspiring Comic.  This is certain one of the more entertaining troll 
posts we have had ;-).


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


Re: Getting the name of a variable which was used as a function parameter.

2008-07-21 Thread Fredrik Lundh

Ravi Kotecha wrote:


Of course I wouldn't, it is a total hack, mostly useless but fun.  I
tried to do it after someone in #python efnet said it was impossible!


your function only finds *some* name (if it finds a name at all), not 
*the* name, so you haven't really proven that someone wrong yet.


you can get a lot closer by using more radical approaches, but I don't 
think it's possible to do this in a fully robust way, at least not from 
the Python level.




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


Re: Trying to solve a python/mechanize "error 500" http error

2008-07-21 Thread Larry Bates

bruce wrote:

i'm getting the following error:
mechanize._response.httperror_seek_wrapper: HTTP Error 500:

i'm running python 5.1
and mechanize 0.1.7b

I have no idea as to what I have to change/modify/include to handle this
issue. The link that I'm testing is at the bottom of the page. When I insert
the link into the browser, I actually get an err page.. so, I suspect that
there is a handler that I should be able to modify/use to handle this
situation...

Thoughts/Comments will be greatly appreciated...

Thanks


the output is:

www =  www.1800ink.com
url2= http://www.quantcast.com/www.1800ink.com/traffic
Traceback (most recent call last):
  File "./reseller_scrape_child.py", line 288, in 
q1 = shopfuncs.quant(rhref)
  File "/adkiller/shopfuncs.py", line 56, in quant
br.open(url2)
  File "build/bdist.linux-x86_64/egg/mechanize/_mechanize.py", line 203, in
open
  File "build/bdist.linux-x86_64/egg/mechanize/_mechanize.py", line 254, in
_mech_open
mechanize._response.httperror_seek_wrapper: HTTP Error 500:
[EMAIL PROTECTED] adkiller]# ./reseller_scrape_child.py



my code segment looks like:

from  mechanize import Browser
import mechanize
br = Browser()
user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
values1 = {'name' : 'Michael Foord',
  'location' : 'Northampton',
  'language' : 'Python' }
headers = { 'User-Agent' : user_agent }

#br.set_cookiejar(cj)
br.set_handle_redirect(True)
br.set_handle_referer(True)
br.set_handle_robots(False)
br.addheaders = [('User-Agent', 'Firefox')]

url2 ="http://www.quantcast.com//traffic";
#gets the page (url) from the quantcast app
url2=url2.replace("",url)
print "url2=",url2
br.open(url2)

===

this works ok for most of the sites.. but something weird is happening with
the actual page:
http://www.quantcast.com/www.1800ink.com/traffic


thanks...





Looking up 500 error (here
http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html)
gives me:

10.5.1 500 Internal Server Error

The server encountered an unexpected condition which prevented it from 
fulfilling the request.



On some servers (Amazon), when you get 500 errors you are instructed to try
the request again.  I don't know about this server.

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


Re: Importing different versions of a module

2008-07-21 Thread norseman


mercado mercado wrote:

Thanks norseman for the reply.

You're right that I didn't like it though.  :-)

Also note that my original question has to do with importing modules from
different locations.  If all I had to do was use different paths within the
script (e.g. for sending to os.path.join or whatever), then I could just put
those in a config file.  That's not a problem...





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

===

I started to import a module using its path and now see what you mean.
Python is missing the concept: Programmer dictates what machine does.

(I come from assembly. If the hardware can do it, so can I.)

sys.path can be modified to switch between file sets (prod/test).
if a global is set one way, use the normal paths,
if set another, modify the needed to force the test_section into use.

Unfortunately this is not much of an answer. It means hardcoding two 
paths into globals and using a third to control which is used.  Since 
Python has a habit of coming and going on its own this may not work in a 
major effort. It may unload something and later reload with the sys.path 
set wrong. Docs say it will reload file that did load originally even if 
the file was modified between loads.  Docs do not say it keeps original 
location. I'll need some time to set things up to test what it does.


Nothing I've done in Python had bumped into your problem until I ran the
test. Never dawned on me it would be this stupid. I had intended to use 
Python to talk to ESRI products and my stuff. I made a few minor 
routines just to get used to Python and was starting to tackle the real 
problem. My assembly, C, fortran & bash scripts all work as expected.

They do, Python doesn't.



ORIGINALLY, IN THIS REPLY, I HAD STARTED TO SAY:
I've used this before. Maybe it will work in Python, maybe not.
Global sets which section to use by being a prefix to each test module
name. Something like "my_" for test and empty otherwise.

global WHICH
WHICH='my_'

import WHICH+'subrtn'

WHICH=''

import WHICH+'subrtn2'


gets my_subrtn from the test suite
  and
gets subrtn2 from the production section.

Each module would thus need to store/reset the Global's value upon init
to be used in its own imports since it's status at any given time is in
question.

Python docs say Python keeps the original name of the originally
successfully loaded file. The built-in 'reload' can get it back, even if
it has been changed (edited) during the session.

The files my_ whatever have the my_ removed from the disk name when they
go production.
#
  BUT
import WILL NOT TAKE VARS
#

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

WHICH="my_"
import WHICH+"popen2"

  File "", line 1
import WHICH+"popen2"
^
SyntaxError: invalid syntax



OK  check#2


x=WHICH+"open2"
x

'my_open2'

import x

Traceback (most recent call last):
  File "", line 1, in 
ImportError: No module named x



OK   check#3


help(x)

no Python documentation found for 'my_open2'#true, proves x OK




BOY-O-BOY,  DOES THAT SCREW THE POOCH

Mercado, like you, I'm not very happy right now.  This means that
prefixing cannot be used to control imports. For decades I have used 
prefixing in both scripts and compiled lib routines for controlling what 
gets loaded or not.


Right now I'm not a happy Python camper, not at all.



Steve
[EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list


Re: imported module no longer available

2008-07-21 Thread Fredrik Lundh

Jeff Dyke wrote:


actually no, the only things in that fucntion were.
   print globals().keys() - i see it here
   print mymodulename - it fails here.

the `import mymodulename` statement is at the very top of the file.

plus the processing that was attempted after.


so how did that processing use the "mymodulename" name?

>> in fact in the calling

method i was able to execute print mymodulename and it printed the
expected python output.


the calling method has nothing to do with what's considered to be a 
local variable in the method being called, so that only means that the 
name is indeed available in the global scope.



So i went back to check that the name 'mymodulename' was not getting
overwritten by something else and the error went away.  I've been
working on something else entirely for the past few hours and have
changed none of the code...and now it works.  which is even more
troublesome then the error itself.


more likely, it indicates that you removed the line that caused Python 
to treat that name as a local variable.



Follow on question.  If this name, mymodulename, was imported in some
other module.fucntion local to a function like
def anotherfunc():
   import mymodulename

would that remove it from the globals() and save it to a locals() ?  I
would assume the answer to be no.


even after reading the page I pointed you to?

import binds a name, so an import statement inside a function will cause 
Python to treat that name as a local variable (unless you add a global 
declaration to that function).


maybe a few examples will make this clearer; the following snippets are 
complete programs:


snippet 1:

import module # adds module to the global namespace

def func():
module.func() # uses module from the global namespace

func() # no error here

snippet 2:

def func():
import module # adds module to the *local* namespace
module.func()

func() # no error here
module.func() # doesn't work; no module in global namespace

snippet 3:

def func():
global module # marks module as a global name
import module # adds module to the *global* namespace
module.func()

func() # no error here
module.func() # no error here; global module set by function

snippet 4:

import module # adds module to global namespace

def func():
import module # adds module to local namespace too
print module # prints local variable
module = None # sets local variable to None

func() # no error here
module.func() # no error here either; uses global namespace

snippet 5:

import module

def func():
print module # fails with an UnboundLocalError.
# lots of lines
import module # adds to local namespace; marks name as local
# some more code

func() # will fail at print statement

my guess is that the last snippet corresponds to your case.



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


Re: Getting the name of a variable which was used as a function parameter.

2008-07-21 Thread Ravi Kotecha
Of course I wouldn't, it is a total hack, mostly useless but fun.  I
tried to do it after someone in #python efnet said it was impossible!

On Jul 21, 9:56 pm, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote:
> On Mon, 21 Jul 2008 09:01:10 -0700, Ravi Kotecha wrote:
> > I thought this was pretty cool and since I spent 30 mins or so
> > goggling before giving up and figuring out myself I thought I'd share
> > it with you.
>
>  def a(a):
> > ...     for k,v in sys._getframe(1).f_locals.items():
> > ...         if id(v) == id(a):
> > ...             print k
> > ...
>
>  hello = 123
>
>  a(hello)
> > hello
>
> > ## pretty cool.
>
> Or ugly hack.  Beauty lies in the eye of the beer holder…
>
> > It's totally useless but I wanted to do it for logging purposes.
>
> Don't use such things in production code, please.
>
> Ciao,
>         Marc 'BlackJack' Rintsch

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


RE: Python Written in C?

2008-07-21 Thread Phil Runciman



On 20 jul, 19:50, [EMAIL PROTECTED] wrote:
> I'm just learning about Python now and it sounds interesting. But I
> just read (on the Wiki page) that mainstream Python was written in C.
> That's what I was searching for: Python was written in what other
> language?
>
> See, my concern was something like: OK, if Python is so hot, then,
> hopefully someone is writing it in assembly language for each MPU chip
> out there. Otherwise, if, say, they've written it in C#, then it looks
> like the REAL, generally useful language to learn is C# and Python is
> akin to Visual Basic or something: a specialty languagewhereas
> REAL WORLD programmers who want to be generally useful go and learn
> C#.
>
> So I was suspecting the Python compiler or interpreter is written in a

".. if Python is so hot.." Python represents progress not the ultimate
goal. Thank goodness we are continuing to learn from past mistakes. 

All compilers and interpreters started out being written in another
language. You do not help us by stating the obvious. 

This is even true of the interpreter in your own brain that processes
English. IMHO The latter still has some bugs in it. ;-)


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


Re: Python Written in C?

2008-07-21 Thread Marc 'BlackJack' Rintsch
On Mon, 21 Jul 2008 11:26:27 -0700, castironpi wrote:

> On Jul 20, 11:59 pm, Michael Torrie <[EMAIL PROTECTED]> wrote:
>> [EMAIL PROTECTED] wrote:
>> > I'm not dissing Python, here. Just noting that, if it is written in C,
>> > that throws a curve at me in trying to balance the value of learning
>> > Python vs. some other major language.
>>
>> Definitely one of the most non-sequitor statements I have ever heard.
>> Actually your entire post doesn't make much sense.  Maybe you are a
>> brother bot to castropini?  Perhaps a less-trained one, although none of
>> castropini's posts seem to make sense either.  The AI needs a bit of work.
> 
> Are you saying Python is not good for writing A.I., or the A.I. isn't
> good at writing Python?

Are you saying python is not as smart as you.

Ciao,
Marc 'BlackJack' Rintsch
--
http://mail.python.org/mailman/listinfo/python-list

Re: Getting the name of a variable which was used as a function parameter.

2008-07-21 Thread Marc 'BlackJack' Rintsch
On Mon, 21 Jul 2008 09:01:10 -0700, Ravi Kotecha wrote:

> I thought this was pretty cool and since I spent 30 mins or so
> goggling before giving up and figuring out myself I thought I'd share
> it with you.
> 
 def a(a):
> ... for k,v in sys._getframe(1).f_locals.items():
> ... if id(v) == id(a):
> ... print k
> ...
> 
 hello = 123
> 
 a(hello)
> hello
> 
> ## pretty cool.

Or ugly hack.  Beauty lies in the eye of the beer holder…

> It's totally useless but I wanted to do it for logging purposes.

Don't use such things in production code, please.

Ciao,
Marc 'BlackJack' Rintsch
--
http://mail.python.org/mailman/listinfo/python-list

Re: Seriously, though, about LLVM

2008-07-21 Thread Fredrik Lundh

mk wrote:

This project has gained some publicity. There's IronPython, right, so 
has anybody thought about implementing Python using LLVM as backend, 
as it seems not out of question at all?


you mean like:

http://llvm.org/ProjectsWithLLVM/#pypy

?


No, I don't mean "Python written in Python", with whatever backend.


so anyone attempting to write a Python implementation for the LLVM 
aren't allowed to use Python for the front-end?  why not?




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


Re: Converting List of String to Integer

2008-07-21 Thread Samir
On Jul 21, 4:44 pm, Gary Herron <[EMAIL PROTECTED]> wrote:
> Samir wrote:
> > On Jul 21, 3:20 pm, Gary Herron <[EMAIL PROTECTED]> wrote:
>
> >> Samir wrote:
>
> >>> Hi Everyone,
>
> >>> I am relatively new to Python so please forgive me for what seems like
> >>> a basic question.
>
> >>> Assume that I have a list, a, composed of nested lists with string
> >>> representations of integers, such that
>
> >>> a = [['1', '2'], ['3'], ['4', '5', '6'], ['7', '8', '9', '0']]
>
> >>> I would like to convert this to a similar list, b, where the values
> >>> are represented by integers, such as
>
> >>> b = [[1, 2], [3], [4, 5, 6], [7, 8, 9, 0]]
>
> >>> I have unsuccessfully tried the following code:
>
> >>> n = []
> >>> for k in a:
> >>>     n.append([int(v) for v in k])
> >>> print n
>
> >>> Does anyone know what I am doing wrong?
>
> >>> Thanks in advance.
>
> >>> Samir
> >>> --
> >>>http://mail.python.org/mailman/listinfo/python-list
>
> >> You didn't tell us how it failed for you, so I can't guess what's wrong.
>
> >> However, your code works for me:
>
> >>  >>> a = [['1', '2'], ['3'], ['4', '5', '6'], ['7', '8', '9', '0']]
> >>  >>> n = []
> >>  >>> for k in a:
> >> ...    n.append([int(v) for v in k])
> >> ...
> >>  >>> print n
> >> [[1, 2], [3], [4, 5, 6], [7, 8, 9, 0]]
>
> >> (Although you seem to have confused variables b and n.)
>
> >> Gary Herron- Hide quoted text -
>
> >> - Show quoted text -
>
> > Hi Gary,
>
> > Thanks for your quick response (and sorry about mixing up b and n).
> > For some reason, the logic I posted seems to work ok while I'm using
> > the Python shell, but when used in my code, the program just hangs.
> > It never outputs the results.  Below is the code in its entirety.  Is
> > there a problem with my indendentation?
>
> Aha.  There's the problem, right there in the first line.
>
> > a = n = []
>
> This sets a and n to the *same* empty list.    This line creates one
> empty list and binds both n and a to that list.  Note carefully,  there
> is only one empty list here, but it can be accessed under two names
>
> Later in your code,
>
>   for k in a:
>
> runs through that list, and
>
>   n.append(...)
>
> append to the end of the same list.  Thus the loop never get to the end of 
> the (continually growing) list.
>
> Solve it by creating two different empty lists:
>
>   a = []
>   n = []
>
> Gary Herron
>
>
>
> > t = """
> > 1 2
> > 3
> > 4 5 6
> > 7 8 9 0
> > """
>
> > d = t.split("\n")
>
> > for x in range(1,len(d)-1):
> >     a.append(d[x].split(" "))
> > print a
>
> > for k in a:
> >     n.append([int(v) for v in k])
>
> > print n
>
> > Thanks again.
>
> > Samir
> > --
> >http://mail.python.org/mailman/listinfo/python-list- Hide quoted text -
>
> - Show quoted text -- Hide quoted text -
>
> - Show quoted text -

Gary,

That did the trick!  I didn't realize that the way I initialized my
lists would lead to the behavior that I observed.  After doing
something similar to what John had suggested I did indeed discover
that I created an endless loop.  I'm glad I learned something today.

Thanks for your help.

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


Re: Change PC to Win or Windows

2008-07-21 Thread Derek Martin
On Mon, Jul 21, 2008 at 12:32:00PM -0700, Lie wrote:
> > The term "PC" is commonly used in English, in the United States
> > and other English speaking countries, to mean a computer running
> > Microsoft Windows.
> 
> As far as I am aware, they're like that because most people aren't
> even aware that there are other OSes than Microsoft Windows. 

You are missing two points.

The first one:  It doesn't matter what the reasons are for the
terminology to be common.  It only matters that it IS common.  It is;
and it is therefore "correct" in the sense that it conveys a meaning
to the overwhelming majority of English speakers, which is the
intended one.

As for the question of whether or not it is appropriate to refer to
Windows installations as "PC", it's as simple as that.  It is, by
definition (via common usage).  That is what this thread is about.

> The reason why the world hasn't evolved to the two predictable cases
> ("all kinds of microcomputers" or "IBM-PC and clones"), is what I'll
> explain below.

Your explanation is irrelevant to the argument of whether or not the
term PC is an inappropriate term to describe a Windows installation,
which is what this thread is about.  That is the premise put forth by
the OP, and that is the notion to which I am responding.  It simply is
not wrong or inappropriate in any sense; it is in fact correct,
regardless of how the meaning or usage resulted, and regardless of any
ADDITIONAL meanings the term may have.
 
For what it's worth, your explanation is also WRONG; the term PC
began to be popularly used in the United States to describe
Intel-based Microsoft machines when there was a proliferation of other
kinds of personal computers available to consumers.  When it was first
used this way, the IBM PC was *NOT* the most popular personal computer...
the Commodore 64 was.  It dates from a time when the Commodore VIC-20
and C64, Atari 400 and 800, Timex Sinclair, and other computers were
all very popluar home machines.

The term probably originated primarily because IBM chose to name their
computer the IBM PC, and because of Americans' predeliction to
abbreviate everything that's more than 2 syllables. ;-)

> > It wasn't something that Apple started; it's been used this way
> > in increasingly common usage for at least 20 years, although
> > exactly what combination of hardware and software was being
> > refered to as a "PC" has evolved over that timeframe.
> 
> Apple popularizes the term by explicit marketing, 

And here is the last point you are missing: Apple does no such
thing.  They are only using a term in a way that has previously been
popularized by the computer industry as a whole, and its market (i.e.
consumers, predominantly American consumers historically) for
*DECADES*.  If I'm not mistaken, their ad campaign mentioning PCs is
less than 10 years old (though I can't quickly find any references as
to the date).  The popularization of the term PC to refer to
Intel-compatible machines running Microsoft OSes PREDATES APPLE'S AD
CAMPAIGN BY OVER 10 YEARS.

Therefore none of your points are valid or relevant, as to the
question of whether the usage of the term "PC" to describe windows
builds of Python is appropriate.

Can we return to the subject of Python now?

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



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

Re: Converting List of String to Integer

2008-07-21 Thread Gary Herron

Samir wrote:

On Jul 21, 3:20 pm, Gary Herron <[EMAIL PROTECTED]> wrote:
  

Samir wrote:


Hi Everyone,
  
I am relatively new to Python so please forgive me for what seems like

a basic question.
  
Assume that I have a list, a, composed of nested lists with string

representations of integers, such that
  
a = [['1', '2'], ['3'], ['4', '5', '6'], ['7', '8', '9', '0']]
  
I would like to convert this to a similar list, b, where the values

are represented by integers, such as
  
b = [[1, 2], [3], [4, 5, 6], [7, 8, 9, 0]]
  
I have unsuccessfully tried the following code:
  
n = []

for k in a:
n.append([int(v) for v in k])
print n
  
Does anyone know what I am doing wrong?
  
Thanks in advance.
  
Samir

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

You didn't tell us how it failed for you, so I can't guess what's wrong.

However, your code works for me:

 >>> a = [['1', '2'], ['3'], ['4', '5', '6'], ['7', '8', '9', '0']]
 >>> n = []
 >>> for k in a:
...n.append([int(v) for v in k])
...
 >>> print n
[[1, 2], [3], [4, 5, 6], [7, 8, 9, 0]]

(Although you seem to have confused variables b and n.)

Gary Herron- Hide quoted text -

- Show quoted text -



Hi Gary,

Thanks for your quick response (and sorry about mixing up b and n).
For some reason, the logic I posted seems to work ok while I'm using
the Python shell, but when used in my code, the program just hangs.
It never outputs the results.  Below is the code in its entirety.  Is
there a problem with my indendentation?

  

Aha.  There's the problem, right there in the first line.


a = n = []
  


This sets a and n to the *same* empty list.This line creates one 
empty list and binds both n and a to that list.  Note carefully,  there 
is only one empty list here, but it can be accessed under two names


Later in your code, 


 for k in a:

runs through that list, and 


 n.append(...)

append to the end of the same list.  Thus the loop never get to the end of the 
(continually growing) list.

Solve it by creating two different empty lists:

 a = []
 n = []


Gary Herron






t = """
1 2
3
4 5 6
7 8 9 0
"""

d = t.split("\n")

for x in range(1,len(d)-1):
a.append(d[x].split(" "))
print a

for k in a:
n.append([int(v) for v in k])

print n

Thanks again.

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


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


Re: sending input to an embedded application

2008-07-21 Thread norseman


Matthew Fitzgibbons wrote:


mefyl wrote:

Uwe Schmitt wrote:

On 12 Jul., 09:08, George Oliver <[EMAIL PROTECTED]> wrote:

What I would like to do is take a program and embed it or put it
within a Python-run GUI, using the GUI just to capture and send input
to the application, and display the ouput.

Which interface does your interpreter provide ? Just commandline or
can you access by other methods ?

http://sourceforge.net/projects/pexpect/ might help you



Although Pexpect looks more advanced and complete, you might want to 
take a
look at popen* modules. It enables you to easily run a subprocess, 
feed him

data on stdin, retrieve output from stdout/stderr, and wait for its
completion.

http://docs.python.org/lib/module-popen2.html



I believe the subprocess module is the recommended module to use now.

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


=

HUMM!



#
print "popen3 run"
## from existing python docs:
from popen2 import *

r,w,e= popen3('dmesg | grep hda')
print r.read()


print "subprocess run"
## from existing python docs:
# "... Replacing older functions with the subprocess module..."
from subprocess import *

p1 = Popen(["dmesg"], stdout=PIPE)
p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
output = p2.communicate()[0]
#documentation quits

print p2.communicate()

#
""" Why do children insists on making things more complicated
   than necessary?  If the stated bragging rights of Python
   is that one writes less code to accomplish more, then I
   have to say "bullshit", just count the printable characters.

   to write less would be to change something like this:
   try:
   f = open(arg, 'r')
   except IOError:
   print 'cannot open', arg
   else:
   print arg, 'has', len(f.readlines()), 'lines'
   f.close()
   ### I have to guess what type error to code for and I'll need another
   module to decode what actually went wrong.


   to this:
   if (fd = os.open(filename, 'O_RDRW|O_BINARY, 0666) == -1)
 ...handle it
 if fd.err.type == THIS #catagory
   if fd.err == this#specific
 do this
 etc.
 ## just to see what went wrong?  print fd.err.type, fd.err
   else:#just to match above
 continue processing
   ###  error reporting actually usefull

   who says fd cannot be simple interger or pointer to error block
   depending on whether it's valid or not?  The bonus is, if there is
   no trap it will stop anyway first time fd is used as a file number.
   The crash usually actually points to the correct place. :)

   All that aside:  subprocess seems to have a problem:

"""
# When I run the above I get:

==
PY:> py test.py
popen3 run
   ide0: BM-DMA at 0x1400-0x1407, BIOS settings: hda:DMA, hdb:pio
hda: ST9160821A, ATA DISK drive
hda: attached ide-disk driver.
hda: host protected area => 1
hda: cannot use LBA48 - capacity reset from 312581808 to 268435456
hda: 268435456 sectors (137439 MB) w/8192KiB Cache, CHS=19457/255/63, 
UDMA(100)

hda: hda1 hda2 hda3 < hda5 hda6 hda7 hda8 >

subprocess run
('', None)
PY:>
=

Note subprocess yields unexpected answer. Probably needs better
documentation and less typing. :)

The "PY:> " is result of script to change to dir python and set the PATH
py is copy of python renamed to afford less typing. (Unix vs Microsoft)

Note: without lots of extra effort, the piping only works for commands 
like grep that are built to accept redirected I/O. I have yet to get it 
to work with the GUI type. Those need special things implanted at 
compile time because they don't use or even want the command line 
interface. Typically they are "Point'n'Click" or take a hike. GUIs are 
visually more appealing but don't play well in the production world.


Steve
[EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list


Re: Missing sqlite3.h Error when Building Debug Python -- Windows Vista

2008-07-21 Thread Bev in TX
Thanks for letting me know about this.  I installed Subversion and
tried to make the build work like that, but it fails.

1) I am building 64-bit on Vista, so I used build-amd64.bat instead of
build.bat.

2) build-amd64.bat was setup to use MSVS 9.0, while I am using MSVS
8.0.  Also, some of the BATCH programs incorrectly added a backslash
after the %VS90COMNTOOLS% environment variable.  I corrected those to
use %VS80COMNTOOLS%, without the backslash.

3) It then complained about incompatible solution/project files, so I
modified build-amd64.bat to use the solution/project files in pc\vs8.0
instead of pcbuild.

4) It now has errors/warnings like:
C:\Program Files (x86)\Microsoft Visual Studio 8\VC\PlatformSDK\include
\prsht.h(531) : error C2016: C requires that a struct or union has at
least one member
...
c1 : fatal error C1083: Cannot open source file: '..\..\..
\db-4.4.20\common\zerofill.c': No such file or directory
xa_map.c
...
4>..\..\Python\getargs.c(319) : warning C4244: 'function' : conversion
from 'Py_ssize_t' to 'int', possible loss of data

So I don't see how the amd64-bit builds are working out of the box on
MS Windows Vista, and I may have made some error when changing the
build files.

I'd appreciate any other thoughts ...

Bev in TX

On Jul 20, 10:36 am, Tim Golden <[EMAIL PROTECTED]> wrote:
> I'll leave others to comment on whether or not
> it's expected to build with VS2005, but the easiest
> way to get a debug build is to pretend to be a buildbot.
>
> 1) Check out the python source into, say, c:\dev\python
>
> svn cohttp://svn.python.org/projects/python/trunkc:\dev\python
>
> 2) Switch to that directory
>
> cd \dev\python
>
> 3) Pretend to be a buildbot
>
> tools\buildbot\build
>
> This will checkout all the necessary sources into, in my
> example, c:\dev. It will then run all the build steps
> necessary to get a debug build which will then be in
>
> c:\dev\python\pcbuild\python_d.exe
>
> TJG

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


Re: Converting List of String to Integer

2008-07-21 Thread John Machin
On Jul 22, 6:11 am, Samir <[EMAIL PROTECTED]> wrote:
[snip]

> For some reason, the logic I posted seems to work ok while I'm using
> the Python shell, but when used in my code, the program just hangs.
> It never outputs the results.  Below is the code in its entirety.  Is
> there a problem with my indendentation?
>
> a = n = []
> t = """
> 1 2
> 3
> 4 5 6
> 7 8 9 0
> """
>
> d = t.split("\n")
>
> for x in range(1,len(d)-1):
> a.append(d[x].split(" "))
> print a
>
> for k in a:
> n.append([int(v) for v in k])

To see what is happening, insert some print statements, plus something
to slow it down e.g.

for k in a:
print id(a), a
print id(n), n
n.append([int(v) for v in k])
raw_input('Hit Enter to continue ->')

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


Trying to solve a python/mechanize "error 500" http error

2008-07-21 Thread bruce
i'm getting the following error:
mechanize._response.httperror_seek_wrapper: HTTP Error 500:

i'm running python 5.1
and mechanize 0.1.7b

I have no idea as to what I have to change/modify/include to handle this
issue. The link that I'm testing is at the bottom of the page. When I insert
the link into the browser, I actually get an err page.. so, I suspect that
there is a handler that I should be able to modify/use to handle this
situation...

Thoughts/Comments will be greatly appreciated...

Thanks


the output is:

www =  www.1800ink.com
url2= http://www.quantcast.com/www.1800ink.com/traffic
Traceback (most recent call last):
  File "./reseller_scrape_child.py", line 288, in 
q1 = shopfuncs.quant(rhref)
  File "/adkiller/shopfuncs.py", line 56, in quant
br.open(url2)
  File "build/bdist.linux-x86_64/egg/mechanize/_mechanize.py", line 203, in
open
  File "build/bdist.linux-x86_64/egg/mechanize/_mechanize.py", line 254, in
_mech_open
mechanize._response.httperror_seek_wrapper: HTTP Error 500:
[EMAIL PROTECTED] adkiller]# ./reseller_scrape_child.py



my code segment looks like:

from  mechanize import Browser
import mechanize
br = Browser()
user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
values1 = {'name' : 'Michael Foord',
  'location' : 'Northampton',
  'language' : 'Python' }
headers = { 'User-Agent' : user_agent }

#br.set_cookiejar(cj)
br.set_handle_redirect(True)
br.set_handle_referer(True)
br.set_handle_robots(False)
br.addheaders = [('User-Agent', 'Firefox')]

url2 ="http://www.quantcast.com//traffic";
#gets the page (url) from the quantcast app
url2=url2.replace("",url)
print "url2=",url2
br.open(url2)

===

this works ok for most of the sites.. but something weird is happening with
the actual page:
http://www.quantcast.com/www.1800ink.com/traffic


thanks...



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


Trying to solve a python/mechanize "error 500" http error

2008-07-21 Thread bruce
i'm getting the following error:
mechanize._response.httperror_seek_wrapper: HTTP Error 500:

i'm running python 5.1
and mechanize 0.1.7b

I have no idea as to what I have to change/modify/include to handle this
issue. The link that I'm testing is at the bottom of the page. When I insert
the link into the browser, I actually get an err page.. so, I suspect that
there is a handler that I should be able to modify/use to handle this
situation...

Thoughts/Comments will be greatly appreciated...

Thanks


the output is:

www =  www.1800ink.com
url2= http://www.quantcast.com/www.1800ink.com/traffic
Traceback (most recent call last):
  File "./reseller_scrape_child.py", line 288, in 
q1 = shopfuncs.quant(rhref)
  File "/adkiller/shopfuncs.py", line 56, in quant
br.open(url2)
  File "build/bdist.linux-x86_64/egg/mechanize/_mechanize.py", line 203, in
open
  File "build/bdist.linux-x86_64/egg/mechanize/_mechanize.py", line 254, in
_mech_open
mechanize._response.httperror_seek_wrapper: HTTP Error 500:
[EMAIL PROTECTED] adkiller]# ./reseller_scrape_child.py



my code segment looks like:

from  mechanize import Browser
import mechanize
br = Browser()
user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
values1 = {'name' : 'Michael Foord',
  'location' : 'Northampton',
  'language' : 'Python' }
headers = { 'User-Agent' : user_agent }

#br.set_cookiejar(cj)
br.set_handle_redirect(True)
br.set_handle_referer(True)
br.set_handle_robots(False)
br.addheaders = [('User-Agent', 'Firefox')]

url2 ="http://www.quantcast.com//traffic";
#gets the page (url) from the quantcast app
url2=url2.replace("",url)
print "url2=",url2
br.open(url2)

===

this works ok for most of the sites.. but something weird is happening with
the actual page:
http://www.quantcast.com/www.1800ink.com/traffic


thanks...


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


Re: Converting List of String to Integer

2008-07-21 Thread Samir
On Jul 21, 3:20 pm, Gary Herron <[EMAIL PROTECTED]> wrote:
> Samir wrote:
> > Hi Everyone,
>
> > I am relatively new to Python so please forgive me for what seems like
> > a basic question.
>
> > Assume that I have a list, a, composed of nested lists with string
> > representations of integers, such that
>
> > a = [['1', '2'], ['3'], ['4', '5', '6'], ['7', '8', '9', '0']]
>
> > I would like to convert this to a similar list, b, where the values
> > are represented by integers, such as
>
> > b = [[1, 2], [3], [4, 5, 6], [7, 8, 9, 0]]
>
> > I have unsuccessfully tried the following code:
>
> > n = []
> > for k in a:
> >     n.append([int(v) for v in k])
> > print n
>
> > Does anyone know what I am doing wrong?
>
> > Thanks in advance.
>
> > Samir
> > --
> >http://mail.python.org/mailman/listinfo/python-list
>
> You didn't tell us how it failed for you, so I can't guess what's wrong.
>
> However, your code works for me:
>
>  >>> a = [['1', '2'], ['3'], ['4', '5', '6'], ['7', '8', '9', '0']]
>  >>> n = []
>  >>> for k in a:
> ...    n.append([int(v) for v in k])
> ...
>  >>> print n
> [[1, 2], [3], [4, 5, 6], [7, 8, 9, 0]]
>
> (Although you seem to have confused variables b and n.)
>
> Gary Herron- Hide quoted text -
>
> - Show quoted text -

Hi Gary,

Thanks for your quick response (and sorry about mixing up b and n).
For some reason, the logic I posted seems to work ok while I'm using
the Python shell, but when used in my code, the program just hangs.
It never outputs the results.  Below is the code in its entirety.  Is
there a problem with my indendentation?

a = n = []
t = """
1 2
3
4 5 6
7 8 9 0
"""

d = t.split("\n")

for x in range(1,len(d)-1):
a.append(d[x].split(" "))
print a

for k in a:
n.append([int(v) for v in k])

print n

Thanks again.

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


Re: persistent deque (continued)

2008-07-21 Thread Larry Bates

castironpi wrote:

Some time ago, I was asking about the feasibility of a persistent
deque, a double-ended queue.

It runs into the typical space allocation problems.  If you're storing
a pickle, you have to allocate and fragment the file you've opened,
since pickles can be variable-length strings; i.e. if the new data is
too long, blank out its entry, and grow the file.  If you're storing a
data-type, you lose Python's dynamic-type advantages, as well as its
long integers, as they can be any length.  If you change the object in
the deque, such as when using any mutable type, you have to update the
container too.

Does anyone have any experience storing pickles (I am aware of the
similarities to shelf) to a database?
Can the file system facilitate the variable-length string problem?
How feasible is a length-of-length - length - data solution to the
unbounded integer problem?
Is there any alternative to completely re-pickling a large (say 1k
pickled) object you only change slightly?
What other issues are there?
Is a hybrid-storage type possible, that stores the contents of its
Python-allocated memory block to disk, including reference count, even
if it's a lot slower?  The object could not contain any references to
objects not allocated on disk.

A first approach is for the file to look like this:

00 data 01 data 02
01 data 03 data 04
02 data 05 data 06

Append would add:

03 data 07 data 08

AppendLeft would add:

-01 data 09 data 0a

Pop would remove 03, PopLeft would remove -01.  You would need a
length-and-head index to make 'rotate' available.  Remove would run a
worst-case risk of renumbering half of the indices stored, plus a
rotate.


It is so much easier to implement this using a database table that IMHO most 
people would go that route.


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


Re: scanf in python

2008-07-21 Thread AMD


I'm pretty certain python won't grow an additional operator for this. 
Yet you are free to create a scanf-implementation as 3rd-party-module.


IMHO the usability of the approach is very limited though. First of all, 
the need to capture more than one input token is *very* seldom - nearly 
all commandline-tools I know that do require interactive user-input 
(like the linux kernel config tool) do so by providing either 
line-by-line value entry (including defaults, something you can't do 
with your approach), or even dialog-centric value entry with curses.


So - I doubt you will gather much momentum on this. Good luck though.


Diez


Actually it is quite common, it is used for processing of files not for 
reading parameters. You can use it whenever you need to read a simple 
csv file or fixed format file which contains many lines with several 
fields per line.
The advantage of the approach is that it combines the parsing and 
conversion of the fields into one operation.
Another advantage of using simple formatting strings is that it allows 
for easy translation of these lines, just like you have with the % 
operator for output. I don't see why python can have an operator for 
output but it can't have one for input, it's just not symmetrical.
I don´t see why you can't use this method for line-by-line value entry, 
just add \n between your %s or %d.
The method is quite versatile and much simpler than regular expressions 
plus conversion afterwards.


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


Re: Python Written in C?

2008-07-21 Thread Johannes Bauer

Mensanator schrieb:


You want cool?
THIS is cool:

j = ((invert(xyz[1]-xyz[0],xyz[1]**(k-1))*(xyz[1]**(k-1)-prev_gen[2]))
% xyz[1]**(k-1))/xyz[1]**(k-2)


You call it cool, I call it NameError: name 'invert' is not defined.

Regards,
Johannes

--
"Wer etwas kritisiert muss es noch lange nicht selber besser können. Es
reicht zu wissen, daß andere es besser können und andere es auch
besser machen um einen Vergleich zu bringen." - Wolfgang Gerber
  in de.sci.electronics <[EMAIL PROTECTED]>
--
http://mail.python.org/mailman/listinfo/python-list

Re: Change PC to Win or Windows

2008-07-21 Thread Lie

> It very much IS the point.  Language evolves based on common usage
> patterns of the people who use it.

That is inarguably correct.

> The term "PC" is commonly used in English, in the United States
> and other English speaking countries, to mean a computer running
> Microsoft Windows.

As far as I am aware, they're like that because most people aren't
even aware that there are other OSes than Microsoft Windows. If the
world is still back in the 80s or 90s when people that use computers
means they're knowledgeable enough about computer, PCs would be either
applied to "all kinds of small computer/microcomputer" or only to "IBM-
branded microcomputers", the latter because PC is originally IBM's
marketing term, the former is a natural expansion of the meaning since
"Personal Computer" is a neutral term, unlike marketing terms like:
"TravelMate", "Lifebook", "MacBook", "GeForce", etc. "Personal
Computer" is more like the term "Mobile Phone" which is brand-neutral
and is usable by any brand, regardless of how the term originated.

The reason why the world hasn't evolved to the two predictable cases
("all kinds of microcomputers" or "IBM-PC and clones"), is what I'll
explain below.

> That's a simple fact that you can not escape, no matter how
> much you may not like it (it just so happens that I also don't l
> ike it, but I realized long ago the futility of arguing against
> its usage).  It's still a fact, and I described roughly how
> that fact came to be.

> It wasn't something that Apple started; it's been used this way
> in increasingly common usage for at least 20 years, although
> exactly what combination of hardware and software was being
> refered to as a "PC" has evolved over that timeframe.

Apple popularizes the term by explicit marketing, but the real blame
is to Microsoft's dominance, though it is without their explicit
consent, blessing, or resistance. Not entirely Microsoft's fault for
being dominant, but their dominance in the lower level users makes
those lower level user unaware of other OSes and applied the term PC
to Windows-based computers. When other OSes are gaining popularity
again (i.e. when Microsoft starts to lose its total and complete
dominance, i.e. around right now) the term's meaning become a huge
matter because people associated the term with Microsoft Windows (i.e.
software), not with IBM-PC and its clones anymore (i.e. hardware).

On Jul 21, 11:50 pm, Derek Martin <[EMAIL PROTECTED]> wrote:
> On Sat, Jul 19, 2008 at 02:56:07AM -0700, Lie wrote:
> > government, etc. IBM PC is one of the first computers that ordinary
> > people could possess, when IBM-clones appeared on the market, they're
> > referred as PCs too because they are Personal Computer, a computer
> > that is designed for personal use.
>
> Just to be clear, this statement is WRONG.  PC-clones were so called
> because they were clones of the IBM-PC.  The term is very specific to
> IBM-compatible hardware.  
>
>  http://en.wikipedia.org/wiki/Pc_clone
>
>     IBM PC compatible computers are those generally similar to the
>     original IBM PC, XT, and AT. Such computers used to be referred to
>     as PC clones, or IBM clones since they almost exactly duplicated
>     all the significant features of the PC, XT, or AT internal design,
>     facilitated by various manufacturers' ability to legally reverse
>     engineer the BIOS through cleanroom design.
>
> Wikipedia's article on the personal computer accurately reflects
> the multiple meanings of the term, and points out the common usage
> to mean a Windows box:
>
>  http://en.wikipedia.org/wiki/Personal_computer
>
>     Today a PC may be a desktop computer, a laptop computer or a
>     tablet computer. The most common operating systems are Microsoft
>     Windows, Mac OS X and Linux, while the most common microprocessors
>     are x86 compatible CPUs.  However, the term "PC" is often used
>     only to refer to computers running Microsoft Windows.
>
> So please stop your whining and get used to the idea that THE REST OF
> THE WORLD uses PC to mean a Windows box.

The rest of the world? Not in this part of the world, not in my whole
country at the least...
--
http://mail.python.org/mailman/listinfo/python-list


Re: Converting List of String to Integer

2008-07-21 Thread Gary Herron

Samir wrote:

Hi Everyone,

I am relatively new to Python so please forgive me for what seems like
a basic question.

Assume that I have a list, a, composed of nested lists with string
representations of integers, such that

a = [['1', '2'], ['3'], ['4', '5', '6'], ['7', '8', '9', '0']]

I would like to convert this to a similar list, b, where the values
are represented by integers, such as

b = [[1, 2], [3], [4, 5, 6], [7, 8, 9, 0]]

I have unsuccessfully tried the following code:

n = []
for k in a:
n.append([int(v) for v in k])
print n

Does anyone know what I am doing wrong?

Thanks in advance.

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


You didn't tell us how it failed for you, so I can't guess what's wrong.

However, your code works for me:

>>> a = [['1', '2'], ['3'], ['4', '5', '6'], ['7', '8', '9', '0']]
>>> n = []
>>> for k in a:
...n.append([int(v) for v in k])
...
>>> print n
[[1, 2], [3], [4, 5, 6], [7, 8, 9, 0]]

(Although you seem to have confused variables b and n.)

Gary Herron


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


Re: Python Written in C?

2008-07-21 Thread Luis M . González
Let's say you want to build a house...
You can use pre-built bricks and stack them together to build your
walls, or you can cook your own bricks out of clay because hey! clay
is the real thing not those ready-made bricks that anyone can use!
In the end, you'll have a truly original house but you would have
spent 5 years instead of 6 months.

The question is: Is it worth it?

Bceause you can use pre-built bricks instead and, after applying
stucco, nobody will notice you used bricks instead of your own in
house-original-cooked bricks.

Ok, making your own bricks give you more control over the final result
and the way you work with them, but after building two or three
houses, you realize it is very cumbersome and time consuming, and not
really practical for a "real world" builder...
Although making your own bricks could make sense if instead of being a
house builder, you are a bricks vendor.

It is the same with programming languages:
If you are planning to write the next operating system, or a database
management system to be used in mission critical applications by
millions of users, or perhaps a 3D graphics application, you'd better
use C.

Fort anything else, boy, don't lose your time. Use Python, get the job
done with the least delay and have fun.
My two cents...

Luis




On 20 jul, 19:50, [EMAIL PROTECTED] wrote:
> I'm just learning about Python now and it sounds interesting. But I
> just read (on the Wiki page) that mainstream Python was written in C.
> That's what I was searching for: Python was written in what other
> language?
>
> See, my concern was something like: OK, if Python is so hot, then,
> hopefully someone is writing it in assembly language for each MPU chip
> out there. Otherwise, if, say, they've written it in C#, then it looks
> like the REAL, generally useful language to learn is C# and Python is
> akin to Visual Basic or something: a specialty languagewhereas
> REAL WORLD programmers who want to be generally useful go and learn
> C#.
>
> So I was suspecting the Python compiler or interpreter is written in a

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


persistent deque (continued)

2008-07-21 Thread castironpi
Some time ago, I was asking about the feasibility of a persistent
deque, a double-ended queue.

It runs into the typical space allocation problems.  If you're storing
a pickle, you have to allocate and fragment the file you've opened,
since pickles can be variable-length strings; i.e. if the new data is
too long, blank out its entry, and grow the file.  If you're storing a
data-type, you lose Python's dynamic-type advantages, as well as its
long integers, as they can be any length.  If you change the object in
the deque, such as when using any mutable type, you have to update the
container too.

Does anyone have any experience storing pickles (I am aware of the
similarities to shelf) to a database?
Can the file system facilitate the variable-length string problem?
How feasible is a length-of-length - length - data solution to the
unbounded integer problem?
Is there any alternative to completely re-pickling a large (say 1k
pickled) object you only change slightly?
What other issues are there?
Is a hybrid-storage type possible, that stores the contents of its
Python-allocated memory block to disk, including reference count, even
if it's a lot slower?  The object could not contain any references to
objects not allocated on disk.

A first approach is for the file to look like this:

00 data 01 data 02
01 data 03 data 04
02 data 05 data 06

Append would add:

03 data 07 data 08

AppendLeft would add:

-01 data 09 data 0a

Pop would remove 03, PopLeft would remove -01.  You would need a
length-and-head index to make 'rotate' available.  Remove would run a
worst-case risk of renumbering half of the indices stored, plus a
rotate.
--
http://mail.python.org/mailman/listinfo/python-list


Converting List of String to Integer

2008-07-21 Thread Samir
Hi Everyone,

I am relatively new to Python so please forgive me for what seems like
a basic question.

Assume that I have a list, a, composed of nested lists with string
representations of integers, such that

a = [['1', '2'], ['3'], ['4', '5', '6'], ['7', '8', '9', '0']]

I would like to convert this to a similar list, b, where the values
are represented by integers, such as

b = [[1, 2], [3], [4, 5, 6], [7, 8, 9, 0]]

I have unsuccessfully tried the following code:

n = []
for k in a:
n.append([int(v) for v in k])
print n

Does anyone know what I am doing wrong?

Thanks in advance.

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


Re: scanf in python

2008-07-21 Thread Diez B. Roggisch

AMD schrieb:

Hello,

I often need to parse strings which contain a mix of characters, 
integers and floats, the C-language scanf function is very practical for 
this purpose.
I've been looking for such a feature and I have been quite surprised to 
find that it has been discussed as far back as 2001 but never 
implemented. The recommended approach seems to be to use split and then 
atoi or atof or to use regex and then atoi and atof. Both approaches 
seem to be a lot less natural and much more cumbersome than scanf. If 
python already has a % string operator that behaves like printf, why not 
implement either a %% or << string operator to behave like scanf, use 
could be like the followng:


a, b, c = "%d %f %5c" %% "1 2.0 abcde"

or

a, b, c = "%d %f %5c" << "1 2.0 abcde"

%% is closer to the % operator

<< seems more intuitive to me

either of this methods seems to me much simpler than:

lst = "1 2;0 abcde".split()
a = int(lst[0])
b = float(lst[1])
c = lst[2]

or even worse when using regular expressions to parse such simple input.

I like python because it is concise and easy to read and I really think 
it could use such an operator.


I know this has been discussed before and many times, but all previous 
threads I found seem to be dead and I would like to invite further 
investigation of this topic.


I'm pretty certain python won't grow an additional operator for this. 
Yet you are free to create a scanf-implementation as 3rd-party-module.


IMHO the usability of the approach is very limited though. First of all, 
the need to capture more than one input token is *very* seldom - nearly 
all commandline-tools I know that do require interactive user-input 
(like the linux kernel config tool) do so by providing either 
line-by-line value entry (including defaults, something you can't do 
with your approach), or even dialog-centric value entry with curses.


So - I doubt you will gather much momentum on this. Good luck though.


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


Re: interpreter vs. compiled

2008-07-21 Thread castironpi
On Jul 18, 2:13 pm, Dan <[EMAIL PROTECTED]> wrote:
> On Jul 18, 2:17 pm, castironpi <[EMAIL PROTECTED]> wrote:
>
>
>
> > On Jul 17, 11:39 pm, Kay Schluehr <[EMAIL PROTECTED]> wrote:
>
> > > On 18 Jul., 01:15, castironpi <[EMAIL PROTECTED]> wrote:
>
> > > > On Jul 17, 5:37 pm, I V <[EMAIL PROTECTED]> wrote:
>
> > > > > On Thu, 17 Jul 2008 15:08:17 -0700, castironpi wrote:
> > > > > > The Python disassembly is baffling though.
>
> > > > >  y= 3
> > > > >  dis.dis('x=y+1')
>
> > > > > You can't disassemble strings of python source (well, you can, but, as
> > > > > you've seen, the results are not meaningful). You need to compile the
> > > > > source first:
>
> > > > > >>> code = compile('y=x+1','-', 'single')
> > > > > >>> dis.dis(code)
>
> > > > >   1           0 LOAD_NAME                0 (x)
> > > > >               3 LOAD_CONST               0 (1)
> > > > >               6 BINARY_ADD
> > > > >               7 STORE_NAME               1 (y)
> > > > >              10 LOAD_CONST               1 (None)
> > > > >              13 RETURN_VALUE
>
> > > > > You may well find these byte codes more meaningful. Note that there 
> > > > > is a
> > > > > list of opcodes athttp://docs.python.org/lib/bytecodes.html
>
> > > > Oh.  How is the stack represented?
>
> > > As a pointer to a pointer of PyObject structs.
>
> > > > Does it keep track of which stack
> > > > positions (TOS, TOS1, etc.) are in what registers?  Does stack
> > > > manipulation consume processor cycles?
>
> > > Python does not store values in registers. It stores locals in arrays
> > > and accesses them by position ( you can see the positional index in
> > > the disassembly right after the opcode name ) and globals / object
> > > attributes in dicts.
>
> > > For more information you might just download the source distribution
> > > and look for src/Python/ceval.c. This file contains the main
> > > interpreter loop.
>
> > Ah, found it.  The parts that are making sense are:
>
> > register PyObject **stack_pointer;
> > #define TOP()           (stack_pointer[-1])
> > #define BASIC_POP()     (*--stack_pointer)
>
> > ...(line 1159)...
> > w = POP();
> > v = TOP();
> > if (PyInt_CheckExact(v) && PyInt_CheckExact(w)) {
> >         /* INLINE: int + int */
> >         register long a, b, i;
> >         a = PyInt_AS_LONG(v);
> >         b = PyInt_AS_LONG(w);
> >         i = a + b;
> >         if ((i^a) < 0 && (i^b) < 0)
> >                 goto slow_add;
> >         x = PyInt_FromLong(i);
>
> > ... Which is more than I was picturing was involved.  I understand it
> > is also specific to CPython.  Thanks for the pointer to the code.
>
> > My basic question was, what is the difference between compilers and
> > interpreters, and why are interpreters slow?  I'm looking at some of
> > the answer right now in "case BINARY_ADD:".
>
> The basic difference between a (traditional) compiler and an
> interpreter is that a compiler emits (assembly) code for a specific
> machine. Therefore it must know the specifics of the machine (how many
> registers, memory addressing modes, etc), whereas interpreters
> normally define themselves by their conceptual state, that is, a
> virtual machine. The instructions (bytecode) of the virtual machine
> are generally more high-level than real machine instructions, and the
> semantics of the bytecode are implemented by the interpreter, usually
> in a sort-of high level language like C. This means the interpreter
> can run without detailed knowledge of the machine as long as a C
> compiler exists. However, the trade off is that the interpreter
> semantics are not optimized for that machine.
>
> This all gets a little more hairy when you start talking about JITs,
> runtime optimizations, and the like. For a real in-depth look at the
> general topic of interpretation and virtual machines, I'd recommend
> Virtual Machines by Smith and Nair (ISBN:1-55860910-5).
>
> -Dan

You're saying the VM can't compile code.  That makes sense, it's not a
compiler.  Do I understand correctly that JIT does compile to native
code in some cases?

Python: x= y+ 1
Python VM: push, push, add, store
Assembly: load, load, add, store

Except, the assembly doesn't contain the type-checking that
PyInt_AS_LONG does.  But that's not the only thing that stops python
from precompiling to assembly directly.  GNU doesn't come with
Python.  What sorts of minimal information would be necessary to take
from the GNU libs for the user's specific processor, (the one they're
downloading their version of Python for), to move Python to the
further step of outputting the machine code?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python Written in C?

2008-07-21 Thread castironpi
On Jul 20, 11:59 pm, Michael Torrie <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] wrote:
> > I'm not dissing Python, here. Just noting that, if it is written in C,
> > that throws a curve at me in trying to balance the value of learning
> > Python vs. some other major language.
>
> Definitely one of the most non-sequitor statements I have ever heard.
> Actually your entire post doesn't make much sense.  Maybe you are a
> brother bot to castropini?  Perhaps a less-trained one, although none of
> castropini's posts seem to make sense either.  The AI needs a bit of work.

Are you saying Python is not good for writing A.I., or the A.I. isn't
good at writing Python?
--
http://mail.python.org/mailman/listinfo/python-list


Re: automating python programs

2008-07-21 Thread Dan Upton
On Mon, Jul 21, 2008 at 2:12 PM, Zach Hobesh <[EMAIL PROTECTED]> wrote:
> Hi,
>
> I'm trying to figure out how to run a python program on a schedule, maybe
> every half an hour...  Is this possible?
>
> Thanks!
>
> -Zach
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>

On Linux, man cron.
--
http://mail.python.org/mailman/listinfo/python-list


RE: automating python programs

2008-07-21 Thread Ahmed, Shakir
Windows scheduler is one of the option.

 

 

 

 

 



From: [EMAIL PROTECTED]
[mailto:[EMAIL PROTECTED] On Behalf Of
Zach Hobesh
Sent: Monday, July 21, 2008 2:13 PM
To: python-list@python.org
Subject: automating python programs

 

Hi,

I'm trying to figure out how to run a python program on a schedule,
maybe every half an hour...  Is this possible?

Thanks!

-Zach

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

Re: calling source command within python

2008-07-21 Thread arsyed
On Mon, Jul 21, 2008 at 1:59 PM, mk <[EMAIL PROTECTED]> wrote:

> Jie wrote:
>
>> Hi all,
>>
>> i'm having trouble executing os.system('source .bashrc') command
>> within python, it always says that source not found and stuff. Any
>> clue?
>>
>
> It _might_ be that the shell it fires up is /bin/sh and this in turn is not
> bash.
>
> Anyway, it's better to use subprocess / Popen for this sort of operation.
>
>
>
"source" is a bash built-in command and not an executable file. That's why
you need to do something like execute "/bin/bash .bashrc".
--
http://mail.python.org/mailman/listinfo/python-list

automating python programs

2008-07-21 Thread Zach Hobesh
Hi,

I'm trying to figure out how to run a python program on a schedule, maybe
every half an hour...  Is this possible?

Thanks!

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

Re: Python Written in C?

2008-07-21 Thread Dan Upton
On Mon, Jul 21, 2008 at 1:21 PM, Marc 'BlackJack' Rintsch
<[EMAIL PROTECTED]> wrote:
> On Mon, 21 Jul 2008 18:12:54 +0200, mk wrote:
>
>> Seriously, though, would there be any advantage in re-implementing
>> Python in e.g. C++?
>>
>> Not that current implementation is bad, anything but, but if you're not
>> careful, the fact that lists are implemented as C arrays can bite your
>> rear from time to time (it recently bit mine while using lxml). Suppose
>> C++ re-implementation used some other data structure (like linked list,
>> possibly with twists like having an array containing pointers to 1st
>> linked list elements to speed lookups up), which would be a bit slower
>> on average perhaps, but it would behave better re deletion?

Aside (actual reply below): at least for a sorted LL, you're basically
describing Henriksen's algorithm.  They can asymptotically be faster,
based on amortized analysis, but they're somewhat more complicated to
implement.

>
> An operation that most people avoid because of the penalty of "shifting
> down" all elements after the deleted one.  Pythonistas tend to build new
> lists without unwanted elements instead.  I can't even remember when I
> deleted something from a list in the past.
>
> Ciao,
>Marc 'BlackJack' Rintsch

The other side of the equation though is the OO-overhead for C++
programs as compared to C.  (A couple years ago we used an
instrumentation tool to check the instruction count for a simple hello
world program written in C (ie, main(){printf("Hello world!"); return
0;}) and Python (main(){cout<<"hello world"

Re: Almost keywords

2008-07-21 Thread Duncan Booth
[EMAIL PROTECTED] wrote:

> A possible way to avoid such bugs is to turn all those names like
> "list", "map", "filter", "self", etc into keywords. But this may have
> some disadvantages (well, I think I'd like to have "self" as keyword,
> seen how all Python books strong suggest to not use a name different
> from "self").

I'm not convinced by making 'self' a keyword. Forcing the first argument of 
a method to be named 'self' fails for many reasons (e.g. 
classmethod/staticmethod) so I don't really see a benefit to making it 
special in any way.

For the other names though, this would have the advantage of allowing the 
compiler to optimise access to builtins which should provide a slight speed 
improvement and I think would also make life easier for some 
implementations (especially things like 'locals()').

A half-way house would be to generate a warning for any use of a name which 
masks one of the reserved builtins, but only optimise lookups in scopes 
where no such masking is seen by the compiler: this would prevent you 
overriding builtins by injecting a name into the global namespace from 
outside a module but not otherwise break existing code.

Of course any of this would break some existing code and therefore isn't 
going to happen.
--
http://mail.python.org/mailman/listinfo/python-list


Re: calling source command within python

2008-07-21 Thread mk

Jie wrote:

Hi all,

i'm having trouble executing os.system('source .bashrc') command
within python, it always says that source not found and stuff. Any
clue?


It _might_ be that the shell it fires up is /bin/sh and this in turn is 
not bash.


Anyway, it's better to use subprocess / Popen for this sort of operation.


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


Re: Error importing modules with mod_python

2008-07-21 Thread Diez B. Roggisch
Aaron Scott wrote:

> I've installed mod_python, and everything seems to be working, but it
> fails when I try to import another file into the file that's actually
> producing the output. I have these lines at the top of index.py:
> 
> from mod_python import apache
> from storylab import *
> 
> ... and in the directory where index.py resides (/htdocs/python/), I
> have a directory called "storylab". Inside that directory is
> __init__.py. When I try to execute /htdocs/python/index.py, I get the
> following error:
> 
> ---
> 
> MOD_PYTHON ERROR
> ProcessId:  828
> Interpreter:'localhost'
> ServerName: 'localhost'
> DocumentRoot:   'C:/htdocs'
> URI:'/python/index.py'
> Location:   None
> Directory:  'C:/htdocs/python/'
> Filename:   'C:/htdocs/python/index.py'
> PathInfo:   ''
> Phase:  'PythonHandler'
> Handler:'index'
> 
> Traceback (most recent call last):
> 
>   File "C:\Python25\lib\site-packages\mod_python\importer.py", line
> 1537, in HandlerDispatch
> default=default_handler, arg=req, silent=hlist.silent)
> 
>   File "C:\Python25\lib\site-packages\mod_python\importer.py", line
> 1202, in _process_target
> module = import_module(module_name, path=path)
> 
>   File "C:\Python25\lib\site-packages\mod_python\importer.py", line
> 296, in import_module
> log, import_path)
> 
>   File "C:\Python25\lib\site-packages\mod_python\importer.py", line
> 680, in import_module
> execfile(file, module.__dict__)
> 
>   File "C:\htdocs\python\index.py", line 2, in 
> from storylab import *
> 
> ImportError: No module named storylab
> 
> ---
> 
> What am I doing wrong? Any insight would be greatly appreciated.

You need to tell python that it should add the path your storylab-module is
residing in to the sys.path-list of module locations.

There are a bunch of ways to do so:

 - in your main-script, import sys, and append the proper path to sys.path
 - add a .pth-file into python's site-packages that points to the location
 - set the environment variable PYTHONPATH 
 - use distutils or setuptools to proper install the module.

Google will help you to find additional information about the above
mentioned concepts.

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


Re: Seriously, though, about LLVM

2008-07-21 Thread mk

Fredrik Lundh wrote:

mk wrote:

This project has gained some publicity. There's IronPython, right, so 
has anybody thought about implementing Python using LLVM as backend, 
as it seems not out of question at all?


you mean like:

http://llvm.org/ProjectsWithLLVM/#pypy

?


No, I don't mean "Python written in Python", with whatever backend.


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


Error importing modules with mod_python

2008-07-21 Thread Aaron Scott
I've installed mod_python, and everything seems to be working, but it
fails when I try to import another file into the file that's actually
producing the output. I have these lines at the top of index.py:

from mod_python import apache
from storylab import *

... and in the directory where index.py resides (/htdocs/python/), I
have a directory called "storylab". Inside that directory is
__init__.py. When I try to execute /htdocs/python/index.py, I get the
following error:

---

MOD_PYTHON ERROR
ProcessId:  828
Interpreter:'localhost'
ServerName: 'localhost'
DocumentRoot:   'C:/htdocs'
URI:'/python/index.py'
Location:   None
Directory:  'C:/htdocs/python/'
Filename:   'C:/htdocs/python/index.py'
PathInfo:   ''
Phase:  'PythonHandler'
Handler:'index'

Traceback (most recent call last):

  File "C:\Python25\lib\site-packages\mod_python\importer.py", line
1537, in HandlerDispatch
default=default_handler, arg=req, silent=hlist.silent)

  File "C:\Python25\lib\site-packages\mod_python\importer.py", line
1202, in _process_target
module = import_module(module_name, path=path)

  File "C:\Python25\lib\site-packages\mod_python\importer.py", line
296, in import_module
log, import_path)

  File "C:\Python25\lib\site-packages\mod_python\importer.py", line
680, in import_module
execfile(file, module.__dict__)

  File "C:\htdocs\python\index.py", line 2, in 
from storylab import *

ImportError: No module named storylab

---

What am I doing wrong? Any insight would be greatly appreciated.

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


Re: Python Written in C?

2008-07-21 Thread Marc 'BlackJack' Rintsch
On Mon, 21 Jul 2008 18:12:54 +0200, mk wrote:

> Seriously, though, would there be any advantage in re-implementing 
> Python in e.g. C++?
> 
> Not that current implementation is bad, anything but, but if you're not 
> careful, the fact that lists are implemented as C arrays can bite your 
> rear from time to time (it recently bit mine while using lxml). Suppose 
> C++ re-implementation used some other data structure (like linked list, 
> possibly with twists like having an array containing pointers to 1st 
> linked list elements to speed lookups up), which would be a bit slower 
> on average perhaps, but it would behave better re deletion?

An operation that most people avoid because of the penalty of "shifting
down" all elements after the deleted one.  Pythonistas tend to build new
lists without unwanted elements instead.  I can't even remember when I
deleted something from a list in the past.

Ciao,
Marc 'BlackJack' Rintsch
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python Written in C?

2008-07-21 Thread David C. Ullrich
In article <[EMAIL PROTECTED]>,
 Erik Max Francis <[EMAIL PROTECTED]> wrote:

> [EMAIL PROTECTED] wrote:
> 
> > I'm just learning about Python now and it sounds interesting. But I
> > just read (on the Wiki page) that mainstream Python was written in C.
> > That's what I was searching for: Python was written in what other
> > language?
> > 
> > See, my concern was something like: OK, if Python is so hot, then,
> > hopefully someone is writing it in assembly language for each MPU chip
> > out there. Otherwise, if, say, they've written it in C#, then it looks
> > like the REAL, generally useful language to learn is C# and Python is
> > akin to Visual Basic or something: a specialty languagewhereas
> > REAL WORLD programmers who want to be generally useful go and learn
> > C#.
> 
> Psst.  What language do you think the primary implementations of C# is 
> written in?

I know, I know, call on me!

Object Pascal, obviously.

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


Re: Python Written in C?

2008-07-21 Thread Marc 'BlackJack' Rintsch
On Mon, 21 Jul 2008 17:06:03 +0100, Tim Golden wrote:

> mk wrote:
>
>> Wrong! Real programmers can program using only Touring machine
> 
> Is that some kind of bicycle?

Maybe it's a Turing machine after Bicycle Repair Man got his hands on it!?

Ciao,
Marc 'BlackJack' Rintsch
--
http://mail.python.org/mailman/listinfo/python-list


Re: how to create GUI dynamically

2008-07-21 Thread Peter Wang
On Jul 21, 8:19 am, [EMAIL PROTECTED] wrote:
> Hi;
>
> i m working on a project where i need  run time creation of GUI.
>
> i have some no. of entities for which i want checkboxes in front of
> them which can be checked/ unchecked by user.
>
> But the problem is that the number and name of entities is not fixed
> and it depends on the file which is used as input.
>
> So is there any way to tackle this problem.
>
> By the way ; i use Boa constructor (zope editor) for GUI now.
>
> regards
> pawan pundir

You should check out Traits and Traits UI:
http://code.enthought.com/projects/traits/examples.php

It allows you to dynamically create views and UIs in an easy,
declarative manner.  It is also powerful enough to build much more
complex interactions and dialogs.  It currently supports both WX and
Qt toolkits.

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


Re: how to create GUI dynamically

2008-07-21 Thread Larry Bates

[EMAIL PROTECTED] wrote:

Hi;

i m working on a project where i need  run time creation of GUI.

i have some no. of entities for which i want checkboxes in front of
them which can be checked/ unchecked by user.

But the problem is that the number and name of entities is not fixed
and it depends on the file which is used as input.

So is there any way to tackle this problem.

By the way ; i use Boa constructor (zope editor) for GUI now.

regards
pawan pundir


All the GUI tookits (Tkinter, wxWindows, QT) allow you to build the GUI 
dynamically.

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


Re: Please recommend a RPC system working with twisted.

2008-07-21 Thread Larry Bates

??? wrote:

Hi all,

I'm looking for an RPC system working with twisted.

1. Binary.  I want it run faster than any xml based RPC.

2. Bidirectional.  Unlike  HTTP, on which the client has to poll the
sever for events, the server should "call" the client's method to
notify events.

3. C/Python support.  Part of the system shall be written in C.

4. Could easily integrated  with twisted.

Unfortunately, there seems no such resolution existed.  So maybe I
have to give up some requirements.

---

It would be wonderful if ICE could integrate with twisted!


Twisted Perspective Broker?

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


scanf in python

2008-07-21 Thread AMD

Hello,

I often need to parse strings which contain a mix of characters, 
integers and floats, the C-language scanf function is very practical for 
this purpose.
I've been looking for such a feature and I have been quite surprised to 
find that it has been discussed as far back as 2001 but never 
implemented. The recommended approach seems to be to use split and then 
atoi or atof or to use regex and then atoi and atof. Both approaches 
seem to be a lot less natural and much more cumbersome than scanf. If 
python already has a % string operator that behaves like printf, why not 
implement either a %% or << string operator to behave like scanf, use 
could be like the followng:


a, b, c = "%d %f %5c" %% "1 2.0 abcde"

or

a, b, c = "%d %f %5c" << "1 2.0 abcde"

%% is closer to the % operator

<< seems more intuitive to me

either of this methods seems to me much simpler than:

lst = "1 2;0 abcde".split()
a = int(lst[0])
b = float(lst[1])
c = lst[2]

or even worse when using regular expressions to parse such simple input.

I like python because it is concise and easy to read and I really think 
it could use such an operator.


I know this has been discussed before and many times, but all previous 
threads I found seem to be dead and I would like to invite further 
investigation of this topic.


Cheers,

André M. Descombes
--
http://mail.python.org/mailman/listinfo/python-list


Re: Change PC to Win or Windows

2008-07-21 Thread Derek Martin
On Sat, Jul 19, 2008 at 02:56:07AM -0700, Lie wrote:
> government, etc. IBM PC is one of the first computers that ordinary
> people could possess, when IBM-clones appeared on the market, they're
> referred as PCs too because they are Personal Computer, a computer
> that is designed for personal use. 

Just to be clear, this statement is WRONG.  PC-clones were so called
because they were clones of the IBM-PC.  The term is very specific to
IBM-compatible hardware.  

  http://en.wikipedia.org/wiki/Pc_clone

IBM PC compatible computers are those generally similar to the
original IBM PC, XT, and AT. Such computers used to be referred to
as PC clones, or IBM clones since they almost exactly duplicated
all the significant features of the PC, XT, or AT internal design,
facilitated by various manufacturers' ability to legally reverse
engineer the BIOS through cleanroom design.

Wikipedia's article on the personal computer accurately reflects
the multiple meanings of the term, and points out the common usage
to mean a Windows box:

  http://en.wikipedia.org/wiki/Personal_computer

Today a PC may be a desktop computer, a laptop computer or a
tablet computer. The most common operating systems are Microsoft
Windows, Mac OS X and Linux, while the most common microprocessors
are x86 compatible CPUs.  However, the term "PC" is often used
only to refer to computers running Microsoft Windows.

So please stop your whining and get used to the idea that THE REST OF
THE WORLD uses PC to mean a Windows box.

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



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

Re: Run as Service

2008-07-21 Thread Larry Bates

[EMAIL PROTECTED] wrote:

I have, in the past, used SRVANY to run a Python app as a Windows
service.  However, now I am interested in distributing my scripts and
want to make it as painless for the end user as possible (hands-off is
best :).  How can you go about running a Python app as a Windows
service without SRVANY?


Pick up a copy of Mark Hammond's book "Python on Win32".  It has an excellent 
chapter on using Win32 extensions to write Windows Services.  Also you might 
consider looking at gmane.comp.python.windows usergroup.


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


  1   2   >