Re: [Tutor] Help...

2009-07-28 Thread Alan Gauld

"Ryan V"  wrote


as i am returning all the values. it is telling me that there is no value
for the variables i am returning.  any help is greatly appreciated!


You are returning the values to variables in the main function.
But in Python variables inside functions (aka local variables) are
only visible inside that fuinction, they are NOT cvisible to
functions that are called from inside the same function.

So yor variables in main() are not visible to the input_
set of functions. They are visible to calc_price because
you pass them in as arguments.


def main():
   print 'The menu is:'
   print 'Yum Yum Burger for $0.99'
   print 'Grease Yum Fries for $0.79'
   print 'Soda Yum For $1.09'
   mealOrder = input_meal()
   burgerPrice = input_burger()
   friesPrice = input_fries()
   sodaPrice = input_soda()
   mealEnd = input_mealEnd()
   calc_total(burgerPrice, friesPrice, sodaPrice)
#print_info(total)

def input_meal():
   print 'If you want the Yum Yum Burger please press 1'
   print 'If you want the Grease Yum Fries please press 2'
   print 'If you want the Soda Yum please press 3'
   print 'If you entered no instead of yes just hit 4'


Whee would the user enter no instead of yes?
At this stage of the program you haven't asked them to enter yes or no.

BTW from a presentation point of view you might want to
put the menu in a long string using triple quotes which
will help you align the menu options:

print '''
If you want the Yum Yum Burger please press 1
If you want the Grease Yum Fries please press  2
If you want the Soda Yum please press3
If you entered no instead of yes just hit 4
'''


   mealOrder = input('Enter Now - ')


In Python 2.x using input() is considered a bad idea since it
allows users to (deliberately or by accident) enter python code
that could do damage to your program or even your computer!
Its better to use raw_input() and convert the result to the
required type, such as int.

mealOrder = int( raw_input('Enter Now - ') )

Slightly more typing but much safer.


   if mealOrder == '1' :
   input_burger()
   elif mealOrder == '2' :
   input_fries()
   elif mealOrder == '3' :
   input_soda()
   elif mealOrder == '4' :
   calc_total(burgerPrice, friesPrice, sodaPrice)


But this won't work because you are inside input_meal()
which doesn''t have any variables called burgerPrice etc.

However, this also means that you are going to call
calc_total twice, since after you return from input_meal()
you also call calc_total in main(). I suspect you don't want
that, instead you want to return the values back to main
so that calc_total there can do the calculation after all the
data collection has been completed?


def input_burger():
   amountBurger = input('How many burgers would you like?')
   burgerPrice = amountBurger * 0.99
   input_mealEnd()
   return burgerPrice


Now this is where it gets really complicated.
You call input_MealEnd here which in turn can
call input_meal which in turn can call input_burger
and so on. This kind of deep cyclic tree of function
calls is called recursion and is not the best way to
control the flow of your code. Look at using loops
and branches to do that at the top level. The top
level function should control the flow of your program,
the lower level functions should perform only one step
and return a value.


def input_fries():
   amountFries = input('How many Fries would you like?')
   friesPrice = amountFries * 0.79
   input_mealEnd()
   return friesPrice


Notice that these other functions are exactly the same
as each other apart from the names you used for the
variables. You could therefore write one function that
takes the food and price as parameters:


def input_food(food, price):
   amount = int( raw_input('How many %s would you like?' % food) )
   thePrice = amount * price
   return thePrice


You would then call it as:

friesPrice = input_food('fries', 0.79)


def input_mealEnd():
   mealEnd = raw_input('Would you like to end your order? (Enter yes or
no)')
   if mealEnd == 'yes' :
   calc_total(burgerPrice, friesPrice, sodaPrice)
   elif mealEnd == 'no' :
   input_meal()


And here we have yet another call to calc_total


#Calculation of meal cost
def calc_total(burgerPrice, friesPrice, sodaPrice):
   totalFood = burgerPrice + friesPrice + sodaPrice
   totalTax = totalFood * .06
   total = totalTax + totalFood
   print 'The total price for food is $', totalFood
   print 'The Tax is $', totalTax
   print 'The total is $', total


Its probably better not to print the values in a rfunction that
claims to calculate. Instead return the values so that a display
function can print them suitable formatted. That way you can
easily change the display(to HTML say) without changing
the calculation functions.

So instead of the print lines simply return the three values:

return totalFood, totalTax, total



#Displays total, and what you ordered
#def print_info(total):
#print 'The 

Re: [Tutor] self.name vs. passing a name

2009-07-28 Thread Alan Gauld

"Che M"  wrote


Let's say you have a sequence of two calculations ...each one
done as a function called by an overall calculate_something() function.



The "answer" to each function is then used in the next function.
I can think of two ways to make that answer available ...
  1) pass it in, or
  2) declare it as self.answer


The first is the best solution in the general case however,
1)  if your functions are methods of a class AND
2) you can use the intermediate result for something useful
   elsewhere in the class

then you could use the second method.
Otherwise the second merthod is just a variation in storing the
result in a global variable wjhich is generally considered a bad
design style.

In general keep data as close to its point of use as possible.


HTH,

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



___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to use Python 2.6 with IDLE?

2009-07-28 Thread Dave Angel

Dick Moores wrote:



I'm not sure how to edit it. What's required for Ulipad is quite
different, I believe.

This is what I got from Dave Angel:
e:
  cd \Python26\Lib\idlelib\
  ..\..\pythonw.exe idle.pyw %*

And I can't decipher it. What is the "..\..\"?

  
Just ask.The double-dots are the standard way of indicating "the 
directory above the previous one."  That's useful knowledge not only 
within batch files but also within shortcuts and within Python programs.


The batch file starts by changing to the E: drive.  Then it changes to 
the explicit directory \Python26\Lib\idlelib, and because of the leading 
slash, that refers to an absolute directory, irrespective of what the 
current directory happened to be earlier. The 3rd line means that we 
want to run a program pythonw.exe, located two directories up from the 
current one, *without changing" the current directory.  It could have 
been written:


e:\Python26\pythonw.exe idle.pyw %*

but then if you ever changed to a different version, or installed on a 
different drive or directory, you'd have two places in the batch file to 
change.  I like using relative directories where possible.


Finally, the %* at the end means copy whatever other parameters were 
passed to the batch file, as additional parameters to the program.

I would like to learn how to write simple batch files, however, quite
aside from writing one to solve my Ulipad problem.





___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help...

2009-07-28 Thread Dave Angel

Ryan V wrote:

For this source code, i am getting some errors, and not sure how to fix it,
as i am returning all the values. it is telling me that there is no value
for the variables i am returning.  any help is greatly appreciated!
Source
#main function
def main():
print 'The menu is:'
print 'Yum Yum Burger for $0.99'
print 'Grease Yum Fries for $0.79'
print 'Soda Yum For $1.09'
mealOrder = input_meal()
burgerPrice = input_burger()
friesPrice = input_fries()
sodaPrice = input_soda()
mealEnd = input_mealEnd()
calc_total(burgerPrice, friesPrice, sodaPrice)
#print_info(total)

def input_meal():
print 'If you want the Yum Yum Burger please press 1'
print 'If you want the Grease Yum Fries please press 2'
print 'If you want the Soda Yum please press 3'
print 'If you entered no instead of yes just hit 4'
mealOrder = input('Enter Now - ')
if mealOrder == '1' :
input_burger()
elif mealOrder == '2' :
input_fries()
elif mealOrder == '3' :
input_soda()
elif mealOrder == '4' :
calc_total(burgerPrice, friesPrice, sodaPrice)

def input_burger():
amountBurger = input('How many burgers would you like?')
burgerPrice = amountBurger * 0.99
input_mealEnd()
return burgerPrice

def input_fries():
amountFries = input('How many Fries would you like?')
friesPrice = amountFries * 0.79
input_mealEnd()
return friesPrice

def input_soda():
amountSoda = input('How many sodas would you like?')
sodaPrice = amountSoda * 1.09
input_mealEnd()
return sodaPrice

def input_mealEnd():
mealEnd = raw_input('Would you like to end your order? (Enter yes or
no)')
if mealEnd == 'yes' :
calc_total(burgerPrice, friesPrice, sodaPrice)
elif mealEnd == 'no' :
input_meal()

#Calculation of meal cost
def calc_total(burgerPrice, friesPrice, sodaPrice):
totalFood = burgerPrice + friesPrice + sodaPrice
totalTax = totalFood * .06
total = totalTax + totalFood
print 'The total price for food is $', totalFood
print 'The Tax is $', totalTax
print 'The total is $', total
#Displays total, and what you ordered
#def print_info(total):
#print 'The meal price is $', total

#call main function
main()
 and here is the output i am getting

The menu is:
Yum Yum Burger for $0.99
Grease Yum Fries for $0.79
Soda Yum For $1.09
If you want the Yum Yum Burger please press 1
If you want the Grease Yum Fries please press 2
If you want the Soda Yum please press 3
If you entered no instead of yes just hit 4
Enter Now - 1
How many burgers would you like?2
Would you like to end your order? (Enter yes or no)no
If you want the Yum Yum Burger please press 1
If you want the Grease Yum Fries please press 2
If you want the Soda Yum please press 3
If you entered no instead of yes just hit 4
Enter Now - 2
How many Fries would you like?2
Would you like to end your order? (Enter yes or no)no
If you want the Yum Yum Burger please press 1
If you want the Grease Yum Fries please press 2
If you want the Soda Yum please press 3
If you entered no instead of yes just hit 4
Enter Now - 3
How many sodas would you like?2
Would you like to end your order? (Enter yes or no)yes
*Traceback (most recent call last):
  File "...", line 74, in 
main()
  File "...", line 16, in main
sodaPrice = input_soda()
  File "...", line 51, in input_soda
input_mealEnd()
  File "...", line 57, in input_mealEnd
calc_total(burgerPrice, friesPrice, sodaPrice)
NameError: global name 'burgerPrice' is not defined*

  
Please tell us - is this your first programming language, or are you 
comfortable with another, and you need to see how Python differs from 
it?  I suspect it's your first.


The main problem is that you're trying to use a function meal_end() to 
do flow control that needs to be in main().  Each time the user says 
"no" to "Would you like to end your order" you don't loop back to the 
same place, you call a new copy of input_meal(). (That's called 
recursion, and it's very useful, but not here).  But you never return to 
the first copy of input_meal().  So you end up with several copies of 
that function.  And only when all of them return (which won't happen) 
would you get back to main().  You need a loop (while or for), not 
recursion.


Second problem is that you're calling functions that return values, and 
only some of the time recording those actual values anywhere.  When/if 
input_meal() calls input_burger(), it doesn't save the result anywhere. 
So if it did return, main() still couldn't get the value, it's already lost.


Third problem is that you have function input_mealEnd() that defines 
only one variable, but then expect three others to somehow have useful 
values.


Fourth is that you don't have a good way to terminate the program.  
Where do you expect to go after printing the current order?  You might 
expect to start a new order, or something else, but that would require 
t

Re: [Tutor] self.name vs. passing a name

2009-07-28 Thread Dave Angel

Che M wrote:

This is another very basic structural question, related to one I asked last 
week, and again is not necessarily germane only to Python.

Let's say you have a sequence of two calculations or manipulations you need to do, each 
one done as a function called by an overall calculate_something() function.  The 
"answer" to each function is then used in the next function.  I can think of 
two ways to make that answer available for use in the next function:  1) pass it in, or 
2) declare it as self.answer and then it is available to the whole class instance.

What are the dis/advantages to these two different ways?  Here are examples, 
with only the overall calculate_something() function shown:

1.Pass the variable to the second function.

def calculate_something(self):
answer = self.do_first_calculation()#1st function returns answer
self.do_second_calculation(answer)#2nd is passed answer and uses it.

2. Create the variable in the class instance scope and use that in the second 
function.

def calculate_something(self):

self.do_first_calculation() #1st function creates 
self.answer

self.do_second_calculation() #2nd uses self.answer

Both of these approaches can work, but I would like to better understand when 
it is best to do one or the other.  Obviously if I know I will need to make 
self.answer available for use by other functions, I would want to choose (2).  
But what other considerations should I, well, consider?

Thanks,
Che


  
You call these functions, but since you have the "self" argument, I'll 
assume it's a method instead.


use #2 only if the "answer" is relevant for further operations, AND  (is 
time-consuming to calculate compared to the memory consumed by storing 
it, OR  if calculating it has side effects)


prefer #1 because:
 it doesn't take up space in the object
 it goes away when the particular method ends, not when the object 
is destroyed (rule -- the sooner the better)

 it doesn't clutter the namespace of the class

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to use Python 2.6 with IDLE?

2009-07-28 Thread Dick Moores
On Tue, Jul 28, 2009 at 02:20, Dave Angel wrote:
> Dick Moores wrote:
>>
>> 
>> I'm not sure how to edit it. What's required for Ulipad is quite
>> different, I believe.
>>
>> This is what I got from Dave Angel:
>> e:
>>  cd \Python26\Lib\idlelib\
>>  ..\..\pythonw.exe idle.pyw %*
>>
>> And I can't decipher it. What is the "..\..\"?
>>
>>
>
> Just ask.The double-dots are the standard way of indicating "the
> directory above the previous one."  That's useful knowledge not only within
> batch files but also within shortcuts and within Python programs.
>
> The batch file starts by changing to the E: drive.  Then it changes to the
> explicit directory \Python26\Lib\idlelib, and because of the leading slash,
> that refers to an absolute directory, irrespective of what the current
> directory happened to be earlier. The 3rd line means that we want to run a
> program pythonw.exe, located two directories up from the current one,
> *without changing" the current directory.  It could have been written:
>
>e:\Python26\pythonw.exe idle.pyw %*
>
> but then if you ever changed to a different version, or installed on a
> different drive or directory, you'd have two places in the batch file to
> change.  I like using relative directories where possible.
>
> Finally, the %* at the end means copy whatever other parameters were passed
> to the batch file, as additional parameters to the program.

Thanks, Dave. Very informative.

Dick
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Django test case problem

2009-07-28 Thread VIJAY KUMAR
Hi,
   I am running testcase from django when I run them from models.py it run.
   But when I put the same in test.py in the same directory where models is 
define it not even getting called.
  My structure django application is  mysite
Settings.py
 Urls.py
  Polls
 __int__.py
 models.py
 test.py
 views.py
I used this command to run the test cases   python manage.py test polls
Can some help me know what am I missing or should need to do something  so my 
testcase from test.py start get executed.
I tried to follow this link for the same 
http://docs.djangoproject.com/en/dev/topics/testing/
 
 
 
with thanks
Vijay 
 


  Love Cricket? Check out live scores, photos, video highlights and more. 
Click here http://cricket.yahoo.com___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] how to get blank value

2009-07-28 Thread amrita
Sorry to say, but till now I have not got the solution of my problem, I
tried with this command:-

import re

if __name__ == '__main__':
 data = open('chem.txt').readlines()
 for line in data:
 RE = re.compile('C = (.)',re.M)
 matches = RE.findall(line)
 for m in matches:
 print line

but with this also I am getting those lines for which C value is there.


> Hi,
>
> I have a file having lines:-
>
> 48 ALA H = 8.33 N = 120.77 CA = 55.18 HA = 4.12 C = 181.50
> 104 ALA H = 7.70 N = 121.21 CA = 54.32 HA = 4.21 C =
> 85 ALA H = 8.60 N =  CA =  HA = 4.65 C =
>
> Now i want to make two another file in which i want to put those lines for
> which C is missing and another one for which N,CA and C all are missing,
>
> With these commands:-
>
> import re
> f = open('chem.txt')
> for line in f:
>  if re.search('C = ',line):
> print line
>
> I am getting those lines for which C value is there but how to get those
> one for which it doesn't have any value, i did google search but still i
> am not getting.
>
> Amrita Kumari
> Research Fellow
> IISER Mohali
> Chandigarh
> INDIA
>


Amrita Kumari
Research Fellow
IISER Mohali
Chandigarh
INDIA

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] how to get blank value

2009-07-28 Thread bob gailer

amr...@iisermohali.ac.in wrote:

Sorry to say, but till now I have not got the solution of my problem, I
tried with this command:-

import re

  

# assuming H = , N = , CA = , HA =  and C = always present in that order
if __name__ == '__main__':
 data = open('chem.txt').readlines()
 for line in data:
   line = line.split('=')
   if not line[5]: # C value missing
if len(line[2])==1 and len(line[3])==1: # N and CA values missing
   print "all missing", line
 else:
   print "C missing", line



  

Hi,

I have a file having lines:-

48 ALA H = 8.33 N = 120.77 CA = 55.18 HA = 4.12 C = 181.50
104 ALA H = 7.70 N = 121.21 CA = 54.32 HA = 4.21 C =
85 ALA H = 8.60 N =  CA =  HA = 4.65 C =

Now i want to make two another file in which i want to put those lines for
which C is missing and another one for which N,CA and C all are missing,

With these commands:-

import re
f = open('chem.txt')
for line in f:
 if re.search('C = ',line):
print line

I am getting those lines for which C value is there but how to get those
one for which it doesn't have any value, i did google search but still i
am not getting.

Amrita Kumari
Research Fellow
IISER Mohali
Chandigarh
INDIA






--
Bob Gailer
Chapel Hill NC
919-636-4239
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Messages not going through (testing again)

2009-07-28 Thread Eduardo Vieira
Hello, this is just a test. I have posted 2 different messages and
they have never reached this list.

Eduardo
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] [BangPypers] Django test case problem

2009-07-28 Thread B.Nanda Kishore
By default django looks for a file called *tests.py*(plural) and not *
test.py*. Check that and let us know.
Regards,
Nandakishore


On Tue, Jul 28, 2009 at 6:40 PM, VIJAY KUMAR  wrote:

>  Hi,
>
>I am running testcase from django when I run them from models.py it
> run.
>
>But when I put the same in test.py in the same directory where models
> is define it not even getting called.
>
>   My structure django application is  mysite
>
> Settings.py
>
>  Urls.py
>
>   Polls
>
>  __int__.py
>
>  models.py
>
>  test.py
>
>  views.py
>
> I used this command to run the test cases   python manage.py test polls
>
> Can some help me know what am I missing or should need to do something  so
> my testcase from test.py start get executed.
>
> I tried to follow this link for the same
> http://docs.djangoproject.com/en/dev/topics/testing/
>
>
>
>
>
>
>
> with thanks
>
> Vijay
>
>
> --
> Love Cricket? Check out live scores, photos, video highlights and more. Click
> here .
> ___
> BangPypers mailing list
> bangpyp...@python.org
> http://mail.python.org/mailman/listinfo/bangpypers
>
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Messages not going through (testing again)

2009-07-28 Thread Ataulla S H
welcome to Tutor:)

On Tue, Jul 28, 2009 at 8:18 PM, Eduardo Vieira wrote:

> Hello, this is just a test. I have posted 2 different messages and
> they have never reached this list.
>
> Eduardo
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>



-- 
Ataulla SH

web:www.kring.com
personal blog:www.ataulla.objectis.net
KRING Technologies India Pvt. Ltd.
1st Floor, Tower B, Infinity Towers, DLF II, Gurgaon-122 002
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] how to know if process is running?

2009-07-28 Thread shawn bright
Hey all,

I have an app that runs in a GUI written in pygtk. It spawns several
threads, and runs all the time.
It is mission critical that we can never have two instances of this
running at once.

So, my question is, how can i write something that will know if there
is an instance of that something already running?

I am doing this in python 2.5 on Ubuntu, if that matters ( which i
suspect it does ).

thanks,
shawn
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] how to know if process is running?

2009-07-28 Thread shawn bright
Thanks for the pointers Wayne, Tino,
Looks easier than i had thought.
sk

On Tue, Jul 28, 2009 at 11:10 AM, Tino Dai wrote:
> On Tue, Jul 28, 2009 at 11:45 AM, shawn bright  wrote:
>>
>> So, my question is, how can i write something that will know if there
>> is an instance of that something already running?
>>
>
> There are a lot of ways to do this. Writing to a file on the filesystem and
> having the 2nd process check for that file. Have the thread write to a log
> file every x seconds and having the 2nd process check for that. Having some
> sort of ipc mechanism set up (http://docs.python.org/library/ipc.html). Have
> a semaphore mechanism set up.
> (http://www.python.org/doc/2.5.2/lib/semaphore-objects.html)
>
> HTH,
> Tino
>
>
>
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] how to get blank value

2009-07-28 Thread amrita
It is not giving any value, without any error

ph08...@sys53:~> python trial.py
ph08...@sys53:~>
it is coming out from shell.

Thanks for help.
Amrita

> amr...@iisermohali.ac.in wrote:
>> Sorry to say, but till now I have not got the solution of my problem, I
>> tried with this command:-
>>
>> import re
>>
>>
> # assuming H = , N = , CA = , HA =  and C = always present in that order
> if __name__ == '__main__':
>   data = open('chem.txt').readlines()
>   for line in data:
> line = line.split('=')
> if not line[5]: # C value missing
>  if len(line[2])==1 and len(line[3])==1: # N and CA values missing
> print "all missing", line
>   else:
> print "C missing", line
>
>>
>>
>>> Hi,
>>>
>>> I have a file having lines:-
>>>
>>> 48 ALA H = 8.33 N = 120.77 CA = 55.18 HA = 4.12 C = 181.50
>>> 104 ALA H = 7.70 N = 121.21 CA = 54.32 HA = 4.21 C =
>>> 85 ALA H = 8.60 N =  CA =  HA = 4.65 C =
>>>
>>> Now i want to make two another file in which i want to put those lines
>>> for
>>> which C is missing and another one for which N,CA and C all are
>>> missing,
>>>
>>> With these commands:-
>>>
>>> import re
>>> f = open('chem.txt')
>>> for line in f:
>>>  if re.search('C = ',line):
>>> print line
>>>
>>> I am getting those lines for which C value is there but how to get
>>> those
>>> one for which it doesn't have any value, i did google search but still
>>> i
>>> am not getting.
>>>
>>> Amrita Kumari
>>> Research Fellow
>>> IISER Mohali
>>> Chandigarh
>>> INDIA
>>>
>>>
>>>
>
>
> --
> Bob Gailer
> Chapel Hill NC
> 919-636-4239
>


Amrita Kumari
Research Fellow
IISER Mohali
Chandigarh
INDIA

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] how to know if process is running?

2009-07-28 Thread Chris Fuller
On Tuesday 28 July 2009 10:45, shawn bright wrote:
> Hey all,
>
> I have an app that runs in a GUI written in pygtk. It spawns several
> threads, and runs all the time.
> It is mission critical that we can never have two instances of this
> running at once.
>
> So, my question is, how can i write something that will know if there
> is an instance of that something already running?
>
> I am doing this in python 2.5 on Ubuntu, if that matters ( which i
> suspect it does ).

The usual way is with file locks, but these are tricky to do in a cross 
platform way, and I find that when the program crashes unexpectedly, it can 
take awhile for the locks to get cleaned up by the operating system.

What I do is open an UDP socket.  The code is dead simple:

from socket import socket, AF_INET, SOCK_DGRAM

def check_port(addr):
   s = socket(AF_INET, SOCK_DGRAM)

   try:
  s.bind( addr )
   except SocketError, e:
  if type(e.args) == tuple:
 if e[0] == errno.EADDRINUSE:
return True

  raise

   else:
  s.close()
  return False

def check_port(addr):
   return check_port(addr, SOCK_DGRAM)

# returns False if the port is bound
def socket_lock(port, check_only=False):
   s = socket(AF_INET, SOCK_DGRAM)
   addr = ('localhost', port)

   if not check_port(addr):
  if not check_only:
 s.bind( addr )
 return s
  else:
 return True
   else:
  return False


addr is the address tuple used by the socket module.  First element is 
hostname (usually "localhost"), and the second element is the port number.  
Note that you need root/Administrator privileges to open a port under 1024.

Cheers
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] how to know if process is running?

2009-07-28 Thread Mac Ryan
I am not an expert, but if I got you correctly, what you want to achieve
is a "singleton": http://en.wikipedia.org/wiki/Singleton_pattern if you
watch at the sample implementation, there is a Python example too.

Mac.

On Tue, 2009-07-28 at 10:45 -0500, shawn bright wrote:
> Hey all,
> 
> I have an app that runs in a GUI written in pygtk. It spawns several
> threads, and runs all the time.
> It is mission critical that we can never have two instances of this
> running at once.
> 
> So, my question is, how can i write something that will know if there
> is an instance of that something already running?
> 
> I am doing this in python 2.5 on Ubuntu, if that matters ( which i
> suspect it does ).
> 
> thanks,
> shawn
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] how to get blank value

2009-07-28 Thread bob gailer

amr...@iisermohali.ac.in wrote:

It is not giving any value, without any error

ph08...@sys53:~> python trial.py
ph08...@sys53:~>
it is coming out from shell.
  

Try this. I embedded the test data to simplify testing:

data = """48 ALA H = 8.33 N = 120.77 CA = 55.18 HA = 4.12 C = 181.50
104 ALA H = 7.70 N = 121.21 CA = 54.32 HA = 4.21 C =
85 ALA H = 8.60 N =  CA =  HA = 4.65 C =""".split('\n')
for line in data:
   line2 = line.split('=')
   if not line2[5]: # C value missing
 if len(line2[2]) <= 5 and len(line2[3]) <= 5: # N and CA values 
missing

   print "all missing", line
 else:
   print "C missing", line

--
Bob Gailer
Chapel Hill NC
919-636-4239
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Two problems related to dispathing.

2009-07-28 Thread Mac Ryan
Hello,

I'm working on an application in which I need the main loop to call the
same method on a number of objects. I came up with this solution that
seem to work, but I was wondering if there is a better / more pythonic
solution to the problem.


def invokeAll(method, data):
"""This function is a dispatcher: it invokes all the content types
of the application calling 'contenttype.method(data)'"""
return [getattr(content, method)(data) for content in contents]


I am also unsatisfied by how I generate the content list I use in the
above function. In fact, as I have the need to access the object both
individually and with the dispatcher, I am doing something like this
every time I instantiate a new object: 


mycontent = ContentA()
contents.append(mycontent)


...but although I "feel" this is silly, I can't imagine how to get it
better (i.e. a single call that will make available the object with his
unique name and append it to the list of contents.

Thank you in advance for your input,
Mac.

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] how to know if process is running?

2009-07-28 Thread shawn bright
Hey all, i used the popen with getpid() option.
working well so far, thanks to all of you.
shawn

On Tue, Jul 28, 2009 at 12:11 PM, Mac Ryan wrote:
> I am not an expert, but if I got you correctly, what you want to achieve
> is a "singleton": http://en.wikipedia.org/wiki/Singleton_pattern if you
> watch at the sample implementation, there is a Python example too.
>
> Mac.
>
> On Tue, 2009-07-28 at 10:45 -0500, shawn bright wrote:
>> Hey all,
>>
>> I have an app that runs in a GUI written in pygtk. It spawns several
>> threads, and runs all the time.
>> It is mission critical that we can never have two instances of this
>> running at once.
>>
>> So, my question is, how can i write something that will know if there
>> is an instance of that something already running?
>>
>> I am doing this in python 2.5 on Ubuntu, if that matters ( which i
>> suspect it does ).
>>
>> thanks,
>> shawn
>> ___
>> Tutor maillist  -  tu...@python.org
>> http://mail.python.org/mailman/listinfo/tutor
>
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Two problems related to dispathing.

2009-07-28 Thread Kent Johnson
On Tue, Jul 28, 2009 at 1:22 PM, Mac Ryan wrote:

> def invokeAll(method, data):
>    """This function is a dispatcher: it invokes all the content types
>    of the application calling 'contenttype.method(data)'"""
>    return [getattr(content, method)(data) for content in contents]

In Python 2.6 you can use operator.methodcaller() to do this:
def invokeAll(method, data):
  caller = operator.methodcaller(method, data)
  return map(caller, contents)

> mycontent = ContentA()
> contents.append(mycontent)

This is not so bad. You could also make a class member of the base
class that keeps track of instances:
class ContentA(object):
  contents = []
  def __init__(self):
contents.append(self)

Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] how to get blank value

2009-07-28 Thread Alan Gauld


 wrote


Sorry to say, but till now I have not got the solution of my problem, I
tried with this command:-

import re

if __name__ == '__main__':
data = open('chem.txt').readlines()
for line in data:
RE = re.compile('C = (.)',re.M)


The regex still does not match the end of line.
The regex character for end of line is $ thus you should find something 
like



RE = re.compile('C =$')


You might need to allow for whitespace between the = and $...

If the blanks are not at the end of the line things get slightly more
complicated

HTH,

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



___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Two problems related to dispathing.

2009-07-28 Thread Alan Gauld


"Mac Ryan"  wrote



above function. In fact, as I have the need to access the object both
individually and with the dispatcher, I am doing something like this
every time I instantiate a new object: 



mycontent = ContentA()
contents.append(mycontent)


...but although I "feel" this is silly, I can't imagine how to get it
better (i.e. a single call that will make available the object with his
unique name and append it to the list of contents.


There is no simpler solution without changing the class.
If you can do that you could pass the container to the constructor 
and get the class to add itself to the container


HTH,

Alan G.

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] how to know if process is running?

2009-07-28 Thread Alan Gauld


"shawn bright"  wrote 


So, my question is, how can i write something that will know if there
is an instance of that something already running?

I am doing this in python 2.5 on Ubuntu, if that matters ( which i
suspect it does ).


I suspect the simplest way is to use the ps command and grep.
Wrap your code in a shell script that checks ps before launching 
the script.


If thats not acceptable call ps from subprocess module as soon 
as you start, hopefuilly that won;t break anything although the 
processes will be running together briefly.
If so  you could do the check then fork() or exec() to create the 
real new process...


Finally you can write a signal file into /tmp and then look for that 
file on startup. Don't forget to delete it when you exit though!


Lots of options depending on how hard core you need to be!

HTH,


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

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Two problems related to dispathing.

2009-07-28 Thread Mac Ryan
On Tue, 2009-07-28 at 19:03 +0100, Alan Gauld wrote:
> There is no simpler solution without changing the class.
> If you can do that you could pass the container to the constructor 
> and get the class to add itself to the container

Kent, Alan...

thank you very much, indeed I finally adopted the solution that both of
you suggested, and I am now an happy man! :)

Mac.

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] how to get blank value

2009-07-28 Thread amrita
with these data it is giving output but when I tried

if __name__ == '__main__':
  data = open('chem.txt').readlines()
  for line in data:
  line2 = line.split('=')
  if not line2[5]: # C value missing
if len(line2[2]) <= 5 and len(line2[3]) <= 5:  # N and CA values
missing
  print "all missing", line
else:
  print "C missing", line

by putting data in .txt file then it is not giving output. Actually I have
few large data file what I want that I will put those lines in one file
for which only C value is missing and in another one I will put those line
for which N, CA and C all values are missing.

Thanks for help.
Amrita

> amr...@iisermohali.ac.in wrote:
>> It is not giving any value, without any error
>>
>> ph08...@sys53:~> python trial.py
>> ph08...@sys53:~>
>> it is coming out from shell.
>>
> Try this. I embedded the test data to simplify testing:
>
> data = """48 ALA H = 8.33 N = 120.77 CA = 55.18 HA = 4.12 C = 181.50
> 104 ALA H = 7.70 N = 121.21 CA = 54.32 HA = 4.21 C =
> 85 ALA H = 8.60 N =  CA =  HA = 4.65 C =""".split('\n')
> for line in data:
> line2 = line.split('=')
> if not line2[5]: # C value missing
>   if len(line2[2]) <= 5 and len(line2[3]) <= 5: # N and CA values
> missing
> print "all missing", line
>   else:
> print "C missing", line
>
> --
> Bob Gailer
> Chapel Hill NC
> 919-636-4239
>


Amrita Kumari
Research Fellow
IISER Mohali
Chandigarh
INDIA

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] how to get blank value

2009-07-28 Thread शंतनू

You may like to have a look @ pyparsing module.
URL: http://pyparsing.wikispaces.com/

HTH.
regards,
shantanoo

On 29-Jul-09, at 1:03 AM, amr...@iisermohali.ac.in wrote:


with these data it is giving output but when I tried

if __name__ == '__main__':
data = open('chem.txt').readlines()
for line in data:
line2 = line.split('=')
if not line2[5]: # C value missing
  if len(line2[2]) <= 5 and len(line2[3]) <= 5:  # N and CA values
missing
print "all missing", line
  else:
print "C missing", line

by putting data in .txt file then it is not giving output. Actually  
I have
few large data file what I want that I will put those lines in one  
file
for which only C value is missing and in another one I will put  
those line

for which N, CA and C all values are missing.

Thanks for help.
Amrita


amr...@iisermohali.ac.in wrote:

It is not giving any value, without any error

ph08...@sys53:~> python trial.py
ph08...@sys53:~>
it is coming out from shell.


Try this. I embedded the test data to simplify testing:

data = """48 ALA H = 8.33 N = 120.77 CA = 55.18 HA = 4.12 C = 181.50
104 ALA H = 7.70 N = 121.21 CA = 54.32 HA = 4.21 C =
85 ALA H = 8.60 N =  CA =  HA = 4.65 C =""".split('\n')
for line in data:
  line2 = line.split('=')
  if not line2[5]: # C value missing
if len(line2[2]) <= 5 and len(line2[3]) <= 5: # N and CA values
missing
  print "all missing", line
else:
  print "C missing", line

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




Amrita Kumari
Research Fellow
IISER Mohali
Chandigarh
INDIA

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] how to get blank value

2009-07-28 Thread Dave Angel

amr...@iisermohali.ac.in wrote:

It is not giving any value, without any error

ph08...@sys53:~> python trial.py
ph08...@sys53:~>
it is coming out from shell.

Thanks for help.
Amrita

  

amr...@iisermohali.ac.in wrote:


Sorry to say, but till now I have not got the solution of my problem, I
tried with this command:-

import re


  

# assuming H = , N = , CA = , HA =  and C = always present in that order
if __name__ == '__main__':
  data = open('chem.txt').readlines()
  for line in data:
line = line.split('=')
if not line[5]: # C value missing
 if len(line[2])==1 and len(line[3])==1: # N and CA values missing
print "all missing", line
  else:
print "C missing", line


  

Hi,

I have a file having lines:-

48 ALA H = 8.33 N = 120.77 CA = 55.18 HA = 4.12 C = 181.50
104 ALA H = 7.70 N = 121.21 CA = 54.32 HA = 4.21 C =
85 ALA H = 8.60 N =  CA =  HA = 4.65 C =

Now i want to make two another file in which i want to put those lines
for
which C is missing and another one for which N,CA and C all are
missing,

With these commands:-

import re
f = open('chem.txt')
for line in f:
 if re.search('C = ',line):
print line

I am getting those lines for which C value is there but how to get
those
one for which it doesn't have any value, i did google search but still
i
am not getting.

Amrita Kumari
Research Fellow
IISER Mohali
Chandigarh
INDIA





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





Amrita Kumari
Research Fellow
IISER Mohali
Chandigarh
INDIA


  
If you add a strip() ,method call to Bob's line2 definition, it should 
work with your data, when read from file.


  line2 = line.strip().split('=')


But you should realize his code assumes the data fits rather rigid 
rules.  Before you use such code, you should make sure the data will fit 
it correctly.


For example, a blank line will crash the loop.  A line with the four 
variables in some other order will not work.  A fifth variable on a line 
will make it not work.


DaveA

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] self.name vs. passing a name

2009-07-28 Thread Che M


> > The "answer" to each function is then used in the next function.
> > I can think of two ways to make that answer available ...
> >   1) pass it in, or
> >   2) declare it as self.answer

Thank you Alan, Kent, and Dave.  Full agreement, and it makes sense
to me.  (Maybe this is also an example of "explicit is better than implicit"?)

Che

_
Windows Live™ Hotmail®: Celebrate the moment with your favorite sports pics. 
Check it out.
http://www.windowslive.com/Online/Hotmail/Campaign/QuickAdd?ocid=TXT_TAGLM_WL_QA_HM_sports_photos_072009&cat=sports___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] searching for an ip and subnets in a dir of csv's

2009-07-28 Thread Nick Burgess
Good evening List,

I am trying to have this script search for an IP or nearest subnet
match in a dir of csv's. It works with an absolute match,  It will be
receiving a whole IP address, so if there is no absolute match no data
is returned, however if it is listed somewhere in a subnet I want to
know.   I need it to search and loop through the 32 bit, then the 24
bit, 16, 8.  I am stumped at how to cut of the numbers on the right
with the period as the delimiter. I have looked at strip, split need a
clue what else to try.

Thanks!



args.append(arg.strip("\n"))
args = list(set(args))
for arg in args:
for f in files:
pattern = re.compile(sys.argv[1])   <   I
am thinking loop 4 times and do something different here
ff = csv.reader(open (f, 'rb'), delimiter=' ', quotechar='|')
for row in ff:
if any(pattern.search(cell) for cell in row):
print f
print ', '.join(row)
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] "File exists, overwrite?" dialog help

2009-07-28 Thread pedro
Hi I am learning python for use in Nuke (image compositing software). I 
would like to test if a file exists and receive a warning if it does. 
To do a Nuke command line render, it looks something like this:


/Applications/Nuke5.1v5/Nuke5.1v5.app/Contents/MacOS/Nuke5.1v5 -iX 
WriteComp '/Volumes/sgtb/comp_v05.nk'


Where "WriteComp" is the name of a write node within the nuke script 
'/Volumes/sgtb/comp_v05.nk'.
The problem with the above command line command is that it overwrites 
the files that "WriteComp" points to without warning me. So what I 
would like to do is have the command line (or python) ask "File exists, 
overwrite?" Below I have some code which tests whether the file already 
exists by parsing the Nuke script. It is working fine. I am not sure 
how to combine the script below with the command line command above so 
that the above command won't be executed unless I am first asked "File 
exists, overwrite?"





#start
import re, linecache, shutil, sys, os
theFile = (sys.argv[1])

lines = theFile.readlines()
theFile.close()

pattern = re.compile(' name WriteComp')

for i, line in enumerate(lines):
   if pattern.search(line):

   theWriteFilePath = linecache.getline(theFile.name, i-1)

#nukeFilePathAsString =

nukeFilePathContainerAsString = 
'/'.join((theWriteFilePath.split()[1]).split('/')[:-1])

nukeImageAsString = '/'.join((theWriteFilePath.split()[1]).split('/')[-1:])
nukeImageWithZeroesAsString =  nukeImageAsString.split('.')[0] + 
'.0001.' + nukeImageAsString.split('.')[2]


thePythonFriendlyFilePath = nukeFilePathContainerAsString + '/'+ 
nukeImageWithZeroesAsString

#print thePythonFriendlyFilePath

if os.path.exists(thePythonFriendlyFilePath):
   print 'yes'
#end


Thanks
Pete


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Problem with multiple input

2009-07-28 Thread pja

Hi!

I am trying to teach myself Python (using John Zelle's book "Python 
Programming"). One major problem is that the book is written for Python 
2.x and I am using Python 3.1 (and don't want to switch back).


There is a sample script for calculating the sum and difference of two 
numbers:


#   sum_and_difference.py

def sumDiff(x,y):
total = x + y
diff = x - y
return total, diff

def main():
# Introduction
print("This program calculates the sum and difference of two numbers.")
# number1 = float(input("Enter the first number: "))
# number2 = float(input("Enter the second number: "))
number1, number2 = (input("Please enter two numbers: ").split())
number1, number2 = float(number1), float(number2)

total, diff = sumDiff(number1, number2)
diff = abs(diff)
print("The sum is", total, "and the difference is", diff)

main()

I have commented out the two lines where user input is collected (that 
works fine) and tried to replace the two lines with a single input line. 
 The example code works but I don't think it is either optimum or 
elegant.  Could someone help me with the "correct" Python way of doing 
this.  Also the working code only woks with input numbers that are 
separated by a space.  How would I do this with numbers that are 
separated by a comma?


Thanks in advance.

Regards,
Peter
--
*Peter Anderson*
There is nothing more difficult to take in hand, more perilous to
conduct, or more uncertain in its success, than to take the lead in the
introduction of a new order of things—Niccolo Machiavelli, /The Prince/,
ch. 6
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Problem with multiple input

2009-07-28 Thread Alan Gauld

"pja"  wrote

One major problem is that the book is written for Python 2.x and I am 
using Python 3.1 (and don't want to switch back).


Very few books/tutorials exist yet for v3. But you seem to be
coping with the differences adequately. My tutorial for v3 is
almost half-way complete, you might find it useful as a secondary
resource:

http://www.alan-g.me.uk/l2p/


def main():
# Introduction
print("This program calculates the sum and difference of two 
numbers.")

# number1 = float(input("Enter the first number: "))
# number2 = float(input("Enter the second number: "))
number1, number2 = (input("Please enter two numbers: ").split())
number1, number2 = float(number1), float(number2)

  The example code works but I don't think it is either optimum or 
elegant.  Could someone help me with the "correct" Python way of doing


That loooks OK although its a little bit unusual to request two input
values on one line - just because of the difficulty of parsing the result.
Its hard enough to get users to input correct values one at a time!
Never mind formatting two values... as you discovered:

Also the working code only woks with input numbers that are separated by 
a space.  How would I do this with numbers that are separated by a comma?


However you can pass a string to split() that will split the line on
any of the characters in the string. So in your case you could
request a split using spaces and commas - and I suggest adding
semi colons and tabs too?

number1, number2 = (input("Please enter two numbers: ").split(" 
,;\t"))



HTH,

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



___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] how to get blank value

2009-07-28 Thread Paul McGuire
Ok, I've seen various passes at this problem using regex, split('='), etc.,
but the solutions seem fairly fragile, and the OP doesn't seem happy with
any of them.  Here is how this problem looks if you were going to try
breaking it up with pyparsing:
- Each line starts with an integer, and the string "ALA"
- "ALA" is followed by a series of "X = 1.2"-type attributes, where the
value part might be missing.

And to implement (with a few bells and whistles thrown in for free):

data = """48 ALA H = 8.33 N = 120.77 CA = 55.18 HA = 4.12 C = 181.50
104 ALA H = 7.70 N = 121.21 CA = 54.32 HA = 4.21 C =
85 ALA H = 8.60 N =  CA =  HA = 4.65 C =""".splitlines()


from pyparsing import *

# define some basic data expressions
integer = Word(nums)
real = Combine(Word(nums) + "." + Word(nums))

# use parse actions to automatically convert numeric 
# strings to actual numbers at parse time
integer.setParseAction(lambda tokens:int(tokens[0]))
real.setParseAction(lambda tokens:float(tokens[0]))

# define expressions for 'X = 1.2' assignments; note that the
# value might be missing, so use Optional - we'll fill in
# a default value of 0.0 if no value is given
keyValue = Word(alphas.upper()) + '=' + \
Optional(real|integer, default=0.0)

# define overall expression for the data on a line
dataline = integer + "ALA" + OneOrMore(Group(keyValue))("kvdata")

# attach parse action to define named values in the returned tokens
def assignDataByKey(tokens):
for k,_,v in tokens.kvdata:
tokens[k] = v
dataline.setParseAction(assignDataByKey)

# for each line in the input data, parse it and print some of the data
fields
for d in data:
print d
parsedData = dataline.parseString(d)
print parsedData.dump()
print parsedData.CA
print parsedData.N
print


Prints out:

48 ALA H = 8.33 N = 120.77 CA = 55.18 HA = 4.12 C = 181.50
[48, 'ALA', ['H', '=', 8.3301], ['N', '=', 120.77], ['CA', '=',
55.18], ['HA', '=', 4.1201], ['C', '=', 181.5]]
- C: 181.5
- CA: 55.18
- H: 8.33
- HA: 4.12
- N: 120.77
- kvdata: [['H', '=', 8.3301], ['N', '=', 120.77], ['CA', '=',
55.18], ['HA', '=', 4.1201], ['C', '=', 181.5]]
55.18
120.77

104 ALA H = 7.70 N = 121.21 CA = 54.32 HA = 4.21 C =
[104, 'ALA', ['H', '=', 7.7002], ['N', '=', 121.20],
['CA', '=', 54.32], ['HA', '=', 4.21], ['C', '=', 0.0]]
- C: 0.0
- CA: 54.32
- H: 7.7
- HA: 4.21
- N: 121.21
- kvdata: [['H', '=', 7.7002], ['N', '=', 121.20],
['CA', '=', 54.32], ['HA', '=', 4.21], ['C', '=', 0.0]]
54.32
121.21

85 ALA H = 8.60 N =  CA =  HA = 4.65 C =
[85, 'ALA', ['H', '=', 8.5996], ['N', '=', 0.0], ['CA', '=',
0.0], ['HA', '=', 4.6504], ['C', '=', 0.0]]
- C: 0.0
- CA: 0.0
- H: 8.6
- HA: 4.65
- N: 0.0
- kvdata: [['H', '=', 8.5996], ['N', '=', 0.0], ['CA', '=',
0.0], ['HA', '=', 4.6504], ['C', '=', 0.0]]
0.0
0.0


Learn more about pyparsing at http://pyparsing.wikispaces.com.

-- Paul


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] how to get blank value

2009-07-28 Thread amrita
Thanks for help Sir but with these commands it is showing error:-

ph08...@sys53:~> python trip.py
Traceback (most recent call last):
  File "trip.py", line 6, in 
from pyparsing import *
ImportError: No module named pyparsing


> Ok, I've seen various passes at this problem using regex, split('='),
> etc.,
> but the solutions seem fairly fragile, and the OP doesn't seem happy with
> any of them.  Here is how this problem looks if you were going to try
> breaking it up with pyparsing:
> - Each line starts with an integer, and the string "ALA"
> - "ALA" is followed by a series of "X = 1.2"-type attributes, where the
> value part might be missing.
>
> And to implement (with a few bells and whistles thrown in for free):
>
> data = """48 ALA H = 8.33 N = 120.77 CA = 55.18 HA = 4.12 C = 181.50
> 104 ALA H = 7.70 N = 121.21 CA = 54.32 HA = 4.21 C =
> 85 ALA H = 8.60 N =  CA =  HA = 4.65 C =""".splitlines()
>
>
> from pyparsing import *
>
> # define some basic data expressions
> integer = Word(nums)
> real = Combine(Word(nums) + "." + Word(nums))
>
> # use parse actions to automatically convert numeric
> # strings to actual numbers at parse time
> integer.setParseAction(lambda tokens:int(tokens[0]))
> real.setParseAction(lambda tokens:float(tokens[0]))
>
> # define expressions for 'X = 1.2' assignments; note that the
> # value might be missing, so use Optional - we'll fill in
> # a default value of 0.0 if no value is given
> keyValue = Word(alphas.upper()) + '=' + \
> Optional(real|integer, default=0.0)
>
> # define overall expression for the data on a line
> dataline = integer + "ALA" + OneOrMore(Group(keyValue))("kvdata")
>
> # attach parse action to define named values in the returned tokens
> def assignDataByKey(tokens):
> for k,_,v in tokens.kvdata:
> tokens[k] = v
> dataline.setParseAction(assignDataByKey)
>
> # for each line in the input data, parse it and print some of the data
> fields
> for d in data:
> print d
> parsedData = dataline.parseString(d)
> print parsedData.dump()
> print parsedData.CA
> print parsedData.N
> print
>
>
> Prints out:
>
> 48 ALA H = 8.33 N = 120.77 CA = 55.18 HA = 4.12 C = 181.50
> [48, 'ALA', ['H', '=', 8.3301], ['N', '=', 120.77], ['CA',
> '=',
> 55.18], ['HA', '=', 4.1201], ['C', '=', 181.5]]
> - C: 181.5
> - CA: 55.18
> - H: 8.33
> - HA: 4.12
> - N: 120.77
> - kvdata: [['H', '=', 8.3301], ['N', '=', 120.77], ['CA', '=',
> 55.18], ['HA', '=', 4.1201], ['C', '=', 181.5]]
> 55.18
> 120.77
>
> 104 ALA H = 7.70 N = 121.21 CA = 54.32 HA = 4.21 C =
> [104, 'ALA', ['H', '=', 7.7002], ['N', '=',
> 121.20],
> ['CA', '=', 54.32], ['HA', '=', 4.21], ['C', '=', 0.0]]
> - C: 0.0
> - CA: 54.32
> - H: 7.7
> - HA: 4.21
> - N: 121.21
> - kvdata: [['H', '=', 7.7002], ['N', '=', 121.20],
> ['CA', '=', 54.32], ['HA', '=', 4.21], ['C', '=', 0.0]]
> 54.32
> 121.21
>
> 85 ALA H = 8.60 N =  CA =  HA = 4.65 C =
> [85, 'ALA', ['H', '=', 8.5996], ['N', '=', 0.0], ['CA', '=',
> 0.0], ['HA', '=', 4.6504], ['C', '=', 0.0]]
> - C: 0.0
> - CA: 0.0
> - H: 8.6
> - HA: 4.65
> - N: 0.0
> - kvdata: [['H', '=', 8.5996], ['N', '=', 0.0], ['CA', '=',
> 0.0], ['HA', '=', 4.6504], ['C', '=', 0.0]]
> 0.0
> 0.0
>
>
> Learn more about pyparsing at http://pyparsing.wikispaces.com.
>
> -- Paul
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>


Amrita Kumari
Research Fellow
IISER Mohali
Chandigarh
INDIA

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] how to get blank value

2009-07-28 Thread Paul McGuire
> -Original Message-
> From: amr...@iisermohali.ac.in [mailto:amr...@iisermohali.ac.in]
> Sent: Wednesday, July 29, 2009 12:13 AM
> To: Paul McGuire
> Cc: tutor@python.org
> Subject: Re: [Tutor] how to get blank value
> 
> Thanks for help Sir but with these commands it is showing error:-
> 
> ph08...@sys53:~> python trip.py
> Traceback (most recent call last):
>   File "trip.py", line 6, in 
> from pyparsing import *
> ImportError: No module named pyparsing
> 

Wow.  You are on your own from here, you will have to do *some* work for
yourself.  This problem should definitely be within the abilities of a
"Research Fellow" to solve.

Did you even see the link I added at the bottom of my earlier post?

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] concerning help() function

2009-07-28 Thread David
Dear Tutors,

whenever I make use of the help() function, I have a good chance of
getting an error. I have not yet understood this tool very well.

Take the modules operator and random as examples. The former is
built-in, the latter not.
Do I wish to see the help files, I have to use a different syntax:

help(random)
help('operator')

I figured this by trial and error, and I am keen to find out when the
help() function is to be supplied with a string, and when no '' is
required. It certainly does not seem intuitive to me!

Many thanks,

David

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor