[Tutor] Generating XML using Python

2011-04-11 Thread tee chwee liong

hi, 

 
i'm using python to generate xml with elementtree api. and i'm getting error 
when opening the output xml. it doesnt give error when running. 
i also tried to use python to output to a text file and it works without any 
error. Pls advise me how i can rectify the error when opening the output xml.
attached is my code, output in text file and output in xml. 
 
thanks
tcl
p/s: i sent earlier email but got bounced email so sending out again.
 

  import elementtree.ElementTree as ET

lspeed=2
tspeed=3
f=open(out.txt, w)

for port in range(1,9):
print Port %d %port
root = ET.Element(Test)
f.write(Port %d\n %port)
head1 = ET.SubElement(root, Default_Config, Port=str(port))
print Link speed: %d %lspeed
f.write(Link speed: %d\n %lspeed)
title = ET.SubElement(head1, LINK)
title.text = str(lspeed)
print Target speed: %d %tspeed
f.write(Target speed: %d\n %tspeed)
title = ET.SubElement(head1, Target Speed)
title.text = str(tspeed)
tree = ET.ElementTree(root)
tree.write(C:\\Python25\\myscript\\cmm\\port1.xml)

f.close()




port1.xml
Description: Binary data
Port 1
Link speed: 2
Target speed: 3
Port 2
Link speed: 2
Target speed: 3
Port 3
Link speed: 2
Target speed: 3
Port 4
Link speed: 2
Target speed: 3
Port 5
Link speed: 2
Target speed: 3
Port 6
Link speed: 2
Target speed: 3
Port 7
Link speed: 2
Target speed: 3
Port 8
Link speed: 2
Target speed: 3
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Generating XML using Python

2011-04-11 Thread Peter Otten
tee chwee liong wrote:

 i'm using python to generate xml with elementtree api. and i'm getting
 error when opening the output xml. it doesnt give error when running. i
 also tried to use python to output to a text file and it works without any
 error. Pls advise me how i can rectify the error when opening the output
 xml. attached is my code, output in text file and output in xml.

 title = ET.SubElement(head1, Target Speed) 

Did you forget to replace the blank between Target and Speed with an 
underscore? It looks like ElementTree doesn't validate the Element tag.
  
 p/s: i sent earlier email but got bounced email so sending out again.

I see them both.

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to design the structure of multi-steps(and substeps)scripts

2011-04-11 Thread Alan Gauld


leechau char...@sohu.com wrote



def step1:
   local_var1 = ...
   # some other variable definitions for step1
   def substep11:
   pass
   # more substeps
...
global_var1 = ...
# more global var definitions...
if step1.return_success:
   step2


Since this is obviously pseudo code I'll assume the
real code has fixed the synrax issues.

steps in one module, where one step corresponding to one funciton 
and

one substep corresponding to one nested function.


While that may seem logical it does limit reuse of the subfunctions.
Do these subfunctions look very similar? Could the be written more
generically - perhaps using some parameters to deal with
differences? If so take them outside the steps.

Then define your steps as tables of functions

step1 = [substep1,substep2,substep3]

and call using a loop:

for step in step1: step()


maintain this script because of totally 1000+ lines of code.


Thats getting close to the biggest I like my modules to be but
not huge. The size is not the problem - after all thats what
search is for in the editor! :-)

when I manipulate different projects with this script I need to 
modify
the value of some variables and detailed task logic. Obviously it's 
a
dirty work to modify the source code directly for different 
projects.


If you are reusing then break the modules down to the size of
the unit of reuse. So if you only use a single step then make
each step a module. BUt if you reuse the entire group then
keep it as one.


If I should put the default value of a
variable and high level task logic in a abstract class, and define
specific value and detailed task logic in concrete subclass?


That would be good to get rid of the globals at least and enable
different projects to modify the instance values for their own 
purposes.



any design patterns available for this kind of multi-steps scripts?


I'd definitely consider a data driven approach as suggested above,
but a lot depends on how complex the real logic is inside the steps.
If it can be simplified to little more than a sequence of substeps
and those substeps can be generic then a table driven style will
greatly simplify the code. Another pattern that is likely to apply
is a state machine, either implemented using state classes or
as a table.

But without knowlege of the detail of the real code we cannot
make definite recommendations.

HTH,


--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python to XML

2011-04-11 Thread Alan Gauld


tee chwee liong tc...@hotmail.com wrote


i just started to learn xml using python and i'm getting
error when opening the output xml. it doesnt give error when 
running.


Always post full error codes and the asociated source code.
For shorty programs like this its more convenient to include
the text in the body rather than as attachments.


how i can rectify the error when opening the output xml.
attached is my code, output in text file and output in xml.


The error I got from IE was an invalid name and looking at
you names it seems that you do indeed have an invalid
name in your XML.  When I deleted the space chartacter
it worked OK.

Error messages are there to help you find the error.
They are usually accurate. Read them carefully and
do as they ask.

HTH,


--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/











___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor




___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Generating XML using Python

2011-04-11 Thread tee chwee liong

hi Peter, 
 
thanks for your reply. seems that xml doesnt accept a space in between. 
anyway, the output generated is:

- Test


- Default_Config Port=8


  LINK2/LINK 

  Target_Speed3/Target_Speed 
  /Default_Config
  /Test
 
it overwrites every time the port number is incremented and only capture the 
last iteration number. how can i modify it to capture all the iteration? for eg:
Port 1
Link speed: 2
Target speed: 3
Port 2
Link speed: 2
Target speed: 3
Port 3
Link speed: 2
Target speed: 3
Port 4
Link speed: 2
Target speed: 3
Port 5
Link speed: 2
Target speed: 3
Port 6
Link speed: 2
Target speed: 3
Port 7
Link speed: 2
Target speed: 3
Port 8
Link speed: 2
Target speed: 3

thanks
tcl

 
  ___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Invisible Characters in Fortran/Python

2011-04-11 Thread Francesco Loffredo

On 04/10/2011 0.12, Tyler Glembo wrote:

Hi All,
So I have a ~3000 line fortran code that needs to be updated to run new files 
by simply updating a few lines in the code (~10
lines).  I thought python would be a great way to do so since I know a little 
python but not fortran.  So, my plan was to read in
each line, and then at a certain line number, write out the changed code.  A 
short snippet is as follows:

dest= open( f1, w )
source= open( f2, r )
for line in source:
if X:
   dest.write( newline + \n )
else:
   dest.write( line )
dest.close()
source.close()

The problem I am having is with hidden/invisible character.  In the fortran 
code, there are line indents which are denoted with an
invisible character ^I.  When I write with python, there is no ^I at the 
beginning of the line and the fortran code no longer
compiles.  I know how to put in the invisible line return character (\n), but 
how can I put in other invisible characters?


I think you could avoid entirely this problem by using the binary option in the 
open function:

dest= open( f1, wb )
source= open( f2, rb )

This way, each read and each write you perform will take into account all kinds of characters, and so your written lines will be 
identical to those you read. If the problem was only with the newline lines, then Steven's answer has already solved your problem.


Hope that helps

Francesco


-
Nessun virus nel messaggio.
Controllato da AVG - www.avg.com
Versione: 10.0.1209 / Database dei virus: 1500/3564 -  Data di rilascio: 
10/04/2011

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Generating XML using Python

2011-04-11 Thread Peter Otten
tee chwee liong wrote:

 thanks for your reply. seems that xml doesnt accept a space in between.
 anyway, the output generated is:
 
 - Test
 
 
 - Default_Config Port=8
 
 
   LINK2/LINK
 
   Target_Speed3/Target_Speed
   /Default_Config
   /Test
  
 it overwrites every time the port number is incremented and only capture
 the last iteration number. how can i modify it to capture all the
 iteration? 

Do you want them all in one file? Move the code to create the root element 
and the code to write the file out of the loop.

Do you want to write multiple files? Use a different name from every file.

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Generating XML using Python

2011-04-11 Thread tee chwee liong

sorry for lack of details. yes i would like to output in 1 xml file. 
i would like to generate port 1 and its details (link, speed etc) then move to 
second port, port 2 and generate its details (link, speed etc) tq
 
 To: tutor@python.org
 From: __pete...@web.de
 Date: Mon, 11 Apr 2011 10:39:48 +0200
 Subject: Re: [Tutor] Generating XML using Python
 
 tee chwee liong wrote:
 
  thanks for your reply. seems that xml doesnt accept a space in between.
  anyway, the output generated is:
  
  - Test
  
  
  - Default_Config Port=8
  
  
  LINK2/LINK
  
  Target_Speed3/Target_Speed
  /Default_Config
  /Test
  
  it overwrites every time the port number is incremented and only capture
  the last iteration number. how can i modify it to capture all the
  iteration? 
 
 Do you want them all in one file? Move the code to create the root element 
 and the code to write the file out of the loop.
 
 Do you want to write multiple files? Use a different name from every file.
 
 ___
 Tutor maillist - Tutor@python.org
 To unsubscribe or change subscription options:
 http://mail.python.org/mailman/listinfo/tutor
  ___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Generating XML using Python

2011-04-11 Thread tee chwee liong


 Do you want them all in one file? Move the code to create the root element 
 and the code to write the file out of the loop.
 
 Do you want to write multiple files? Use a different name from every file.
 

yes i would like to generate 1 xml file by incrementing the port number in the 
range. i'm confuse why xml is overwritten inside the for loop. i tried to test 
by writing to a text file, and it works. tq
 
Port 1
Link speed: 2
Target speed: 3
Port 2
Link speed: 2
Target speed: 3
Port 3
Link speed: 2
Target speed: 3
Port 4
Link speed: 2
Target speed: 3
Port 5
Link speed: 2
Target speed: 3
Port 6
Link speed: 2
Target speed: 3
Port 7
Link speed: 2
Target speed: 3
Port 8
Link speed: 2
Target speed: 3   ___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Generating XML using Python

2011-04-11 Thread tee chwee liong

hi peter, 
 
yes it worked after i moved the root outside the for loop. 
code:
 
import elementtree.ElementTree as ET
lspeed=2
tspeed=3
f=open(out.txt, w)
root = ET.Element(Test)
for port in range (1,9):
print Port %d %port
#root = ET.Element(Test)
f.write(Port %d\n %port)
head1 = ET.SubElement(root, Default_Config, Port=str(port))
print Link speed: %d %lspeed
f.write(Link speed: %d\n %lspeed)
title = ET.SubElement(head1, LINK)
title.text = str(lspeed)
print Target speed: %d %tspeed
f.write(Target speed: %d\n %tspeed)
title = ET.SubElement(head1, Target_Speed)
title.text = str(tspeed)
tree = ET.ElementTree(root)
tree.write(C:\\Python25\\myscript\\cmm\\port1.xml)
f.close()
 
output:

- Test


- Default_Config Port=1


  LINK2/LINK 

  Target_Speed3/Target_Speed 
  /Default_Config

- Default_Config Port=2


  LINK2/LINK 

  Target_Speed3/Target_Speed 
  /Default_Config

- Default_Config Port=3


  LINK2/LINK 

  Target_Speed3/Target_Speed 
  /Default_Config

- Default_Config Port=4


  LINK2/LINK 

  Target_Speed3/Target_Speed 
  /Default_Config

- Default_Config Port=5


  LINK2/LINK 

  Target_Speed3/Target_Speed 
  /Default_Config

- Default_Config Port=6


  LINK2/LINK 

  Target_Speed3/Target_Speed 
  /Default_Config

- Default_Config Port=7


  LINK2/LINK 

  Target_Speed3/Target_Speed 
  /Default_Config

- Default_Config Port=8


  LINK2/LINK 

  Target_Speed3/Target_Speed 
  /Default_Config
  /Test

  ___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Generating XML using Python

2011-04-11 Thread Peter Otten
tee chwee liong wrote:

 
 sorry for lack of details. yes i would like to output in 1 xml file.
 i would like to generate port 1 and its details (link, speed etc) then
 move to second port, port 2 and generate its details (link, speed etc) tq

As I said, instead of creating a new root on every iteration, create it once 
before you enter the loop. Then write the tree after the loop has 
termininated:

import xml.etree.ElementTree as ET

lspeed=2
tspeed=3

root = ET.Element(Test)
for port in range(1,9):
head = ET.SubElement(root, Default_Config, Port=str(port))
title = ET.SubElement(head, LINK)
title.text = str(lspeed)
title = ET.SubElement(head, Target_Speed)

tree = ET.ElementTree(root)
tree.write(port1.xml)


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] A Dictionary question

2011-04-11 Thread Sophie DeNofrio
Hi Everyone, 
I am a super beginner and am little muddled right now. So I apologize for the 
low level question but I am trying to write a function that will return a 
dictionary of a given list of strings containing two coordinates separated by a 
space with the first numbers as a key and the second numbers as its 
corresponding value. I thought maybe a set might be helpful but that didn't 
seem to work at all. I am pretty much as confused as they come and any help 
would be very much appreciated. Thank you so much for your time. 
.___.

{O,o}

/)__) Annie

---___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] A Dictionary question

2011-04-11 Thread Andre Engels
On Mon, Apr 11, 2011 at 1:01 PM, Sophie DeNofrio swimbabe...@yahoo.comwrote:

 Hi Everyone,

 I am a super beginner and am little muddled right now. So I apologize for
 the low level question but I am trying to write a function that will return
 a dictionary of a given list of strings containing two coordinates separated
 by a space with the first numbers as a key and the second numbers as its
 corresponding value. I thought maybe a set might be helpful but that didn't
 seem to work at all. I am pretty much as confused as they come and any help
 would be very much appreciated. Thank you so much for your time.


def createDictionary(data):
result = {}
for datapiece in data:
# Code here to make coordinate1 and coordinate2 the values you want
# Leaving that part to you, but feel free to ask again if you fail
result[coordinate1] = coordinate2
return result


-- 
André Engels, andreeng...@gmail.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] A Dictionary question

2011-04-11 Thread Wayne Werner
On Mon, Apr 11, 2011 at 6:01 AM, Sophie DeNofrio swimbabe...@yahoo.comwrote:

 Hi Everyone,

 I am a super beginner and am little muddled right now. So I apologize for
 the low level question


That's what this list is for, so you're asking in the right place!


 but I am trying to write a function that will return a dictionary of a
 given list of strings containing two coordinates separated by a space with
 the first numbers as a key and the second numbers as its corresponding
 value. I thought maybe a set might be helpful but that didn't seem to work
 at all. I am pretty much as confused as they come and any help would be very
 much appreciated. Thank you so much for your time.


It's always helpful to give example input and output, as well as show us
what you've done so far.It's *also* a good idea to tell us what your end
goal is, rather than just I have this data and I want to manipulate it
thus, because oft times it turns out that there are much better ways to
accomplish the end goal.

Here's what it sounds like you say you want to do:

line_xy = ['1 1', '2 2', '3 3', '4 4'] # Coordinates along the line y = x

def dictify_list(coords):
returnval = {}
for pair in coords:
x, y = pair.split()
returnval[x] = y
return returnval

dictify_list(line_xy) # produces {'1':'1', '3':'3', '2':'2', '4':'4'} or
some equivalent dict - they're non-ordered

But I can't think of a time that I would want data collected this way. My
guess is that unless you have a super special case, you don't really need
the data that way either.

HTH,
Wayne
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] A Dictionary question

2011-04-11 Thread Steven D'Aprano

Hello Sophie, or do you prefer Annie?

Sophie DeNofrio wrote:

Hi Everyone,



I am a super beginner and am little muddled right now. So I apologize
for the low level question but I am trying to write a function that
will return a dictionary of a given list of strings containing two
coordinates separated by a space with the first numbers as a key and
the second numbers as its corresponding value. I thought maybe a set
might be helpful but that didn't seem to work at all. I am pretty
much as confused as they come and any help would be very much
appreciated. Thank you so much for your time.



It will help if you give us an example of what your input data is, and 
what you expect to get for your result. I'm going to try to guess.


I think your input data might look like this:


data = [1 2, 4 5, 23 42]

and you want to return a dictionary like:

{1: 2, 4: 5, 23: 42}

Am I close?

This sounds like homework, and our policy is not to solve homework for 
people, but to guide them into solving it themselves. So here are some 
hints. Please feel free to show us the code you are using if you have 
any problems.



You will need to have a dict ready to store keys and values in, and then 
you need to look at each string in the data list one at a time:


result = {}  # This is an empty dictionary.
for s in data:
# Process the variable s each time.
print(s)


Since s is a string that looks like two numbers separated by a space, 
processing the string needs two tasks: first you have to split the 
string into the two parts, and then you have to turn each part from a 
string into an actual number.


(Remember that in Python, 42 is not a number, it is just a string that 
looks like a number.)


There are two functions that are useful for that: one is a string 
method, and one is a proper function. Here are some examples to show 
them in action:



# Splitting a string into two pieces:

 s = 1234 5678
 s.split()
['1234', '5678']


# Converting a string into a proper number:

 a = 987
 int(a)
987



The split method is especially useful when you use assignment to create 
two variables at once:



 s = 1234 5678
 a, b = s.split()
 a
'1234'
 b
'5678'
 int(a)
1234



Lastly, do you know how to store objects into a dictionary? You need two 
pieces, a key and a value:



 d = {}  # Empty dict.
 key = dinner
 value = pizza
 d[key] = value

 print What's for dinner?, d[dinner]
What's for dinner? pizza


Only in your case, rather than storing strings in the dict, you want to 
store numbers created by int(). So now you have to put all the pieces 
together into one piece of code:




(1) Create an empty dict.
(2) Loop over the individual strings in the input list.
(3) For each string, split it into two pieces.
(4) Convert each piece into an int (integer).
(5) Store the first piece in the dict as the key, and the second piece 
as the value.



Good luck!




--
Steven

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] A Dictionary question

2011-04-11 Thread Sophie DeNofrio
Thank you to everyone who helped!
Steven D'Aprano I was secretly hoping you'd help. This is a family not personal 
and 'junk' (this isn't junk obviously. But it falls into that not personal 
category) account so you are talking to Annie lol. I guess I should have just 
signed up using my own email address in retrospect. Thank you for walking me 
through what I have to do as I want to learn. That dictionary is a much smaller 
piece to a file reading program. Next time I will attach my code. I totally 
blanked on how helpful that would be. Thank you for taking time out of your day 
to explain so fully. :)   
.___.

{O,o}

/)__) Annie

---

--- On Mon, 4/11/11, Steven D'Aprano st...@pearwood.info wrote:

From: Steven D'Aprano st...@pearwood.info
Subject: Re: [Tutor] A Dictionary question
To: tutor@python.org
Date: Monday, April 11, 2011, 8:09 AM

Hello Sophie, or do you prefer Annie?

Sophie DeNofrio wrote:
 Hi Everyone,

 I am a super beginner and am little muddled right now. So I apologize
 for the low level question but I am trying to write a function that
 will return a dictionary of a given list of strings containing two
 coordinates separated by a space with the first numbers as a key and
 the second numbers as its corresponding value. I thought maybe a set
 might be helpful but that didn't seem to work at all. I am pretty
 much as confused as they come and any help would be very much
 appreciated. Thank you so much for your time.


It will help if you give us an example of what your input data is, and what you 
expect to get for your result. I'm going to try to guess.

I think your input data might look like this:


data = [1 2, 4 5, 23 42]

and you want to return a dictionary like:

{1: 2, 4: 5, 23: 42}

Am I close?

This sounds like homework, and our policy is not to solve homework for people, 
but to guide them into solving it themselves. So here are some hints. Please 
feel free to show us the code you are using if you have any problems.


You will need to have a dict ready to store keys and values in, and then you 
need to look at each string in the data list one at a time:

result = {}  # This is an empty dictionary.
for s in data:
    # Process the variable s each time.
    print(s)


Since s is a string that looks like two numbers separated by a space, 
processing the string needs two tasks: first you have to split the string into 
the two parts, and then you have to turn each part from a string into an actual 
number.

(Remember that in Python, 42 is not a number, it is just a string that looks 
like a number.)

There are two functions that are useful for that: one is a string method, and 
one is a proper function. Here are some examples to show them in action:


# Splitting a string into two pieces:

 s = 1234 5678
 s.split()
['1234', '5678']


# Converting a string into a proper number:

 a = 987
 int(a)
987



The split method is especially useful when you use assignment to create two 
variables at once:


 s = 1234 5678
 a, b = s.split()
 a
'1234'
 b
'5678'
 int(a)
1234



Lastly, do you know how to store objects into a dictionary? You need two 
pieces, a key and a value:


 d = {}  # Empty dict.
 key = dinner
 value = pizza
 d[key] = value

 print What's for dinner?, d[dinner]
What's for dinner? pizza


Only in your case, rather than storing strings in the dict, you want to store 
numbers created by int(). So now you have to put all the pieces together into 
one piece of code:



(1) Create an empty dict.
(2) Loop over the individual strings in the input list.
(3) For each string, split it into two pieces.
(4) Convert each piece into an int (integer).
(5) Store the first piece in the dict as the key, and the second piece as the 
value.


Good luck!




-- Steven

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Running python on windows

2011-04-11 Thread Mike Silverson
Hi, I need to know if there is any way to run a python file without Python
installed on the target computer.  I am trying to send a program to a friend
using windows and he does not have python installed, and does not want to
take the time to install it.  Is there any way to send him the file (or a
group of files) that will run right away?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Converting files

2011-04-11 Thread sunil tech
Hi all...

is there any way to convert any file (eg: document files  image files) to
.pdf?

if so, kindly share...

thank you in advance.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Generating XML using Python

2011-04-11 Thread Karim

On 04/11/2011 10:04 AM, tee chwee liong wrote:

hi Peter,

thanks for your reply. seems that xml doesnt accept a space in between.
anyway, the output generated is:
*-* file:///C:/Python25/myscript/cmm/port1.xml# Test
*-* file:///C:/Python25/myscript/cmm/port1.xml# 
Default_ConfigPort=*8*

** LINK*2*/LINK
** Target_Speed*3*/Target_Speed
** /Default_Config
** /Test

it overwrites every time the port number is incremented and only 
capture the last iteration number. how can i modify it to capture all 
the iteration? for eg:

Port 1
Link speed: 2
Target speed: 3
Port 2
Link speed: 2
Target speed: 3
Port 3
Link speed: 2
Target speed: 3
Port 4
Link speed: 2
Target speed: 3
Port 5
Link speed: 2
Target speed: 3
Port 6
Link speed: 2
Target speed: 3
Port 7
Link speed: 2
Target speed: 3
Port 8
Link speed: 2
Target speed: 3

thanks
tcl




for config in doctree_instance.iter('Default_ConfigPort'):
link = config.find('LINK')
target = config.find('Target_Speed')

print('Port ', config.attrib['Port'])
print('Link speed:', link.text)
print('Target speed:', target.text)

Regards



___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Running python on windows

2011-04-11 Thread Nicholas Holley
On Mon, 11 Apr 2011 21:01:37 +0800
Mike Silverson msilvers...@gmail.com wrote:

 Hi, I need to know if there is any way to run a python file without
 Python installed on the target computer.  I am trying to send a
 program to a friend using windows and he does not have python
 installed, and does not want to take the time to install it.  Is
 there any way to send him the file (or a group of files) that will
 run right away?

http://py2exe.org/ is one such method and will probably be your easiest.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Converting files

2011-04-11 Thread Emile van Sebille

On 4/11/2011 10:40 AM sunil tech said...

Hi all...

is there any way to convert any file (eg: document files  image files)
to .pdf?




Look into reportlab.  Look at the opensource area:

http://www.reportlab.com/software/opensource/




if so, kindly share...

thank you in advance.



___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor



___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Python on TV

2011-04-11 Thread Alan Gauld

I've just watched the Channel 5 programme The Gadget Show
where the presenters set a new Guinness world record for operating
the heaviest machine(*) using mind power. The software behind
this feat - was written in Python of course! :-)

(*)The machine in question was a 50 ton industrial crane... used
to move a car from one end of a warehouse to the other.

The show should be here - Pause at 1 minute 20 for the
Python screnshot:

http://fwd.channel5.com/gadget-show/videos/challenge/surprise-special-part-4

Enjoy :-)

Alan G.



___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Running python on windows

2011-04-11 Thread James Reynolds
I use http://cx-freeze.sourceforge.net/ personally. I found py2exe to be a
headache compared to cx.

On Mon, Apr 11, 2011 at 9:01 AM, Mike Silverson msilvers...@gmail.comwrote:

 Hi, I need to know if there is any way to run a python file without Python
 installed on the target computer.  I am trying to send a program to a friend
 using windows and he does not have python installed, and does not want to
 take the time to install it.  Is there any way to send him the file (or a
 group of files) that will run right away?
 ___
 Tutor maillist  -  Tutor@python.org
 To unsubscribe or change subscription options:
 http://mail.python.org/mailman/listinfo/tutor


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Running python on windows

2011-04-11 Thread Alan Gauld


Mike Silverson msilvers...@gmail.com wrote

installed on the target computer.  I am trying to send a program to 
a friend
using windows and he does not have python installed, and does not 
want to

take the time to install it.


Given how quickly Python installs compared to many other apps I
can only assume he uses Wordpad as his word processor?! Honestly
you could just build an installer that installed Python and your files
and I doubt he'd notice the install time as being excessive!

However, there is no way to run Python without installing an 
interpreter.
If you don't use a standalone install you need to build the 
interpreter
into an exe and then install a separate python installation for every 
app

he uses. Its mad. Does he refuse to install .Net or Java or the
VisualBasic runtime?

But if he must there are several options available, the best known
is py2exe but there are others out there.

--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] ImportError: No module named wdmmgext.load

2011-04-11 Thread Ben Teeuwen
Hi, 

Thanks Emile van Sebille for answering my last question.
I'm now testing my imported data and I get 21 errors (see attached). The 
majority sounds like:

from wdmmgext.load import uganda
ImportError: No module named wdmmgext.load

I've searched the files that use this module. Attached is an example file.

I see 2 more errors;
1) that the file 'ukgov-finances-cra/cra_2009_db.csv' does not exist. 
2) SolrException: HTTP code=404, reason=Not Found
Maybe both are due to the wdmmgext.load error, so I'll ignore this for now and 
first try to find answer to my first question.

Thanks in advance for the help!

Ben

import json
import os
import pkg_resources
import wdmmg.model as model
from wdmmgext.load import uganda

class TestDepartments(object):

@classmethod
def setup_class(self):
model.repo.delete_all()
model.Session.remove()
self.name = uganda.dataset_name
filepath = 'wdmmg/tests/uganda_sample.xls'
test_file = os.path.abspath(filepath)
uganda.load_files(filename=test_file, commit_every=10)
model.Session.commit()
model.Session.remove()

@classmethod
def teardown_class(self):
model.repo.delete_all()
model.Session.commit()
model.Session.remove()

# check dataset exists
def test_01_dataset(self):
out = (model.Session.query(model.Dataset)
.filter_by(name=self.name)
).first()
assert out, out

# Get our keys, and check values exist for them.
def test_02_classification(self):
for key_name in [u'from', u'time', u'uganda_id', u'gou_vote',
u'vote_name', u'project_code', u'project_name', 
u'funded_by_donor',
u'funded_by_govt', u'mtef_sector', u'mtef_reference', 
u'swg', u'sector_objective', u'peap1_pillar', 
u'peap2_objective', u'peap3_area']:
key = 
model.Session.query(model.Key).filter_by(name=key_name).first()
assert key, key_name
count = (model.Session.query(model.ClassificationItem)
.join(model.EnumerationValue)
.filter_by(key=key)
).count()
assert count, (key_name, count)

# Check there are some entries and none of them are null
def test_03_entry(self):
dataset_ = (model.Session.query(model.Dataset)
.filter_by(name=self.name)
).one()
count = (model.Session.query(model.Entry)
.filter_by(dataset_=dataset_)
).count()
assert count, 'There are no Entries'
assert not (model.Session.query(model.Entry)
.filter_by(dataset_=dataset_)
.filter_by(amount=None)
).first(), 'Some Entries have NULL amounts'

# Look for a 'to' field on the first entry in the dataset.
def test_04_entry_to(self):
dataset_ = (model.Session.query(model.Dataset)
.filter_by(name=self.name)
).one()
txn = (model.Session.query(model.Entry)
.filter_by(dataset_=dataset_)
).first()
classif = txn.classification_as_dict()
print classif['to']
assert classif['to'] == 'uganda-society'
EE....EEE
==
ERROR: test suite for class 
'wdmmg.tests.functional.test_aggregate.TestAggregateController'
--
Traceback (most recent call last):
  File 
/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/nose/suite.py,
 line 208, in run
self.setUp()
  File 
/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/nose/suite.py,
 line 291, in setUp
self.setupContext(ancestor)
  File 
/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/nose/suite.py,
 line 314, in setupContext
try_run(context, names)
  File 
/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/nose/util.py,
 line 478, in try_run
return func()
  File /Users/bteeuwen/Sites/wdmmg/wdmmg/tests/functional/test_aggregate.py, 
line 8, in setup_class
Fixtures.setup()
  File /Users/bteeuwen/Sites/wdmmg/wdmmg/lib/cli.py, line 101, in setup
from wdmmgext.load import cofog
ImportError: No module named wdmmgext.load
  begin captured logging  
pylons.configuration: DEBUG: Initializing configuration, package: 'wdmmg'
pylons.configuration: DEBUG: Pushing process configuration
pylons.configuration: DEBUG: Adding mako engine with alias None and 
{'myghty.data_dir': '/Users/bteeuwen/Sites/wdmmg/pylons_data/templates', 
'mako.directories': ['/Users/bteeuwen/Sites/wdmmg/wdmmg/templates'], 
'myghty.component_root': [{'templates': 
'/Users/bteeuwen/Sites/wdmmg/wdmmg/templates'}], 'kid.encoding': 'utf-8', 
'kid.assume_encoding': 'utf-8', 'mako.module_directory': 

Re: [Tutor] Converting files

2011-04-11 Thread Alan Gauld


sunil tech sunil.tech...@gmail.com wrote

is there any way to convert any file (eg: document files  image 
files) to

.pdf?

if so, kindly share...


Install a PDF print driver and then print the file to that printer.
Set it to save as a file. Then if its printable you can get it as a 
PDF.


You can do the same with postscript(and postscript drivers
come with most OS). Then send the postscript file to Adobe's
web site to get them to generate the PDF from postscript.
(You can also download free convertors)

Finally, and because this is a Python list,  you could use a
Python library and generate the file yourself - but while thats
ok for your own data its a lot harder for many file types!

HTH,

--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Running python on windows

2011-04-11 Thread James Reynolds
At least in my case it was about simplicity. If it was a simple matter of
using a base python program, that would be one thing, but the last program
i distributed here at work used pygtk as it's GUI (which at the time
required four different packages, I believe they have consolidated this down
to one, thank god), a month / date arithmetic module a few other modules I
can't remember off the top of my head.

It doesn't make sense to say, go here, install this, ok, now drop this in
this folder, ok now drop this in that folder, ok now open your command
prompt and type this string of words. But don't typo while your at it.

It took all of five minutes to learn how to use CX enough so I could freeze
something and send it around to people here to use. It would have taken 30
minutes to explain how to install each component to people who just want
stuff to work.

On Mon, Apr 11, 2011 at 4:44 PM, Alan Gauld alan.ga...@btinternet.comwrote:


 Mike Silverson msilvers...@gmail.com wrote

  installed on the target computer.  I am trying to send a program to a
 friend
 using windows and he does not have python installed, and does not want to
 take the time to install it.


 Given how quickly Python installs compared to many other apps I
 can only assume he uses Wordpad as his word processor?! Honestly
 you could just build an installer that installed Python and your files
 and I doubt he'd notice the install time as being excessive!

 However, there is no way to run Python without installing an interpreter.
 If you don't use a standalone install you need to build the interpreter
 into an exe and then install a separate python installation for every app
 he uses. Its mad. Does he refuse to install .Net or Java or the
 VisualBasic runtime?

 But if he must there are several options available, the best known
 is py2exe but there are others out there.

 --
 Alan Gauld
 Author of the Learn to Program web site
 http://www.alan-g.me.uk/



 ___
 Tutor maillist  -  Tutor@python.org
 To unsubscribe or change subscription options:
 http://mail.python.org/mailman/listinfo/tutor

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python on TV

2011-04-11 Thread bob gailer

On 4/11/2011 4:20 PM, Alan Gauld wrote:

I've just watched the Channel 5 programme The Gadget Show
where the presenters set a new Guinness world record for operating
the heaviest machine(*) using mind power. The software behind
this feat - was written in Python of course! :-)

(*)The machine in question was a 50 ton industrial crane... used
to move a car from one end of a warehouse to the other.

The show should be here - Pause at 1 minute 20 for the
Python screnshot:

http://fwd.channel5.com/gadget-show/videos/challenge/surprise-special-part-4 



I am told the video ... cannot be viewed from your currrent country ...

Sigh.


--
Bob Gailer
919-636-4239
Chapel Hill NC

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Import multiple lines of text into a variable

2011-04-11 Thread Sean Carolan
I'm not sure how to do this. I'm reading lines in from a text file.
When I reach the string notes:, I want to assign the remainder of
the text file to a single variable (line breaks and all):

text
moretext
moretext
notes:
This is the stuff I want in my variable.
And this line should be included too.
Also this one.

So right now my code looks something like this:

for line in open('myfile','r'):
  if line.startswith('notes'):
  ## Assign rest of file to variable

Is there an easy way to do this?  Or do I need to read the entire file
as a string first and carve it up from there instead?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Converting files

2011-04-11 Thread Evans Anyokwu
I use Openoffice and it has an option to export your files to .pdf and lots
of other file formats.
It's a free download - and has all the usual Office applications...

Search for 'OpenOffice' online.

On Mon, Apr 11, 2011 at 9:48 PM, Alan Gauld alan.ga...@btinternet.comwrote:


 sunil tech sunil.tech...@gmail.com wrote


  is there any way to convert any file (eg: document files  image files) to
 .pdf?

 if so, kindly share...


 Install a PDF print driver and then print the file to that printer.
 Set it to save as a file. Then if its printable you can get it as a PDF.

 You can do the same with postscript(and postscript drivers
 come with most OS). Then send the postscript file to Adobe's
 web site to get them to generate the PDF from postscript.
 (You can also download free convertors)

 Finally, and because this is a Python list,  you could use a
 Python library and generate the file yourself - but while thats
 ok for your own data its a lot harder for many file types!

 HTH,

 --
 Alan Gauld
 Author of the Learn to Program web site
 http://www.alan-g.me.uk/



 ___
 Tutor maillist  -  Tutor@python.org
 To unsubscribe or change subscription options:
 http://mail.python.org/mailman/listinfo/tutor

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Import multiple lines of text into a variable

2011-04-11 Thread Sean Carolan
 So right now my code looks something like this:

 for line in open('myfile','r'):
  if line.startswith('notes'):
      ## Assign rest of file to variable

 Is there an easy way to do this?  Or do I need to read the entire file
 as a string first and carve it up from there instead?

I ended up doing this, but please reply if you have a more elegant solution:

if line.startswith('notes'):
   break
notes = open('myfile','r').read().split(notes:\n')[1]
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Import multiple lines of text into a variable

2011-04-11 Thread bob gailer

On 4/11/2011 5:14 PM, Sean Carolan wrote:

So right now my code looks something like this:

for line in open('myfile','r'):
  if line.startswith('notes'):
  ## Assign rest of file to variable

Is there an easy way to do this?  Or do I need to read the entire file
as a string first and carve it up from there instead?

I ended up doing this, but please reply if you have a more elegant solution:

if line.startswith('notes'):
break
notes = open('myfile','r').read().split(notes:\n')[1]


Seems like an elegant solution to me, as long as the file fits available 
memory. There will be 2 copies of the file after the split.


Another way:

textFile = open('myfile','r')
for line in textFile:
 if line.startswith('notes'):
  notes = textFile.read()

--
Bob Gailer
919-636-4239
Chapel Hill NC

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Running python on windows

2011-04-11 Thread ALAN GAULD


 At least in my case it was about simplicity. If it was a simple matter of 
 using 

 a base python program, that would be one thing, but the last program i 
 distributed here at work used pygtk as it's GUI 

Valid comment although its not much more work to build a custom 
installer that installs Python plus all the other libs. And checks that 
they aren't already there first...

However due to the incompatibility issues around v3 I'm much less 
anti-packages than I used to be. But I do think the reluctance to 
install Python is not a valid reason, it's not much different to installing 
a JVM for java.

 It doesn't make sense to say, go here, install this, ok, now drop 
 this in this folder, ok now drop this in that folder, ok now open 
 your command prompt and type this string 

Agreed, we need to package our apps so the user doesn't need to 
do this. But that doesn't necessariily mean creating a packed exe.
But sadly that usually means using a third party installer, and the 
best of those are all commercial so it costs $$$.

Alan G.___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Running python on windows

2011-04-11 Thread Wayne Werner
On Mon, Apr 11, 2011 at 4:24 PM, ALAN GAULD alan.ga...@btinternet.comwrote:

   It doesn't make sense to say, go here, install this, ok, now drop
  this in this folder, ok now drop this in that folder, ok now open
  your command prompt and type this string

 Agreed, we need to package our apps so the user doesn't need to
 do this. But that doesn't necessariily mean creating a packed exe.
 But sadly that usually means using a third party installer, and the
 best of those are all commercial so it costs $$$.


The best, yes, but the likes of InnoSetup or NSIS are free, and fairly
reasonable to use.

Once I graduate, I suspect it won't be long before I've built a few
templates around one or the other specifically designed for Python. I'm not
aware if anyone else has done such things.

-Wayne
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Generating XML using Python

2011-04-11 Thread Karim

On 04/11/2011 07:50 PM, Karim wrote:

On 04/11/2011 10:04 AM, tee chwee liong wrote:

hi Peter,

thanks for your reply. seems that xml doesnt accept a space in between.
anyway, the output generated is:
*-* file:///C:/Python25/myscript/cmm/port1.xml# Test
*-* file:///C:/Python25/myscript/cmm/port1.xml# 
Default_ConfigPort=*8*

** LINK*2*/LINK
** Target_Speed*3*/Target_Speed
** /Default_Config
** /Test

it overwrites every time the port number is incremented and only 
capture the last iteration number. how can i modify it to capture all 
the iteration? for eg:

Port 1
Link speed: 2
Target speed: 3
Port 2
Link speed: 2
Target speed: 3
Port 3
Link speed: 2
Target speed: 3
Port 4
Link speed: 2
Target speed: 3
Port 5
Link speed: 2
Target speed: 3
Port 6
Link speed: 2
Target speed: 3
Port 7
Link speed: 2
Target speed: 3
Port 8
Link speed: 2
Target speed: 3

thanks
tcl




Sorry for the error, must remove ' Port' in iter() this example use std 
lib xml.etree.ElementTree doctree_instance obtain through parse()
method from ElementTree and it works with infinite tag 'default_Config' 
list:

for config in doctree_instance.iter('Default_Config'):
link = config.find('LINK')
target = config.find('Target_Speed')

print('Port ', config.attrib['Port'])
print('Link speed:', link.text)
print('Target speed:', target.text)

Regards



___
Tutor maillist  -Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor



___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Import multiple lines of text into a variable

2011-04-11 Thread Alan Gauld


Sean Carolan scaro...@gmail.com wrote

I ended up doing this, but please reply if you have a more elegant 
solution:


if line.startswith('notes'):
   break
notes = open('myfile','r').read().split(notes:\n')[1]


The first two lines are redundant you only need the last one.

HTH,

Alan G. 



___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Import multiple lines of text into a variable

2011-04-11 Thread Sean Carolan
 if line.startswith('notes'):
   break
 notes = open('myfile','r').read().split(notes:\n')[1]

 The first two lines are redundant you only need the last one.

I should have clarified, the if line.startswith part was used to
break out of the previous for loop, which was used to import the
other, shorter strings.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor