os.walk question

2008-07-23 Thread Lanny
How would one make a list of the files in the top directory
using os.walk.

I need to pick a random file from said list.

Thanks. 



-- Posted on news://freenews.netfront.net - Complaints to [EMAIL PROTECTED] --
--
http://mail.python.org/mailman/listinfo/python-list


Re: Proper way to query user and group database on a Unix host?

2008-07-23 Thread Chris Brannon
Mike MacCana <[EMAIL PROTECTED]> writes:

> Hi folks,
>
> What's the proper way to query the passwd and group database on a Unix
> host? 

Use the pwd and grp modules, respectively.

> ## Get the full group database entry, leave just the user list,
> ## and split the list on comma
> groupname=users
> groupsusers = commands.getoutput('getent group 
> '+groupname).split(':',-1)[3].split(',')

Instead, do this:

import grp
groupname = 'users'
groupusers = grp.getgrnam(groupname)[3]
print 'The group named "users" contains:'
for username in groupusers:
print username

The functions from the grp and pwd modules return tuples.  The docs describe
their formats.

Hope this helps,
-- Chris
--
http://mail.python.org/mailman/listinfo/python-list


Re: sys.stderr.write returns string length in Python 3

2008-07-23 Thread Fredrik Lundh

Alan G Isaac wrote:


Can you give me an example of using the returned value?


it's for consistency with stream objects that support raw I/O (as 
described in the PEP).  when using buffered I/O, you can ignore it.




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


Re: os.walk question

2008-07-23 Thread alex23
On Jul 24, 11:52 am, "Lanny" <[EMAIL PROTECTED]> wrote:
> How would one make a list of the files in the top directory
> using os.walk.
>
> I need to pick a random file from said list.

So you -only- want the files from one directory?

Try: _, _, files = os.walk('/top/folder/here').next()

The single underscore is a convention to indicate we don't care about
those results.

The .next() is needed to step through os.walk once, which will start
at the path you specify.

Hope this helps.

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


Re: Proper way to query user and group database on a Unix host?

2008-07-23 Thread Fredrik Lundh

Mike MacCana wrote:


What's the proper way to query the passwd and group database on a Unix
host? 


I'd like to fetch the users in a group (obviously from name services),
but my many varied searches can't find any reference of someone ever
looking up users on a Unix system, just NT. Weird, I know.


the relevant modules are "pwd", "spwd" and "grp"; see:

http://docs.python.org/lib/unix.html



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


Re: How to replace the values with keys ?

2008-07-23 Thread Fredrik Lundh

"Graps Graps" wrote:


Text2 is a python dictionary containing data as

{0: 'a', 1: 'b', 2: 'c'...}

now I want the data in text1 to be replaced with the keys, say like

0 1
0 2
0 3
0 6
1 2... so on..


someone asked a very similar question not long ago, so maybe you're 
really supposed to figure this out yourself.  I'm sure your teacher 
won't kill you if you ask for a hint.


(if you asked me for a hint, I'd tell you to look for questions about 
dictionaries in the mailing list archives).




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


Re: os.walk question

2008-07-23 Thread Fredrik Lundh

Lanny wrote:


How would one make a list of the files in the top directory
using os.walk.

I need to pick a random file from said list.


if you want a list of files from a single directory, use listdir, not walk:

 >>> import os, random
 >>> random.choice(os.listdir("/"))
 'python25'



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


mean of arobase in python

2008-07-23 Thread Guilhem Faure
Hello,

What means @ in python ?

In this script for exemple (this script return an error in my konsole...)

@f1(arg)
@f2
def func(): pass


I see several script where used this symbol but I can't understand.

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

game programming

2008-07-23 Thread smartx
Game programming became as a box of art and science, the box contains
a lot of arts, musics, sounds, graphics,scenario, math, ai and
physics ...etc.
great department, great skills, great tips, also you can observe your
source is the internet that has a lot of articles a lot of great sites
like gamedev.net, gameinstitute.com, gametutorials.com. all of these
encourage you to be a professional game programmer, for me I love it
so much, it's important to love something, because this will help you
to develop yourself in this domain, I hope for all the best wishes in
game development's journey.





Best wishes for all,
smartx
gptutors.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: mean of arobase in python

2008-07-23 Thread Fredrik Lundh

Guilhem Faure wrote:


What means @ in python ?


usually called "at sign" in english.


In this script for exemple (this script return an error in my konsole...)

@f1(arg)
@f2
def func(): pass

I see several script where used this symbol but I can't understand.


in your example, "f1(arg)" and "f2" are decorators.  the above is 
equivalent to writing


def func():
pass
func = f1(arg)(f2(func))

that is, define a function, and then pass it to the function "f2", and 
then to the function that's returned by calling "f1(arg)".  the final 
value of the "func" variable is whatever the decorators returned.


the decorator functions (f2 and whatever f1(arg) returns) can manipulate
the function being defined, or even replace it with something else.

specification:

http://www.python.org/dev/peps/pep-0318/

some (semi-advanced) articles:

http://www.ibm.com/developerworks/linux/library/l-cpdecor.html
http://www.phyast.pitt.edu/~micheles/python/documentation.html



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


Undefined calling conventions in Python.h

2008-07-23 Thread Jaco Naude
Hi there,

This is my first post over here and I hope someone can give me some
guidance.

I'm trying to embed Python into a Visual C++ 2008 application and I'm
getting linker problems. I've compiled a DLL of the Python source code
using the pythoncode VC++ project in the PCbuild folder of the source
download and this works 100% without any warnings etc. I've done this
in Debug and Release mode without any problems.

When I include python_install_path\include\Python.h in my application
(with the linking setup correctly to the .lib and .dll files generated
by myself) it builds fine. However as soon as I try to call any Python
function (Py_Exit for example) I get linker errors as shown below:

1>application.obj : error LNK2031: unable to generate p/invoke for
"extern "C" void __clrcall Py_Exit(int)" (?Py_Exit@@[EMAIL PROTECTED]);
calling convention missing in metadata
1>frmPythonInterface.obj : error LNK2031: unable to generate p/invoke
for "extern "C" void __clrcall Py_Exit(int)" (?Py_Exit@@[EMAIL PROTECTED]);
calling convention missing in metadata

I'm probably missing something but I can't find any calling convention
details in Python.h or the other headers included in this file. In my
VC++ DLL project I've specified the calling convention as __stdcall. I
know the __clrcall naming convention has to do with managed code in VC+
+ but thats as far as my knowledge on that goes. Should I define the
calling conventions manually? Or is there a setting wrong somewhere in
my application project?

If anybody can give some guidance it would be greatly appreciated.

Thanks
Jaco

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


maximum value in a column of file

2008-07-23 Thread maurizio
which is the best way for the calculation of the maximum value in a 
   column of a file?


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


Re: xpathEval fails for large files

2008-07-23 Thread Kanch
On Jul 23, 11:05 am, Stefan Behnel <[EMAIL PROTECTED]> wrote:
> Kanch wrote:
> > Original file was 18MB, and contained 288328 element attributes for
> > the particular path.
>
> You didn't say how many elements there are in total, but I wouldn't expect
> that to be a problem, unless you have very little free memory (say, way below
> 256MB). I just tried with lxml 2.1 and a 40MB XML file with 300 000 elements
> and it lets the whole Python interpreter take up some 140MB of memory in
> total. Looping over all elements by calling "list(root.iter())" takes a bit
> more than one second on my laptop. That suggests that /any/ solution involving
> lxml (or cElementTree) will do just fine for you.
>
> > I wonder whether for loop will cause a problem in iterating for 288328
> > times.
>
> You are heavily underestimating the power of the Python here.
>
> Stefan

Hi,

thanks for the help. lxml will suit my work. I have not being working
with python for that long. :)

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


Re: Undefined calling conventions in Python.h

2008-07-23 Thread Fredrik Lundh

Jaco Naude wrote:


1>application.obj : error LNK2031: unable to generate p/invoke for
"extern "C" void __clrcall Py_Exit(int)" (?Py_Exit@@[EMAIL PROTECTED]);
calling convention missing in metadata
1>frmPythonInterface.obj : error LNK2031: unable to generate p/invoke
for "extern "C" void __clrcall Py_Exit(int)" (?Py_Exit@@[EMAIL PROTECTED]);
calling convention missing in metadata

I'm probably missing something but I can't find any calling convention
details in Python.h or the other headers included in this file.


the precence of name mangling indicates that your compiler doesn't
understand that Python's a C library, and therefore uses C calling
conventions.  have you managed to override the defaults in some odd
way?



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


Re: maximum value in a column of file

2008-07-23 Thread Fredrik Lundh

maurizio wrote:

which is the best way for the calculation of the maximum value in a
column of a file?


what approach have you tried, and what happened when you tried it?



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


Re: How do I compare files?

2008-07-23 Thread Gerhard Häring

Clay Hobbs wrote:

I am making a program that (with urllib) that downloads two jpeg files
and, if they are different, displays the new one.  I need to find a way
to compare two files in Python.  How is this done?


There's a module in the standard library called filecmp ;-)

-- Gerhard

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


Strange problem ....

2008-07-23 Thread karthikbalaguru
Hi,

I am new to python, Kindly suggest to resolve a problem with a python
file.
What does the below error refer to ?
I use Redhat 9.0, python-2.2.2-26, python-devel-2.2.2-26 and
db4-4.0.14-20.

[EMAIL PROTECTED] processor]# Analyzer processorcycle
/usr/local/SDK/bin/../core/bin/processorlib.py:8
8: Warning: 'yield' will become a reserved keyword in the future
Traceback (most recent call last):
  File "/usr/local/SDK/bin/Analyzer", line 48, in ?
from debuglib import ProcessorInfo
  File "/usr/local/SDK/bin/../core/bin/processorlib.py", line 88
yield ProcessorObjectInfo(child, self.pt)
^
SyntaxError: invalid syntax

Is this error related with the version of python / python-devel that i
use .
Any ideas / tips ?

Thx in advans,
Karthik Balaguru
--
http://mail.python.org/mailman/listinfo/python-list


Re: Strange problem ....

2008-07-23 Thread Simon Brunning
2008/7/23 karthikbalaguru <[EMAIL PROTECTED]>:
> I use Redhat 9.0, python-2.2.2-26, python-devel-2.2.2-26 and
> db4-4.0.14-20.
>
>  File "/usr/local/SDK/bin/../core/bin/processorlib.py", line 88
>yield ProcessorObjectInfo(child, self.pt)
>^
> SyntaxError: invalid syntax
>
> Is this error related with the version of python / python-devel that i
> use .
> Any ideas / tips ?

Yup - generators (and hence the yield statement) were first introduced
in Python 2.2, but in order to maintain backward compatibility, you'll
need this line in any module using them:

from __future__ import generators

As of Python 2.3, this is no longer necessary, and I'd imagine that
whatever you are running was targeted at a post 2.2 release.

-- 
Cheers,
Simon B.
[EMAIL PROTECTED]
http://www.brunningonline.net/simon/blog/
GTalk: simon.brunning | MSN: small_values | Yahoo: smallvalues | Twitter: brunns
--
http://mail.python.org/mailman/listinfo/python-list


Re: Strange problem ....

2008-07-23 Thread Francesco Bochicchio
Il Wed, 23 Jul 2008 01:19:48 -0700, karthikbalaguru ha scritto:

> Hi,
> 
> I am new to python, Kindly suggest to resolve a problem with a python
> file.
> What does the below error refer to ?
> I use Redhat 9.0, python-2.2.2-26, python-devel-2.2.2-26 and
> db4-4.0.14-20.
> 
> [EMAIL PROTECTED] processor]# Analyzer processorcycle
> /usr/local/SDK/bin/../core/bin/processorlib.py:8 8: Warning: 'yield'
> will become a reserved keyword in the future Traceback (most recent call
> last):
>   File "/usr/local/SDK/bin/Analyzer", line 48, in ?
> from debuglib import ProcessorInfo
>   File "/usr/local/SDK/bin/../core/bin/processorlib.py", line 88
> yield ProcessorObjectInfo(child, self.pt)
> ^
> SyntaxError: invalid syntax
> 
> Is this error related with the version of python / python-devel that i
> use .

Yes. Generators (and thus the yield keyword) are not available in python 
2.2.


> Any ideas / tips ?
> 

First try doing: 
from __future__ import generators.
In __future__ package you can find the features which are to become 
standard in the next releases. I don't remember when the generators have 
been introduced but maybe you will be lucky.
 
Otherwhise install a newer version of python.  You can probably do it 
without replacing the one you have, but I'm not using RH and I can't 
thell you how. 


> Thx in advans,
> Karthik Balaguru

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


Re: Uploading an image using PUT

2008-07-23 Thread noelob
Hi All,
I finally figured it out, thanks to Wireshark! I was adding my own
"Content-Length: 50173" header to the request, but httplib appears to
add its own header (also "Content-Length: 50173") which must have been
causing a conflict and making the sever return "HTTP/1.1 400 Bad
Request\r\n". As soon as I removed my own Content-Length header, it
worked!

Regards,
Noel

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


Re: maximum value in a column of file

2008-07-23 Thread Chris
On Jul 23, 9:25 am, maurizio <[EMAIL PROTECTED]> wrote:
>  which is the best way for the calculation of the maximum value in a
>     column of a file?

oddly enough

>>> help(max)
Help on built-in function max in module __builtin__:

max(...)
max(iterable[, key=func]) -> value
max(a, b, c, ...[, key=func]) -> value

With a single iterable argument, return its largest item.
With two or more arguments, return the largest argument.
--
http://mail.python.org/mailman/listinfo/python-list


Is this possible ....

2008-07-23 Thread Stef Mientki

hello,

I'm looking for a way to remove duplicate code.
The problem is this:
In all my modules I've version information,
containing version information, date, author, testconditions etc,
something like this:

Version_Text = [
[ 0.2, '10-02-2008', 'Stef Mientki',
'Test Conditions:', (1,2),
_(0, """
  - scaling and offset is set for each individual signal
  - Time history window for 1 signal with min/max display
  - set attributes for all signals at once
""") ],

[ 0.1, '04-11-2007', 'Stef Mientki',
'Test Conditions:', (1,),
"""
   - orginal release
""" ]
]

Now I've made modules that can generate docs, a library manager, etc,
and that even in different languages.

But for the simple case I would like to have a simple function, which 
just displays the version number.

So in each module, there is a function:

def version () :
 return ( version_text [0] [0] )

But is there a way to avoid the placing of this function "version" in 
each module,

and still use a simple call like:
 .version()


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


Re: Re: maximum value in a column of file

2008-07-23 Thread maurizio

i tryed to use the module max of numpy,
the problem is that i don't know how to put the column of the file in an 
array.

(i'm new in phyton).
anyway if you think there is a better way.

Fredrik Lundh wrote:
maurizio 
wrote:


which is the best way for the calculation of the maximum value in 
acolumn of a file?


what approach have you tried, and what happened when you tried it?






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


Re: Is this possible ....

2008-07-23 Thread Paul Hankin
On Jul 23, 9:58 am, Stef Mientki <[EMAIL PROTECTED]> wrote:
> hello,
>
> I'm looking for a way to remove duplicate code.
> The problem is this:
> In all my modules I've version information,
> containing version information, date, author, testconditions etc,
> something like this:
>
> Version_Text = [
> [ 0.2, '10-02-2008', 'Stef Mientki',
> 'Test Conditions:', (1,2),
> _(0, """
>    - scaling and offset is set for each individual signal
>    - Time history window for 1 signal with min/max display
>    - set attributes for all signals at once
> """) ],
>
> [ 0.1, '04-11-2007', 'Stef Mientki',
> 'Test Conditions:', (1,),
> """
>     - orginal release
> """ ]
> ]
>
> Now I've made modules that can generate docs, a library manager, etc,
> and that even in different languages.
>
> But for the simple case I would like to have a simple function, which
> just displays the version number.
> So in each module, there is a function:
>
> def version () :
>   return ( version_text [0] [0] )
>
> But is there a way to avoid the placing of this function "version" in
> each module,
> and still use a simple call like:
>   .version()

You could use version() instead of module.version(), and just
declare 'version' in one place. Presumably you already have a module
for getting the metadata out of one of your modules; perhaps it could
go in there?

def version(module):
return getattr(module, 'Version_Text')[0][0]

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


Re: software engineering foundations?

2008-07-23 Thread Fredrik Lundh

[EMAIL PROTECTED] wrote:


In my work I have from time-to-time had to pick up and maintain
scripts (generally shell/Python stuff) which non-professional programmers
have written.  It's never what you would call a "pleasant" task.


And yes, for the specific art of writing code that others might have to 
read, see this short essay:


   http://www.perforce.com/perforce/papers/prettycode.html



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


Re: maximum value in a column of file

2008-07-23 Thread Michiel Overtoom
Maurizio wrote...

> the problem is that i don't know how to put the column of the file in an 
> array. (i'm new in phyton).

Give us an example of how your file looks, and what you want to 
extract from it, so that we don't have to guess.

Greetings,

-- 
"The ability of the OSS process to collect and harness
the collective IQ of thousands of individuals across
the Internet is simply amazing." - Vinod Vallopillil
http://www.catb.org/~esr/halloween/halloween4.html

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


Re: maximum value in a column of file

2008-07-23 Thread Fredrik Lundh

maurizio wrote:


i tryed to use the module max of numpy,
the problem is that i don't know how to put the column of the file in an 
array.

(i'm new in phyton).
anyway if you think there is a better way.


What kind of file is it?  Did you pick numpy because you want to do 
matrix operations (beyond just finding a maximum value), or was it just 
the first thing you stumbled upon when researching the problem?


A simple pattern for finding the maximum value in a file, using only 
plain Python code, is:


max_value = ... some very small value ...
for line in file:
 value = ... extract value from line ...
 if value > max_value:
 max_value = value

If it's not obvious what "some very small value" is, given the range of 
data you're working with, you can do


max_value = None
for line in file:
 value = ... extract value from line ...
 if max_value is None or value > max_value:
 max_value = value

instead (this leaves max_value set to None if the file is empty)

A more experienced Python hacker might write

def get_all_values(file):
for line in file:
value = ... extract value from line ...
yield value

...

max_value = max(get_all_values(file))

instead.  But this still leaves us with the problem of extracting the 
value.  The best way to do that depends on the kind of files you're 
working with; for fixed-format text files, you could use string slicing 
and int/float for conversion (e.g. "value = float(line[10:20])", see the 
tutorial for details); for other text formats, you could use 
split/partition or regular expressions, or maybe an existing module 
(such as "csv"); for binary formats, there's a large

number of existing tools.

And if you really want to use numpy for other reasons than just getting 
a maximum value from a column, there's plenty of stuff in NumPy and 
SciPy (http://www.scipy.org/) that might be useful.


So, in other words, I guess we still need more info.



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


Re: Function editing with Vim throws IndentError

2008-07-23 Thread Thomas Troeger

ptn wrote:

Hi everybody,

I have a weird problem.  Say I have a .py file with some functions in
it, like this:


[...]


Could someone provide some pointers?

Thanks,

Pablo Torres N.


Have you enabled the `list' option to see which characters are acutally 
on the lines of interest? Try out `:set list' and see the contents! 
Otherwise helpful is `ga' to see the code values. Of course this will 
not tell you why it is going wrong, but maybe it helps you to determine 
what is going wrong :-)

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


Re: Undefined calling conventions in Python.h

2008-07-23 Thread Jaco Naude
On Jul 23, 9:59 am, Fredrik Lundh <[EMAIL PROTECTED]> wrote:
> Jaco Naude wrote:
> > 1>application.obj : error LNK2031: unable to generate p/invoke for
> > "extern "C" void __clrcall Py_Exit(int)" (?Py_Exit@@[EMAIL PROTECTED]);
> > calling convention missing in metadata
> > 1>frmPythonInterface.obj : error LNK2031: unable to generate p/invoke
> > for "extern "C" void __clrcall Py_Exit(int)" (?Py_Exit@@[EMAIL PROTECTED]);
> > calling convention missing in metadata
>
> > I'm probably missing something but I can't find any calling convention
> > details in Python.h or the other headers included in this file.
>
> the precence of name mangling indicates that your compiler doesn't
> understand that Python's a C library, and therefore uses C calling
> conventions.  have you managed to override the defaults in some odd
> way?
>
> 

good point. I agree that the problem is probably due to name mangling.
I'm not sure how its possible to tell the application that the DLL is
a C dll? I've looked at the DLL using Dependency Walker and the
functions in the DLL are clean (Thus no name mangling used).

How do I tell Visual C++ that the DLL is a C dll? I thought it should
be in Python.h but this line appears at the top of the file:

/* Since this is a "meta-include" file, no #ifdef __cplusplus / extern
"C" { */

Thanks for the help
Jaco


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


Re: Undefined calling conventions in Python.h

2008-07-23 Thread Fredrik Lundh

Jaco Naude wrote:


good point. I agree that the problem is probably due to name mangling.
I'm not sure how its possible to tell the application that the DLL is
a C dll? I've looked at the DLL using Dependency Walker and the
functions in the DLL are clean (Thus no name mangling used).

>

How do I tell Visual C++ that the DLL is a C dll? I thought it should
be in Python.h but this line appears at the top of the file:

/* Since this is a "meta-include" file, no #ifdef __cplusplus / extern
"C" { */


All the individual includes are wrapped in the usual

#ifdef __cplusplus
extern "C" {
#endif

stuff, so the compiler should default to C bindings, without you having 
to do anything.  Unfortunately, I haven't used VS 2008, but I find it 
hard to believe that they've messed this up completely, and a quick 
googling indicates that people are using it with Python without trouble.


Maybe there's some override in your project settings caused by some 
other parts of your project?  (or an #undef __cplusplus somewhere, perhaps?)




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


Re: Re: maximum value in a column of file

2008-07-23 Thread maurizio

thank you for your answer
actually i've to do some statistics (maximum,minimum,mean,standard 
deviation,) of a file of data in which each column is a particular 
type of data. (the file is a tab separated value).
I was trying to do this by using python (usually i work with fortran or 
bash, but i'm learning python), that the reason why i tried to use numpy.


Fredrik Lundh wrote:
maurizio 
wrote:



i tryed to use the module max of numpy,
the problem is that i don't know how to put the column of the file in 
an array.

(i'm new in phyton).
anyway if you think there is a better way.


What kind of file is it?  Did you pick numpy because you want to do 
matrix operations (beyond just finding a maximum value), or was it 
just the first thing you stumbled upon when researching the problem?


A simple pattern for finding the maximum value in a file, using only 
plain Python code, is:


max_value = ... some very small value ...
for line in file:
 value = ... extract value from line ...
 if value > max_value:
 max_value = value

If it's not obvious what "some very small value" is, given the range 
of data you're working with, you can do


max_value = None
for line in file:
 value = ... extract value from line ...
 if max_value is None or value > max_value:
 max_value = value

instead (this leaves max_value set to None if the file is empty)

A more experienced Python hacker might write

def get_all_values(file):
for line in file:
value = ... extract value from line ...
yield value

...

max_value = max(get_all_values(file))

instead.  But this still leaves us with the problem of extracting the 
value.  The best way to do that depends on the kind of files you're 
working with; for fixed-format text files, you could use string 
slicing and int/float for conversion (e.g. "value = 
float(line[10:20])", see the tutorial for details); for other text 
formats, you could use split/partition or regular expressions, or 
maybe an existing module (such as "csv"); for binary formats, there's 
a large

number of existing tools.

And if you really want to use numpy for other reasons than just 
getting a maximum value from a column, there's plenty of stuff in 
NumPy and SciPy (http://www.scipy.org/) that might be useful.


So, in other words, I guess we still need more info.






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


logging into a website using python

2008-07-23 Thread leo davis
Hi,
 
I''m trying achieve the following by running python programs
-login to a website 
-automate filling up web forms 
 
So far I 've tried out the following codes:
import cookielib, urllib, urllib2

login = 'cod45'
password = 'mell'

# Enable cookie support for urllib2
cookiejar = cookielib.CookieJar()
urlOpener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookiejar))

# Send login/password to the site and get the session cookie
values = {'login':login, 'password':password }
data = urllib.urlencode(values)
request = urllib2.Request("https://student-webmail.surrey.ac.uk/webmail/";, data)
url = urlOpener.open(request)  # Our cookiejar automatically receives the 
cookies
page = url.read(50)

# Make sure we are logged in by checking the presence of the cookie "id".
# (which is the cookie containing the session identifier.)
if not 'id' in [cookie.name for cookie in cookiejar]:
    raise ValueError, "Login failed with login=%s, password=%s" % 
(login,password)

print "We are logged in !"
 
 
***I get this error msg:Login failed with login cod45' &  password
 
 
Code 2:
 
import urllib2
theurl = 'www.tek-tips.com'
protocol = 'http://'
username = 'ub007'
password = 'with'

passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
# this creates a password manager
passman.add_password(None, theurl, username, password)
# because we have put None at the start it will always
# use this username/password combination for  urls
# for which `theurl` is a super-url
authhandler = urllib2.HTTPBasicAuthHandler(passman)
# create the AuthHandler
opener = urllib2.build_opener(authhandler)
urllib2.install_opener(opener)
# All calls to urllib2.urlopen will now use our handler
# Make sure not to include the protocol in with the URL, or
# HTTPPasswordMgrWithDefaultRealm will be very confused.
# You must (of course) use it when fetching the page though.
pagehandle = urllib2.urlopen(protocol + theurl)
# authentication is now handled automatically for us
the_page=pagehandle.read()
print the_page
 
 This code prints out the html for  the home page ''www.tek-tips.com'.I was 
expecting it would log me in and take me to the members page.What am i 
missing here?
Why is it that the script doesnt attempt a login?Thanks in advance
 
Cheers
David



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

Re: logging into a website using python

2008-07-23 Thread Fredrik Lundh

leo davis wrote:


I''m trying achieve the following by running python programs

-login to a website
-automate filling up web forms


http://twill.idyll.org/



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


Re: Is this possible ....

2008-07-23 Thread Stef Mientki

thanks Paul,

your solution works very well.

cheers,
Stef


Paul Hankin wrote:

On Jul 23, 9:58 am, Stef Mientki <[EMAIL PROTECTED]> wrote:
  


You could use version() instead of module.version(), and just
declare 'version' in one place. Presumably you already have a module
for getting the metadata out of one of your modules; perhaps it could
go in there?

def version(module):
return getattr(module, 'Version_Text')[0][0]

--
Paul Hankin
  


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


Re: Strange problem ....

2008-07-23 Thread Diez B. Roggisch
karthikbalaguru wrote:

> Hi,
> 
> I am new to python, Kindly suggest to resolve a problem with a python
> file.
> What does the below error refer to ?
> I use Redhat 9.0, python-2.2.2-26, python-devel-2.2.2-26 and
> db4-4.0.14-20.
> 
> [EMAIL PROTECTED] processor]# Analyzer processorcycle
> /usr/local/SDK/bin/../core/bin/processorlib.py:8
> 8: Warning: 'yield' will become a reserved keyword in the future
> Traceback (most recent call last):
>   File "/usr/local/SDK/bin/Analyzer", line 48, in ?
> from debuglib import ProcessorInfo
>   File "/usr/local/SDK/bin/../core/bin/processorlib.py", line 88
> yield ProcessorObjectInfo(child, self.pt)
> ^
> SyntaxError: invalid syntax
> 
> Is this error related with the version of python / python-devel that i
> use .
> Any ideas / tips ?

I asked you yesterday why you are under the impression that your script is
destined for version 2.2. The above error proves: it is *not*. Why don't
you try running it with the installed version 2.4 or whatever fedora ships?

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


Re: Undefined calling conventions in Python.h

2008-07-23 Thread Jaco Naude
On Jul 23, 12:16 pm, Fredrik Lundh <[EMAIL PROTECTED]> wrote:
> Jaco Naude wrote:
> > good point. I agree that the problem is probably due to name mangling.
> > I'm not sure how its possible to tell the application that the DLL is
> > a C dll? I've looked at the DLL using Dependency Walker and the
> > functions in the DLL are clean (Thus no name mangling used).
>
> > How do I tell Visual C++ that the DLL is a C dll? I thought it should
> > be in Python.h but this line appears at the top of the file:
>
> > /* Since this is a "meta-include" file, no #ifdef __cplusplus / extern
> > "C" { */
>
> All the individual includes are wrapped in the usual
>
>      #ifdef __cplusplus
>      extern "C" {
>      #endif
>
> stuff, so the compiler should default to C bindings, without you having
> to do anything.  Unfortunately, I haven't used VS 2008, but I find it
> hard to believe that they've messed this up completely, and a quick
> googling indicates that people are using it with Python without trouble.
>
> Maybe there's some override in your project settings caused by some
> other parts of your project?  (or an #undef __cplusplus somewhere, perhaps?)
>
> 

I've figured out that the names in the DLL are not mangled by looking
into the DLL using dependancy walker. I also figured out that the
problem is on the application's side and not on the dll's side.

What Visual C++ is doing is that it is looking for mangled names since
it does not know the DLL contains C functions. I've managed to work
around this by declaring the Python functions as follows before using
them in the C++ application side:

extern "C"
{
void Py_Initialize(void);
}

This seems to work and the C++ application side is not looking for
mangled names any more. Is this the right way of doing it? It seems
unnecessary to have to declare each Python function you want to use
using the extern "C" way as shown above.

It is probably more of a C++ question it turns out, but I would think
that someone in the Python group would use the Python DLL in C++. The
documentation also suggest that there is no extra work needed when
using C++ rather than C.

Thanks for the help so far.
Jaco
--
http://mail.python.org/mailman/listinfo/python-list


Re: Parsing VHDL with python, where to start.

2008-07-23 Thread c d saunter
Svenn Are Bjerkem ([EMAIL PROTECTED]) wrote:
: Hi,
: I am in the need to write an application for PyQt to visualise the
: structure of a VHDL project I am working on. Looking for a sensible
: way to parse VHDL files and putting them into a data structure that
: PyQt can represent as a tree (or whatever the MVC is supporting)
: through search engines does not give me many hints. From what I know,
: VHDL is not a very easy language to parse. There seems to be a parser
: for perl available, but I do not know if it is wise to use a perl
: module as a template for writing something similar in python.

Hi Sven,

How much of VHDL are you looking to parse?  Are you just looking at files 
intended for synthesis, or at simulation/testbench files as well?

I wrote a basic parser a few years ago for automatically stringing modules 
together, but it was very limited in scope.  I thought VHDL was quite 
simple to parse, it's very rigid.  Having written a basic one I realised 
I'd coded myself into a dead-end as you say.  Maybe not so simple after 
all... :-)

If I started again I'd use pyparsing:
http://pyparsing.wikispaces.com/

Looks like someone is already there in part:
http://pyparsing.wikispaces.com/message/view/home/103973

Regards,
Chris

: My initial idea is to start simple and extend features in my
: application, but I fear that I may start off with wrong ideas how to
: parse and then code myself into a dead-end requiring myself to rewrite
: the whole application in order to get any further. I would start
: finding definitions of entities and the instantiations of these and
: build a tree from a set of external vhdl files stored in a file
: hierarchy. If somebody have a starting point where to get going with a
: task like this, I would be happy to know.

: --
: kind regards,
: Svenn
--
http://mail.python.org/mailman/listinfo/python-list


Re: Undefined calling conventions in Python.h

2008-07-23 Thread Fredrik Lundh

Jaco Naude wrote:


What Visual C++ is doing is that it is looking for mangled names since
it does not know the DLL contains C functions. I've managed to work
around this by declaring the Python functions as follows before using
them in the C++ application side:

extern "C"
{
void Py_Initialize(void);
}

This seems to work and the C++ application side is not looking for
mangled names any more. Is this the right way of doing it? It seems
unnecessary to have to declare each Python function you want to use
using the extern "C" way as shown above.


Eh, are you saying that you're not including the Python.h file?  Because 
it does exactly that, for each and every public function in the C API.



It is probably more of a C++ question it turns out, but I would think
that someone in the Python group would use the Python DLL in C++. The
documentation also suggest that there is no extra work needed when
using C++ rather than C.


Oh, but I do that all the time, without doing any extra work.  Both 
embedding Python in C++ programs and existing it with C++ extensions. 
And I'm definitely not alone.


Here's an actual session, using the version of Visual Studio I happen to 
have on this machine (2003, I think) from the command line:


> more test.cc

#include "Python.h"
#include 

main()
{
Py_Initialize();
PyRun_SimpleString("print 'hello'\n");
Py_Finalize();

std::cout << "world\n";
}

> cl cl -EHsc -MD -I \python25\include test.cc \python25\libs\python25.lib
Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 13.10.3077
for 80x86
Copyright (C) Microsoft Corporation 1984-2002. All rights reserved.

...

> test
hello
world

If you cannot get the same console program to work in your compiler 
setup, something's wrong with your configuration.




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


Re: Undefined calling conventions in Python.h

2008-07-23 Thread Fredrik Lundh

Fredrik Lundh wrote:


 > cl cl -EHsc -MD -I \python25\include test.cc \python25\libs\python25.lib


cut and paste error there: the "cl cl" should be just one "cl", of course.

and just for the record/google, if I

1) don't include the header file, I get

test.cc(5) : error C3861: 'Py_Initialize': identifier not found, even 
with argument-dependent lookup


2) attempt to undef the __cplusplus macro, I get

test.cc(1) : warning C4117: macro name '__cplusplus' is reserved, 
'#undef' ignored


3) cut and paste declarations from the header files to my own file 
instead of including the files, ignoring the extern "C" part, I get


test.obj : error LNK2019: unresolved external symbol "int __cdecl 
Py_Finalize(void)" (?Py_Finalize@@YAHXZ) referenced in function _main


which looks pretty similar to the errors posted earlier.



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


Re: os.walk question

2008-07-23 Thread alex23
On Jul 23, 5:22 pm, Fredrik Lundh <[EMAIL PROTECTED]> wrote:
> if you want a list of files from a single directory, use listdir, not walk:
>
>       >>> import os, random
>       >>> random.choice(os.listdir("/"))
>       'python25'

This will include folders as well, though, which isn't what the OP
asked for.

>>> import os, random
>>> root = "/"
>>> random.choice([f for f in os.listdir(root) if 
>>> os.path.isfile(os.path.join(root, f))])
'initrd.img'

It just seems clunky compared to os.walk :)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Undefined calling conventions in Python.h

2008-07-23 Thread Jaco Naude
On Jul 23, 1:10 pm, Fredrik Lundh <[EMAIL PROTECTED]> wrote:
> Jaco Naude wrote:
> > What Visual C++ is doing is that it is looking for mangled names since
> > it does not know the DLL contains C functions. I've managed to work
> > around this by declaring the Python functions as follows before using
> > them in the C++ application side:
>
> > extern "C"
> > {
> >     void Py_Initialize(void);
> > }
>
> > This seems to work and the C++ application side is not looking for
> > mangled names any more. Is this the right way of doing it? It seems
> > unnecessary to have to declare each Python function you want to use
> > using the extern "C" way as shown above.
>
> Eh, are you saying that you're not including the Python.h file?  Because
> it does exactly that, for each and every public function in the C API.
>
> > It is probably more of a C++ question it turns out, but I would think
> > that someone in the Python group would use the Python DLL in C++. The
> > documentation also suggest that there is no extra work needed when
> > using C++ rather than C.
>
> Oh, but I do that all the time, without doing any extra work.  Both
> embedding Python in C++ programs and existing it with C++ extensions.
> And I'm definitely not alone.
>
> Here's an actual session, using the version of Visual Studio I happen to
> have on this machine (2003, I think) from the command line:
>
>  > more test.cc
>
> #include "Python.h"
> #include 
>
> main()
> {
>      Py_Initialize();
>      PyRun_SimpleString("print 'hello'\n");
>      Py_Finalize();
>
>      std::cout << "world\n";
>
> }
>
>  > cl cl -EHsc -MD -I \python25\include test.cc \python25\libs\python25.lib
> Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 13.10.3077
> for 80x86
> Copyright (C) Microsoft Corporation 1984-2002. All rights reserved.
>
> ...
>
>  > test
> hello
> world
>
> If you cannot get the same console program to work in your compiler
> setup, something's wrong with your configuration.
>
> 

Ok that's probably good news, although it points out that there is
something wrong with my configuration since that does not work. I
would rather sort out the problem that having to defined each function
with a extern "C" command.

That said, let me double check something which might be causing
problems since you will be familiar with this. Which Python.h file do
you include when including the DLL in your programs? The one in the
source distribution of the one in the installation distribution? I've
been including the one in the installation distribution all along.
When I try to include the one in the source distribution it gets up to
the point where it looks for the following include:

#include "pyconfig.h"

This file is not in the same directory as the Python.h file in the
source distribution. Because of this I just used Python.h in the
installation distribution.

Thanks again,
Jaco

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


Re: Undefined calling conventions in Python.h

2008-07-23 Thread Fredrik Lundh

Jaco Naude wrote:


That said, let me double check something which might be causing
problems since you will be familiar with this. Which Python.h file do
you include when including the DLL in your programs? The one in the
source distribution of the one in the installation distribution? I've
been including the one in the installation distribution all along.
When I try to include the one in the source distribution it gets up to
the point where it looks for the following include:

#include "pyconfig.h"

This file is not in the same directory as the Python.h file in the
source distribution. Because of this I just used Python.h in the
installation distribution.


that's just two copies of the same file, as far as I know.

the "pyconfig.h" file contains platform-specific information; it's 
generated from pyconfig.h.in on Unix-style systems, and copied from the 
PC directory on Windows.




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


Re: Undefined calling conventions in Python.h

2008-07-23 Thread Jaco Naude
On Jul 23, 1:50 pm, Jaco Naude <[EMAIL PROTECTED]> wrote:
> On Jul 23, 1:10 pm, Fredrik Lundh <[EMAIL PROTECTED]> wrote:
>
>
>
> > Jaco Naude wrote:
> > > What Visual C++ is doing is that it is looking for mangled names since
> > > it does not know the DLL contains C functions. I've managed to work
> > > around this by declaring the Python functions as follows before using
> > > them in the C++ application side:
>
> > > extern "C"
> > > {
> > >     void Py_Initialize(void);
> > > }
>
> > > This seems to work and the C++ application side is not looking for
> > > mangled names any more. Is this the right way of doing it? It seems
> > > unnecessary to have to declare each Python function you want to use
> > > using the extern "C" way as shown above.
>
> > Eh, are you saying that you're not including the Python.h file?  Because
> > it does exactly that, for each and every public function in the C API.
>
> > > It is probably more of a C++ question it turns out, but I would think
> > > that someone in the Python group would use the Python DLL in C++. The
> > > documentation also suggest that there is no extra work needed when
> > > using C++ rather than C.
>
> > Oh, but I do that all the time, without doing any extra work.  Both
> > embedding Python in C++ programs and existing it with C++ extensions.
> > And I'm definitely not alone.
>
> > Here's an actual session, using the version of Visual Studio I happen to
> > have on this machine (2003, I think) from the command line:
>
> >  > more test.cc
>
> > #include "Python.h"
> > #include 
>
> > main()
> > {
> >      Py_Initialize();
> >      PyRun_SimpleString("print 'hello'\n");
> >      Py_Finalize();
>
> >      std::cout << "world\n";
>
> > }
>
> >  > cl cl -EHsc -MD -I \python25\include test.cc \python25\libs\python25.lib
> > Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 13.10.3077
> > for 80x86
> > Copyright (C) Microsoft Corporation 1984-2002. All rights reserved.
>
> > ...
>
> >  > test
> > hello
> > world
>
> > If you cannot get the same console program to work in your compiler
> > setup, something's wrong with your configuration.
>
> > 
>
> Ok that's probably good news, although it points out that there is
> something wrong with my configuration since that does not work. I
> would rather sort out the problem that having to defined each function
> with a extern "C" command.
>
> That said, let me double check something which might be causing
> problems since you will be familiar with this. Which Python.h file do
> you include when including the DLL in your programs? The one in the
> source distribution of the one in the installation distribution? I've
> been including the one in the installation distribution all along.
> When I try to include the one in the source distribution it gets up to
> the point where it looks for the following include:
>
> #include "pyconfig.h"
>
> This file is not in the same directory as the Python.h file in the
> source distribution. Because of this I just used Python.h in the
> installation distribution.
>
> Thanks again,
> Jaco

I only saw your last message after posting my previous one. Ok, so the
problem is definitely with the include file Python.h. As I said in my
last post, I might be including the wrong one. I would appreciate it
if you can tell me which one it the correct one to use: The one in the
source distribution or the one in the release distribution
(installation done from the .msi file).

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


Re: Undefined calling conventions in Python.h

2008-07-23 Thread Ben Sizer
On Jul 23, 11:43 am, Jaco Naude <[EMAIL PROTECTED]> wrote:
> What Visual C++ is doing is that it is looking for mangled names since
> it does not know the DLL contains C functions. I've managed to work
> around this by declaring the Python functions as follows before using
> them in the C++ application side:
>
> extern "C"
> {
>     void Py_Initialize(void);
>
> }

You should put the extern block around the #include  call
rather than individual functions, as surely the C calling convention
should apply to everything within.

> It is probably more of a C++ question it turns out, but I would think
> that someone in the Python group would use the Python DLL in C++.

More of a Visual C++ question specifically, since the __clrcall prefix
is a MS specific extension (http://msdn.microsoft.com/en-us/library/
ec7sfckb(VS.80).aspx). If you're not using managed code in your app,
disable it in the project/build options. If you are, then perhaps you
just need to specify that you're not with this DLL, though I've never
had to deal with anything like that myself.

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


Re: Python Written in C?

2008-07-23 Thread mk

Marc 'BlackJack' Rintsch wrote:

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. 


Which is exactly what I have done with my big lxml.etree, from which I 
needed to delete some elements: constructed a new tree only with 
elements I wanted. Sure, that works.


There _is_ a minor side effect: nearly doubling memory usage while the 
operation lasts. 99% of the time it's not a problem, sure.


> I can't even remember when I

deleted something from a list in the past.


Still, doesn't that strike you as.. workaround?

I half-got used to it, but it would still be nice not to (practically) 
have to use it.


Enough whining. Gonna eat my quiche and do my Python. :-)




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


Re: os.walk question

2008-07-23 Thread Larry Bates

Fredrik Lundh wrote:

Lanny wrote:


How would one make a list of the files in the top directory
using os.walk.

I need to pick a random file from said list.


if you want a list of files from a single directory, use listdir, not walk:

 >>> import os, random
 >>> random.choice(os.listdir("/"))
 'python25'




Or use glob.

import glob
random.choice([f for f in glob.glob(root, "*")])

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


Re: Python Written in C?

2008-07-23 Thread mk

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.


Doesn't g++ translate C++ into C and then compile C?

Last I heard, most C++ compilers were doing that.




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


Re: Undefined calling conventions in Python.h

2008-07-23 Thread Fredrik Lundh

Ben Sizer wrote:


You should put the extern block around the #include  call
rather than individual functions, as surely the C calling convention
should apply to everything within.


Hello?  Python's include files are C++ safe.  I even posted a complete 
compiler session to show that I'm not making that up.




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


Re: Proper way to query user and group database on a Unix host?

2008-07-23 Thread Sebastian "lunar" Wiesner
Chris Brannon <[EMAIL PROTECTED]>:

Iirc since Python 2.5 these tuples are named ...

> Instead, do this:
> 
> import grp
> groupname = 'users'
> groupusers = grp.getgrnam(groupname)[3]
... thus this line could be written as:

groupusers = grp.getgrnam(groupname).gr_mem

Slightly more readable, imho



-- 
Freedom is always the freedom of dissenters.
  (Rosa Luxemburg)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Undefined calling conventions in Python.h

2008-07-23 Thread Jaco Naude
On Jul 23, 2:08 pm, Ben Sizer <[EMAIL PROTECTED]> wrote:
> On Jul 23, 11:43 am, Jaco Naude <[EMAIL PROTECTED]> wrote:
>
> > What Visual C++ is doing is that it is looking for mangled names since
> > it does not know the DLL contains C functions. I've managed to work
> > around this by declaring the Python functions as follows before using
> > them in the C++ application side:
>
> > extern "C"
> > {
> >     void Py_Initialize(void);
>
> > }
>
> You should put the extern block around the #include  call
> rather than individual functions, as surely the C calling convention
> should apply to everything within.
>
> > It is probably more of a C++ question it turns out, but I would think
> > that someone in the Python group would use the Python DLL in C++.
>
> More of a Visual C++ question specifically, since the __clrcall prefix
> is a MS specific extension (http://msdn.microsoft.com/en-us/library/
> ec7sfckb(VS.80).aspx). If you're not using managed code in your app,
> disable it in the project/build options. If you are, then perhaps you
> just need to specify that you're not with this DLL, though I've never
> had to deal with anything like that myself.
>
> --
> Ben Sizer


Fredrik, thanks for the help. I'm not sure why but it seems to work
now even if I don't include the extern "C" command. It also works with
both Python.h files (after I copied pyconfig.h from the PC folder). So
it seems like everything is working now.

Ben, Thanks for the reply. Good suggestion to place the extern "C"
around the include. I will remember that. It turns out that it works
without that as well in the end. As for the question on managed code:
My application do use managed code. I've been able to turn this off
when I created the Python DLL and it seems to work.

Thanks for all the help,
All the best
Jaco
--
http://mail.python.org/mailman/listinfo/python-list


Re: os.walk question

2008-07-23 Thread Fredrik Lundh

alex23 wrote:


if you want a list of files from a single directory, use listdir, not walk:

  >>> import os, random
  >>> random.choice(os.listdir("/"))
  'python25'


This will include folders as well, though, which isn't what the OP
asked for.


as illustrated by my example (cut and pasted from a windows machine).  oops.

random.choice(filter(os.path.isfile, glob.glob("/*")))

isn't that bad, though.



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


Re: How to replace the values with keys ?

2008-07-23 Thread SvaPs
Hi all..,

I tried with this..

def multiple_replace(text,adict):
rx=re.compile('|'.join(map(re.escape,adict)))
def one_xlat(match):
return adict[match.group(0)]
return rx.sub(one_xlat,text)

print multiple_replace(text,adict)

I am thrown with a error:
Traceback (most recent call last):
  File "", line 1, in 
  File "", line 2, in multiple_replace
TypeError: argument 2 to map() must support iteration


I would be grateful for any comments..

Thankin in advance'
GraPs.


Fredrik Lundh wrote:
> "Graps Graps" wrote:
>
> > Text2 is a python dictionary containing data as
> >
> > {0: 'a', 1: 'b', 2: 'c'...}
> >
> > now I want the data in text1 to be replaced with the keys, say like
> >
> > 0 1
> > 0 2
> > 0 3
> > 0 6
> > 1 2... so on..
>
> someone asked a very similar question not long ago, so maybe you're
> really supposed to figure this out yourself.  I'm sure your teacher
> won't kill you if you ask for a hint.
>
> (if you asked me for a hint, I'd tell you to look for questions about
> dictionaries in the mailing list archives).
>
> 
--
http://mail.python.org/mailman/listinfo/python-list


Re: Undefined calling conventions in Python.h

2008-07-23 Thread Fredrik Lundh

Jaco Naude wrote:


Fredrik, thanks for the help. I'm not sure why but it seems to work
now even if I don't include the extern "C" command. It also works with
both Python.h files (after I copied pyconfig.h from the PC folder). So
it seems like everything is working now.


As it's supposed to do.  It's times like this that you really want to 
use a system that takes snapshots of every single revision of the files 
you work on, so you can see what exactly it was you had done when it 
didn't work (it's more often a "do'h" thing than a heisenbug ;-).


(fwiw, I'm currently trying to track down a problem at a customer site 
when the entire Python application managed to remove itself during a 
test run; the program crashed with "zipimport: IOError" when they tried 
to use a part of the system that did some lazy imports, and when they 
tried to restart the program, neither the startup script nor the ZIP 
archive that contained the bulk of the application were anywhere to be 
seen.  Other PY files in the same directory were left intact.  Fully 
patched Windows XP, clean bill of health from a virus scanner.  If 
anyone's ever experienced anything similar, let me know.)




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


Re: maximum value in a column of file

2008-07-23 Thread Scott David Daniels

maurizio wrote:

thank you for your answer
actually i've to do some statistics (maximum,minimum,mean,standard 
deviation,) of a file of data in which each column is a particular 
type of data. (the file is a tab separated value).
I was trying to do this by using python (usually i work with fortran or 
bash, but i'm learning python), that the reason why i tried to use numpy.



Look into the csv module (comma separated values).  It also can deal
with tab separated values.

--Scott David Daniels
[EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python Embedding Thread

2008-07-23 Thread Graham Dumpleton
On Jul 23, 12:15 pm, "Jaimy Azle" <[EMAIL PROTECTED]> wrote:
> <[EMAIL PROTECTED]> wrote:
> > I fixed the code. This code snippet runs in a seperate thread:
>
> > PyObject *dict=NULL;
> > PyGILState_STATE state = PyGILState_Ensure();
> > dict = CreateMyGlobalDictionary();
>
> > PyRun_String(, Py_file_input, dict, dict);
>
> > ReleaseGlobalDictionary(dict);
>
> > But it still does not work... :-/
>
> Have you initialize interpreter with PyEval_InitThreads? look 
> athttp://www.python.org/doc/1.5.2/api/threads.htmlfor more information.
>
> Oh, btw... I did use python in a bit different scenario than you've
> described. Since you attempt to run different script per-host thread, you
> might need python multiple interpreter support, I suggest you take a 
> lookmod_pythonimplementation.

Please don't look at mod_python. Current versions of mod_python don't
use Python simplified GIL APIs correctly.

  http://issues.apache.org/jira/browse/MODPYTHON-217

Look at mod_wsgi instead, it is closer to the mark, although still has
some not quite cruft in there to workaround mistakes in mod_python for
case where mod_python and mod_wsgi are being loaded together. :-(

Graham

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


Re: maximum value in a column of file

2008-07-23 Thread Fredrik Lundh

maurizio wrote:


thank you for your answer
actually i've to do some statistics (maximum,minimum,mean,standard 
deviation,) of a file of data in which each column is a particular 
type of data. (the file is a tab separated value).
I was trying to do this by using python (usually i work with fortran or 
bash, but i'm learning python), that the reason why i tried to use numpy.


As I implied, you can do all this in standard Python "by hand", but 
numpy/scipy can definitely make things easier.  There's a dependency 
cost here (your program needs one or more extra libraries to work), but 
if that's no problem in your environment, I'd recommend that approach.


The scipy add-on contains a bunch of things for file i/o; see

http://www.scipy.org/doc/api_docs/SciPy.io.html

for an overview.  Since you're reading text files, the "array_import" 
module seems to be what you need:


http://www.scipy.org/doc/api_docs/SciPy.io.array_import.html

There are active user communities for both numpy and scipy that can help 
you sort out any remaining issues; for details, see:


http://www.scipy.org/Mailing_Lists

Hope this helps!



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


Re: Problem with Python Server Pages (PSP)

2008-07-23 Thread barun . saha04
On Jul 22, 5:36 pm, "Sebastian \"lunar\" Wiesner"
<[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] <[EMAIL PROTECTED]>:
>
> > Hi,
>
> > I am facing a very basic problem with PSP. I have installed mod_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.
>
> Not directly related to this issue, but I wouldn't start developing with
> PSP.  Modern web development is better done with a WSGI compatible
> framework like Django ...
>
> --
> Freedom is always the freedom of dissenters.
>   (Rosa Luxemburg)

Thanks to all. But can someone suggest me what the possible cause/
solution for this behaviour could be?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python Written in C?

2008-07-23 Thread Matthieu Brucher
2008/7/23 mk <[EMAIL PROTECTED]>:
>> 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.
>
> Doesn't g++ translate C++ into C and then compile C?
>
> Last I heard, most C++ compilers were doing that.

GCC translates every language into its one as a tree, which is then
translated to assembly.

Matthieu
-- 
French PhD student
Website : http://matthieu-brucher.developpez.com/
Blogs : http://matt.eifelle.com and http://blog.developpez.com/?blog=92
LinkedIn : http://www.linkedin.com/in/matthieubrucher
--
http://mail.python.org/mailman/listinfo/python-list


Re: os.walk question

2008-07-23 Thread alex23
On Jul 23, 10:11 pm, Larry Bates <[EMAIL PROTECTED]> wrote:
> import glob
> random.choice([f for f in glob.glob(root, "*")])

glob.glob only accepts one argument though, did you mean root + "*"?

It also returns folders as well as files, though, and the list
comprehension is not necessary given it returns a list itself.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Problem with Python Server Pages (PSP)

2008-07-23 Thread Graham Dumpleton
On Jul 22, 1:54 pm, [EMAIL PROTECTED] wrote:
> 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_pythonand 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
> 

Go read the documentation properly.

http://www.modpython.org/live/current/doc-html/hand-psp.html

What is PythonHandler set to?

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


Re: os.walk question

2008-07-23 Thread alex23
On Jul 23, 10:26 pm, Fredrik Lundh <[EMAIL PROTECTED]> wrote:
>      random.choice(filter(os.path.isfile, glob.glob("/*")))
>
> isn't that bad, though.

I'll agree to that.
--
http://mail.python.org/mailman/listinfo/python-list


Re: fromfile error on windows, not mac

2008-07-23 Thread Tommy Nordgren

One question : Did you remember to open the file in binary mode?
This MUST be done on windows.
On 22 jul 2008, at 06.36, jadamwil wrote:


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


--
Skinheads are so tired of immigration, that they are going to move to  
a country that don't accept immigrants!

Tommy Nordgren
[EMAIL PROTECTED]



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


Re: maximum value in a column of file

2008-07-23 Thread [EMAIL PROTECTED]
> > thank you for your answer
> > actually i've to do some statistics (maximum,minimum,mean,standard
> > deviation,) of a file of data in which each column is a particular
> > type of data. (the file is a tab separated value).
> > I was trying to do this by using python (usually i work with fortran or
> > bash, but i'm learning python), that the reason why i tried to use numpy.

numpy.loadtxt is probably what your looking for, provided your file
contains only numbers and comment lines.
check the example here: 
http://www.scipy.org/Numpy_Example_List_With_Doc#head-88ade192dacf0c15e4f1377096134ee559df07a0

X = numpy.loadtxt('data.txt')
X[:,0].mean() # mean of first column
X[:,0].max() # mux of first column
X[:,0].var() # variance of first column
...

enjoy! bernhard


>
> As I implied, you can do all this in standard Python "by hand", but
> numpy/scipy can definitely make things easier.  There's a dependency
> cost here (your program needs one or more extra libraries to work), but
> if that's no problem in your environment, I'd recommend that approach.
>
> The scipy add-on contains a bunch of things for file i/o; see
>
>  http://www.scipy.org/doc/api_docs/SciPy.io.html
>
> for an overview.  Since you're reading text files, the "array_import"
> module seems to be what you need:
>
>  http://www.scipy.org/doc/api_docs/SciPy.io.array_import.html
>
> There are active user communities for both numpy and scipy that can help
> you sort out any remaining issues; for details, see:
>
>  http://www.scipy.org/Mailing_Lists
>
> Hope this helps!
>
> 

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


Re: Problem with Python Server Pages (PSP)

2008-07-23 Thread barun . saha04
On Jul 23, 6:18 pm, Graham Dumpleton <[EMAIL PROTECTED]>
wrote:
> On Jul 22, 1:54 pm, [EMAIL PROTECTED] wrote:
>
>
>
> > 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_pythonand 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
> > 
>
> Go read the documentation properly.
>
> http://www.modpython.org/live/current/doc-html/hand-psp.html
>
> What is PythonHandler set to?
>
> Graham

Hi Graham,

I'm extremely sorry. I had typed wrongly the configuration. Following
is the one I'm using:


  AddHandler mod_python .psp .psp_
  PythonHandler mod_python.psp
  PythonDebug On


Strange thing is, same thing is working in windows, but not in Linux.
--
http://mail.python.org/mailman/listinfo/python-list


python.exe crash and ctypes use

2008-07-23 Thread waldek
Hi,

I have module A.py and B.dll which exports C functions by cdecl_

In A.py I pass callback (py callable) to dll. Next,  thread inside dll
simply calls my callback (in a loop). After few secs I got crash of
python.exe.

How to debug it?

I'm using winxp and py 2.5.2


===
def mycallback(data, size)
return 0

CBFUNC = CFUNCTYPE(c_int,POINTER(c_int), c_int)
dll  = cdll.mydll

if dll.RegisterCallback(CBFUNC(mycallback)) != 0:
print "Error."
===
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python Written in C?

2008-07-23 Thread Grant Edwards
On 2008-07-23, mk <[EMAIL PROTECTED]> wrote:
>> 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.
>
> Doesn't g++ translate C++ into C and then compile C?

No.

> Last I heard, most C++ compilers were doing that.

A decade or two ago there were some C++ front-ends that did
that, but I don't think it's common in modern C++ compilers.

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


Re: python.exe crash and ctypes use

2008-07-23 Thread Diez B. Roggisch
waldek wrote:

> Hi,
> 
> I have module A.py and B.dll which exports C functions by cdecl_
> 
> In A.py I pass callback (py callable) to dll. Next,  thread inside dll
> simply calls my callback (in a loop). After few secs I got crash of
> python.exe.
> 
> How to debug it?
> 
> I'm using winxp and py 2.5.2
> 
> 
> ===
> def mycallback(data, size)
> return 0
> 
> CBFUNC = CFUNCTYPE(c_int,POINTER(c_int), c_int)
> dll  = cdll.mydll
> 
> if dll.RegisterCallback(CBFUNC(mycallback)) != 0:
> print "Error."
> ===

Attach a debugger of choice to your python-process, and see what happens.

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


Re: Python Written in C?

2008-07-23 Thread Marc 'BlackJack' Rintsch
On Wed, 23 Jul 2008 14:10:22 +0200, mk wrote:

> Marc 'BlackJack' Rintsch wrote:
>> I can't even remember when I deleted something from a list in the past.
> 
> Still, doesn't that strike you as.. workaround?

No, I find it actually safer; I don't have to care where modifications of
the list might be seen elsewhere in the program.

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


Re: python.exe crash and ctypes use

2008-07-23 Thread Thomas Heller
waldek schrieb:
> Hi,
> 
> I have module A.py and B.dll which exports C functions by cdecl_
> 
> In A.py I pass callback (py callable) to dll. Next,  thread inside dll
> simply calls my callback (in a loop). After few secs I got crash of
> python.exe.
> 
> How to debug it?
> 
> I'm using winxp and py 2.5.2
> 
> 
> ===
> def mycallback(data, size)
> return 0
> 
> CBFUNC = CFUNCTYPE(c_int,POINTER(c_int), c_int)
> dll  = cdll.mydll
> 
> if dll.RegisterCallback(CBFUNC(mycallback)) != 0:
> print "Error."
> ===

You need the callback function instance - what the CBFUNC(mycallback)
call returns - alive as long as some C code is calling it.
If you don't sooner or later the Python garbage collector will
free it since it seems to be no longer used.  ctypes does NOT keep
the callback function alive itself.

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


Doubt

2008-07-23 Thread ജഗന്നാഥ്
Friends

I am a Perl programmer new to Python. I have a small doubt.
How to convert the perl notation
$a = ""; expression in Python ?

How to represent the loop
for ($a = $b; $a<=$c;$a++){
} in Python

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


Re: Function editing with Vim throws IndentError

2008-07-23 Thread Matimus
On Jul 22, 2:02 pm, ptn <[EMAIL PROTECTED]> wrote:
> Hi everybody,
>
> I have a weird problem.  Say I have a .py file with some functions in
> it, like this:
>
>     # (...)
>     def foo():
>         print("bar")
>
> When I open it and add a line to one of the functions,
>
>     # (...)
>     def foo():
>         troz = "bar"
>         print(troz)
>
> I get the following traceback from the interpreter:
>
>     Traceback (most recent call last):
>       File "SOMEWHERE/example.py", line ??
>         troz = "bar"
>                           ^
>     IndentationError: unindent does not match any outer indentation
> level
>
> And so I'm forced to rewrite the function entirely just to add the new
> line.
>
> I thought that my problem was the w option from formatoptions, so I
> changed my .vimrc file to this:
>
>     augroup filetype
>       autocmd BufNewFile,BufRead *.txt set filetype=human
>     augroup END
>     autocmd FileType human setlocal formatoptions+=ta2w
>     autocmd FileType lisp,scheme,python,c,java,vim setlocal
> formatoptions-=ta2w
>
> But the problem didn't go away.  I don't think this has anything to
> do
> with the tabs and spaces, because I have them set up like this:
>
>     set tabstop=4 shiftwidth=4 expandtab
>
> which is the standard way to handle them.
>
> The scripts I load are: qbuf, TagList, indent/python.vim and a reduced
> version of the standard python.vim
>
> Could someone provide some pointers?
>
> Thanks,
>
> Pablo Torres N.

That isn't the standard. With that setup tabs will show up as 4
spaces, and still confuse you. You want this:

set shiftwidth=4
set tabstop=8
set softtabstop=4
set expandtab

tab characters in the file will show up as 8 characters long (which is
how the python interpreter sees them also) but pressing tab will
insert 4 spaces.

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


Re: How do I compare files?

2008-07-23 Thread Clay Hobbs

On Tue, 2008-07-22 at 17:29 -0700, Matimus wrote:
> On Jul 22, 4:27pm, Clay Hobbs <[EMAIL PROTECTED]> wrote:
> > I am making a program that (with urllib) that downloads two jpeg files
> > and, if they are different, displays the new one. I need to find a way
> > to compare two files in Python. How is this done?
> >
> > -- Ratfink
> 
> Do you just want to check to see if they are the same? Or do you
> actually want to know what the differences are?
> 
> import urllib
> 
> data1 = urllib.urlopen("http://url.of.jpg1";).read()
> data2 = urllib.urlopen("http://url.of.jpg2";).read()
> 
> if data1 == data2:
> print "they are the same"
> 

I just wanted to see if they are different.  The code I was using that
didn't work was almost the same, except that the lines that download the
files didn't end in .read().  Thank you for your help

-- Ratfink

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


repr(string)

2008-07-23 Thread David C. Ullrich
I've been saving data in a file with one line per field.
Now some of the fields may become multi-line strings...

I was about to start escaping and unescaping linefeeds
by hand, when I realized that repr() and eval() should
do. Hence the question: If s is a string, is repr(s)
guaranteed not to contain line breaks?

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


Re: Doubt

2008-07-23 Thread Guilherme Polo
On Wed, Jul 23, 2008 at 11:51 AM, ജഗന്നാഥ് <[EMAIL PROTECTED]> wrote:
> Friends
>
> I am a Perl programmer new to Python. I have a small doubt.
> How to convert the perl notation
> $a = ""; expression in Python ?

a = ""

>
> How to represent the loop
> for ($a = $b; $a<=$c;$a++){
> } in Python
>

for a in range(b, c + 1): pass

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



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

Re: Doubt

2008-07-23 Thread Stephen Johnson
You don't need a mailing list, you need to read the tutorial. Those  
are completely trivial questions.


http://docs.python.org/tut/tut.html

-Steve Johnson

On Jul 23, 2008, at 10:51 AM, ജഗന്നാഥ് wrote:


Friends

I am a Perl programmer new to Python. I have a small doubt.
How to convert the perl notation
$a = ""; expression in Python ?

How to represent the loop
for ($a = $b; $a<=$c;$a++){
} in Python

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


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

Re: repr(string)

2008-07-23 Thread Guilherme Polo
On Wed, Jul 23, 2008 at 12:04 PM, David C. Ullrich <[EMAIL PROTECTED]> wrote:
> I've been saving data in a file with one line per field.
> Now some of the fields may become multi-line strings...
>
> I was about to start escaping and unescaping linefeeds
> by hand, when I realized that repr() and eval() should
> do. Hence the question: If s is a string, is repr(s)
> guaranteed not to contain line breaks?

In the sense that line breaks are quoted ? Yes, repr does that.

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



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


concatenate the elements in each list of a list of lists

2008-07-23 Thread antar2
I already asked a similar question, but encounter problems with
python...
How can I concatenate the elements in each list of a list of lists

list_of_listsA =

[['klas*', '*', '*'],
['mooi*', '*', '*', '*'],
['arm*', '*', '*(haar)']]

wanted result:

list_of_listsA =

[['klas* * *']
['mooi* * * *']
['arm* * *(haar)']]

Thanks a lot !

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


lxml, comparing nodes

2008-07-23 Thread code_berzerker
I'd like to know if there is any built in mechanism in lxml that lets
you check equality of two nodes from separate documents. I'd like it
to ignore attribute order and so on. It would be even better if there
was built in method for checking equality of whole documents (ignoring
document order). Please let me know if you know of such method or
existing scipt. I dont like reinventing the wheel :)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Proper way to query user and group database on a Unix host?

2008-07-23 Thread Guilherme Polo
On Wed, Jul 23, 2008 at 9:16 AM, Sebastian lunar Wiesner
<[EMAIL PROTECTED]> wrote:
> Chris Brannon <[EMAIL PROTECTED]>:
>
> Iirc since Python 2.5 these tuples are named ...
>
>> Instead, do this:
>>
>> import grp
>> groupname = 'users'
>> groupusers = grp.getgrnam(groupname)[3]
> ... thus this line could be written as:
>
> groupusers = grp.getgrnam(groupname).gr_mem
>

That is valid since Python 2.3 actually

> Slightly more readable, imho
>
>
>
> --
> Freedom is always the freedom of dissenters.
>  (Rosa Luxemburg)
> --
> http://mail.python.org/mailman/listinfo/python-list
>



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


Get dict value but not as reference.

2008-07-23 Thread Robert Rawlins
Guys,

 

This feels like a strange question but it's not something I've done before,
I'm sure it's quite simple.

 

I have a dictionary, and I want to get one of the values from it, but rather
than returning it as a reference I want to actually detach/remove the
element from the dictionary. Like so:

 

Def get_something():

Something = self.my_dict["keythatIwanttoredetach"]

 

Return something

 

I can then use something, however, it no longer exists in the dictionary.

 

Sorry, I couldn't really explain this very well. How can I achieve this?

 

Cheers,

 

Robert

 

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

Re: Get dict value but not as reference.

2008-07-23 Thread Jerry Hill
On Wed, Jul 23, 2008 at 11:49 AM, Robert Rawlins
<[EMAIL PROTECTED]> wrote:
> I have a dictionary, and I want to get one of the values from it, but rather
> than returning it as a reference I want to actually detach/remove the
> element from the dictionary. Like so:

Use the pop() method of the dictionary, like this:

>>> my_dict = {'a': 'Item A', 'b': 'Item B', 'c': 'Item C'}
>>> my_dict.pop('a')
'Item A'
>>> my_dict
{'c': 'Item C', 'b': 'Item B'}
>>>

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


Re: Proper way to query user and group database on a Unix host?

2008-07-23 Thread Sebastian "lunar" Wiesner
Guilherme Polo <[EMAIL PROTECTED]>:

> On Wed, Jul 23, 2008 at 9:16 AM, Sebastian lunar Wiesner
> <[EMAIL PROTECTED]> wrote:
>> Chris Brannon <[EMAIL PROTECTED]>:
>>
>> Iirc since Python 2.5 these tuples are named ...
>>
>>> Instead, do this:
>>>
>>> import grp
>>> groupname = 'users'
>>> groupusers = grp.getgrnam(groupname)[3]
>> ... thus this line could be written as:
>>
>> groupusers = grp.getgrnam(groupname).gr_mem
>>
> 
> That is valid since Python 2.3 actually

Thanks for clarification


-- 
Freedom is always the freedom of dissenters.
  (Rosa Luxemburg)
--
http://mail.python.org/mailman/listinfo/python-list


Re: lxml, comparing nodes

2008-07-23 Thread Sebastian "lunar" Wiesner
code_berzerker <[EMAIL PROTECTED]>:

> I'd like to know if there is any built in mechanism in lxml that lets
> you check equality of two nodes from separate documents. I'd like it
> to ignore attribute order and so on. It would be even better if there
> was built in method for checking equality of whole documents (ignoring
> document order). Please let me know if you know of such method or
> existing scipt. I dont like reinventing the wheel :)

Did you try the equality operator?

-- 
Freedom is always the freedom of dissenters.
  (Rosa Luxemburg)
--
http://mail.python.org/mailman/listinfo/python-list


RE: Get dict value but not as reference.

2008-07-23 Thread Robert Rawlins
> Use the pop() method of the dictionary, like this:

Ah, of course! Pop! I have seen this before I think Jerry, seems to do the 
trick nicely.

Thank you.

Robert

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


Re: Strange problem ....

2008-07-23 Thread karthikbalaguru
On Jul 23, 1:31 pm, "Simon Brunning" <[EMAIL PROTECTED]> wrote:
> 2008/7/23 karthikbalaguru <[EMAIL PROTECTED]>:
>
> > I use Redhat 9.0, python-2.2.2-26, python-devel-2.2.2-26 and
> > db4-4.0.14-20.
>
> >  File "/usr/local/SDK/bin/../core/bin/processorlib.py", line 88
> >yield ProcessorObjectInfo(child, self.pt)
> >^
> > SyntaxError: invalid syntax
>
> > Is this error related with the version of python / python-devel that i
> > use .
> > Any ideas / tips ?
>
> Yup - generators (and hence the yield statement) were first introduced
> in Python 2.2, but in order to maintain backward compatibility, you'll
> need this line in any module using them:
>
> from __future__ import generators
>
> As of Python 2.3, this is no longer necessary, and I'd imagine that
> whatever you are running was targeted at a post 2.2 release.
>

Your answers helped me to solve the problem.

I found some while loop inside def children(def).

I initially tried by putting 'from __future__ import generators'
just before the
 def children(self):
present inside the class definition of 'DebugProcessorInfo'. But it
did not work.

Later i placed the 'from __future__ import generators' at the
beginning
of the python file and it worked sucessfully.

Thx for that info.
Karthik Balaguru

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


Re: Undefined calling conventions in Python.h

2008-07-23 Thread Martin v. Löwis
> 1>application.obj : error LNK2031: unable to generate p/invoke for
> "extern "C" void __clrcall Py_Exit(int)" (?Py_Exit@@[EMAIL PROTECTED]);
> calling convention missing in metadata

The main problem here is the __clrcall hint: apparently, you are
using Managed C++ resp. C++/CLI, i.e. the Microsoft .NET Framework for
C++.

Don't do that.

Instead, make sure that your project targets native Intel x86 code;
then compile your code either as C or C++ (your choice). To integrate
Python into managed C++ would require a lot of experience, and it may
well not be possible.

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


Re: lxml, comparing nodes

2008-07-23 Thread Stefan Behnel
code_berzerker wrote:
> I'd like to know if there is any built in mechanism in lxml that lets
> you check equality of two nodes from separate documents.

No, because, as you state yourself, equality is not something that everyone
defines the same way.


> I'd like it
> to ignore attribute order and so on. It would be even better if there
> was built in method for checking equality of whole documents (ignoring
> document order). Please let me know if you know of such method or
> existing scipt. I dont like reinventing the wheel :)

Your requirements for a single Element are simple enough to write it in three
to five lines of Python code (depending on your definition of equality).
Checking this equality recursively is another two to three lines. Not complex
enough to be considered a wheel in the first place.

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


Re: interpreter vs. compiled

2008-07-23 Thread castironpi
On Jul 22, 11:38 pm, Tim Roberts <[EMAIL PROTECTED]> wrote:
> castironpi <[EMAIL PROTECTED]> wrote:
>
> >You're saying the VM can't compile code.  That makes sense, it's not a
> >compiler.
>
> I wouldn't say "can't".  The current CPython VM does not compile code.  It
> COULD.  The C#/.NET VM does.  IronPython, for example, is an implementation
> of Python that uses .NET.  In that case, the code *IS* JIT compiled to
> assembly when the program starts.
>
> >Do I understand correctly that JIT does compile to native
> >code in some cases?
>
> VMs that use JIT do, yes.
>
> >But that's not the only thing that stops python
> >from precompiling to assembly directly.  GNU doesn't come with
> >Python.
>
> Do you mean Linux?
>
> >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?
>
> I don't know why you think GNU has anything to do with this.  There's
> nothing that prevents the Python run-time from JIT compiling the code.
> IronPython does this.  CPython does not.  It's an implementation decision.
> --
> Tim Roberts, [EMAIL PROTECTED]
> Providenza & Boekelheide, Inc.

Compiling a program is different than running it.  A JIT compiler is a
kind of compiler and it makes a compilation step.  I am saying that
Python is not a compiler and in order to implement JIT, it would have
to change that fact.

> of Python that uses .NET.  In that case, the code *IS* JIT compiled to
> assembly when the program starts.

But still not the user's code, only the interpreter, which is running
in assembly already anyway in CPython.
--
http://mail.python.org/mailman/listinfo/python-list


Re: concatenate the elements in each list of a list of lists

2008-07-23 Thread Chris
On Jul 23, 5:33 pm, antar2 <[EMAIL PROTECTED]> wrote:
> I already asked a similar question, but encounter problems with
> python...
> How can I concatenate the elements in each list of a list of lists
>
> list_of_listsA =
>
> [['klas*', '*', '*'],
> ['mooi*', '*', '*', '*'],
> ['arm*', '*', '*(haar)']]
>
> wanted result:
>
> list_of_listsA =
>
> [['klas* * *']
> ['mooi* * * *']
> ['arm* * *(haar)']]
>
> Thanks a lot !

Nice and easy. :)

>>> list_of_listsA = [['klas*', '*', '*'],
['mooi*', '*', '*', '*'],
['arm*', '*', '*(haar)']]
>>> [' '.join(l) for l in list_of_listsA]
['klas* * *', 'mooi* * * *', 'arm* * *(haar)']
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python Written in C?

2008-07-23 Thread castironpi
On Jul 23, 9:11 am, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote:
> On Wed, 23 Jul 2008 14:10:22 +0200, mk wrote:
> > Marc 'BlackJack' Rintsch wrote:
> >> I can't even remember when I deleted something from a list in the past.
>
> > Still, doesn't that strike you as.. workaround?
>
> No, I find it actually safer; I don't have to care where modifications of
> the list might be seen elsewhere in the program.
>
> Ciao,
>         Marc 'BlackJack' Rintsch

a[:]= newlist

and

a= newlist

have two completely different effects, and one is just as safe as
'del'.  Besides, del isn't safe to be seen elsewhere in the program in
other threads, if they aren't locking the GIL.
--
http://mail.python.org/mailman/listinfo/python-list


Europe's Best Computer Enthusiast Website, Eurotechzone is now Open!

2008-07-23 Thread Eurotechzone
http://www.eurotechzone.com
Catering to the computer enthusiasts from all over the world,
Eurotechzone is Europe’s first multi-lingual website on hardware
news&reviews. In this site you will find:

•   The hottest news from IT Bussiness world
•   The Reviews of the newest electronic components and PC
hardwares.
•   A dynamic community/forum to discuss IT subjects and technical
issues.
•   …and more and more is awaiting for you in www.eurotechzone.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: concatenate the elements in each list of a list of lists

2008-07-23 Thread Michael Schneider
Am Wed, 23 Jul 2008 08:33:57 -0700 wrote antar2:

> I already asked a similar question, but encounter problems with
> python...
> How can I concatenate the elements in each list of a list of lists
> 
> list_of_listsA =
> 
> [['klas*', '*', '*'],
> ['mooi*', '*', '*', '*'],
> ['arm*', '*', '*(haar)']]
> 
> wanted result:
> 
> list_of_listsA =
> 
> [['klas* * *']
> ['mooi* * * *']
> ['arm* * *(haar)']]
> 
> Thanks a lot !

Hello,

maybe this will help:

In [5]: list_of_listsA = [['klas*', '*', '*'], ['mooi*', '*', '*', '*'], 
['arm*', '*', '*(haar)']]
In [6]: s = ""
In [7]: print [[s.join(item)] for item in list_of_listsA]
[['klas***'], ['mooi'], ['arm***(haar)']]

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


Wrapping std::set in Boost::Python

2008-07-23 Thread Eric First
All:

Has anybody had success at wrapping std::set using Boost::Python? Any ideas,
snippets of code, etc... would be very helpful.

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

Re: lxml, comparing nodes

2008-07-23 Thread code_berzerker
On Jul 23, 6:29 pm, Stefan Behnel <[EMAIL PROTECTED]> wrote:

> Your requirements for a single Element are simple enough to write it in three
> to five lines of Python code (depending on your definition of equality).
> Checking this equality recursively is another two to three lines. Not complex
> enough to be considered a wheel in the first place.

Forgive my ignorance as I am new to both Python and lxml ;)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python Written in C?

2008-07-23 Thread Marc 'BlackJack' Rintsch
On Wed, 23 Jul 2008 09:42:29 -0700, castironpi wrote:

> On Jul 23, 9:11 am, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote:
>> On Wed, 23 Jul 2008 14:10:22 +0200, mk wrote:
>> > Marc 'BlackJack' Rintsch wrote:
>> >> I can't even remember when I deleted something from a list in the past.
>>
>> > Still, doesn't that strike you as.. workaround?
>>
>> No, I find it actually safer; I don't have to care where modifications of
>> the list might be seen elsewhere in the program.
>>
>> Ciao,
>>         Marc 'BlackJack' Rintsch
> 
> a[:]= newlist
> 
> and
> 
> a= newlist
> 
> have two completely different effects, and one is just as safe as
> 'del'.  Besides, del isn't safe to be seen elsewhere in the program in
> other threads, if they aren't locking the GIL.

As usual you are talking nonsense…

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

Re: interpreter vs. compiled

2008-07-23 Thread Martin v. Löwis
>> Oh.  How is the stack represented?
> 
> As usual, as successive locations in memory.
> I have the impression that CPython uses the same stack C does.

Actually, it doesn't (at least not for the evaluation stack).

In CPython, when a Python function starts, the maximum depth of the
evaluation stack is known, but it depends on the specific function
(of course). So Python needs to allocate an array for the evaluation
stack with known size, but can't do so on the C stack (at least not
portably), since you can't allocate dynamically-sized array as
a local variable in C.

So instead, pymalloc is used to allocate the evaluation stack, and
it is part of the frame object (so the entire frame object is allocated
in one chunk, and then split up into local variables and evaluation
stack.

> While conceptually, CPython may put objects on the stack, I am pretty
> sure it actually stacks references (C pointers) to objects in heap memory.

Correct.

>> Does it keep track of which stack
>> positions (TOS, TOS1, etc.) are in what registers?
> 
> I am sure they are not in registers, just normal memory.

Correct. As discussed above, they are located on the heap (making
Python's frame stack a spaghetti stack).

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


Segv in mmap.move()

2008-07-23 Thread [EMAIL PROTECTED]
Does anyone recognize this little Python crasher?

I'll file a bug report unless someone notices it as an already
documented bug. I found some open mmap bugs, but it wasn't
obvious to me that this problem was one of those...

Python 2.5.2 (r252:60911, Apr 21 2008, 11:12:42)
[GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import mmap
>>> data = mmap.mmap(-1, 1)
>>> data.move(1,1,-1)
Segmenteringsfel (core dumped)

I first noticed the problem under Windows in 2.5.1.


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


Using variables across modules

2008-07-23 Thread Aaron Scott
I'm having some trouble understanding how Python handles variables
across multiple modules. I've dug through the documentation, but I
still find myself at a loss.

When you import a module, are you creating an instance of the
variables within? For instance, if I have one file, "variables.py",
which contains "myvar = 0", and I import it into both "foo.py" and
"bar.py" with the line "from variables import *", and then set myvar
in "foo.py" and "bar.py" to different values, will each file have a
different value for myvar? If so, how can I ensure that a change to
myvar in "bar.py" is reflected by "foo.py"? Or am I completely off
base?
--
http://mail.python.org/mailman/listinfo/python-list


Undocumented Python 2.6 change: Py_None vs NULL when C implementation raises exception

2008-07-23 Thread Heikki Toivonen
I was debugging M2Crypto function written in C which changed behavior
between Python 2.6 and earlier Python versions. In an error condition
the function was supposed to raise exception type A, but with 2.6 it
raised type B, and further, there was no string value for the exception.

I tracked this down to the C code incorrectly returning Py_None when it
should have returned NULL. Changing the C code to return NULL made it
behave correctly in 2.6.

I don't know how common a mistake it is to return Py_None when NULL
should have been returned, but it might be worth a note in the list of
changes for 2.6 that this behavior changed, don't you think?

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


Re: tkinter for my python program !!

2008-07-23 Thread David


Further, finally when i invoke the python program by
giving the necessary input file, i get the following
errors .
Does it have any relation with the python version installed ?
  

yes


I am using Redhat 9.0

You may want to install a current Linux distro.

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


  1   2   >