Re: [Tutor] How install Pyramid on a Windows 7 computer?

2012-05-31 Thread Vince Spicer
Step 1)  install Ubuntu

OK sorry couldn't resist.

This should help.
http://docs.pylonsproject.org/projects/pyramid/en/latest/narr/install.html#installing-pyramid-on-a-windows-system

Vince

On Thu, May 31, 2012 at 10:20 AM, Tamar Osher emeraldoff...@hotmail.comwrote:

  Months ago, I learned Python version 3.  I have read a few books, and
 want to learn how to use Python for the web.  Pyramid is a Python web
 framework that is ready for Python version 3, but I don't know how to
 install it on my Windows 7 computer.  Online, there are no Pyramid
 installation instructions that discuss how to install Pyramid on a Windows
 7 computer.  Can someone please help me?

 from Tamar Osher, emeraldoff...@hotmail.com


 **
 *



 *

 * http://www.emeraldvitamins.net/*


 ___
 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] Datetime Integers

2012-05-21 Thread Vince Spicer
This should do what you want.

import time
timestring = '2010-10-10 01:10:00'
time_format = '%Y-%m-%d %H:%M:%S'
timestruct = time.strptime(timestring, time_format)
print [x for x in timestruct]


For complex date parsing I would recommend checking out the dateutil.parser
http://labix.org/python-dateutil



On Mon, May 21, 2012 at 9:47 AM, Jeremy Traurig jeremy.trau...@gmail.comwrote:

 Hello,

 Is there a module available for python to convert datetime into an
 array of integers. For example, I have date where the first column is
 a datetime string (i.e. '2010-10-10 01:10:00') and I would like to
 convert that into an array with 5 columns corresponding to the integer
 values of Year,Month,Day,Hour,Minute. There is a function in Matlab
 that performs called datevec() that performs this operation. I find it
 much easier to index datetime or perform calculations on other data
 when date and time are integers. For example, i generally need to
 calculate averages, std, etc based on specific months, years, days,
 and hours. Those calculations are extremely simple when I can index an
 array of datetime integers. If there is no module to convert datetime
 to an array of integers, does anyone have an example of how i might
 index datetime using python datetime or numpy datetime64? In each
 case, I would need an array of datetime the same dimension as my data
 array.

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




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


Re: [Tutor] Python Job Scheduling package

2011-10-13 Thread Vince Spicer
You could take a peak at these. Both work without external dependencies

http://packages.python.org/APScheduler/#features
http://pypi.python.org/pypi/TGScheduler/1.6.2

VInce

On Thu, Oct 13, 2011 at 3:53 AM, harish bansal
harishbansal...@gmail.com wrote:
 Has anyone seen a python job scheduling framework that could provide the
 following features

 Add/remove job from the queue
 View job list
 check job status
 Run concurrent jobs.

 I am looking for something similar to
 coalition(http://code.google.com/p/coalition/)
 --
 Harry


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





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


Re: [Tutor] Accessing a secured webpage

2011-01-28 Thread Vince Spicer
You may want to look at httplib2

http://code.google.com/p/httplib2/

This great module makes auth very simple

Vince

On Fri, Jan 28, 2011 at 3:54 PM, Karim karim.liat...@free.fr wrote:


 Hello,

 I want to create a client to access a webpage. But when I access it
 interactively  there is a dialog box
 which ask for login and password.
 I want to access it in batch via python but I could only found a basic
 example:

 #!/bin/env python# -*- coding: utf-8 -*-
  import urllib2
 reponse = urllib2.urlopen('http://www.kernel.org/')
 xhtmldata = reponse.read()for num,ligne in enumerate(xhtmldata.splitlines()) :
 print %04d - %s%(num,ligne)

 I want to provide login and password via python code. The web adress is
 like http://website.com:8081/ddts/ddts_main.
 If you have link it is welcome!

 Regards
 Karim

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




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


Re: [Tutor] Help listing directory timestamps and deleting directories

2011-01-24 Thread Vince Spicer
On Mon, Jan 24, 2011 at 11:25 AM, bsd...@gmail.com bsd...@gmail.com wrote:

 Hi, hoping for some help here. I've been trying to write a python script
 (complete newb) and have spent several days trying to get this right with no
 success.

 I am trying to list timestamps in a directory and if they are older than x
 amount of days delete the directories. It seems that in my for loop it is
 only evaluating the last timestamp of the last directory and using that
 timestamp to make the deletion decision. I realize that this script isn't
 going to delete the directories with evaluate as true but I haven't been
 able to get that far yet...



 ###start script##
 ###Modules###

 import os
 import time

 ###Global Variables###

 curr_t = time.time()

 days = 2629743 #2629743 is 30 days in epoch time.

 directory=os.path.join(/home, userid, python)


 for r,d,f in os.walk(directory):
 for dir in d:
 timestamp = os.path.getmtime(os.path.join(r,dir)) ## It seems that
 the below if statement is only comparing the timestamp of the last
 directory that this variable lists.
 print timestamp
 if curr_t - days  timestamp:   I am expecting
 this statement to compare each timestamp of the directory variable and
 print out if it should be deleted or not.
 print Your file will be deleted

 else:
 print File will NOT be deleted...


 ###end of script#



 Thank you for your time!

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


First off, I would recommend using dates and not times, this can help make
things clearer
when dealing with dates, also the dateutil module can make date math a lot
simpler (easy_install dateutil)


from datetime import datetime
from dateutil.relativedelta import relativedelta

remove_after = datetime.now() - relativedelta(days=31)  # exactly 1 month
prior to today
check_dir = /path/to/whatever

for r,d,f in os.walk(check_dir):
for dir in d:
loc =  os.path.join(r,dir)
last_modified = datetime.fromtimestamp(os.path.getmtime(loc))
if last_modifed  remove_after:
print delete old directory, loc
else:
print keep recently modified, loc



Hope this helps,

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


Re: [Tutor] Odd result from function call

2011-01-07 Thread Vince Spicer
On Fri, Jan 7, 2011 at 11:38 AM, Ben Ganzfried ben.ganzfr...@gmail.comwrote:

 When I call one of my functions from the shell (ie compare(10, 5)) it
 produces the correct output.  However, when I run the program after calling
 the method later in the script, the result is bizarre.  I'm curious why the
 wrong result is printed.  Here is an example:

 def compare(x,y):
 if x  y:
 print (x,  is less than , y)
 print(x is , x, y is , y)
 elif x  y:
 print(x,  is greater than , y)
 else:
 print(x,  and , y,  are equal.)


 x = input(First x is: )
 y = input(First y is: )
 print(x is , x)
 print(y is , y)
 compare(x,y)
 a = input(Second x is: )
 b = input(Second y is: )
 print(x is , a)
 print(y is , b)
 compare(a,b)
 c = input(Third x is: )
 d = input(Third y is: )
 print(x is , c)
 print(y is , d)
 compare(c,d)

 Sample (and incorrect) output w/ 10, 5:

 First x is: 10
 First y is: 5
 x is  10
 y is  5
 10  is less than  5
 x is  10 y is  5
 Second x is:

 When I do simply compare(10, 5) from the shell, I get the correct output
 (ie 10 is greater than 5).  I had thought I had narrowed the problem down to
 the fact that when I run the script only the first digit is counted--
 however, it seems as if only the first digit is counted (ie anything
 starting w/ a 9 will be greater than anything starting with a 1 (even if the
 numbers are 9 and 1324234)), and THEN, the second digit is counted (such
 that 89 is correctly identified at 81).

 Anyway I'm wondering:
 1) Why does the script run correctly when I simply call the function from
 the shell but not when I try to call the function from within the script?
 2) What is actually going on such that only the first digit is being
 evaluated?  That is, the interpreter knows that x is 10 and y is 5-- and
 yet, for some reason the 5 is being tested against the 1 and since 5 is
 bigger than 1, it concludes that 5 is greater than 10.

 thanks!

 Ben

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


Ben

It would appear that you are comparing string in your script and not
integers

a=  int(input(...))

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


Re: [Tutor] if statement

2010-11-02 Thread Vince Spicer
On Tue, Nov 2, 2010 at 1:07 PM, Glen Clark gle...@gmail.com wrote:

 sorry:

 NumItems = int(input(How many Items: ))


 Entries = []
 for In in range(0,NumItems):
   Entries.append()



 for In in range(0,NumItems):
   Entries[In]=str(input(Enter name  + str(In+1) + : ))


 for In in range(0,NumItems):
   print(Entries[In])

 confirmed = int(input(Are you happy with this? (y/n): )

 if confirmed == y:
   for In in range(0,NumItems):
  print(Entries[In] + :  + str(In))
   change = int(input(Which item would you like to change: )
   Entries[change]=str(input(Please enter a nem name: )
 else:
#do nothing

 print(Entries)

 On Tue, 2010-11-02 at 15:05 -0400, Alex Hall wrote:
  On 11/2/10, Glen Clark gle...@gmail.com wrote:
File /home/glen/workspace/test.py, line 19
   if confirmed == y:
  ^
   SyntaxError: invalid syntax
  
   Why does this not work??? PyDev says Expected:else
  It may help to see the rest of the file, or at least more of the code
  surrounding this statement.
  
   ___
   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


confirmed = int(input(Are you happy with this? (y/n): )

You are missing a ) that the end of this line to close the int

-- 
Vince Spicer


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


Re: [Tutor] rights

2010-11-01 Thread Vince Spicer
On Mon, Nov 1, 2010 at 2:05 PM, Chris King g.nius...@gmail.com wrote:

  Dear Tutors,
How do you give a script right to read a folder?
 ___
 Tutor maillist  -  Tutor@python.org
 To unsubscribe or change subscription options:
 http://mail.python.org/mailman/listinfo/tutor



Which Operation System?

In linux the user that is running the script must be have read access

chmod +r folder


-- 
Vince Spicer

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


Re: [Tutor] pythonpath

2010-11-01 Thread Vince Spicer
On Mon, Nov 1, 2010 at 3:41 PM, Chris King g.nius...@gmail.com wrote:

  Dear Tutors,
When I try to import a module, how can I make it look in certain
 directories for them easily.
 Sincerely,
Chris
 ___
 Tutor maillist  -  Tutor@python.org
 To unsubscribe or change subscription options:
 http://mail.python.org/mailman/listinfo/tutor


Hello Chris

You can manage you path from within your script,

import sys
sys.path.append(/home/user/lib)

Or in bash you can edit your  $PYTHONPATH env variable
echo $PYTHONPATH


-- 
Vince Spicer


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


Re: [Tutor] pythonpath

2010-11-01 Thread Vince Spicer
On Mon, Nov 1, 2010 at 3:58 PM, Chris King g.nius...@gmail.com wrote:

  On 11/1/2010 5:57 PM, Vince Spicer wrote:



 On Mon, Nov 1, 2010 at 3:54 PM, Chris King g.nius...@gmail.com wrote:

   On 11/1/2010 5:47 PM, Vince Spicer wrote:



 On Mon, Nov 1, 2010 at 3:41 PM, Chris King g.nius...@gmail.com wrote:

  Dear Tutors,
When I try to import a module, how can I make it look in certain
 directories for them easily.
 Sincerely,
Chris
 ___
 Tutor maillist  -  Tutor@python.org
 To unsubscribe or change subscription options:
 http://mail.python.org/mailman/listinfo/tutor


  Hello Chris

 You can manage you path from within your script,

  import sys
 sys.path.append(/home/user/lib)

  Or in bash you can edit your  $PYTHONPATH env variable
  echo $PYTHONPATH


 --
 Vince Spicer


  --
 Sent from Ubuntu

So doing it in cmd windows will permanently change it?



 the first way with work for Window,  the second is for Linux or posix
 systems

  Sorry I can't help with PYTHONPATH on windows.

 --
 Vince Spicer


  --
 Sent from Ubuntu

  I want a permanent change.


There is probably a Windows alternative to env variables and PYTHONPATH,
Google may help.


-- 
Vince Spicer

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


Re: [Tutor] pythonpath

2010-11-01 Thread Vince Spicer
On Mon, Nov 1, 2010 at 4:00 PM, Vince Spicer vi...@vinces.ca wrote:



 On Mon, Nov 1, 2010 at 3:58 PM, Chris King g.nius...@gmail.com wrote:

  On 11/1/2010 5:57 PM, Vince Spicer wrote:



 On Mon, Nov 1, 2010 at 3:54 PM, Chris King g.nius...@gmail.com wrote:

   On 11/1/2010 5:47 PM, Vince Spicer wrote:



 On Mon, Nov 1, 2010 at 3:41 PM, Chris King g.nius...@gmail.com wrote:

  Dear Tutors,
When I try to import a module, how can I make it look in certain
 directories for them easily.
 Sincerely,
Chris
 ___
 Tutor maillist  -  Tutor@python.org
 To unsubscribe or change subscription options:
 http://mail.python.org/mailman/listinfo/tutor


  Hello Chris

 You can manage you path from within your script,

  import sys
 sys.path.append(/home/user/lib)

  Or in bash you can edit your  $PYTHONPATH env variable
  echo $PYTHONPATH


 --
 Vince Spicer


  --
 Sent from Ubuntu

So doing it in cmd windows will permanently change it?



 the first way with work for Window,  the second is for Linux or posix
 systems

  Sorry I can't help with PYTHONPATH on windows.

 --
 Vince Spicer


  --
 Sent from Ubuntu

  I want a permanent change.


 There is probably a Windows alternative to env variables and PYTHONPATH,
 Google may help.


 --
 Vince Spicer

 --
 Sent from Ubuntu



Sorry I don't know any developers that run Windows anymore, if you find the
solution please post it back here.

Thanks.


-- 
Vince Spicer


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


Re: [Tutor] Requesting restricted URL (further authentication requested)

2010-10-19 Thread Vince Spicer
On Tue, Oct 19, 2010 at 1:56 PM, Tim Johnson t...@johnsons-web.com wrote:

 I've written the following function which successfully gets an
 authenticated URL:
 def getRestrictedURL(authName,URL,log,pswd):
auth_handler = urllib2.HTTPBasicAuthHandler()
auth_handler.add_password(authName, URL,log,pswd)
opener = urllib2.build_opener(auth_handler)
urllib2.install_opener(opener)
return opener.open(URL).read()
 # But, alas, any links in content 'beneath' the URL
 # require additional authentication.
 Any way around this?
 Thanks
 --
 Tim
 tim at johnsons-web.com or akwebsoft.com
 http://www.akwebsoft.com
 ___
 Tutor maillist  -  Tutor@python.org
 To unsubscribe or change subscription options:
 http://mail.python.org/mailman/listinfo/tutor


Tim,

Unless you are tied to the standard library I would recommend looking at

httplib2  http://code.google.com/p/httplib2/

This handles your authentication and connection much better then the
standard urllib.

-- 
Vince Spicer

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


Re: [Tutor] Statistic-Program Problems! Please Help Quickly!

2010-10-15 Thread Vince Spicer
On Thu, Oct 14, 2010 at 10:11 PM, Colleen Glaeser
songbird42...@gmail.comwrote:

 BTW, the error message my program gives me for the B and M functions is:

 Traceback (most recent call last):
   File I:\Lab 7 wierd stat data.py, line 49, in module
 B()
   File I:\Lab 7 wierd stat data.py, line 44, in B

 ((Y() * Q()) - (P() * X())) / ((6 * Q()) - (X()**2))
 TypeError: unsupported operand type(s) for *: 'NoneType' and 'NoneType'

 On Thu, Oct 14, 2010 at 11:09 PM, Colleen Glaeser songbird42...@gmail.com
  wrote:

 Dear tutors,

 I am in a beginning-level computer science class in college and am running
 into problems with an assignment.

 The assignment is as follows:

 Statisticians are fond of drawing regression lines.  In statistics and
 other fields where people analyze lots of data, one of the most commonly
 used regression lines is called the “least squares line.” This is the line
 that is supposed to best fit the set of data points, in the sense that it
 minimizes the squared vertical distances between the points and the line.
 Why this should be a good fit is beyond the scope of this assignment.

 Presume that you have a collection of n two-dimensional data points.  I’ll
 give it as a list of lists, where each of the lists inside represents one
 data point.

 Data :[ [x1, y1], [x2, y2], [x3, y3], …, [xn, yn]]

 Compute the following

   The regression line is then given by

 where m and b may be obtained by

 and

 Your task is to compute the m and b (slope and intercept, respectively)
 for a set of data.  You have to analyze the data as given, not count or
 add anything yourself.  Your program should do everything, even figure
 out how many data points there are.

 Here’s your data:

 First set:  [ [3, 1], [4, 3], [6, 4], [7, 6], [8, 8], [9, 8] ]

 Second set:  [ [63, 11], [22, 7.5], [63, 11], [28, 10], [151, 12], [108,
 10], [18, 8], [115, 10], [31,7], [44, 9] ]

 Find m and b, then calculate an estimate for x = 5 using the first data
 set.  That is, plug in 5 for x and see what y you get.  For the second
 set, try x = 95.

 Turn in:  code, m, b, and the estimates for both data sets.




 ***

 There’s an easy way to walk through the data and extract the values you
 need.  Use a for loop.  Try this:

 for item in data:

 [x, y] = item

 print(x)


 ~~

 For extra credit:  draw a scatter plot of the data, and draw in the least
 squares line.  Scale the window to fit, making it a bit wider and higher
 than the data requires, so that some of the points are near but not on the
 edges of the window.  Then sketch in the regression line.  Note that you
 should calculate the window size based on the data – don’t set them
 yourself; find the max and min values for x and y.  You can print the
 scatter plot, or point me toward your web page.  In any case, show me the
 code.



 So far, my program is as follows:

 Data = [[3,1],[4,3],[6, 4],[7, 6],[8, 8],[9, 8]]

 def X():
 accX = 0
 for item in Data:
 [x,y] = item

 accX = accX + x
 print (accX)


 def Y():
 accY = 0
 for item in Data:
 [x,y] = item

 accY = accY + y
 print (accY)

 def P():
 accXY = 0
 for item in Data:
 [x,y] = item

 accXY = accXY + (y*x)
 print (accXY)

 def Q():
 accX2 = 0
 for item in Data:
 [x,y] = item

 accX2 = accX2 + (x**2)
 print (accX2)

 X()
 Y()
 P()
 Q()



 def B():
 ((Y() * Q()) - (P() * X())) / ((6 * Q()) - (X()**2))

 def M():
 ((Y() * Q()) - (P() * X())) / (X() * Q())

 B()
 M()

 Now, my functions for X, Y, P, and Q are correct, but I have a couple of
 problems when it comes to continuing.  First of all, despite what my teacher
 has told me, my method for trying to multiply X,Y,P, and Q's results in the
 functions for B and M are not working.  I'm not sure if there is a way to
 make functions into variables or how to solve this problem.

 Second, I am confused as to what my teacher means to do when it comes to
 inputting different values of x.

 Find m and b, then calculate an estimate for x = 5 using the first data
 set.  That is, plug in 5 for x and see what y you get.  For the second
 set, try x = 95.

 Turn in:  code, m, b, and the estimates for both data sets.


 I mean, I know I need to calculate the line of best fit for the data sets
 using B and M, but what in the world is x supposed to do and where does it
 go?  How do I program this?  This is especially harder since I've never
 taken a proper stat class before.

 Thank you all so much!

 --
 Colleen Glaeser
 songbird42...@gmail.com
 636.357.8519




 --
 Colleen Glaeser
 songbird42...@gmail.com
 636.357.8519

 ___
 Tutor maillist  -  Tutor@python.org
 To unsubscribe 

Re: [Tutor] Getting/setting attributes

2010-09-21 Thread Vince Spicer
On Tue, Sep 21, 2010 at 4:16 PM, bob gailer bgai...@gmail.com wrote:

  On 9/21/2010 5:06 PM, lists wrote:

 Hi tutors,

 I'm trying to each myself programming and come from a background in
 system administration with some experience in scripting (so I'm very
 new to it).

 Currently I'm grappling with the concept of object orientating
 programming and have a question about setting  getting attributes.

 As I understand it, it makes most sense to set/get the attribute of an
 object using a method rather than doing it directly.


 My opinion - unless there is some verification or translation or action
 required it is better (easier, clearer) to just access and assign the
 attribute directly.


  I've been reading various ways of doing this, and the information seems a
 little
 contradictory.

  Example, please?

  I've muddled my way through the code below to try and force setting or
 getting the 'address' attribute through the address method rather than
 allowing direct access.

 Just because you have a getter and setter does not prohibit direct
 reference to _address.

 Does this make sense to you?


 class Computer(object):

def __init__(self):
instantiate the class with default values
self.address = 

  I suggest (if you want to go the setter/getter route that you initialize
 _address, just in case someone tries to reference it without setting it.


 @property # use the property.getter decorator on this method
def address(self):
return self._address

@address.setter #use the property.setter decorator on this method
def address(self, addrvalue):
self._address = addrvalue

 computer1 = Computer()
 computer1.address = test
 print computer1.address


 --
 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



Hello Bob,

Here is a working example of what I think you are trying to achieve. In this
example the address is set via the setter
and some simple validation is there and the private var isn't available as
__address but get rewritten to _Computer__address (so not private but not
obvious)


class Computer(object):
def __init__(self):
self.__address = None
# see note on private vars in Python
http://docs.python.org/tutorial/classes.html?highlight=private#private-variables

   @property
def address(self):
return self.__address

@address.setter
def address(self, value):
if value not in (available, criteria):
raise AttributeError(Nope)
self.__address = value


Hope that helps,

Vince Spicer


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


Re: [Tutor] Overloading methods

2010-09-16 Thread Vince Spicer
On Thu, Sep 16, 2010 at 6:02 AM, Michael Powe mich...@trollope.org wrote:

 Hello,

 Strictly speaking, this isn't overloading a method in the way we do it
 in Java.  But similar.  Maybe.

 I am writing a module for processing web server log files and one of
 the methods I provide is to extract a given query parameter and its
 value. Because there are several types of log files with different
 line structures, I had the thought to write methods with descriptive
 names that simply returned a generic method that processed the method
 arguments. e.g.,

 def setpattern_iis(self,pattern,parameter) :
type='iis'
return pattern_generator(self,type,pattern,parameter)

 In this case, creating a regular expression to parse the log lines for
 a query parameter.

 This is just a bit more self documenting than using the generic
 method with the 'type' argument and requiring the user to enter the
 type.  At the same time, it allows me to put all the parsing code in
 one method.

 My question is, is this a bad thing to do in python?

 Thanks.

 mp

 --
 Michael Powemich...@trollope.orgNaugatuck CT USA
 War is a sociological safety valve that cleverly diverts popular
 hatred for the ruling classes into a happy occasion to mutilate or
 kill foreign enemies. - Ernest Becker

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


Well I can't comment on right or wrong I would think creating a simple class
with a __call__ method is a
little more pythonic.

Example:

class PatternGenerator(object):
Run a regex.
def __init__(self, type_):
self.type = type_
def __call__(self, pattern, parameter):
return pattern_generator(self, self.type, pattern, parameter)

# Initialize class
setpattern_iis = PatternGenerator('iis')

# call the method here
setpattern_iis(pattern, params)

Hope that helps,

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


Re: [Tutor] Comparing two lists

2010-09-16 Thread Vince Spicer
On Thu, Sep 16, 2010 at 12:27 PM, Michael Powe mich...@trollope.org wrote:

 Hello,

 I have two lists.

 alist = ['label', 'guid']

 blist = ['column0label', 'column1label', 'dimension0guid',
 'description', 'columnid']

 I want to iterate over blist and extract the items that match my
 substrings in alist; alternatively, throw out the items that aren't in
 alist (but, I've had bad experiences removing items from lists in
 place, so I tend toward the copy motif.)

 In real life, blist column entries could have embedded column numbers
 from 0 to 19.

 I can do this with excrutiatingly painful 'for' loops.  Looking for
 something more efficient and elegant.

 Thanks.

 mp

 --
 Michael Powemich...@trollope.orgNaugatuck CT USA

 The secret to strong security: less reliance on secrets.
 -- Whitfield Diffie

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


Michel,

One solution is to use list comprehensions.

newlist = [x for x in blist if [a for a in alist if a in x]]

This works, although there may be more efficient ways to accomplish this

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


Re: [Tutor] Comparing two lists

2010-09-16 Thread Vince Spicer
On Thu, Sep 16, 2010 at 12:49 PM, Vince Spicer vi...@vinces.ca wrote:



 On Thu, Sep 16, 2010 at 12:27 PM, Michael Powe mich...@trollope.orgwrote:

 Hello,

 I have two lists.

 alist = ['label', 'guid']

 blist = ['column0label', 'column1label', 'dimension0guid',
 'description', 'columnid']

 I want to iterate over blist and extract the items that match my
 substrings in alist; alternatively, throw out the items that aren't in
 alist (but, I've had bad experiences removing items from lists in
 place, so I tend toward the copy motif.)

 In real life, blist column entries could have embedded column numbers
 from 0 to 19.

 I can do this with excrutiatingly painful 'for' loops.  Looking for
 something more efficient and elegant.

 Thanks.

 mp

 --
 Michael Powemich...@trollope.orgNaugatuck CT USA

 The secret to strong security: less reliance on secrets.
 -- Whitfield Diffie

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


 Michel,

 One solution is to use list comprehensions.

 newlist = [x for x in blist if [a for a in alist if a in x]]

 This works, although there may be more efficient ways to accomplish this

 Vince


On major speed up is to make a simple filter that returns as soon as a match
is found instead of
completing the loop every element in alist

def filter_(x, against):
for a in against:
if a in x:
return True
return False

newlist = [x for x in blist if filter_(x, alist)]

:)

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


Re: [Tutor] If/elif/else when a list is empty

2010-09-13 Thread Vince Spicer
On Mon, Sep 13, 2010 at 9:58 PM, aenea...@priest.com wrote:

  Hi,

 I'm parsing IMDB movie reviews (each movie is in its own text file). In my
 script, I'm trying to extract genre information. Movies have up to three
 categories of genres--but not all have a genre tag and that fact is making
 my script abort whenever it encounters a movie text file that doesn't have a
 genre tag.

 I thought the following should solve it, but it doesn't. The basic question
 is how I say if genre information doesn't at all, just make
 rg1=rg2=rg3=NA?

 rgenre = re.split(r';', rf.info[genre]) # When movies have genre
 information they store it as genreDrama;Western;Thriller/genre

 if len(rgenre)0:
   if len(rgenre)2:
   rg1=rgenre[0]
   rg2=rgenre[1]
   rg3=rgenre[2]
   elif len(rgenre)==2:
   rg1=rgenre[0]
   rg2=rgenre[1]
   rg3=NA
   elif len(rgenre)==1:
   rg1=rgenre[0]
   rg2=NA
   rg3=NA
else len(rgenre)1: # I was hoping this would take care of the there is
 no genre information scenario but it doesn't
rg1=rg2=rg3=NA

 This probably does a weird nesting thing, but even simpler version I have
 tried don't work.

 Thanks very much for any help!

 Tyler



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


Hey Tyler you can simplify this with a onliner.

rg1, rg2, rg3 = rgenre + [NA]*(3-len(rgenre[:3]))

Hope that helps, if you have any questions feel free to ask.

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


Re: [Tutor] If/elif/else when a list is empty

2010-09-13 Thread Vince Spicer
Tyler,

This is a simple error the KeyError is caused because the key isn't in the
dictionary
http://docs.python.org/library/exceptions.html#exceptions.KeyError and easy
fix you can either check for the key prior to using or use the get method

1) rgenre = re.split(r';', rf.info[genre]) if genre in rf.info else []
the regex will never get executed here and an empty list will be returned if
genre not present

2) rgenre = re.split(r';', rf.info.get(genre, ''))
the get will not throw this error and return '' if ''genre' is not found in
the dictionary

Hope that helps,

Vince
http://docs.python.org/library/exceptions.html#exceptions.KeyError

On Mon, Sep 13, 2010 at 10:46 PM, aenea...@priest.com wrote:

 Hi Vince,

 Thanks very much for the one-line version--unfortunately, I still get
 errors. The overall script runs over every text file in a directory, but as
 soon as it hits a text file without a genre tag, it gives this error:

 Traceback (most recent call last):
   File
 C:\Users\tylersc\Desktop\Tyler2\Tyler\words_per_review_IMDB_9-13-10.py,
 line 168, in module
 main(.,output.csv)
   File
 C:\Users\tylersc\Desktop\Tyler2\Tyler\words_per_review_IMDB_9-13-10.py,
 line 166, in main
 os.path.walk(top_level_dir, reviewDirectory, writer )
   File C:\Python26\lib\ntpath.py, line 259, in walk
 func(arg, top, names)
   File
 C:\Users\tylersc\Desktop\Tyler2\Tyler\words_per_review_IMDB_9-13-10.py,
 line 162, in reviewDirectory
 reviewFile( dirname+'/'+fileName, args )
   File
 C:\Users\tylersc\Desktop\Tyler2\Tyler\words_per_review_IMDB_9-13-10.py,
 line 74, in reviewFile

 rgenre = re.split(r';', rf.info[genre])
 KeyError: 'genre'
  I'm about to give what may be too much information--I really thought
 there must be a way to say don't choke if you don't find any rgenres
 because rf.info[genre] was empty. But maybe I need to define the None
 condition earlier?

 Basically a text file has this structure:
 info
 titleHigh Noon/title
 genreDrama;Western/genre # But this tag doesn't exist for all text
 files
 # etc
 /info
 review
 authoru493498/author
 rating9 out of 10/rating
 summaryA great flick/summary
 textblah blah blah/text
 # etc
 /review
 # next review--all about the movie featured in the info tags




 -Original Message-
 From: Vince Spicer vi...@vinces.ca
 To: aenea...@priest.com
 Cc: tutor@python.org
 Sent: Mon, Sep 13, 2010 9:08 pm
 Subject: Re: [Tutor] If/elif/else when a list is empty



 On Mon, Sep 13, 2010 at 9:58 PM, aenea...@priest.com wrote:

 Hi,

 I'm parsing IMDB movie reviews (each movie is in its own text file). In my
 script, I'm trying to extract genre information. Movies have up to three
 categories of genres--but not all have a genre tag and that fact is making
 my script abort whenever it encounters a movie text file that doesn't have a
 genre tag.

 I thought the following should solve it, but it doesn't. The basic
 question is how I say if genre information doesn't at all, just make
 rg1=rg2=rg3=NA?

 rgenre = re.split(r';', rf.info[genre]) # When movies have genre
 information they store it as genreDrama;Western;Thriller/genre

 if len(rgenre)0:
   if len(rgenre)2:
   rg1=rgenre[0]
   rg2=rgenre[1]
   rg3=rgenre[2]
   elif len(rgenre)==2:
   rg1=rgenre[0]
   rg2=rgenre[1]
   rg3=NA
   elif len(rgenre)==1:
   rg1=rgenre[0]
   rg2=NA
   rg3=NA
else len(rgenre)1: # I was hoping this would take care of the there
 is no genre information scenario but it doesn't
rg1=rg2=rg3=NA

 This probably does a weird nesting thing, but even simpler version I have
 tried don't work.

 Thanks very much for any help!

 Tyler



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


 Hey Tyler you can simplify this with a onliner.

  rg1, rg2, rg3 = rgenre + [NA]*(3-len(rgenre[:3]))

  Hope that helps, if you have any questions feel free to ask.

  Vince

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


Re: [Tutor] Append sub-key to dictionary

2010-05-25 Thread vince spicer
On Tue, May 25, 2010 at 12:28 PM, M. Bashir Al-Noimi mbno...@gmx.comwrote:

  Hi All,

 I'm trying to append a new sub-key to specific dictionary but it replacing
 the content of parent key instead of add a sub-key!


 How I can fix this issue?

 --snippet--

 addressbook = {
'work': {
  'Andre': {
   'phone': '22761654',
   'e-mail': '5456646',
   'address': 'Syria, Aleppo',
   'website': 'www.sdff.com'
   }
 },
 'Friends': {
 'Ahmad': {
  'phone': '34646464',
  'picture': '/home/fiends/wael.png',
  'posts': {
'blog': 'http://www.dsfd.com/',
'newspaper': 'http://news.com/'
}
  },
 'Issa': {
  'e-mail': 'a...@dsfdsc.com'
  }
 }
}

 addressbook['Friends'] = {
'kassem': {
'address':'Aleppo Street',
'Country':'Palestine',
'articles':{

 'blog':'http://blogger.com',
'news':'http://news.com/'
}
}
}


  --
 Best Regards
 Muhammad Bashir Al-Noimi
 My Blog: http://mbnoimi.net


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



You may have better results with:

addressbook['Friends']['kassem] = {
   'address':'Aleppo Street',
   'Country':'Palestine',
   'articles':{
   'blog':'
http://blogger.com',
   'news':'http://news.com/'
   }
   }
   }


this will create a new key in the Friends dict

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


Re: [Tutor] test

2010-02-25 Thread vince spicer
On Thu, Feb 25, 2010 at 4:03 PM, Kirk Bailey kbai...@howlermonkey.netwrote:

 test
 --


 Cheers!
  -Kirk D Bailey

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



Hello World!  usually a good test
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] html and python

2010-02-10 Thread vince spicer
On Wed, Feb 10, 2010 at 1:30 PM, Grigor Kolev grigor.ko...@gmail.comwrote:

 Hi.
 I want to make a list of E-mail, photos and some additional data.
 But I want this list to be displayed in one site.
 How can I send data from a list of site page. Which module should I use
 --
 Grigor Kolev grigor.ko...@gmail.com

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


do you have any code currently?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] html and python

2010-02-10 Thread vince spicer
On Wed, Feb 10, 2010 at 1:30 PM, Grigor Kolev grigor.ko...@gmail.comwrote:

 Hi.
 I want to make a list of E-mail, photos and some additional data.
 But I want this list to be displayed in one site.
 How can I send data from a list of site page. Which module should I use
 --
 Grigor Kolev grigor.ko...@gmail.com

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



Your best bet is show us some code .. then we can help.

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


Re: [Tutor] Compile py to exe in ubuntu

2010-02-10 Thread vince spicer
On Wed, Feb 10, 2010 at 1:40 PM, Harya Dananjaya dananz...@gmail.comwrote:

 Can I compile my python source to exe in ubuntu?
 if I can do it, which compiler can do it?

 Thanks you,

 Harya Dananjaya

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


1. Ubuntu and linux in general don't use exe per say
2. Python can be compiled but not usually in the way you are thinking
3. you might check out http://pypi.python.org/pypi/bbfreeze/
Vince
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] help with strings

2010-02-03 Thread vince spicer
On Wed, Feb 3, 2010 at 7:19 AM, NISA BALAKRISHNAN 
snisa.balakrish...@gmail.com wrote:

 hi

 I am very new to python.
 I have a string for example : 123B new Project
 i want to separate 123B as a single string and new  project as another
 string .
 how can i do that.
 i tried using partition but couldnt do it

 pls help.
 thanks in advance!


Can we see some example code you are trying?

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


Re: [Tutor] how to sort a tab delim file

2010-01-13 Thread vince spicer
On Wed, Jan 13, 2010 at 9:21 AM, Hs Hs ilhs...@yahoo.com wrote:

 Hi:

 I have a tab-delim file:

 col1 col2 col3
 andrew1987   1990
 jake 1974   1980
 jim   1964   1970
 lance1984   1992


 how can I sort column 2 and get :
 jim   1964   1970
 jake 1974   1980
 lance1984   1992
 andrew1987   1990


 I know how to sort a items in one list. but I cannot get how this can be
 done on a file.

 any suggestions. thanks!
 Hs




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



Sounds like a school project to me
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] how to sort a tab delim file

2010-01-13 Thread vince spicer
On Wed, Jan 13, 2010 at 9:21 AM, Hs Hs ilhs...@yahoo.com wrote:

 Hi:

 I have a tab-delim file:

 col1 col2 col3
 andrew1987   1990
 jake 1974   1980
 jim   1964   1970
 lance1984   1992


 how can I sort column 2 and get :
 jim   1964   1970
 jake 1974   1980
 lance1984   1992
 andrew1987   1990


 I know how to sort a items in one list. but I cannot get how this can be
 done on a file.

 any suggestions. thanks!
 Hs




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


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


Re: [Tutor] Unexpected Result in Test Sequence

2009-11-16 Thread vince spicer
On Mon, Nov 16, 2009 at 1:18 PM, kb1...@aim.com wrote:

 Hello Tutor list.
 I'm running a test to find what the experimental average of a d20 is, and
 came across a strange bug in my code.
 import random
 list1 = []
 def p():
   d = 0
   for number in range(1,1000):
   t = random.randrange(1,19)
   list1.append(t)
   for value in list1:
   d+=value
   print d/1000
   d = 0
 for value in range(1,100):
   p()

 It works, but I have a logic error somewhere. It runs, and the results have
 a pattern :
 9
 19
 28
 37
 47
 56
 66
 75
 85
 94
 104
 113
 ...
 ...
 It just adds 10, and every second result, subtracts 1, till it gets to 0,
 and then starts again with 9 in singles, and whatever in the 10's, etc.
 What is causing this?
 ___
 Tutor maillist  -  Tutor@python.org
 To unsubscribe or change subscription options:
 http://mail.python.org/mailman/listinfo/tutor



I think that one problem you are seeing is caused by the use of integers
When you are dividing sum of the random number by 1000, python is rounding
your output.

Also your list, never gets cleared and you keep adding to the original list,
and you are then dividing by the original 1000


A simple fix is to use floats (PS: cleaned up a bit):

from random import randrange
def p():
mylist = [randrange(1,19) for x in range(1, 1000)]
d = sum(list)
print float(d) / len(mylist)

for value in range(1,100):
p()


Hope this point you in a better direction

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


Re: [Tutor] Retrieving information from a plain text file (WinXP/py2.6.2/Beginner)

2009-11-02 Thread vince spicer
On Sun, Nov 1, 2009 at 5:37 PM, Katt the_only_kat...@verizon.net wrote:

 Hello all,

 Thank you all for your help.  I appreciate it alot.

 I have been trying to work with file IO alot recently and would like to
 improve my little program so that I no longer use a hard coded list, but a
 text file that I can edit easily.

 The text file is three lines long and looks exactly like this:

 Reminder1,2009_10_28
 Reminder2,2009_11_01
 Reminder3,2009_11_15

 My program consists of the following code:
 
 #]--[import modules]--[
 from time import strftime, mktime, localtime
 from WConio import textcolor
 #][
 #]--[define functions]--[
 def read_reminders():
   print \nReading text file into program: reminders.txt
   text_file = open(reminders.txt,r)
   reminders = [line.strip().split(') for line in text_file]
   text_file.close()
   print reminders
 #
 def get_computer_date():
   #Get today's date from the computer
   todays_date = strftime(%Y_%m_%d)
   return todays_date
 #
 def color_print(strings):
   #Change the text color in the WinXP dos shell
   #The way to use:
   #color_print([(string,color number),\
   #(str(variable),color number),(etc)])
   for string in strings:
   textcolor(string[1])
   print string[0],
 #
 def change_to_julian(reminder_date):
   #Receives the year, month, and day
   #in the form of a single string (2009_10_15)
   #and changes it into three different int
   #variables.  Then take those three variables
   #and append six zeros and change into a
   #julian date.
   date = []
   date = reminder_date.split(_)
   year = int(date[0])
   month = int(date[1])
   day = int(date[2])
   timetuple = (year, month, day) + ( (0,) * 6 )
   unixtime = mktime(timetuple)
   timetuple = localtime(unixtime)
   print days_left(timetuple[7])
   # [7] is the number of julian-date field of
   #the unixtime tuple.
   return days_left(timetuple[7])
 #
 def days_left(julian_date):
   #This function calculates the days left
   #until a reminder.  If the days left are
   #greater than 0 it will print normally.
   #If it is -1 then it will print differently.
   #Also if it is greater than -1 it will print
   #yet again differently.
   days_until_reminder = julian_date - localtime().tm_yday
   if days_until_reminder  0:
   color_print ([(There are,7),(str(days_until_reminder),4),(days
 left until this reminder.,7),(\n,7)])
   elif days_until_reminder == -1:
   color_print ([(\tYou have missed this reminder
 by,4),(str(days_until_reminder*-1),4),(day!,4),(\n,7)])
   color_print [(
  
 ,4),(\n,7)])
   else:
   color_print ([(\tYou have missed this reminder
 by,4),(str(days_until_reminder*-1),4),(days!,4),(\n,7)])
   color_print [(
  
 ,4),(\n,7)])
 print
 #
 def compare_reminders(todays_date):
   #This function compares the reminders
   #to the computer date.
   #It has three different paths:
   # 1.Matches today's date
   # 2.The reminder date has already
   #  passed by
   # 3.The reminder date is yet to
   #  come.
   #After determining which it is it will
   #access the change_to_julian and
   #days_left functions.
   #reminders.sort()
   color_print ([(
 [-],4),(\n,7)])
   index = 0
   while index  len(reminders):
   if todays_date == reminders[index][1]:
   print
   color_print [(
  
 ,4),(\n,7)])
   print Today's reminder is:
 ,reminders[index][0],on,reminders[index][1]
   color_print ([(\t\tTake care of this reminder
 immediately,2),(\n,7)])
   elif todays_date  reminders[index][1]:
   print
   print Whoops, you missed the following
 reminder.,reminders[index][0],on,reminders[index][1]
   change_to_julian(reminders[index][1])
   else:
   print
   print Your upcoming reminders are:
 ,reminders[index][0],on,reminders[index][1]
   change_to_julian(reminders[index][1])
   index = index + 1
   color_print ([(
 [-],4),(\n,7)])
 #][
 #]---[Main Program]---[
 read_reminders()
 print reminders
 compare_reminders(get_computer_date())
 pause_it = raw_input(Press a key to end: )
 #][
 
 Could someone explain to me why my read_reminders function retrieves the
 information, but cannot process that information?

 When I try and run the program I get the following error message:
 
 Reading text file into program: reminders.txt
 

Re: [Tutor] replacing a long list of if,elif

2009-10-23 Thread vince spicer
On Fri, Oct 23, 2009 at 9:05 AM, John jfabi...@yolo.com wrote:

 I'm using python 2.5

 I have a long list of if, elif, else.  I always thought it was very NOT
 pythonic.  It's easy to read but not pretty.

 for fldType in fieldList:
  if int in fldType:
  fld = I
  elif char in fldType :
  fld = C
  elif bool in fldType :
 fld = B .
  else:
 fld = '?'


 I have considered:

  mydict = {'int': 'I', 'char':'C', 'bool':'B'}
  for fldType in fieldList:
try:
fld = mydict[fldType]
except:
fld = '?'

 I also considered some sort of  lambda function as

 x = lambda fld: mydict[fldType]

 But could not determine how to account for the key exception. So I tried

 x = lambda fldType: mydict[fldType]
 if fldType in mydict:
   x(fldType)
 else:
fld = '?'


 Any suggestions would be helpful  and would help me learn.

 Johnf




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


John,

Using a Dictionary is the best method to use here and you can use dict.get
in order to bypass the KeyError

EX:

myDict.get(fldType, None)

this will output the value from myDict if the key exists, if not it will
return None


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


Re: [Tutor] i can't for the life of me get #! /usr/bin/env python or #!/usr/bin/python to work

2009-10-21 Thread vince spicer
On Wed, Oct 21, 2009 at 12:21 PM, Jason Willis chaoticslac...@gmail.comwrote:

 hi everyone,

 sorry for the rather boring question but i'm having serious issues getting
 my programs to run from the command line without having to type python
 in-front of them. I've tried a lot of different variations on the
 #!/usr/bin/ etc. line and have come up with the following every time:

 *[r...@localhost moonshinerat]# mycode.py
 bash: mycode.py: command not found
 [r...@localhost moonshinerat]# mycode
 bash: mycode: command not found
 [r...@localhost moonshinerat]#

 I've chmod'ed the program and everything but i still get command not found
 from the shell. The only thing that does work is ./mycode.py but from what i
 understand that's been built into linux itself to work that way...

 please someone let me know what i'm doing wrong here and possibly help??

 thanks!

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


try:

./mycode.py

since i'm guess your current path isn't in the system path

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


Re: [Tutor] i can't for the life of me get #! /usr/bin/env python or #!/usr/bin/python to work

2009-10-21 Thread vince spicer
On Wed, Oct 21, 2009 at 12:31 PM, vince spicer vinces1...@gmail.com wrote:



 On Wed, Oct 21, 2009 at 12:21 PM, Jason Willis 
 chaoticslac...@gmail.comwrote:

 hi everyone,

 sorry for the rather boring question but i'm having serious issues getting
 my programs to run from the command line without having to type python
 in-front of them. I've tried a lot of different variations on the
 #!/usr/bin/ etc. line and have come up with the following every time:

 *[r...@localhost moonshinerat]# mycode.py
 bash: mycode.py: command not found
 [r...@localhost moonshinerat]# mycode
 bash: mycode: command not found
 [r...@localhost moonshinerat]#

 I've chmod'ed the program and everything but i still get command not found
 from the shell. The only thing that does work is ./mycode.py but from what i
 understand that's been built into linux itself to work that way...

 please someone let me know what i'm doing wrong here and possibly help??

 thanks!

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


 try:

 ./mycode.py

 since i'm guess your current path isn't in the system path

 Vince


Sorry didn't read full post,

you would have add your program directory to the system path in order to
call the program by name

you can add this to you bashrc

export PATH=~/my/program/dir:${PATH}


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


Re: [Tutor] i can't for the life of me get #! /usr/bin/env python or #!/usr/bin/python to work

2009-10-21 Thread vince spicer
On Wed, Oct 21, 2009 at 12:33 PM, vince spicer vinces1...@gmail.com wrote:



 On Wed, Oct 21, 2009 at 12:31 PM, vince spicer vinces1...@gmail.comwrote:



 On Wed, Oct 21, 2009 at 12:21 PM, Jason Willis 
 chaoticslac...@gmail.comwrote:

 hi everyone,

 sorry for the rather boring question but i'm having serious issues
 getting my programs to run from the command line without having to type
 python in-front of them. I've tried a lot of different variations on the
 #!/usr/bin/ etc. line and have come up with the following every time:

 *[r...@localhost moonshinerat]# mycode.py
 bash: mycode.py: command not found
 [r...@localhost moonshinerat]# mycode
 bash: mycode: command not found
 [r...@localhost moonshinerat]#

 I've chmod'ed the program and everything but i still get command not
 found from the shell. The only thing that does work is ./mycode.py but from
 what i understand that's been built into linux itself to work that way...

 please someone let me know what i'm doing wrong here and possibly help??

 thanks!

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


 try:

 ./mycode.py

 since i'm guess your current path isn't in the system path

 Vince


 Sorry didn't read full post,

 you would have add your program directory to the system path in order to
 call the program by name

 you can add this to you bashrc

 export PATH=~/my/program/dir:${PATH}


 Vince


A better description of linux PATH:

http://www.linuxheadquarters.com/howto/basic/path.shtml
http://www.linfo.org/path_env_var.html

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


Re: [Tutor] i can't for the life of me get #! /usr/bin/env python or #!/usr/bin/python to work

2009-10-21 Thread vince spicer
On Wed, Oct 21, 2009 at 3:56 PM, Jason Willis chaoticslac...@gmail.comwrote:

 so i changed the .bashrc and added at the end :
 PATH=/home/compy/pythons:$PATH  ###which is the actual path to my python
 proggies###

 and i still get
 co...@compy-laptop:~/pythons$ herosinventory.py
 herosinventory.py: command not found
 co...@compy-laptop:~/pythons$ herosinventory.py
 herosinventory.py: command not found
 co...@compy-laptop:~/pythons$ herosinventory
 herosinventory: command not found
 co...@compy-laptop:~/pythons$


 I must be retarded. I'm sorry , what am I doing wrong here?


 On Wed, Oct 21, 2009 at 2:31 PM, vince spicer vinces1...@gmail.comwrote:



 On Wed, Oct 21, 2009 at 12:21 PM, Jason Willis 
 chaoticslac...@gmail.comwrote:

 hi everyone,

 sorry for the rather boring question but i'm having serious issues
 getting my programs to run from the command line without having to type
 python in-front of them. I've tried a lot of different variations on the
 #!/usr/bin/ etc. line and have come up with the following every time:

 *[r...@localhost moonshinerat]# mycode.py
 bash: mycode.py: command not found
 [r...@localhost moonshinerat]# mycode
 bash: mycode: command not found
 [r...@localhost moonshinerat]#

 I've chmod'ed the program and everything but i still get command not
 found from the shell. The only thing that does work is ./mycode.py but from
 what i understand that's been built into linux itself to work that way...

 please someone let me know what i'm doing wrong here and possibly help??

 thanks!

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


 try:

 ./mycode.py

 since i'm guess your current path isn't in the system path

 Vince



you need export:

export PATH=/home/compy/pythons:$PATH


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


Re: [Tutor] Pexpect maxread searchwindowsize, timeout

2009-10-20 Thread vince spicer
On Tue, Oct 20, 2009 at 11:11 AM, Nathan Farrar nathan.far...@gmail.comwrote:

 I haven't been able to find any real examples of pexpect usage, nor
 documentation.  Just little bits here and there, so I'm kind of
 struggling through.

 I've got the follow bit of code I'm working with:

 def main():
try:
print 'attempting to spawn connection ... '
session = pexpect.spawn('ssh usern...@x.x.x.x')
except:
print 'couldn\'t spawn connection ... '

print 'waiting for password prompt ... '
session.expect('password:')
print 'received password prompt ... '

try:
print 'attempting to send password ... '
session.sendline(password)
except:
print 'error sending password ... '

print 'waiting for command prompt ... '
session.expect(command_prompt)
print 'received command prompt ... '

try:
print 'attempting to issue \'show version\' command ... '
session.sendline([expect.TIMEOUT=1, 'show version'])
except:
print 'error issuing \'show version\' command ... '

print 'waiting for command prompt ... '
session.expect(command_prompt)
print 'received command prompt ... '

print 'attempting to print command results ... '
print session.before

print 'closing session ... '
session.close()

 if __name__=='__main__':
main()

 When I run this against a cisco device, it times out waiting for the
 command prompt after issuing the show version command.  However, if I
 change 'show version' to something like 'blah blah' it doesn't time
 out, and I get the results of the command (an error message that is
 much shorter in length).

 I believe that the results of the show version command are simply too
 large.  I think I may need to increase the size of maxread 
 searchwindowsize  set the timeout to something lower than the
 default, but I haven't been able to figure out how to do this
 correctly yet.

 Any help would be greatly appreciated.  I'm pulling my hair out.  Thank
 you.

 --
 The presence of those seeking the truth is infinitely to be preferred
 to the presence of those who think they've found it.

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


Looks like you are trying to end multiple commands to the sendline and not
expect
you can specify the timeout on the expect line

try this code:

#

def main():
   try:
   print 'attempting to spawn connection ... '
   session = pexpect.spawn('ssh usern...@x.x.x.x')
   except:
   print 'couldn\'t spawn connection ... '

   print 'waiting for password prompt ... '
   session.expect('password:')
   print 'received password prompt ... '

   try:
   print 'attempting to send password ... '
   session.sendline(password)
   except:
   print 'error sending password ... '

   print 'waiting for command prompt ... '
   session.expect(command_prompt)
   print 'received command prompt ... '

   try:
   print 'attempting to issue \'show version\' command ... '
   session.sendline('show version') #: send only command
   except:
   print 'error issuing \'show version\' command ... '

   print 'waiting for command prompt ... '
   session.expect(command_prompt, timeout=1) #: set the timeout here
   print 'received command prompt ... '

   print 'attempting to print command results ... '
   print session.before

   print 'closing session ... '
   session.close()

if __name__=='__main__':
   main()

#==

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


Re: [Tutor] if clause in list comprehensions.

2009-10-19 Thread vince spicer
On Mon, Oct 19, 2009 at 1:58 PM, Emile van Sebille em...@fenx.com wrote:

 On 10/19/2009 12:20 PM Alan Gauld said...


 Sander Sweers sander.swe...@gmail.com wrote

  mylist = ['John', 'Canada', 25, 32, 'right']
 a = [item.upper() for item in mylist if type(item) == type('good')]


 Usually it is recommended to use hasattr() instead of type()
   hasattr(s, 'upper')


 Nope, they do  completely different things
 I think you might be thinking of isinstance() which can be used instead of
 type(). I see you use hasattr as a means of testing for a method but that is
 still different from testing type - the method names might be the same but
 the functions be completely different in effect!

  returned this: ['JOHN', 'CANADA', 'RIGHT']
 I was expecting this: ['JOHN', 'CANADA', 25, 32, 'RIGHT']
 So, actually the if acted like a filter.


 It is intended to be used as a filter.

  In order to use a list comprehension I created this function instead.
 def upperfy(item)
   try:
   item = item.upper()
   except AttributeError:
   pass
   return item


  I would move return item under the except and remove the pass, other
 might disagree on this.


 I would :-)
 Doing that would result in None being returned for each successful
 conversion. The OPs code is correct (even if unnecessary)

  a = [upperfy(item) for item in mylist]


 a = [item.upper() if type(item) == str else item for item in mylist]

 should do it I think.


 or even

  a = [ str(item).upper() for item in mylist ]

 Emile



 HTH,



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



Lambda can save the day to keep everything on one line, and leave variable
type the same:

mylist = ['John', 'Canada', 25, 32, 'right']
new_list = [(lambda y: y.upper() if hasattr(y, 'upper') else y)(a) for a in
x]

  ['JACK', 'CANADA', 25, 32, 'RIGHT']

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


Re: [Tutor] if clause in list comprehensions.

2009-10-19 Thread vince spicer
On Mon, Oct 19, 2009 at 2:14 PM, vince spicer vinces1...@gmail.com wrote:



 On Mon, Oct 19, 2009 at 1:58 PM, Emile van Sebille em...@fenx.com wrote:

 On 10/19/2009 12:20 PM Alan Gauld said...


 Sander Sweers sander.swe...@gmail.com wrote

  mylist = ['John', 'Canada', 25, 32, 'right']
 a = [item.upper() for item in mylist if type(item) == type('good')]


 Usually it is recommended to use hasattr() instead of type()
   hasattr(s, 'upper')


 Nope, they do  completely different things
 I think you might be thinking of isinstance() which can be used instead
 of type(). I see you use hasattr as a means of testing for a method but that
 is still different from testing type - the method names might be the same
 but the functions be completely different in effect!

  returned this: ['JOHN', 'CANADA', 'RIGHT']
 I was expecting this: ['JOHN', 'CANADA', 25, 32, 'RIGHT']
 So, actually the if acted like a filter.


 It is intended to be used as a filter.

  In order to use a list comprehension I created this function instead.
 def upperfy(item)
   try:
   item = item.upper()
   except AttributeError:
   pass
   return item


  I would move return item under the except and remove the pass, other
 might disagree on this.


 I would :-)
 Doing that would result in None being returned for each successful
 conversion. The OPs code is correct (even if unnecessary)

  a = [upperfy(item) for item in mylist]


 a = [item.upper() if type(item) == str else item for item in mylist]

 should do it I think.


 or even

  a = [ str(item).upper() for item in mylist ]

 Emile



 HTH,



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



 Lambda can save the day to keep everything on one line, and leave variable
 type the same:

 mylist = ['John', 'Canada', 25, 32, 'right']
 new_list = [(lambda y: y.upper() if hasattr(y, 'upper') else y)(a) for a in
 mylist ]

   ['JACK', 'CANADA', 25, 32, 'RIGHT']

 Vince


wrong var name x, fixed
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Testing for empty list

2009-10-18 Thread vince spicer
On Sun, Oct 18, 2009 at 7:29 PM, Wayne sri...@gmail.com wrote:

 Hi, I think I recall seeing this here, but I wanted to make sure I'm
 correct.
 Is the best way to test for an empty list just test for the truth value?
 I.e.

 mylist = [1,2,3]

 while mylist:
print mylist.pop()

 Thanks,
 Wayne

 --
 To be considered stupid and to be told so is more painful than being called
 gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness,
 every vice, has found its defenders, its rhetoric, its ennoblement and
 exaltation, but stupidity hasn’t. - Primo Levi

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


I believe it is better to check the list length, I think some changes are
coming on evaling list


mylist = [1,2,3]

while len(mylist)  0:
   print mylist.pop()






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


Re: [Tutor] Help with pexpect

2009-10-16 Thread vince spicer
On Fri, Oct 16, 2009 at 1:45 PM, Nathan Farrar nathan.far...@gmail.comwrote:

 I'm trying to automate the collection of data to remote devices over
 ssh via pexpect.  I had originally attempted (with limited success) to
 use paramiko, however due to cisco's ssh implimentation I cannot send
 mulitple commands over the same connection, which is absolutely
 essential.  Therefore, I'm now attempting to use pexpect, but am
 having trouble getting started.  I have a simple script, such as:

 session = pexpect.spawn('ssh u...@host')
 session.expect([pexpect.TIMETOUT, 'password:'])
 session.send('password')
 print session.read() # shouldn't this display the logon banner  command
 prompt?
 session.close()

 This code results in no output  a hanging window. What am I doing
 incorrect?

 Additionally, I will need to add conditional pexpect statements, such
 that when I execute a command I want to gather the output, however if
 '--More--' is encountered (and it this can happen multiple times), I
 want to send a newline character to the session and continue gathering
 the output.

 Thanks for the help!
 Nathan

 --
 The presence of those seeking the truth is infinitely to be preferred
 to the presence of those who think they've found it.

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


when using pexpect for ssh you can run into some issues, I have used to
script some elaborate green screen apps, but not without some unforeseen
bugs

when connecting to a new machine, most ssh client will ask you verify the
fingerprint

something like:

 are you sure you want to continue (yes/no)?

also session.send  doesn't send eol \n but sendline does

So this should fix your connection

###
session = pexpect.spawn('ssh u...@host')
i = session.expect([pexpect.TIMETOUT, 'password:', yes/no])
if i == 2:
session.sendline(yes)
session.expect([pexpect.TIMETOUT, 'password:'])
if i == 1:
session.sendline('password')
print session.read() # shouldn't this display the logon banner  command
prompt?
session.close()
###

the other your question,  pexpects sendline(''), will just send a newline

not perfect but should work
###
license = 
while True:
i = session.expect([--more--, yes/no])
if i == 1:
   break
license += session.before
session.sendline('')
###


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


Re: [Tutor] Package for verify validity of any kind of IP

2009-10-08 Thread vince spicer
On Thu, Oct 8, 2009 at 2:38 AM, Ansuman Dash ansuman.d...@gmail.com wrote:

 Hi,

 Can anybody suggest me a package to verify validity of any kind of IP, i.e.
 IPv4 or IPv6.

 Thanks,
 AD

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


I have used googles ipaddr package and have found it to work quite well

http://code.google.com/p/ipaddr-py/

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


Re: [Tutor] how to run php scripts in pylons framework?

2009-10-02 Thread vince spicer
On Fri, Oct 2, 2009 at 1:24 AM, ggi ggi gop...@gmail.com wrote:


 Dear All,

  I have some php scripts which I don't want to rewrite in python. How can I
 run php Scripts in python?

 Thanks in advance
 Googi G

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



Although rewriting is a better option, you can use the subprocess module to
make system calls to the php interpreter


import subprocess

#simple caller, disguard output

subprocess.call(php /path/to/my/old/script.php)

# if you want output

proc = subprocess.Popen(php /path/to/my/script.php, shell=True,
stdout=subprocess.PIPE)

script_response = proc.stdout.read()



Hope that helps,

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


Re: [Tutor] help with alternate execution

2009-09-29 Thread vince spicer
On Tue, Sep 29, 2009 at 10:59 AM, wrobl...@cmich.edu wrote:

 I'm trying to make a very simple example to show alternate execution... if
 a
 number is divisible by 3 it will say so and if it isnt, it will say so.
 Heres my
 program

 n= raw_input(enter a number= )
 def divisible(n):
if n%3 == 0:
print n, is divisible by 3
else:
print n, is not divisible by 3
 print divisible

 when I try it out, and enter 3, I get this--

 enter a number= 3
 function divisible at 0x02CC06B0
 

 I'm not sure why I am getting this and am not quite sure what this means...
 could someone explain what I am doing wrong here and why it is telling me
 this?
 ___
 Tutor maillist  -  Tutor@python.org
 To unsubscribe or change subscription options:
 http://mail.python.org/mailman/listinfo/tutor


You need the call the function with the user input

n = raw_input(enter a number= )
def divisible(n):
   if n%3 == 0:
   print n, is divisible by 3
   else:
   print n, is not divisible by 3
print divisible(n)


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


Re: [Tutor] Help required

2009-09-25 Thread vince spicer
On Fri, Sep 25, 2009 at 1:56 PM, waqas ahmad waqas...@hotmail.com wrote:



  Hi,

 I dont know it is the right place to post this question. I need help to
 change one search code line . can you help me please.

 here is my search method code:

 search=re.compile(^#acl InternationalGroup.*\n, re.M).search(pagetext)
 if search:
 ret=search.group()
 else:
 ret='not defined'
 return ret

 here i am searching for #acl InternationalGroup in the pageText and when
 it true is then give me search group.


 I want to change this for following requirement:

 I want to search  for #acl InternationalGroup and  CatInternational for
 both in the pageText.
 when #acl InternationalGroup is not there but only CatInternational is
 there. then return me search group.

 I shall be thankful to you for any help.

 Best Regards,
 Waqas



 --
 What can you do with the new Windows Live? Find 
 outhttp://www.microsoft.com/windows/windowslive/default.aspx

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


i think this is what you are looking for:



search=re.compile((#acl\sInternationalGroup|CatInternational).*\n,
re.M).search(pagetext)
if search:
ret=search.findall()
else:
ret='not defined'
return ret
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Image manipluation (On-the-fly thumbnail creation)

2009-09-15 Thread vince spicer
On Tue, Sep 15, 2009 at 10:03 AM, dan06 dan.king...@yahoo.com wrote:


 I've recently delved into python, about a week or so ago; I'm trying to
 figure out how to create on-the-fly thumbnails. Are there python standard
 library modules I could/should use or should I use external libraries like:
 GD, Gimp, or ImageMagick?
 --
 View this message in context:
 http://www.nabble.com/Image-manipluation-%28On-the-fly-thumbnail-creation%29-tp25456792p25456792.html
 Sent from the Python - tutor mailing list archive at Nabble.com.

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



check out:

http://www.pythonware.com/products/pil/


creating thumbnail example here

http://www.pythonware.com/library/pil/handbook/image.htm


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


Re: [Tutor] Getting list of attributes from list of objects

2009-09-10 Thread vince spicer
On Thu, Sep 10, 2009 at 8:51 AM, Oleg Oltar oltarase...@gmail.com wrote:

 Hi!

 I have the following list

 l= [ a, b, c]

 Where a,b,c are objects created from one class, e.g. each has title
 attribute.
 What I want to have is a list of titles, e.g. [a.title, b.title, c.title]

 Is there a quick way to do it? Or I should use loops (looping through each
 element, and generating list)

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


you can use list comprehension, which is a type of loop, but looks so pretty
:)

titles = [x.title for x in l]

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


Re: [Tutor] Boolean operations

2009-09-02 Thread vince spicer
On Wed, Sep 2, 2009 at 4:30 AM, Anthony Casey amca...@xtra.co.nz wrote:

 Hello, tutors.

 I'm someone who used to programme as a hobby and who is trying to get back
 into it via Python. I'm reading Programming in Python 3 by Summerfield
 (excellent book).

 I read something unusual about Boolean operations in Python:

  five = 5
  two = 2
  zero = 0
  five and two
 2

 I understand what it's doing here: returning the operand. But what is the
 practical application of that? How might I use that function?
 (Short-sighted
 imagination, I realise.)

 (I know how binary Booleans work etc., so this is a bit of a change of
 outlook.)

 Please pardon me if this is a silly or inane question.

 Regards,
 Anthony

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



this might make the and operator a little clearer

http://pyref.infogami.com/and

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


Re: [Tutor] I always get this message as a reply

2009-09-02 Thread vince spicer
On Wed, Sep 2, 2009 at 7:55 AM, Kristina Ambert krissy.amb...@gmail.comwrote:

 Hi,

 I just wanted to ask if everyone else gets this message as a first reply
 everytime you send out a message to tutor.
 It feels like I'm getting spam or something.
 Geneviève DIAGORN to me
 show details 3:59 PM (17 hours ago)

 Bonjour,
 Je suis absente jusqu'au 02/09 inclus.
 En cas d'urgence Soprane, contacter notre adresse générique
 projet.sopr...@teamlog.com.
 Cordialement.

 Geneviève




 --
 Krissy
 ---
 Testing the waters is always fun...

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



Someone on the list has gone on vacation and has an auto responder to tell
clients that they are away.

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


Re: [Tutor] packing a list of lists

2009-08-28 Thread vince spicer
On Fri, Aug 28, 2009 at 8:05 AM, kevin parks k...@me.com wrote:

 Back to python after a long long layoff. So i am running into some
 beginner's confusion...

 I am trying to plot a list of numbers in gnuplot.py. To do that I am trying
 to pack the list with an index by iterating over the list so i can get
 something like:

 foo = [12, 11, 9, 6, 2, 9, 3, 8, 12, 3, 5, 6]

 [ [1, 12], [2, 11], [3, 9], [4, 6], [5, 2], [6, 9], [7, 3], [8, 8] ... ]

 So that i have x, y pairs to plot. When i print in my func i get the right
 thing, for each item (note scaffolding) yet when i reurn the whole list i
 just get the last pair repeated over and over.

 I am not sure why this is.


 def pack(in_seq):
out_list=[]
x = 1
ll=[1, 1]
for each in in_seq:
ll[0] = x
ll[1] = each
out_list.append(ll)
#print ll
x = x + 1
print out_list


 # function declarations would go here
 def test():
test function - say what this does here and skip a line

Keyword arguments:
none


print
foo = minus(200)
plot_me = pack(foo)
#print foo
print
print plot_me


 if __name__ == __main__:
test()


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



Although I didn't test your code, I think what you are trying to accomplish
can be done using enumerate cleaner


def pack(foo):
out = []
for x,y in enumerate(foo, 1):
out.append((x,y))
return out
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] packing a list of lists

2009-08-28 Thread vince spicer
On Fri, Aug 28, 2009 at 9:18 AM, vince spicer vinces1...@gmail.com wrote:



 On Fri, Aug 28, 2009 at 8:05 AM, kevin parks k...@me.com wrote:

 Back to python after a long long layoff. So i am running into some
 beginner's confusion...

 I am trying to plot a list of numbers in gnuplot.py. To do that I am
 trying to pack the list with an index by iterating over the list so i can
 get something like:

 foo = [12, 11, 9, 6, 2, 9, 3, 8, 12, 3, 5, 6]

 [ [1, 12], [2, 11], [3, 9], [4, 6], [5, 2], [6, 9], [7, 3], [8, 8] ... ]

 So that i have x, y pairs to plot. When i print in my func i get the right
 thing, for each item (note scaffolding) yet when i reurn the whole list i
 just get the last pair repeated over and over.

 I am not sure why this is.


 def pack(in_seq):
out_list=[]
x = 1
ll=[1, 1]
for each in in_seq:
ll[0] = x
ll[1] = each
out_list.append(ll)
#print ll
x = x + 1
print out_list


 # function declarations would go here
 def test():
test function - say what this does here and skip a line

Keyword arguments:
none


print
foo = minus(200)
plot_me = pack(foo)
#print foo
print
print plot_me


 if __name__ == __main__:
test()


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



 Although I didn't test your code, I think what you are trying to accomplish
 can be done using enumerate cleaner


 def pack(foo):
 out = []
 for x,y in enumerate(foo, 1):
 out.append((x,y))
 return out




Or even cleaner with list comprehension

def pack(foo):
return [x for x in enumerate(foo, 1)]
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] packing a list of lists

2009-08-28 Thread vince spicer
On Fri, Aug 28, 2009 at 10:49 AM, kevin parks k...@me.com wrote:


 Thanks for the replies. Though the list comprehension does not work:

 TypeError: enumerate() takes exactly 1 argument (2 given)


 On Aug 29, 2009, at 12:20 AM, vince spicer wrote:



   #print foohough I didn't test your code, I think what you are trying
 to accomplish can be done using enumerate cleaner


 def pack(foo):
out = []
for x,y in enumerate(foo, 1):
out.append((x,y))
return out




 Or even cleaner with list comprehension

 def pack(foo):
return [x for x in enumerate(foo, 1)]



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


What version of python are using, python 2.6+ have a start parameter

http://docs.python.org/library/functions.html#enumerate
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Looking up a value in a dictionary from user input problem

2009-08-06 Thread vince spicer
On Thu, Aug 6, 2009 at 3:18 PM, chase pettet chase...@gmail.com wrote:

 I am trying to write a script to work our LVS implementation.  I want to be
 able to have  user do something like this ./script SITE SERVER and have
 the script look up the ip value of the site on that server and issue the
 command to pull the status from LVS.  I am almost there but for some reason
 when I try to pass the site parameter dynamically (the name of the
 dictionary) I keep getting errors about value type.  I have two example that
 work where the dictionary name is hard coded to to speak in the script, and
 the value I want to pull is dynamic using sys.argv[1], and one where I'm
 trying to pass the dictionary name and it does not work.  I tried to slim
 thse examples down, so hopefully they are helpful:

 works #1...

 ./script.py t

 #!/usr/bin/env python
 site = {l:10.1.1.1, t:10.1.1.2, x:10.1.1.3, s1:10.1.1.4,
 s2:10.1.1.5, s3:10.1.1.6}

 def runBash(cmd):
   p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
   out = p.stdout.read().strip()
   return out

 class LVS_Site:
   def show(self, site):
 showsite = ipvsadm -L -t %s:443 % (site)
 showsiteresult = runBash(showsite)
 return showsiteresult

 a = LVS_Site()
 b = site[%s % (sys.argv[1])]
 c = a.show(b)
 print 
 print 
 print 
 print c

 works #2...

 ./script.py t

 #!/usr/bin/env python
 site = {l:10.1.1.1, t:10.1.1.2, x:10.1.1.3, s1:10.1.1.4,
 s2:10.1.1.5, s3:10.1.1.6}

 def runBash(cmd):
   p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
   out = p.stdout.read().strip()
   return out

 class LVS_Site:
   def show(self, site):
 showsite = ipvsadm -L -t %s:443 % (site)
 showsiteresult = runBash(showsite)
 return showsiteresult

 a = LVS_Site()
 z = site
 b = z[%s % (sys.argv[1])]
 c = a.show(b)
 print 
 print 
 print 
 print c


 Not working...

 ./script.py t site

 #!/usr/bin/env python
 site = {l:10.1.1.1, t:10.1.1.2, x:10.1.1.3, s1:10.1.1.4,
 s2:10.1.1.5, s3:10.1.1.6}

 def runBash(cmd):
   p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
   out = p.stdout.read().strip()
   return out

 class LVS_Site:
   def show(self, site):
 showsite = ipvsadm -L -t %s:443 % (site)
 showsiteresult = runBash(showsite)
 return showsiteresult

 a = LVS_Site()
 z = sys.argv[2]
 b = b[%s % (sys.argv[1])]
 c = a.show(b)
 print 
 print 
 print 
 print c

 Error:

 Traceback (most recent call last):
   File ./python2.py, line 22, in ?
 b = z[%s % (sys.argv[1])]
 TypeError: string indices must be integers


 I don't understand why the third one does not work. Thanks for any help!

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


In your code

z = sys.argv[2] which is a string

think you want

b = site[z]
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Looking up a value in a dictionary from user input problem

2009-08-06 Thread vince spicer
On Thu, Aug 6, 2009 at 3:42 PM, vince spicer vinces1...@gmail.com wrote:



 On Thu, Aug 6, 2009 at 3:18 PM, chase pettet chase...@gmail.com wrote:

 I am trying to write a script to work our LVS implementation.  I want to
 be able to have  user do something like this ./script SITE SERVER and have
 the script look up the ip value of the site on that server and issue the
 command to pull the status from LVS.  I am almost there but for some reason
 when I try to pass the site parameter dynamically (the name of the
 dictionary) I keep getting errors about value type.  I have two example that
 work where the dictionary name is hard coded to to speak in the script, and
 the value I want to pull is dynamic using sys.argv[1], and one where I'm
 trying to pass the dictionary name and it does not work.  I tried to slim
 thse examples down, so hopefully they are helpful:

 works #1...

 ./script.py t

 #!/usr/bin/env python
 site = {l:10.1.1.1, t:10.1.1.2, x:10.1.1.3, s1:10.1.1.4,
 s2:10.1.1.5, s3:10.1.1.6}

 def runBash(cmd):
   p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
   out = p.stdout.read().strip()
   return out

 class LVS_Site:
   def show(self, site):
 showsite = ipvsadm -L -t %s:443 % (site)
 showsiteresult = runBash(showsite)
 return showsiteresult

 a = LVS_Site()
 b = site[%s % (sys.argv[1])]
 c = a.show(b)
 print 
 print 
 print 
 print c

 works #2...

 ./script.py t

 #!/usr/bin/env python
 site = {l:10.1.1.1, t:10.1.1.2, x:10.1.1.3, s1:10.1.1.4,
 s2:10.1.1.5, s3:10.1.1.6}

 def runBash(cmd):
   p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
   out = p.stdout.read().strip()
   return out

 class LVS_Site:
   def show(self, site):
 showsite = ipvsadm -L -t %s:443 % (site)
 showsiteresult = runBash(showsite)
 return showsiteresult

 a = LVS_Site()
 z = site
 b = z[%s % (sys.argv[1])]
 c = a.show(b)
 print 
 print 
 print 
 print c


 Not working...

 ./script.py t site

 #!/usr/bin/env python
 site = {l:10.1.1.1, t:10.1.1.2, x:10.1.1.3, s1:10.1.1.4,
 s2:10.1.1.5, s3:10.1.1.6}

 def runBash(cmd):
   p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
   out = p.stdout.read().strip()
   return out

 class LVS_Site:
   def show(self, site):
 showsite = ipvsadm -L -t %s:443 % (site)
 showsiteresult = runBash(showsite)
 return showsiteresult

 a = LVS_Site()
 z = sys.argv[2]
 b = b[%s % (sys.argv[1])]
 c = a.show(b)
 print 
 print 
 print 
 print c

 Error:

 Traceback (most recent call last):
   File ./python2.py, line 22, in ?
 b = z[%s % (sys.argv[1])]
 TypeError: string indices must be integers


 I don't understand why the third one does not work. Thanks for any help!

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


 In your code

 z = sys.argv[2] which is a string

 think you want

 b = site[z]


or even better

b =  site.get(z, None)
if b is None:
print Not Found
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Assigning each line of text to a separate variable

2009-07-30 Thread vince spicer
On Thu, Jul 30, 2009 at 1:19 PM, Marv Boyes marvbo...@gmail.com wrote:

 Hello, all. This is probably embarrassingly basic, but I haven't been able
 to find something that works.

 I'm working on a script that needs to manipulate a list (not 'list' in the
 Python sense) of URLs returned in a server response. Right now, I'm
 stripping the XML tags from that response and assigning the resulting list
 of URLs to a variable so I can print it in the terminal. So when I do, say,
 'print urls' I get something like this:

http://server.com/thing1
http://server.com/thing2
http://server.com/thing3

 And so on. What I would _like_ to do is assign each line of that list to a
 separate variable, so that I can format my output to be more explicit;
 something like this:

Link to Thing1: http://server.com/thing1
Link to Thing2: http://server.com/thing2

 And so on. I know this should be extremely easy, but I appear to be having
 some manner of mental block. Any and all guidance would be greatly
 appreciated; many thanks in advance.
 ___
 Tutor maillist  -  Tutor@python.org
 http://mail.python.org/mailman/listinfo/tutor


Hello,

you could use a dictionary to assign a key value and a descrption, but
without seeing some data this is very rough

data = {}
for line in response:
key, value = response.split(,)  # line is myname, http://blah.com;
data[key] = value

#then later
for key, value in data.items():
print Link To %s : %s % key, value
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Web crawling!

2009-07-29 Thread vince spicer
On Wed, Jul 29, 2009 at 9:59 AM, Raj Medhekar cosmicsan...@yahoo.comwrote:

 Does anyone know a good webcrawler that could be used in tandem with the
 Beautiful soup parser to parse out specific elements from news sites like
 BBC and CNN? Thanks!
 -Raj


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



I have used httplib2 http://code.google.com/p/httplib2/ to crawl sites(with
auth/cookies) and lxml (html xpath) to parse out links.

but you could use builtin urllib2 to request pages if no auth/cookie support
is required, here is a simple example

import urllib2
from lxml import html

page = urllib2.urlopen(http://this.page.com http://this.page/)
data = html.fromstring(page.read())

all_links = data.xpath(//a) # all links on the page

for link in all_links:
print link.attrib[href]
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Issues with regex escaping on \{

2009-07-29 Thread vince spicer
On Wed, Jul 29, 2009 at 11:35 AM, gpo goodpotat...@yahoo.com wrote:


 My regex is being run in both Python v2.6 and v3.1
 For this example, I'll give one line.  This lines will be read out of log
 files.  I'm trying to get the GUID for the User ID to query a database with
 it, so I'd like a sub match.  Here is the code
 -
 import re
 line = 'Checking Privilege for UserId:
 {88F96ED2-D471-DE11-95B6-0050569E7C88}, PrivilegeId:
 {71AD2527-8494-4654-968D-FE61E9A6A9DF}. Returned hr = 0'
 pUserID=re.compile('UserID: \{(.+)\}',re.I)  #Sub match is one or more
 characters between the first set of squigglies immediately following
 'UserID: '

 #the output is:
 (re.search(pUserID,line)).group(1)
 '88F96ED2-D471-DE11-95B6-0050569E7C88}, PrivilegeId:
 {71AD2527-8494-4654-968D-FE61E9A6A9DF'
 ---
 Why isn't the match terminating after it finds the first \}  ?
 --
 View this message in context:
 http://www.nabble.com/Issues-with-regex-escaping-on-%5C%7B-tp24724060p24724060.html
 Sent from the Python - tutor mailing list archive at Nabble.com.

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




your grouping (.+) appears to be greedy, you can make it non-greedy with a
question mark

EX:

pUserID=re.compile('UserID:\s+{(.+?)}',re.I)

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


Re: [Tutor] traversing page and then following the link

2009-07-24 Thread vince spicer
there are many ways to parse html pages and retrieve data, I tend to use
lxml and xpath to simplify things and urllib to pull down the data

lxml is not a core library but can be installed via easy_install, the main
benefit is the xpath support

=
import urllib2
from lxml import html as HTML

useragent = Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.1)
Gecko/20090716 Ubuntu/9.04 (jaunty) Shiretoko/3.5.1

opener = urllib2.build_opener()

main_page = urllib2.Request(
http://en.wikipedia.org/wiki/Gallery_of_sovereign-state_flags;)
main_page.headers[User-Agent] = useragent #: wikipedia will return a 403
otherwise

html = HTML.fromstring(opener.open(main_page).read())

images = html.xpath(//a...@class='image']/img) #: parse all image tags

for img in images:
url = img.attrib[src].split(/)
url.pop(url.index(thumb)) #: remove reference to thumb folder

local = open(url[-2], wb) #: open local file

url = /.join(url[:-1]) #: cleanup the .png reference

print Downloading %s % url

imgreq = urllib2.Request(url)
imgreq.headers[User-Agent] = useragent

local.write(opener.open(imgreq).read()) #: read the remote svg file into
local file
local.close()



On Fri, Jul 24, 2009 at 8:48 AM, davidwil...@safe-mail.net wrote:

 Hello,
 I would like to download all the flags from the
 http://en.wikipedia.org/wiki/Gallery_of_sovereign-state_flags so that I
 can create a flags sprite from this.

 The flags seem to follow some order in that all the svg files are in the
 following pattern:

 http://en.wikipedia.org/wiki/File:Flag_of_*.svg and then on this page
 there is the link of the file.

 I have looked at using Twill to follow each link and record the actual url,
 but can somone point me at a simpler solution.

 Dave
 ___
 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] Help with multiple substitution

2009-07-24 Thread vince spicer
not perfect or tested but

import re

chopset.reverse() #: put the longer extensions first

exts = |.join([re.escape(x) fro x in chopset)])

for line in file:
print exts.sub(, line)



On Fri, Jul 24, 2009 at 9:22 AM, vankayala sailakshman 
sailakshm...@hotmail.com wrote:


 Hi All,

 Help needed to write a python script!!!

 Iam a python newbie and my problem is doing multiple substitution in a text
 file using Python regular expressions. Here is my following data, I need to
 chop of all the extensions that are given in the following list and replace
 with empty string in their position. I have tried to solve for the past two
 days but couldn't succeed. Any help would be appreciated. Thanks in advance.

 Sai


  for example, for “abc22035.pr.1” i need to get “abc22035”


  chopset = ['.p', '.pr', '.prp', '.prpp', '.ps', '.psp', '.pspp', '.s',
 '.p.1','.pr.1', '.prp.1', '.prpp.1', '.ps.1', '.psp.1','.pspp.1', '.s.1']


  abc22035.pr

 abc22035.pr.1 abc21409 .ps.1

 abc21409.pr.1 abc21154

 abc21154.pr.1 abc07584_EAOEA

 abc07584_EAOEA.ps.1 abc20991.pr

 abc20991.ps. abc21156

 abc21156.ps.1 abc21409

 abc21409.ps. abc21156

 abc21156.pr.1 abc21408

 abc21408.ps.1 abc21370.psp

 abc21370.pr.1 abc21370

 abc21370.ps.1 abc22036

 abc22036.pr.1 abc21154

 abc21154.ps.1 abc22036.prpp

 abc22036.ps.1 abc20991

 abc20991.pr.1 abc21772

 abc21772.pr.1 abc21408

 abc21408.pr.1 abc07584_EAOEA

 abc07584_EAOEA.pr.1 abc21065



 --
 Videos Get the latest video streams on movies, Try 
 it!http://video.msn.com/?mkt=en-in

 ___
 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] Reading text until a certain point

2009-07-24 Thread vince spicer
you can build a dictionary and keep the active key, again this would only
work in predictable data

users = {}
name = None

for line in file:
key, value = [x.strip() for x in line.split(:)]
if key == name:
name = data[1]
users[name] = {}
 else:
 users[name][data[0]]

 users
{stefan: {
  id:12345
  color:blue
})

Vince

On Fri, Jul 24, 2009 at 9:39 AM, Stefan Lesicnik ste...@lsd.co.za wrote:

 Hi Guys,

 It seems like this keeps coming up (for me anyways), and i'm never sure how
 to do it. I'm very new to programming...

 I have a file that has text in a certain format. Lets assume

 '''
 name: stefan
 id: 12345
 color: blue
 name: joe
 id: 54321
 color: red
 '''

 The format is predictable.  I understand for non predictable text, you
 would have to use pyparser or the like to build a match.

 For predictable format, I am never sure how to handle this. I normally use
 something like

 for line in file:
 line.split('\n')

 The problem being i dont really do something per line?  I would like to say
 something like, for line until the next 'name', make that 1 element.
 So i would like to then have a list or dict (this probably makes sense for
 a dict) with that group. I would then probably split it into various
 elements.

 So essentially im asking, how do i say the for line until next 'match'.
 Would this be something for the re module? Or is there an inbuilt core way?

 I hope this makes sense

 Thanks!

 Stefan


 ___
 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] dictionaries help

2009-07-23 Thread vince spicer
this should work


def find_value(value, lst):
for obj in lst:
if value in obj.values():
return obj

 find_value(aaa, my_lst)

Vince

On Thu, Jul 23, 2009 at 9:55 AM, davidwil...@safe-mail.net wrote:

 hello,
 please excuse me, but i would like to understand how dictionaris work.

 for example:
  my_lst = [{'code': 'aaa', 'name': 'a name'}, {'code': 'bbb', 'name': 'b
 name'}]
  my_code = 'aaa'


 from the above i would like to compare my_code and return the dictionary
 which has code == my_code

 dave
 ___
 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] decorators, __call__ (able) objects

2009-07-16 Thread Vince Spicer


no the __call__ function can is like any function

def __call__(self, passedin):

or simply 

def __call__(self)


*args and **kws explained   http://www.saltycrane.com/blog/2008/01/how-to-
use-args-and-kwargs-in-python/

On Thursday 16 July 2009 12:09:52 am Todd Matsumoto wrote:
 Thanks guys,

 In the example the __call__ method has *args and **kws as arguments. Is
 that required?

 Also when, in what situation would you use callable objects?

 Cheers,

 T
  Original-Nachricht 

  Datum: Wed, 15 Jul 2009 12:02:05 -0700
  Von: wesley chun wes...@gmail.com
  An: vince spicer vinces1...@gmail.com, tmatsum...@gmx.net
  CC: Kent Johnson ken...@tds.net, tutor@python.org
  Betreff: Re: [Tutor] decorators, __call__ (able) objects
 
Can some one give, or point to some good examples of how
@decorators work, and __call__ (able) objects?
  
   simple example of calling a class
  
   class myKlass(object):
  
   def __call__(self, *args, **kws):
print i was called
  
test = myKlass()
test()
  
   i was called
 
  close. the example was right, but the description wasn't accurate...
  you meant, calling an instance. i'm going to plagarize and rip this
  right out of section 14.1.4 from Core Python Programming:
 
  Python provides the __call__() special method for classes, which allows
  a programmer to create objects (instances) that are callable. By default,
  the
  __call__() method is not implemented, meaning that most instances are
  not callable. However, if this method is overridden in a class
  definition,
  instances of such a class are made callable. Calling such instance
  objects is
  equivalent to invoking the __call__() method. Naturally, any arguments
  given in the instance call are passed as arguments to __call__().
 
  as far as decorators go, kent's tutorial is great place to start. here
  are 2 more articles plus PEP 318, where they were defined:
 
  http://www.ibm.com/developerworks/linux/library/l-cpdecor.html
  http://www.artima.com/weblogs/viewpost.jsp?thread=240808
  http://www.python.org/dev/peps/pep-0318
 
  in addition, i devoted section 11.3.6 of Core Python to decorators.
 
  finally, it should be mentioned that starting in 2.6, you can now
  decorate *classes*, as seen here in PEP 3129:
 
  http://www.python.org/dev/peps/pep-3129/
 
  hope this helps!
  -- wesley
  - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  Core Python Programming, Prentice Hall, (c)2007,2001
  Python Fundamentals, Prentice Hall, (c)2009
  http://corepython.com
 
  wesley.j.chun :: wescpy-at-gmail.com
  python training and technical consulting
  cyberweb.consulting : silicon valley, ca
  http://cyberwebconsulting.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to pass command line variables to this python code...

2009-07-15 Thread vince spicer
good catch, my mistake

args[1] == 'yankees'
True


On Wed, Jul 15, 2009 at 12:25 AM, Christian Witts cwi...@compuscan.co.zawrote:

 vince spicer wrote:

 First off, selenium is a great tool and the python driver is very powerful

 there are numerous ways to access cli variables,

 the quickest

 import sys
 print sys.srgv

 sys.argv will it output a array of all command line args

 ./selenium-google-test.py yankees
 will out put:

 ['selenium-google-test.py', 'yankees']

 so

 args = sys.argv

 args[0] == 'yankees'
 True

 That would be false, the first argument (list index zero) is the script
 name.  You would need to do
 args = sys.argv[1:]
 if you want to dump the filename from the list.

 --
 Kind Regards,
 Christian Witts



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


Re: [Tutor] decorators, __call__ (able) objects

2009-07-15 Thread vince spicer
simple example of calling a class


class myKlass(object):



On Wed, Jul 15, 2009 at 6:33 AM, Kent Johnson ken...@tds.net wrote:

 On Wed, Jul 15, 2009 at 7:41 AM, Todd Matsumototmatsum...@gmx.net wrote:
  Hi,
 
  Can some one give, or point to some good examples of how @decorators
 work, and __call__ (able) objects?

 Decorators:
 http://personalpages.tds.net/~kent37/kk/1.htmlhttp://personalpages.tds.net/%7Ekent37/kk/1.html

 Kent
 ___
 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] decorators, __call__ (able) objects

2009-07-15 Thread vince spicer
simple example of calling a class

class myKlass(object):

def __call__(self, *args, **kws):
 print i was called


 test = myKlass()

 test()

 i was called





 On Wed, Jul 15, 2009 at 6:33 AM, Kent Johnson ken...@tds.net wrote:

 On Wed, Jul 15, 2009 at 7:41 AM, Todd Matsumototmatsum...@gmx.net
 wrote:
  Hi,
 
  Can some one give, or point to some good examples of how @decorators
 work, and __call__ (able) objects?

 Decorators:
 http://personalpages.tds.net/~kent37/kk/1.htmlhttp://personalpages.tds.net/%7Ekent37/kk/1.html

 Kent
 ___
 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] just one question

2009-07-15 Thread vince spicer
one way is:

import re

infile = open(test.txt, r) #: open read mode
outfile = open(out.tx, w) #: open write mode

for line in infile:
values = re.split(\s+, line) # split values on spaces EX: ['47', '8',
'ALA', 'H', 'H', '7.85', '0.02', '1']
outfile.write(%s  %s C =  %s  CA =  %s CB = %s % (values[1],
values[2], values[5], values[6], values[7]))

infile.close()
outfile.close()

not tested but should work

Vince

On Wed, Jul 15, 2009 at 6:24 AM, amr...@iisermohali.ac.in wrote:

 Hi,

 i want to ask one thing that suppose i have a .txt file having content
 like:---


  47 8   ALA   H H  7.85 0.02 1
  48 8   ALA   HAH  2.98 0.02 1
  49 8   ALA   HBH  1.05 0.02 1
  50 8   ALA   C C179.39  0.3 1
  51 8   ALA   CAC 54.67  0.3 1
  52 8   ALA   CBC 18.85  0.3 1
  53 8   ALA   N N123.95  0.3 1
 10715   ALA   H H  8.05 0.02 1
 10815   ALA   HAH  4.52 0.02 1
 10915   ALA   HBH  1.29 0.02 1
 11015   ALA   C C177.18  0.3 1
 11115   ALA   CAC 52.18  0.3 1
 11215   ALA   CBC 20.64  0.3 1
 11315   ALA   N N119.31  0.3 1
 15421   ALA   H H  7.66 0.02 1
 15521   ALA   HAH  4.05 0.02 1
 15621   ALA   HBH  1.39 0.02 1
 15721   ALA   C C179.35  0.3 1
 15821   ALA   CAC 54.33  0.3 1

 now what i want that i will make another .txt file in which first it will
 write the position of ALA lets say 8, 15, 21 then its name ALA and then
 the fifth column value for only three atoms C,CA and CB.

 Means it will be someting like:

 8  ALA  C = 179.39  CA = 54.67  CB = 18.85
 15 ALA  C = 177.18  CA = 52.18  CB = 20.64
 21 ALA  C = 179.35  CA = 54.33  CB =

 if some value is not there then it will leave that as blank.I am new in
 python but this is what we want, so how can i do it using python script.





 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] decorators, __call__ (able) objects

2009-07-15 Thread vince spicer
agreed much better description, thanks

On Wed, Jul 15, 2009 at 1:02 PM, wesley chun wes...@gmail.com wrote:

   Can some one give, or point to some good examples of how @decorators
   work, and __call__ (able) objects?
 
  simple example of calling a class
 
  class myKlass(object):
 
  def __call__(self, *args, **kws):
   print i was called
 
   test = myKlass()
   test()
  i was called


 close. the example was right, but the description wasn't accurate...
 you meant, calling an instance. i'm going to plagarize and rip this
 right out of section 14.1.4 from Core Python Programming:

 Python provides the __call__() special method for classes, which allows a
 programmer to create objects (instances) that are callable. By default, the
 __call__() method is not implemented, meaning that most instances are
 not callable. However, if this method is overridden in a class definition,
 instances of such a class are made callable. Calling such instance objects
 is
 equivalent to invoking the __call__() method. Naturally, any arguments
 given in the instance call are passed as arguments to __call__().

 as far as decorators go, kent's tutorial is great place to start. here
 are 2 more articles plus PEP 318, where they were defined:

 http://www.ibm.com/developerworks/linux/library/l-cpdecor.html
 http://www.artima.com/weblogs/viewpost.jsp?thread=240808
 http://www.python.org/dev/peps/pep-0318

 in addition, i devoted section 11.3.6 of Core Python to decorators.

 finally, it should be mentioned that starting in 2.6, you can now
 decorate *classes*, as seen here in PEP 3129:

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

 hope this helps!
 -- wesley
 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
 Core Python Programming, Prentice Hall, (c)2007,2001
 Python Fundamentals, Prentice Hall, (c)2009
http://corepython.com

 wesley.j.chun :: wescpy-at-gmail.com
 python training and technical consulting
 cyberweb.consulting : silicon valley, ca
 http://cyberwebconsulting.com

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


Re: [Tutor] How to pass command line variables to this python code...

2009-07-14 Thread vince spicer
First off, selenium is a great tool and the python driver is very powerful

there are numerous ways to access cli variables,

the quickest

import sys
print sys.srgv

sys.argv will it output a array of all command line args

./selenium-google-test.py yankees
will out put:

['selenium-google-test.py', 'yankees']

so

args = sys.argv

args[0] == 'yankees'
True

for a more functional way, check out
http://docs.python.org/library/getopt.html



On Tue, Jul 14, 2009 at 11:11 AM, J Cook jcook...@gmail.com wrote:

 Hello,

 I have some autogenerated code from Selenium which I cannot figure out how
 to pass some command line variables to. For example I could export the same
 in Perl and it would be for example:

 code
 use strict;
 use warnings;
 use Time::HiRes qw(sleep);
 use Test::WWW::Selenium;
 use Test::More no_plan;
 use Test::Exception;

 my $sel = Test::WWW::Selenium-new( host = localhost,
port = ,
browser = *chrome,
browser_url =   
 http://www.google.com/; );

 $sel-open_ok(/);
 $sel-type_ok(q, red sox);
 /code

 I could then go in and add something like:

 my ($arg1) = shift || default;

 which would pick up the first command line parameter and then I could do
 something like:

 $sel-(type_ok, $arg1);

 All is good here, now Selenium will export the following for Python:

 code
 from selenium import selenium
 import unittest, time, re

 class NewTest(unittest.TestCase):
def setUp(self):
self.verificationErrors = []
self.selenium = selenium(localhost, , *chrome, 
 http://www.google.com/;)
self.selenium.start()

def test_new(self):
sel = self.selenium
sel.open(/)
sel.type(q, red sox)

def tearDown(self):
self.selenium.stop()
self.assertEqual([], self.verificationErrors)

 if __name__ == __main__:
unittest.main()
 /code

 Now I am confused on how to pass a command line parameter here. Any
 suggestions? I would like to be able to run something like:

 $ python selenium-google-test.py yankees

 Suggestions?


 TIA

 Justin
 ___
 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 pass command line variables to this python code...

2009-07-14 Thread vince spicer
Sorry I do remember that issue in the past, the unittest.main takes over the
cli variables in order to select modules to run

python selenium-google-test.py --help

so unittest is assuming yankees is a test module, you can override this
functionality however with:

unittest.main(argv=['mytestapp'])

this will cause the default run all test modules, and allow you to access
the argv

Hope that helps

Vince



On Tue, Jul 14, 2009 at 1:36 PM, J Cook jcook...@gmail.com wrote:

 Ok,

 So I added the following:

 code
 from selenium import selenium
 import unittest, time, re
 import sys # added this

 q = sys.argv[1] # added this
 print q # added this just to see

 class NewTest(unittest.TestCase):
def setUp(self):
self.verificationErrors = []
self.selenium = selenium(localhost, , *chrome, 
 http://www.google.com/;)
self.selenium.start()

def test_new(self):
sel = self.selenium
sel.open(/)
sel.type(q, q) # this is where I want the argument to end up

def tearDown(self):
self.selenium.stop()
self.assertEqual([], self.verificationErrors)

 if __name__ == __main__:
unittest.main()
 /code

 I run the following:

 $ python selenium-google-test.py yankees
 yankees
 Traceback (most recent call last):
  File selenium-google-test.py, line 24, in module
unittest.main()
  File /usr/lib/python2.6/unittest.py, line 816, in __init__
self.parseArgs(argv)
  File /usr/lib/python2.6/unittest.py, line 843, in parseArgs
self.createTests()
  File /usr/lib/python2.6/unittest.py, line 849, in createTests
self.module)
  File /usr/lib/python2.6/unittest.py, line 613, in loadTestsFromNames
suites = [self.loadTestsFromName(name, module) for name in names]
  File /usr/lib/python2.6/unittest.py, line 584, in loadTestsFromName
parent, obj = obj, getattr(obj, part)
 AttributeError: 'module' object has no attribute 'yankees'

 How do I get the argument over to where I need it to be?

 Justin

 vince spicer wrote:

 First off, selenium is a great tool and the python driver is very powerful

 there are numerous ways to access cli variables,

 the quickest

 import sys
 print sys.srgv

 sys.argv will it output a array of all command line args

 ./selenium-google-test.py yankees
 will out put:

 ['selenium-google-test.py', 'yankees']

 so

 args = sys.argv

 args[0] == 'yankees'
 True

 for a more functional way, check out
 http://docs.python.org/library/getopt.html



 On Tue, Jul 14, 2009 at 11:11 AM, J Cook jcook...@gmail.com mailto:
 jcook...@gmail.com wrote:

Hello,

I have some autogenerated code from Selenium which I cannot figure
out how to pass some command line variables to. For example I could
export the same in Perl and it would be for example:

code
use strict;
use warnings;
use Time::HiRes qw(sleep);
use Test::WWW::Selenium;
use Test::More no_plan;
use Test::Exception;

my $sel = Test::WWW::Selenium-new( host = localhost,
   port = ,
   browser = *chrome,
   browser_url =  
 http://www.google.com/; );

$sel-open_ok(/);
$sel-type_ok(q, red sox);
/code

I could then go in and add something like:

my ($arg1) = shift || default;

which would pick up the first command line parameter and then I
could do something like:

$sel-(type_ok, $arg1);

All is good here, now Selenium will export the following for Python:

code
from selenium import selenium
import unittest, time, re

class NewTest(unittest.TestCase):
   def setUp(self):
   self.verificationErrors = []
   self.selenium = selenium(localhost, , *chrome,
http://www.google.com/;)
   self.selenium.start()

   def test_new(self):
   sel = self.selenium
   sel.open(/)
   sel.type(q, red sox)

   def tearDown(self):
   self.selenium.stop()
   self.assertEqual([], self.verificationErrors)

if __name__ == __main__:
   unittest.main()
/code

Now I am confused on how to pass a command line parameter here. Any
suggestions? I would like to be able to run something like:

$ python selenium-google-test.py yankees

Suggestions?


TIA

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



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


Re: [Tutor] string pickling and sqlite blob'ing

2009-06-25 Thread vince spicer
Dinesh

In theory you can store in either type(i have done it), however you should
store in the binary column, blob

Vince



On Wed, Jun 24, 2009 at 2:42 PM, Dinesh B Vadhia
dineshbvad...@hotmail.comwrote:

  Hi Vince

 That's terrific!  Once a string is compressed with gzip.zlib does it make a
 difference whether it is stored it in a TEXT or BLOB column?

 Dinesh



 *From:* vince spicer vinces1...@gmail.com
 *Sent:* Wednesday, June 24, 2009 10:49 AM
 *To:* Dinesh B Vadhia dineshbvad...@hotmail.com
 *Cc:* tutor@python.org
 *Subject:* Re: [Tutor] string pickling and sqlite blob'ing

 Pickle is more for storing complex objects (arrays, dict, etc). pickling a
 string makes it bigger.

 I have stored large text chunks in text and/or blob columns compressed with
 gzip.zlib.compress and extracted with gzip.zlib.decompress

 Comparison:

 import cPickle as Pickle
 import gzip

 x = asdfasdfasdfasdfasdfasdfasdfasdfasdf

 print len(x)
  36

 print len(Pickle.dumps(x))
  44

 print len(gzip.zlib.compress(x))
  14


 Vince

 On Wed, Jun 24, 2009 at 11:17 AM, Dinesh B Vadhia 
 dineshbvad...@hotmail.com wrote:
 I want to pickle (very long) strings and save them in a sqlite db.  The
 plan is to use pickle dumps() to turn a string into a pickle object and
 store it in sqlite.  After reading the string back from the sqlite db, use
 pickle loads() to turn back into original string.

 - Is this a good approach for storing very long strings?

 - Are the pickle'd strings stored in the sqlite db as a STRING or BLOB?

 Cheers.

 Dinesh




 ___
 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] string pickling and sqlite blob'ing

2009-06-24 Thread vince spicer
Pickle is more for storing complex objects (arrays, dict, etc). pickling a
string makes it bigger.

I have stored large text chunks in text and/or blob columns compressed with
gzip.zlib.compress and extracted with gzip.zlib.decompress

Comparison:

import cPickle as Pickle
import gzip

x = asdfasdfasdfasdfasdfasdfasdfasdfasdf

print len(x)
 36

print len(Pickle.dumps(x))
 44

print len(gzip.zlib.compress(x))
 14


Vince

On Wed, Jun 24, 2009 at 11:17 AM, Dinesh B Vadhia dineshbvad...@hotmail.com
 wrote:

  I want to pickle (very long) strings and save them in a sqlite db.  The
 plan is to use pickle dumps() to turn a string into a pickle object and
 store it in sqlite.  After reading the string back from the sqlite db, use
 pickle loads() to turn back into original string.

 - Is this a good approach for storing very long strings?

 - Are the pickle'd strings stored in the sqlite db as a STRING or BLOB?

 Cheers.

 Dinesh



 ___
 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] Trouble with passing commands / variables to os.system()

2009-06-23 Thread vince spicer
os.system is not the best way to handle this you may want to look into
the subprocess module

however:

import os

username = 'charlie'
private_key = '/path/to/key'
ssh = '/usr/bin/ssh'
command = 'hostname  df -h  exit'

servers = ['172.16.1.1', '172.16.12.2', '172.16.1.3']

for host in servers:
os.system(ssh %...@%s -i %s %s %(username, host, private_key, command)



On Tue, Jun 23, 2009 at 2:01 PM, Charlie Reddington 
charlie.redding...@gmail.com wrote:

 Hi,

 I'm very very green when it comes to python. I know bash better than
 python, so I figured a good way to learn things was covert my bash stuff to
 python. So here goes...

 Here's a quick example of the code I have that is broken.

 import os

 username = 'charlie'
 private_key = '/path/to/key'
 ssh = '/usr/bin/ssh'
 command = 'hostname  df -h  exit'

 servers = ['172.16.1.1', '172.16.12.2', '172.16.1.3']

 for host in servers:
print(os.system(ssh -l username -i private_key host command))

 What I'm trying to do is is, is use ssh with a private key. That way I can
 quickly run some remote commands on a few hundred servers in a quick way to
 do stuff (disk usage, top, etc).

 When I run this, I get errors like this for every host in my list.

 Warning: Identity file private_key not accessible: No such file or
 directory.
 ssh: Could not resolve hostname i: nodename nor servname provided, or not
 known
 65280

 My first thoughts are, it's not passing my variables to the function the
 way I'd expect.

 So my questions are...

 1.) Is it nessacary to put my IP's in quotes?
 2.) When I call a variable in a function (like os.system() or print()) I
 don't use $'s right?
 3.) Am I putting variables in my functions properly? Can I put variables
 like this in there?

 Thanks for any help.

 Charlie

 ___
 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] extracting lines in large file

2009-06-22 Thread vince spicer
14mb file shouldn't be an issue, unless you very little ram, is there any
errors being outputted?

a cleaner way for reading the file:

for line in open(output.new):
if line.startswith(intrinsic):
print line


On Mon, Jun 22, 2009 at 2:16 PM, Bryan Fodness bryan.fodn...@gmail.comwrote:

 I am trying to output all the lines that start with a specific word.
 It is a large output file (~14 Mb), but nothing that I thought would
 be a problem.

 for line in open('output.new'):
i_line = line.split()
if i_line:
if i_line[0] == intrinsic:
print i_line

 It does not get all of the lines, it stops at line 130323.  There are
 ~26 line.  Is there a limit to the number of lines you can read in
 this way, or am I overlooking something else.

 Bryan
 ___
 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] Handling Generator exceptions in Python 2.5

2009-06-19 Thread vince spicer
Well*

*result = [(ListA[i] - ListB[i-1])/ListA[i] for i in range(len(ListA))*if
not ListA[i] == 0*]

will exclude any results where listA[i] is 0, if you still want these in the
result
you may want to use good'ol for statement instead of list comprehension


results = []
for x in range(len(listA)):
y = ListA[i] - ListB[i-1]
if not ListA[i] == 0:
y = y / ListA[i]
results.append(y)

print results

Vince


On Fri, Jun 19, 2009 at 8:55 AM, Joe Python jopyt...@gmail.com wrote:

 I have a generator as follows to do list calculations.

 *result = [(ListA[i] - ListB[i-1])/ListA[i] for i in range(len(ListA))]*

 The above generator, throws  '*ZeroDivisionError*' exception if ListA[i] =
 0.
 Is there a way to say 'Don't divide by ListA[i] if its equal to 0 (within
 that statement)'.

 Sorry if this question sounds too stupid.

 TIA
 Joe

 ___
 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] New to programming and python first minimilistic program (Bottles of beer), , please comment!

2009-06-17 Thread vince spicer
Like in any language there any number for ways, heres another

b = bottles of beer
w = on the wall
bottles = range(1, 101)
bottles.reverse()
for bottle in bottles:
print  %s %s %s if one of those bottles should happen to fall there'll
be %s %s %s % (bottle, b,w, bottle-1, b,w)

Vince

2009/6/17 matthew andriani skellem2...@hotmail.com

  Hi Guys,

 I wrote this program for some practice to get into python..I'm trying to
 find fun ways to learn the language so if anyone has a challenge on this
 basic level using loops that sounds exciting please let me know.. If you
 think this program can be improved please let me know too :)

 b = bottles of beer
 w = on the wall
 a = 100
 while a != 0:
 a = a-1
 print a,b,w,a,b,if one of those bottles should happen to fall there'll
 be,a-1,b,w


 Thanks for the feedback..

 Cheers,
 Skellem.



 --
 What can you do with the new Windows Live? Find 
 outhttp://www.microsoft.com/windows/windowslive/default.aspx

 ___
 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] Simple factorial program

2009-06-11 Thread vince spicer
did you declare factorial before trying to use it?

factorial = 1
print Factorial finder
number = int(input(Please enter a non-negative integer: ))
for number in range(number, 1)
factorial = (factorial * number)

print Factorial:, factorial

On Thu, Jun 11, 2009 at 9:53 AM, Eddie eddie9...@gmail.com wrote:

 I'm trying to write a simple factorial program and am unsure at what is
 wrong with it. Why Can't I go *factorial = factorial * number* where
 factorial and number are both integers?

 #Factorial program

 print Factorial finder
 number = input(Please enter a non-negative integer: 
 for number in range(number, 1)
 factorial = (factorial * number)

 print Factorial:, factorial

 Thanks Eddie [?]


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


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


Re: [Tutor] Simple factorial program

2009-06-11 Thread vince spicer
no : after for statement

Vince

On Thu, Jun 11, 2009 at 10:06 AM, Eddie eddie9...@gmail.com wrote:

 Thanks, that is my problem.

 With that code, why is it giving an error  (indenting?) at the end of* for
 number in range(number, 1) *?

 2009/6/12 vince spicer vinces1...@gmail.com

 did you declare factorial before trying to use it?

 factorial = 1
 print Factorial finder
 number = int(input(Please enter a non-negative integer: ))
 for number in range(number, 1)
 factorial = (factorial * number)

 print Factorial:, factorial

 On Thu, Jun 11, 2009 at 9:53 AM, Eddie eddie9...@gmail.com wrote:

 I'm trying to write a simple factorial program and am unsure at what is
 wrong with it. Why Can't I go *factorial = factorial * number* where
 factorial and number are both integers?

 #Factorial program

 print Factorial finder
 number = input(Please enter a non-negative integer: 
 for number in range(number, 1)
 factorial = (factorial * number)

 print Factorial:, factorial

 Thanks Eddie [?]


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




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


Re: [Tutor] improvement of if - else code

2009-06-04 Thread vince spicer
you could assign loop variable

   @staticmethod
   def get_form(address=None, postcode=None, town=None, phone=None,
fax=None,
freephone=None, address_country=None, address_region=None,
address_county=None, hotel=None):
   context = get_context()
   root = context.root
   # List authorized countries

   loopvar = root.get_active_countries(context) if hotel else
root.get_authorized_countries(context)

   countries = [ {'name': y, 'title': x, 'selected': y ==
address_country} for x, y in loopvar ]




On Thu, Jun 4, 2009 at 11:25 AM, Norman Khine nor...@khine.net wrote:

 Hello,
 Is there a better way to write this:

@staticmethod
def get_form(address=None, postcode=None, town=None, phone=None,
 fax=None,
 freephone=None, address_country=None, address_region=None,
 address_county=None, hotel=None):
context = get_context()
root = context.root
# List authorized countries
if hotel is True:
countries = [
{'name': y, 'title': x, 'selected': y == address_country}
for x, y in root.get_active_countries(context) ]
else:
countries = [
{'name': y, 'title': x, 'selected': y == address_country}
for x, y in root.get_authorized_countries(context) ]

 Thanks
 ___
 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 o convert spaces into tabs??

2009-06-02 Thread vince spicer
regex will do it


import re

line = re.sub(r\s+, \t, line)

print line



Vince

On Tue, Jun 2, 2009 at 11:42 AM, jyotsna guleria
jyotsna.gule...@gmail.comwrote:


 Hello every one,

 I am trying to parse a file:

 I want to convert all the spaces in between the characters to single tab.

 e.g: my file has contents like:

 1G579011  10  2   0  00
 0   0   00
 5Ht-2  60459  11  0   0  00
 0   0   00


 I want them to be separated by a single tab not with spaces..

 It should look like:

 1G5790111020000000
 5Ht-2604591100000000

 each separated by Tab...

 It is a text file containing such a data ..


 Thanks
 --
 Jyotsna Guleria

 ___
 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 variable from an external script or program

2009-05-29 Thread vince spicer
import commands
output = commands.getout(ls -lah)

Vince

On Fri, May 29, 2009 at 3:27 PM, shawn bright neph...@gmail.com wrote:

 Hey all

 I have a small program that when run from the command line, will
 return a certain value for an arguement. Like this:

  mfetchz 45
  45j

 so the program is mfetchz and the argument is 45

 i know i can call the program with os.system(mfetchz 45)
 but how do i get the return?

 The OS is linux, if that matters

 thanks

 sk
 ___
 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 variable from an external script or program

2009-05-29 Thread vince spicer
Sorry *output

import commands
 output = commands.getoutput(ls -lah)



 Vince


 On Fri, May 29, 2009 at 3:27 PM, shawn bright neph...@gmail.com wrote:

 Hey all

 I have a small program that when run from the command line, will
 return a certain value for an arguement. Like this:

  mfetchz 45
  45j

 so the program is mfetchz and the argument is 45

 i know i can call the program with os.system(mfetchz 45)
 but how do i get the return?

 The OS is linux, if that matters

 thanks

 sk
 ___
 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] web cam

2009-05-20 Thread vince spicer
I've seen this win32 library:

http://videocapture.sourceforge.net via
http://technobabbler.com?p=22

for linux

http://www.antonym.org/libfg

Vince

2009/5/20 Ricardo Aráoz ricar...@gmail.com

 Hi, a friend of mine has asked me how difficult would it be to send web
 cam images through python program as a hobby project.
 Honestly, at this point I have no idea where does he want to put python
 in the equation nor what does the project entail. So I'm asking for
 pointers to :
 a) Any already done projects in python
 b) keywords to google for
 c) what parts do you think I'll need to put together (web service,
 client, browser) and which modules do you recommend.

 I know this is a half baked question, just some pointers on where to
 start from would be enough.

 Thanks


 ___
 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] Allow only one instance of a process

2009-05-16 Thread Vince Spicer
simple solution would be to create a lock file before processing, 

lock = open(videoname.lck)
lock.close()





On Saturday 16 May 2009 8:26:31 pm Sylvain Ste-Marie wrote:
 I'm currently writing a script to batch convert video for my psp

 It basically looks into a folder for video and launch ffmpeg:

 ffmpeg -i videoname -f psp -r 29.97 -b 768k -ar 24000 -ab 64k -s
 368x208 videoname.mp4

 my idea is basically to check for pid but how do i do that?


 ___
 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] Python popen command using cat textfile .... how to terminate

2009-05-14 Thread vince spicer
Take a peak at commands.getoutput


EX:

import commmands

ls = commands.getoutput(ls- ls)

Vince

On Thu, May 14, 2009 at 3:50 PM, MK lop...@gmx.net wrote:

 Hi there,

 i am using this code to send an cat  ThisIsMyUrl with popen.
 Of cos cat now waits for the CTRL+D command.
 How can i send this command ?

 def console_command(cmd):
print cmd
console = os.popen(cmd,r)
output = console.read()
console.close()
return output

 command=cat   + working_dir + / + subdir + www.thisismyurl.com
 console_command(command)


 Thank you.


 ___
 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] Sorting a list

2009-05-13 Thread vince spicer
you can pass sort a custom compare function


Simple ex:

def compare(x,y):
try:
return cmp(int(x), int(y))
except:
pass
try:
int(x)
except:
return -1
try:
int(y)
except:
return 1
return 0


x = [4, 6, 'word', 3, 9]
x.sort(cmp=compare)

 ['word', 3,4, 6, 9]


On Wed, May 13, 2009 at 10:25 AM, Timo timomli...@gmail.com wrote:

 Hello,

 I don't think this should be difficult, so maybe I look over it. But I
 can't seem to find the solution.

 I have a list with one word and a couple of numbers. Now I want the word to
 be kept in the first location and the numbers to be sorted.

 So this:
 [4, 6, 'word', 3, 9]

 should be:

 ['word', 3, 4, 6, 9]

 Timo
 ___
 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] Advanced String Search using operators AND, OR etc..

2009-05-04 Thread vince spicer
Advanced Strings searches are Regex via re module.

EX:

import re

m = re.compile((FDA.*?(approved|supported)|Ben[^\s])*)

if m.search(Text):
print m.search(Text).group()


Vince


On Mon, May 4, 2009 at 6:45 AM, Alex Feddor alex.fed...@gmail.com wrote:

 Hi

 I am looking for method enables advanced text string search. Method
 string.find() or re module seems no  supporting what I am looking for. The
 idea is as follows:

 Text =FDA meeting was successful. New drug is approved for whole sale
 distribution!

 I would like to scan the text using AND and OR operators and gets -1 or
 other value if the searching elements haven't found in the text.
 Example 01:
 search criteria:  FDA AND ( approve* OR supported)
 The catch is that in Text variable FDA and approve words  are not one after
 another (other words are in between).
  Example 02:
 search criteria: Ben
 The catch is that code sould find only exact Ben words not also words which
 that has firts three letters Ben such as Benquick, Benseek etc.. Only Ben is
 the right word we are looking for.

 I would really appreciated your advice - code sample / links how above can
 be achieved! if possible I would appreciated solution achieved with free of
 charge module.

 Cheers,  Alex
 PS:
 A few moths ago I have discovered Python. I am amazed what all can be done
 with it. Really cool programming language..

 ___
 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] Add newline's, wrap, a long string

2009-04-28 Thread vince spicer
first, grabbing output from an external command try:

import commands

USE = commands.getoutput('grep USE /tmp/comprookie2000/emege_info.txt |head
-n1|cut -d\\-f2')
then you can wrap strings,

import textwrap

Lines = textwrap.wrap(USE, 80) # return a list

so in short:

import commands, textwrap
data = textwrap.wrap(commands.getoutput('my command'), 80)



Vince





On Tue, Apr 28, 2009 at 3:43 PM, David da...@abbottdavid.com wrote:

 I am getting information from .txt files and posting them in fields on a
 web site. I need to break up single strings so they are around 80 characters
 then a new line because when I enter the info to the form on the website it
 has fields and it errors out with such a long string.

 here is a sample of the code;

 #!/usr/bin/python
 import subprocess
 import os

 u_e = subprocess.Popen(
 'grep USE /tmp/comprookie2000/emerge_info.txt |head -n1|cut -d\\-f2',
 shell=True, stdout=subprocess.PIPE,)
 os.waitpid(u_e.pid, 0)
 USE = u_e.stdout.read().strip()
 L = len(USE)
 print L
 print USE

 L returns 1337

 Here is what USE returns;
 http://linuxcrazy.pastebin.com/m2239816f

 thanks
 -david
 --
 Powered by Gentoo GNU/Linux
 http://linuxcrazy.com
 ___
 Tutor maillist  -  Tutor@python.org
 http://mail.python.org/mailman/listinfo/tutor

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