Re: [Tutor] Code to open a website

2013-02-10 Thread Peter Otten
ALAN GAULD wrote: Maybe the OP meant to say 'quit()' ? That does not require an import. Ooh! another option I didn't know about! So many ways to get rid of Python and here's me been importing sys or raising SystemExit all these years... :-) I tend to use none of these and my scripts

Re: [Tutor] How to override getting items from a list for iteration

2013-02-10 Thread Peter Otten
Walter Prins wrote: Hello, I have a program where I'm overriding the retrieval of items from a list. As background: The data held by the lists are calculated but then read potentially many times thereafter, so in order to prevent needless re-calculating the same value over and over, and

Re: [Tutor] How to override getting items from a list for iteration

2013-02-10 Thread Peter Otten
Peter Otten wrote: def __iter__(self): for i in range(len(self)): return self[i] That should of course be 'yield', not 'return' ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http

Re: [Tutor] python help!

2013-02-09 Thread Peter Otten
Ghadir Ghasemi wrote: Hi guys can you tell me what is wrong with the second part of this code(elif choice == '2'). When I type something other than 0-255, it correctly asks again for an input but when I enter a number from 0-255 it does nothing : It doesn't do nothing, it keeps running the

Re: [Tutor] help with running perl script that writes to a text file

2013-02-06 Thread Peter Otten
3n2 Solutions wrote: Hello, I want to automate the following manual process from DOS promp: c:/scripts/perlperl fix.pl base.gtx base.txt Here is my python script: path=c:/scripts/perl/ subprocess.call(['perl','fix.pl','base.gtx base.txt',path]) I also tried this alternative:

Re: [Tutor] changing unicode to ascii

2013-01-30 Thread Peter Otten
Benjamin Fishbein wrote: I was trying to write text to a file and got the following error: UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 5495: ordinal not in range(128) I tried several things I found online, such as: text.encode(ascii, ignore) which gave

Re: [Tutor] using ranges with argparse()

2013-01-28 Thread Peter Otten
Kurt Lieber wrote: Hi -- brand new to python, but trying to write a simple script that takes command line arguments. One of the arguments needs to test if a value is a) an integer and b) within a stated range. I currently have: parser.add_argument(-f, --floor, default=6000, help=floor is

Re: [Tutor] Cheese shop tutorial mirror

2013-01-26 Thread Peter Otten
Per Fagrell wrote: I'm interested in uploading a module to pypi, but with the python wiki down after the hack there's no access to the Cheese shop tutorial. Does anyone have a mirror or reasonable facsimile that could be used until the wiki is back on-line and repopulated? You're lucky, the

Re: [Tutor] Calculate hours

2013-01-25 Thread Peter Otten
शंतनू wrote: s = [sum(x) for x in matrix] for q in sorted([(x,y) for x,y in enumerate(s)], key=operator.itemgetter(1)): print(Employee %d has worked %d hours % (q[0], q[1])) A minor simplification: s = (sum(x) for x in matrix) for q in sorted(enumerate(s), key=operator.itemgetter(1)):

Re: [Tutor] String formatting expression g conversion type case.

2013-01-24 Thread Peter Otten
Krupkina Lesya Olegovna wrote: Python outputs decimal as declared as but with more significant digits than default value of 6 - if integer part of the decimal is equal to zero. %#g%0.3 '0.30' In this context significant digits are the first non-zero digit and any digits (including zero)

Re: [Tutor] list of references to object properties

2013-01-18 Thread Peter Otten
Jose Amoreira wrote: Hello Suppose I have a list l_obj of similar objects. Is there any way I can generate a list l_prp of references to a given property of those objects in such a way that, if change the value of one element in l_prp, the corresponding object in l_obj gets its property

Re: [Tutor] Problem with calling class methods stored in a list

2013-01-11 Thread Peter Otten
Tobias M. wrote: Am 10.01.2013 15:15, schrieb Peter Otten: Of course handle_1_42() is not exactly the method name one would hope for. You could, again, strive for simplicity and add a lookup table that maps protocol tuples to function /names/ , but as simplicity doesn't seem to be your cup

Re: [Tutor] Problem with calling class methods stored in a list

2013-01-10 Thread Peter Otten
Tobias Marquardt wrote: Hello, I have a class with some class methods that are also stored in a list. Now I have a problem calling these methods. Essentially the relevant code looks like this: class MyClass(object): @classmethod def foo(cls): cls.method_list[0]()

Re: [Tutor] Problem with calling class methods stored in a list

2013-01-10 Thread Peter Otten
Tobias M. wrote: Peter Otten wrote: Build the list outside the class: MyClass.method_list = [MyClass.bar] Thanks, that is a solution. But I don't really like to put the list outside the class as it is strongly related to the class and not used outside. Actually in my code it's not a list

Re: [Tutor] Problem with calling class methods stored in a list

2013-01-10 Thread Peter Otten
Tobias M. wrote: Am 10.01.2013 13:48, schrieb Peter Otten: If you adopt this approach you might omit the lookup dictionary and use getattr(): ... @classmethod ... def handle_foo(cls): print Hello from B.handle_foo() ... @classmethod ... def get_handler(cls, packet_type

Re: [Tutor] .strip question

2013-01-09 Thread Peter Otten
richard kappler wrote: I have a sort of a dictionary resulting from psutil.disk_usage('/') that tells me info about my hard drive, specifically: usage(total=147491323904, used=62555189248, free=77443956736, percent=42.4) I'm having a bit of a brain fudge here and can't remember how to

Re: [Tutor] writing effective unittests

2013-01-03 Thread Peter Otten
Steven D'Aprano wrote: Notice that tests are not necessarily definitive. I haven't tested that spam(n) returns a string for every imaginable integer n, because there are too many. Instead, I just test a small, representative sample. Likewise I haven't tested that spam() might succeed when

Re: [Tutor] List Comprehension Syntax

2012-12-23 Thread Peter Otten
Mario Cacciatore wrote: Hey everyone, I am having a very hard time understanding the list comprehension syntax. I've followed the docs and could use some guidance from the fine folks here to supplement my findings. If someone wouldn't mind replying back with an example or two, with some

Re: [Tutor] Tutor Digest, Vol 106, Issue 42

2012-12-18 Thread Peter Otten
Alan Gauld wrote: On 18/12/12 07:56, Peter Otten wrote: myMain. The c file input content might change in the future like different values assigned, added fields in the MainStruct, etc. Also I am not permitted to change the c file. How about running the C source with an added dump

Re: [Tutor] sys.getfilesystemencoding()

2012-12-18 Thread Peter Otten
Albert-Jan Roskam wrote: I am trying to write a file with a 'foreign' unicode name (I am aware that this is a highly western-o-centric way of putting it). In Linux, I can encode it to utf-8 and the file name is displayed correctly. In windows xp, the characters can, apparently, not be

Re: [Tutor] Tutor Digest, Vol 106, Issue 42

2012-12-17 Thread Peter Otten
Marefe Serentas wrote: On 12/18/2012 12:38 AM, tutor-requ...@python.org wrote: Re: Get the structure values from a c file I apologize for some syntax errors in my c file. I would like to correct my mistakes and append some lines in the c file to make it clearer. #define max (3)

Re: [Tutor] Better way to insert items into a list

2012-12-09 Thread Peter Otten
Mike wrote: Hello everyone, I was wondering if someone could show me a better way to achieve what I am trying to do. Here is my test code: d=[] c=00 a=A,B,C,D b=a.split(',') for item in b: d.append(item) d.append(c) print tuple(d)

Re: [Tutor] how to struct.pack a unicode string?

2012-11-30 Thread Peter Otten
Albert-Jan Roskam wrote: How can I pack a unicode string using the struct module? If I simply use packed = struct.pack(fmt, hello) in the code below (and 'hello' is a unicode string), I get this: error: argument for 's' must be a string. I keep reading that I have to encode it to a utf-8

Re: [Tutor] stop a loop after precise amount of time

2012-11-25 Thread Peter Otten
Saad Javed wrote: import time running = True while running: print 'yes' time.sleep(10) This will print 'yes' after every 10s. I want to print 'yes' for 10s, then quit. Then combine the two techniques, the busy waiting loop with sleeping for a shorter amount of time: import

Re: [Tutor] Beginner's question

2012-11-23 Thread Peter Otten
Steven D'Aprano wrote: On 23/11/12 01:56, Peter O'Doherty wrote: This code appears to work although it's very cumbersome. Is there a better way to do it? Of course it is cumbersome, that's because of the artificial constraints set on the problem. I quote from your description Indeed

[Tutor] Beginner's question

2012-11-22 Thread Peter O'Doherty
the simple operators and keywords above, no functions, lists or any other form of iteration. (It's from p. 16 of Introduction to Computation and Programming Using Python, and no, it's not homework!) Many thanks, Peter ___ Tutor maillist - Tutor

Re: [Tutor] Beginner's question

2012-11-22 Thread Peter O'Doherty
Hi Varun, Thanks for your reply. I agree the problem is logic - but how can one inspect one number using if x%2 == 0 and then compare it to two other numbers which should at the same time be checked for oddness, just using the basic constructs? Thanks, Peter On 11/22/2012 02:06 PM, Varun

Re: [Tutor] Beginner's question

2012-11-22 Thread Peter O'Doherty
On 11/22/2012 03:17 PM, Walter Prins wrote: Hi Peter, On 22 November 2012 12:55, Peter O'Doherty m...@peterodoherty.net mailto:m...@peterodoherty.net wrote: Hi list, Firstly, apologies for the low-level nature of this question - it's really quite basic but I don't seem

Re: [Tutor] Beginner's question

2012-11-22 Thread Peter O'Doherty
Many, many thanks to all those who replied to my question. I hope the next time I post, it will be with something more advanced. Judging by the volume of replies, is it fair to say that this problem was much too advanced for page 16 of an introductory text? Best wishes, Peter

Re: [Tutor] Tkinter, how to retrieve information about an object on canvas

2012-11-15 Thread Peter Otten
Matheus Soares da Silva wrote: Hello, I would like to be able to get information from a Tkinter canvas object. (color, width, tags, root points, etc), I wrote the following function that, with a canvas bind, returns me the widget that has been clicked on, the widget is returned as a tuple

Re: [Tutor] run with default value if input not given

2012-10-29 Thread Peter Otten
Saad Javed wrote: Hi, #!/usr/bin/env python import sys x = 'Saad is a boy' def main(x): a = [] b = x.split(' ') for item in b: a.append(item) print a if __name__ == '__main__': x = sys.argv[1] main(x) How can I make this program run with the default value of x if I don't

Re: [Tutor] greater precision?

2012-10-29 Thread Peter Otten
John Collins wrote: Hi, OS: XP Py: 2.7.2 I am running some old scripts, not written by me, that produce substantial calculated values data as decimals, 12 significant figures. AFAIK, the keys calls are; [On modern hardware] Python uses IEEE 754 double-precision

Re: [Tutor] Python Pipes

2012-10-29 Thread Peter Otten
Ganesh Manal wrote: Please give me sample python program that works with python31 $ touch sample.py $ cat sample.py $ python3 sample.py So the minimal python3 program is an empty file. ___ Tutor maillist - Tutor@python.org To unsubscribe or change

Re: [Tutor] map() practice

2012-10-21 Thread Peter Otten
Malcolm Newsome wrote: Hello all, I looked at map() tonight. I think I have a decent understanding now of how it works. However, I'm wondering when it is most commonly used in the real world and if you could provide some examples (I like to do a lot of web stuff...it that helps with

Re: [Tutor] ctypes question

2012-10-10 Thread Peter Otten
Albert-Jan Roskam wrote: I have a program that reads and writes files using ctypes. When I want it to read AND write (e.g. read a file, select some stuff and write that), the library returns a 'read-open' error. I think that the pointer to the file handle for read and write point to the same

Re: [Tutor] a question about maxint

2012-10-02 Thread Peter Otten
Katya Stolpovskaya wrote: I have this error: from sys import * maxint Traceback (most recent call last): File pyshell#4, line 1, in module maxint NameError: name 'maxint' is not defined What does it mean and how to deal with it? You are probably using Python 3 which doesn't have

Re: [Tutor] lazily decorated sort

2012-09-28 Thread Peter Otten
Chris Smith wrote: I'm wondering if anyone has seen or knows of a good way to do a lazily decorated sort. I was reading about how good the DSU (decorate, sort, undecorate) approach is but the problem that we are running into in SymPy is that we want to get by with a fast hash sort if

Re: [Tutor] lazily decorated sort

2012-09-28 Thread Peter Otten
eryksun wrote: On Fri, Sep 28, 2012 at 8:17 AM, Peter Otten __pete...@web.de wrote: def make_key(keys): @total_ordering class Key(object): def __init__(self, value): self._keys = keys(value) self._cached = [] Using a generator/iterator to pump

Re: [Tutor] Relative import help

2012-09-22 Thread Peter Otten
Matthew Ngaha wrote: i have an assignment from a book to practice implementing relative imports. it gave a very clear and easy to follow explanation, but my results are proving the instructions are wrong. here's what i have tried. my folder structure: Project / __init__.py

Re: [Tutor] index of elements in numpy array

2012-09-14 Thread Peter Otten
Bala subramanian wrote: Thank you all for the answer. Below, i have pasted a sample code that shows what i am intending to do. The code fails at line 13 as numpy array dnt have a index attribute. 1 #!/usr/bin/env python 2 import numpy as np 3 4

Re: [Tutor] (2.7.3) Inexplicable change of type

2012-09-14 Thread Peter Otten
Ray Jones wrote: source = source.remove('') list.remove() modifies the list in-place and therefore by convention returns None: source = [one, , three] source.remove() source ['one', 'three'] ___ Tutor maillist - Tutor@python.org To

Re: [Tutor] Help with class in class

2012-09-09 Thread Peter Otten
leam hall wrote: I'm in the O'Reilly Python 2 class, so pointers to learning would be better than just answers, please. My brain is a bit slow but needs to go forward. Line 16 calls line 31. Rather, it is supposed to. I'm trying to figure out why I get File ./ch8_project.py, line 31,

Re: [Tutor] group txt files by month

2012-09-08 Thread Peter Otten
questions anon wrote: Hello All, it has been a few months since I have used this and I have only just realised I am having problems with leap years. each time I get to February of a leap year my program stops, Does it throw an exception (if so, post the traceback) or does it just terminate?

Re: [Tutor] Formatting questions regarding datetime.isoformat()

2012-09-06 Thread Peter Otten
staticsafe wrote: Hello, I am running Python 2.6.6 on a Debian Squeeze system. I am using two modules in this bit of code - datetime and python-tvrage (available on pypy here: http://pypi.python.org/pypi/python-tvrage/). My goal is to find the time remaining until a certain show airs.

Re: [Tutor] math description

2012-09-06 Thread Peter Otten
damjan kuzmic wrote: i would like to know how to write a formula that in excell looks like this: A / EXP(-LN(2) * t) import math A = 1.23 t = 4.56 Literally (math.log is the natural logarithm): A / math.exp(-math.log(2) * t) 29.013618196288864 However, exp(-x) == 1 / exp(x) and

Re: [Tutor] python 2.7.1

2012-09-06 Thread Peter Otten
john wrote: print hello world #this is just something to say /Users/jonathan/Documents/hello.py File stdin, line 1 /Users/jonathan/Documents/hello.py ^ SyntaxError: invalid syntax what am i doing wrong? The prompt indicates that you have already started the interactive

Re: [Tutor] Making big 'uns into little 'uns

2012-09-06 Thread Peter Otten
Ray Jones wrote: I have a multiple 'if' expression that I need to drastically reduce in size, both for readability and to keep errors from creeping in. For example, I would like to have the variable 'test' point to the a location 'grid[rcount-1][ccount-1]' so that everywhere I would use

Re: [Tutor] Unicode? UTF-8? UTF-16? WTF-8? ;)

2012-09-05 Thread Peter Otten
Ray Jones wrote: I have directory names that contain Russian characters, Romanian characters, French characters, et al. When I search for a file using glob.glob(), I end up with stuff like \x93\x8c\xd1 in place of the directory names. I thought simply identifying them as Unicode would clear

Re: [Tutor] Unicode? UTF-8? UTF-16? WTF-8? ;)

2012-09-05 Thread Peter Otten
Ray Jones wrote: You can work around that by specifying the appropriate encoding explicitly: $ python tmp2.py iso-8859-5 | cat � $ python tmp2.py latin1 | cat Traceback (most recent call last): File tmp2.py, line 4, in module print uЯ.encode(encoding) UnicodeEncodeError: 'latin-1' codec

Re: [Tutor] Unicode? UTF-8? UTF-16? WTF-8? ;)

2012-09-05 Thread Peter Otten
Ray Jones wrote: On 09/05/2012 04:52 AM, Peter Otten wrote: Ray Jones wrote: But doesn't that entail knowing in advance which encoding you will be working with? How would you automate the process while reading existing files? If you don't *know* the encoding you *have* to guess

Re: [Tutor] 2.7.3 generator objects

2012-09-02 Thread Peter Otten
Steven D'Aprano wrote: On 02/09/12 17:09, Ray Jones wrote: But didn't I read somewhere that you can reset an iterator to go through the whole process again? In general, no. The usual way to reset an iterator is to re-create it. walker = os.walk(/home/steve/start) # ... process

Re: [Tutor] making len() and __len__ return a non-int

2012-09-02 Thread Peter Otten
Albert-Jan Roskam wrote: If I implement __len__ in my own class, does it really have to return an int? Is there no way around this (other than modifying the source code of python itself ;-) It would be nice if len(Example(row, col)) would return a dictionary, or a two-tuple (see code below).

Re: [Tutor] checking input parameters

2012-08-31 Thread Peter Otten
Bala subramanian wrote: I use the following way to check for the input parameters. I would like to know if there is a any better way to show or describe the script usage. So when the user just runs it without any input params., the program shd not execute but just shows the documentation.

Re: [Tutor] Why begin a function name with an underscore

2012-08-30 Thread Peter Otten
Steven D'Aprano wrote: On 28/08/12 20:00, Peter Otten wrote: [...] The differences to _validate_int() are subtle: class S(str): ... def __eq__(self, other): return True ... def __ne__(self, other): return False ... def __add__(self, other): return self ... vi(S(42

Re: [Tutor] Why begin a function name with an underscore

2012-08-30 Thread Peter Otten
Steven D'Aprano wrote: On 28/08/12 19:02, Peter Otten wrote: Personally, I'm a big fan of ducktyping, so I would probably remove the check completely and live with the consequences: pyprimes._validate_int = lambda x: None pyprimes.isprime_naive(8.5) True garbage-in, garbage-out -- so

Re: [Tutor] Why begin a function name with an underscore

2012-08-28 Thread Peter Otten
Timo wrote: Op 28-08-12 10:06, Richard D. Moores schreef: On Tue, Aug 28, 2012 at 12:13 AM, Jerry Zhang jerry.scofi...@gmail.com wrote: 2012/8/28 Richard D. Moores rdmoo...@gmail.com On Mon, Aug 27, 2012 at 6:33 PM, Japhy Bartlett ja...@pearachute.com wrote: something like: def

Re: [Tutor] Why begin a function name with an underscore

2012-08-28 Thread Peter Otten
Richard D. Moores wrote: On Tue, Aug 28, 2012 at 1:21 AM, Timo timomli...@gmail.com wrote: Op 28-08-12 10:06, Richard D. Moores schreef: What if I wanted 3., 1234., etc. to be considered ints, as they are by _validate_int() ? isinstance(3., (int, float)) True Because 3. is a float,

Re: [Tutor] Why begin a function name with an underscore

2012-08-28 Thread Peter Otten
eryksun wrote: On Tue, Aug 28, 2012 at 6:00 AM, Peter Otten __pete...@web.de wrote: Anyway here's an alternative implementation: def vi(x): ... if not isinstance(x, numbers.Number): ... raise TypeError ... if not int(x) == x: ... raise ValueError You

Re: [Tutor] Installing modules with easy_install

2012-08-28 Thread Peter Otten
Ray Jones wrote: I'm working on another Python replacement for a Bash script, and I ran into a need for enhanced time zone functions. Following directions I found on a web site, I did the following: # easy_install --upgrade pytz Searching for pytz Reading

Re: [Tutor] Installing modules with easy_install

2012-08-28 Thread Peter Otten
Ray Jones wrote: On 08/28/2012 11:06 AM, Peter Otten wrote: Ray Jones wrote: I'm working on another Python replacement for a Bash script, and I ran into a need for enhanced time zone functions. Following directions I found on a web site, I did the following: # easy_install --upgrade pytz

Re: [Tutor] reason(s) for trailing comma in dict declarations

2012-08-25 Thread Peter Otten
aklei...@sonic.net wrote: Part of a previous post: Here's the style I'd use: combos = { 0: 'id', 2: 'country', 3: 'type', 5: 'lat', 6: 'lon', 12: 'name', } Put each entry on its own line, indented by two spaces, and leave a trailing comma on the last entry. The

Re: [Tutor] list comprehension, testing for multiple conditions

2012-08-24 Thread Peter Otten
Pete O'Connell wrote: Hi, I have tried to simplify things and am running into a bit of trouble. What i am really trying to do is: Keep all the lines starting with v and then delete those lines whose modulus 5 don't equal zero I have written it like this which seems to take a really long

Re: [Tutor] better way to write this code

2012-08-24 Thread Peter Otten
Norman Khine wrote: I have this code (http://pastie.org/4575790) which pulls data from a list and then modifies some of the values such as the 'yield' entry, which has entries like: 21 15 le; 1000 le; 20 2.2 - 30 so that they are cleaned up. can the code be improved further? It

Re: [Tutor] how to split/partition a string on keywords?

2012-08-24 Thread Peter Otten
Jared Nielsen wrote: I implemented eryksun's suggestion and used the replace() method. But, playing around with it, what I discovered is that it won't store the change. For example, when the input text is, Ham and cheese or chicken and waffles: #!/usr/bin/python text = raw_input(Enter

Re: [Tutor] What are all those letters after terminal commands?

2012-08-23 Thread Peter Otten
Cecilia Chavana-Bryant wrote: Hola, I'm going through the 'Command line crash course' by Zed Shaw, thanks to the people that recommended this book, its quite a good course, I can see what the author was going for with the title but if it wasn't for your recommendations, it would have put

Re: [Tutor] Error message...

2012-08-23 Thread Peter Otten
Victoria Homsy wrote: Sorry to bother you with a beginner's problem again... This is the place for beginners. I have tried to write a program that can check if a string is a palindrome. My code is as follows: def isPalindrome(s): if len(s) = 1: return True else: return s(0)

Re: [Tutor] Python 3.2: processing text files in binary mode, because I want to remove carriage returns and line feeds...

2012-08-23 Thread Peter Otten
Flynn, Stephen (L P - IT) wrote: Python 3.2, as in the subject, although I also have 2.7 on this machine too. I have some data which contains text separated with field delimiters (|~) and a record terminator (||)

Re: [Tutor] list comprehension, testing for multiple conditions

2012-08-22 Thread Peter Otten
Pete O'Connell wrote: Hi I am trying to parse a text file and create a list of all the lines that don't include: vn, vt or are empty. I want to make this as fast as possible because I will be parsing many files each containing thousands of lines. I though I would give list comprehensions a

Re: [Tutor] list comprehension, testing for multiple conditions

2012-08-22 Thread Peter Otten
Pete O'Connell wrote: [Please don't to-post. Clip all text of previous posts except the portion relevant to your question] Hi. The next step for me to parse the file as I want to is to change lines that look like this: f 21/21/21 22/22/22 24/24/23 23/23/24 into lines that look like this: f

Re: [Tutor] Escaping globs for glob.iglob()

2012-08-21 Thread Peter Otten
Ray Jones wrote: The code: curDir = os.getcwd() znDir = shutil.abspath('../') baseDir = shutil.abspath('../../') Files = glob.iglob(os.path.join(znDir, '*')) print Files for moveFile in Files: print moveFile shutil.move(moveFile, curDir) Nothing happens. The

Re: [Tutor] Confusion regarding the 'from' statement

2012-08-15 Thread Peter Otten
Mazhar Hussain wrote: thanks alot for the help, was really confused with this. Well what ure trying to say is that even when a module object is deleted from the global namespace of a module, a reference of it is still present in the sys.modules dict? Yes, adding the reference to the

Re: [Tutor] output not in ANSI, conversing char set to locale.getpreferredencoding()

2012-08-14 Thread Peter Otten
leon zaat wrote: I get the error: UnicodeDecodeError: 'ascii' codecs can't decode byte 0xc3 in position 7: ordinal not in range(128) for the openbareruimtenaam=u'' + (openbareruimtenaam1.encode(chartype)) line. The error message means that database.select() returns a byte string.

Re: [Tutor] Confusion regarding the 'from' statement

2012-08-14 Thread Peter Otten
Mazhar Hussain wrote: Im new to python and theres something thats bothering me for quite a time. I read in 'Learning Python' by Mark Lutz that when we use a 'from' statement to import a name present in a module, it first imports the module then assigns a new name to it(i.e. the name of the

Re: [Tutor] pickle problems

2012-08-12 Thread Peter Otten
Richard D. Moores wrote: f = open(factors.txt, 'rb') data = pickle.load(f) f.close f.close looks up the close method but doesn't invoke it; you need f.close(). Alternatively use a with statement: with open(factors.txt, rb) as f: data = pickle.load(f) This will close the file even if an

Re: [Tutor] help -Global name xxxxxxxx is not definied.

2012-08-09 Thread Peter Otten
leon zaat wrote: Hello everyone, Can anybody help me with this problem. Ik have a program that i' am modifying. Ik build a function to export data to a csv file. I tried the functions over different parts, that needed to be extracted. The parts on it self worked fine. Now I put all

Re: [Tutor] Unzip a zipfile, then unzip the zipfiles within the original zip

2012-08-08 Thread Peter Otten
Gregory Lund wrote: Not too sure on protocol either, sorry if this email is out of line. You have to hit [Reply all] in your email client for your answer to go to the list instead of just me. When you answer a post put your reply after the relevant part of the quoted post (don't top-post).

Re: [Tutor] How to import a few modules when I enter python?

2012-08-07 Thread Peter Otten
Santosh Kumar wrote: Hello there, I have a few scripts that I made to experiment with, I have to import them everytime I enter the Python shell. The scripts are in `/home/username/workshop/` (this directory has also some non .py files) directory. Is there a way I can import them as soon as

Re: [Tutor] Built in functions

2012-08-07 Thread Peter Otten
Dane Saltzman wrote: I'm new to python and I was wondering if you could tell me how I would: first, define a function,distance_from_zero, with one parameter (choose any parameter name you like). Second, have that function do the following: 1. Check the type of the input it receives. 2.

Re: [Tutor] Question about reading from a file.

2012-08-07 Thread Peter Otten
Brad Dutton wrote: I recently discovered how to read from a file but I've having some trouble with it. I made a short example program that goes like this: 1. fob = open('c:/python27/a.txt', 'r') 2. 3. print fob.read() 4. print fob.read() When it runs it returns this:

Re: [Tutor] Unzip a zipfile, then unzip the zipfiles within the original zip

2012-08-07 Thread Peter Otten
Gregory Lund wrote: [For improved readability please avoid # prefixes for the parts of your post that are not comments in snippets of python code] neophyte .py/pyTutor user. Welcome. I am also a university GIS lecturer. My students submit their lab assignments (zipped up into one zipfile)

Re: [Tutor] Code Review?

2012-08-06 Thread Peter Otten
Brian Carpio wrote: Hi, Hopefully I am allowed to ask this here. I am pretty new to python I've only been writing code for about 6 months now strictly for system administration purposes; however I have now decided to write something real that others might benefit from but I am looking for

Re: [Tutor] filelist

2012-08-05 Thread Peter Otten
richard kappler wrote: Starting to work through Programming Computer Vision with Python in my -summer of learning python- quest. As I read through the intro to the PIL library, I came across the below code. When I read it, I said to my self I don't see how that calls a set of files, there's

Re: [Tutor] Recursive assignment in nested lists

2012-08-04 Thread Peter Otten
Alonzo Quijote wrote: Is there a way to define a function which takes a list (of lists), a position specified by a list of integers [i0,i1,...,in], and a value and returns the result of setting list[i0][i1]...[in]=value The following function works for positions up to length

Re: [Tutor] sqlite3 Dilemma

2012-07-30 Thread Peter Otten
Khalid Al-Ghamdi wrote: I am a teacher at an industrial training center. We have to conduct hands-on exams (fixing pumps, etc). I review all the test schedules for all the students (made by other teachers) to make sure there are no clashes due to lack of ample supply of equipment or tools.

Re: [Tutor] Flatten a list in tuples and remove doubles

2012-07-29 Thread Peter Otten
Mark Lawrence wrote: On 29/07/2012 00:53, Alan Gauld wrote: On 29/07/12 00:12, Francesco Loffredo wrote: Every time this happens, I have to admit that I'm a newbie and I've still got a lot to learn about Python. Especially about its wonderful standard library. Don't worry, I've been using

Re: [Tutor] Flatten a list in tuples and remove doubles

2012-07-29 Thread Peter Otten
eryksun wrote: On Sun, Jul 29, 2012 at 7:21 AM, Peter Otten __pete...@web.de wrote: If you don't have to deal with large datasets many of its functions can easily be emulated with lists and loops though. As an example here's the grouping with a plain vanilla dict: groups = {} for item

Re: [Tutor] Recreating the help module

2012-07-25 Thread Peter Otten
M Nickey wrote: Hey all, I'm trying to recreate the 'help' on various modules that are available. So far, I have a bit of code and it seems to be working for the most part. I can get the modules available but I also want to be able to print the information that is available for each

Re: [Tutor] Getting name of Widget for event.widget?

2012-07-25 Thread Peter Otten
Leam Hall wrote: Note that this is for an on-line class so I'd appreciate pointers to what I need to read or think about more than the answer out right. Using Python 3 on Linux, is there a way to get the name of a widget instead of numeric representations in event.widget? What I tried

Re: [Tutor] Creating a dictionary on user filter

2012-07-20 Thread Peter Otten
Mike Nickey wrote: What I have is this: firstList = ['a', 'b', 'c'] secondList = [1,2,3] thirdList = [1.20, 1.23, 2.54] What I am looking for is something like this for output: {'a': [1, 1.20], 'b': [2, 1.23], 'c': [3, 2.54]} To get this combine second and third into the list of values

Re: [Tutor] Simple text file processing using fileinput module. Grabbing successive lines failure

2012-07-03 Thread Peter Otten
Flynn, Stephen (L P - IT) wrote: Tutors, Whilst having a play around with reading in textfiles and reformatting them I tried to write a python 3.2 script to read a CSV file, looking for any records which were short (indicating that the data may well contain an embedded CR/LF. I've

Re: [Tutor] Python XML for newbie

2012-07-02 Thread Peter Otten
Sean Carolan wrote: Thank you, this is helpful. Minidom is confusing, even the documentation confirms this: The name of the functions are perhaps misleading But I'd start with the etree tutorial (of which there are many variations on the web): Ok, so I read through these tutorials

Re: [Tutor] Issue with classes

2012-06-12 Thread Peter Otten
Bod Soutar wrote: Hi, I am having some difficulty calling a class method from a different class. When I run the attached script like this python cheatsheet.py --list C:\python cheatsheet.py --list done here? Traceback (most recent call last): File cheatsheet.py, line 167, in module

Re: [Tutor] Unexpected result of division by negative integer, was: (no subject)

2012-06-02 Thread Peter Otten
Jason Barrett wrote: [Jason, please use reply all instead of sending a private mail. Your answer will then appear on the mailing list and other readers get a chance to offer an alternative explanation.] In python, why does 17/-10= -2? Shouldn't it be -1?

Re: [Tutor] (no subject)

2012-06-01 Thread Peter Otten
Jason Barrett wrote: In python, why does 17/-10= -2? Shouldn't it be -1? http://docs.python.org/faq/programming.html#why-does-22-10-return-3 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options:

Re: [Tutor] sqlite3 question

2012-05-24 Thread Peter Otten
Alan Gauld wrote: On 23/05/12 17:11, Khalid Al-Ghamdi wrote: I'm using Python 3 and have read that you need sqlite to be installed to use the sqlite3 module, but when it is imported it seems to work ok. The info is wrong. Unlike other SQL databases SQLite is not a server based system so

Re: [Tutor] odd behavior when renaming a file

2012-05-09 Thread Peter Otten
Joel Goldstick wrote: import os def pre_process(): if os.path.isfile('revelex.csv'): os.rename('revelex.csv', 'revelex.tmp') print Renamed ok else: print Exiting, no revelex.csv file available exit() out_file = open('revelex.csv', 'w') #

Re: [Tutor] error when using using subprocess.popen in Python wrapper script

2012-05-07 Thread Peter Otten
Rogelio wrote: If I want to write this command to a file, would this be the right format? * import subprocess (all my variables defined okay) perl_script=subprocess.call(['perl',perl_prog,ipfile,cmd,user,timeout,]) log=open('/tmp/pythonOutput.txt',w)

Re: [Tutor] looking for some advice

2012-05-07 Thread Peter Otten
Chris Hare wrote: Hello Everyone: Here is what I am trying to do: I have a window which has a row of buttons on it. Below the buttons is a label frame. Depending upon which button they push, I want to change the widgets in the label frame. I can add widgets now with no problem.

Re: [Tutor] Sorting the parts of a dictionary into a list

2012-05-06 Thread Peter Otten
Jacob Bender wrote: Dear tutors, I'm trying to create a neural network program. Each neuron is in a dictionary and each of its connections and their strengths are in a nested dictionary. So {0:{1:4, 2:5}}, 1:{0:6}, 2:{1:2}} would mean that neuron 0 is connected to neuron 1 with a strength

Re: [Tutor] the regex boundary about chinese word

2012-05-04 Thread Peter Otten
goog cheng wrote: Hi, I got this problem : #!python # -*- coding: utf-8 -*- import re p = re.compile(ur'\bc123\b') print '**',p.search('no class c123 at all').group() p = re.compile(ur'\b\u7a0b\u6770\b') print ur'\u7a0b\u6770' print '',p.search(' 程杰 abc'.decode('utf8')) why

<    5   6   7   8   9   10   11   12   13   14   >