Re: joining files

2010-05-17 Thread Dave Angel

mannu jha wrote:

On Sun, 16 May 2010 13:52:31 +0530  wrote
  

mannu jha wrote:



  

Hi,



  

  

I have few files like this:
file1:
22 110.1 
33 331.5 22.7 
5 271.9 17.2 33.4
4 55.1 



  

file1 has total 4 column but some of them are missing in few row.



  

file2:
5 H
22 0



  

file3:
4 T
5 B
22 C
121 S



  

  

in all these files first column is the main source of matching their entries. 
So What I want in the output is only those entries which is coming in all three 
files.



  

output required:



  

5 271.9 17.2 33.4 5 H 5 T
22 110.1 22 0 22 C



  
I am trying with this :


from collections import defaultdict

def merge(sources):
blanks = [blank for items, blank, keyfunc in sources]
d = defaultdict(lambda: blanks[:])
for index, (items, blank, keyfunc) in enumerate(sources):
for item in items:
d[keyfunc(item)][index] = item
for key in sorted(d):
yield d[key]

if __name__ == "__main__":
a = open("input1.txt")

c = open("input2.txt")


def key(line):
return line[:2]
def source(stream, blank="", key=key):
return (line.strip() for line in stream), blank, key
for m in merge([source(x) for x in [a,c]]):
print "|".join(c.ljust(10) for c in m)

but with input1.txt:
1877.79   122.27   54.37   4.26   179.75
1948.00   121.23   54.79   4.12   180.06
158.45   119.04   55.02   4.08   178.89
1767.78   118.68   54.57   4.20   181.06
1807.50   119.21   53.93  179.80
1907.58   120.44   54.62   4.25   180.02
1528.39   120.63   55.10   4.15   179.10
1547.79   119.62   54.47   4.22   180.46
1758.42   120.50   55.31   4.04   180.33
and input2.txt:
 15   H 
 37   H 
 95   T
124   H 
130   H 
152   H 
154   H 
158   H 
164   H
175   H 
176   H 
180   H
187   H 
190   T

194   C
196   H 
207   H 
210   H 
232   H 
it is giving output as:

  |
  |124   H
  |130   H
1547.79   119.62   54.47   4.22   180.46|158   H
  |164   H
1758.42   120.50   55.31   4.04   180.33|176   H
1807.50   119.21   53.93  179.80|187   H
1907.58   120.44   54.62   4.25   180.02|196   H
  |207   H
  |210   H
  |232   H
  |37   H
  |95   T
so it not matching it properly, can anyone please suggest where I am doing 
mistake.


  
Several mistakes here, some in making it unnecessarily complex, but I'll 
concentrate on the ones that just don't work.


Your key() function returns the first two characters of the line.  So 
you're keying not on the whole number, but only on the first two digits 
of it.  To find out what's going on, you need to decompose the complex 
line from:
 


   d[keyfunc(item)][index] = item

to some things you can actually examine:
  key = keyfunc(item)
  d[key][index] = item


You don't make any check to see if a particular item is in all the 
files.  For your particular data structure, this would mean that a 
particular value in the dictionary (which is a list of two items) has 
all non-blank strings in it.  To do this, you might want to do an all() 
function on the list.



DaveA


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


Re: Human word reader

2010-05-17 Thread Gregory Ewing

Dennis Lee Bieber wrote:


And is it supposed to handle

for london give the weather to me
for the london weather give me


Or

Where can I buy some new weather boarding for my
house in London?

:-)

--
Greg



...

Do a search on "natural language processing"... You are at the level
of algorithms, and algorithms are not limited to Python...

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


Re: tone generation for motherboard and sound card speakers?

2010-05-17 Thread Gaby
It is amazing, the Ballon Bleu de Cartier Replica Watches at 
http://www.swizwatch.com/ are perfect, cheap and high quality.

Ballon Bleu de Cartier Watches Collection: 
http://www.swizwatch.com/ballon-bleu-de-cartier-replica-watches.html

Replica Cartier Ballon Bleu de Cartier Two-Tone Ladies Watch W69007Z3
http://www.swizwatch.com/Cartier-Ballon-Bleu-de-Cartier-Two-Tone-Ladies-Watch-W69007Z3-.html

Replica Cartier Ballon Bleu de Cartier 18K Yellow Gold Leather Strap Mens 
Watch W6900551
http://www.swizwatch.com/Cartier-Ballon-Bleu-de-Cartier-18K-Yellow-Gold-Leather-Strap-Mens-Watch-W6900551.html

Replica Cartier Ballon Bleu de Cartier Two-Tone Mens Watch W69009Z3
http://www.swizwatch.com/Cartier-Ballon-Bleu-de-Cartier-Two-Tone-Mens-Watch-W69009Z3.html

Replica Cartier Ballon Bleu de Cartier 18K Rose Gold Mens Watch W69006Z2
http://www.swizwatch.com/Cartier-Ballon-Bleu-de-Cartier-18K-Rose-Gold-Mens-Watch-W69006Z2.html

Replica Cartier Ballon Bleu de Cartier Mens Gold Watch W69013Z2

http://www.swizwatch.com/Cartier-Ballon-Bleu-de-Cartier-Mens-Gold-Watch-W69013Z2.html


Buy more Cartier replica watches at low price by click:
http://www.swizwatch.com/cartier-replica-watches.html

"Alex Hall"  
??:[email protected]...
> Hi all,
> I am wondering if there is a way to generate a tone for the
> motherboard speaker, like the call to Beep() in C++?
>
> Also, is there a module to generate tones in Python using the sound
> card? A module that can beep at a given frequency for a given time
> using the usual sine wave is okay, but the fancier the better
> (different waves, sweeping, and so on).
>
> My final question will likely hinge upon the answer to the second
> question, but is there a way to play a tone in a given position in the
> stereo field? For example, I have a Battleship tactical board (my name
> for where the little red and white pins go) which I am trying to
> sonify using different tones for each status (not fired on, ship
> sighted, ship hit, ship sunk). I want each row to play, from top to
> bottom, but each square in each row should start at the left and
> continue to the last square playing in the right speaker, giving the
> user a better idea of where each square is. Oh, this is for blind
> users, in case you were wondering why anyone would want to sonify a
> battleship board.
> Thanks for any information, and note that I am using Python2.6; unless
> there is an easy way to use a module meant for 2.5 or before inside a
> 2.6 project, I would need a 2.6 module.
>
> -- 
> Have a great day,
> Alex (msg sent from GMail website)
> [email protected]; http://www.facebook.com/mehgcap 


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


Re: Updating values in a dictionary

2010-05-17 Thread Gregory Ewing

On 5/16/2010 1:36 PM, Thomas wrote:

row = dict([(x,0) for x in range(3)])
matrix = dict([(x,row) for x in range(-3,4,1)])

matrix[2][1] += 1
matrix[-1][2] += 1


Another possibility is to use a single dict with
tuples for the indexes.

  matrix = dict([((x, y), 0) for x in range(-3, 4) for y in range(3)])

  matrix[2, 1] += 1
  matrix[-1, 2] += 1

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


Re: Global variables for python applications

2010-05-17 Thread Gregory Ewing

John Nagle wrote:

Also, more compile-time arithmetic becomes possible.


But only if their values can be computed at compile time. This
leads to a huge can of worms if you want to be able to import
named constants from other modules. A large part of what
currently happens only at run time would have to become
possible at compile time as well. Either that or so many
restrictions would have to be placed on the way that the
values of named constants are specified that they would not
be very useful in practice.


   I think there's some religious objection to constants in Python,


Not religious, but pragmatic. What appears to be a simple and
obvious idea on the surface turns out not to be nearly so simple
or obvious in a language as dynamic as Python.

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


Re: tone generation for motherboard and sound card speakers?

2010-05-17 Thread Gregory Ewing

Alex Hall wrote:


Also, is there a module to generate tones in Python using the sound
card? A module that can beep at a given frequency for a given time
using the usual sine wave is okay, but the fancier the better
(different waves, sweeping, and so on).

My final question will likely hinge upon the answer to the second
question, but is there a way to play a tone in a given position in the
stereo field?


The mixer module of pygame will do all of this, I think:

   http://www.pygame.org/

You may find the rest of pygame useful for implementing your
battleship game as well, if you haven't already chosen a library
for that.

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


Re: Re: joining files

2010-05-17 Thread mannu jha

On Sun, 16 May 2010 23:51:10 +0530  wrote
>On 05/16/2010 05:04 PM, Dave Angel wrote:
> (You forgot to include the python-list in your response. So it only
> went to me. Normally, you just do reply-all to the message)
> mannu jha wrote:
>> On Sun, 16 May 2010 13:52:31 +0530 wrote
>>> mannu jha wrote:
>>> Hi,
>>> I have few files like this:
>>> file1:
>>> 22 110.1 33 331.5 22.7 5 271.9 17.2 33.4
>>> 4 55.1
>>> file1 has total 4 column but some of them are missing in few row.
>>> file2:
>>> 5 H
>>> 22 0
>>> file3:
>>> 4 T
>>> 5 B
>>> 22 C
>>> 121 S
>>> in all these files first column is the main source of matching their 
>>> entries. So What I want in the output is only those entries which is coming 
>>> in all three files. output required:
>>> 5 271.9 17.2 33.4 5 H 5 T
>>> 22 110.1 22 0 22 C
>> I am trying with this :
>> from collections import defaultdict
>> def merge(sources):
>> blanks = [blank for items, blank, keyfunc in sources]
>> d = defaultdict(lambda: blanks[:])
>> for index, (items, blank, keyfunc) in enumerate(sources):
>> for item in items:
>> d[keyfunc(item)][index] = item
>> for key in sorted(d):
>> yield d[key]
>> if __name__ == "__main__":
>> a = open("input1.txt")
>> c = open("input2.txt")
>> def key(line):
>> return line[:2]
>> def source(stream, blank="", key=key):
>> return (line.strip() for line in stream), blank, key
>> for m in merge([source(x) for x in [a,c]]):
>> print "|".join(c.ljust(10) for c in m)
>> but with input1.txt:
>> 187 7.79 122.27 54.37 4.26 179.75
>> 194 8.00 121.23 54.79 4.12 180.06
>> 15 8.45 119.04 55.02 4.08 178.89
>> 176 7.78 118.68 54.57 4.20 181.06
>> 180 7.50 119.21 53.93 179.80
>> 190 7.58 120.44 54.62 4.25 180.02
>> 152 8.39 120.63 55.10 4.15 179.10
>> 154 7.79 119.62 54.47 4.22 180.46
>> 175 8.42 120.50 55.31 4.04 180.33
>> and input2.txt:
>> 15 H 37 H 95 T
>> 124 H 130 H 152 H 154 H 158 H 164 H
>> 175 H 176 H 180 H
>> 187 H 190 T
>> 194 C
>> 196 H 207 H 210 H 232 H it is giving output as:
>> |
>> |124 H
>> |130 H
>> 154 7.79 119.62 54.47 4.22 180.46|158 H
>> |164 H
>> 175 8.42 120.50 55.31 4.04 180.33|176 H
>> 180 7.50 119.21 53.93 179.80|187 H
>> 190 7.58 120.44 54.62 4.25 180.02|196 H
>> |207 H
>> |210 H
>> |232 H
>> |37 H
>> |95 T
>> so it not matching it properly, can anyone please suggest where I am doing 
>> mistake.

import os

def merge_sources(sources):
   # sources is a list of tuples (source_name, source_data)
   data = []
   keysets = []
   for nme, sce in sources:
 lines = {}
 for line in sce.split(os.linesep):
   lst = line.split()
   lines[lst[0]] = (nme, lst)
 keysets.append(set(lines.keys()))
 data.append(lines)
   common_keys = keysets[0]
   for keys in keysets[1:]:
 common_keys = common_keys.intersection(keys)
   result = {}
   for key in common_keys:
 result[key] = dict(d[key] for d in data if key in d)
   return result
if __name__ == "__main__":
   # Your test files here are replaced by local strings
   print merge_sources([("file1", file1), ("file2", file2), ("file3", 
file3)])
   print merge_sources([("input1", input1), ("input2", input2)])
Test_results = '''
{'22': {'file3': ['22', 'C'],
 'file2': ['22', '0'],
 'file1': ['22', '110.1', '33', '331.5', '22.7', '5', '271.9',
  '17.2', '33.4']}}
{'194': {'input2': ['194', 'C'],
 'input1': ['194', '8.00', '121.23', '54.79', '4.12',
   '180.06']},
 '175': {'input2': ['175', 'H', '176', 'H', '180', 'H'],
 'input1': ['175', '8.42', '120.50', '55.31', '4.04',
   '180.33']},
  '15': {'input2': ['15', 'H', '37', 'H', '95', 'T'],
 'input1': ['15', '8.45', '119.04', '55.02', '4.08',
   '178.89']},
 '187': {'input2': ['187', 'H', '190', 'T'],
 'input1': ['187', '7.79', '122.27', '54.37', '4.26',
   '179.75']}}

Dear Sir,

I tried above program but with that it is showing error:
nmru...@caf:~> python join1.py
Traceback (most recent call last):
  File "join1.py", line 24, in 
print merge_sources([("file1", file1), ("file2", file2), ("file3",
NameError: name 'file1' is not defined
nmru...@caf:~> 



-- 

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

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


reading XML file using python

2010-05-17 Thread shanti bhushan
Hi ,
i am new to python.i want to read the XML file using python it ,by
using DOm or SAX any of them.
I want to read the http://www.google.com(any hyper text) from XML and
print that.
please give me the sample program for this.
regards
Shanti Bhushan
Bangalore,India
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: reading XML file using python

2010-05-17 Thread Stefan Behnel

shanti bhushan, 17.05.2010 10:34:

i am new to python.i want to read the XML file using python it ,by
using DOm or SAX any of them.
I want to read the http://www.google.com (any hyper text) from XML and
print that.


Note that web sites usually are HTML, not XML. Are you sure you want to 
read XML as well? Also, DOM/SAX are certainly not the easiest way to 
extract information from XML, use the xml.etree.ElementTree package instead.


To parse HTML from web pages, you can use several different tools in 
Python, see


http://www.google.com/search?q=python+web+scraping

Stefan

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


Re: reading XML file using python

2010-05-17 Thread Franz Kelnreiter
2010/5/17 shanti bhushan :
> Hi ,
> i am new to python.i want to read the XML file using python it ,by
> using DOm or SAX any of them.
> I want to read the http://www.google.com(any hyper text) from XML and
> print that.
> please give me the sample program for this.
Hi Shanti,
The question how to read an XML file has already been answerd more
than 50 times within this group. So I fear nobody wont any longer be
willing to repeat this matter every 15 days...
Greetings,
Franz
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: reading XML file using python

2010-05-17 Thread Simon Brunning
On 17 May 2010 09:34:51 UTC+1, shanti bhushan  wrote:
> Hi ,
> i am new to python.i want to read the XML file using python it ,by
> using DOm or SAX any of them.
> I want to read the http://www.google.com(any hyper text) from XML and
> print that.
> please give me the sample program for this.

Your question isn't very clear. Do you want to read the data from a
URL (such as http://www.google.com) and parse it? If so, you probably
don't want an XML parser as such - try Beautiful Soup.

Or do you have a piece of XML with some URLs in it that you want to
extract? ElementTree in the standard library is one good choice here
if you're not wedded to one of DOM or SAX.

What have you tried so far? No one is going to write code for you, but
we'd be happy to help you fix problems with your own code.
 might be worth a
read.

-- 
Cheers,
Simon B.
-- 
http://mail.python.org/mailman/listinfo/python-list


Fw: Re: Re: Re: joining files

2010-05-17 Thread mannu jha
Note: Forwarded message attached

-- Original Message --

From: "mannu jha"[email protected]
To: [email protected]
Subject: Re: Re: Re: joining files--- Begin Message ---
On Sun, 16 May 2010 23:51:10 +0530 wrote
>On 05/16/2010 05:04 PM, Dave Angel wrote:
> (You forgot to include the python-list in your response. So it only
> went to me. Normally, you just do reply-all to the message)
> mannu jha wrote:
>> On Sun, 16 May 2010 13:52:31 +0530 wrote
>>> mannu jha wrote:
>>> Hi,
>>> I have few files like this:
>>> file1:
>>> 22 110.1 33 331.5 22.7 5 271.9 17.2 33.4
>>> 4 55.1
>>> file1 has total 4 column but some of them are missing in few row.
>>> file2:
>>> 5 H
>>> 22 0
>>> file3:
>>> 4 T
>>> 5 B
>>> 22 C
>>> 121 S
>>> in all these files first column is the main source of matching their 
>>> entries. So What I want in the output is only those entries which is coming 
>>> in all three files. output required:
>>> 5 271.9 17.2 33.4 5 H 5 T
>>> 22 110.1 22 0 22 C
>> I am trying with this :
>> from collections import defaultdict
>> def merge(sources):
>> blanks = [blank for items, blank, keyfunc in sources]
>> d = defaultdict(lambda: blanks[:])
>> for index, (items, blank, keyfunc) in enumerate(sources):
>> for item in items:
>> d[keyfunc(item)][index] = item
>> for key in sorted(d):
>> yield d[key]
>> if __name__ == "__main__":
>> a = open("input1.txt")
>> c = open("input2.txt")
>> def key(line):
>> return line[:2]
>> def source(stream, blank="", key=key):
>> return (line.strip() for line in stream), blank, key
>> for m in merge([source(x) for x in [a,c]]):
>> print "|".join(c.ljust(10) for c in m)
>> but with input1.txt:
>> 187 7.79 122.27 54.37 4.26 179.75
>> 194 8.00 121.23 54.79 4.12 180.06
>> 15 8.45 119.04 55.02 4.08 178.89
>> 176 7.78 118.68 54.57 4.20 181.06
>> 180 7.50 119.21 53.93 179.80
>> 190 7.58 120.44 54.62 4.25 180.02
>> 152 8.39 120.63 55.10 4.15 179.10
>> 154 7.79 119.62 54.47 4.22 180.46
>> 175 8.42 120.50 55.31 4.04 180.33
>> and input2.txt:
>> 15 H 37 H 95 T
>> 124 H 130 H 152 H 154 H 158 H 164 H
>> 175 H 176 H 180 H
>> 187 H 190 T
>> 194 C
>> 196 H 207 H 210 H 232 H it is giving output as:
>> |
>> |124 H
>> |130 H
>> 154 7.79 119.62 54.47 4.22 180.46|158 H
>> |164 H
>> 175 8.42 120.50 55.31 4.04 180.33|176 H
>> 180 7.50 119.21 53.93 179.80|187 H
>> 190 7.58 120.44 54.62 4.25 180.02|196 H
>> |207 H
>> |210 H
>> |232 H
>> |37 H
>> |95 T
>> so it not matching it properly, can anyone please suggest where I am doing 
>> mistake.

import os

def merge_sources(sources):
# sources is a list of tuples (source_name, source_data)
data = []
keysets = []
for nme, sce in sources:
lines = {}
for line in sce.split(os.linesep):
lst = line.split()
lines[lst[0]] = (nme, lst)
keysets.append(set(lines.keys()))
data.append(lines)
common_keys = keysets[0]
for keys in keysets[1:]:
common_keys = common_keys.intersection(keys)
result = {}
for key in common_keys:
result[key] = dict(d[key] for d in data if key in d)
return result
if __name__ == "__main__":
# Your test files here are replaced by local strings
print merge_sources([("file1", file1), ("file2", file2), ("file3",
file3)])
print merge_sources([("input1", input1), ("input2", input2)])
Test_results = '''
{'22': {'file3': ['22', 'C'],
'file2': ['22', '0'],
'file1': ['22', '110.1', '33', '331.5', '22.7', '5', '271.9',
'17.2', '33.4']}}
{'194': {'input2': ['194', 'C'],
'input1': ['194', '8.00', '121.23', '54.79', '4.12',
'180.06']},
'175': {'input2': ['175', 'H', '176', 'H', '180', 'H'],
'input1': ['175', '8.42', '120.50', '55.31', '4.04',
'180.33']},
'15': {'input2': ['15', 'H', '37', 'H', '95', 'T'],
'input1': ['15', '8.45', '119.04', '55.02', '4.08',
'178.89']},
'187': {'input2': ['187', 'H', '190', 'T'],
'input1': ['187', '7.79', '122.27', '54.37', '4.26',
'179.75']}}

Dear Sir,

I tried above program but with that it is showing error:
nmru...@caf:~> python join1.py
Traceback (most recent call last):
File "join1.py", line 24, in
print merge_sources([("file1", file1), ("file2", file2), ("file3",
NameError: name 'file1' is not defined
nmru...@caf:~> 

I tried with this:
import os

def merge_sources(sources):
# sources is a list of tuples (source_name, source_data)
data = []
keysets = []
for nme, sce in sources:
lines = {}
for line in sce.split(os.linesep):
lst = line.split()
lines[lst[0]] = (nme, lst)
keysets.append(set(lines.keys()))
data.append(lines)
common_keys = keysets[0]
for keys in keysets[1:]:
common_keys = common_keys.intersection(keys)
result = {}
for key in common_keys:
result[key] = dict(d[key] for d in data if key in d)
return result

if __name__ == "__main__":
# Your test files here are replaced by local strings
   file1 = ["22 110.1 33 331.5 22.7 5 271.9 17.2 33.4",
"4 55.1"]
   file2 = ["5 H",
"22 0"]
   print merge_sources([("file1", file1), ("file2", file2)])

but with this it is showing error:

Re: Global variables for python applications

2010-05-17 Thread Steven D'Aprano
On Mon, 17 May 2010 19:56:15 +1200, Gregory Ewing wrote:

> John Nagle wrote:
>> Also, more compile-time arithmetic becomes possible.
> 
> But only if their values can be computed at compile time.

John said "more", not "everything imaginable can be calculated at compile 
time" :)

Python already does constant folding at compile time:


>>> code = compile('"abc"*2*3', '', 'single')
>>> dis.dis(code)
  1   0 LOAD_CONST   5 ('abcabcabcabcabcabc')
  3 PRINT_EXPR
  4 LOAD_CONST   3 (None)
  7 RETURN_VALUE



> This leads to
> a huge can of worms if you want to be able to import named constants
> from other modules.


Why? Once the module is loaded, the named constant is bound to an object. 
Provided that it can't be rebound or mutated, where's the can of worms?


> A large part of what currently happens only at run
> time would have to become possible at compile time as well. Either that
> or so many restrictions would have to be placed on the way that the
> values of named constants are specified that they would not be very
> useful in practice.

I disagree. Enforcing immutability would be tricky, but enforcing once-
only name binding is relatively simple. There's even a recipe for it in 
the Python Cookbook.




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


Issue with PyUnicodeObject type variables

2010-05-17 Thread gmail
A variable whose data type is PyUnicodeObject checked whether it is a 
UnicodeObject type.
Got output as false

example :

PyUnicodeObject *p; 

if (PyUnicode_Check(path)) {
printf("\nTrue.\n");

}
else {
printf("\nfalse.\n");
}

output: false


Confused what went wrong.

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


Re: reading XML file using python

2010-05-17 Thread superpollo

Simon Brunning ha scritto:

On 17 May 2010 09:34:51 UTC+1, shanti bhushan  wrote:

Hi ,
i am new to python.i want to read the XML file using python it ,by
using DOm or SAX any of them.
I want to read the http://www.google.com(any hyper text) from XML and
print that.
please give me the sample program for this.


Your question isn't very clear. Do you want to read the data from a
URL (such as http://www.google.com) and parse it? If so, you probably
don't want an XML parser as such - try Beautiful Soup.


btw, is there any chance that bs will be part of the stdlib anytime soon?

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


Re: Issue with PyUnicodeObject type variables

2010-05-17 Thread Stefan Behnel

gmail, 17.05.2010 11:24:

A variable whose data type is PyUnicodeObject checked whether it is a 
UnicodeObject type.
Got output as false

example :

PyUnicodeObject *p;
if (PyUnicode_Check(path)) {
 printf("\nTrue.\n");

}
else {
 printf("\nfalse.\n");
}

output: false


Doesn't surprise me at all. Could you make sure this is the code you are 
using? Especially the names 'p' and 'path'? And that you are initialising 
neither of the two in your code?


Stefan

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


Re: reading XML file using python

2010-05-17 Thread Stefan Behnel

superpollo, 17.05.2010 11:24:

Simon Brunning ha scritto:

On 17 May 2010 09:34:51 UTC+1, shanti bhushan wrote:

i am new to python.i want to read the XML file using python it ,by
using DOm or SAX any of them.
I want to read the http://www.google.com(any hyper text) from XML and
print that.
please give me the sample program for this.


Your question isn't very clear. Do you want to read the data from a
URL (such as http://www.google.com) and parse it? If so, you probably
don't want an XML parser as such - try Beautiful Soup.


btw, is there any chance that bs will be part of the stdlib anytime soon?


If someone takes over maintainership and offers support for the stdlib, 
this might be worth discussing. Otherwise, no.


Stefan

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


Re: reading XML file using python

2010-05-17 Thread Simon Brunning
On 17 May 2010 10:43:06 UTC+1, Shanti Bhushan  wrote:
> Hi simon,
> you are right in 2nd paragaraph.
> i have a piece of XML with some URLs in it that i want to
> extract.
> I have no clue from where to get help on this.
> Please atleast guide me for document or link where i can get such help
> i can use elementary tree also but i dont know how to proceed with that.

You've not given us any idea as to the structure of your XML, so this
won't work. ;-)

import xml.etree.ElementTree as ET

for node in ET.parse('our.xml'):
print node.text

An introduction to ElementTree at .

-- 
Cheers,
Simon B.
-- 
http://mail.python.org/mailman/listinfo/python-list


Call for papers: SETP-10, USA, July 2010

2010-05-17 Thread James Heralds
It would be highly appreciated if you could share this announcement
with your colleagues, students and individuals whose research is in
software engineering, software testing, software quality assurance,
software design and related areas.

Call for papers: SETP-10, USA, July 2010

The 2010 International Conference on Software Engineering Theory and
Practice (SETP-10) (website: http://www.PromoteResearch.org ) will be
held during 12-14 of July 2010 in Orlando, FL, USA.  SETP is an
important event in the areas of Software development, maintenance, and
other areas of software engineering and related topics.

The conference will be held at the same time and location where
several other major international conferences will be taking place.
The conference will be held as part of 2010 multi-conference
(MULTICONF-10). MULTICONF-10 will be held during July 12-14, 2010 in
Orlando, Florida, USA. The primary goal of MULTICONF is to promote
research and developmental activities in computer science, information
technology, control engineering, and related fields. Another goal is
to promote the dissemination of research to a multidisciplinary
audience and to facilitate communication among researchers,
developers, practitioners in different fields. The following
conferences are planned to be organized as part of MULTICONF-10.

•   International Conference on Artificial Intelligence and Pattern
Recognition (AIPR-10)
•International Conference on Automation, Robotics and Control
Systems (ARCS-10)
•   International Conference on Bioinformatics, Computational Biology,
Genomics and Chemoinformatics (BCBGC-10)
•   International Conference on Computer Communications and Networks
(CCN-10)
•   International Conference on Enterprise Information Systems and Web
Technologies (EISWT-10)
•   International Conference on High Performance Computing Systems
(HPCS-10)
•   International Conference on Information Security and Privacy
(ISP-10)
•   International Conference on Image and Video Processing and Computer
Vision (IVPCV-10)
•   International Conference on Software Engineering Theory and Practice
(SETP-10)
•   International Conference on Theoretical and Mathematical Foundations
of Computer Science (TMFCS-10)

MULTICONF-10 will be held at Imperial Swan Hotel and Suites.  It is a
full-service resort that puts you in the middle of the fun! Located
1/2 block south of the famed International Drive, the hotel is just
minutes from great entertainment like Walt Disney World® Resort,
Universal Studios and Sea World Orlando. Guests can enjoy free
scheduled transportation to these theme parks, as well as spacious
accommodations, outdoor pools and on-site dining — all situated on 10
tropically landscaped acres. Here, guests can experience a full-
service resort with discount hotel pricing in Orlando.


We invite draft paper submissions. Please see the website
http://www.PromoteResearch.org  for more details.

Sincerely
James Heralds
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Issue with PyUnicodeObject type variables

2010-05-17 Thread mathan kumar
-- Forwarded message --
From: Stefan Behnel 
To: [email protected]
Date: Mon, 17 May 2010 11:33:40 +0200
Subject: Re: Issue with PyUnicodeObject type variables
gmail, 17.05.2010 11:24:

> A variable whose data type is PyUnicodeObject checked whether it is a
> UnicodeObject type.
> Got output as false
>
> example :
>
> PyUnicodeObject *p;
> if (PyUnicode_Check(path)) {
> printf("\nTrue.\n");
>
> }
> else {
> printf("\nfalse.\n");
> }
>
> output: false
>

Doesn't surprise me at all. Could you make sure this is the code you are
using? Especially the names 'p' and 'path'? And that you are initialising
neither of the two in your code?

Stefan


Tat was a typo mistake instead of *p pls consider *path as follows.

PyUnicodeObject *path;
if (PyUnicode_Check(path)) {
printf("\nTrue.\n");

}
else {
printf("\nfalse.\n");
}
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: platform-independent image copy/paste with Tkinter?

2010-05-17 Thread eb303
On May 15, 4:56 pm, technocake  wrote:
> Hi.
>
> Is there a good way to copy from or paste to the clipboard on all
> systems running python using Tkinter?
> started a small road too it here:
>
> #!/usr/bin/python
> __author__="technocake"
> __date__ ="$15.mai.2010 15:53:39$"
>
> from Tkinter import *
>
> if __name__ == "__main__":
>
>     def displayClipboard(event):
>         try:
>             data = event.widget.clipboard_get(type="STRING")
>         except :
>             #Need a method for displaying a image here..
>             data = "Image" #
>         finally: #Updates the textlabel
>             lbl.config(text=data)
>
>     root = Tk()
>     lbl= Label(root, width=20)
>     lbl.bind("", displayClipboard) #binding to leftclick
>     lbl.pack()
>
>     root.mainloop()

The copy part is done via the methods clipboard_clear and
clipboard_append, available on all Tkinter widgets. By the way, the
default value for the 'type' option is 'STRING', so you actually don't
need it here, and neither do you in clipboard_append.

To be able to copy/paste images is much more platform dependent. There
are actually types for clipboard contents that handle images, but they
will vary from platform to platform and sometimes from application to
application. You can even have several types for the same contents. To
get these, you can use:
widget.selection_get(selection='CLIPBOARD', type='TARGETS')
You can try to copy an image on various platforms with various
applications, then print the value for this expression to figure out
what you can do with it.

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


Re: parsing XML

2010-05-17 Thread [email protected]
On May 16, 10:52 am, Stefan Behnel  wrote:
> Jake b, 16.05.2010 09:40:
>
> > Check out Amara:http://www.xml3k.org/Amara/QuickRef
>
> > It looks promising. For a pythonic solution over sax / dom.
>
> > >>> Iter(doc.team.player)
> > # or
> > >>> doc.team.player[0].name
>
> Ah, right, and there's also lxml.objectify:
>
>      from lxml.objectify import parse
>
>      root = parse('teamfile.xml').getroot()
>
>      for player in root.player:
>          print(player.attrib)
>
> Prints an attribute dict for each player.
>
> Stefan

Thank you all so much!!!
And it's not for a homework.
Just trying to find out the style DOM, SAX, ElementTree etc. that fits
better to my kind of thinking.
Antonis
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Issue with PyUnicodeObject type variables

2010-05-17 Thread Stefan Behnel

mathan kumar, 17.05.2010 12:16:

From: Stefan Behnel

Doesn't surprise me at all. Could you make sure this is the code you are
using? Especially the names 'p' and 'path'? And that you are initialising
neither of the two in your code?


Tat was a typo mistake instead of *p pls consider *path as follows.

PyUnicodeObject *path;
if (PyUnicode_Check(path)) {


Again, you are not initialising the pointer, so it contains an arbitrary 
value when you run the program. You are lucky that it gives you a result at 
all, instead of just plain crashing.


You do not seem to have much experience with C. Is there any reason why you 
want to use it? Or is this just for curiosity?


Stefan

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


Re: an element from a set

2010-05-17 Thread Bryan
Carl Banks wrote:
[...]
> Random element from a set is such a natural idea.
>
> Even if we were to modify the set type at the C level to support it, I
> can't think of an easy way to get a random element without selection
> bias.  For instance, if you start from a random hash code, some
> elements are more likely to be selected than others, depending on
> distance between entries in the hash table.  You'd probably have to
> choose an number in range(len(s)) and count off that many, but then
> might as well have just converted it to a list or used an iterator.  A
> little disappointing, actually.
>
> Probably the "right" way is to use a binary-tree-based set.

There's a reasonably straightforward solution supporting O(1) time
random choice that also preserves the O(1) average-case time of set's
add(), remove(), and 'in'. The trick is to keep each element in both a
list and a hash table. Implementing Python's entire set interface is a
bit of project, so the code below just supports enough for a demo.

-Bryan Olson

# 

from random import choice

class SetWithRandom:

def __init__(self, *args):
self.lst = list(*args)
self.dct = dict((elem, i) for (i, elem) in
enumerate(self.lst))

def audit(self):
# Test consistency of dict and list.
assert len(self.lst) == len(self.dct)
for elem in self.dct:
assert self.lst[self.dct[elem]] == elem

def random(self):
return choice(self.lst)

def add(self, elem):
if elem not in self.dct:
self.dct[elem] = len(self.lst)
self.lst.append(elem)

def remove(self, elem):
index = self.dct[elem]
# Move the last item into vacated index.
mover = self.lst[-1]
self.lst[index] = mover
self.dct[mover] = index
del self.dct[elem]
self.lst.pop()

def __len__(self):
return len(self.lst)

def __contains__(self, elem):
return elem in self.dct

def __iter__(self):
return self.dct.__iter__()


# -
# Test against Python's built-in set.
for i in range(0, 100, 20):
trange = list(range(1000, 1000 + i))
pyset = set(trange)
testset = SetWithRandom(pyset)
testset.audit()
assert pyset == set(testset)
rands = set(testset.random() for _ in trange)
assert len(rands) >= i / 4
while pyset:
randx = testset.random()
pyset.remove(randx)
testset.remove(randx)
testset.audit()
for _ in range(choice([0, 0, 1, 2])):
randx = choice(trange)
pyset.add(randx)
testset.add(randx)
assert pyset == set(testset)
assert not testset

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


cmd with three arguments

2010-05-17 Thread [email protected]
Hi pythonistas,
While playing with the Python Standard Library, i came across "cmd".
So I'm trying to make a console application. Everything works fine, i
created many function with do_(self, line) prefix, but when i
tried to create a function with more arguments
 i can't make it work.  e.g
def do_connect(self, ip, command):

>>> connect 127.0.0.1 delete
 Are there any work arounds

Thanks in advance

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


Re: cmd with three arguments

2010-05-17 Thread Tim Chase

On 05/17/2010 07:11 AM, [email protected] wrote:

While playing with the Python Standard Library, i came across "cmd".
So I'm trying to make a console application. Everything works fine, i
created many function with do_(self, line) prefix, but when i
tried to create a function with more arguments
  i can't make it work.  e.g
def do_connect(self, ip, command):


connect 127.0.0.1 delete

  Are there any work arounds


You simply receive all the text after the command:

  class C(Cmd):
def do_thing(self, arguments):
  print repr(arguments)

If you want to split it, you can do it boringly:

def do_thing(self, arguments):
  args = arguments.split()

or you can let Python's standard library do some heavy-lifting 
for you:


  import shlex
  #...
def do_thing(self, arguments):
  args = shlex.split(arguments)

-tkc



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


python application question

2010-05-17 Thread a
I am trying to write an application that takes two files from over the
internet and plots one against the other

i am getting the data ok.

if i want to plot it i have to use something like matplotlib?  but
this doesn't come with the standard installation.  so if i want
someone else to use this application, do they have to install
matplotlib themselves or is there a better way?

ps someone helped me with enumerate(), which works on the linux but
not on the windows?

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


Re: cmd with three arguments

2010-05-17 Thread [email protected]
On May 17, 4:12 pm, Tim Chase  wrote:
> On 05/17/2010 07:11 AM, [email protected] wrote:
>
> > While playing with the Python Standard Library, i came across "cmd".
> > So I'm trying to make a console application. Everything works fine, i
> > created many function with do_(self, line) prefix, but when i
> > tried to create a function with more arguments
> >   i can't make it work.  e.g
> > def do_connect(self, ip, command):
>
>  connect 127.0.0.1 delete
> >   Are there any work arounds
>
> You simply receive all the text after the command:
>
>    class C(Cmd):
>      def do_thing(self, arguments):
>        print repr(arguments)
>
> If you want to split it, you can do it boringly:
>
>      def do_thing(self, arguments):
>        args = arguments.split()
>
> or you can let Python's standard library do some heavy-lifting
> for you:
>
>    import shlex
>    #...
>      def do_thing(self, arguments):
>        args = shlex.split(arguments)
>
> -tkc

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


Re: cmd with three arguments

2010-05-17 Thread Peter Otten
[email protected] wrote:

> Hi pythonistas,
> While playing with the Python Standard Library, i came across "cmd".
> So I'm trying to make a console application. Everything works fine, i
> created many function with do_(self, line) prefix, but when i
> tried to create a function with more arguments
>  i can't make it work.  e.g
> def do_connect(self, ip, command):
> 
 connect 127.0.0.1 delete
>  Are there any work arounds
> 
> Thanks in advance
> 
> Antonis

You have to split the user input into arguments yourself. You can do this in 
the body of the do_xxx() methods, use a decorator, or subclass cmd.Cmd.

Here's a solution using a decorator:

import cmd
import inspect
import shlex

def split(f):
def g(self, line):
argvalues = shlex.split(line)
argnames = inspect.getargspec(f).args
argcount = len(argnames) - 1
if len(argvalues) != argcount:
print "Need exactly %d args" % argcount
return
return f(self, *argvalues)
return g

class Cmd(cmd.Cmd):
@split
def do_connect(self, ip, command):
print "ip=%r, command=%r" % (ip, command)


if __name__ == "__main__":
c = Cmd()
c.cmdloop()

And here's a subclass that avoids the need for explicit @split decorations:

import cmd
import inspect
import shlex

def split(f):
def g(line):
argvalues = shlex.split(line)
argnames = inspect.getargspec(f).args
argcount = len(argnames) -1
if len(argvalues) != argcount:
print "Need exactly %d args" % argcount
return
return f(*argvalues)
return g

class CmdBase(cmd.Cmd, object):
def __getattribute__(self, name):
attr = object.__getattribute__(self, name)
if name.startswith("do_"):
attr = split(attr)
return attr

class Cmd(CmdBase):
def do_connect(self, ip, command):
print "ip=%r, command=%r" % (ip, command)


if __name__ == "__main__":
c = Cmd()
c.cmdloop()

Now you've got an idea of the general direction you can certainly come up 
with something less hackish ;)

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


pythonic ssh

2010-05-17 Thread John Maclean

hi,

pyssh, pexpect, paramiko or creating your your own sockets. what do you 
use to pythonically ssh to boxes?



--
John Maclean
MSc. (DIC) BSc. (Hons)
Linux Systems and Applications
07739 171 531
--
http://mail.python.org/mailman/listinfo/python-list


Re: abc don't play well with private method

2010-05-17 Thread mouadino
Hello
and thanx for your answer it's was very helpful

but just to clear some thinks :

> There's no such thing as a "private" attribute in Python. The
> name-mangling mechanism invoked by "__name" is really meant to avoid
> accidental redefinition of the attribute in a derived class.

> In this case, your attribute is expected to be redefined, so you
> definitly don't want any name mangling here.

yes , but what i have supposed is that the name mangling will not be
applied when you use abc especially when you decorate the function
with abc.abstractmethod , because it's will(should) be redefined (so
something is wrong with the abc module) .

> Also and FWIW, the naming convention for "implementation attributes" is
> a single leading underscore

sorry but i don't agree on this. the two underscore (__) are used in
classes level for defining private method in the python way, and the
one underscore (_) is used in the module level :

"""Prepending a single underscore (_) has some support for protecting
module variables and functions (not included with import * from).
Prepending a double underscore (__) to an instance variable or method
effectively serves to make the variable or method private to its class
(using name mangling). """
src:http://google-styleguide.googlecode.com/svn/trunk/pyguide.html

> >     def close(self):
>
> >         self.close()
>
> >     def quit(self):
>
> >         self.quit()
>
> Don't you see kind of a problem here ? Something like, say, an infinite
> recursion ?

yep , thanx


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


Re: abc don't play well with private method

2010-05-17 Thread mouadino
Hello
and thanx for your answer it's was very helpful

but just to clear some thinks :

> There's no such thing as a "private" attribute in Python. The
> name-mangling mechanism invoked by "__name" is really meant to avoid
> accidental redefinition of the attribute in a derived class.

> In this case, your attribute is expected to be redefined, so you
> definitly don't want any name mangling here.

yes , but what i have supposed is that the name mangling will not be
applied when you use abc especially when you decorate the function
with abc.abstractmethod , because it's will(should) be redefined (so
something is wrong with the abc module) .

> Also and FWIW, the naming convention for "implementation attributes" is
> a single leading underscore

sorry but i don't agree on this. the two underscore (__) are used in
classes level for defining private method in the python way, and the
one underscore (_) is used in the module level :

"""Prepending a single underscore (_) has some support for protecting
module variables and functions (not included with import * from).
Prepending a double underscore (__) to an instance variable or method
effectively serves to make the variable or method private to its class
(using name mangling). """
src:http://google-styleguide.googlecode.com/svn/trunk/pyguide.html

> >     def close(self):
>
> >         self.close()
>
> >     def quit(self):
>
> >         self.quit()
>
> Don't you see kind of a problem here ? Something like, say, an infinite
> recursion ?

yep , thanx


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


Re: cmd with three arguments

2010-05-17 Thread [email protected]
On May 17, 4:34 pm, Peter Otten <[email protected]> wrote:
> [email protected] wrote:
> > Hi pythonistas,
> > While playing with the Python Standard Library, i came across "cmd".
> > So I'm trying to make a console application. Everything works fine, i
> > created many function with do_(self, line) prefix, but when i
> > tried to create a function with more arguments
> >  i can't make it work.  e.g
> > def do_connect(self, ip, command):
>
>  connect 127.0.0.1 delete
> >  Are there any work arounds
>
> > Thanks in advance
>
> > Antonis
>
> You have to split the user input into arguments yourself. You can do this in
> the body of the do_xxx() methods, use a decorator, or subclass cmd.Cmd.
>
> Here's a solution using a decorator:
>
> import cmd
> import inspect
> import shlex
>
> def split(f):
>     def g(self, line):
>         argvalues = shlex.split(line)
>         argnames = inspect.getargspec(f).args
>         argcount = len(argnames) - 1
>         if len(argvalues) != argcount:
>             print "Need exactly %d args" % argcount
>             return
>         return f(self, *argvalues)
>     return g
>
> class Cmd(cmd.Cmd):
>     @split
>     def do_connect(self, ip, command):
>         print "ip=%r, command=%r" % (ip, command)
>
> if __name__ == "__main__":
>     c = Cmd()
>     c.cmdloop()
>
> And here's a subclass that avoids the need for explicit @split decorations:
>
> import cmd
> import inspect
> import shlex
>
> def split(f):
>     def g(line):
>         argvalues = shlex.split(line)
>         argnames = inspect.getargspec(f).args
>         argcount = len(argnames) -1
>         if len(argvalues) != argcount:
>             print "Need exactly %d args" % argcount
>             return
>         return f(*argvalues)
>     return g
>
> class CmdBase(cmd.Cmd, object):
>     def __getattribute__(self, name):
>         attr = object.__getattribute__(self, name)
>         if name.startswith("do_"):
>             attr = split(attr)
>         return attr
>
> class Cmd(CmdBase):
>     def do_connect(self, ip, command):
>         print "ip=%r, command=%r" % (ip, command)
>
> if __name__ == "__main__":
>     c = Cmd()
>     c.cmdloop()
>
> Now you've got an idea of the general direction you can certainly come up
> with something less hackish ;)
>
> Peter

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


Re: abc don't play well with private method

2010-05-17 Thread mouadino
Hello
and thanx for your answer it's was very helpful

but just to clear some thinks :

> There's no such thing as a "private" attribute in Python. The
> name-mangling mechanism invoked by "__name" is really meant to avoid
> accidental redefinition of the attribute in a derived class.

> In this case, your attribute is expected to be redefined, so you
> definitly don't want any name mangling here.

yes , but what i have supposed is that the name mangling will not be
applied when you use abc especially when you decorate the function
with abc.abstractmethod , because it's will(should) be redefined (so
something is wrong with the abc module) .

> Also and FWIW, the naming convention for "implementation attributes" is
> a single leading underscore

sorry but i don't agree on this. the two underscore (__) are used in
classes level for defining private method in the python way, and the
one underscore (_) is used in the module level :

"""Prepending a single underscore (_) has some support for protecting
module variables and functions (not included with import * from).
Prepending a double underscore (__) to an instance variable or method
effectively serves to make the variable or method private to its class
(using name mangling). """
src:http://google-styleguide.googlecode.com/svn/trunk/pyguide.html

> >     def close(self):
>
> >         self.close()
>
> >     def quit(self):
>
> >         self.quit()
>
> Don't you see kind of a problem here ? Something like, say, an infinite
> recursion ?

yep , thanx


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


Re: python application question

2010-05-17 Thread Adam Tauno Williams
On Mon, 2010-05-17 at 06:20 -0700, a wrote:
> if i want to plot it i have to use something like matplotlib?  but
> this doesn't come with the standard installation.  so if i want
> someone else to use this application, do they have to install
> matplotlib themselves or is there a better way?

Use PyPI to distribute your application and declare matplotlib as a
requirement in your setup.py.  Then when they easy_install it should
take care of it.

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


Re: imports and exec

2010-05-17 Thread Paul Carter
On May 16, 4:22 pm, Patrick Maupin  wrote:
> On May 16, 1:51 pm, Paul Carter  wrote:
>
>
>
> > We are using python for our build system. Each subproject dir has a
> > python script that builds it. Parent dirs have python scripts that
> > recurse into their children and use exec to invoke the python scripts.
> > Recently we discovered that one of the python scripts works when
> > invoked directly, but fails when invoked with exec. I've created a
> > very simple pair of python scripts that demonstrates the problem.
> > (We're using python 2.6)
>
> > Can someone explain or point to a good explanation of why this problem
> > occurs?
>
> > I have two python files: prim.py and sec.py.
> > prim.py:
> > -
> > #!/usr/bin/env python
>
> > ##sec2 = open('sec.py')
> > ##exec sec2
>
> > def invoke():
> >   sec = open('sec.py')
> >   exec sec
>
> > invoke()
> > --
>
> > and sec.py:
> > --
> > import sys
>
> > def sec():
> >   print('Inside sec(): ' +  str(sys.argv))
>
> > print('Outside sec(): ' + str(sys.argv))
> > sec()
> > --
>
> > When I run prim.py, I get an error:
> > 
> > Outside sec(): ['./prim.py']
> > Traceback (most recent call last):
> >   File "./prim.py", line 10, in 
> >     invoke()
> >   File "./prim.py", line 8, in invoke
> >     exec sec
> >   File "sec.py", line 7, in 
> >     sec()
> >   File "sec.py", line 4, in sec
> >     print('Inside sec(): ' +  str(sys.argv))
> > NameError: global name 'sys' is not defined
> > --
>
> > I don't understand why the sys import is not visible in the sec()
> > function. I can fix this by adding a:
> >   global sys
> > or
> >   import sys
> > inside the sec() function. But I would like to understand why this is
> > necessary, especially since sys is visible in sec.py outside of the
> > sec() function. I found this page discussing exec
>
> >http://docs.python.org/reference/executionmodel.html
>
> > but I'm afraid I couldn't quite follow it. It makes me think that a
> > free variable is involved, but I don't see how. It did made me try
> > invoking exec in prim.py outside of the invoke() function (see the
> > commented out code). Everything worked fine when I did that.
>
> > Can someone set me straight? Suggestions on avoiding this problem are
> > welcome as well!
>
> > Thanks in advance.
>
> Yes.  Since you did not pass any dictionaries to your exec of "sec",
> sec inherited the globals and locals from the calling function.  So
> the import of sys happened in that functions locals (bad practice in
> any case) and the globals used by sec() are the globals of your main
> module.
>
> Especially if invoked from inside a function, you should always pass a
> dict to exec.  Just "exec sec() in {}" will do the trick.  But if you
> want to use your caller's dictionaries, you can do "exec sec() in
> globals()"  But you should *not* use a functions locals directly if
> you are going to modify them (as you are currently doing).
>
> Regards,
> Pat

Thanks, that helped a lot! I was misunderstanding what exec does by
default.

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


Re: python application question

2010-05-17 Thread Patrick Maupin
On May 17, 8:20 am, a  wrote:

> ps someone helped me with enumerate(), which works on the linux but
> not on the windows?

enumerate() works fine on windows.  Perhaps your windows box has a
really old Python?

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


[ANN] doit - automation tool 0.8 released

2010-05-17 Thread Eduardo Schettino
pypi: http://pypi.python.org/pypi/doit
homepage: http://python-doit.sourceforge.net/


`doit` comes from the idea of bringing the power of build-tools to
execute any kind of task. It will keep track of dependencies between
"tasks" and execute them only when necessary. It was designed to be
easy to use and "get out of your way".

Features:

 * Easy to use, "no-API"
 * Use python to dynamically create tasks on-the-fly
 * Flexible, adapts to many workflows for creation of tasks/rules/recipes
 * Support for multi-process parallel execution
 * Built-in integration of inotify (automatically re-execution)

`doit` can be used as:

 * a build tool (generic and flexible)
 * home of your management scripts (it helps you organize and combine
shell scripts and python scripts)
 * a functional tests runner (combine together different tools)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Access to comp.lang.python

2010-05-17 Thread cjw

On 16-May-10 12:47 PM, Jim Byrnes wrote:

Grant Edwards wrote:

On 2010-05-16, cjw wrote:

On 16-May-10 01:31 AM, James Mills wrote:

On Sun, May 16, 2010 at 3:12 PM, Aahz wrote:

It's also at least partly due to problems with mail<->news gateways
and
the differing fields used to maintain threading.


Some blame goes on MUAs too :)


Thanks for the responses.

Is it possible to connect a newsreader to gmane?


nntp://news.gmane.org/



Could someone please explain how to subscribe to this list on gmane. I
subscribe to a couple of other groups there but can't find this one.

Regards, Jim


With Thunderbird, you need to set up a new account:

Tools => AccountSettings => Account Actions => Add another account.

=> News Group Account => Next

From there, it's a matter of filling in the blanks.

The news server is "news.gmane.org".

I'm just trying it.

Colin W,
--
http://mail.python.org/mailman/listinfo/python-list


Re: pythonic ssh

2010-05-17 Thread Michael Crute
On Mon, May 17, 2010 at 9:37 AM, John Maclean  wrote:
> pyssh, pexpect, paramiko or creating your your own sockets. what do you use
> to pythonically ssh to boxes?

I think the answer to this depends on your goals. Paramiko is the best
way to go if you want a pythonic API to ssh but you also will
introduce a dependency on paramiko and a transitive dependency on
pycrypto (which requires openssl). I personally prefer to just use
subprocess with the ssh binary for most of my scripts because it
doesn't introduce any extra dependencies and is relatively easy to
implement. pyssh tries to wrap up the common ssh patterns using
os.popen but it hasn't been maintained in several years so your best
bet is probably to stick with using subprocess if you don't go with
paramiko.

-- 
Michael E. Crute
http://mike.crute.org

It is a mistake to think you can solve any major problem just with
potatoes. --Douglas Adams
-- 
http://mail.python.org/mailman/listinfo/python-list


Pyserial and pysqlite data types, need advice

2010-05-17 Thread jon vs. python
Hi,
I'm trying to store frames received via serial port (using Pyserial) into a
sqlite database (using Pysqlite) in order to perform off-line processing.
Thus I could use both SQL's power and Python's magic to make everything
easier. I'd like my code to be generic and work both for binary and ascii
protocols, too.

Which kind of data should I use to store the frames?
Should I store every byte as a char in VARCHAR? (This seems to fail when
trying to store non printable characters).
Should I encapsulate frames in buffer objects and store them in BLOBs? (This
seems to work but hides content and thus doesn't allow to use database
operations directly on the data)
I've also tried, unsuccessfully, to use bytearrays with pysqlite...

Any suggestion?

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


[jython] Problem with an huge dictionary

2010-05-17 Thread keobox
Hi,
I apologize if this is not the right group for posting question
related to jython.
Please give me the right directions if this is the case.

The question is:
Is there a limit on the number of entries a dictionary can have i
jython?

I wrote a little app where my data is stored in a huge dictionary
(11746 entries) generated with a python script.
When I try to import the dictionary, jython complains with the
following message:

Microsoft Windows XP [Version 5.1.2600]
(C) Copyright 1985-2001 Microsoft Corp.

C:\Documents and Settings\ceplacan\My Documents\Documents\Source\source
\Python\j
moco-test>jython
Jython 2.5.1 (Release_2_5_1:6813, Sep 26 2009, 13:47:54)
[Java HotSpot(TM) Client VM (Sun Microsystems Inc.)] on java1.5.0_13
Type "help", "copyright", "credits" or "license" for more information.
>>> import jmoco_event_data
Traceback (most recent call last):
  File "", line 1, in 
java.lang.ClassFormatError: Invalid this class index 3241 in constant
pool in cl
ass file _1076
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:620)
at org.python.core.BytecodeLoader
$Loader.loadClassFromBytes(BytecodeLoad
er.java:119)
at
org.python.core.BytecodeLoader.makeClass(BytecodeLoader.java:37)
at org.python.core.BytecodeLoader.makeCode(BytecodeLoader.java:
67)
at org.python.core.imp.createFromSource(imp.java:288)
at org.python.core.imp.loadFromSource(imp.java:514)
at org.python.core.imp.find_module(imp.java:411)
at org.python.core.imp.import_next(imp.java:635)
at org.python.core.imp.import_name(imp.java:746)
at org.python.core.imp.importName(imp.java:806)
at org.python.core.ImportFunction.__call__(__builtin__.java:
1232)
at org.python.core.PyObject.__call__(PyObject.java:367)
at org.python.core.__builtin__.__import__(__builtin__.java:
1202)
at org.python.core.__builtin__.__import__(__builtin__.java:
1185)
at org.python.core.imp.importOne(imp.java:817)
at org.python.pycode._pyx1.f$0(:1)
at org.python.pycode._pyx1.call_function()
at org.python.core.PyTableCode.call(PyTableCode.java:165)
at org.python.core.PyCode.call(PyCode.java:18)
at org.python.core.Py.runCode(Py.java:1204)
at org.python.core.Py.exec(Py.java:1248)
at
org.python.util.PythonInterpreter.exec(PythonInterpreter.java:181)
at
org.python.util.InteractiveInterpreter.runcode(InteractiveInterpreter
.java:89)
at
org.python.util.InteractiveInterpreter.runsource(InteractiveInterpret
er.java:70)
at
org.python.util.InteractiveInterpreter.runsource(InteractiveInterpret
er.java:46)
at
org.python.util.InteractiveConsole.push(InteractiveConsole.java:110)
at
org.python.util.InteractiveConsole.interact(InteractiveConsole.java:9
0)
at org.python.util.jython.run(jython.java:316)
at org.python.util.jython.main(jython.java:129)

java.lang.ClassFormatError: java.lang.ClassFormatError: Invalid this
class index
 3241 in constant pool in class file _1076

What can I do to avoid this?

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


[BarCamp] WebWorkersCamp BarCamp: NodeJS, NoSQL, Message Queues, Asynchronous programming, Web Sockets, Distributed Applications, Decentralized Social Networks, buzzword generators...

2010-05-17 Thread Pierre
Hello,

AF83 will be holding a barcamp event on Saturday afternoon, July 3rd
in Paris (in La Cantine, a famous Parisian tech place). We wanted to
let you know about this event and tell you that you would be most
welcome if you could join us on that day.

In the ever-growing context of real-time web and multiplying
webservices, websites as they are now designed are hardly scalable, or
at high costs. So we thought appropriate to hold an event to discuss
the technologies which will allow us to code differently in order to
solve these issues.

Our guests will be invited to share their experience in asynchronous
programming (server-side javascript with NodeJS, Python’s Tornado,
Ruby’s Event Machine, etc.) as well as Websockets, NoSQL databases,
queues, XMPP and others.

We’d be thrilled to have you amongst us and hear your story on this
matter! We thought this could be the opportunity for you to tell us
about your work and learn from other developers. Would you be
interested in coming and, if you wish, leading a workshop?
Then register on http://barcamp.org/WebWorkersCamp .

We’re looking forward to hearing from you soon,

Thank you,
The AF83 team.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: an element from a set

2010-05-17 Thread Raymond Hettinger
On May 14, 3:24 pm, gerardob  wrote:
> Hello, let S be a python set which is not empty
> (http://docs.python.org/library/sets.html)
>
> i would like to obtain one element (anyone, it doesn't matter which one) and
> assign it to a variable.
>
> How can i do this?

x = next(iter(s))

or you can supply a default value in case the set is empty:

x = next(iter(s), default_value)


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


Re: [jython] Problem with an huge dictionary

2010-05-17 Thread Allan Davis
KeoBox,

Can i look at the jython file you are executing? the ClassFormatException is
not with the size of the dictionary.  Jython is failing on an import.

thanks,
--
Allan Davis
Member of NetBeans Dream Team
http://wiki.netbeans.org/NetBeansDreamTeam
Lead Developer, nbPython
http://wiki.netbeans.org/Python
http://codesnakes.blogspot.com (my blog)
Co-Chair, CajunJUG
http://www.cajunjug.org


On Mon, May 17, 2010 at 10:09 AM, keobox  wrote:

> Hi,
> I apologize if this is not the right group for posting question
> related to jython.
> Please give me the right directions if this is the case.
>
> The question is:
> Is there a limit on the number of entries a dictionary can have i
> jython?
>
> I wrote a little app where my data is stored in a huge dictionary
> (11746 entries) generated with a python script.
> When I try to import the dictionary, jython complains with the
> following message:
>
> Microsoft Windows XP [Version 5.1.2600]
> (C) Copyright 1985-2001 Microsoft Corp.
>
> C:\Documents and Settings\ceplacan\My Documents\Documents\Source\source
> \Python\j
> moco-test>jython
> Jython 2.5.1 (Release_2_5_1:6813, Sep 26 2009, 13:47:54)
> [Java HotSpot(TM) Client VM (Sun Microsystems Inc.)] on java1.5.0_13
> Type "help", "copyright", "credits" or "license" for more information.
> >>> import jmoco_event_data
> Traceback (most recent call last):
>  File "", line 1, in 
> java.lang.ClassFormatError: Invalid this class index 3241 in constant
> pool in cl
> ass file _1076
>at java.lang.ClassLoader.defineClass1(Native Method)
>at java.lang.ClassLoader.defineClass(ClassLoader.java:620)
>at org.python.core.BytecodeLoader
> $Loader.loadClassFromBytes(BytecodeLoad
> er.java:119)
>at
> org.python.core.BytecodeLoader.makeClass(BytecodeLoader.java:37)
>at org.python.core.BytecodeLoader.makeCode(BytecodeLoader.java:
> 67)
>at org.python.core.imp.createFromSource(imp.java:288)
>at org.python.core.imp.loadFromSource(imp.java:514)
>at org.python.core.imp.find_module(imp.java:411)
>at org.python.core.imp.import_next(imp.java:635)
>at org.python.core.imp.import_name(imp.java:746)
>at org.python.core.imp.importName(imp.java:806)
>at org.python.core.ImportFunction.__call__(__builtin__.java:
> 1232)
>at org.python.core.PyObject.__call__(PyObject.java:367)
>at org.python.core.__builtin__.__import__(__builtin__.java:
> 1202)
>at org.python.core.__builtin__.__import__(__builtin__.java:
> 1185)
>at org.python.core.imp.importOne(imp.java:817)
>at org.python.pycode._pyx1.f$0(:1)
>at org.python.pycode._pyx1.call_function()
>at org.python.core.PyTableCode.call(PyTableCode.java:165)
>at org.python.core.PyCode.call(PyCode.java:18)
>at org.python.core.Py.runCode(Py.java:1204)
>at org.python.core.Py.exec(Py.java:1248)
>at
> org.python.util.PythonInterpreter.exec(PythonInterpreter.java:181)
>at
> org.python.util.InteractiveInterpreter.runcode(InteractiveInterpreter
> .java:89)
>at
> org.python.util.InteractiveInterpreter.runsource(InteractiveInterpret
> er.java:70)
>at
> org.python.util.InteractiveInterpreter.runsource(InteractiveInterpret
> er.java:46)
>at
> org.python.util.InteractiveConsole.push(InteractiveConsole.java:110)
>at
> org.python.util.InteractiveConsole.interact(InteractiveConsole.java:9
> 0)
>at org.python.util.jython.run(jython.java:316)
>at org.python.util.jython.main(jython.java:129)
>
> java.lang.ClassFormatError: java.lang.ClassFormatError: Invalid this
> class index
>  3241 in constant pool in class file _1076
>
> What can I do to avoid this?
>
> Regards,
> Cesare
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Installing Lightweight Python

2010-05-17 Thread Nima
I'd like to install python on an embedded system. It's a powerful x86-
based computer with the only limitation of having a small-size flash
ROM as its secondary storage. So there is no hard drive and the system
is booted from the flash memory.
The operating system, BusyBox (a flavor of Linux), and other
applications occupy most of the flash memory. As the subject implies,
Python isn't already installed on the box. I tried to compile/install
python on a Linux box which roughly took 60MB of the memory. The
maximum amount of Flash memory I'm permitted to use is about 10-20 MB.
Is there a light-weight implementation of python which I could use? Is
there a way to remove unnecessary modules?
BTW,
+ I'm supposed to write a web management interface for this system
(using python).
+ I know how to use Google!
+ I'm a newbie, so please be gentle :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: an element from a set

2010-05-17 Thread Terry Reedy

On 5/17/2010 12:53 AM, Carl Banks wrote:


Even if we were to modify the set type at the C level to support it, I
can't think of an easy way to get a random element without selection
bias.


At the C level, a (hashed) set is a list with empty slots. So the C 
function would have to pick random ints in the appropriate range until 
it got an index for a non-empty slot. A sequence of selections from 
equal sets would not, in general, be reproducible, since the internal 
array need not be the same.


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


OT Pagina sobre programacion en paralelo

2010-05-17 Thread Miguel Beltran R.
Hola Lista,

Disculpen el off-topic, pero creo que aqui fue donde una vez postearon un
enlace sobre programación en paralelo y explica porque no es el doble de
rapido que con 1 micro.

Tambien hablaba de que si el algoritmo es log(n) o log(n2) o algo asi

ya lo busque en el historial pero no lo encuentro, alguien tiene el enlace?
o no lo vi aqui?

-- 

Lo bueno de vivir un dia mas
es saber que nos queda un dia menos de vida
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A couple questions about classes and inheritance

2010-05-17 Thread Terry Reedy

On 5/16/2010 10:52 PM, Mark Young wrote:

You can't subclass Ellipsis.


You clipped what I believe you were responding to that I posted:
"I believe that in 3.1, the builtin classes with builtin names can be 
subclassed and and those without cannot. (If you find any exceptionss, 
please post ;-). The ones with names are exactly the ones you are 
expected to directly interact with in normal code."


Ellipsis is not an exception to what I said but rather an example that 
supports my point. It is not a class, but an instance of an 
intentionally *unnamed* class which one cannot subclass. It is unnamed 
in the sense of not being bound to a name in a namespace (builtins), 
even though, like all classes, it has a 'definition' or name-attribute name.


>>> Ellipsis
Ellipsis
>>> type(Ellipsis)

>>> class C(type(Ellipsis)): pass

Traceback (most recent call last):
  File "", line 1, in 
class C(type(Ellipsis)): pass
TypeError: type 'ellipsis' is not an acceptable base type

The class of None is also unnamed, while the class of True and False, 
bool, is named so we can call it. It does turn out that bool *is* an 
exception to the general rule.


>>> class C(bool): pass

Traceback (most recent call last):
  File "", line 1, in 
class C(bool): pass
TypeError: type 'bool' is not an acceptable base type

If there were a practical reason to subclass it, a subclass of int 
instead should do just as well.


Terry Jan Reedy

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


Re: Installing Lightweight Python

2010-05-17 Thread geremy condra
On Mon, May 17, 2010 at 9:12 AM, Nima  wrote:
> I'd like to install python on an embedded system. It's a powerful x86-
> based computer with the only limitation of having a small-size flash
> ROM as its secondary storage. So there is no hard drive and the system
> is booted from the flash memory.
> The operating system, BusyBox (a flavor of Linux), and other
> applications occupy most of the flash memory. As the subject implies,
> Python isn't already installed on the box. I tried to compile/install
> python on a Linux box which roughly took 60MB of the memory. The
> maximum amount of Flash memory I'm permitted to use is about 10-20 MB.
> Is there a light-weight implementation of python which I could use? Is
> there a way to remove unnecessary modules?
> BTW,
> + I'm supposed to write a web management interface for this system
> (using python).
> + I know how to use Google!
> + I'm a newbie, so please be gentle :)
> --
> http://mail.python.org/mailman/listinfo/python-list
>

I'm not an expert, but there are probably a large-ish number of modules
you could remove without much sacrifice on your part. Looking at the
module list and just picking the platform-dependent ones:

* _winreg
* aepack
* aetools
* aetypes
* AL
* al
* applesingle
* autoGIL
* buildtools
* Carbon
* cd
* cfmfile
* chunk
* colorpicker
* etc
* etc
* etc

You could also probably remove things like 2to3, tabnanny, etc,
and I doubt tkinter is doing you much good.

I also recall someone at pycon talking about importing modules
from a .zip archive. I'm not sure how easy/hard that is, but you
may want to look at PEP 302.

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


Re: OT Pagina sobre programacion en paralelo

2010-05-17 Thread Terry Reedy

On 5/17/2010 12:27 PM, Miguel Beltran R. wrote:


Disculpen el off-topic, pero creo que aqui fue donde una vez postearon
un enlace sobre programación en paralelo y explica porque no es el doble
de rapido que con 1 micro.


No me recuerdo algo como esto. Lo dudo mucho.



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


Converting datetime.ctime() values to Unicode

2010-05-17 Thread python
I would like to convert datetime.ctime() values to Unicode.

Using Python 2.6.4 running under Windows I can set my locale to
Spanish like below:

>>> import locale
>>> locale.setlocale(locale.LC_ALL, 'esp' )

Then I can pass %a, %A, %b, and %B to ctime() to get day and
month names and abbreviations.

>>> import datetime
>>> dateValue = datetime.date( 2010, 5, 15 )
>>> dayName = dateValue.strftime( '%A' )
>>> dayName
's\xe1bado'

How do I convert the 's\xe1bado' value to Unicode? Specifically what
encoding do I use?

I'm thinking I might do something like the following, but I'm not sure
this is the right approach.

>>> codePage = locale.getdefaultlocale()[ 1 ]
>>> dayNameUnicode = unicode( dayName, codePage )
>>> dayNameUnicode
u's\xe1bado'

Feedback appreciated.

Regards,
Malcolm

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


Re: Engineering numerical format PEP discussion

2010-05-17 Thread Eike Welk
Keith wrote:

> I am considering writing a PEP for the inclusion of an engineering
> format specifier, and would appreciate input from others.

I think it's a good idea. I regularly type numbers into my pocket calculator 
just to do this conversion. 


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


Re: Converting datetime.ctime() values to Unicode

2010-05-17 Thread python
In researching a solution, I believe locale.getpreferredencoding() might
be a better choice (than locale.getdefaultlocale()[ 1 ]) for determining
a system's default encoding?

In other words change:

>>> codePage = locale.getdefaultlocale()[ 1 ]

To this:

>>> codePage = locale.getpreferredencoding() 

... in my original post's code (original post follows my signature).

Malcolm

- Original message -
From: [email protected]
To: [email protected]
Date: Mon, 17 May 2010 13:54:27 -0400
Subject: Converting datetime.ctime() values to Unicode

I would like to convert datetime.ctime() values to Unicode.

Using Python 2.6.4 running under Windows I can set my locale to
Spanish like below:

>>> import locale
>>> locale.setlocale(locale.LC_ALL, 'esp' )

Then I can pass %a, %A, %b, and %B to ctime() to get day and
month names and abbreviations.

>>> import datetime
>>> dateValue = datetime.date( 2010, 5, 15 )
>>> dayName = dateValue.strftime( '%A' )
>>> dayName
's\xe1bado'

How do I convert the 's\xe1bado' value to Unicode? Specifically what
encoding do I use?

I'm thinking I might do something like the following, but I'm not sure
this is the right approach.

>>> codePage = locale.getdefaultlocale()[ 1 ]
>>> dayNameUnicode = unicode( dayName, codePage )
>>> dayNameUnicode
u's\xe1bado'

Feedback appreciated.

Regards,
Malcolm

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

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


Re: Converting datetime.ctime() values to Unicode

2010-05-17 Thread Jerry Hill
On Mon, May 17, 2010 at 2:14 PM,   wrote:
> In researching a solution, I believe locale.getpreferredencoding() might
> be a better choice (than locale.getdefaultlocale()[ 1 ]) for determining
> a system's default encoding?

I haven't used the locale module a lot, but it seems to me that if
you're setting the locale with locale.setlocale(), you should get the
encoding from locale.getlocale()[1].

You're not really interested in the system's default encoding at this
point, you're interested in the encoding of the locale you've
explicitly set.

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


Python3 buffer extra byte??

2010-05-17 Thread Dodo

Let's consider this code:

#!/usr/bin/python3
import cgi, sys
print("Content-type:image/jpeg\n\n")
f = open("img.jpg","rb")
sys.stdout.flush()
sys.stdout.buffer.write( f.read() )
f.close()

I receive the file with one padding byte at the start of the file (0x0a)
http://www.1pix.org/multi/images/wg7zg58gsgbhc9cppo5i.jpg

Any idea why?

Dorian
(yes, this is the continuation of "CGI python 3 write RAW BINARY")
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python3 buffer extra byte??

2010-05-17 Thread Antoine Pitrou
On Mon, 17 May 2010 20:34:21 +0200
Dodo  wrote:

> Let's consider this code:
> 
> #!/usr/bin/python3
> import cgi, sys
> print("Content-type:image/jpeg\n\n")

print() adds an additional \n, so there's one too many.
Also, HTTP headers should be separated with \r\n, not \n.

(besides, under Windows \n will be converted to \r\n by the text I/O
layer, therefore, it would be better to use the binary I/O layer, a.k.a
sys.stdout.buffer, if you want your script to be portable)

Therefore, I would advocate rewriting it as:

sys.stdout.buffer.write(b"Content-type:image/jpeg\r\n\r\n")



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


Re: Installing Lightweight Python

2010-05-17 Thread Nima Mohammadi
Thanks Geremy :)

The majority of installed files (56MB of data) reside in /lib/
python2.6/. So far, I took these steps to make it as compact as
possible:
1. I deleted /lib/python2.6/test directory. This reduced the size by
20MB.
2. I deleted .py files (cause the corresponding pyc ones are there).
This reduced the size by 9MB.
3. I deleted the /lib/libpython2.6.a which was 6MB.
* By far the python runs flawlessly.

4. I zip up the /lib/python2.6/ as python26.zip and place it in the /
lib/ directory.
Then I delete the /lib/python2.6/ directory. By running python, I get
this output, though /lib/python26.zip is in the sys.path variable.

n...@nima-desktop:~/py$ ./bin/python
Could not find platform independent libraries 
Could not find platform dependent libraries 
Consider setting $PYTHONHOME to [:]
'import site' failed; use -v for traceback
Python 2.6.5 (r265:79063, May 17 2010, 18:36:54)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.path
['', '/home/nima/py/lib/python26.zip', '/home/nima/py/lib/python2.6/',
'/home/nima/py/lib/python2.6/plat-linux2', '/home/nima/py/lib/
python2.6/lib-tk', '/home/nima/py/lib/python2.6/lib-old', '/home/nima/
py/lib/lib-dynload']



On May 17, 9:00 pm, geremy condra  wrote:
> I'm not an expert, but there are probably a large-ish number of modules
> you could remove without much sacrifice on your part. Looking at the
> module list and just picking the platform-dependent ones:
>
> * _winreg
> * aepack
> * aetools
> * aetypes
> * AL
> * al
> * applesingle
> * autoGIL
> * buildtools
> * Carbon
> * cd
> * cfmfile
> * chunk
> * colorpicker
> * etc
> * etc
> * etc
>
> You could also probably remove things like 2to3, tabnanny, etc,
> and I doubt tkinter is doing you much good.
>
> I also recall someone at pycon talking about importing modules
> from a .zip archive. I'm not sure how easy/hard that is, but you
> may want to look at PEP 302.
>
> Geremy Condra

Yours sincerely,
Nima Mohammadi
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Installing Lightweight Python

2010-05-17 Thread Nima
Well, I tried to run Python with -v option. It seems that python26.zip is
partially loaded but can't be used, because zlib is "unavailable".

n...@nima-desktop:~/py$ ./bin/*python -v*
Could not find platform independent libraries 
Could not find platform dependent libraries 
Consider setting $PYTHONHOME to [:]
# installing zipimport hook
import zipimport # builtin
# installed zipimport hook
*# zipimport: found 2509 names in /home/nima/py/lib/python26.zip*
# zipimport: *zlib UNAVAILABLE*
'import site' failed; traceback:
*zipimport.ZipImportError: can't decompress data; zlib not available
# zipimport: zlib UNAVAILABLE*
Python 2.6.5 (r265:79063, May 17 2010, 18:36:54)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.path
['', '/home/nima/py/lib/python26.zip', '/home/nima/py/lib/python2.6/',
'/home/nima/py/lib/python2.6/plat-linux2',
'/home/nima/py/lib/python2.6/lib-tk', '/home/nima/py/lib/python2.6/lib-old',
'/home/nima/py/lib/lib-dynload']


-- 
*Yours sincerely,
Nima Mohammadi*
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Installing Lightweight Python

2010-05-17 Thread Nima Mohammadi
Well, I tried to run Python with -v option. It seems that python26.zip
is partially loaded but can't be used, because zlib is "unavailable".

n...@nima-desktop:~/py$ ./bin/python -v
Could not find platform independent libraries 
Could not find platform dependent libraries 
Consider setting $PYTHONHOME to [:]
# installing zipimport hook
import zipimport # builtin
# installed zipimport hook
# zipimport: found 2509 names in /home/nima/py/lib/python26.zip
# zipimport: zlib UNAVAILABLE
'import site' failed; traceback:
zipimport.ZipImportError: can't decompress data; zlib not available
# zipimport: zlib UNAVAILABLE

Python 2.6.5 (r265:79063, May 17 2010, 18:36:54)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.path
['', '/home/nima/py/lib/python26.zip', '/home/nima/py/lib/python2.6/',
'/home/nima/py/lib/python2.6/plat-linux2', '/home/nima/py/lib/
python2.6/lib-tk', '/home/nima/py/lib/python2.6/lib-old', '/home/nima/
py/lib/lib-dynload']


--
Yours sincerely,
Nima Mohammadi
-- 
http://mail.python.org/mailman/listinfo/python-list


classes and __init__ question

2010-05-17 Thread Alex Hall
Hi all,
I am a bit confused about classes. What do you pass a class, since all
the actual information is passed to __init__? For example, say you
have a dog class. The dog object has a name, a size, and a color. I
believe you would say this:

class dog():
 def __init__(self, name, size, color):
  self.name=name
  self.size=size
  self.color=color
 #end def
#end class

What, then, gets passed to the class constructor?
class dog(whatGoesHere?):
Sometimes I see things passed to this. For example, if you create a
class for a wxPython frame, you will say:
class myapp(wx.App):
In this case you pass something. However, I have a class that I use in
one of my programs to create "contact" objects, which looks like this:
class contact():
 def __init__(self, name, email, status, service):
  self.name=name
  self.email=email
  self.status=status
  self.service=service
 #end def
#end class

Here, I do not pass anything to the class, only to __init__. What is going on?

On a related note, is it horrible for resource usage to create a large
array, up to 500 or so, where each member is a small object? I am
thinking of, for example, a game board array where each member of the
array is a "square" object. A square might have a status, a color, and
other flags associated with it, so you could then say something like
board[i][j].hasGamePiece=True. Lookups and adjustments like this will
be going on a lot. Am I better off using an array of numbers where
each number means something different?

Thanks in advance for any info.


-- 
Have a great day,
Alex (msg sent from GMail website)
[email protected]; http://www.facebook.com/mehgcap
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Installing Lightweight Python

2010-05-17 Thread geremy condra
On Mon, May 17, 2010 at 1:05 PM, Nima  wrote:
> Well, I tried to run Python with -v option. It seems that python26.zip is
> partially loaded but can't be used, because zlib is "unavailable".

is the zlib module among the files you've compressed?

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


Re: classes and __init__ question

2010-05-17 Thread Patrick Maupin
On May 17, 3:19 pm, Alex Hall  wrote:
> Hi all,
> I am a bit confused about classes. What do you pass a class, since all
> the actual information is passed to __init__? For example, say you
> have a dog class. The dog object has a name, a size, and a color. I
> believe you would say this:
>
> class dog():
>  def __init__(self, name, size, color):
>   self.name=name
>   self.size=size
>   self.color=color
>  #end def
> #end class
>
> What, then, gets passed to the class constructor?
> class dog(whatGoesHere?):
> Sometimes I see things passed to this. For example, if you create a
> class for a wxPython frame, you will say:
> class myapp(wx.App):
> In this case you pass something. However, I have a class that I use in
> one of my programs to create "contact" objects, which looks like this:
> class contact():
>  def __init__(self, name, email, status, service):
>   self.name=name
>   self.email=email
>   self.status=status
>   self.service=service
>  #end def
> #end class
>
> Here, I do not pass anything to the class, only to __init__. What is going on?
>
> On a related note, is it horrible for resource usage to create a large
> array, up to 500 or so, where each member is a small object? I am
> thinking of, for example, a game board array where each member of the
> array is a "square" object. A square might have a status, a color, and
> other flags associated with it, so you could then say something like
> board[i][j].hasGamePiece=True. Lookups and adjustments like this will
> be going on a lot. Am I better off using an array of numbers where
> each number means something different?
>
> Thanks in advance for any info.
>
> --
> Have a great day,
> Alex (msg sent from GMail website)
> [email protected];http://www.facebook.com/mehgcap

What you are calling "passing to a class" is the superclass (or list
of superclasses) if you are creating a subclass.

Under Python 2.x, you might want to subclass object (if you need/want
a newstyle class), so it is fairly common to see:

class foo(object):
   whatever

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


How to determine subprocess.Popen() failed when shell=True

2010-05-17 Thread python
Windows version of Python 2.6.4: Is there any way to determine if
subprocess.Popen() fails when using shell=True?

Popen() successfully fails when shell=False

>>> import subprocess
>>> p = subprocess.Popen( 'Nonsense.application', shell=False )
Traceback (most recent call last):
  File "", line 1, in 
p = subprocess.Popen( 'Nonsense.application' )
  File "C:\Python26\lib\subprocess.py", line 621, in __init__
errread, errwrite)
  File "C:\Python26\lib\subprocess.py", line 830, in
_execute_child
startupinfo)
WindowsError: [Error 2] The system cannot find the file specified

But when shell=True, there appears to be no way to determine if a
Popen() call was successful or not.

>>> p = subprocess.Popen( 'Nonsense.application', shell=True )
>>> p

>>> p.pid
6620
>>> p.returncode
>>>

Regards,
Malcolm

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


Re: classes and __init__ question

2010-05-17 Thread Chris Rebert
On Mon, May 17, 2010 at 1:19 PM, Alex Hall  wrote:
> Hi all,
> I am a bit confused about classes. What do you pass a class, since all
> the actual information is passed to __init__? For example, say you
> have a dog class. The dog object has a name, a size, and a color. I
> believe you would say this:
>
> class dog():
>  def __init__(self, name, size, color):
>  self.name=name
>  self.size=size
>  self.color=color
>  #end def
> #end class
>
> What, then, gets passed to the class constructor?
> class dog(whatGoesHere?):
> Sometimes I see things passed to this. For example, if you create a
> class for a wxPython frame, you will say:
> class myapp(wx.App):
> In this case you pass something. However, I have a class that I use in
> one of my programs to create "contact" objects, which looks like this:
> class contact():
>  def __init__(self, name, email, status, service):
>  self.name=name
>  self.email=email
>  self.status=status
>  self.service=service
>  #end def
> #end class
>
> Here, I do not pass anything to the class, only to __init__. What is going on?

There is no notion of "passing" stuff to classes (at least in the way
you're thinking about it). The parentheses in these cases have nothing
to do with function calls.

`class Foo(Bar, Baz):` declares a new class with classes Bar and Baz
as base classes (Python has multiple inheritance).

`class Foo():` declares a new class with only the class `object` as
its implicit base class. The parentheses can and almost always are
omitted in such cases, so one would normally write `class Foo:`
instead.

There's some metaclass magic involved and the constructor of the
metaclass is called (in the earlier case, with Bar and Baz among the
parameters) behind the scenes to create the class Foo itself, but Foo
itself isn't "called" when Foo is being created; indeed, that wouldn't
even make sense, for how could the class possibly be called when it's
still being defined?

In other words, the parentheses in class declarations have nothing
directly to do with function calls and it's probably best not to
conceptualize it that way; they're used just to specify base classes
(and the metaclass in recent Python versions with some extra syntax).

> On a related note, is it horrible for resource usage to create a large
> array, up to 500 or so, where each member is a small object? I am
> thinking of, for example, a game board array where each member of the
> array is a "square" object. A square might have a status, a color, and
> other flags associated with it, so you could then say something like
> board[i][j].hasGamePiece=True. Lookups and adjustments like this will
> be going on a lot. Am I better off using an array of numbers where
> each number means something different?

Premature optimization is the root of all evil. Only *if* your program
ends up using too much memory *and* memory profiling shows the board
to be a significant contributor to the problem, *then* you would start
looking into such memory optimizations.

Cheers,
Chris
--
http://blog.rebertia.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: classes and __init__ question

2010-05-17 Thread Alex Hall
On 5/17/10, Patrick Maupin  wrote:
> On May 17, 3:19 pm, Alex Hall  wrote:
>> Hi all,
>> I am a bit confused about classes. What do you pass a class, since all
>> the actual information is passed to __init__? For example, say you
>> have a dog class. The dog object has a name, a size, and a color. I
>> believe you would say this:
>>
>> class dog():
>>  def __init__(self, name, size, color):
>>   self.name=name
>>   self.size=size
>>   self.color=color
>>  #end def
>> #end class
>>
>> What, then, gets passed to the class constructor?
>> class dog(whatGoesHere?):
>> Sometimes I see things passed to this. For example, if you create a
>> class for a wxPython frame, you will say:
>> class myapp(wx.App):
>> In this case you pass something. However, I have a class that I use in
>> one of my programs to create "contact" objects, which looks like this:
>> class contact():
>>  def __init__(self, name, email, status, service):
>>   self.name=name
>>   self.email=email
>>   self.status=status
>>   self.service=service
>>  #end def
>> #end class
>>
>> Here, I do not pass anything to the class, only to __init__. What is going
>> on?
>>
>> On a related note, is it horrible for resource usage to create a large
>> array, up to 500 or so, where each member is a small object? I am
>> thinking of, for example, a game board array where each member of the
>> array is a "square" object. A square might have a status, a color, and
>> other flags associated with it, so you could then say something like
>> board[i][j].hasGamePiece=True. Lookups and adjustments like this will
>> be going on a lot. Am I better off using an array of numbers where
>> each number means something different?
>>
>> Thanks in advance for any info.
>>
>> --
>> Have a great day,
>> Alex (msg sent from GMail website)
>> [email protected];http://www.facebook.com/mehgcap
>
> What you are calling "passing to a class" is the superclass (or list
> of superclasses) if you are creating a subclass.
So what is a subclass compared to a class? Are you saying that what is
passed to the class, so what is in the parentheses of the class, is
really the superclass? If so, what is the advantage of doing this; why
not just create a class that is not a sub? I thinking I am missing
something elementary here. :)
>
> Under Python 2.x, you might want to subclass object (if you need/want
> a newstyle class), so it is fairly common to see:
>
> class foo(object):
>whatever
In Java, a class is an object. Is Python the same thing? Would you say
that my dog class, for example, creates a new dog object when an
instance is instantiated?
Thanks.
>
> Regards,
> Pat
> --
> http://mail.python.org/mailman/listinfo/python-list
>


-- 
Have a great day,
Alex (msg sent from GMail website)
[email protected]; http://www.facebook.com/mehgcap
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to determine subprocess.Popen() failed when shell=True

2010-05-17 Thread Chris Rebert
On Mon, May 17, 2010 at 1:45 PM,   wrote:
> Windows version of Python 2.6.4: Is there any way to determine if
> subprocess.Popen() fails when using shell=True?
>
> Popen() successfully fails when shell=False
>
 import subprocess
 p = subprocess.Popen( 'Nonsense.application', shell=False )
> Traceback (most recent call last):
>  File "", line 1, in 
>    p = subprocess.Popen( 'Nonsense.application' )
>  File "C:\Python26\lib\subprocess.py", line 621, in __init__
>    errread, errwrite)
>  File "C:\Python26\lib\subprocess.py", line 830, in
> _execute_child
>    startupinfo)
> WindowsError: [Error 2] The system cannot find the file specified
>
> But when shell=True, there appears to be no way to determine if a
> Popen() call was successful or not.
>
 p = subprocess.Popen( 'Nonsense.application', shell=True )
 p
> 
 p.pid
> 6620
 p.returncode


I don't have a Windows box to test on, but have you tried p.wait()?
Worked for me on *nix:
$ python
Python 2.6.5 (r265:79063, May 11 2010, 13:15:13)
[GCC 4.2.1 (Apple Inc. build 5659)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from subprocess import Popen
>>> a = Popen("nonsense", shell=True)
>>> /bin/sh: nonsense: command not found

>>> a.returncode
>>> a.wait()
127
>>> a.returncode
127

Cheers,
Chris
--
http://blog.rebertia.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Installing Lightweight Python

2010-05-17 Thread Nima Mohammadi
On May 18, 12:30 am, geremy condra  wrote:
> On Mon, May 17, 2010 at 1:05 PM, Nima  wrote:
> > Well, I tried to run Python with -v option. It seems that python26.zip is
> > partially loaded but can't be used, because zlib is "unavailable".
>
> is the zlib module among the files you've compressed?
>
> Geremy Condra

zlib.so is a shared library which is in the /lib/python2.6/lib-
dynload/ directory.
In PEP 273 is noted that:

> Any files may be present in the zip archive, but only files
> *.py and *.py[co] are available for import.  Zip import of
> dynamic modules (*.pyd, *.so) is disallowed.

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

--
Yours sincerely,
Nima Mohammadi
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: classes and __init__ question

2010-05-17 Thread Patrick Maupin
On May 17, 3:55 pm, Alex Hall  wrote:

> So what is a subclass compared to a class? Are you saying that what is
> passed to the class, so what is in the parentheses of the class, is
> really the superclass? If so, what is the advantage of doing this; why
> not just create a class that is not a sub? I thinking I am missing
> something elementary here. :)

A subclass can inherit methods and attributes from a base class.  This
is not necessary, but is sometimes useful.

> In Java, a class is an object. Is Python the same thing?

Yes, a class is an object.  A class's class is its "metaclass".

An instance of a class is also an object.

> Would you say
> that my dog class, for example, creates a new dog object when an
> instance is instantiated?

Yes. But the actual act of coding something like:

class foo(object):
pass

Creates a class object, which is a subclass of the 'object' object,
and is an instance of the 'type' object.  Since Python is so dynamic,
you can easily determine this at the command prompt:

>>> class foo(object):
... pass
...
>>> x = foo()
>>>
>>> type(x)

>>> type(foo)

>>>


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


Re: Installing Lightweight Python

2010-05-17 Thread Nima Mohammadi
On May 18, 1:04 am, Nima Mohammadi  wrote:
> On May 18, 12:30 am, geremy condra  wrote:
>
> > On Mon, May 17, 2010 at 1:05 PM, Nima  wrote:
> > > Well, I tried to run Python with -v option. It seems that python26.zip is
> > > partially loaded but can't be used, because zlib is "unavailable".
>
> > is the zlib module among the files you've compressed?
>
> > Geremy Condra
>
> zlib.so is a shared library which is in the /lib/python2.6/lib-
> dynload/ directory.
> In PEP 273 is noted that:
>
> > Any files may be present in the zip archive, but only files
> > *.py and *.py[co] are available for import.  Zip import of
> > dynamic modules (*.pyd, *.so) is disallowed.
>
> http://www.python.org/dev/peps/pep-0273/
>
> --
> Yours sincerely,
> Nima Mohammadi

The problem is solved! I just needed to make a directory named
"python2.6" in the /lib/ directory and copy the lib-dynload/ directory
in it.
Thanks for your precious help, Geremy :)

Does anyone have the list of essentials modules to run python?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Installing Lightweight Python

2010-05-17 Thread Stephen Hansen
On Mon, May 17, 2010 at 2:04 PM, Nima Mohammadi  wrote:

> On May 18, 12:30 am, geremy condra  wrote:
> > On Mon, May 17, 2010 at 1:05 PM, Nima  wrote:
> > > Well, I tried to run Python with -v option. It seems that python26.zip
> is
> > > partially loaded but can't be used, because zlib is "unavailable".
> >
> > is the zlib module among the files you've compressed?
> >
> > Geremy Condra
>
> zlib.so is a shared library which is in the /lib/python2.6/lib-
> dynload/ directory.
>


Yes, but you're not running python from say, /bin; if you were, it might go
out and look in /lib and such to find files. You're running it from a local
directory, ./bin/python. Thus, its finding its "center" (where the
executable is installed), and from there building a search path.

Its center -- PYTHONHOME -- is /home/nima/py; from there, it adds
/home/nima/py/lib-dynload among other search paths.

So: zlib.so needs to be in /home/nima/py/lib-dynload. If its not, then it
won't be able to decompress python26.zip into memory.

In PEP 273 is noted that:
>
> > Any files may be present in the zip archive, but only files
> > *.py and *.py[co] are available for import.  Zip import of
> > dynamic modules (*.pyd, *.so) is disallowed.
>
> http://www.python.org/dev/peps/pep-0273/


He knows, he was wondering if you accidentally zipped up zlib.so in the zip,
basically. I think :)

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


Some help needed with small multi-threaded program!

2010-05-17 Thread Oltmans
I've a small multi-threaded program that is written by keeping
Producer-Consumer pattern in mind. In the Producer part of the program
we create new users by doing a POST to a certain web URL whereas in
the Consumer part of the program we try to login newly created users.
Problem is that program sort of runs fine, however, it never
terminates itself and, more importantly, it doesn't print last-three
lines of the program(which is important for my purposes). I've looked
at the docs, but I couldn't figure out a solution so if someone can
spot the problem and suggest a solution that will be highly
appreciated. Many thanks in advance.

-
#!/usr/bin/env python

import Queue
import re
import random
import time
import threading
import urllib2
import simplejson
from urllib2 import HTTPError
import urllib

base_url = "http://example.com/";
queue = Queue.Queue()
total_users = 0
#keeps the record of time it takes to create a user
create_user_times = {}
#keeps the record of time it takes to authenticate a user
login_user_times = {}
lock = threading.Lock()
errors = []

class User():
def
__init__(self,firstName,lastName,email,password,userName,active):
self.firstName = firstName
self.lastName = lastName
self.password = password
self.email = email
self.userName = userName
#producer
class CreateUsers(threading.Thread):
def __init__(self,queue,limit):
threading.Thread.__init__(self)
self.queue = queue
self.limit = limit

def create_user(self):

url = base_url + "users/"
email = "stokeywonder+"+str(random.randrange(0,10))
+"@example.com"
obj = {'firstName' : 'Coyotee',
'lastName' : 'Stevey', 'email' : email,
'password':'7887',
'userName':email
}
req = urllib2.Request(url)
req.add_header('User-Agent', 'Mozilla/4.0 (compatible; MSIE
5.5; Windows NT)')
req.add_header("Content-Type","application/json")
req.add_data(simplejson.dumps(obj))

try:

t = time.time()
f = urllib2.urlopen(req)
page = f.read()
if str(f.code) != '200':
pass
else:
create_user_times[obj['userName']] = str("%.
2f"%float(time.time() - t))
user = User(**obj)
self.queue.put(user)

except:
errors.append(obj['userName'])

def run(self):
global total_users
global lock

while total_users < self.limit:
lock.acquire()
try:
total_users += 1
finally:
lock.release()

self.create_user()
if total_users == self.limit:
try:
self.queue.task_done()
except ValueError:
pass

#Consumer
class TestService(threading.Thread):
def __init__(self,queue):
threading.Thread.__init__(self)
self.queue = queue

def login(self,user):

user_name = user.userName
pwd = user.password
url = base_url+'u?uName='+user_name+'&pwd='+pwd
user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
req = urllib2.Request(url)
req.add_header('User-Agent', user_agent)
try:
t = time.time()

f = urllib2.urlopen(req)

if str(f.code) != '200':
pass
else:
login_user_times[user_name] = str("%.
2f"%float(time.time() - t))
except:
errors.append(user_name)

def run (self):
while True:
user = self.queue.get()
if user:
self.login(user)


if __name__ == "__main__":
#limit = number of users
limit = 5
th = []
for i in range(2):
t = CreateUsers(queue,limit)
t1 = TestService(queue)
t.start()
t1.start()
th.append(t1)
th.append(t)

for t in th:
t.join()
print create_user_times
print '---'
print login_user_times



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


wxPython: How to get letter colour from TextCtrl

2010-05-17 Thread D. Schramm

Hello,

I've got a problem getting the colour of a single letter within the 
TextCtrl widget:


letterstyle = wx.TextAttr()
self.p1.GetStyle(self.p1.XYToPosition(0,0),letterstyle)
color = letterstyle.GetTextColour()
print color

This should display the colour value of the very first letter in the 
very first line of the TextCtrl. But no matter what I try, it always 
returns the value (-1, -1, -1, 255).


Any help?

Thanks in advance,

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


Re: classes and __init__ question

2010-05-17 Thread Ethan Furman

Alex Hall wrote:

Hi all,
I am a bit confused about classes. What do you pass a class, since all
the actual information is passed to __init__? For example, say you
have a dog class. The dog object has a name, a size, and a color. I
believe you would say this:

class dog():
 def __init__(self, name, size, color):
  self.name=name
  self.size=size
  self.color=color


Here you have defined a dog class (you have not called it, yet).



What, then, gets passed to the class constructor?
class dog(whatGoesHere?):


whatGoesHere = any parent classes (the constructor is *not* being called 
yet)


parent classes can be used when you want what they have, but need to 
either add more, or change some, of the methods/attributes that the 
parent has.



Sometimes I see things passed to this. For example, if you create a
class for a wxPython frame, you will say:
class myapp(wx.App):


wx.App is not being passed, per se, rather Python is being told that 
myapp is based on wx.App, and will have all the methods/attributes that 
wx.App has, plus whatever else follows.


So far, all that has been done is to _define_ classes.


class contact():
 def __init__(self, name, email, status, service):
  self.name=name
  self.email=email
  self.status=status
  self.service=service

Here, I do not pass anything to the class, only to __init__. What is going on?


You have defined a class -- nothing more, nothing less.

When you actually call the class is when any necessary items are passed 
to the constructor (__init__):


a_dog = dog('Ralph', 'big', RED)

this_app = myapp()

fred = contact('Fred Flinstone','[email protected]','active','exemplary')

Hope this helps.

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


Re: wxPython: How to get letter colour from TextCtrl

2010-05-17 Thread Stef Mientki
On 17-05-2010 23:29, D. Schramm wrote:
> Hello,
>
> I've got a problem getting the colour of a single letter within the
> TextCtrl widget:
>
> letterstyle = wx.TextAttr()
> self.p1.GetStyle(self.p1.XYToPosition(0,0),letterstyle)
> color = letterstyle.GetTextColour()
> print color
>
> This should display the colour value of the very first letter in the
> very first line of the TextCtrl. But no matter what I try, it always
> returns the value (-1, -1, -1, 255).
>
> Any help?
>
AFAIK, TextAttributes are just onw way, you can set them, but never read
them back.

cheers,
Stef
>
> Thanks in advance,
>
> Dennis Schramm

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


Re: Picking a license

2010-05-17 Thread Ben Finney
[email protected] (Aahz) writes:

> Ben Finney   wrote:
> >[It is impractical to] sell free software like selling loaves of
> >bread, but that's a much more limited case and a far cry from your
> >claim [that it's impractical to sell free software]. Selling free
> >software is quite practical and a good way to fund development of
> >software that otherwise wouldn't be written as free software.
>
> From my POV, if you're not selling COTS, you're really selling support
> and consulting services, because that's what keeps your competitors
> from just picking up your software and reselling it for cheaper. BTDT.

This thread has revealed some staggering gulfs in concepts as held by
different people. For example, I don't think it's at all germane to the
definition of “sell FOO” that “your competitors can pick up the FOO and
resell it cheaper”. Whether they can or not, that doesn't change that
fact that one is selling FOO.

Moreover, I don't try to prevent my competitors from reselling the
software (so long as they don't misrepresent who holds copyright or
further restrict the terms). That's part and parcel of the freedoms in
the software. Indeed, I find that helps the customers trust me more and
tend to come back when they want something else new; and my customers
are free to show others the solutions I've already implemented.

Thus is an ongoing business relationship crafted, including return
customers and referrals for new work. It really is practical to sell
free software.

-- 
 \  “It's dangerous to be right when the government is wrong.” |
  `\   —Francois Marie Arouet Voltaire |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Encoding troubles

2010-05-17 Thread JB
I'm working on the webapp of our company intranet and I had a question
about proper handling of user input that's causing encoding issues.

Some of the uesrs take notes in Microsoft Office and copy/paste these
into textarea's of the webapp. Some of the characters from Word such
as hypens (–) and apostrophes (’) are in an odd encoding. When passed
to the database using sqlalchemy they appear as – and other
characters.

What's the proper handling (conversion?) of user input before it gets
to my database. Do I need to start making a list of the offending
characters and .replace them? Or is there a means to decode/encode the
user input to something more generic? Thanks for your time.
-- 
http://mail.python.org/mailman/listinfo/python-list


Can't find _sqlite3.so in lib-dynload

2010-05-17 Thread Peng Yu
I compiled python2.6.4 from source. But I can't find _sqlite3.so in
the install directory. I thought that _sqlite3.so should be generated
to the install directory.

Would you please let me know how to fix it?

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


Re: reading XML file using python

2010-05-17 Thread Alessandro Molari
I can suggest you the lxml library at http://codespeak.net/lxml/

I've already used it and I think it works very well, it's more pythonic 
than the built-in xml library

For a simple use of xml functionalities you can read 
http://codespeak.net/lxml/tutorial.html


Alessandro Molari

On Monday 17 May 2010 10:34:51 shanti bhushan wrote:
> Hi ,
> i am new to python.i want to read the XML file using python it ,by
> using DOm or SAX any of them.
> I want to read the http://www.google.com(any hyper text) from XML 
and
> print that.
> please give me the sample program for this.
> regards
> Shanti Bhushan
> Bangalore,India
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Global variables for python applications

2010-05-17 Thread Rhodri James
On Mon, 17 May 2010 05:29:20 +0100, Steven D'Aprano  
 wrote:



On Sun, 16 May 2010 18:57:15 -0700, John Nagle wrote:


James Mills wrote:

The only place global variables are considered somewhat "acceptable"
are as constants in a module shared as a static value.


Python really ought to have named constants.


+1

Unfortunately, it will most likely require new syntax, and semantics.
While the concept of a constant is pretty straightforward for immutable
types like ints and strings, what about mutable types?

And then there's the moratorium, so even if we had agreement on semantics
and syntax, and a patch, it couldn't be deployed for a few years.


Careful, you're reconflating two concepts that John separated: mutability  
of an object and binding of a name.  I'm on the side of 'named constant'  
meaning 'this name (in this scope) is bound to this object and cannot be  
rebound.'  That would cover most of the cases people care about, and the  
gotchas are essentially the same as with default arguments.


But yes, it would require new syntax.

--
Rhodri James *-* Wildebeeste Herder to the Masses
--
http://mail.python.org/mailman/listinfo/python-list


Re: Encoding troubles

2010-05-17 Thread Neil Hodgson
JB:

> as hypens (–) and apostrophes (’) are in an odd encoding. When passed
> to the database using sqlalchemy they appear as – and other
> characters.

   The encoding is UTF-8. Normally the best way to handle encodings is
to convert to Unicode strings (unicode(s, "UTF-8")) as soon as possible
and perform most processing in Unicode.

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


Re: Some help needed with small multi-threaded program!

2010-05-17 Thread Bryan
Oltmans wrote:
> I've a small multi-threaded program that is written by keeping
> Producer-Consumer pattern in mind.
[...]
> Problem is that program sort of runs fine, however, it never
> terminates itself and, more importantly, it doesn't print last-three
> lines of the program(which is important for my purposes). I've looked
> at the docs, but I couldn't figure out a solution so if someone can
> spot the problem and suggest a solution that will be highly
> appreciated. Many thanks in advance.

Well, "the problem" may be a bit presumptuous, but here's *a* problem:

> class TestService(threading.Thread):
[...]
>     def run (self):
>         while True:
>             user = self.queue.get()
>             if user:
>                 self.login(user)

That thread will not exit, and your main thread tries to join it.

In other news. There's no reason to call queue.task_done() if you
never call queue.join(). Your exception handling is kind of whacked;
that errors[] list doesn't collect enough info and if your program
hangs it's no use.

Your Producer-Consumer pattern is a misfit. Registering a user then
trying to log her in is a nice sequential unit of work that one thread
could handle. The reason for threading in this problem is so that when
one user's work is waiting for the network, you can make progress on
other users.

Hope that helps.

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


Re: Global variables for python applications

2010-05-17 Thread Giampaolo Rodolà
2010/5/16 Chris Rebert :
> On Sun, May 16, 2010 at 10:50 AM, AON LAZIO  wrote:
>> Hi,
>>How can I set up global variables for the entire python applications?
>> Like I can call and set this variables in any .py files.
>>Think of it as a global variable in a single .py file but this is for the
>> entire application.
>
> Thankfully, there is no such thing (can you say spaghetti code?). The
> closest approximation, as I said in my previous reply, is to use the
> namespace of a designated module for this purpose, and import that
> module wherever you need to access/modify these "superglobal"
> variables.
>
> Example:
> #g.py:
> #this module exists to hold superglobal vars
> global1 = "foo"
> global2 = "bar"
>
>
> #elsewhere.py:
> #this is some other module in the same program
> import mypackage.g as g
>
> print "global #1 = ", g.global1
> print "global #2 =", g.global2
> g.global1 = "baz" # modify a superglobal
> g.global3 = "qux" # create a new superglobal
>
>
> Cheers,
> Chris
> --
> http://blog.rebertia.com
> --
> http://mail.python.org/mailman/listinfo/python-list

I agree global variables are evil, but a config.py module within a
serie of global constants which are supposed to be shared amongst all
other modules is a little less evil, and also a different beast IMO.
Even if you use a class to store such data, a "global" reference to
its instance accessible from everywhere must still exist, so the
problem basically still stands.
I would be interested to know a good practice to solve such a problem.


--- Giampaolo
http://code.google.com/p/pyftpdlib
http://code.google.com/p/psutil
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can't find _sqlite3.so in lib-dynload

2010-05-17 Thread Aahz
In article ,
Peng Yu   wrote:
>
>I compiled python2.6.4 from source. But I can't find _sqlite3.so in
>the install directory. I thought that _sqlite3.so should be generated
>to the install directory.
>
>Would you please let me know how to fix it?

Only if you provide some relevant details.  Such as, what OS?

http://www.mikeash.com/getting_answers.html
-- 
Aahz ([email protected])   <*> http://www.pythoncraft.com/

f u cn rd ths, u cn gt a gd jb n nx prgrmmng.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can't find _sqlite3.so in lib-dynload

2010-05-17 Thread Peng Yu
On May 17, 6:38 pm, [email protected] (Aahz) wrote:
> In article ,
> Peng Yu   wrote:
>
>
>
> >I compiled python2.6.4 from source. But I can't find _sqlite3.so in
> >the install directory. I thought that _sqlite3.so should be generated
> >to the install directory.
>
> >Would you please let me know how to fix it?
>
> Only if you provide some relevant details.  Such as, what OS?
>
> http://www.mikeash.com/getting_answers.html

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


Re: Global variables for python applications

2010-05-17 Thread Steven D'Aprano
On Mon, 17 May 2010 23:54:38 +0100, Rhodri James wrote:

> On Mon, 17 May 2010 05:29:20 +0100, Steven D'Aprano
>  wrote:
> 
>> On Sun, 16 May 2010 18:57:15 -0700, John Nagle wrote:
>>
>>> James Mills wrote:
 The only place global variables are considered somewhat "acceptable"
 are as constants in a module shared as a static value.
>>>
>>> Python really ought to have named constants.
>>
>> +1
>>
>> Unfortunately, it will most likely require new syntax, and semantics.
>> While the concept of a constant is pretty straightforward for immutable
>> types like ints and strings, what about mutable types?
>>
>> And then there's the moratorium, so even if we had agreement on
>> semantics and syntax, and a patch, it couldn't be deployed for a few
>> years.
> 
> Careful, you're reconflating two concepts that John separated:
> mutability of an object and binding of a name.

In my own head the two issues of mutability and rebinding were completely 
separate, but I see now that didn't come through as clearly as I hoped in 
my post. My apologies for any confusion.


> I'm on the side of
> 'named constant' meaning 'this name (in this scope) is bound to this
> object and cannot be rebound.'  That would cover most of the cases
> people care about, and the gotchas are essentially the same as with
> default arguments.

I think it is an abuse of the term constant to allow you to talk about a 
mutable object being "constant", since it can vary. Generally, you don't 
care about identity, only equality. Making up a syntax on the spot:

constant pi = [3.1415]
assert pi = 3.1415
pi[0] = 3
assert pi = 3.1415

makes a mockery of the concept of a constant.

Having said that, recognising mutable objects is a hard problem, so 
simply for reasons of practicality we might have to just live with the 
limitation that "constants" can be mutated if the object supports it.



> But yes, it would require new syntax.


Ideally, but there may be alternatives. I've already mentioned the 
Cookbook recipe, or perhaps something like:

import constants
constants.register('pi')
pi = 3.1415


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


Re: abc don't play well with private method

2010-05-17 Thread Steven D'Aprano
On Mon, 17 May 2010 06:35:11 -0700, mouadino wrote:

>> There's no such thing as a "private" attribute in Python. The
>> name-mangling mechanism invoked by "__name" is really meant to avoid
>> accidental redefinition of the attribute in a derived class.
> 
>> In this case, your attribute is expected to be redefined, so you
>> definitly don't want any name mangling here.
> 
> yes , but what i have supposed is that the name mangling will not be
> applied when you use abc especially when you decorate the function with
> abc.abstractmethod , because it's will(should) be redefined (so
> something is wrong with the abc module) .

No, your expectations are wrong. Name mangling works the same no matter 
what class, whether you are using ABCs or not.


>> Also and FWIW, the naming convention for "implementation attributes" is
>> a single leading underscore
> 
> sorry but i don't agree on this. the two underscore (__) are used in
> classes level for defining private method in the python way, and the one
> underscore (_) is used in the module level :

Whether you agree or not, single underscores are commonly used as the 
convention for private methods and attributes. See PEP 8, which is 
written by Python's creator, Guido van Rossum:

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




> """Prepending a single underscore (_) has some support for protecting
> module variables and functions (not included with import * from).
> Prepending a double underscore (__) to an instance variable or method
> effectively serves to make the variable or method private to its class
> (using name mangling). """
> src:http://google-styleguide.googlecode.com/svn/trunk/pyguide.html


If that's what it says, it's wrong, because there's nothing "effective" 
about double-underscore privacy. It's a very weak, easily bypassed 
(deliberately and accidentally) form of privacy, and it complicates 
debugging.

Generally, most people here recommend you ignore leading double-
underscores and just flag your methods as "private by convention" with a 
single leading underscore.



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


pickle unable to load collection

2010-05-17 Thread paragk
Hi,

I am unable to figure out the cause of python pickle unable to find
the collection module.

I am getting

__import__(module)
ImportError: No module named collections

when I try to load a pickled object.

Details:

Python version:

Python 2.6 (r26:66721, Oct  2 2008, 11:35:03) [MSC v.1500 32 bit
(Intel)] on win32


[CODE]

import sys
import glob
import collections
import pickle

...

SomeListDict = collections.defaultdict(list)

... # Populate SomeListDict

DictFile = open (options.saveDict, 'w')
pickle.dump(SomeListDict , DictFile, -1)
DictFile.close()

...

# Try loading the dictionary

LoadDictFile = open(options.loadDict, 'rb')
SomeListDict = pickle.load(LoadDictFile)
LoadDictFile.close()

...
 [CODE END]

The pickle.dump(CallGraphDict, DictFile, -1) works fine. The
dictionary is saved.

The interesting thing is, the dump function is able to find the
collections module.
try:
__import__(module)
mod = sys.modules[module]
klass = getattr(mod, name)

The above try block succeeds.

module
str: collections

mod
module: 

klass
type: 


The SomeListDict = pickle.load(LoadDictFile) fails with

__import__(module)
ImportError: No module named collections


The sequence of calls is:

def load_global(self):
module = self.readline()[:-1]
name = self.readline()[:-1]
klass = self.find_class(module, name)
self.append(klass)
dispatch[GLOBAL] = load_global

Variables:

module
str: collections

name
str: defaultdict


The code where the exception occurs is:

def find_class(self, module, name):
# Subclasses may override this
__import__(module)
mod = sys.modules[module]
klass = getattr(mod, name)
return klass


>From the above analysis, clearly the collection module exists, since
the dump works.

What am I missing?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: pickle unable to load collection

2010-05-17 Thread Steven D'Aprano
On Mon, 17 May 2010 19:02:18 -0700, paragk wrote:

> Hi,
> 
> I am unable to figure out the cause of python pickle unable to find the
> collection module.
> 
> I am getting
> 
> __import__(module)
> ImportError: No module named collections

What is the actual value of module? Here's an obvious failure mode:

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


> module
> str: collections

Try printing repr(str) to see what's actually there.


It may also help if you post a copy-and-paste of the complete traceback.



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


Re: Encoding troubles

2010-05-17 Thread Bryan
Neil Hodgson wrote:
> JB:
>
> > as hypens (–) and apostrophes (’) are in an odd encoding. When passed
> > to the database using sqlalchemy they appear as – and other
> > characters.
>
>    The encoding is UTF-8. Normally the best way to handle encodings is
> to convert to Unicode strings (unicode(s, "UTF-8")) as soon as possible
> and perform most processing in Unicode.

Good advice to work in Unicode (and in Python 3.X str is unicode), but
I'd guess the encoding he's getting is "Windows-1252". The default
character set of HTTP is ISO-8859-1, but Microsoft likes to use
Windows-1252 in it's place.

What to do about it? First, try specifying utf-8 in the form
containing the textarea, as in

  

Note that specifying ISO-8859-1 will not work, in that Microsoft will
still use Windows-1252. I've heard they've gotten better at supporting
utf-8, but I haven't tested.

When a request comes in, check for a Content-Type header that names
the character set, which should be:

  Content-Type: application/x-www-form-urlencoded; charset=utf-8

Then you con decode to a unicode object as Neil Hodgson explained.

In case you still have to deal with Windows-1252, Python knows how to
translate Windows-1252 to the best-fit in Unicode. In current Python
2.x:

  ustring = unicode(raw_string, 'Windows-1252')

In Python 3.X, what comes from a socket is bytes, and str means
unicode:

  ustring = str(raw_bytes, 'Windows-1252')


Of course this all assumes that JB's database likes Unicode. If it
chokes, then alternatives include encoding back to utf-8 and storing
as binary, or translating characters to some best-fit in the set the
database supports.


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


getting attributes and methods of class without creating object

2010-05-17 Thread shuvro
Suppose I have a class like this -

class myClass(object):

def __init__(self):
self.a = 10
self.b = 20

def my_method(self,var = 20):
self.local_var = var

I want to know about its method(__init__ and my_method) and
variables(a,b, local_var) without creating the object of it. I tried
getmembers function of inspect module. But it can do this with an
object of myClass as argument. Like

import inspect
var = myClass()
inspect.getmembers(var)

I have to know about this without creating the object of myClass.
Can anyone help me please?
-- 
http://mail.python.org/mailman/listinfo/python-list


PyCon Australia 2010 program announced

2010-05-17 Thread Richard Jones
Hi all,

The program for PyCon Australia 2010, to be held at the Sydney
Masonic Center over the weekend of June 26 and 27, has been posted.

View the full list of presentations and the schedule at:

  http://pycon-au.org/2010/conference/

Register here:

  http://pycon-au.org/reg


Richard Jones
PyCon Australia 2010 Program Chair
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: getting attributes and methods of class without creating object

2010-05-17 Thread Patrick Maupin
On May 17, 10:52 pm, shuvro  wrote:
> Suppose I have a class like this -
>
> class myClass(object):
>
>     def __init__(self):
>         self.a = 10
>         self.b = 20
>
>     def my_method(self,var = 20):
>         self.local_var = var
>
> I want to know about its method(__init__ and my_method) and
> variables(a,b, local_var) without creating the object of it. I tried
> getmembers function of inspect module. But it can do this with an
> object of myClass as argument. Like
>
> import inspect
> var = myClass()
> inspect.getmembers(var)
>
> I have to know about this without creating the object of myClass.
> Can anyone help me please?

Well, you can do the same thing with myClass itself:

inspect.getmembers(myClass)

But that won't show you a,b, or local_var, because those don't belong
to the class.  They only belong to class instances, and maybe even not
all class instances.  (For example, if my_method is not called, then
the instance won't have local_var defined.)

Python is a very dynamic language, and class instances (and even the
classes themselves!) can be modified at any time during execution.
You don't even have to be executing inside a class's function to add
stuff to it:

class foo:
pass

bar = foo()
bar.a = 3


So to "know" about the attributes of an instance of a class without
actually creating that instance is very difficult.  You didn't specify
why you want to do this, but often the reason is to try to catch
potential errors without actually running code.  This is typically
called "linting", and there are a few Python packages designed to do
this, such as pylint and pychecker.  Probably others, but I don't know
anything about them, because I find that in most cases, the best way
to test or to reason about Python code is to actually run it.

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


url fetching from xml depending upon selection

2010-05-17 Thread shanti bhushan
I have a sample.XML file
the code is like this




My Podcasts
Sun, 07 Mar 2010 15:53:26

GMT
Sun, 07 Mar 2010 15:53:26

GMT


  
http://first.co.jp"; />
http://www.google.com"; />
http://www.epaper.times.india.com"; />
  
  
http://second.co.jp"; />
http://www.google.com"; />
http://www.epaper.times.india.com"; />
  
  
http://third.co.jp"; />
http://www.google.com"; />
http://www.epaper.times.india.com"; />
  




This my python code
from xml.etree import ElementTree

with open('our.xml', 'rt') as f:
tree = ElementTree.parse(f)

for node, value in tree.findall('.//TestCase/Input'):

url=node.attrib.get('url')
print url



i want to print the url depending on name="sprint_001".
If i change my option to sprint_002 it should print url for sprint_002
-- 
http://mail.python.org/mailman/listinfo/python-list


Is this an ok thing to do in a class

2010-05-17 Thread Vincent Davis
Just wondering if there is a problem with mixing a dictionary into a class
like this. Everything seems to work as I would expect.

class foo(object):
def __init__(self, x):
self.letter = dict(a=1,b=2,c=3)
self.A=self.letter['a']
self.x=self.letter[x]

>>> afoo = foo('b')
>>> afoo.x
2
>>> afoo.A
1
>>> afoo.letter['a']
1
>>> afoo.letter.items()
[('a', 1), ('c', 3), ('b', 2)]

  *Vincent Davis
720-301-3003 *
[email protected]
 my blog  |
LinkedIn
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: url fetching from xml depending upon selection

2010-05-17 Thread shanti bhushan
On May 18, 10:18 am, shanti bhushan  wrote:
> I have a sample.XML file
> the code is like this
>
> 
> 
> 
>         My Podcasts
>         Sun, 07 Mar 2010 15:53:26
>
> GMT
>         Sun, 07 Mar 2010 15:53:26
>
> GMT
> 
> 
>   
>     http://first.co.jp"; />
>     http://www.google.com"; />
>     http://www.epaper.times.india.com"; />
>   
>   
>     http://second.co.jp"; />
>     http://www.google.com"; />
>     http://www.epaper.times.india.com"; />
>   
>   
>     http://third.co.jp"; />
>     http://www.google.com"; />
>     http://www.epaper.times.india.com"; />
>   
> 
> 
>
> This my python code
> from xml.etree import ElementTree
>
> with open('our.xml', 'rt') as f:
>     tree = ElementTree.parse(f)
>
> for node, value in tree.findall('.//TestCase/Input'):
>
>         url=node.attrib.get('url')
>         print url
>
> i want to print the url depending on name="sprint_001".
> If i change my option to sprint_002 it should print url for sprint_002

this code print all URL but there is no option to select URLs
depending upon my choice

from xml.etree import ElementTree
with open('our.xml', 'rt') as f:
tree = ElementTree.parse(f)
for node in tree.findall('.//TestCase/Input'):
url=node.attrib.get('url')
print url
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: url fetching from xml depending upon selection

2010-05-17 Thread shanti bhushan
On May 18, 10:18 am, shanti bhushan  wrote:
> I have a sample.XML file
> the code is like this
>
> 
> 
> 
>         My Podcasts
>         Sun, 07 Mar 2010 15:53:26
>
> GMT
>         Sun, 07 Mar 2010 15:53:26
>
> GMT
> 
> 
>   
>     http://first.co.jp"; />
>     http://www.google.com"; />
>     http://www.epaper.times.india.com"; />
>   
>   
>     http://second.co.jp"; />
>     http://www.google.com"; />
>     http://www.epaper.times.india.com"; />
>   
>   
>     http://third.co.jp"; />
>     http://www.google.com"; />
>     http://www.epaper.times.india.com"; />
>   
> 
> 
>
> This my python code
> from xml.etree import ElementTree
>
> with open('our.xml', 'rt') as f:
>     tree = ElementTree.parse(f)
>
> for node, value in tree.findall('.//TestCase/Input'):
>
>         url=node.attrib.get('url')
>         print url
>
> i want to print the url depending on name="sprint_001".
> If i change my option to sprint_002 it should print url for sprint_002



i am trying to do with this code
please correct my code

from xml.etree import ElementTree

with open('our.xml', 'rt') as f:
tree = ElementTree.parse(f)

for node in tree.findall('.//TestCase/Input'):
if name=='Sprint_001':
print node.attrib.get('url')

i want to print only url that comes under name=Sprint_001
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: getting attributes and methods of class without creating object

2010-05-17 Thread shuvro
On May 18, 11:50 am, Patrick Maupin  wrote:
> On May 17, 10:52 pm, shuvro  wrote:
>
>
>
> > Suppose I have a class like this -
>
> > class myClass(object):
>
> >     def __init__(self):
> >         self.a = 10
> >         self.b = 20
>
> >     def my_method(self,var = 20):
> >         self.local_var = var
>
> > I want to know about its method(__init__ and my_method) and
> > variables(a,b, local_var) without creating the object of it. I tried
> > getmembers function of inspect module. But it can do this with an
> > object of myClass as argument. Like
>
> > import inspect
> > var = myClass()
> > inspect.getmembers(var)
>
> > I have to know about this without creating the object of myClass.
> > Can anyone help me please?
>
> Well, you can do the same thing with myClass itself:
>
> inspect.getmembers(myClass)
>
> But that won't show you a,b, or local_var, because those don't belong
> to the class.  They only belong to class instances, and maybe even not
> all class instances.  (For example, if my_method is not called, then
> the instance won't have local_var defined.)
>
> Python is a very dynamic language, and class instances (and even the
> classes themselves!) can be modified at any time during execution.
> You don't even have to be executing inside a class's function to add
> stuff to it:
>
> class foo:
>     pass
>
> bar = foo()
> bar.a = 3
>
> So to "know" about the attributes of an instance of a class without
> actually creating that instance is very difficult.  You didn't specify
> why you want to do this, but often the reason is to try to catch
> potential errors without actually running code.  This is typically
> called "linting", and there are a few Python packages designed to do
> this, such as pylint and pychecker.  Probably others, but I don't know
> anything about them, because I find that in most cases, the best way
> to test or to reason about Python code is to actually run it.
>
> Regards,
> Pat

Thanks Pat for your informative reply.
Actually what I am trying to do is to write an external exporter for
the data types an open source software(Blender). So, I have to collect
the properties of the classes.
Here, I have no chance to edit the class and add inspect codes there,
neither I can create objects of the
existing classes (that will do some additional things which I not
want).
Is it not possible with the existing python facilities (without adding
external libraries) ?


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