Re: [Tutor] "Ctrl-C (unix)" in python
On Thu, Feb 19, 2009 at 9:44 AM, pa yo wrote: > I am running my Twitter>>Wiki bots in infinite loops but can't find > an easy way to turn them off gracefully once I have started them. At > the moment I have to go into the terminal window where they are > running and type "Ctrl-C". (I am running Ubuntu 8.10 and python 2.5.2) > > I was thinking that I could get the bot script to read a text file at > the start of the main loop and have a separate script writing the > "exit" order to the same text file but before I get too involved > with this I wanted to know if there was an built-in function to > switch scripts on and off. > > Any help or assistance much appreciated. > > Payo > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > how about kill -9 :) ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Exception Handling
On Wed, Dec 31, 2008 at 8:33 AM, David wrote: > On Mon, 29 Dec 2008 16:57:44 +0100, spir wrote: >> >> > On Mon, 29 Dec 2008 09:10:45 - >>> > "Alan Gauld" wrote: >>> > > >>> >> "bob gailer" wrote >> > >> > Also IMHO it is bad design to put a lot of code inside a try > block. > >> > In this case the user might make a mistake on day and then is > forced > >> > to reenter the year and month! > >> >> Obviously there is no absolute rule here but I disagree. One of the >> biggest advantages of try/except error handling is that it keeps the >> mess of handling errors out of the main logic of the code. This has two >> effects: >> 1) Code that is much easier to read >> 2) a lot less error handling code >>> Also, I'd rather ask for the dates in one raw_input, cuts much of the >> mess for the user (although it's a bit of extra codes) >> > Thank you all for the tips. Next to do is to get the dates in one raw_input > with the correct format and to check for a valid year, month, and day. Here > is what I have now; > #!/usr/bin/python > import time > > curr_date = time.strftime("%Y %m %d", time.gmtime()) > print "Please enter the date format as: ", curr_date > > while True: >yr = raw_input("\nWhat year were you born? ") >mn = raw_input("What month were you born? ") >dy = raw_input("What day were you born? ") >try: >ynum = int(time.strftime("%Y", time.gmtime())) - int(yr) >mnum = int(time.strftime("%m", time.gmtime())) >dnum = int(time.strftime("%d", time.gmtime())) >except ValueError: >print "Oops, You must enter a number!" >else: >mn = int(mn) >dy = int(dy) > >if mn <= mnum: >print "You are", ynum, "years old." >break >elif mn == mnum and dy < dnum: >print "You are", ynum, "years old." >break >else: >ret = int(ynum) - 1 >print "You are", ret, "years old." >break > > > -- > Powered by Gentoo GNU/LINUX > http://www.linuxcrazy.com > pgp.mit.edu > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > Hi David, If the user enters incorrect data for the month or day, a ValueError will still be raised on the conversion to integer. I suggest that you wrap your request for user information in a function that does the checking for you. You can re-use this function for each piece of integer information you require from the user. example: import time class BadUserError(Exception): pass def get_integer(retrieve, question, attempts=3): """ A small function to attempt to retrieve information from a user, given a prompt question. retrive - any function that will accept a string as an argument and return a string or otherwise response from the user. question - a string type question that you would like to ask the user to respond to. attempts[optional] - how many times the user can incorrectly enter data before the BadUserError is raised. """ while attempts > 0: num = retrieve(question) try: # try casting the user input as an integer. return int(num) except ValueError: print "Oops, You must enter a number!" attempts -= 1 raise BadUserError("Too many incorrect tries!") curr_date = time.strftime("%Y %m %d", time.gmtime()) print "Please enter the date format as: ", curr_date yr = get_integer(raw_input, "\nWhat year were you born? ") mn = get_integer(raw_input, "What month were you born? ") dy = get_integer(raw_input, "What day were you born? ") today = time.gmtime() ynum = today.tm_year - yr mnum = today.tm_mon dnum = today.tm_mday if mn <= mnum: print "You are", ynum, "years old." elif mn == mnum and dy < dnum: print "You are", ynum, "years old." else: ret = int(ynum) - 1 print "You are", ret, "years old." ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Exception Handling
On Wed, Dec 31, 2008 at 11:18 AM, David wrote: > > . I still need to get it to prduce an error if the year is 0 or 2009, the > month is 0 or 13 and the day is 0 or 32. Try using the datetime module to check validity of entered data. example: >>> import datetime >>> datetime.datetime(2008, 12, 32) # should be an error, there are only 31 days in December! ValueError: day is out of range for month > david [06:56 PM] opteron ~ $ ./py_get_age.py > Please enter the date format as: 2008 12 30 > > What year were you born? 2010 > What month were you born? 14 > What day were you born? 34 > You are -3 years old. You can also use it to check if the input is in the future. >>> userdate = datetime.datetime(2010, 1, 1) >>> datetime.datetime.now() > userdate # a check to see if userdate is in the past. False Cheers, Jervis ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Better way - fnmatch with list ? CORRECTION
On Sat, Jan 3, 2009 at 10:48 AM, bob gailer wrote: > bob gailer wrote: >> >> >> for fn in files: >> base, ext = os.path.splitext(fn) >> if ext in ['.flac','.mp3','.m4a']: ## CORRECTION removed * >> >> > for fn in files: base, ext = os.path.splitext(fn) if ext.lower() in ['.flac', '.mp3', '.mp4']: takes into account systems with case sensitive filenames. cheers, Jervis ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Question regarding win32com getting ldap object
On Mon, Jan 5, 2009 at 8:04 PM, vishwajeet singh wrote: > Hi List, > > I am running following code to get ldap com object but the result I am > getting is unknown > I am using Python 25 and win32 bindings available at > http://downloads.sourceforge.net/pywin32/pywin32-212.win32-py2.2.exe?modtime=1217535908&big_mirror=0 > > *adsi = win32com.client.Dispatch('ADsNameSpaces') > print adsi > ldap = adsi.getobject('', 'LDAP:') > print ldap* > > OutPut: > > > > > Any ideas what I am doing wrong ? > > -- > Cheers, > Vishwajeet > http://www.singhvishwajeet.com > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > Hi, try the following from the archive: http://mail.python.org/pipermail/python-list/1999-December/018594.html Cheers, Jervis ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Gamma distribution function
On Wed, Jan 14, 2009 at 8:27 AM, culpritNr1 wrote: > > > there some kind of random.poisson()? > > Thank you, > > culpritNr1 > > Hello try the scipy library: >>> from scipy import stats >>> lamb = 10 >>> stats.distributions.poisson.rvs(lamb, loc=0) array([5]) >>> stats.distributions.poisson.rvs(lamb, loc=0) array([14]) http://www.scipy.org/ cheers, ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Fwd: Gamma distribution function
-- Forwarded message -- From: Jervis Whitley Date: Wed, Jan 14, 2009 at 9:26 AM Subject: Re: [Tutor] Gamma distribution function To: culpritNr1 On Wed, Jan 14, 2009 at 9:11 AM, culpritNr1 wrote: > > The python documentation on this functionality is extremely poor. Look > >>> help("scipy.stats.distributions.poisson.rvs") > Help on method rvs in scipy.stats.distributions.poisson: > scipy.stats.distributions.poisson.rvs = rvs(self, *args, **kwds) method of > scipy.stats.distributions.poisson_gen instance > > Do you understand what's going on? > > Thanks, > > culpritNr1 > > > -- > View this message in context: > http://www.nabble.com/Gamma-distribution-function-tp21444899p21445597.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 previous email said you wanted to sample from the poisson function, which is what that rvs method is doing, taking random samples from a poisson distribution of lambda = 1 in your case. They also provide a means to shift the function from a nominal x crossing of 0 using the second argument, in your case you have used 2. So you were sampling from a function of mean 1 shifted right by 2. The below has been taken from the poisson documentation itself: print stats.distributions.poisson.__doc__ A poisson discrete random variable. Discrete random variables are defined from a standard form. The standard form may require some other parameters to complete its specification. The distribution methods also take an optional location parameter using loc= keyword. The default is loc=0. The calling form of the methods follow: poisson.rvs(mu,loc=0) - random variates poisson.pmf(x,mu,loc=0) - probability mass function poisson.cdf(x,mu,loc=0) - cumulative density function poisson.sf(x,mu,loc=0) - survival function (1-cdf --- sometimes more accurate) poisson.ppf(q,mu,loc=0) - percent point function (inverse of cdf --- percentiles) poisson.isf(q,mu,loc=0) - inverse survival function (inverse of sf) poisson.stats(mu,loc=0,moments='mv') - mean('m',axis=0), variance('v'), skew('s'), and/or kurtosis('k') poisson.entropy(mu,loc=0) - entropy of the RV Alternatively, the object may be called (as a function) to fix the shape and location parameters returning a "frozen" discrete RV object: myrv = poisson(mu,loc=0) - frozen RV object with the same methods but holding the given shape and location fixed. You can construct an aribtrary discrete rv where P{X=xk} = pk by passing to the rv_discrete initialization method (through the values= keyword) a tuple of sequences (xk,pk) which describes only those values of X (xk) that occur with nonzero probability (pk). Poisson distribution poisson.pmf(k, mu) = exp(-mu) * mu**k / k! for k >= 0 If you are after a probability at a given k (which it now sounds like you may be after) you might be interested in the pmf method. (Sorry I did a reply instead of reply-all) Cheers, Jervis ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] eval and floating point
On Thu, Jan 15, 2009 at 1:19 PM, Mr Gerard Kelly wrote: > Thanks very much > > I've noticed that the eval() function gives an integer, so eval("3/2") > gives back 1. float(eval("3/2")) doesn't seem to work, any way to get a > floating point number back with eval()? > > I know you can just do ("3./2."), but is there any way to do it with > just ("3/2")? > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > Hi, at the top of your script you can write: from __future__ import division now >>> eval("4/3") 1.3 You can read up on it here if you are interested.. http://www.python.org/dev/peps/pep-0238/ Cheers ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] single key ordered sequence
On Fri, Jan 16, 2009 at 4:56 AM, Senthil Kumaran wrote: > > Also, how to practically walk in reverse order in a list without > > copying it (e.g. items[::-1]), > > especially if i need both indexes and items (couldn't find with > > enumerate()). > > > Are you looking for reversed()? > The way you are doing it is probably OK. > But it can be simplified thus: > > keys = [] > target = [] > > for item in reversed(items): > if not item[0] in keys: >keys.append(item[0]) >target.append(item) > > print target > > If this is not what you wanted,then I have misunderstood your > requirement and just based it on your code. > > Thanks, > Senthil > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > how about this: items = [(1,'a'),(1,'b'),(2,'a'),(3,'a'), (3,'b'),(4,'a'),(5,'a'),(5,'b'),(5,'c')] mydict = dict(items) items = [item for item in mydict.iteritems()] testing shows: C:\WINDOWS\system32\cmd.exe /c python test_time.py **ORIGINAL** s = """ items = [(1,'a'),(1,'b'),(2,'a'),(3,'a'), (3,'b'),(4,'a'),(5,'a'),(5,'b'),(5,'c')] keys = [] for index in range(len(items)-1,-1,-1): key = items[index][0] if key in keys: items[index] = None else: keys.append(key) items = [item for item in items if item is not None] """ timeit.Timer(stmt=s).timit() 5.40928835422 **Test1** s = """ items = [(1,'a'),(1,'b'),(2,'a'),(3,'a'), (3,'b'),(4,'a'),(5,'a'),(5,'b'),(5,'c')] keys = [] for item in reversed(items): key = item[0] if key in keys: items.remove(item) else: keys.append(key) #items = [item for item in items if item is not None] """ timeit.Timer(stmt=s).timit() 5.02896436267 **Test2** s= """ items = [(1,'a'),(1,'b'),(2,'a'),(3,'a'), (3,'b'),(4,'a'),(5,'a'),(5,'b'),(5,'c')] keys = dict(items) items = [item for item in keys.iteritems()] """ timeit.Timer(stmt=s).timit() 3.38715506199 Hit any key to close this window... ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] single key ordered sequence
On Fri, Jan 16, 2009 at 9:15 AM, Kent Johnson wrote: > On Thu, Jan 15, 2009 at 3:44 PM, Jervis Whitley > wrote: > > how about this: > > items = [(1,'a'),(1,'b'),(2,'a'),(3,'a'), > > (3,'b'),(4,'a'),(5,'a'),(5,'b'),(5,'c')] > > mydict = dict(items) > > items = [item for item in mydict.iteritems()] > > That only coincidentally preserves order; the order of items in a > dictionary is, for practical purposes, unpredictable. > > BTW [item for item in mydict.iteritems()] can be written as just > mydict.items(). > > Kent I realise that what you have said is true, however can you show me a case where > items = dict(items).items() will not preserve order? Thanks. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] single key ordered sequence
On Fri, Jan 16, 2009 at 10:39 AM, bob gailer wrote: > Jervis Whitley wrote: > >> >> >> On Fri, Jan 16, 2009 at 9:15 AM, Kent Johnson > ken...@tds.net>> wrote: >> >>On Thu, Jan 15, 2009 at 3:44 PM, Jervis Whitley >>mailto:jervi...@gmail.com>> wrote: >>> how about this: >>> items = [(1,'a'),(1,'b'),(2,'a'),(3,'a'), >>> (3,'b'),(4,'a'),(5,'a'),(5,'b'),(5,'c')] >>> mydict = dict(items) >>> items = [item for item in mydict.iteritems()] >> >>That only coincidentally preserves order; the order of items in a >>dictionary is, for practical purposes, unpredictable. >> >>BTW [item for item in mydict.iteritems()] can be written as just >>mydict.items(). >> >>Kent >> >> I realise that what you have said is true, however can you show me a case >> where >> > items = dict(items).items() >> >> will not preserve order? Thanks. >> >> > On my computer: > > >>> dict((('z', 1), ('y', 2))).items() > [('y', 2), ('z', 1)] > > -- > Bob Gailer > Chapel Hill NC > 919-636-4239 > Same on mine, thanks. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] running & debugging in python interactive she
On Fri, Jan 16, 2009 at 9:56 AM, Che M wrote: > > > > >> I'd like to add to this question and expand it: can anyone point me to > >> a good resource on debugging *generally*? > > The first result on "Debugger tutorial" on google sent me to this: > > > http://www.cs.princeton.edu/~benjasik/gdb/gdbtut.html > > > Though it's for a specific program, it seems to have some good general > purpose advice. > > Personally, I've never had the need for a debugger (maybe because I'm not > writing complicated > > enough programs) - a simple "print" statement (in the right spot) tends > to take care of all of my > > debugging needs. > > That page didn't strike me as very helpful for my case, but thanks > anyway. I'll Google for it, too, but just wondered if any of the > tutors here had any recommendations. I just checked Alan Gauld's > tutorial and I see it doesn't have a debugger section (completely > understandably, as this is sort of advanced). > > I also use print statements a fair bit. I've just heard that using > a debugger is a very useful thing and I thought maybe someone would > have some tips here or knew of a good Python-relevant tutorial about it. > > Thanks, > Che > > > -Wayne > > I did a search for 'python pdb tutorial' and found this resource: http://www.ferg.org/papers/debugging_in_python.html pdb is the python debugger, this tutorial will give you more than enough to get started. Cheers, ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Properties of an object
> > > > For me, the "()" look like artificial, not necessary. I would prefer just > to type"a.list_1stpart" , a property. > > > > -- > > Others have explained their preference for using get methods for accessing internal data structures, However it does look like you have specifically mentioned a preference for attribute like access: e = ExampleList([1,2,3,4], 2) >>> e.firstpart [1,2] rather than >>> e.firstpart() [1,2] We can implement this using properties, and I will refer you to some of the documentation http://docs.python.org/library/functions.html#property Here is just one way that you could simply implement a property in your case: class ExampleList(object): """Note that this is a new style class.""" def __init__(self, sequence, position): self._sequence = sequence self._position = position @property def firstpart(self): """This method will be called on inst.firstpart rather than inst.firstpart().""" return self._sequence[:self._position] Here I have used property as a decorator (described in the link), now you can get your firstpart through attribute access (not that you cannot 'set' to it): e.firstpart Cheers, ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] regex: not start with FOO
On Tue, Feb 3, 2009 at 9:46 AM, Bernard Rankin wrote: > Hello, > > > I'd like to match any line that does not start with FOO. (Using just a > reg-ex rule) > > 1) What is the effective difference between: > > (?!^FOO).* > > ^(?!FOO).* > > 2) Is there a better way to do this? > myline = 'FOO things in line' >>> myline.startswith('FOO') True Cheers, ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor