From kent37 at tds.net Sat Nov 1 00:05:54 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 31 Oct 2008 19:05:54 -0400 Subject: [Tutor] mergin two csv files based on a common join In-Reply-To: <24055736.1225490697083.JavaMail.root@ps28> References: <24055736.1225490697083.JavaMail.root@ps28> Message-ID: <1c2a2c590810311605u72388599qa82c1f3bcae43294@mail.gmail.com> On Fri, Oct 31, 2008 at 6:04 PM, qsqgeekyogdty at tiscali.co.uk wrote: > Hello again, > Thanks for the replies on my previous post, but I have a different > problem now and don't see how to deal with it in a smooth way. > > I have two csv files where: > > 1.csv > > "1", "text", "aa" > "2", "text2", "something else" > "3", "text3", "something else" > > 2.csv > > "text", "xx" > "text", "yy" This line doesn't appear in the output, why not? > "text3", "zz" > > now I would like to have an output like: > > "1", "text", "aa" > "1", "text", "xx" > "2", "text2", "something else" > "3", "text3", "something else" > "3", "text3", "zz" > > I basically need to merge the two csv files based on the column-2 Assuming that at least one file does not repeat values in the key field: Read one of the csv files and create a dict whose keys are the common field and values are the entire line containing the field. Read the other csv file. Look up the key field in the dict to get the values from the other file. Output as appropriate. If the keys repeat in both files, make a dict whose values are a list of all lines containing the key. collections.defaultdict(list) can help with this. Kent From srilyk at gmail.com Sat Nov 1 00:09:24 2008 From: srilyk at gmail.com (W W) Date: Fri, 31 Oct 2008 17:09:24 -0600 Subject: [Tutor] mergin two csv files based on a common join In-Reply-To: <24055736.1225490697083.JavaMail.root@ps28> References: <24055736.1225490697083.JavaMail.root@ps28> Message-ID: <333efb450810311609j167112d8le126bb31cdca481c@mail.gmail.com> On Fri, Oct 31, 2008 at 4:04 PM, qsqgeekyogdty at tiscali.co.uk < qsqgeekyogdty at tiscali.co.uk> wrote: > Hello again, > Thanks for the replies on my previous post, but I have a different > problem now and don't see how to deal with it in a smooth way. I'd probably use a dict with a list as the value: > > "1", "text", "aa" > "1", "text", "xx" > "2", "text2", "something else" > "3", "text3", "something else" > "3", "text3", "zz" > this is untested, and it's been a while since I've messed with the CSV module, but something like this should work, if you split the first file into 3 lists and the 2nd into two lists: for col1, col2, col3 in zip(inCol1, inCol2, inCol3): try: mydict[(col1, col2)] mydict[(col1, col2)].append(col3) except KeyError: mydict[(col1, col2)] = [col3] I think that should work. HTH, 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 -------------- next part -------------- An HTML attachment was scrubbed... URL: From roadierich at googlemail.com Sat Nov 1 00:55:11 2008 From: roadierich at googlemail.com (Rich Lovely) Date: Fri, 31 Oct 2008 23:55:11 +0000 Subject: [Tutor] Problem formatting raw_input In-Reply-To: <490B536B.1060300@gmail.com> References: <490A758D.2080103@internode.on.net> <490A9670.1000400@internode.on.net> <490B536B.1060300@gmail.com> Message-ID: <551664B0-A10C-453D-9277-A26BF180F90F@googlemail.com> The try: except: clauses allow for someone typing something like 'spam' when the program expects a number. It stops the program dying with an error message. --- Richard "Roadie Rich" Lovely Part of the JNP|UK Famille www.theJNP.com --- (Sent from my iPod - please allow for any typos: it's a very small keyboard) On 31 Oct 2008, at 18:50, bob gailer wrote: > Peter Anderson wrote: >> Dj Gilcrease wrote: >>> The simple answer is to just use chr(int(inNum)) >>> >>> though here is how I would do it >>> >>> def convert_string_to_int(strInt): >>> try: >>> return int(strInt) >>> except ValueError: >>> return 0 >>> >>> def getNumbers(output): >>> inNum = raw_input("Please enter an ASCII number\n(33 - 126, >>> [Enter] to quit): ") >>> ascii_num = convert_string_to_int(inNum) >>> if ascii_num >= 33 and ascii_num <=126: >>> output.append(chr(ascii_num)) >>> getNumbers(output) > > I would avoid recursion. Save that for recursive algorithms. An > ordinary loop is easier to read/maintain and you will not run out of > recursion depth. Also give user a meaningful error message. > > while True: > inNum = raw_input("Please enter an ASCII number\n(33 - 126, > [Enter] to quit): ") > if not inNum: > break > ascii_num = convert_string_to_int(inNum) > if ascii_num >= 33 and ascii_num <=126: > output.append(chr(ascii_num)) > else: > print "Input must be an integer in range 33..126" > >>> >>> if __name__ == '__main__': >>> print "This script converts a sequence of ASCII numbers" >>> print "into the string of text that it represents." >>> print >>> output = [] >>> getNumbers(output) >>> print output >>> >>> Dj Gilcrease >>> OpenRPG Developer >>> ~~http://www.openrpg.com >> Dj, >> >> Thanks for the suggestions; both work perfectly. Can I ask a >> supplementary question please? >> >> In the def convert_string... function why do you include the >> "except ValueError: / return 0" clause? > try: must be followed by except or finally. > > -- > Bob Gailer > Chapel Hill NC 919-636-4239 > > When we take the time to be aware of our feelings and needs we have > more satisfying interatctions with others. > > Nonviolent Communication provides tools for this awareness. > > As a coach and trainer I can assist you in learning this process. > > What is YOUR biggest relationship challenge? > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From roadierich at googlemail.com Sat Nov 1 01:03:49 2008 From: roadierich at googlemail.com (Rich Lovely) Date: Sat, 1 Nov 2008 00:03:49 +0000 Subject: [Tutor] how to call a binding method from an imported module In-Reply-To: <30629396.1225484212200.JavaMail.root@mswamui-swiss.atl.sa.earthlink.net> References: <30629396.1225484212200.JavaMail.root@mswamui-swiss.atl.sa.earthlink.net> Message-ID: <8F38CEAC-FFDB-4091-A142-21CAF9AE4DD9@googlemail.com> Is TempDef defined within a class block? All functions defined within a class take self as the first (or only) argument. That appears to be the usual cause of that error... Otherwise, you can say def tempDef(*args): #stuff Or just def tempDef(args): #stuff Seeing as it only receives one arguement. --- Richard "Roadie Rich" Lovely Part of the JNP|UK Famille www.theJNP.com --- (Sent from my iPod - please allow for any typos: it's a very small keyboard) On 31 Oct 2008, at 20:16, dwbarne at earthlink.net wrote: > This problem involves a callback method while using 'bind'. The bind > statement and the callback function are both in a module imported to > the main program. Relevant code snippets are as follows: > > #++++ begin snippet > > # main code > > import module_Editor > . > class MyClass(): > > def editor(self): > > module_Editor.my_Editor(self,self.frameParent) > > # end of main code > > # module 'module_Editor' > > def my_Editor(self,parentFrame): > > self.textMyCode.bind( > "", > handlerTextLineNumbersReturn(self) > ) > > def handlerTextLineNumbersReturn(self,event): > def temp(): > > print '\n** In handlerTextLineNumbersReturn' > > return temp > > # end of module 'module_Editor' > > # ++++ end snippet > > When the bind callback handler is called, the following error is > returned: > > ++++ begin error > Exception in Tkinter callback > Traceback (most recent call last): > File "c:\Python251_102507\lib\lib-tk\Tkinter.py", line 1403, in > __call__ > return self.func(*args) > TypeError: tempDef() takes no arguments (1 given) > > ++++ end error > > The above approach works for widgets in the module calling callback > handlers that return a def like the above, but bind statements > apparently do not like this approach for some reason. > > Any ideas on what I'm doing wrong here? Maybe a "*args" needs to go > somewhere in the calling or def statements? If so, where does it go? > > Daniel > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From denis.spir at free.fr Sat Nov 1 10:49:19 2008 From: denis.spir at free.fr (spir) Date: Sat, 01 Nov 2008 10:49:19 +0100 Subject: [Tutor] mergin two csv files based on a common join In-Reply-To: <24055736.1225490697083.JavaMail.root@ps28> References: <24055736.1225490697083.JavaMail.root@ps28> Message-ID: <490C261F.7010303@free.fr> qsqgeekyogdty at tiscali.co.uk a ?crit: Hello again, Thanks for the replies on my previous post, but I have a different problem now and don't see how to deal with it in a smooth way. I have two csv files where: 1.csv "1", "text", "aa" "2", "text2", "something else" "3", "text3", "something else" 2.csv "text", "xx" "text", "yy" "text3", "zz" now I would like to have an output like: "1", "text", "aa" "1", "text", "xx" "2", "text2", "something else" "3", "text3", "something else" "3", "text3", "zz" I basically need to merge the two csv files based on the column-2 Two points seem unclear: -1- As Kent asks, what happened to "yy" up there? Did you mean to keep it instead? -2- You seem not to merge both file on column #2, rather to build a union. Right? The following outline applies only if this guess is correct -- if not, just skip. You need to add an index field to the second csv file, then build a union of both: for record in csv2: Possibly, what you really want is only the union to be /sorted/ on "text" field. And the index only serves this purpose. If this is true, then the index field may be kept anyway (but needs not be output), as it will speed up the sort. From wesbrooks at gmail.com Sat Nov 1 13:04:33 2008 From: wesbrooks at gmail.com (Wesley Brooks) Date: Sat, 1 Nov 2008 12:04:33 +0000 Subject: [Tutor] Is it thread safe to collect data from threads where run has finished? Message-ID: Dear Users, I've got a few tasks that block for a while and cause my wxPython interface to lock up while they process. I'm thinking about migrating these to threads which I kick off when I want the task done. In the run bit of the thread the main work will be done, it will store the information as part of the object and when done post an event to the user interface for it to collect of the information and dispose of the thread. So there'll be a part of a wx event that looks something like: *self.loadThread = FileLoadThread(fileName, doneEvent) self.loadThread.start() * The FileLoadThread object would look like: *class FileLoadThread(threading.Thread): def __init__(self, mainGUI, fName, doneEvent): self.mainGUI = mainGUI self.fName = fName self.event = doneEvent threading.Thread.__init__(self) def run(self): self.dataObject = self.LoadFile(fName) wx.PostEvent(mainGUI, doneEvent)* ...where doneEvent is a custom event that signals to the user interface that it can collect the dataObject by doing the following: *self.dataObject = self.loadThread.dataObject* *del self.loadThread* Is this the best way to do this or should I just attach the dataObject to the event? Is the use of wx.PostEvent thread safe? Thanks in advance of any advice, Wesley Brooks -------------- next part -------------- An HTML attachment was scrubbed... URL: From otu at iptech-ghana.com Sat Nov 1 12:17:06 2008 From: otu at iptech-ghana.com (otu at iptech-ghana.com) Date: Sat, 1 Nov 2008 06:17:06 -0500 (CDT) Subject: [Tutor] (no subject) Message-ID: <1162.41.210.18.243.1225538226.squirrel@iptech-ghana.com> Dear Friends, I have just started learning python programming. I have no previous programming knowledge. I am presently using Python 2.6 windows version. I am struggling with how to enable executable files. I copied the ff program on idlle non-interactice and run it. the_world_is_flat =1 if the_world_is_flat: print"Be careful not to fall off" The result came out on the interactive window. I saved this as "example.py" on the desktop. The python icon appears on the the desktop alright. When I attempt to run it by double clicking the icon, only a black DOS window flashes. I know I am doing something seriously wrong. What is it? Regards, Bennedy. From kent37 at tds.net Sat Nov 1 17:02:59 2008 From: kent37 at tds.net (Kent Johnson) Date: Sat, 1 Nov 2008 12:02:59 -0400 Subject: [Tutor] (no subject) In-Reply-To: <1162.41.210.18.243.1225538226.squirrel@iptech-ghana.com> References: <1162.41.210.18.243.1225538226.squirrel@iptech-ghana.com> Message-ID: <1c2a2c590811010902h2d924533wc2c86b27732e631f@mail.gmail.com> On Sat, Nov 1, 2008 at 7:17 AM, wrote: > > I am struggling with how to enable executable files. I copied the ff > program on idlle non-interactice and run it. > > the_world_is_flat =1 > if the_world_is_flat: > print"Be careful not to fall off" > > The result came out on the interactive window. I saved this as > "example.py" on the desktop. The python icon appears on the the desktop > alright. When I attempt to run it by double clicking the icon, only a > black DOS window flashes. The problem is that the DOS window closes when the program exits. Try adding the line raw_input("Press return to exit ") to the end of your program. Kent -------------- next part -------------- An HTML attachment was scrubbed... URL: From jenmiller7 at gmail.com Sat Nov 1 17:21:37 2008 From: jenmiller7 at gmail.com (Jennifer Miller) Date: Sat, 1 Nov 2008 12:21:37 -0400 Subject: [Tutor] Debugging, other Message-ID: Hello, I would like to step through with debugging in PythonWin, I have added this toolbar, but I cannot click on it as an option. Also, when I click run, to define the arguments, do I enter them in the format name, name? Also, when I try to run my code, I get a message at the bottom of the screen that says, Failed to run script - syntax error - expected an indented block. I am not sure where I am going wrong here - maybe if I could do the debugging, that would help. Thanks, Python Beginner From denis.spir at free.fr Sat Nov 1 17:21:58 2008 From: denis.spir at free.fr (spir) Date: Sat, 01 Nov 2008 17:21:58 +0100 Subject: [Tutor] [Re: class/type methods/functions] In-Reply-To: <490B0099.90803@tue.nl> References: <490A13E4.5000206@free.fr> <490B0099.90803@tue.nl> Message-ID: <490C8226.4080809@free.fr> Thank you for this relevant & precise review, Albert. I will answer specific topic, then give a overall introduction of the problem(s) adressed by this project, that may clarify a bit some topics. A.T.Hofkamp a ?crit : > However, by moving the 'type' information to a seperate object, your classes become less cluttered, and the problem (and thus the solution) becomes easier to understand/program. > You have a Factory class + factory object (usually 1) that represents the real factory, and you have a Product class + many prduct objects for the products it makes. > > Each product object has properties and functions (ie its color and how you can use it). > Meta information, like what kind of products exist and how to make/transform them however is *not* part of the product object but belongs in the factory object. > (Look at real life, you can use a car to get from A to B and back, but a car cannot tell you what kinds of other cars exist, or how to install eg a radio.) > In your application, that would mean that the things you call 'instance' above are part of eg the 'format' object, and things you name 'type' above, are part of the 'formatfactory' (or 'formattype') object. > > The difference between your approach and the factory pattern imho is that the 'type' information of an object is not stored in its class, but in another object (of class Factory). [...] I think I get it better now. FactoryCLass ==> factory | "models" | v ObjectClass ==> objects Couldn't the factory actually be the same object as ObjectClass? Isn't this in a way similar to the use of meta-classes (that I have never used, even never explored)? I think I understand the point in this pattern, mainly for clarification. In the case of my projet, it could be used to implement the flexibility of the types/classes which depend on config parameters, and these parameters may change at runtime. However, this seems to me overload / over structuration / over abstraction. I don't make a heavy use of type/class attributes, and they rather clearly appear as what they are/mean. (See also below for further clarification.) >> class Format(Symbol): >> ''' block formats symbol ''' >> # import relevant config data for this symbol type >> from_codes = config.formats.from_codes >> to_codes = config.formats.to_codes >> names = config.formats.names >> # open_format to be checked with closing tag (xhtml only) >> open_format = None >> def __init__(self, source, mark, section_level, posV, posH, close = False, >> list_type = None, list_level=0): >> # posV & posH ~ line & element numbers for error output >> # 'mark' can be a wiki code or an xhfml tag >> self.section_level = section_level # = current title level >> self.indent = section_level * TAB # for nicer xhtml output > > As a side-note: > self.indent can be computed from self.section_level. In general, it is better in such cases not to store the computable attribute, but instead to compute whenever you need it. > This strategy prevents that you get inconsistencies in your data (ie suppose that self.section_level == 1 and self.indent == TAB + TAB at some point in the program, which of both is then the true value?) Right! I let down self.indent. In my case, such an unexpected change could not happen, but I agree upon the better practice. > >> self.close = close # for automatic closing (wiki only) >> self.list_level = list_level # nesting level >> self.list_type = list_type # bullet or number >> self.error = False # flag used for no output > > As a side-note: > you may want to consider using doc strings for documenting your class and instance variables, see eg pydoc or epydoc. Right again! I will move argument and attribute description to doc strings. > A variable like "section_level" leads me to believe that Format class is a part of a page. This is true. All (symbol) types, of which Format is a sample, represent document elements/language features. There is a type for plain text content, one for (block) format, one for additional 'aspect' (e.g. strong or a custom span class), one for links, etc... See below. Section_level is used for writing into wiki, because wiki codes for headers are usually of the form "===", where the number of chars means the section level. Additionally, it lets me write xhtml docs in a nicer form, where indentation represents the logical structure, similar to python code:

section 1

some text

section 1.1

some text

section 1.2

some text By the way, I answer here your question about the meaning of "Format": after your remark, I called it back BlockFormat. A BlockFormat instance represents a block formatting mark. For instance: table_cell : xhtml <--> wiki | list_item : xhtml
  • <--> wiki * or # paragraph : xhtml

    <--> wiki (implicit) I first considered making a symbol type for each kind of block format. But I finally merged them all into BlockFormat, because the only major difference is their class (=CSS class), that becomes an instance attribute. > >> # read & record symbol data >> if source == WIKI: >> self.from_wiki(mark, posV, posH) >> return >> if source == XHTML: >> self.from_xhtml(mark, posV, posH) > > This looks like a (factory!) class hierarchy you currently don't have. In OOP I would expect something like > > self.load(...) # 'self.from()' is not possible, since 'from' is a reserved word in Python > > and the underlying object type of 'self' would decide the conversion you actually perform. In a sense, yes. I first considered creating a version of each type for each language. E.g. WikiBlockFormat & HTMLBlockFormat. Then I merged them because they actually represent the same thing: a common language feature. The type holds r/w methods for both languages. I actually find this clearer and more consistent than having specific types for each language, all having the same sense ("block format") & holding the same data (class, open/close status, additional sub-kind & nesting level for list items). Right? Or Have misunderstood? > In the factory pattern, you'd have a formattype object (of class FormatType) that holds the global (config?) information, and each Format object may hold a reference to formattype (if you want). Yes. The reference would mainly be used to access config data, in order to check the source text validity and to write (back) to a specific language. >> Now, imagine the source is a wiki text, and the user wishes to output into a different wiki language. At some point between reading & writing will the config been rebuilt and, as a consequence, data held by each Symbol (sub-)type. As this is an action of the type, I wish it to be performed by the type. So: > > That's one option. Another option may be to make the page object language-agnostic (ie you have a 'list', a 'picture' and many more page elements, but not attached to a specific language.) Exactly. You reach here the core of the model. The result of parsing is fully "language agnostic". An object I called tortue (turtle) ;-) parses the source document; it's a kind of state machine, as it needs to 'know' its position (e.g. start of a block) and 'remember' things like open tags. The result simply is a list of symbols which builds an abstract representation of the parsed text. Right? These symbols are independent of the input language -- actually it is *the* point; and are able to further 'express' themselves into any know language. Presently the turtle can only parse wiki and a third format (table, see below), not xhtml; but xhtml is simpler to parse (more explicit & regular) because less human-oriented. [Side note: Each symbol type is implemented as a sub-type of a super-type called Symbol. Symbol presently is of nearly no use, but who knows? Now, thank to your explanations, I tend to see it as a symbol type factory! It could even hold the whole configuration, instead of each symbol holding its relevant part.] > Also, you have a number of language objects that know how to convert the page to their language. > A few class definitions to make it a bit clearer (hopefully): > > class Language(object): > """ > Base class containing symbols/tags of any language used in your application. It also states what operations you can do, and has common code. > """ > def __init__(self): > # Setup common attributes (valid for all languages) > > def load_page(self, ....): > """ Load a page """ > raise NotImplementedError("Implement me in a derived class") > > Language class is not really needed, but very nice to make clear what operations you >can do with it. > > class WikiLanguage(Language): > """ > Properties and symbols/tags that exist in the wiki language > """ > def __init__(self): > Language.__init__() > self.list_tag = '*' > > def load_page(self, ....): > # load page in wiki format, and return a Page object > > class XHtmlLanguage(Language): > """ > Properties and symbols/tags that exist in the xhtml language > """ > def __init__(self): > Language.__init__() > self.list_tag = 'li' > > def load_page(self, ....): > # load page in xhtml format, and return a Page object > > For each language class that you have, you make a object (probably 1 for each language that you have). It describes what the language contains and how it performs its functions. > A Language object also knows how to load/save a page in its language, how to render it, etc. Well, I understand your point of view. However, this is where I rather disagree. Additional information is probably needed for a constructive exchange, now. You will find some below. > class Page(object): > """ > A page of text > """ > def __init__(self, lang): > self.symbols = [] # Contents of the page, list or tree of Element's Exactly. Actually, you could replace 'Page' with Turtle (I see it as a dynamic thing) and add this methods: def symbolise(wiki_doc): def symbolise(html_doc): > class Element(object): > """ > A concept that exists at a page (list, text, paragraph, picture, etc) > """ = Symbol -- except that symbol is not language specific > class ListElement(Element): > .... > > class TextElement(Element): > ..... = Symbol sub-types -- ditto > A page is simply a tree or a list of Elements. Since a page here is language-agnostic, it doesn't even need to know its language. > (don't know whether this would work for you). Perfectly well. I first started buil a tree-like model of a page. Then swithed to a simple list (that better matches both wiki and xhtml expression -- actually a series of token, with block highest level of structure -- the rest beeing implicit). Maybe I go back to tree model later, just as an additional tool. May alse be used for semantic parsing? > Hope it makes some sense, I'm rather impressed how clearly you're able to dive into a (for me rather complex) problem, without even knowing what kind of need it is supposed to meet. So if you like to know a bit more, I will here start from the start. You may have a look at www.creole.org. Creole is an attempt to create an interwiki standard language, in order to allow users of several wiki engines (& languages) to contribute on 'foreign' wiki sites that use another format. I have had for a long time the idea that it is indeed possible to allow (programming) language customization. Implemented through an editor configuration layer, this allows both respect of a common standard for code sharing, and comfortable personal use (Gem?tlichkeit). Right? This is similar to syntax highlighting or indent preferences. The /saving/ form is not touched (obviously, semantics neither). [Note that 95% of the programmers seem not to reach this point, as they argue that this would launch millions of weird versions of their beloved language into the wild.] [note: I plan to extend a python editor to allow this. I long for the day when I can get rid of the ':' at end of headers, use ':' for assignment, endly use '=' for "equals" -- among lot's of other (so important for me) details.] This applies for wiki of course. What I propose. A subset of xhtml, matching common wiki lang feature, can be used as saving/standard/exchange format. The present project, as an amateur work basically done for pleasure, was first an attempt to build a demonstration of how this may actually work. Now, it has become a bit more. A list of requisites: * use of several wiki lang configuration * further customization (i.e. def of differences only) * inner abstract represention (currently beeing refactored) * r/w to/from presently configured wiki lang * use an xhtml subset as saving format, thus * r/w to from xhtml (write ok, read planned) * r/w to/from table format (ok) The last format is used for debug; but it's also a kind of template or bridge for DB r/w. I had never thought at implementing whole language specifications as you propose above. This is actually an option. But first, here is how it works up to now: Each symbol type started as a kind of description of a common wiki language feature, for instance a token that introduces a section title: type "title", level 3: creole === <--> xhtml

    ...

    According to this pattern, both following source text snippets |I'm a **pride** cell I'm a pride cell will be innerly represented as the same list of symbols. Which output in table format is: BlockFormat table_cell open Text I'm a SegmentAspect important open Text pride SegmentAspect important close Text cell BlockFormat table_cell close Conversely, this symbol list can be output in either form. Now, as you clearly explain above, in order to implement language "super_objects", I will still need to build classes for each type of symbol. For instance a Link type, inside the XHTML_language object. Now, I need nearly the same object, with the same semantics and same held data inside the wiki_language object, and also inside the table_format object. Correct? So why not just add r/w methods for each language inside a single, common, symbol type? Now, why the idea of language object didn't jump into my brain is probably because it is too hard for me! Anyway, I see several uses/advantages for it: * for wiki, hold the current config * hold language specific r/w rules (e.g. the <...>, presently a tool function does it) * specify syntactic rules This is the hard part for me! For instance,the wiki config is presently nearly only about lexik (ie choice of codes), only some syntactic details can be set -- eg whether an aspect code must be closed. The real syntax rules are hidden, actually implicit inside the r/w methods of each language and turtle's symbolisation method. Samples of such rule: * wiki: block format codes a single characters, lie at the start of block, are not closed * html : segment aspect take either a ... or a form. * both list nesting and list mixing are available Now, if I could specify such rules into a set of parameters, then I could write a general parsing (symbolisation) method for turtle, that takes this rule set as parameter. Idem for each symbol type read & write method. Now, this seems much too difficult for programming talent: the way I see, it tends to a parser generator. > Albert Denis From denis.spir at free.fr Sat Nov 1 18:09:21 2008 From: denis.spir at free.fr (spir) Date: Sat, 01 Nov 2008 18:09:21 +0100 Subject: [Tutor] (no subject) In-Reply-To: <1162.41.210.18.243.1225538226.squirrel@iptech-ghana.com> References: <1162.41.210.18.243.1225538226.squirrel@iptech-ghana.com> Message-ID: <490C8D41.7020205@free.fr> otu at iptech-ghana.com a ?crit : > Dear Friends, > I have just started learning python programming. I have no previous > programming knowledge. Welcome! I'm an amateur, too. Some words to add to Kent's answer. > I am presently using Python 2.6 windows version. > I am struggling with how to enable executable files. I copied the ff > program on idlle non-interactice and run it. > > the_world_is_flat =1 > if the_world_is_flat: > print"Be careful not to fall off" > > You can alternatively write: the_world_is_flat = True The reason for this is that "the world is flat" is a logical assertion which may be either true or false. Right? More logical assertions of that kind: "end of file reached", "searched pattern found", "invalid syntax",... For both historical and practical reasons, python represents logical values (called booleans or bools) as integers. This can be considered an internal, background, feature, that can safely be forgotten 99% of the time. Their meaning always remains logical. Writing True or False instead of 1 or 0 then makes your code more legible. This is no necessity, just a common recommendation. Another point of view about logical variables is that they are like closed questions ("is the world flat?"), which answer/value can be yes or no. Some languages allow that. Ruby also identifies logical variables with a '?'. > > The result came out on the interactive window. I saved this as > "example.py" on the desktop. The python icon appears on the the desktop > alright. When I attempt to run it by double clicking the icon, only a > black DOS window flashes. I know I am doing something seriously wrong. > What is it? You do it all right. The tricky problem is what Kent explained. If you are under windows and rename your program with a .pyw extension, it will run slightly differently, so that you won't even see the DOS window flash. This is rather for GUI programs. Anyway, when you run a program inside Idle, it really runs! For instance, if you create a file, you can check it after execution. So that you may not need to execute your programs from outside the editor. It's a very practicle advantage. You just have to know that they will run "normally", with no change, on any machine with python installed. > Regards, > Bennedy. > > _ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From srilyk at gmail.com Sat Nov 1 18:35:42 2008 From: srilyk at gmail.com (W W) Date: Sat, 1 Nov 2008 12:35:42 -0500 Subject: [Tutor] Debugging, other In-Reply-To: References: Message-ID: <333efb450811011035j4c0fe19al83baea4f2726e0f9@mail.gmail.com> On Sat, Nov 1, 2008 at 11:21 AM, Jennifer Miller wrote: > Hello, > > I would like to step through with debugging in PythonWin, I have added > this toolbar, but I cannot click on it as an option. Also, when I > click run, to define the arguments, do I enter them in the format > name, name? Also, when I try to run my code, I get a message at the > bottom of the screen that says, Failed to run script - syntax error - > expected an indented block. I am not sure where I am going wrong here > - maybe if I could do the debugging, that would help. It helps to post the exact error message. For instance: File "", line 2 print x ^ IndentationError: expected an indented block came from this entered into the interactive interpreter: >>> for x in xrange(1,10): ... print x Because after a for statement, it expects an indentation. It's considered standard to indent with four spaces. My guess is there's something in your code that caused such an error. The more information you give us, the better we are able to help you. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Sat Nov 1 20:08:50 2008 From: bgailer at gmail.com (bob gailer) Date: Sat, 01 Nov 2008 15:08:50 -0400 Subject: [Tutor] Debugging, other In-Reply-To: References: Message-ID: <490CA942.7060305@gmail.com> Jennifer Miller wrote: > Hello, > > I would like to step through with debugging in PythonWin, I have added > this toolbar, but I cannot click on it as an option. "cannot click on it" is pretty vague. Is your mouse broken? Or do you mean that nothing happens when you click. > Also, when I click run, to define the arguments, do I enter them in the format > name, name? the same as you would do at a command or shell prompt: name name > Also, when I try to run my code, I get a message at the > bottom of the screen that says, Failed to run script - syntax error - > expected an indented block. As Wayne said check the indentation. When you get a syntax error the program failed to compile. It does not get to execute, so debugging is not available. The cursor should be on the line where the problem was detected. > I am not sure where I am going wrong here > - maybe if I could do the debugging, that would help. > Press shift-ctrl-C to error check the program. To set breakpoints: put the cursor on a line then click the hand icon or press F9. Press F5 to run the program, or F11 to start it and suspend at the first line. > Thanks, > > Python Beginner > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Bob Gailer Chapel Hill NC 919-636-4239 When we take the time to be aware of our feelings and needs we have more satisfying interatctions with others. Nonviolent Communication provides tools for this awareness. As a coach and trainer I can assist you in learning this process. What is YOUR biggest relationship challenge? From sander.sweers at gmail.com Sat Nov 1 22:40:38 2008 From: sander.sweers at gmail.com (Sander Sweers) Date: Sat, 1 Nov 2008 22:40:38 +0100 Subject: [Tutor] Manipulate list in place or append to a new list Message-ID: Hi, What is the better way to process data in a list? Make the changes in place, for example somelist = [1,2,3,4] for x in range(len(somelist)): somelist[x] = somelist[x] + 1 Or would making a new list like somelist = [1,2,3,4] newlist = [] for x in somelist: newlist.append(x + 1) Or is there another way of doing this kind of things. Pointers to online resources are most welcome :-) Thx Sander From denis.spir at free.fr Sat Nov 1 23:18:39 2008 From: denis.spir at free.fr (spir) Date: Sat, 01 Nov 2008 23:18:39 +0100 Subject: [Tutor] Manipulate list in place or append to a new list In-Reply-To: References: Message-ID: <490CD5BF.7020309@free.fr> Sander Sweers a ?crit : > Hi, > > What is the better way to process data in a list? Make the changes in > place, for example > > somelist = [1,2,3,4] > > for x in range(len(somelist)): > somelist[x] = somelist[x] + 1 > > Or would making a new list like > > somelist = [1,2,3,4] > newlist = [] > > for x in somelist: > newlist.append(x + 1) > > Or is there another way of doing this kind of things. Pointers to > online resources are most welcome :-) > Look for "list comprehension in the tutorial chap 5.1.4, or better Dive into Python chap 3.6: /result/ = *[*/expression/ *for* /item1/ *in* /sequence/] (result is a new list) Denis > Thx > Sander > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > From bgailer at gmail.com Sun Nov 2 01:23:23 2008 From: bgailer at gmail.com (bob gailer) Date: Sat, 01 Nov 2008 20:23:23 -0400 Subject: [Tutor] Manipulate list in place or append to a new list In-Reply-To: References: Message-ID: <490CF2FB.8000900@gmail.com> Sander Sweers wrote: > Hi, > > What is the better way to process data in a list? Depends on what you mean by "better". Could mean faster, smaller, more readable, or ?? Get clear on your goals. > Make the changes in place, for example > > somelist = [1,2,3,4] > > for x in range(len(somelist)): > somelist[x] = somelist[x] + 1 > > Or would making a new list like > > somelist = [1,2,3,4] > newlist = [] > > for x in somelist: > newlist.append(x + 1) > > Or is there another way of doing this kind of things. Pointers to > online resources are most welcome :-) > Take a look at Numerical Python http://numpy.scipy.org/, which works much like APL: >>> /print a/ [1 2 3] >>> /print a + 3/ [4 5 6] -- Bob Gailer Chapel Hill NC 919-636-4239 When we take the time to be aware of our feelings and needs we have more satisfying interatctions with others. Nonviolent Communication provides tools for this awareness. As a coach and trainer I can assist you in learning this process. What is YOUR biggest relationship challenge? From nephish at gmail.com Sun Nov 2 03:45:12 2008 From: nephish at gmail.com (shawn bright) Date: Sat, 1 Nov 2008 21:45:12 -0500 Subject: [Tutor] how to read over serial port Message-ID: <384c93600811011945x3a6922f9hf3e0faac604070cd@mail.gmail.com> Hey there all, I have a gps device that talks to the computer over a serial port. i am using the pyserial module and getting values in. Here is my delima, i am supposed to read a message in that starts with a $ (this is all ascii). but when i do a ser.read(16) and i try to print it to a screen, it is all just weird characters. i had it write each byte to a file like f = open('test', 'wb') msg = ser.read(16) for i in msg: f.write(i) f.close() then when i open it with python and do f = open('test', 'rb') and read it it is the same weird characters. when i add a line to print the type after reading like this: for i in msg: print str(type(i)) i consistantly get type str so, what am i supposed to be doing to get real values out of this stream of bytes? thanks all shawn From jmorcombe at westnet.com.au Sun Nov 2 04:27:11 2008 From: jmorcombe at westnet.com.au (Jim Morcombe) Date: Sun, 02 Nov 2008 12:27:11 +0900 Subject: [Tutor] Multi-User file system Message-ID: <490D1E0F.6070303@westnet.com.au> I want to have a couple of files that can be updated simultaneously be several users. I don't want to go to the effort of having the users set up a RDMS and would like to control everything from Python. I am after something like shelve, but with record locking. Is there such a thing? Jim Morcombe From bgailer at gmail.com Sun Nov 2 05:02:46 2008 From: bgailer at gmail.com (bob gailer) Date: Sun, 02 Nov 2008 00:02:46 -0400 Subject: [Tutor] how to read over serial port In-Reply-To: <384c93600811011945x3a6922f9hf3e0faac604070cd@mail.gmail.com> References: <384c93600811011945x3a6922f9hf3e0faac604070cd@mail.gmail.com> Message-ID: <490D2666.4010904@gmail.com> shawn bright wrote: > Hey there all, > > I have a gps device that talks to the computer over a serial port. > i am using the pyserial module and getting values in. > > Here is my delima, > > i am supposed to read a message in that starts with a $ (this is all ascii). > but when i do a ser.read(16) and i try to print it to a screen, it is > all just weird characters. > I did not realize there was a Weird character set. I'd have expected ASCII characters. (chuckle?) When you say "weird" I guess you mean unexpected. What exactly did you get and what exactly did you expect? > i had it write each byte to a file like > f = open('test', 'wb') > msg = ser.read(16) > for i in msg: > f.write(i) > f.close() > > then when i open it with python and do > f = open('test', 'rb') > and read it it is the same weird characters. > Well of course. Writing to a file and then reading it should give the same results. Again what did you expect and why does this surprise you? > when i add a line to print the type after reading like this: > for i in msg: > print str(type(i)) > > i consistantly get type str > That's good. It tells us that msg is a character string. > so, what am i supposed to be doing to get real values out of this > stream of bytes? > Depends again on what you are expecting. What do you mean by "real"? -- Bob Gailer Chapel Hill NC 919-636-4239 When we take the time to be aware of our feelings and needs we have more satisfying interatctions with others. Nonviolent Communication provides tools for this awareness. As a coach and trainer I can assist you in learning this process. What is YOUR biggest relationship challenge? From nephish at gmail.com Sun Nov 2 05:23:25 2008 From: nephish at gmail.com (shawn bright) Date: Sat, 1 Nov 2008 23:23:25 -0500 Subject: [Tutor] how to read over serial port In-Reply-To: <490D2666.4010904@gmail.com> References: <384c93600811011945x3a6922f9hf3e0faac604070cd@mail.gmail.com> <490D2666.4010904@gmail.com> Message-ID: <384c93600811012123m23516511i34ed8778af18ef72@mail.gmail.com> First, thanks for you time with me on this. When i said weird characters, i meant that they were not characters you would find on a keyboard. Like one of them is a black diamond with a question mark in it. there are some weird block characters, occationally a letter, etc.. did not clarify why i wrote it to a file. It is running in a thread, so i captured a few of the messages on a file, and moved them to a different computer that is not running our company so i could work with this stuff there. the output is supposed to be a mix of mostly numbers and some letters and commas that seperate the fields of data. thanks for any suggestions on this. shawn On Sat, Nov 1, 2008 at 11:02 PM, bob gailer wrote: > shawn bright wrote: >> >> Hey there all, >> >> I have a gps device that talks to the computer over a serial port. >> i am using the pyserial module and getting values in. >> >> Here is my delima, >> >> i am supposed to read a message in that starts with a $ (this is all >> ascii). >> but when i do a ser.read(16) and i try to print it to a screen, it is >> all just weird characters. >> > > I did not realize there was a Weird character set. I'd have expected ASCII > characters. (chuckle?) > > When you say "weird" I guess you mean unexpected. What exactly did you get > and what exactly did you expect? > >> i had it write each byte to a file like >> f = open('test', 'wb') >> msg = ser.read(16) >> for i in msg: >> f.write(i) >> f.close() >> >> then when i open it with python and do >> f = open('test', 'rb') >> and read it it is the same weird characters. >> > > Well of course. Writing to a file and then reading it should give the same > results. Again what did you expect and why does this surprise you? > >> when i add a line to print the type after reading like this: >> for i in msg: >> print str(type(i)) >> >> i consistantly get type str >> > > That's good. It tells us that msg is a character string. >> >> so, what am i supposed to be doing to get real values out of this >> stream of bytes? >> > > Depends again on what you are expecting. What do you mean by "real"? > > > -- > Bob Gailer > Chapel Hill NC 919-636-4239 > > When we take the time to be aware of our feelings and needs we have more > satisfying interatctions with others. > > Nonviolent Communication provides tools for this awareness. > > As a coach and trainer I can assist you in learning this process. > > What is YOUR biggest relationship challenge? > > From jmorcombe at westnet.com.au Sun Nov 2 07:32:48 2008 From: jmorcombe at westnet.com.au (Jim Morcombe) Date: Sun, 02 Nov 2008 15:32:48 +0900 Subject: [Tutor] Multi-User file system In-Reply-To: <490D1E0F.6070303@westnet.com.au> References: <490D1E0F.6070303@westnet.com.au> Message-ID: <490D4990.6030304@westnet.com.au> Would pySQLite be a reasonable choice for this? Jim Morcombe Jim Morcombe wrote: > I want to have a couple of files that can be updated simultaneously be > several users. I don't want to go to the effort of having the users > set up a RDMS and would like to control everything from Python. I am > after something like shelve, but with record locking. Is there such a > thing? > > Jim Morcombe > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From rschroev_nospam_ml at fastmail.fm Sun Nov 2 10:26:42 2008 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Sun, 02 Nov 2008 10:26:42 +0100 Subject: [Tutor] how to read over serial port In-Reply-To: <384c93600811011945x3a6922f9hf3e0faac604070cd@mail.gmail.com> References: <384c93600811011945x3a6922f9hf3e0faac604070cd@mail.gmail.com> Message-ID: shawn bright schreef: > Hey there all, > > I have a gps device that talks to the computer over a serial port. > i am using the pyserial module and getting values in. > > Here is my delima, > > i am supposed to read a message in that starts with a $ (this is all ascii). > but when i do a ser.read(16) and i try to print it to a screen, it is > all just weird characters. Are you sure you opened the serial port with the correct baudrate and other settings? It's common to see unexpected characters coming from a serial port if you use the wrong baudrate. -- The saddest aspect of life right now is that science gathers knowledge faster than society gathers wisdom. -- Isaac Asimov Roel Schroeven From sander.sweers at gmail.com Sun Nov 2 11:43:36 2008 From: sander.sweers at gmail.com (Sander Sweers) Date: Sun, 2 Nov 2008 11:43:36 +0100 Subject: [Tutor] Manipulate list in place or append to a new list In-Reply-To: <490CF2FB.8000900@gmail.com> References: <490CF2FB.8000900@gmail.com> Message-ID: On Sun, Nov 2, 2008 at 01:23, bob gailer wrote: >> What is the better way to process data in a list? > > Depends on what you mean by "better". Could mean faster, smaller, more > readable, or ?? Get clear on your goals. Inexperienced beginner programmer asking more experienced programmer what they would choose and maybe why... Goal, learning best practises.for pythoin progtramming. >> Make the changes in place, for example >> >> somelist = [1,2,3,4] >> >> for x in range(len(somelist)): >> somelist[x] = somelist[x] + 1 >> >> Or would making a new list like >> >> somelist = [1,2,3,4] >> newlist = [] >> >> for x in somelist: >> newlist.append(x + 1) >> >> Or is there another way of doing this kind of things. Pointers to >> online resources are most welcome :-) Thanks for you encouraging feedback. Greets Sander From kent37 at tds.net Sun Nov 2 13:27:17 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 2 Nov 2008 08:27:17 -0400 Subject: [Tutor] Multi-User file system In-Reply-To: <490D4990.6030304@westnet.com.au> References: <490D1E0F.6070303@westnet.com.au> <490D4990.6030304@westnet.com.au> Message-ID: <1c2a2c590811020427o7b3746bch47cc2cc71621beae@mail.gmail.com> On Sun, Nov 2, 2008 at 2:32 AM, Jim Morcombe wrote: > Would pySQLite be a reasonable choice for this? >From the SQLite docs at http://sqlite.org/whentouse.html: - A good rule of thumb is that you should avoid using SQLite in situations where the same database will be accessed simultaneously from many computers over a network filesystem. - SQLite uses reader/writer locks on the entire database file. That means if any process is reading from any part of the database, all other processes are prevented from writing any other part of the database. >> I want to have a couple of files that can be updated simultaneously be >> several users. I don't want to go to the effort of having the users set up >> a RDMS and would like to control everything from Python. I am after >> something like shelve, but with record locking. Is there such a thing? If you want record-level locking I think you will have to use some kind of server. You might be able to set up a simple server using say CherryPy for a web server or XML-RPC or Pyro. Or perhaps convert the app to be web-based using Django or TurboGears or another web framework. Kent From kent37 at tds.net Sun Nov 2 13:32:29 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 2 Nov 2008 08:32:29 -0400 Subject: [Tutor] Manipulate list in place or append to a new list In-Reply-To: References: Message-ID: <1c2a2c590811020432g10009a11j8264fa987ed36475@mail.gmail.com> On Sat, Nov 1, 2008 at 5:40 PM, Sander Sweers wrote: > Hi, > > What is the better way to process data in a list? Make the changes in > place, for example > > somelist = [1,2,3,4] > > for x in range(len(somelist)): > somelist[x] = somelist[x] + 1 > > Or would making a new list like > > somelist = [1,2,3,4] > newlist = [] > > for x in somelist: > newlist.append(x + 1) > > Or is there another way of doing this kind of things. Pointers to > online resources are most welcome :-) Use a list comprehension: somelist = [ x+1 for x in somelist ] Note that this creates a new list, replacing the one that was in somelist. If you need to actually modify somelist in place (rare) then use somelist[:] = [ x+1 for x in somelist ] which creates a new list, then replaces the *contents* of somelist with the contents of the new list. If you don't understand how these are different, this might help: http://personalpages.tds.net/~kent37/kk/00012.html Kent From sander.sweers at gmail.com Sun Nov 2 14:13:54 2008 From: sander.sweers at gmail.com (Sander Sweers) Date: Sun, 2 Nov 2008 14:13:54 +0100 Subject: [Tutor] Manipulate list in place or append to a new list In-Reply-To: <1c2a2c590811020432g10009a11j8264fa987ed36475@mail.gmail.com> References: <1c2a2c590811020432g10009a11j8264fa987ed36475@mail.gmail.com> Message-ID: On Sun, Nov 2, 2008 at 13:32, Kent Johnson wrote: > Use a list comprehension: > somelist = [ x+1 for x in somelist ] Got it. > Note that this creates a new list, replacing the one that was in > somelist. If you need to actually modify somelist in place (rare) then > use somelist[:] = [ x+1 for x in somelist ] > > which creates a new list, then replaces the *contents* of somelist > with the contents of the new list. In what (rare) situation would you use this? > http://personalpages.tds.net/~kent37/kk/00012.html This page helped. Especially the link to the 'Reset your brain' article is very interesting. Thanks Sander From kent37 at tds.net Sun Nov 2 15:34:23 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 2 Nov 2008 10:34:23 -0400 Subject: [Tutor] Manipulate list in place or append to a new list In-Reply-To: References: <1c2a2c590811020432g10009a11j8264fa987ed36475@mail.gmail.com> Message-ID: <1c2a2c590811020634m2ed63a33n5f7e671969a1ce76@mail.gmail.com> On Sun, Nov 2, 2008 at 9:13 AM, Sander Sweers wrote: > On Sun, Nov 2, 2008 at 13:32, Kent Johnson wrote: >> Note that this creates a new list, replacing the one that was in >> somelist. If you need to actually modify somelist in place (rare) then >> use somelist[:] = [ x+1 for x in somelist ] >> >> which creates a new list, then replaces the *contents* of somelist >> with the contents of the new list. > > In what (rare) situation would you use this? For example if you have a function that adds one to each element of a list passed to it. def brokenAdder(somelist): somelist = [ x+1 for x in somelist ] This just modifies the local name, the caller will not see any change. def adder(somelist): somelist[:] = [ x+1 for x in somelist ] In this case the caller will see a changed list. Basically any time you have two names referencing (aliasing) the same list and you want changes to the list to be seen for all the aliases. Function parameters are a simple example of aliasing. Kent From bcl at brianlane.com Sun Nov 2 16:38:31 2008 From: bcl at brianlane.com (Brian C. Lane) Date: Sun, 02 Nov 2008 07:38:31 -0800 Subject: [Tutor] how to read over serial port In-Reply-To: <384c93600811011945x3a6922f9hf3e0faac604070cd@mail.gmail.com> References: <384c93600811011945x3a6922f9hf3e0faac604070cd@mail.gmail.com> Message-ID: <490DC977.8080207@brianlane.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 shawn bright wrote: > Hey there all, > > I have a gps device that talks to the computer over a serial port. > i am using the pyserial module and getting values in. Here are the relevant bits of a serial to tcp/ip app that I use. Most likely you have the wrong baudrate set. If it is an older GPS device the baudrate will be 4800, newer devices allow you to set it to higher speeds, 9600 being standard. Check the device settings to make sure that it doesn't have any weird parity settings too. 8 bits, No Parity, 1 stop bit is common. import sys import serial port = "/dev/ttyS0" baud = 9600 ser = serial.Serial() ser.port = port ser.baudrate = baud try: ser.open() except: sys.stderr.write("Error opening serial port %s\n" % (ser.portstr) ) sys.exit(1) ser.setRtsCts(0) while 1: # Read from serial port, blocking data = ser.read(1) # If there is more than 1 byte, read the rest n = ser.inWaiting() if n: data = data + ser.read(n) sys.stdout.write(data) - -- - ---[Office 68.7F]--[Outside 51.0F]--[Server 103.2F]--[Coaster 70.0F]--- - ---[ TACOMA WSF (366772760) @ 47 36.3260 -122 23.1697 ]--- Software, Linux, Microcontrollers http://www.brianlane.com AIS Parser SDK http://www.aisparser.com -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.8 (Darwin) Comment: Remember Lexington Green! iD8DBQFJDcl3Iftj/pcSws0RAs2+AJ91ynHgzdXDfVpbh37iM7XITnDI7wCeNON8 qxyWcuc5opuOpeRCJ6cWr+o= =fPs4 -----END PGP SIGNATURE----- From denis.spir at free.fr Sun Nov 2 17:41:56 2008 From: denis.spir at free.fr (spir) Date: Sun, 02 Nov 2008 17:41:56 +0100 Subject: [Tutor] Manipulate list in place or append to a new list In-Reply-To: References: <1c2a2c590811020432g10009a11j8264fa987ed36475@mail.gmail.com> Message-ID: <490DD854.3040200@free.fr> Sander Sweers a ?crit : > On Sun, Nov 2, 2008 at 13:32, Kent Johnson wrote: >> Use a list comprehension: >> somelist = [ x+1 for x in somelist ] > > Got it. > >> Note that this creates a new list, replacing the one that was in >> somelist. If you need to actually modify somelist in place (rare) then >> use somelist[:] = [ x+1 for x in somelist ] >> >> which creates a new list, then replaces the *contents* of somelist >> with the contents of the new list. > > In what (rare) situation would you use this? [post sent again -- seems not to have reached the list -- ??] When you need to cleanup or normalize the objects held in a list. For instance, in text processing: lines = text.splitlines() lines = [line.strip() for line in lines] or e.g. lines = [line.lower() for line in lines] Both "pre-processing" actions that will make further processing more straitforward. Note that you can chain actions: lines = [line.strip().lower() for line in lines] Denis From denis.spir at free.fr Sun Nov 2 17:33:52 2008 From: denis.spir at free.fr (spir) Date: Sun, 02 Nov 2008 17:33:52 +0100 Subject: [Tutor] err... list.pairs()? In-Reply-To: References: <1c2a2c590811020432g10009a11j8264fa987ed36475@mail.gmail.com> Message-ID: <490DD670.7040505@free.fr> Excuse me for such a stupid question, I just wish to stop and lose my time searching for something that maybe simply does not exist. I'm looking for the builtin function for sequences that would return a list of (index,item) pairs to be used in loops. analog to dict's items() function. [I was writnig "for index,item in symbols.items():" when I had a doubt on 'item', as this hardly refers to a pair in the case of sequences. So that I wanted to check... I have not found it yet ;-)] Thank you, Denis PS: It /should/ exist! From nephish at gmail.com Sun Nov 2 18:50:45 2008 From: nephish at gmail.com (shawn bright) Date: Sun, 2 Nov 2008 11:50:45 -0600 Subject: [Tutor] how to read over serial port In-Reply-To: <490DC977.8080207@brianlane.com> References: <384c93600811011945x3a6922f9hf3e0faac604070cd@mail.gmail.com> <490DC977.8080207@brianlane.com> Message-ID: <384c93600811020950y166e5ce4r5c472a2af8c26fa5@mail.gmail.com> Thanks all, Yeah, checked the settings, and when i have the thing talk to a program that just prints out whatever the serial port reads, It was looking fine. Incorrect baudrate was my first problem, and did cause weirdness, escpeially on the latter end of the message, but this isn't the same problem. Just don't know how to read it. thanks shawn On Sun, Nov 2, 2008 at 9:38 AM, Brian C. Lane wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > shawn bright wrote: >> Hey there all, >> >> I have a gps device that talks to the computer over a serial port. >> i am using the pyserial module and getting values in. > > Here are the relevant bits of a serial to tcp/ip app that I use. Most > likely you have the wrong baudrate set. If it is an older GPS device the > baudrate will be 4800, newer devices allow you to set it to higher > speeds, 9600 being standard. Check the device settings to make sure that > it doesn't have any weird parity settings too. 8 bits, No Parity, 1 stop > bit is common. > > > import sys > import serial > > port = "/dev/ttyS0" > baud = 9600 > > ser = serial.Serial() > ser.port = port > ser.baudrate = baud > > try: > ser.open() > except: > sys.stderr.write("Error opening serial port %s\n" % (ser.portstr) ) > sys.exit(1) > > ser.setRtsCts(0) > > while 1: > # Read from serial port, blocking > data = ser.read(1) > > # If there is more than 1 byte, read the rest > n = ser.inWaiting() > if n: > data = data + ser.read(n) > > sys.stdout.write(data) > > > > - -- > - ---[Office 68.7F]--[Outside 51.0F]--[Server 103.2F]--[Coaster 70.0F]--- > - ---[ TACOMA WSF (366772760) @ 47 36.3260 -122 23.1697 ]--- > Software, Linux, Microcontrollers http://www.brianlane.com > AIS Parser SDK http://www.aisparser.com > > -----BEGIN PGP SIGNATURE----- > Version: GnuPG v1.4.8 (Darwin) > Comment: Remember Lexington Green! > > iD8DBQFJDcl3Iftj/pcSws0RAs2+AJ91ynHgzdXDfVpbh37iM7XITnDI7wCeNON8 > qxyWcuc5opuOpeRCJ6cWr+o= > =fPs4 > -----END PGP SIGNATURE----- > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Sun Nov 2 19:53:04 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 2 Nov 2008 14:53:04 -0400 Subject: [Tutor] err... list.pairs()? In-Reply-To: <490DD670.7040505@free.fr> References: <1c2a2c590811020432g10009a11j8264fa987ed36475@mail.gmail.com> <490DD670.7040505@free.fr> Message-ID: <1c2a2c590811021053s5c43bd63gcca2a752e57c9852@mail.gmail.com> On Sun, Nov 2, 2008 at 12:33 PM, spir wrote: > Excuse me for such a stupid question, I just wish to stop and lose my time > searching for something that maybe simply does not exist. > I'm looking for the builtin function for sequences that would return a list > of (index,item) pairs to be used in loops. analog to dict's items() > function. IIUC you are looking for enumerate(): http://docs.python.org/library/functions.html#enumerate The doc page on built-in functions, which contains enumerate(), is worth skimming or reading. I also recommend the docs on built-in types, which tell you everything you can do with a list, dict, set, file, etc: http://docs.python.org/library/stdtypes.html Kent From kent37 at tds.net Sun Nov 2 19:55:02 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 2 Nov 2008 14:55:02 -0400 Subject: [Tutor] Manipulate list in place or append to a new list In-Reply-To: <490DD854.3040200@free.fr> References: <1c2a2c590811020432g10009a11j8264fa987ed36475@mail.gmail.com> <490DD854.3040200@free.fr> Message-ID: <1c2a2c590811021055g3845f525wcf4638c3d8edf8bb@mail.gmail.com> On Sun, Nov 2, 2008 at 12:41 PM, spir wrote: > Sander Sweers a ?crit : >>> Note that this creates a new list, replacing the one that was in >>> somelist. If you need to actually modify somelist in place (rare) then >>> use somelist[:] = [ x+1 for x in somelist ] >>> >>> which creates a new list, then replaces the *contents* of somelist >>> with the contents of the new list. >> >> In what (rare) situation would you use this? > > [post sent again -- seems not to have reached the list -- ??] > When you need to cleanup or normalize the objects held in a list. For > instance, > in text processing: > lines = text.splitlines() > lines = [line.strip() for line in lines] > These are good examples of list comp but note that Sander was specifically asking when you might want to replace a list in place using the somelist[:] syntax. Kent From srilyk at gmail.com Sun Nov 2 20:53:40 2008 From: srilyk at gmail.com (W W) Date: Sun, 2 Nov 2008 14:53:40 -0500 Subject: [Tutor] Iterate by twos Message-ID: <333efb450811021153t2f4ce954oaf4f086c3073fe9b@mail.gmail.com> is there a better/more pythonic way to do something like this? spam = ['c','c','v','c','v'] for x in xrange(0,5,2): print spam[x], spam[x+1] There are other things I'll be doing with the values, but I want to get them in chunks of two. (I realize that this code will throw errors, it's just a hasty example of what I need) 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 -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Sun Nov 2 21:50:48 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 2 Nov 2008 16:50:48 -0400 Subject: [Tutor] err... list.pairs()? In-Reply-To: <490E0212.2060600@free.fr> References: <1c2a2c590811020432g10009a11j8264fa987ed36475@mail.gmail.com> <490DD670.7040505@free.fr> <1c2a2c590811021053s5c43bd63gcca2a752e57c9852@mail.gmail.com> <490E0212.2060600@free.fr> Message-ID: <1c2a2c590811021250yf320e10vb784298b05433f8@mail.gmail.com> On Sun, Nov 2, 2008 at 3:40 PM, spir wrote: > That's it, thank you! I was looking among sequence methods instaed if > built-in functions. You're welcome. Making it a function instead of a method allows it to be applied to any kind of sequence - actually any kind of iterable, including generator expressions and user-defined iterators. Kent From kent37 at tds.net Sun Nov 2 22:02:02 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 2 Nov 2008 17:02:02 -0400 Subject: [Tutor] Iterate by twos In-Reply-To: <333efb450811021153t2f4ce954oaf4f086c3073fe9b@mail.gmail.com> References: <333efb450811021153t2f4ce954oaf4f086c3073fe9b@mail.gmail.com> Message-ID: <1c2a2c590811021302x5d1f0c23tc18c7f1c78ed43b5@mail.gmail.com> On Sun, Nov 2, 2008 at 3:53 PM, W W wrote: > is there a better/more pythonic way to do something like this? > > spam = ['c','c','v','c','v'] > > for x in xrange(0,5,2): > print spam[x], spam[x+1] You could use this function (from the itertools recipes): def grouper(n, iterable, fillvalue=None): "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx" args = [iter(iterable)] * n return itertools.izip_longest(fillvalue=fillvalue, *args) This problem has many solutions. It is a perennial on comp.lang.python and in the Python Cookbook, perhaps because none of the solutions is compellingly better than the rest. They also vary depending on how they handle missing values in the last group. Here is a thread on comp.lang.python with some ideas: http://groups.google.com/group/comp.lang.python/browse_thread/thread/4696a3b3e1a6d691/ But really, what you did is fine. Here is a simple generator for pairs that returns a short pair if len(seq) is odd: def pairs(seq): for i in xrange(0, len(seq), 2): yield seq[i:i+2] Kent From jwcaldwell33147 at yahoo.com Sun Nov 2 21:59:16 2008 From: jwcaldwell33147 at yahoo.com (john caldwell) Date: Sun, 2 Nov 2008 12:59:16 -0800 (PST) Subject: [Tutor] request from john caldwell to get off the mailing list Message-ID: <429307.20932.qm@web54205.mail.re2.yahoo.com> Please take me oof of the mailing list. thank you jwcaldwell33147 at yahoo.com From denis.spir at free.fr Sun Nov 2 22:11:19 2008 From: denis.spir at free.fr (spir) Date: Sun, 02 Nov 2008 22:11:19 +0100 Subject: [Tutor] value and object names Message-ID: <490E1777.10500@free.fr> I have just read the following article: http://effbot.org/zone/python-objects.htm (thanks to a link on Kent's site). It is very good, I really recommend it. Still, a short passage has troubled my model about object names: "The names are a bit different ? they?re not really properties of the object, and the object itself doesn?t know what it?s called. An object can have any number of names, or no name at all. Names live in namespaces (such as a module namespace, an instance namespace, a function?s local namespace)." What I guess: The second and third sentence seem to refer to variable names; meaning that objects 'live their life' whatever the number of variables (0, 1 or more) that point to them. These (variable) names are independant of the object -- and conversely. Now, the first sentence contradicts all what I thought I know on the topic! For me, not only /many/ types of objects have names, but they know about it, and these names are *really* bound to the object -- not to a variable pointing at it. Try the following: def smeagol(): pass print smeagol.__name__ # --> 'smeagol' gollum = smeagol print gollum.__name__ # --> 'smeagol' clear enough ;-) I have the impression that what the article says applies to traditional built-in, non-object, data or values (or to the so-called C++ "data object"). In fact, even if types and classes are unified, even if values are object in Python, well, maybe some kinds of objects must remain different of others. Because there is a difference of nature. My model is that there is still a difference between 'real' values and 'real' objects. Values are things ordinary used to described a quality or property: bools, ints, strings... These things have no names. They have value representations instead. To access the integer usually written '1' or 'one', I need no name: I will use a conventional representation that happens to be '1' and is also used as its __repr__. When I write "a=1", I create a variable which is bound to 1 which name is 'a'. But 'a' has nothing to do with 1. print dir(1) [..., '__repr__', ...] # no name Now, 'real' objects, that we usually call class instances, that fit well in a model as parts of a system, have no representation. So that they need names: how could I access smeagol, once created, if it had no name? On the other hand, such objects have no value. I mean no "natural" value. I can simulate a value for an instance by implementing several __xxx__ methods such as __eq__ (there may be a global __value__ method, I would love it). This distinction between representation for values and names for (other) object is not a python idiom. I think it simply can't be else, values are simply something different. Denis From kent37 at tds.net Sun Nov 2 23:38:09 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 2 Nov 2008 17:38:09 -0500 Subject: [Tutor] value and object names In-Reply-To: <490E1777.10500@free.fr> References: <490E1777.10500@free.fr> Message-ID: <1c2a2c590811021438y2c6ac60fs5c557ca5b77e4bc5@mail.gmail.com> On Sun, Nov 2, 2008 at 5:11 PM, spir wrote: > I have just read the following article: > http://effbot.org/zone/python-objects.htm > (thanks to a link on Kent's site). It is very good, I really recommend it. > > Still, a short passage has troubled my model about object names: > "The names are a bit different ? they're not really properties of the > object, and the object itself doesn't know what it's called. > An object can have any number of names, or no name at all. > Names live in namespaces (such as a module namespace, an instance namespace, > a function's local namespace)." > > What I guess: The second and third sentence seem to refer to variable names; > meaning that objects 'live their life' whatever the number of variables (0, > 1 or more) that point to them. These (variable) names are independant of the > object -- and conversely. > Now, the first sentence contradicts all what I thought I know on the topic! > For me, not only /many/ types of objects have names, but they know about it, > and these names are *really* bound to the object -- not to a variable > pointing at it. All three sentences are talking about variable names. Variable names are not a property of the object referred to, and an object doesn't know all the names it is bound to. > Try the following: > > def smeagol(): > pass > print smeagol.__name__ # --> 'smeagol' > gollum = smeagol > print gollum.__name__ # --> 'smeagol' > > clear enough ;-) Well...you have shown that functions have __name__ attributes that contain the name that was given for the function when it was defined. But gollum.__name__ == 'smeagol' shows the effbot's point, that the function smeagol doesn't know that it is bound to the name gollum. > I have the impression that what the article says applies to traditional > built-in, non-object, data or values (or to the so-called C++ "data > object"). In fact, even if types and classes are unified, even if values are > object in Python, well, maybe some kinds of objects must remain different of > others. Because there is a difference of nature. > My model is that there is still a difference between 'real' values and > 'real' objects. No. *All* values are instances of some class. The article applies to all values. > Values are things ordinary used to described a quality or property: bools, > ints, strings... No, values are instances of classes. You are making this too complicated. > These things have no names. You mean, they have no __name__ attribute. > They have value representations > instead. To access the integer usually written '1' or 'one', I need no name: > I will use a conventional representation that happens to be '1' and is also > used as its __repr__. When I write "a=1", I create a variable which is bound > to 1 which name is 'a'. But 'a' has nothing to do with 1. > print dir(1) > [..., '__repr__', ...] # no name The compiler knows about some kinds of literal values - numeric types, strings, lists, dicts - but they are still instances of classes. They just have some special compiler support. > Now, 'real' objects, that we usually call class instances, that fit well in > a model as parts of a system, have no representation. So that they need > names: how could I access smeagol, once created, if it had no name? The __name__ attribute of smeagol doesn't help you access it. You access it through the name(s) it is bound to. In your example, you could del smeagol to remove the name smeagol, and still access the function through the name gollum. You can also save references to values in collections and as attributes of other classes; they may not be bound to any name. When a value is not bound to any name (or otherwise referenced), it is inaccessible and eligible to be garbage collected. > On the > other hand, such objects have no value. I mean no "natural" value. I can > simulate a value for an instance by implementing several __xxx__ methods > such as __eq__ (there may be a global __value__ method, I would love it). They have the value of themselves. There is no such thing as a "natural" value in Python. You are making this too complicated. Python is in many ways very simple, that is one of its strengths. You are drawing artificial distinctions that don't make much sense to me. One distinction that is used in Python is between mutable and immutable values. Strings, numeric types and tuples are immutable - they can't be changed after they are created. Lists, dicts and sets are mutable - they can be changed. Kent From ericfisher22 at gmail.com Mon Nov 3 03:53:41 2008 From: ericfisher22 at gmail.com (Sean Fisher) Date: Sun, 2 Nov 2008 20:53:41 -0600 Subject: [Tutor] unsubscribing to tutor assistance Message-ID: <1808007d0811021853t6857f5eewe7da63b7d9907583@mail.gmail.com> please end y tutor e-mail assistance Thank you -- Sean Eric Fisher -------------- next part -------------- An HTML attachment was scrubbed... URL: From sudhir.tact.mca at gmail.com Mon Nov 3 06:09:57 2008 From: sudhir.tact.mca at gmail.com (sudhir sahu) Date: Mon, 3 Nov 2008 10:39:57 +0530 Subject: [Tutor] sudhir.tact.mca@gmail.com Message-ID: <4c0a2dab0811022109j322650abp1f75ca2dbd94415f@mail.gmail.com> -------------- next part -------------- An HTML attachment was scrubbed... URL: From dineshbvadhia at hotmail.com Mon Nov 3 08:20:47 2008 From: dineshbvadhia at hotmail.com (Dinesh B Vadhia) Date: Sun, 2 Nov 2008 23:20:47 -0800 Subject: [Tutor] pickling, writing, reading individual lists from a file Message-ID: I want to pickle a bunch of lists and write each list separately to a fileand then read them back. Here is my code with the EOF error: import cPickle as pickle m = [[1, 2, 3, 4], [5, 6, 7, 8, 9, 10], [11, 12, 13, 14]] filename = 'lists.txt' fw = open(filename, 'w') for l in m: n = pickle.dumps(l, 2) + "\n" fw.write(n) fw.close() fr = open(filename, 'r') for line in fr: line = line.rstrip("\n") line = pickle.loads(line) print line fr.close() Traceback (most recent call last): File "....py", line 61, in line = pickle.loads(line) EOFError If I change the read file code to: lines = fr.readlines() print lines for line in lines: line = line.rstrip("\n") line = pickle.loads(line) print line fr.close() The error message is: ['\x80\x02]q\x01(K\x01K\x02K\x03K\x04e.\n', '\x80\x02]q\x01(K\x05K\x06K\x07K\x08K\tK\n', 'e.\n', '\x80\x02]q\x01(K\x0bK\x0cK\rK\x0ee.\n'] [1, 2, 3, 4] Traceback (most recent call last): File "....py", line 73, in line = pickle.loads(line) EOFError Note how the list lines contains 4 elements instead of 3. Dinesh -------------- next part -------------- An HTML attachment was scrubbed... URL: From lie.1296 at gmail.com Mon Nov 3 11:45:33 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Mon, 3 Nov 2008 10:45:33 +0000 (UTC) Subject: [Tutor] request from john caldwell to get off the mailing list References: <429307.20932.qm@web54205.mail.re2.yahoo.com> Message-ID: On Sun, 02 Nov 2008 12:59:16 -0800, john caldwell wrote: > Please take me oof of the mailing list. thank you > jwcaldwell33147 at yahoo.com > > You can unsubscribe from here: http://mail.python.org/mailman/listinfo/ tutor alternatively, you can also send some magic mail to a magic email address containing some magic subject line and content. I think for this mailing list, the magic address is: mailman-request at python.org, send a message containing just 'help' From lie.1296 at gmail.com Mon Nov 3 11:45:44 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Mon, 3 Nov 2008 10:45:44 +0000 (UTC) Subject: [Tutor] unsubscribing to tutor assistance References: <1808007d0811021853t6857f5eewe7da63b7d9907583@mail.gmail.com> Message-ID: On Sun, 02 Nov 2008 20:53:41 -0600, Sean Fisher wrote: > please end y tutor e-mail assistance > Thank you You can unsubscribe from here: http://mail.python.org/mailman/listinfo/ tutor alternatively, you can also send some magic mail to a magic email address containing some magic subject line and content. I think for this mailing list, the magic address is: mailman-request at python.org, send a message containing just 'help' From lie.1296 at gmail.com Mon Nov 3 11:52:51 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Mon, 3 Nov 2008 10:52:51 +0000 (UTC) Subject: [Tutor] (no subject) References: <1162.41.210.18.243.1225538226.squirrel@iptech-ghana.com> Message-ID: On Sat, 01 Nov 2008 06:17:06 -0500, otu wrote: > Dear Friends, > I have just started learning python programming. I have no previous > programming knowledge. > I am presently using Python 2.6 windows version. I am struggling with > how to enable executable files. I copied the ff program on idlle > non-interactice and run it. > > the_world_is_flat =1 > if the_world_is_flat: > print"Be careful not to fall off" > > > > > The result came out on the interactive window. I saved this as > "example.py" on the desktop. The python icon appears on the the desktop > alright. When I attempt to run it by double clicking the icon, only a > black DOS window flashes. I know I am doing something seriously wrong. > What is it? > Regards, > Bennedy. There are two ways to answer your problem. First, you open the command prompt (Start > Run > cmd) then change directory (cd) to where your script is located (e.g. cd C:/scripts/ test.py). Then run the script with "python " (including the .py extension) Second alternative, which is usually easier if you're not comfortable with working in command prompt, is to use an IDE (Integrated Development Environment), python ships with an IDE called IDLE by default. From lie.1296 at gmail.com Mon Nov 3 12:15:28 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Mon, 3 Nov 2008 11:15:28 +0000 (UTC) Subject: [Tutor] pickling, writing, reading individual lists from a file References: Message-ID: On Sun, 02 Nov 2008 23:20:47 -0800, Dinesh B Vadhia wrote: > I want to pickle a bunch of lists and write each list separately to a > fileand then read them back. Here is my code with the EOF error: > > filename = 'lists.txt' > fw = open(filename, 'w') > for l in m: > n = pickle.dumps(l, 2) + "\n" > fw.write(n) > fw.close() That is because a pickle.dumps() produces a string of bytes, and may contain "\n". When you try to read the file, you split the file based on "\n", since the original pickled items contains "\n", you split the pickled data in places where it shouldn't be. To solve your problem, you have several alternative possibilities: 1. just pickle the whole of them 2. put each pickled object in separate file (alternatively zipping them if you have a lot of them) 3. choose a separator that is guaranteed that pickle wouldn't emit 4. escape the separator you choose 5. put the pickled data in a list/dict, then pickle that list/dict 1. pickle.dump(m, 'lists.p', 2) 2. for i, l in enumerate(m): pickle.dump(l, 'list%s.p' % i, 2) 3. #from __future__ import with_statement # uncomment the line above if python version < 2.6 separator = "something pickle wouldn't emit" with open('lists.txt', 'w') as fw: for l in m: n = pickle.dumps(l, 2) + separator fw.write(n) 4. separator = "|" with open('lists.txt', 'w') as fw: for l in m: n = escape(pickle.dumps(l, 2)) + separator fw.write(n) 5. # since the objects you're pickling is already in a list # this solution is exactly the same as solution #1 # however, in cases where the object you intend to pickle # is scattered, you should make a dict/list. From kent37 at tds.net Mon Nov 3 12:42:28 2008 From: kent37 at tds.net (Kent Johnson) Date: Mon, 3 Nov 2008 06:42:28 -0500 Subject: [Tutor] pickling, writing, reading individual lists from a file In-Reply-To: References: Message-ID: <1c2a2c590811030342t7e86bc60h3b0787eb86cfad95@mail.gmail.com> On Mon, Nov 3, 2008 at 6:15 AM, Lie Ryan wrote: > On Sun, 02 Nov 2008 23:20:47 -0800, Dinesh B Vadhia wrote: > >> I want to pickle a bunch of lists and write each list separately to a >> fileand then read them back. > To solve your problem, you have several alternative possibilities: 6. Make multiple calls to dump() and load() using an explicit pickler, pickling directly to the file (not tested): filename = 'lists.txt' fw = open(filename, 'wb') # Note open in binary mode for protocol 2 pickler = pickle.Pickler(fw, 2) for l in m: pickler.dump(l) fw.close() fr = open(filename, 'rb') pickler = pickle.Unpickler(fr) for i in range(3): line = pickler.load(fr) print line fr.close() Kent From lie.1296 at gmail.com Mon Nov 3 12:53:08 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Mon, 3 Nov 2008 11:53:08 +0000 (UTC) Subject: [Tutor] pickling, writing, reading individual lists from a file References: <1c2a2c590811030342t7e86bc60h3b0787eb86cfad95@mail.gmail.com> Message-ID: On Mon, 03 Nov 2008 06:42:28 -0500, Kent Johnson wrote: > On Mon, Nov 3, 2008 at 6:15 AM, Lie Ryan wrote: >> On Sun, 02 Nov 2008 23:20:47 -0800, Dinesh B Vadhia wrote: >> >>> I want to pickle a bunch of lists and write each list separately to a >>> fileand then read them back. > >> To solve your problem, you have several alternative possibilities: > > 6. Make multiple calls to dump() and load() using an explicit pickler, > pickling directly to the file (not tested): > > filename = 'lists.txt' > fw = open(filename, 'wb') # Note open in binary mode for protocol 2 > pickler = pickle.Pickler(fw, 2) > for l in m: > pickler.dump(l) > fw.close() > > fr = open(filename, 'rb') > pickler = pickle.Unpickler(fr) > for i in range(3): > line = pickler.load(fr) > print line > fr.close() Ah, I see, that's why the pickle module contains Pickler object. btw, I have to add, none of the five code I wrote is tested at all, and definitely #4 wouldn't work as it assumed there is a function that could automagically escape the string. And, using Pickler object is probably the best solution here. From btkuhn at email.unc.edu Mon Nov 3 04:33:20 2008 From: btkuhn at email.unc.edu (btkuhn at email.unc.edu) Date: Sun, 02 Nov 2008 22:33:20 -0500 Subject: [Tutor] Tkinter troubles Message-ID: <20081102223320.3p6jw4wogsgo08wk@webmail4.isis.unc.edu> Hi guys, I'm having trouble with weird activity with a Tkinter GUI I'm creating. I've stripped down the code somewhat to simplify the problem somewhat, and I've posted it below, with further explanation at the end of this message: from Tkinter import * import tkFileDialog,tkSimpleDialog WINDOWWIDTH=500 WINDOWHEIGHT=500 class App: def __init__ (self,master): self.window = Frame(master) self.window.pack() self.master= master #Create frame to contain all others self.display=Frame(self.window,width=WINDOWWIDTH,height=WINDOWHEIGHT, bg='black') self.display.pack() self.addMenu(self.master) #Create widgets self.createwidgets() def createwidgets(self): self.leftframe=Frame(self.display, width=WINDOWWIDTH/3,height=WINDOWHEIGHT, bg='white') self.rightframe=Frame(self.display, width=2*WINDOWWIDTH/3,height=WINDOWHEIGHT, bg='blue') self.leftframe.pack(side="left", expand="yes", fill="x") self.rightframe.pack(side="left", expand="yes", fill="x") def displayStories(self): self.lb = Text(self.leftframe) self.lb.pack() def addMenu(self,master): self.menu = Menu(self.window) master.config(menu=self.menu) self.feedmenu = Menu(self.menu) self.menu.add_cascade(label="RSS", menu=self.feedmenu) self.feedmenu.add_command(label="Load RSS", command=self.displayStories) root=Tk() app=App(root) root.mainloop() : Basically I'm trying to create 2 columns on the page so that (eventually) I will be able to have sepearte text boxes in each column. The code so far creates a leftframe and rightframe, with parent frame self.display . When I run the script this happens as expected. But next, I want to create a text box within self.leftframe which is done in function displayStories . self.lb is created with parent self.leftframe . When this is run, the text box shows up, but my layout goes to hell. I want the text box to be contained within self.leftframe, but when it is added self.leftframe disappears (or is completely filled by the text box), the dimensions that I had specified for self.leftframe and self.rightframe are forgotten about, and I can see self.display (black background) on the part of the screen in the left frame that is not filled by the text box. This makes a lot more sense if you run the simple script I've posted. I've tried adjusting various options, and also using the "grid" manager instead of "pack", but I can't seem to figure out why this is happening. Can anyone help out? Thanks, Luke -------------- next part -------------- An HTML attachment was scrubbed... URL: From dineshbvadhia at hotmail.com Mon Nov 3 15:03:47 2008 From: dineshbvadhia at hotmail.com (Dinesh B Vadhia) Date: Mon, 3 Nov 2008 06:03:47 -0800 Subject: [Tutor] pickling, writing, reading individual lists from a file Message-ID: Just one change - pickler.load() doesn't take an argument - otherwise works perfectly! Thank-you. ... 6. Make multiple calls to dump() and load() using an explicit pickler, pickling directly to the file (not tested): import cPickle as pickle filename = 'lists.txt' fw = open(filename, 'wb') # Note open in binary mode for protocol 2 pickler = pickle.Pickler(fw, 2) for l in m: pickler.dump(l) fw.close() fr = open(filename, 'rb') pickler = pickle.Unpickler(fr) for i in range(3): line = pickler.load() print line fr.close() ... Dinesh -------------------------------------------------------------------------------- From: Kent Johnson tds.net> Subject: Re: pickling, writing, reading individual lists from a file Newsgroups: gmane.comp.python.tutor Date: 2008-11-03 11:42:28 GMT (2 hours and 16 minutes ago) On Mon, Nov 3, 2008 at 6:15 AM, Lie Ryan gmail.com> wrote: > On Sun, 02 Nov 2008 23:20:47 -0800, Dinesh B Vadhia wrote: > >> I want to pickle a bunch of lists and write each list separately to a >> fileand then read them back. > To solve your problem, you have several alternative possibilities: 6. Make multiple calls to dump() and load() using an explicit pickler, pickling directly to the file (not tested): filename = 'lists.txt' fw = open(filename, 'wb') # Note open in binary mode for protocol 2 pickler = pickle.Pickler(fw, 2) for l in m: pickler.dump(l) fw.close() fr = open(filename, 'rb') pickler = pickle.Unpickler(fr) for i in range(3): line = pickler.load(fr) print line fr.close() Kent -------------- next part -------------- An HTML attachment was scrubbed... URL: From nephish at gmail.com Mon Nov 3 15:14:54 2008 From: nephish at gmail.com (shawn bright) Date: Mon, 3 Nov 2008 08:14:54 -0600 Subject: [Tutor] how to read over serial port In-Reply-To: <384c93600811020950y166e5ce4r5c472a2af8c26fa5@mail.gmail.com> References: <384c93600811011945x3a6922f9hf3e0faac604070cd@mail.gmail.com> <490DC977.8080207@brianlane.com> <384c93600811020950y166e5ce4r5c472a2af8c26fa5@mail.gmail.com> Message-ID: <384c93600811030614ja686a77w2abc72cebcb1a623@mail.gmail.com> Hey all, sorry, but am i supposed to be using 'rb' to read this? thanks sk On Sun, Nov 2, 2008 at 11:50 AM, shawn bright wrote: > Thanks all, > Yeah, checked the settings, and when i have the thing talk to a > program that just prints out whatever the serial port reads, It was > looking fine. > Incorrect baudrate was my first problem, and did cause weirdness, > escpeially on the latter end of the message, but this isn't the same > problem. Just don't know how to read it. > thanks > > shawn > > > On Sun, Nov 2, 2008 at 9:38 AM, Brian C. Lane wrote: >> -----BEGIN PGP SIGNED MESSAGE----- >> Hash: SHA1 >> >> shawn bright wrote: >>> Hey there all, >>> >>> I have a gps device that talks to the computer over a serial port. >>> i am using the pyserial module and getting values in. >> >> Here are the relevant bits of a serial to tcp/ip app that I use. Most >> likely you have the wrong baudrate set. If it is an older GPS device the >> baudrate will be 4800, newer devices allow you to set it to higher >> speeds, 9600 being standard. Check the device settings to make sure that >> it doesn't have any weird parity settings too. 8 bits, No Parity, 1 stop >> bit is common. >> >> >> import sys >> import serial >> >> port = "/dev/ttyS0" >> baud = 9600 >> >> ser = serial.Serial() >> ser.port = port >> ser.baudrate = baud >> >> try: >> ser.open() >> except: >> sys.stderr.write("Error opening serial port %s\n" % (ser.portstr) ) >> sys.exit(1) >> >> ser.setRtsCts(0) >> >> while 1: >> # Read from serial port, blocking >> data = ser.read(1) >> >> # If there is more than 1 byte, read the rest >> n = ser.inWaiting() >> if n: >> data = data + ser.read(n) >> >> sys.stdout.write(data) >> >> >> >> - -- >> - ---[Office 68.7F]--[Outside 51.0F]--[Server 103.2F]--[Coaster 70.0F]--- >> - ---[ TACOMA WSF (366772760) @ 47 36.3260 -122 23.1697 ]--- >> Software, Linux, Microcontrollers http://www.brianlane.com >> AIS Parser SDK http://www.aisparser.com >> >> -----BEGIN PGP SIGNATURE----- >> Version: GnuPG v1.4.8 (Darwin) >> Comment: Remember Lexington Green! >> >> iD8DBQFJDcl3Iftj/pcSws0RAs2+AJ91ynHgzdXDfVpbh37iM7XITnDI7wCeNON8 >> qxyWcuc5opuOpeRCJ6cWr+o= >> =fPs4 >> -----END PGP SIGNATURE----- >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> > From dave6502 at googlemail.com Mon Nov 3 15:46:09 2008 From: dave6502 at googlemail.com (dave selby) Date: Mon, 3 Nov 2008 14:46:09 +0000 Subject: [Tutor] stopping threads ? Message-ID: Hi All, Why when I use threads in my app (I know they are evil ...lol) does it not stop with ctrl-c, I have to use ctrl-z ? Cheers Dave -- Please avoid sending me Word or PowerPoint attachments. See http://www.gnu.org/philosophy/no-word-attachments.html From nephish at gmail.com Mon Nov 3 15:48:44 2008 From: nephish at gmail.com (shawn bright) Date: Mon, 3 Nov 2008 08:48:44 -0600 Subject: [Tutor] how to read over serial port In-Reply-To: <384c93600811030614ja686a77w2abc72cebcb1a623@mail.gmail.com> References: <384c93600811011945x3a6922f9hf3e0faac604070cd@mail.gmail.com> <490DC977.8080207@brianlane.com> <384c93600811020950y166e5ce4r5c472a2af8c26fa5@mail.gmail.com> <384c93600811030614ja686a77w2abc72cebcb1a623@mail.gmail.com> Message-ID: <384c93600811030648y57513d48kbcb791350b0c9b99@mail.gmail.com> ok, i have another question: if i run this: #!/usr/bin/env python f = 'test_out' f = open(f, 'r').read() for i in f: print ord(i) I get this: 0 6 0 58 128 31 22 103 74 115 222 192 74 115 222 192 (deleted some in the email for brevity) if i do for i in f: print chr(ord(i)) i get the same weird characters. should these be read some other way? thanks, shawn On Mon, Nov 3, 2008 at 8:14 AM, shawn bright wrote: > Hey all, sorry, but am i supposed to be using 'rb' to read this? > thanks > > sk > > On Sun, Nov 2, 2008 at 11:50 AM, shawn bright wrote: >> Thanks all, >> Yeah, checked the settings, and when i have the thing talk to a >> program that just prints out whatever the serial port reads, It was >> looking fine. >> Incorrect baudrate was my first problem, and did cause weirdness, >> escpeially on the latter end of the message, but this isn't the same >> problem. Just don't know how to read it. >> thanks >> >> shawn >> >> >> On Sun, Nov 2, 2008 at 9:38 AM, Brian C. Lane wrote: >>> -----BEGIN PGP SIGNED MESSAGE----- >>> Hash: SHA1 >>> >>> shawn bright wrote: >>>> Hey there all, >>>> >>>> I have a gps device that talks to the computer over a serial port. >>>> i am using the pyserial module and getting values in. >>> >>> Here are the relevant bits of a serial to tcp/ip app that I use. Most >>> likely you have the wrong baudrate set. If it is an older GPS device the >>> baudrate will be 4800, newer devices allow you to set it to higher >>> speeds, 9600 being standard. Check the device settings to make sure that >>> it doesn't have any weird parity settings too. 8 bits, No Parity, 1 stop >>> bit is common. >>> >>> >>> import sys >>> import serial >>> >>> port = "/dev/ttyS0" >>> baud = 9600 >>> >>> ser = serial.Serial() >>> ser.port = port >>> ser.baudrate = baud >>> >>> try: >>> ser.open() >>> except: >>> sys.stderr.write("Error opening serial port %s\n" % (ser.portstr) ) >>> sys.exit(1) >>> >>> ser.setRtsCts(0) >>> >>> while 1: >>> # Read from serial port, blocking >>> data = ser.read(1) >>> >>> # If there is more than 1 byte, read the rest >>> n = ser.inWaiting() >>> if n: >>> data = data + ser.read(n) >>> >>> sys.stdout.write(data) >>> >>> >>> >>> - -- >>> - ---[Office 68.7F]--[Outside 51.0F]--[Server 103.2F]--[Coaster 70.0F]--- >>> - ---[ TACOMA WSF (366772760) @ 47 36.3260 -122 23.1697 ]--- >>> Software, Linux, Microcontrollers http://www.brianlane.com >>> AIS Parser SDK http://www.aisparser.com >>> >>> -----BEGIN PGP SIGNATURE----- >>> Version: GnuPG v1.4.8 (Darwin) >>> Comment: Remember Lexington Green! >>> >>> iD8DBQFJDcl3Iftj/pcSws0RAs2+AJ91ynHgzdXDfVpbh37iM7XITnDI7wCeNON8 >>> qxyWcuc5opuOpeRCJ6cWr+o= >>> =fPs4 >>> -----END PGP SIGNATURE----- >>> _______________________________________________ >>> Tutor maillist - Tutor at python.org >>> http://mail.python.org/mailman/listinfo/tutor >>> >> > From monte at milanuk.net Mon Nov 3 15:54:33 2008 From: monte at milanuk.net (Monte Milanuk) Date: Mon, 3 Nov 2008 06:54:33 -0800 (PST) Subject: [Tutor] string.join() Message-ID: <63368.31520.qm@web604.biz.mail.mud.yahoo.com> Hello again, Just looking for clarification on a point: the book I'm using is written around Python v.2.3, and has an exercise using string.join(). Specifically, it said to use string.join(msgList, ""), the object of which was to take the list items in msgList and concatenate them using a blank or no character between. After some work it did work as advertised, which is all well and good, but I hit a bit of a snag along the way. I *think* I got it figgered out, but would like some verification. Basically... when I was reading through the documentation trying to decide how to re-write an earlier program using string.join() as described above... I noticed the docs said that a bunch of string functions were deprecated and going away in Python 3.0. As such... I thought perhaps since I was in the neighborhood so to speak maybe I should learn to do things the 'new' way. It took me a while to get from string.join(words[, sep]) to str.join()... which almost immediately puked and didn't work. After a while longer, I finally noticed somewhere that 'str' was supposed to be the string used for the separator, so I use ''.join(msgList), which seems to work (or at least give identical output) in this case. So... do I have it correct? Yes/no/maybe? Thanks, Monte -------------- next part -------------- An HTML attachment was scrubbed... URL: From timmichelsen at gmx-topmail.de Mon Nov 3 16:54:45 2008 From: timmichelsen at gmx-topmail.de (Timmie) Date: Mon, 3 Nov 2008 15:54:45 +0000 (UTC) Subject: [Tutor] How to check online status Message-ID: Dear fellow Pythonistas, is it possible to check with Python whether a computer is connected to the internet or not? I don't not find a module which can do such a thing like 'ping'? And how do I make my python scipts that use urllib to recognize the windows operating system proxy settings? Thanks in advance and kind regards, Timmie From a.t.hofkamp at tue.nl Mon Nov 3 17:01:27 2008 From: a.t.hofkamp at tue.nl (A.T.Hofkamp) Date: Mon, 03 Nov 2008 17:01:27 +0100 Subject: [Tutor] string.join() In-Reply-To: <63368.31520.qm@web604.biz.mail.mud.yahoo.com> References: <63368.31520.qm@web604.biz.mail.mud.yahoo.com> Message-ID: <490F2057.6040303@tue.nl> Monte Milanuk wrote: > Hello again, > > Just looking for clarification on a point: the book I'm using is written around Python v.2.3, and has an exercise using string.join(). Specifically, it said to use string.join(msgList, ""), the object of which was to take the list items in msgList and concatenate them using a blank or no character between. After some work it did work as advertised, which is all well and good, but I hit a bit of a snag along the way. I *think* I got it figgered out, but would like some verification. looks fine to me. An experiment in Python confirmed that: Python 2.3.4 (#1, Jul 25 2008, 14:24:21) [GCC 3.4.6 20060404 (Red Hat 3.4.6-10)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import string >>> string.join(['a', 'b', 'c'], '-') 'a-b-c' each value in the list gets seperated from other value(s) by the seperator string ("-" in this case). neighborhood so to speak maybe I should learn to do things the 'new' way. It took me a while to get from string.join(words[, sep]) to str.join()... which almost immediately puked and didn't work. After a while longer, I finally noticed somewhere that 'str' was supposed to be the string used for the separator, so I use ''.join(msgList), which seems to work (or at least give identical output) in this case. Correct too: >>> '-'.join(['a', 'b', 'c']) 'a-b-c' This is indeed the recommended way of joining strings. Sincerely, Albert From kent37 at tds.net Mon Nov 3 16:54:20 2008 From: kent37 at tds.net (Kent Johnson) Date: Mon, 3 Nov 2008 11:54:20 -0400 Subject: [Tutor] string.join() In-Reply-To: <63368.31520.qm@web604.biz.mail.mud.yahoo.com> References: <63368.31520.qm@web604.biz.mail.mud.yahoo.com> Message-ID: <1c2a2c590811030754s639dc473y6f349549039b8205@mail.gmail.com> On Mon, Nov 3, 2008 at 10:54 AM, Monte Milanuk wrote: > Hello again, > > Just looking for clarification on a point: the book I'm using is written > around Python v.2.3, and has an exercise using string.join(). Specifically, > it said to use string.join(msgList, "") > After a while > longer, I finally noticed somewhere that 'str' was supposed to be the string > used for the separator, so I use ''.join(msgList), which seems to work (or > at least give identical output) in this case. > > So... do I have it correct? Yes/no/maybe? Yes, that is correct. Instead of string.join(seq, sep) use sep.join(seq). Kent From mail at timgolden.me.uk Mon Nov 3 17:08:02 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 03 Nov 2008 16:08:02 +0000 Subject: [Tutor] How to check online status In-Reply-To: References: Message-ID: <490F21E2.3090408@timgolden.me.uk> Timmie wrote: > Dear fellow Pythonistas, > is it possible to check with Python whether a computer is connected to the > internet or not? You've got several options. The simplest, cross-platform solution is to connect a socket to a known port on a known server with a timeout and see if it connects. But there are ping-alike Python modules around if that's really what you want: http://www.google.co.uk/search?hl=en&q=python+ping+module > And how do I make my python scipts that use urllib to recognize the windows > operating system proxy settings? http://docs.python.org/howto/urllib2.html TJG From srilyk at gmail.com Mon Nov 3 17:12:07 2008 From: srilyk at gmail.com (W W) Date: Mon, 3 Nov 2008 10:12:07 -0600 Subject: [Tutor] How to check online status In-Reply-To: References: Message-ID: <333efb450811030812g68815474q603af8f5ee51c327@mail.gmail.com> On Mon, Nov 3, 2008 at 9:54 AM, Timmie wrote: > Dear fellow Pythonistas, > is it possible to check with Python whether a computer is connected to the > internet or not? Yes. That's the short answer anyway. > I don't not find a module which can do such a thing like 'ping'? you could use the os module to execute the system command "ping" > And how do I make my python scipts that use urllib to recognize the windows > operating system proxy settings? I'm not particularly sure, but at first glance http://www.google.com/search?q=python+urllib+windows+proxy seems to have some useful looking links. HTH, Wayne > > > Thanks in advance and kind regards, > Timmie > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- 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 -------------- next part -------------- An HTML attachment was scrubbed... URL: From lie.1296 at gmail.com Mon Nov 3 18:14:35 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Mon, 3 Nov 2008 17:14:35 +0000 (UTC) Subject: [Tutor] stopping threads ? References: Message-ID: On Mon, 03 Nov 2008 14:46:09 +0000, dave selby wrote: > Hi All, > > Why when I use threads in my app (I know they are evil ...lol) does it > not stop with ctrl-c, I have to use ctrl-z ? > > Cheers > > Dave Wonder why? Because Ctrl-C merely raises KeyboardInterrupt in the main thread, breaking the main thread, while leaving the other threads running. To interrupt a multi-threaded program, you'd need to stop all running threads. Stopping the current thread is usually easy if you write that thread code, it's usually merely breaking the loop or raising an unhandled exception (or an exception handled outside the thread loop). The problem is to communicate to all threads to quit immediately, a common way is by using an event queue, when the main thread receives a Keyboard Interrupt, it sends as many Quit Event as the number of threads. This Quit Event would be caught by each thread and each thread would exits upon receiving the Quit Event. From lie.1296 at gmail.com Mon Nov 3 18:28:05 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Mon, 3 Nov 2008 17:28:05 +0000 (UTC) Subject: [Tutor] how to read over serial port References: <384c93600811011945x3a6922f9hf3e0faac604070cd@mail.gmail.com> <490DC977.8080207@brianlane.com> <384c93600811020950y166e5ce4r5c472a2af8c26fa5@mail.gmail.com> <384c93600811030614ja686a77w2abc72cebcb1a623@mail.gmail.com> <384c93600811030648y57513d48kbcb791350b0c9b99@mail.gmail.com> Message-ID: On Mon, 03 Nov 2008 08:48:44 -0600, shawn bright wrote: > ok, i have another question: > if i run this: > #!/usr/bin/env python > f = 'test_out' > f = open(f, 'r').read() > for i in f: > print ord(i) > > I get this: > 0 > 6 > 0 > 58 > 128 > 31 > 22 > 103 > 74 > 115 > 222 > 192 > 74 > 115 > 222 > 192 (deleted some in the email for brevity) > > if i do > for i in f: > print chr(ord(i)) > i get the same weird characters. > should these be read some other way? Wait... are these "weird" characters in the form of: ?????????????????????? or if you used "print repr(chr(ord(i)))": "\x87\x88\x89\x8a\x8b\x8c\x8d \x8e\x8f\x90\x91" That is python's escape characters. Python's default byte-to-character encoding is ASCII, a 7-bit encoding, values in the range(128, 256) cannot be represented in ASCII so python uses ? to represent these unrepresentable characters. If you used repr(), it would escape the unrepresentable characters into an escaped form, using '\xkk' where kk is the two-digit hexadecimal representing the byte value of the character From lie.1296 at gmail.com Mon Nov 3 18:28:05 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Mon, 3 Nov 2008 17:28:05 +0000 (UTC) Subject: [Tutor] how to read over serial port References: <384c93600811011945x3a6922f9hf3e0faac604070cd@mail.gmail.com> <490DC977.8080207@brianlane.com> <384c93600811020950y166e5ce4r5c472a2af8c26fa5@mail.gmail.com> <384c93600811030614ja686a77w2abc72cebcb1a623@mail.gmail.com> <384c93600811030648y57513d48kbcb791350b0c9b99@mail.gmail.com> Message-ID: On Mon, 03 Nov 2008 08:48:44 -0600, shawn bright wrote: > ok, i have another question: > if i run this: > #!/usr/bin/env python > f = 'test_out' > f = open(f, 'r').read() > for i in f: > print ord(i) > > I get this: > 0 > 6 > 0 > 58 > 128 > 31 > 22 > 103 > 74 > 115 > 222 > 192 > 74 > 115 > 222 > 192 (deleted some in the email for brevity) > > if i do > for i in f: > print chr(ord(i)) > i get the same weird characters. > should these be read some other way? Wait... are these "weird" characters in the form of: ?????????????????????? or if you used "print repr(chr(ord(i)))": "\x87\x88\x89\x8a\x8b\x8c\x8d \x8e\x8f\x90\x91" That is python's escape characters. Python's default byte-to-character encoding is ASCII, a 7-bit encoding, values in the range(128, 256) cannot be represented in ASCII so python uses ? to represent these unrepresentable characters. If you used repr(), it would escape the unrepresentable characters into an escaped form, using '\xkk' where kk is the two-digit hexadecimal representing the byte value of the character From monte at milanuk.net Mon Nov 3 17:09:30 2008 From: monte at milanuk.net (Monte Milanuk) Date: Mon, 3 Nov 2008 08:09:30 -0800 (PST) Subject: [Tutor] string.join() Message-ID: <455750.26544.qm@web601.biz.mail.mud.yahoo.com> Thanks for the verification, folks. What had me stumped for a while was the first method was string.join(words[,sep]), and the new one showed str.join(words)... it wasn't immediately obvious (to me) that 'str' was in this case supposed to be the separator. Thanks again, Monte -------------- next part -------------- An HTML attachment was scrubbed... URL: From otu at iptech-ghana.com Mon Nov 3 17:34:55 2008 From: otu at iptech-ghana.com (otu at iptech-ghana.com) Date: Mon, 3 Nov 2008 10:34:55 -0600 (CST) Subject: [Tutor] (no subject) In-Reply-To: <1c2a2c590811010902h2d924533wc2c86b27732e631f@mail.gmail.com> References: <1162.41.210.18.243.1225538226.squirrel@iptech-ghana.com> <1c2a2c590811010902h2d924533wc2c86b27732e631f@mail.gmail.com> Message-ID: <2042.41.210.2.20.1225730095.squirrel@iptech-ghana.com> Thank You! Kent and Kerbros. I got it Regards, Bennedy. > On Sat, Nov 1, 2008 at 7:17 AM, wrote: > >> >> I am struggling with how to enable executable files. I copied the ff >> program on idlle non-interactice and run it. >> >> the_world_is_flat =1 >> if the_world_is_flat: >> print"Be careful not to fall off" >> >> The result came out on the interactive window. I saved this as >> "example.py" on the desktop. The python icon appears on the the desktop >> alright. When I attempt to run it by double clicking the icon, only a >> black DOS window flashes. > > > The problem is that the DOS window closes when the program exits. Try > adding > the line > raw_input("Press return to exit ") > to the end of your program. > > Kent > From kent37 at tds.net Mon Nov 3 19:49:38 2008 From: kent37 at tds.net (Kent Johnson) Date: Mon, 3 Nov 2008 14:49:38 -0400 Subject: [Tutor] stopping threads ? In-Reply-To: References: Message-ID: <1c2a2c590811031049l7a159e1bse81b49950da9b322@mail.gmail.com> On Mon, Nov 3, 2008 at 1:14 PM, Lie Ryan wrote: > On Mon, 03 Nov 2008 14:46:09 +0000, dave selby wrote: > >> Hi All, >> >> Why when I use threads in my app (I know they are evil ...lol) does it >> not stop with ctrl-c, I have to use ctrl-z ? >> >> Cheers >> >> Dave > > Wonder why? Because Ctrl-C merely raises KeyboardInterrupt in the main > thread, breaking the main thread, while leaving the other threads > running. To interrupt a multi-threaded program, you'd need to stop all > running threads. If you mark the non-main threads as daemon threads then the program will exit without stopping them. Kent From nephish at gmail.com Mon Nov 3 22:08:56 2008 From: nephish at gmail.com (shawn bright) Date: Mon, 3 Nov 2008 15:08:56 -0600 Subject: [Tutor] how to read over serial port In-Reply-To: References: <384c93600811011945x3a6922f9hf3e0faac604070cd@mail.gmail.com> <490DC977.8080207@brianlane.com> <384c93600811020950y166e5ce4r5c472a2af8c26fa5@mail.gmail.com> <384c93600811030614ja686a77w2abc72cebcb1a623@mail.gmail.com> <384c93600811030648y57513d48kbcb791350b0c9b99@mail.gmail.com> Message-ID: <384c93600811031308o4eeaace0rdd7bdef7ff7de133@mail.gmail.com> yes, they look like this ?????????????????????? so i used your print repr(chr(ord(i))) and got this '\x00' '\x06' '\x00' ':' '\x80' '\x1f' '\x16' 'g' 'J' 's' '\xde' '\xc0' 'J' 's' '\xde' '\xc0' '\xce' '\xcc' '\x06' '\n' '\x00' '\x00' ' ' '\xaf' 'J' 's' '\xde' '\xc0' so, what do i do now? and thanks for the info, by the way, been writing python for 2 years, but this is all new to me. shawn On Mon, Nov 3, 2008 at 11:28 AM, Lie Ryan wrote: > On Mon, 03 Nov 2008 08:48:44 -0600, shawn bright wrote: > >> ok, i have another question: >> if i run this: >> #!/usr/bin/env python >> f = 'test_out' >> f = open(f, 'r').read() >> for i in f: >> print ord(i) >> >> I get this: >> 0 >> 6 >> 0 >> 58 >> 128 >> 31 >> 22 >> 103 >> 74 >> 115 >> 222 >> 192 >> 74 >> 115 >> 222 >> 192 (deleted some in the email for brevity) >> >> if i do >> for i in f: >> print chr(ord(i)) >> i get the same weird characters. >> should these be read some other way? > > Wait... are these "weird" characters in the form of: > ?????????????????????? > > or if you used "print repr(chr(ord(i)))": "\x87\x88\x89\x8a\x8b\x8c\x8d > \x8e\x8f\x90\x91" > > That is python's escape characters. Python's default byte-to-character > encoding is ASCII, a 7-bit encoding, values in the range(128, 256) cannot > be represented in ASCII so python uses ? to represent these > unrepresentable characters. If you used repr(), it would escape the > unrepresentable characters into an escaped form, using '\xkk' where kk is > the two-digit hexadecimal representing the byte value of the character > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From cspears2002 at yahoo.com Mon Nov 3 22:37:10 2008 From: cspears2002 at yahoo.com (Christopher Spears) Date: Mon, 3 Nov 2008 13:37:10 -0800 (PST) Subject: [Tutor] accessing an image with pygame.image.load() Message-ID: <553438.97767.qm@web51603.mail.re2.yahoo.com> I want to access a spaceship image with pygame.image.load(), so I wrote self.image = pygame.image.load("C:Users\Chris\Documents\python\assignment07\chris_graphics\spaceship.gif") However, I got this error message: error: Couldn't open C:Users\Chris\Documents\python\assignment07\chris_graphics\spaceship.gif I can't give pygame.image.load a path? Does anyone know how I would load an image located in a seperate directory? From malaclypse2 at gmail.com Mon Nov 3 22:49:24 2008 From: malaclypse2 at gmail.com (Jerry Hill) Date: Mon, 3 Nov 2008 16:49:24 -0500 Subject: [Tutor] how to read over serial port In-Reply-To: <384c93600811031308o4eeaace0rdd7bdef7ff7de133@mail.gmail.com> References: <384c93600811011945x3a6922f9hf3e0faac604070cd@mail.gmail.com> <490DC977.8080207@brianlane.com> <384c93600811020950y166e5ce4r5c472a2af8c26fa5@mail.gmail.com> <384c93600811030614ja686a77w2abc72cebcb1a623@mail.gmail.com> <384c93600811030648y57513d48kbcb791350b0c9b99@mail.gmail.com> <384c93600811031308o4eeaace0rdd7bdef7ff7de133@mail.gmail.com> Message-ID: <16651e80811031349x496127f0g9980fc779f5ec4f9@mail.gmail.com> On Mon, Nov 3, 2008 at 4:08 PM, shawn bright wrote: > yes, they look like this > ?????????????????????? > > so i used your print repr(chr(ord(i))) and got this Note that that's the same thing as just printing repr(i). > so, what do i do now? > and thanks for the info, by the way, been writing python for 2 years, > but this is all new to me. Maybe we should back up a little bit. You said in your original post that you were expecting ASCII characters from the serial device. How do you know that's what you should be getting back? Have you tried communicating with the device using some other program? If so, what program? Do you have specs that tell you that's how it's supposed to work? Are you sure you're connecting to the device with the right parameters for baudrate, byte size, parity, etc? I notice that nowhere in this thread have you posted the code you use to actually communicate with the serial device. Maybe you should do that. -- Jerry From lister at lihim.org Mon Nov 3 23:21:47 2008 From: lister at lihim.org (lister at lihim.org) Date: Mon, 3 Nov 2008 16:21:47 -0600 Subject: [Tutor] python based blogging software/cms? Message-ID: <20081103222147.GA5236@remington.svcroot.org> Not sure if this is appropriate for the tutor mailing list, but it is a beginner question for python. It seems most of the popular cms/blogging software is php/mysql based Anything of substancial popularity/support based on python? I was looking for something along the lines of wordpress popular, but not sure if there exists something for python. I'm aware of Zine (http://dev.pocoo.org/projects/zine/ ) that is trying to become wordpress like, any others? Regards, From bgailer at gmail.com Tue Nov 4 00:05:05 2008 From: bgailer at gmail.com (bob gailer) Date: Mon, 03 Nov 2008 18:05:05 -0500 Subject: [Tutor] accessing an image with pygame.image.load() In-Reply-To: <553438.97767.qm@web51603.mail.re2.yahoo.com> References: <553438.97767.qm@web51603.mail.re2.yahoo.com> Message-ID: <490F83A1.5020406@gmail.com> Christopher Spears wrote: > I want to access a spaceship image with pygame.image.load(), so I wrote > > > self.image = pygame.image.load("C:Users\Chris\Documents\python\assignment07\chris_graphics\spaceship.gif") > > However, I got this error message: > > error: Couldn't open C:Users\Chris\Documents\python\assignment07\chris_graphics\spaceship.gif > > I can't give pygame.image.load a path? Does anyone know how I would load an image located in a seperate directory? > Since \ is used to "escape" certain characters it is advisable to either use \\ or preface the string with r. "C:Users\\Chris\\ etc. OR r"C:Users\Chris\ That *might* solve your problem. it is unfortunate that the error messages say can't open rather than file not found. -- Bob Gailer Chapel Hill NC 919-636-4239 When we take the time to be aware of our feelings and needs we have more satisfying interatctions with others. Nonviolent Communication provides tools for this awareness. As a coach and trainer I can assist you in learning this process. What is YOUR biggest relationship challenge? From bill at celestial.net Tue Nov 4 00:30:14 2008 From: bill at celestial.net (Bill Campbell) Date: Mon, 3 Nov 2008 15:30:14 -0800 Subject: [Tutor] python based blogging software/cms? In-Reply-To: <20081103222147.GA5236@remington.svcroot.org> References: <20081103222147.GA5236@remington.svcroot.org> Message-ID: <20081103233014.GA14794@ayn.mi.celestial.com> On Mon, Nov 03, 2008, lister at lihim.org wrote: >Not sure if this is appropriate for the tutor mailing list, but it >is a beginner question for python. > >It seems most of the popular cms/blogging software is php/mysql based > >Anything of substancial popularity/support based on python? > >I was looking for something along the lines of wordpress popular, but not >sure if there exists something for python. > >I'm aware of Zine (http://dev.pocoo.org/projects/zine/ ) that is trying to >become wordpress like, any others? We have been using Zope and Plone for about 4 years now. Bill -- INTERNET: bill at celestial.com Bill Campbell; Celestial Software LLC URL: http://www.celestial.com/ PO Box 820; 6641 E. Mercer Way Voice: (206) 236-1676 Mercer Island, WA 98040-0820 Fax: (206) 232-9186 "If taxation without consent is not robbery, then any band of robbers have only to declare themselves a government, and all their robberies are legalized." -- Lysander Spooner, Letter to Grover Cleveland 1886 From nephish at gmail.com Tue Nov 4 03:34:09 2008 From: nephish at gmail.com (shawn bright) Date: Mon, 3 Nov 2008 20:34:09 -0600 Subject: [Tutor] how to read over serial port In-Reply-To: <16651e80811031349x496127f0g9980fc779f5ec4f9@mail.gmail.com> References: <384c93600811011945x3a6922f9hf3e0faac604070cd@mail.gmail.com> <490DC977.8080207@brianlane.com> <384c93600811020950y166e5ce4r5c472a2af8c26fa5@mail.gmail.com> <384c93600811030614ja686a77w2abc72cebcb1a623@mail.gmail.com> <384c93600811030648y57513d48kbcb791350b0c9b99@mail.gmail.com> <384c93600811031308o4eeaace0rdd7bdef7ff7de133@mail.gmail.com> <16651e80811031349x496127f0g9980fc779f5ec4f9@mail.gmail.com> Message-ID: <384c93600811031834y3cffa4e6ne22f3d2431a9020e@mail.gmail.com> Forgot some info, i hooked the device up and used a serial terminal and got back stuff like this !^V$G(R)?LL,3602.0960,N,10229.2959,W,r$4013,V*2E some of the above is what i am looking for. settings are the same as in my python script thanks for any help, shawn On Mon, Nov 3, 2008 at 3:49 PM, Jerry Hill wrote: > On Mon, Nov 3, 2008 at 4:08 PM, shawn bright wrote: >> yes, they look like this >> ?????????????????????? >> >> so i used your print repr(chr(ord(i))) and got this > > Note that that's the same thing as just printing repr(i). > >> so, what do i do now? >> and thanks for the info, by the way, been writing python for 2 years, >> but this is all new to me. > > Maybe we should back up a little bit. You said in your original post > that you were expecting ASCII characters from the serial device. How > do you know that's what you should be getting back? Have you tried > communicating with the device using some other program? If so, what > program? Do you have specs that tell you that's how it's supposed to > work? > > Are you sure you're connecting to the device with the right parameters > for baudrate, byte size, parity, etc? > > I notice that nowhere in this thread have you posted the code you use > to actually communicate with the serial device. Maybe you should do > that. > > -- > Jerry > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From malaclypse2 at gmail.com Tue Nov 4 03:37:48 2008 From: malaclypse2 at gmail.com (Jerry Hill) Date: Mon, 3 Nov 2008 22:37:48 -0400 Subject: [Tutor] accessing an image with pygame.image.load() In-Reply-To: <490F83A1.5020406@gmail.com> References: <553438.97767.qm@web51603.mail.re2.yahoo.com> <490F83A1.5020406@gmail.com> Message-ID: <16651e80811031837g673684f6naec7776e9d1c9b31@mail.gmail.com> On Mon, Nov 3, 2008 at 7:05 PM, bob gailer wrote: > Christopher Spears wrote: >> self.image = >> pygame.image.load("C:Users\Chris\Documents\python\assignment07\chris_graphics\spaceship.gif") >> > > Since \ is used to "escape" certain characters it is advisable to either use > \\ or preface the string with r. Beyond what Bob says about being careful of the escape character ('\') and the need to either double it up in a string literal or use a raw string, are you sure that path is right? Usually a drive letter is followed by a backslash in windows. That is, "C:\Users\Chris" rather than "C:Users\Chris". -- Jerry From bcl at brianlane.com Tue Nov 4 05:14:46 2008 From: bcl at brianlane.com (Brian C. Lane) Date: Mon, 03 Nov 2008 20:14:46 -0800 Subject: [Tutor] how to read over serial port In-Reply-To: <384c93600811031834y3cffa4e6ne22f3d2431a9020e@mail.gmail.com> References: <384c93600811011945x3a6922f9hf3e0faac604070cd@mail.gmail.com> <490DC977.8080207@brianlane.com> <384c93600811020950y166e5ce4r5c472a2af8c26fa5@mail.gmail.com> <384c93600811030614ja686a77w2abc72cebcb1a623@mail.gmail.com> <384c93600811030648y57513d48kbcb791350b0c9b99@mail.gmail.com> <384c93600811031308o4eeaace0rdd7bdef7ff7de133@mail.gmail.com> <16651e80811031349x496127f0g9980fc779f5ec4f9@mail.gmail.com> <384c93600811031834y3cffa4e6ne22f3d2431a9020e@mail.gmail.com> Message-ID: <490FCC36.1050703@brianlane.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 shawn bright wrote: > Forgot some info, > i hooked the device up and used a serial terminal and got back stuff like this > !^V$G(R)?LL,3602.0960,N,10229.2959,W,r$4013,V*2E > some of the above is what i am looking for. > Ok, that looks bad. You have some of the right stuff, but also some non-ascii characters. You should see lines that start with something like $GPRMC, You either have a hardware problem, or a mismatch in the settings. Brian - -- - ---[Office 68.9F]--[Outside 46.4F]--[Server 99.4F]--[Coaster 70.2F]--- - ---[ ISSAQUAH WSF (366773040) @ 47 31.3927 -122 23.8077 ]--- Software, Linux, Microcontrollers http://www.brianlane.com AIS Parser SDK http://www.aisparser.com -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.8 (Darwin) Comment: Remember Lexington Green! iD8DBQFJD8w2Iftj/pcSws0RAvBcAJ4u56Ns1LvM4fUje6J+C/bNUzdI9ACfVGf8 Al9CxP99ODjq6sPztZ1oAQI= =vsxI -----END PGP SIGNATURE----- From nephish at gmail.com Tue Nov 4 06:35:38 2008 From: nephish at gmail.com (shawn bright) Date: Mon, 3 Nov 2008 23:35:38 -0600 Subject: [Tutor] how to read over serial port In-Reply-To: <490FCC36.1050703@brianlane.com> References: <384c93600811011945x3a6922f9hf3e0faac604070cd@mail.gmail.com> <490DC977.8080207@brianlane.com> <384c93600811020950y166e5ce4r5c472a2af8c26fa5@mail.gmail.com> <384c93600811030614ja686a77w2abc72cebcb1a623@mail.gmail.com> <384c93600811030648y57513d48kbcb791350b0c9b99@mail.gmail.com> <384c93600811031308o4eeaace0rdd7bdef7ff7de133@mail.gmail.com> <16651e80811031349x496127f0g9980fc779f5ec4f9@mail.gmail.com> <384c93600811031834y3cffa4e6ne22f3d2431a9020e@mail.gmail.com> <490FCC36.1050703@brianlane.com> Message-ID: <384c93600811032135t19ffbb09oa3459d605197aae0@mail.gmail.com> Hey all, thanks for all the help. I will go out in the morning and check all the equipment, have heard too much advice from too many with python experience to ignore the fact that something is likely screwed up in my settings or baudrate. will be back in touch later as i check it out. sk On Mon, Nov 3, 2008 at 10:14 PM, Brian C. Lane wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > shawn bright wrote: >> Forgot some info, >> i hooked the device up and used a serial terminal and got back stuff like this >> !^V$G(R)?LL,3602.0960,N,10229.2959,W,r$4013,V*2E >> some of the above is what i am looking for. >> > > Ok, that looks bad. You have some of the right stuff, but also some > non-ascii characters. You should see lines that start with something > like $GPRMC, > > You either have a hardware problem, or a mismatch in the settings. > > Brian > > - -- > - ---[Office 68.9F]--[Outside 46.4F]--[Server 99.4F]--[Coaster 70.2F]--- > - ---[ ISSAQUAH WSF (366773040) @ 47 31.3927 -122 23.8077 ]--- > Software, Linux, Microcontrollers http://www.brianlane.com > AIS Parser SDK http://www.aisparser.com > > -----BEGIN PGP SIGNATURE----- > Version: GnuPG v1.4.8 (Darwin) > Comment: Remember Lexington Green! > > iD8DBQFJD8w2Iftj/pcSws0RAvBcAJ4u56Ns1LvM4fUje6J+C/bNUzdI9ACfVGf8 > Al9CxP99ODjq6sPztZ1oAQI= > =vsxI > -----END PGP SIGNATURE----- > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From srilyk at gmail.com Tue Nov 4 12:22:09 2008 From: srilyk at gmail.com (W W) Date: Tue, 4 Nov 2008 05:22:09 -0600 Subject: [Tutor] accessing an image with pygame.image.load() In-Reply-To: <16651e80811031837g673684f6naec7776e9d1c9b31@mail.gmail.com> References: <553438.97767.qm@web51603.mail.re2.yahoo.com> <490F83A1.5020406@gmail.com> <16651e80811031837g673684f6naec7776e9d1c9b31@mail.gmail.com> Message-ID: <333efb450811040322u71103d54x22455f7fad6c206d@mail.gmail.com> On Mon, Nov 3, 2008 at 8:37 PM, Jerry Hill wrote: > Beyond what Bob says about being careful of the escape character ('\') > and the need to either double it up in a string literal or use a raw > string, are you sure that path is right? Usually a drive letter is > followed by a backslash in windows. That is, "C:\Users\Chris" rather > than "C:Users\Chris". And just FYI, you can use forward slashes, even in windows: In [50]: cd D:/Program\ Files/ D:\Program Files HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From nephish at gmail.com Wed Nov 5 15:44:40 2008 From: nephish at gmail.com (shawn bright) Date: Wed, 5 Nov 2008 08:44:40 -0600 Subject: [Tutor] serial port, revisited, but closer Message-ID: <384c93600811050644r58943ef9r94ea5c29009e6b19@mail.gmail.com> Hey all, I am back again with the serial port stuff, i have verified that all the baud rate and settings are ok, had my unit talk directly to a serial port reader and it is looking good, however, i still am not seeming to be able to read this. I had a question that might make me a clue. if i do this: j = ser.read(23) f = open('filename', 'wb') f.write(j) when i do file from the cli in linux, the file says to contain data. however if i do this: i = 1 msg_list = [] while i < 23: msg_list.append(ser.read(1)) items = ''.join(msg_list) f=open('filename', 'wb') f.write(items) f.close() i get that the file is a binary file. i didn't think there would be a difference. anyway, thanks sk From a.t.hofkamp at tue.nl Wed Nov 5 17:06:59 2008 From: a.t.hofkamp at tue.nl (A.T.Hofkamp) Date: Wed, 05 Nov 2008 17:06:59 +0100 Subject: [Tutor] serial port, revisited, but closer In-Reply-To: <384c93600811050644r58943ef9r94ea5c29009e6b19@mail.gmail.com> References: <384c93600811050644r58943ef9r94ea5c29009e6b19@mail.gmail.com> Message-ID: <4911C4A3.5010401@tue.nl> shawn bright wrote: > Hey all, > > I am back again with the serial port stuff, i have verified that all > the baud rate and settings are ok, > had my unit talk directly to a serial port reader and it is looking > good, however, i still am not seeming to be able to read this. > > I had a question that might make me a clue. > if i do this: > j = ser.read(23) > f = open('filename', 'wb') > f.write(j) > > when i do file from the cli in linux, the file says to contain data. > however if i do this: > i = 1 > msg_list = [] > while i < 23: > msg_list.append(ser.read(1)) > items = ''.join(msg_list) > f=open('filename', 'wb') > f.write(items) > f.close() One difference at least is that the first program reads 23 bytes, and the second many more (i is not incremented, so the program loops forever). The second difference is that the first program does not close the file?? (kind of depends how you run things, and at what moment you ask Linux about the file). Also, do 'print repr(j)' in the first program, and 'print repr(items)' in the second program to see exactly what is written to the file. > i get that the file is a binary file. The next question is of course, is there really any difference, and if yes, what? At the file system, you could - Check whether both files equally are long (23 bytes, assuming your loop terminated after 23 iterations). - Compare the files with 'cmp filename1 filename2' which reports whether or not files are equal and if not where the first difference is. - Dump the contents of the file to screen in human-readable hex-dump with eg 'xxd filename' (xxd is part of the vim package I believe). Sincerely, Albert From btkuhn at email.unc.edu Wed Nov 5 21:26:21 2008 From: btkuhn at email.unc.edu (btkuhn at email.unc.edu) Date: Wed, 05 Nov 2008 15:26:21 -0500 Subject: [Tutor] Building RSS reader with Python Message-ID: <20081105152621.66plv7bvsokkgw8c@webmail4.isis.unc.edu> Hi everyone, I'm new to programming and am building a very basic rss reader for my first major project with python and GUI. As it is, I have it set up so that if I input an exact rss feed address (ex http://news.google.com/?output=rss) I can retrieve stories. Id like to make it so that I can enter a site (like http://news.google.com) and have it search for the address of rss feeds on the site, so that I don't have to know exact page addresses for the rss, since most sites don't have such a straightforward location for the RSS page. Is there a way to do this? Thanks, Luke From lister at lihim.org Wed Nov 5 21:36:45 2008 From: lister at lihim.org (lister at lihim.org) Date: Wed, 5 Nov 2008 14:36:45 -0600 Subject: [Tutor] Building RSS reader with Python In-Reply-To: <20081105152621.66plv7bvsokkgw8c@webmail4.isis.unc.edu> References: <20081105152621.66plv7bvsokkgw8c@webmail4.isis.unc.edu> Message-ID: <20081105203645.GA11730@remington.svcroot.org> Might look at rss2email, it works very well for those of us that like to read email instead of yet another website to read rss feeds. It won't solve your "search for the address of rss feeds on the site" but it will give you an idea about rss parsing. rss2email - http://rss2email.infogami.com/ On Wed, Nov 05, 2008 at 03:26:21PM -0500, btkuhn at email.unc.edu wrote: > Hi everyone, > > I'm new to programming and am building a very basic rss reader for my > first major project with python and GUI. As it is, I have it set up so > that if I input an exact rss feed address (ex > http://news.google.com/?output=rss) I can retrieve stories. Id like to > make it so that I can enter a site (like http://news.google.com) and > have it search for the address of rss feeds on the site, so that I > don't have to know exact page addresses for the rss, since most sites > don't have such a straightforward location for the RSS page. Is there a > way to do this? > > Thanks, > Luke From Shawn at milochik.com Wed Nov 5 21:54:53 2008 From: Shawn at milochik.com (Shawn Milochik) Date: Wed, 5 Nov 2008 15:54:53 -0500 Subject: [Tutor] Building RSS reader with Python In-Reply-To: <20081105152621.66plv7bvsokkgw8c@webmail4.isis.unc.edu> References: <20081105152621.66plv7bvsokkgw8c@webmail4.isis.unc.edu> Message-ID: <2dc0c81b0811051254u1df6179bn34b43310475ccdea@mail.gmail.com> On Wed, Nov 5, 2008 at 3:26 PM, wrote: > Hi everyone, > > I'm new to programming and am building a very basic rss reader for my first > major project with python and GUI. As it is, I have it set up so that if I > input an exact rss feed address (ex http://news.google.com/?output=rss) I > can retrieve stories. Id like to make it so that I can enter a site (like > http://news.google.com) and have it search for the address of rss feeds on > the site, so that I don't have to know exact page addresses for the rss, > since most sites don't have such a straightforward location for the RSS > page. Is there a way to do this? > > Thanks, > Luke > _______ My gut reaction is to say that it's a lost cause. Everybody does their own thing on the Internet, and you'll never be able to describe all of the ways people do it. However, there are *some* standards out there. Check with the big CMS tools (WordPress, Drupal, Zope, Plone, etc.) and see if they have a standard. That'll help. Hit up some of the big sites (Google News, Reuters, CNN, BBC) and see what they do. You'll end up with a database of maybe a few dozen things to try (example.com/rss.xml, example.com/blog?feed=rss2, example.com/feeds.atom, and many more), and you can search for them by default. Having said that, it'll never be perfect, and it may not even be close enough to perfect to be worth the maintenance. I refer back to my gut reaction above. But you never know -- you could be the guy who maintains the most complete reference to RSS URLs on the Internet, and all will download your list for their own projects. Somebody has to be the best in that market. Shawn From kent37 at tds.net Wed Nov 5 21:56:21 2008 From: kent37 at tds.net (Kent Johnson) Date: Wed, 5 Nov 2008 15:56:21 -0500 Subject: [Tutor] Building RSS reader with Python In-Reply-To: <20081105152621.66plv7bvsokkgw8c@webmail4.isis.unc.edu> References: <20081105152621.66plv7bvsokkgw8c@webmail4.isis.unc.edu> Message-ID: <1c2a2c590811051256o7acf21b8u1f87cb6d717ddd81@mail.gmail.com> On Wed, Nov 5, 2008 at 3:26 PM, wrote: > Hi everyone, > > I'm new to programming and am building a very basic rss reader for my first > major project with python and GUI. As it is, I have it set up so that if I > input an exact rss feed address (ex http://news.google.com/?output=rss) I > can retrieve stories. Id like to make it so that I can enter a site (like > http://news.google.com) and have it search for the address of rss feeds on > the site, so that I don't have to know exact page addresses for the rss, > since most sites don't have such a straightforward location for the RSS > page. Is there a way to do this? I hope you are using feedparser for your parsing: http://www.feedparser.org/ feedfinder will do discovery: http://www.aaronsw.com/2002/feedfinder/ Kent From kent37 at tds.net Wed Nov 5 21:57:57 2008 From: kent37 at tds.net (Kent Johnson) Date: Wed, 5 Nov 2008 15:57:57 -0500 Subject: [Tutor] Building RSS reader with Python In-Reply-To: <20081105203645.GA11730@remington.svcroot.org> References: <20081105152621.66plv7bvsokkgw8c@webmail4.isis.unc.edu> <20081105203645.GA11730@remington.svcroot.org> Message-ID: <1c2a2c590811051257v577ab4c5r198c05d54c657035@mail.gmail.com> On Wed, Nov 5, 2008 at 3:36 PM, wrote: > Might look at rss2email, it works very well for those of us that like > to read email instead of yet another website to read rss feeds. > > It won't solve your "search for the address of rss feeds on the site" > but it will give you an idea about rss parsing. It uses feedparser for the parsing. Kent From qsqgeekyogdty at tiscali.co.uk Thu Nov 6 01:09:44 2008 From: qsqgeekyogdty at tiscali.co.uk (qsqgeekyogdty at tiscali.co.uk) Date: Thu, 6 Nov 2008 01:09:44 +0100 (GMT+01:00) Subject: [Tutor] validating decimal class Message-ID: <13615245.1225930184847.JavaMail.root@ps30> hello silly question, but i can't seem to figure it it. I have an object which is: >>> type(price) but i can't figure how to validate against it. >>>if not isinstance(price, decimal.Decimal): do something... how do i ensure that the object 'price' is a decimal? thanks ______________________________________________________ 33% off Norton Security Only From Tiscali - http://www.tiscali.co.uk/securepc/ ________________________________________________ From cspears2002 at yahoo.com Thu Nov 6 02:05:08 2008 From: cspears2002 at yahoo.com (Christopher Spears) Date: Wed, 5 Nov 2008 17:05:08 -0800 (PST) Subject: [Tutor] using rect.inflate() Message-ID: <95907.38919.qm@web51609.mail.re2.yahoo.com> I'm modifying a game for an assignment in "Game Programming" by Andy Harris. I'm not reading this book as part of a class. Basically, I turned one of the example games into an Asteroid rip off. However, I didn't like the collisions between the spaceship and the asteroids, so I decided to shrink the ship's bounding box using Rect.inflate(). I inserted this code snippet into the Spaceship class: self.rect = self.image.get_rect() print self.rect self.rect = self.rect.inflate(-50, -50) print self.rect The following was printed to my console: > > I'm assuming that the first two numbers are coordinates for the upper left corner of the rectangle. The third and fourth numbers are the width and height of the rectangle from the upper left corner. Am I off base here? If that is the case, why does rect.inflate() move the upper left corner? From kent37 at tds.net Thu Nov 6 02:10:34 2008 From: kent37 at tds.net (Kent Johnson) Date: Wed, 5 Nov 2008 20:10:34 -0500 Subject: [Tutor] validating decimal class In-Reply-To: <13615245.1225930184847.JavaMail.root@ps30> References: <13615245.1225930184847.JavaMail.root@ps30> Message-ID: <1c2a2c590811051710v99d1de2o4841b23833e3e140@mail.gmail.com> On Wed, Nov 5, 2008 at 7:09 PM, qsqgeekyogdty at tiscali.co.uk wrote: > I have an object which is: > >>>> type(price) > > > but i can't figure how to validate against it. > >>>>if not isinstance(price, decimal.Decimal): > do something... This should work, what problem are you having? > how do i ensure that the object 'price' is a decimal? Why do you need to know? Another approach is to just treat it as a Decimal and catch the exception that is raised if it is not. Kent From bcl at brianlane.com Thu Nov 6 02:12:49 2008 From: bcl at brianlane.com (Brian Lane) Date: Wed, 05 Nov 2008 17:12:49 -0800 Subject: [Tutor] validating decimal class In-Reply-To: <13615245.1225930184847.JavaMail.root@ps30> References: <13615245.1225930184847.JavaMail.root@ps30> Message-ID: <49124491.2050700@brianlane.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 qsqgeekyogdty at tiscali.co.uk wrote: > hello > silly question, but i can't seem to figure it it. > > I have an object which is: > >>>> type(price) > > > but i can't figure how to validate against it. > >>>> if not isinstance(price, decimal.Decimal): > do something... > > how do i ensure that the object 'price' is a decimal? > The above should work (I even tried it to make sure). But you could also compare it to a known type: if not type(price) is type(decimal.Decimal(0)): print "Not Decimal" What error are you getting when you try using isinstance()? Brian - -- - ---[Office 70.0F]--[Outside 47.4F]--[Server 103.2F]--[Coaster 67.3F]--- - ---[ TACOMA WSF (366772760) @ 47 36.0979 -122 27.0253 ]--- Software, Linux, Microcontrollers http://www.brianlane.com AIS Parser SDK http://www.aisparser.com -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.7 (Darwin) Comment: Remember Lexington Green! iD8DBQFJEkSRIftj/pcSws0RAmQkAJ9Y+eFJym2qwqgGl2pDbxAH0gr2xwCggETX LJISNKXlvKhCCveTzUAUzMY= =clEC -----END PGP SIGNATURE----- From john at fouhy.net Thu Nov 6 03:14:08 2008 From: john at fouhy.net (John Fouhy) Date: Thu, 6 Nov 2008 15:14:08 +1300 Subject: [Tutor] using rect.inflate() In-Reply-To: <95907.38919.qm@web51609.mail.re2.yahoo.com> References: <95907.38919.qm@web51609.mail.re2.yahoo.com> Message-ID: <5e58f2e40811051814l20325d5cn9886196f5b7a55d8@mail.gmail.com> 2008/11/6 Christopher Spears : > I inserted this code snippet into the Spaceship class: > > self.rect = self.image.get_rect() > print self.rect > self.rect = self.rect.inflate(-50, -50) > print self.rect > > The following was printed to my console: > > > > > > I'm assuming that the first two numbers are coordinates for the upper left corner of the rectangle. The third and fourth numbers are the width and height of the rectangle from the upper left corner. Am I off base here? > If that is the case, why does rect.inflate() move the upper left corner? At a guess: the inflation (or, in this case, deflation) is centred on the centre of the figure. So a horizontal change of -50 means the left edge moves 25 pixels right and the right edge moves 25 pixels left. (or, rather, the total width drops frrom 70 pixels to 20 pixels) I'm not sure what's going on with the height, though. -- John. From john at fouhy.net Thu Nov 6 03:16:42 2008 From: john at fouhy.net (John Fouhy) Date: Thu, 6 Nov 2008 15:16:42 +1300 Subject: [Tutor] validating decimal class In-Reply-To: <49124491.2050700@brianlane.com> References: <13615245.1225930184847.JavaMail.root@ps30> <49124491.2050700@brianlane.com> Message-ID: <5e58f2e40811051816p2bcd42ddy87a80d6c441bce5a@mail.gmail.com> 2008/11/6 Brian Lane : > But you could also compare it to a known type: > > if not type(price) is type(decimal.Decimal(0)): > print "Not Decimal" Easier to just compare with decimal.Decimal: >>> import decimal >>> d = decimal.Decimal(13) >>> type(d) == decimal.Decimal True -- John. From a.t.hofkamp at tue.nl Thu Nov 6 09:00:31 2008 From: a.t.hofkamp at tue.nl (A.T.Hofkamp) Date: Thu, 06 Nov 2008 09:00:31 +0100 Subject: [Tutor] validating decimal class In-Reply-To: <5e58f2e40811051816p2bcd42ddy87a80d6c441bce5a@mail.gmail.com> References: <13615245.1225930184847.JavaMail.root@ps30> <49124491.2050700@brianlane.com> <5e58f2e40811051816p2bcd42ddy87a80d6c441bce5a@mail.gmail.com> Message-ID: <4912A41F.7040705@tue.nl> John Fouhy wrote: > 2008/11/6 Brian Lane : >> But you could also compare it to a known type: >> >> if not type(price) is type(decimal.Decimal(0)): >> print "Not Decimal" > > Easier to just compare with decimal.Decimal: > >>>> import decimal >>>> d = decimal.Decimal(13) >>>> type(d) == decimal.Decimal > True And since classes are singletons, you can use 'is' instead of '=='. From srilyk at gmail.com Thu Nov 6 12:11:26 2008 From: srilyk at gmail.com (W W) Date: Thu, 6 Nov 2008 05:11:26 -0600 Subject: [Tutor] using rect.inflate() In-Reply-To: <5e58f2e40811051814l20325d5cn9886196f5b7a55d8@mail.gmail.com> References: <95907.38919.qm@web51609.mail.re2.yahoo.com> <5e58f2e40811051814l20325d5cn9886196f5b7a55d8@mail.gmail.com> Message-ID: <333efb450811060311l2e53b28fx61220a5657ac335b@mail.gmail.com> On Wed, Nov 5, 2008 at 8:14 PM, John Fouhy wrote: > 2008/11/6 Christopher Spears : > > I inserted this code snippet into the Spaceship class: > > > > self.rect = self.image.get_rect() > > print self.rect > > self.rect = self.rect.inflate(-50, -50) > > print self.rect > > > > The following was printed to my console: > > > > > > > > > > I'm assuming that the first two numbers are coordinates for the upper > left corner of the rectangle. The third and fourth numbers are the width > and height of the rectangle from the upper left corner. Am I off base here? > > If that is the case, why does rect.inflate() move the upper left corner? > IIRC - in pygame (and some of the other modules) they use a Q4 type coordinate system. I *think* anyway - it's been a while. But I believe they work from the top left corner, instead of bottom left. So your XY rather than (2, 4) moving right and up moves right and down. Similarly, any manipulations you make will also work from (0,0), rather than (2, 4) like you might expect. I'm not 100% sure on that, so you may want to research for a bit just to either verify or disprove my dim memory of the possible situation. HTH, Wayne > > > At a guess: the inflation (or, in this case, deflation) is centred on > the centre of the figure. So a horizontal change of -50 means the > left edge moves 25 pixels right and the right edge moves 25 pixels > left. (or, rather, the total width drops frrom 70 pixels to 20 > pixels) > > I'm not sure what's going on with the height, though. > > -- > John. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- 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 -------------- next part -------------- An HTML attachment was scrubbed... URL: From jmorcombe at westnet.com.au Thu Nov 6 13:29:24 2008 From: jmorcombe at westnet.com.au (Jim Morcombe) Date: Thu, 06 Nov 2008 21:29:24 +0900 Subject: [Tutor] Using Python to replace javascript Message-ID: <4912E324.4020603@westnet.com.au> Is there any way to write python code inside a HTML page instead of using Javascript? Jim From bgailer at gmail.com Thu Nov 6 13:36:55 2008 From: bgailer at gmail.com (bob gailer) Date: Thu, 06 Nov 2008 07:36:55 -0500 Subject: [Tutor] Using Python to replace javascript In-Reply-To: <4912E324.4020603@westnet.com.au> References: <4912E324.4020603@westnet.com.au> Message-ID: <4912E4E7.5020700@gmail.com> Jim Morcombe wrote: > Is there any way to write python code inside a HTML page instead of > using Javascript? Not yet - not directly. But there is pyjamas - a Python - javascript translator centered around GWT. http://code.google.com/p/pyjamas/ http://groups.google.com/group/pyjamas-dev?hl=en -- Bob Gailer Chapel Hill NC 919-636-4239 When we take the time to be aware of our feelings and needs we have more satisfying interatctions with others. Nonviolent Communication provides tools for this awareness. As a coach and trainer I can assist you in learning this process. What is YOUR biggest relationship challenge? From juhasecke at googlemail.com Thu Nov 6 14:04:05 2008 From: juhasecke at googlemail.com (Jan Ulrich Hasecke) Date: Thu, 6 Nov 2008 14:04:05 +0100 Subject: [Tutor] Using Python to replace javascript In-Reply-To: <4912E324.4020603@westnet.com.au> References: <4912E324.4020603@westnet.com.au> Message-ID: <26ba0efc0811060504q46258254i5bcb6fb290ba8885@mail.gmail.com> 2008/11/6 Jim Morcombe > Is there any way to write python code inside a HTML page instead of using > Javascript? > There is the KSS project http://kssproject.org/ It uses a css-like markup to write Ajax-functions. juh -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Thu Nov 6 14:41:19 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 6 Nov 2008 13:41:19 -0000 Subject: [Tutor] Using Python to replace javascript References: <4912E324.4020603@westnet.com.au> Message-ID: "Jim Morcombe" wrote > Is there any way to write python code inside a HTML page instead of > using Javascript? Yes, but only if you a) are using IE as your browser under Windows. b) Have WSH installed c) Have run the scripting activation script in the Pyhonwin package OR you could write your own browser in Python... Another option is to make Javascript more like Python by using Mochikit... http://mochikit.com/ In general I'd try to stick to vanilla JavaScript for client side web scripting, anything else runs the risk of not working as expected on somebody's browser. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From dorseye at gmail.com Thu Nov 6 20:27:53 2008 From: dorseye at gmail.com (Eric Dorsey) Date: Thu, 6 Nov 2008 12:27:53 -0700 Subject: [Tutor] Date validation? Message-ID: Greetings,I have a program where I ask a user to enter a date in format YYYY-MM-DD, and get a string like: '2008-10-25' Can anyone tell me how I would verify this is a real date before allowing it to be passed on to the next part of the program? -- (e) -------------- next part -------------- An HTML attachment was scrubbed... URL: From srilyk at gmail.com Thu Nov 6 20:33:51 2008 From: srilyk at gmail.com (W W) Date: Thu, 6 Nov 2008 13:33:51 -0600 Subject: [Tutor] Date validation? In-Reply-To: References: Message-ID: <333efb450811061133t788aa5cbkdfab7d85487438ab@mail.gmail.com> On Thu, Nov 6, 2008 at 1:27 PM, Eric Dorsey wrote: > Greetings,I have a program where I ask a user to enter a date in format > YYYY-MM-DD, and get a string like: '2008-10-25' > > Can anyone tell me how I would verify this is a real date before allowing > it to be passed on to the next part of the program? > I guess it depends on what your definition of "real date" is... Should the year fall in a certain range? How about the month and day? Are you going to require - between each element? Do you know how to split a string and convert the elements to integers? That should give you some clues to your solution... HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Thu Nov 6 20:37:37 2008 From: bgailer at gmail.com (bob gailer) Date: Thu, 06 Nov 2008 14:37:37 -0500 Subject: [Tutor] Date validation? In-Reply-To: References: Message-ID: <49134781.1000900@gmail.com> Eric Dorsey wrote: > Greetings, > I have a program where I ask a user to enter a date in format > YYYY-MM-DD, and get a string like: '2008-10-25' > > Can anyone tell me how I would verify this is a real date before > allowing it to be passed on to the next part of the program? Take a look at the time module and it's strptime function. >>> import time >>> time.strptime("2008-10-125", "%Y-%m-%d") (2008, 10, 25, 0, 0, 0, 5, 299, -1) >>> time.strptime("2008-10-125", "%Y-%m-%d") Traceback (most recent call last): File "", line 1, in File "H:\Python25\lib\_strptime.py", line 313, in strptime data_string[found.end():]) ValueError: unconverted data remains: 5 -- Bob Gailer Chapel Hill NC 919-636-4239 When we take the time to be aware of our feelings and needs we have more satisfying interatctions with others. Nonviolent Communication provides tools for this awareness. As a coach and trainer I can assist you in learning this process. What is YOUR biggest relationship challenge? From bgailer at gmail.com Thu Nov 6 20:39:43 2008 From: bgailer at gmail.com (bob gailer) Date: Thu, 06 Nov 2008 14:39:43 -0500 Subject: [Tutor] Date validation? Correction In-Reply-To: <49134781.1000900@gmail.com> References: <49134781.1000900@gmail.com> Message-ID: <491347FF.9040600@gmail.com> bob gailer wrote: > Eric Dorsey wrote: >> Greetings, >> I have a program where I ask a user to enter a date in format >> YYYY-MM-DD, and get a string like: '2008-10-25' >> >> Can anyone tell me how I would verify this is a real date before >> allowing it to be passed on to the next part of the program? > > Take a look at the time module and it's strptime function. > > >>> import time > >>> time.strptime("2008-10-25", "%Y-%m-%d") ## CORRECTED > (2008, 10, 25, 0, 0, 0, 5, 299, -1) > >>> time.strptime("2008-10-125", "%Y-%m-%d") > Traceback (most recent call last): > File "", line 1, in > File "H:\Python25\lib\_strptime.py", line 313, in strptime > data_string[found.end():]) > ValueError: unconverted data remains: 5 > -- Bob Gailer Chapel Hill NC 919-636-4239 When we take the time to be aware of our feelings and needs we have more satisfying interatctions with others. Nonviolent Communication provides tools for this awareness. As a coach and trainer I can assist you in learning this process. What is YOUR biggest relationship challenge? From aivars868 at gmail.com Thu Nov 6 22:05:32 2008 From: aivars868 at gmail.com (aivars) Date: Thu, 6 Nov 2008 23:05:32 +0200 Subject: [Tutor] please help with sqlite replace function Message-ID: Hello, I am stuck now. I have a sqlite database with a table calendar (which is an auxilary calendar table containing dates, years, months, days) >From sqlite prompt I can run the following query without any problem: SELECT replace( datums,'-','' ) FROM calendar where Y='2008' and M='5' It gives me back date strings in the format YYYYMMDD. But when I run it from the python script it gives me the following error: sqlite3.OperationalError: no such function: replace. Script is simple as follows: import sqlite3 spath=r'e:\pythonexamples\aivars2.db' sql="SELECT replace(datums,'-','') FROM Calendar where Y='2008' and M='5'" cn=sqlite3.connect(spath) for row in cn.execute(sql): print row[0] When I run the script without the replace function in select statement it runs OK. I use python 2.5.2.2 (activestate), WinXP, sqlite version 3.6.2 Thanks for any tip. maybe I should ask this to sqlite mailing list? Aivars From john at fouhy.net Thu Nov 6 22:54:15 2008 From: john at fouhy.net (John Fouhy) Date: Fri, 7 Nov 2008 10:54:15 +1300 Subject: [Tutor] please help with sqlite replace function In-Reply-To: References: Message-ID: <5e58f2e40811061354jba597cem32bd0d5cfb7fae8b@mail.gmail.com> 2008/11/7 aivars : > I use python 2.5.2.2 (activestate), WinXP, sqlite version 3.6.2 Hi Aivars, I believe python has its own built-in sqlite, rather than using the version you installed independently. So it is possible that the python version of sqlite is older than 3.6.2 and does not yet have the replace() function. (run 'import sqlite3' and then examine 'sqlite3.sqlite_version' to see what version you are using) You could try replacing sqlite3.dll in your python25\dlls directory with the DLL from your sqlite installation (make a backup first :-) ). Alternatively, you could define the replace() function in python and then add it to your database: see http://www.initd.org/pub/software/pysqlite/doc/usage-guide.html#creating-user-defined-functions . HTH. -- John. From john.ertl at navy.mil Thu Nov 6 23:54:50 2008 From: john.ertl at navy.mil (Ertl, John C CIV 63134) Date: Thu, 6 Nov 2008 14:54:50 -0800 Subject: [Tutor] How to use function from specific module and then switch to other module In-Reply-To: References: , <1c2a2c590810211206w179ad95at3cf43315d94bd291@mail.gmail.com>, Message-ID: <07EE4797-FF56-4D29-B71E-1F2747240450@mimectl> An HTML attachment was scrubbed... URL: From john at fouhy.net Fri Nov 7 02:12:46 2008 From: john at fouhy.net (John Fouhy) Date: Fri, 7 Nov 2008 14:12:46 +1300 Subject: [Tutor] How to use function from specific module and then switch to other module In-Reply-To: <07EE4797-FF56-4D29-B71E-1F2747240450@mimectl> References: <1c2a2c590810211206w179ad95at3cf43315d94bd291@mail.gmail.com> <07EE4797-FF56-4D29-B71E-1F2747240450@mimectl> Message-ID: <5e58f2e40811061712i6c325967h3b5b90a9b76c6d@mail.gmail.com> 2008/11/7 Ertl, John C CIV 63134 : > The idea is as I step through a list I want to use a different function > (same name but from a different module) for each element in the list. How > do I have a generic way to do this. > > for example for point 1 I want to use the rain function from Module A and > then for point 2 I want to use the rain function from Module B. Hi John, You could use a dictionary to store the functions. For example: import module_a import module_b rain_functions = { 1:module_a.get_rain, 2:module_b.get_rain } Then you could call the function as: x = forecast() points = x.getPoints() for point in points: rain_functions[point]() Hope this helps, -- John. From kent37 at tds.net Fri Nov 7 04:36:42 2008 From: kent37 at tds.net (Kent Johnson) Date: Thu, 6 Nov 2008 22:36:42 -0500 Subject: [Tutor] How to use function from specific module and then switch to other module In-Reply-To: <07EE4797-FF56-4D29-B71E-1F2747240450@mimectl> References: <1c2a2c590810211206w179ad95at3cf43315d94bd291@mail.gmail.com> <07EE4797-FF56-4D29-B71E-1F2747240450@mimectl> Message-ID: <1c2a2c590811061936w41e65c3eo45753daaaa1c19ab@mail.gmail.com> On Thu, Nov 6, 2008 at 5:54 PM, Ertl, John C CIV 63134 wrote: > Classification: UNCLASSIFIED > Caveat (s): FOUO > > I have a program that collects weather data from weather models. I > originally had a module that contained a bunch of function that I used. So > I just added it to the init of the class I was using and inherited the > functions. That worked great but now I have two different models that I can > get weather from. Each Module A and B have the exact same function names > in them but they both do slightly different things. It might help to see a working example of what you did for one model. > > The idea is as I step through a list I want to use a different function > (same name but from a different module) for each element in the list. How > do I have a generic way to do this. > > for example for point 1 I want to use the rain function from Module A and > then for point 2 I want to use the rain function from Module B. At first > though I would just init the class from either A or B for each point but I > need the function from A or B to be able to use function from my main > program...that is why the inheritance thing worked great for just one > module. Don't try to make the model A and B into base classes of the forecast. Just pass the forecast object to the model. So your rain() method will look more like this: def rain(self, fc): fc.calTime() # this function is in the main forecast class fc.rain = do stuff for model A where fc will be the forecast instance. You might also be able to use simple functions rather than classes: def rain(fc): fc.calTime() # this function is in the main forecast class fc.rain = do stuff for model A then just call moduleA.rain(self) or moduleB.rain(self). You might want to read about the Strategy pattern, that is what you are doing. Here is a Python example of a class-based Strategy. http://mail.python.org/pipermail/python-list/2006-April/379188.html This example passes the strategy to the constructor but you can set it in your pointInfo() method if you like. I would just make one function to handle each point though: for each in x.pointList: x.handlePoint(each) where def handlePoint(self, point): pointStrategy = ... pointStrategy.rain(self, point) Kent Kent From aivars868 at gmail.com Fri Nov 7 05:03:47 2008 From: aivars868 at gmail.com (aivars) Date: Fri, 7 Nov 2008 06:03:47 +0200 Subject: [Tutor] please help with sqlite replace function In-Reply-To: <5e58f2e40811061354jba597cem32bd0d5cfb7fae8b@mail.gmail.com> References: <5e58f2e40811061354jba597cem32bd0d5cfb7fae8b@mail.gmail.com> Message-ID: Thanks, John, Yes it seems you are right. The ActiveState python version I have installed have sqlite 2.3.2 only. I find it strange. I see that on a python website there is is a new version Python26 relesed. Should i go on and install Python26? I understand that I can install pure Python from python website and after that I can install Mark Hammonds PythonWin to get other things for windows? Or maybe I will reinstall ActiveState Python25 and install Python25 from the official website Copying dll to c:\python25\DLLs directory did not help - it still shows version sqlite version 2.3.2. which I also do not understand why Re user defined function - it is one of the ways to go probably quickest but I would like to have newer version of sqlite being already with python I am noob in Python still Thanks for your input Aivars 2008/11/6 John Fouhy : > 2008/11/7 aivars : >> I use python 2.5.2.2 (activestate), WinXP, sqlite version 3.6.2 > > Hi Aivars, > > I believe python has its own built-in sqlite, rather than using the > version you installed independently. So it is possible that the > python version of sqlite is older than 3.6.2 and does not yet have the > replace() function. > > (run 'import sqlite3' and then examine 'sqlite3.sqlite_version' to see > what version you are using) > > You could try replacing sqlite3.dll in your python25\dlls directory > with the DLL from your sqlite installation (make a backup first :-) ). > Alternatively, you could define the replace() function in python and > then add it to your database: see > http://www.initd.org/pub/software/pysqlite/doc/usage-guide.html#creating-user-defined-functions > . > > HTH. > > -- > John. > From btkuhn at email.unc.edu Fri Nov 7 05:14:38 2008 From: btkuhn at email.unc.edu (btkuhn at email.unc.edu) Date: Thu, 06 Nov 2008 23:14:38 -0500 Subject: [Tutor] Intermediate/advanced concepts Message-ID: <20081106231438.ujxyzfnugwcw0sg0@webmail4.isis.unc.edu> Hi everyone, I've been teaching myself python for a few months and I'm becoming frustrated because I've kind of hit a wall in terms of learning new information. In an effort to continue to learn I've found some material on more intermediate/advanced topics like linked lists, nodes, trees, etc. However, it's kind of like reading a math textbook - the tutorials do a decent job of explaining the material but it's all kind of theoretical, and I'm not sure how I'd apply these concepts in real world applications, or incorporate them into my code. Does anyone have any suggestions for learning about real world application of more advanced concepts? Also, are there other concepts that I should focus on? Frankly, I'm a bit bored because I've hit this ceiling, and I'm not really sure where to go to next. Thanks, Ben From aivars868 at gmail.com Fri Nov 7 06:02:16 2008 From: aivars868 at gmail.com (aivars) Date: Fri, 7 Nov 2008 07:02:16 +0200 Subject: [Tutor] please help with sqlite replace function In-Reply-To: References: <5e58f2e40811061354jba597cem32bd0d5cfb7fae8b@mail.gmail.com> Message-ID: John, just to add to my previous post. after copying sqlite3.dll (3.6.2) version into Python25\DLLs directory and running import sqlite3 dir(sqlite3) >>> sqlite3.version '2.3.2' >>> sqlite3.version_info (2, 3, 2) >>> sqlite3.sqlite_version_info (3, 6, 2) >>> sqlite3.sqlite_version '3.6.2' and now my scrip happily runs with sqlite replace function. I am just curious why there are so many different version properties and why now they differ from sqlite3.version? Of course it seems Python now is running sqlite version 3.6.2 since my script accepts replace function Thanks, Aivars 2008/11/7 aivars : > Thanks, John, > Yes it seems you are right. The ActiveState python version I have > installed have sqlite 2.3.2 only. I find it strange. > I see that on a python website there is is a new version Python26 > relesed. Should i go on and install Python26? I understand that I can > install pure Python from python website and after that I can install > Mark Hammonds PythonWin to get other things for windows? Or maybe I > will reinstall ActiveState Python25 and install Python25 from the > official website > > Copying dll to c:\python25\DLLs directory did not help - it still > shows version sqlite version 2.3.2. which I also do not understand why > > Re user defined function - it is one of the ways to go probably > quickest but I would like to have newer version of sqlite being > already with python > > I am noob in Python still > > Thanks for your input > > Aivars > > > > 2008/11/6 John Fouhy : >> 2008/11/7 aivars : >>> I use python 2.5.2.2 (activestate), WinXP, sqlite version 3.6.2 >> >> Hi Aivars, >> >> I believe python has its own built-in sqlite, rather than using the >> version you installed independently. So it is possible that the >> python version of sqlite is older than 3.6.2 and does not yet have the >> replace() function. >> >> (run 'import sqlite3' and then examine 'sqlite3.sqlite_version' to see >> what version you are using) >> >> You could try replacing sqlite3.dll in your python25\dlls directory >> with the DLL from your sqlite installation (make a backup first :-) ). >> Alternatively, you could define the replace() function in python and >> then add it to your database: see >> http://www.initd.org/pub/software/pysqlite/doc/usage-guide.html#creating-user-defined-functions >> . >> >> HTH. >> >> -- >> John. >> > From aivars868 at gmail.com Fri Nov 7 09:49:59 2008 From: aivars868 at gmail.com (aivars) Date: Fri, 7 Nov 2008 10:49:59 +0200 Subject: [Tutor] problem with simple sqlite script Message-ID: Hello, I am getting frustrated. I have been successfully inserting, deleting, etc records with python and sqlite no problem. Suddenly the following very simple scrip does not work: import sqlite3 sPath=r'e:\pythonexamples\aivars2.db' con=sqlite3.connect(sPath) cur=con.cursor() cur.execute("insert into test (name) values (?)",sPath) con.commit() here is an error message Traceback (most recent call last): File "C:\Python25\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", line 307, in RunScript debugger.run(codeObject, __main__.__dict__, start_stepping=0) File "C:\Python25\Lib\site-packages\pythonwin\pywin\debugger\__init__.py", line 60, in run _GetCurrentDebugger().run(cmd, globals,locals, start_stepping) File "C:\Python25\Lib\site-packages\pythonwin\pywin\debugger\debugger.py", line 631, in run exec cmd in globals, locals File "E:\PythonExamples\test.py", line 7, in cur.execute("insert into test (name) values (?)",sPath) ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 28 supplied. What the hell is going on? I have used the syntax with (?) successfully before! I tested and found out that above script allows me to insert only single character into database. Then it works. Using ActiveState python 2.5, WinXP Thanks for any hint. Aivars From alan.gauld at btinternet.com Fri Nov 7 10:12:00 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 7 Nov 2008 09:12:00 -0000 Subject: [Tutor] Intermediate/advanced concepts References: <20081106231438.ujxyzfnugwcw0sg0@webmail4.isis.unc.edu> Message-ID: wrote > on more intermediate/advanced topics like linked lists, nodes, > trees, etc. However, it's kind of like reading a math textbook Thats because these are abstract theoretical concepts at the root of programming but not used much in practice in high level languages like Python. If you were using a language like C or Fortran or Pascal they would be highly relevant because the language would not provide much support for collections of data. But Python offers such a wealth of data collections that these advanced topics are largely redundant; just use a list or a dictionary or a set... > any suggestions for learning about real world application of more > advanced concepts? There are general rules about when different types apply but the edges are blurred in Python. For example a linked list is pretty much a Python list. A double linked list too can often be faked in Python by using negative indexing. Trees are a bit more valid and do have uses in applications like heirarchical data storage such as found in file browsers, family trees, organisational charts etc. They are also very powerful tools for constructing searches of large data sets. Things like bags and sets are just heterogenous collections which Pythons native types mimic well. (Many of these concepts grew out of early languages which only allowed a single type of data in a collection) OTOH there are cases for most of these data types where there are arguments for constructing a dedicated implementation in Python is valid, but they are rare. If you have specific questions about specific types let us know and we can offer more speciofic advice. > Also, are there other concepts that I should focus on? Frankly, I'm > a bit bored because I've hit this ceiling, and I'm not really sure > where to go to next. If you are interested in investigating the more advanced aspects of programming I'd suggest digging into concepts like closures, locking, semaphores, predicate and lambda calculus, boolean algebra, relational data theory, functional programming, aspect oriented programming, literate programming, provable correctness (use of assertions for pre/post conditions and invariance etc), meta data. These are all of more direct relevance in higher level languages like Python. HTH, Alan G. From alan.gauld at btinternet.com Fri Nov 7 10:19:20 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 7 Nov 2008 09:19:20 -0000 Subject: [Tutor] please help with sqlite replace function References: <5e58f2e40811061354jba597cem32bd0d5cfb7fae8b@mail.gmail.com> Message-ID: "aivars" wrote > Yes it seems you are right. The ActiveState python version I have > installed have sqlite 2.3.2 only. I find it strange. Why? SQLite is a separate product. Python bundled the then current version in its standard distribution, but time has moved on. You have apparently installed a more recent version of SQLite. > I see that on a python website there is is a new version Python26 2.6 may or may not have the same version as you but regardless you should be able to get the older version of Python to work with the newer SQLite instal;l, provided the newer version has a Python library available - which it usually has. > Mark Hammonds PythonWin to get other things for windows? Or maybe I > will reinstall ActiveState Python25 and install Python25 from the > official website I don't thing the vanilla Python will make any difference. SQLite is bundled with Python not with ActiveState. > Copying dll to c:\python25\DLLs directory did not help - it still > shows version sqlite version 2.3.2. which I also do not understand > why I think you might need to install more than the DLL. Check the SQLite web site for a new Ptython interface and install that version. Alan G. From alan.gauld at btinternet.com Fri Nov 7 10:23:13 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 7 Nov 2008 09:23:13 -0000 Subject: [Tutor] problem with simple sqlite script References: Message-ID: "aivars" wrote > sPath=r'e:\pythonexamples\aivars2.db' > > con=sqlite3.connect(sPath) > cur=con.cursor() > cur.execute("insert into test (name) values (?)",sPath) > con.commit() > File "E:\PythonExamples\test.py", line 7, in > cur.execute("insert into test (name) values (?)",sPath) > ProgrammingError: Incorrect number of bindings supplied. The current > statement uses 1, and there are 28 supplied. It looks like name expects a char and you are giving it a string. How did you define the name field of test? Can you send us the create statement? -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From eric at ericabrahamsen.net Fri Nov 7 11:12:29 2008 From: eric at ericabrahamsen.net (Eric Abrahamsen) Date: Fri, 7 Nov 2008 18:12:29 +0800 Subject: [Tutor] Intermediate/advanced concepts In-Reply-To: <20081106231438.ujxyzfnugwcw0sg0@webmail4.isis.unc.edu> References: <20081106231438.ujxyzfnugwcw0sg0@webmail4.isis.unc.edu> Message-ID: <3AA20D99-25DF-424D-AC1E-92B7876F84E4@ericabrahamsen.net> On Nov 7, 2008, at 12:14 PM, btkuhn at email.unc.edu wrote: > Hi everyone, > > I've been teaching myself python for a few months and I'm becoming > frustrated because I've kind of hit a wall in terms of learning new > information. In an effort to continue to learn I've found some > material on more intermediate/advanced topics like linked lists, > nodes, trees, etc. However, it's kind of like reading a math > textbook - the tutorials do a decent job of explaining the material > but it's all kind of theoretical, and I'm not sure how I'd apply > these concepts in real world applications, or incorporate them into > my code. Does anyone have any suggestions for learning about real > world application of more advanced concepts? Are you writing real-world applications and using them? My (admittedly limited) experience has taught me that the real complexities of programming don't lie in obscure data structures or rarely-used functions, but in the practical, real-world issues that arise from creating actual applications: OOP best practices, application architecture, programming paradigms, recurring patterns, even just plain-old programming gotchas (though there are fewer of these in Python than other languages, thankfully). In other words, stuff that isn't necessarily described in the manuals, but that becomes evident once you've made the same mistakes two or three times, and start thinking about modifying your approach to programming. I've never used a tree, and a heap only once, but I feel like I've dipped into some pretty mind-bending stuff in terms of how I've arranged programs. Take metaclasses, for instance: no description of metaclasses I've read ever made sense to me; it only started to come clear after I'd looked at a module I was writing, realized that there was something really fundamentally wrong with it, and then slowly realized that the answer was metaclasses. About eleven lines of metaclass programming, as it turned out, but those seven lines turned my brain inside out for a bit. Not boring in the least! Yrs, Eric > Also, are there other concepts that I should focus on? Frankly, I'm > a bit bored because I've hit this ceiling, and I'm not really sure > where to go to next. > > Thanks, > Ben > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From aivars868 at gmail.com Fri Nov 7 11:26:27 2008 From: aivars868 at gmail.com (aivars) Date: Fri, 7 Nov 2008 12:26:27 +0200 Subject: [Tutor] problem with simple sqlite script In-Reply-To: References: Message-ID: Thanks, Alan, here is a create statement: CREATE TABLE "test" ("name" TEXT) And also I would like to thank you for you web page. Classes and OOP seems to start to make sense to me now slowly after I am reading your material. Aivars 2008/11/7 Alan Gauld : > > "aivars" wrote > >> sPath=r'e:\pythonexamples\aivars2.db' >> >> con=sqlite3.connect(sPath) >> cur=con.cursor() >> cur.execute("insert into test (name) values (?)",sPath) >> con.commit() > >> File "E:\PythonExamples\test.py", line 7, in >> cur.execute("insert into test (name) values (?)",sPath) >> ProgrammingError: Incorrect number of bindings supplied. The current >> statement uses 1, and there are 28 supplied. > > It looks like name expects a char and you are giving it a string. > How did you define the name field of test? > Can you send us the create statement? > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.freenetpages.co.uk/hp/alan.gauld > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From srilyk at gmail.com Fri Nov 7 11:52:04 2008 From: srilyk at gmail.com (W W) Date: Fri, 7 Nov 2008 04:52:04 -0600 Subject: [Tutor] Intermediate/advanced concepts In-Reply-To: <3AA20D99-25DF-424D-AC1E-92B7876F84E4@ericabrahamsen.net> References: <20081106231438.ujxyzfnugwcw0sg0@webmail4.isis.unc.edu> <3AA20D99-25DF-424D-AC1E-92B7876F84E4@ericabrahamsen.net> Message-ID: <333efb450811070252t6a1b85d5j746d2ac717365eeb@mail.gmail.com> On Fri, Nov 7, 2008 at 4:12 AM, Eric Abrahamsen wrote: > >> > > Also, are there other concepts that I should focus on? Frankly, I'm a bit >> bored because I've hit this ceiling, and I'm not really sure where to go to >> next. > > If you want to learn all sorts of new and exciting things, I'd suggest learning about cryptography, and writing attacks (on your own data) as a method of learning more. It's fun, challenging, and there's a real world application for it, if you happen to enjoy any type of security. my 2? -Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Fri Nov 7 12:48:13 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 7 Nov 2008 06:48:13 -0500 Subject: [Tutor] problem with simple sqlite script In-Reply-To: References: Message-ID: <1c2a2c590811070348t1d450f80u8d2ce71298ac35be@mail.gmail.com> On Fri, Nov 7, 2008 at 3:49 AM, aivars wrote: > import sqlite3 > > sPath=r'e:\pythonexamples\aivars2.db' > > con=sqlite3.connect(sPath) > cur=con.cursor() > cur.execute("insert into test (name) values (?)",sPath) The second argument to execute() is a *sequence* of parameter values. A string is a sequence of characters, so by passing a plain string you are saying that each character of the string is a parameter to the SQL. Try adding braces around the parameter to make list: cur.execute("insert into test (name) values (?)", [sPath]) Kent From kent37 at tds.net Fri Nov 7 12:53:58 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 7 Nov 2008 06:53:58 -0500 Subject: [Tutor] Intermediate/advanced concepts In-Reply-To: <20081106231438.ujxyzfnugwcw0sg0@webmail4.isis.unc.edu> References: <20081106231438.ujxyzfnugwcw0sg0@webmail4.isis.unc.edu> Message-ID: <1c2a2c590811070353m35acc54as82409366e06bf2cc@mail.gmail.com> On Thu, Nov 6, 2008 at 11:14 PM, wrote: > Hi everyone, > > I've been teaching myself python for a few months and I'm becoming > frustrated because I've kind of hit a wall in terms of learning new > information. You might like to read the (printed) Python Cookbook. It has many good examples of idiomatic Python in the context of solving a real problem. Also I suggest you start working on a project that interests you and learn what you need to know to complete it. Kent From kent37 at tds.net Fri Nov 7 12:57:38 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 7 Nov 2008 06:57:38 -0500 Subject: [Tutor] Intermediate/advanced concepts In-Reply-To: References: <20081106231438.ujxyzfnugwcw0sg0@webmail4.isis.unc.edu> Message-ID: <1c2a2c590811070357y44d1a6eds45811efe999ea763@mail.gmail.com> On Fri, Nov 7, 2008 at 4:12 AM, Alan Gauld wrote: > For example a linked list is > pretty much a Python list. Other than the very different timing characteristics! Python lists are O(1) for reading or writing a value at an index, O(n) for inserting and deleting. Linked lists are O(n) for reading and writing and O(1) for insertion and deletion (at a known location). Kent From aivars868 at gmail.com Fri Nov 7 12:56:30 2008 From: aivars868 at gmail.com (aivars) Date: Fri, 7 Nov 2008 13:56:30 +0200 Subject: [Tutor] problem with simple sqlite script In-Reply-To: <1c2a2c590811070348t1d450f80u8d2ce71298ac35be@mail.gmail.com> References: <1c2a2c590811070348t1d450f80u8d2ce71298ac35be@mail.gmail.com> Message-ID: Kent, Yesss!! That did the trick! It's worth to remeber. Thank you very much! Aivars 2008/11/7 Kent Johnson : > On Fri, Nov 7, 2008 at 3:49 AM, aivars wrote: > >> import sqlite3 >> >> sPath=r'e:\pythonexamples\aivars2.db' >> >> con=sqlite3.connect(sPath) >> cur=con.cursor() >> cur.execute("insert into test (name) values (?)",sPath) > > The second argument to execute() is a *sequence* of parameter values. > A string is a sequence of characters, so by passing a plain string you > are saying that each character of the string is a parameter to the > SQL. > > Try adding braces around the parameter to make list: > cur.execute("insert into test (name) values (?)", [sPath]) > > Kent > From aivars868 at gmail.com Fri Nov 7 15:40:12 2008 From: aivars868 at gmail.com (aivars) Date: Fri, 7 Nov 2008 16:40:12 +0200 Subject: [Tutor] please help with sqlite replace function In-Reply-To: <491450AB.8010208@free.fr> References: <5e58f2e40811061354jba597cem32bd0d5cfb7fae8b@mail.gmail.com> <491450AB.8010208@free.fr> Message-ID: Hello, Denis, Please try what sqlite3.version shows on your machine? Thanks aivars 2008/11/7 spir : > aivars a ?crit : >> >> Thanks, John, >> Yes it seems you are right. The ActiveState python version I have >> installed have sqlite 2.3.2 only. I find it strange. > > I also have ActiveState's python (mainly for its very good doc) and I get: >>>> >>> import sqlite3 >>>> sqlite3.sqlite_version > '3.3.4' > > Denis > > From denis.spir at free.fr Fri Nov 7 16:58:11 2008 From: denis.spir at free.fr (spir) Date: Fri, 07 Nov 2008 16:58:11 +0100 Subject: [Tutor] pattern expressions Message-ID: <49146593.1060600@free.fr> Hello, I'm learning to use parsers: trying pyParsing, construct and simpleparse to have a better overview. I know a bit regular expressions and rather used to BNF-like formats such as used for specification of languages. But I have never really employed them personly, so the following may be trivial. Below is used a BNF dialect that I think is clear and non-ambiguous. format_code := '+' | '-' | '*' | '#' I need to specify that a single, identical, format_code code may be repeated. Not that a there may be several one on a sequence. format := (format_code)+ would catch '+-', which is wrong. I want only patterns such as '--', '+++',... style_code := '/' | '!' | '_' Similar case, but different. I want patterns like: styled_text := style plain_text style where both style instances are identical. As the number of styles may grow (and even be impredictable: the style_code line will actually be written at runtime according to a config file) I don't want, and anyway can't, specify all possible kinds of styled_text. Even if possible, it would be ugly! I would like to specify a "side-condition" for a pattern, meaning that it should only when a specific token lies aside. For instance: A := A_pattern {X} X is not part of the pattern, thus should not be extracted. If X is just "garbage", I can write an enlarged pattern, then let it down later: A := A_pattern A_X := A X If X itself is a token, I can write a super pattern, then extract both items from the combination, and let down As that come alone: X := X_pattern A := A_pattern A_X := A X But what if X is part of another production? For example: B := X B_end_pattern A_X := A X I tried it, but I can't get X in both productions. So that I catch either B or A_X -- according to mysterious priority rules I don't fully understand (it seems to be neither the longest string, nor the first written pattern, by pyParsing). Now, precisely, what about priority? I mean ambiguous cases, when an actual production can match several patterns. Parsers have tricks, rules, or explicit features to cope with such cases, but, as I understand it, these apply during or after the parsing process, as additional treatment. Is there a way to specify priority in the grammar itself? Denis From john.ertl at navy.mil Fri Nov 7 19:56:40 2008 From: john.ertl at navy.mil (Ertl, John C CIV 63134) Date: Fri, 7 Nov 2008 10:56:40 -0800 Subject: [Tutor] How to use function from specific module and then switch to other module In-Reply-To: <1c2a2c590811061936w41e65c3eo45753daaaa1c19ab@mail.gmail.com> References: <1c2a2c590810211206w179ad95at3cf43315d94bd291@mail.gmail.com> <07EE4797-FF56-4D29-B71E-1F2747240450@mimectl>, <1c2a2c590811061936w41e65c3eo45753daaaa1c19ab@mail.gmail.com> Message-ID: Classification: UNCLASSIFIED Caveat (s): FOUO Kent, Thanks for the lead. I eventually did something like the Strategy Pattern you sent. It was so much simpler when I just inherited the functions. I think I need to redesign the code but for now it works and my boss will be happy. Thanks again. John Ertl Meteorologist FNMOC 7 Grace Hopper Ave. Monterey, CA 93943 (831) 656-5704 john.ertl at navy.mil Classification: UNCLASSIFIED Caveat (s): FOUO From: Kent Johnson Sent: Thu 11/6/2008 7:36 PM To: Ertl, John C CIV 63134 Cc: tutor at python.org Subject: Re: [Tutor] How to use function from specific module and then switch to other module On Thu, Nov 6, 2008 at 5:54 PM, Ertl, John C CIV 63134 wrote: > Classification: UNCLASSIFIED > Caveat (s): FOUO > > I have a program that collects weather data from weather models. I > originally had a module that contained a bunch of function that I used. So > I just added it to the init of the class I was using and inherited the > functions. That worked great but now I have two different models that I can > get weather from. Each Module A and B have the exact same function names > in them but they both do slightly different things. It might help to see a working example of what you did for one model. > > The idea is as I step through a list I want to use a different function > (same name but from a different module) for each element in the list. How > do I have a generic way to do this. > > for example for point 1 I want to use the rain function from Module A and > then for point 2 I want to use the rain function from Module B. At first > though I would just init the class from either A or B for each point but I > need the function from A or B to be able to use function from my main > program...that is why the inheritance thing worked great for just one > module. Don't try to make the model A and B into base classes of the forecast. Just pass the forecast object to the model. So your rain() method will look more like this: def rain(self, fc): fc.calTime() # this function is in the main forecast class fc.rain = do stuff for model A where fc will be the forecast instance. You might also be able to use simple functions rather than classes: def rain(fc): fc.calTime() # this function is in the main forecast class fc.rain = do stuff for model A then just call moduleA.rain(self) or moduleB.rain(self). You might want to read about the Strategy pattern, that is what you are doing. Here is a Python example of a class-based Strategy. http://mail.python.org/pipermail/python-list/2006-April/379188.html This example passes the strategy to the constructor but you can set it in your pointInfo() method if you like. I would just make one function to handle each point though: for each in x.pointList: x.handlePoint(each) where def handlePoint(self, point): pointStrategy = ... pointStrategy.rain(self, point) Kent Kent -------------- next part -------------- An HTML attachment was scrubbed... URL: From ahazer84 at gmail.com Fri Nov 7 20:26:27 2008 From: ahazer84 at gmail.com (Ahmet Yasin HAZER) Date: Fri, 7 Nov 2008 21:26:27 +0200 Subject: [Tutor] Torrent Message-ID: <847f2dba0811071126v4be4d658p291b4cff7a1bda29@mail.gmail.com> -------------- next part -------------- An HTML attachment was scrubbed... URL: From lie.1296 at gmail.com Fri Nov 7 20:32:44 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Fri, 7 Nov 2008 19:32:44 +0000 (UTC) Subject: [Tutor] Intermediate/advanced concepts References: <20081106231438.ujxyzfnugwcw0sg0@webmail4.isis.unc.edu> Message-ID: On Thu, 06 Nov 2008 23:14:38 -0500, btkuhn wrote: > Hi everyone, > > I've been teaching myself python for a few months and I'm becoming > frustrated because I've kind of hit a wall in terms of learning new > information. In an effort to continue to learn I've found some material > on more intermediate/advanced topics like linked lists, nodes, trees, > etc. However, it's kind of like reading a math textbook - the tutorials > do a decent job of explaining the material but it's all kind of > theoretical, and I'm not sure how I'd apply these concepts in real world > applications, or incorporate them into my code. Does anyone have any > suggestions for learning about real world application of more advanced > concepts? > > Also, are there other concepts that I should focus on? Frankly, I'm a > bit bored because I've hit this ceiling, and I'm not really sure where > to go to next. > There is really no ceiling in learning programming. The problem is to find a problem. If you're bored, you can do the practically-for-bored- programmers challenges like Python Challenge (http:// www.pythonchallenge.com/) or Project Euler (http://projecteuler.net/ index.php?section=view) If you're up to the challenge and responsibility, you could join an open source program teams or start one yourself. Alternatively, you could also start learning some embedded python flavors, like the one used by OpenOffice.org or Inkscape, these provides different challenge to vanilla python as you've got to learn their libraries. If you think you're bored of python, perhaps it is time to start learning another language. Having many programming language in your toolbox is certainly a life-saver, since some problems are easier to solve in certain languages than other. For example, many mathematical problems are (much) easier to express in functional language, like Haskell, compared to imperative language. Other languages might have features/paradigm that are foreign in python, like Eiffel's "Programming by Contract". You might also start seeing domain-specific languages, like SQL (database), XSLT (XML), (E)BNF (syntax parsing), etc. Alternative languages you might consider: Haskell, Prolog, Eiffel, C- family, Perl, Lisp-family, APL-family, some assembly, shell scripting (bash, bat, etc) If you're EXTREMELY bored though, you might learn some of the more esoteric languages, e.g. Shakespeare, Piet, Whitespace, etc (be ready to abandon all sanity) From ptmcg at austin.rr.com Fri Nov 7 20:34:06 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Fri, 7 Nov 2008 13:34:06 -0600 Subject: [Tutor] pattern expressions In-Reply-To: References: Message-ID: <8849396A50A14F78829FC47F4705664B@AWA2> Question 1: format_code := '+' | '-' | '*' | '#' I need to specify that a single, identical, format_code code may be repeated. Not that a there may be several one on a sequence. format := (format_code)+ would catch '+-', which is wrong. I want only patterns such as '--', '+++',... This interpretation of '+' in your BNF is a bit out of the norm. Usually this notation 'format_code+' would accept 1 or more of any of your format_code symbols, so '+-+--++' would match. In pyparsing, you could match things like '----' using the Word class and specifying a string containing the single character '-': Word('-'). That is, parse a word made up of '-' characters. There is no pyparsing construct that exactly matches your (format_code)+ repetition, but you could use Word and MatchFirst as in: format = MatchFirst(Word(c) for c in "+-*#") A corresponding regular expression might be: formatRE = '|'.join(re.escape(c)+'+' for c in "+-*#") which you could then parse using the re module, or wrap in a pyparsing Regex object: format = Regex(formatRE) Question 2: style_code := '/' | '!' | '_' Similar case, but different. I want patterns like: styled_text := style plain_text style where both style instances are identical. As the number of styles may grow (and even be impredictable: the style_code line will actually be written at runtime according to a config file) I don't want, and anyway can't, specify all possible kinds of styled_text. Even if possible, it would be ugly! pyparsing includes to methods to help you match the same text that was matched before - matchPreviousLiteral and matchPreviousExpr. Here is how your example would look: plain_text = Word(alphanums + " ") styled_text = style + plain_text + matchPreviousLiteral(style) (There is similar capability in regular expressions, too.) Question 3: I would like to specify a "side-condition" for a pattern, meaning that it should only when a specific token lies aside. For instance: A := A_pattern {X} X is not part of the pattern, thus should not be extracted. If X is just "garbage", I can write an enlarged pattern, then let it down later: A := A_pattern A_X := A X I think you might be looking for some kind of lookahead. In pyparsing, this is supported using the FollowedBy class. A_pattern = Word(alphas) X = Literal(".") A = A_pattern + FollowedBy(X).leaveWhitespace() print A.searchString("alskd sldjf sldfj. slfdj . slfjd slfkj.") prints [['sldfj'], ['slfkj']] From denis.spir at free.fr Fri Nov 7 22:22:33 2008 From: denis.spir at free.fr (spir) Date: Fri, 07 Nov 2008 22:22:33 +0100 Subject: [Tutor] pattern expressions In-Reply-To: <8849396A50A14F78829FC47F4705664B@AWA2> References: <8849396A50A14F78829FC47F4705664B@AWA2> Message-ID: <4914B199.7030601@free.fr> Paul McGuire a ?crit : > Question 1: > format_code := '+' | '-' | '*' | '#' > I need to specify that a single, identical, format_code code may be > repeated. > Not that a there may be several one on a sequence. > format := (format_code)+ > would catch '+-', which is wrong. I want only patterns such as '--', > '+++',... > > > This interpretation of '+' in your BNF is a bit out of the norm. Usually > this notation 'format_code+' would accept 1 or more of any of your > format_code symbols, so '+-+--++' would match. That's what I intended to write above. "(format_code)+ would catch '+-', which is wrong." I need a pattern that matches a repetition of the same token, this token beeing an item of a set. Of course, I could write a pattern for each token... but it is supposed to be programming, not cooking ;-) What I'm looking for is a format that may not exist: format := (format_code)++ where '++' means 'repetition of an identical token' > In pyparsing, you could match things like '----' using the Word class and > specifying a string containing the single character '-': Word('-'). That > is, parse a word made up of '-' characters. There is no pyparsing construct > that exactly matches your (format_code)+ repetition, but you could use Word > and MatchFirst as in: > > format = MatchFirst(Word(c) for c in "+-*#") That's it! I had not realized that, as pyparsing is real puthon, one can also use python idioms /inside/ the grammar... good! thank you. So that it is also possible to have variables, no? Then, my question #2 should be solved, too. > A corresponding regular expression might be: > formatRE = '|'.join(re.escape(c)+'+' for c in "+-*#") > > which you could then parse using the re module, or wrap in a pyparsing Regex > object: > > format = Regex(formatRE) > > > Question 2: > style_code := '/' | '!' | '_' > Similar case, but different. I want patterns like: > styled_text := style plain_text style > where both style instances are identical. As the number of styles may grow > (and even be impredictable: the style_code line will actually be written at > runtime according to a config file) I don't want, and anyway can't, specify > all possible kinds of styled_text. Even if possible, it would be ugly! > > pyparsing includes to methods to help you match the same text that was > matched before - matchPreviousLiteral and matchPreviousExpr. Here is how > your example would look: > > plain_text = Word(alphanums + " ") > styled_text = style + plain_text + matchPreviousLiteral(style) > > (There is similar capability in regular expressions, too.) Good, thank you again. Do you know if there is any way to express such things in ordinary E/BNF, or in any dialect coming from BNF? It's like a variable inside a pattern, and I personly have never seen that. Pattern variables would also be very helpful as (said before) I need to write or at least reconfigurate the grammar at runtime. > Question 3: > I would like to specify a "side-condition" for a pattern, meaning that it > should only match when a specific token lies aside. For instance: > A := A_pattern {X} > X is not part of the pattern, thus should not be extracted. If X is just > "garbage", I can write an enlarged pattern, then let it down later: > A := A_pattern > A_X := A X > > I think you might be looking for some kind of lookahead. In pyparsing, this > is supported using the FollowedBy class. > > A_pattern = Word(alphas) > X = Literal(".") > A = A_pattern + FollowedBy(X).leaveWhitespace() > > print A.searchString("alskd sldjf sldfj. slfdj . slfjd slfkj.") > > prints > > [['sldfj'], ['slfkj']] I guess there is the same for left-side conditions. I'm going to search myself. This guy who develops pyParsing thinks at everything. There are so many helper functions and processing methods -- how can you know all of that by heart, Paul ? Denis From kent37 at tds.net Fri Nov 7 22:42:48 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 7 Nov 2008 16:42:48 -0500 Subject: [Tutor] pattern expressions In-Reply-To: <4914B199.7030601@free.fr> References: <8849396A50A14F78829FC47F4705664B@AWA2> <4914B199.7030601@free.fr> Message-ID: <1c2a2c590811071342n156728d6g74f9410afa89a1bc@mail.gmail.com> On Fri, Nov 7, 2008 at 4:22 PM, spir wrote: > This guy who develops pyParsing thinks at everything. There are so > many helper functions and processing methods -- how can you know all of that > by heart, Paul ? Maybe because he *is* the guy who develops pyparsing? ;-) Kent From alan.gauld at btinternet.com Fri Nov 7 23:45:38 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 7 Nov 2008 22:45:38 -0000 Subject: [Tutor] please help with sqlite replace function References: <5e58f2e40811061354jba597cem32bd0d5cfb7fae8b@mail.gmail.com><491450AB.8010208@free.fr> Message-ID: "aivars" wrote > Please try what sqlite3.version shows on your machine? >> I also have ActiveState's python (mainly for its very good doc) and >> I get: >>>>> >>> import sqlite3 >>>>> sqlite3.sqlite_version >> '3.3.4' Me too with Python 2.5.1 from Activestate. Alan G From alan.gauld at btinternet.com Sat Nov 8 00:16:07 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 7 Nov 2008 23:16:07 -0000 Subject: [Tutor] Intermediate/advanced concepts References: <20081106231438.ujxyzfnugwcw0sg0@webmail4.isis.unc.edu> <1c2a2c590811070357y44d1a6eds45811efe999ea763@mail.gmail.com> Message-ID: "Kent Johnson" wrote >> For example a linked list is pretty much a Python list. > > Other than the very different timing characteristics! True, but its pretty rare that timing issues are a reason for me to choose a data structure - especially if I need to hand code it! :-) > Python lists are O(1) for reading or writing a value at an index, > O(n) for inserting and deleting. Linked lists are O(n) for reading > and writing and O(1) for insertion and deletion (at a known > location). I would say O(1) only if you already have a reference to that location (ie its known in that sense) but if you know that it's at position 23 but you only have a reference to the head you still need to navigate sequentially to the 23rd element so its still an O(n). O(1) only applies when inserting at the next position to where you currently are. That's not too common a scenario in my experience. But the geneal point is a good specific example (and I was struggling to think of one!) where you might choose a non standard list over the vanilla version. The array module is another case where performance is improved over the standard lists. Alan G. From alan.gauld at btinternet.com Sat Nov 8 00:10:50 2008 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Fri, 7 Nov 2008 23:10:50 +0000 (GMT) Subject: [Tutor] problem with simple sqlite script Message-ID: <75303.80480.qm@web86710.mail.ird.yahoo.com> > CREATE TABLE "test" ("name" TEXT) OK, That looks fine. >> con=sqlite3.connect(sPath) >> cur=con.cursor() >> cur.execute("insert into test (name) values (?)",sPath) Try putting the string variable in a tuple: cur.execute("insert into test (name) values (?)", (sPath,) ) That seems to work for me... HTH, Alan G. From alan.gauld at btinternet.com Sat Nov 8 00:10:50 2008 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Fri, 7 Nov 2008 23:10:50 +0000 (GMT) Subject: [Tutor] problem with simple sqlite script Message-ID: <75303.80480.qm@web86710.mail.ird.yahoo.com> > CREATE TABLE "test" ("name" TEXT) OK, That looks fine. >> con=sqlite3.connect(sPath) >> cur=con.cursor() >> cur.execute("insert into test (name) values (?)",sPath) Try putting the string variable in a tuple: cur.execute("insert into test (name) values (?)", (sPath,) ) That seems to work for me... HTH, Alan G. From dwbarne at earthlink.net Sat Nov 8 01:09:00 2008 From: dwbarne at earthlink.net (dwbarne at earthlink.net) Date: Fri, 7 Nov 2008 17:09:00 -0700 (GMT-07:00) Subject: [Tutor] gnuplot from a python gui Message-ID: <25632507.1226102941237.JavaMail.root@elwamui-hound.atl.sa.earthlink.net> Hello tutors, I'm trying to generate a plot using gnuplot from within a python gui. In Windows, if after the plot is drawn I use a raw_input string demanding a 'RETURN' be hit, the plot will persist on the screen until the 'RETURN' is pressed. In *nix, one can use the 'persist' switch to easily and much more elegantly accomplish the same. My question is, is there a better way IN WINDOWS to keep the plot on the screen rather than having to leave the gui and find the console window in which a 'RETURN' must be pressed to continue? My gui will not 'quit' until I enter the 'RETURN' in the console window. Kind of a chintzy way to end the gui, really. There must be a better way than using raw_input??? Daniel B. From kent37 at tds.net Sat Nov 8 04:58:35 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 7 Nov 2008 22:58:35 -0500 Subject: [Tutor] Intermediate/advanced concepts In-Reply-To: References: <20081106231438.ujxyzfnugwcw0sg0@webmail4.isis.unc.edu> <1c2a2c590811070357y44d1a6eds45811efe999ea763@mail.gmail.com> Message-ID: <1c2a2c590811071958t14499b32y2f3144ecd2a9be55@mail.gmail.com> On Fri, Nov 7, 2008 at 6:16 PM, Alan Gauld wrote: > True, but its pretty rare that timing issues are a reason for me to choose a > data structure I would guess you commonly choose a dict or set over a list when you need fast tests for membership. Failure to choose dict when appropriate is certainly a common cause of performance problems. > But the geneal point is a good specific example (and I was struggling to > think of one!) where you might choose a non standard list over the vanilla > version. The array module is another case where performance is improved over > the standard lists. The standard lib also includes collections.deque (O(1) insertion and deletion at both ends) and heapq (binary priority queue). Third party implementations of b-tree, avltree and trie are available which have better performance than list and dict for some usage. Kent From jmorcombe at westnet.com.au Sat Nov 8 08:22:59 2008 From: jmorcombe at westnet.com.au (Jim Morcombe) Date: Sat, 08 Nov 2008 16:22:59 +0900 Subject: [Tutor] cgi scripts Message-ID: <49153E53.6080207@westnet.com.au> I want to print a list of the keys and their values passed to a cgi script by an HTML form. I have tried this, but just seems to crash. Any ideas? Jim Morcombe #!C:\python25\python.exe import cgi, sys # import cgitb; cgitb.enable() #Send errors to browser sys.stderr = sys.stdout #Parse data from form data = cgi.FieldStorage() #Send response to browser print "Content-type: text/html\n" print "CGI Form Response\n" print "

    This is the data passed to the cgi script

    " print "These are the keys\n" print "
    " print for k in data.keys(): print "key: ", k, " value: ", data[k] From steve at alchemy.com Sat Nov 8 08:47:04 2008 From: steve at alchemy.com (Steve Willoughby) Date: Fri, 07 Nov 2008 23:47:04 -0800 Subject: [Tutor] cgi scripts In-Reply-To: <49153E53.6080207@westnet.com.au> References: <49153E53.6080207@westnet.com.au> Message-ID: <491543F8.3020901@alchemy.com> Jim Morcombe wrote: > I want to print a list of the keys and their values passed to a cgi > script by an HTML form. > I have tried this, but just seems to crash. When you say "crash", what do you mean, exactly? > > Any ideas? > print "Content-type: text/html\n" > print "CGI Form Response\n" > print "

    This is the data passed to the cgi script

    " It wouldn't hurt to output fully-formed HTML here. > print for k in data.keys(): I think you'll find the source of your problem right about here. From jmorcombe at westnet.com.au Sat Nov 8 09:10:29 2008 From: jmorcombe at westnet.com.au (Jim Morcombe) Date: Sat, 08 Nov 2008 17:10:29 +0900 Subject: [Tutor] cgi scripts In-Reply-To: <491543F8.3020901@alchemy.com> References: <49153E53.6080207@westnet.com.au> <491543F8.3020901@alchemy.com> Message-ID: <49154975.3030704@westnet.com.au> Bt "Crash", I mean the browser displays: Internal Server Error The server encountered an internal error or misconfiguration and was unable to complete your request. The code I sent before had a silly mistake in it. Here is a better example of the things I am trying and failing at. I can print a single key. I can iterate over the keys, just printing out "hello" for each iteration. But I can't figure out how to iterate over all the keys printing out somethinf sensible. #!C:\python25\python.exe import cgi, sys # import cgitb; cgitb.enable() #Send errors to browser sys.stderr = sys.stdout #Parse data from form data = cgi.FieldStorage() #Send response to browser print "Content-type: text/html\n" print "CGI Form Response\n" print "

    This is the data passed to the cgi script

    " # This next bit works and I can see a list of keys displayed in the browser print "Version 4: data.keys()\n" print "
    " print data.keys() # This next bit also works and I can see the value of the variable "JQuiz_q01_score" print "

    -----------------" print "JQuiz_q01_score = ", data["JQuiz_q01_score"].value # However, whenever I try to iterate over all the keys, I get the "Internal Server error" print "

    -----------------" for k in data.keys(): print "
    "data[k].key # I have also tried data[k] # data.key[k] # data[k].value # and many other random combinations. From alan.gauld at btinternet.com Sat Nov 8 09:25:13 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 8 Nov 2008 08:25:13 -0000 Subject: [Tutor] cgi scripts References: <49153E53.6080207@westnet.com.au> <491543F8.3020901@alchemy.com> <49154975.3030704@westnet.com.au> Message-ID: "Jim Morcombe" wrote > The code I sent before had a silly mistake in it. Here is a better > example of the things I am trying and failing at. Look at what you are doing in the two examples.... > # This next bit also works and I can see the value of the variable > print "JQuiz_q01_score = ", data["JQuiz_q01_score"].value > > # However, whenever I try to iterate over all the keys, I get the > print "
    "data[k].key Can you see what you are doing differently whwen accessing the data? HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From jmorcombe at westnet.com.au Sat Nov 8 09:38:31 2008 From: jmorcombe at westnet.com.au (Jim Morcombe) Date: Sat, 08 Nov 2008 17:38:31 +0900 Subject: [Tutor] cgi scripts In-Reply-To: References: <49153E53.6080207@westnet.com.au> <491543F8.3020901@alchemy.com> <49154975.3030704@westnet.com.au> Message-ID: <49155007.7020304@westnet.com.au> Thanks guys, This works :) field_list = '

      \n' for field in data.keys(): field_list = field_list + '
    • %s : %s
    • \n' % (field, data[field].value) field_list = field_list + '
    \n' print field_list I think the problem wasn't in getting the keys and values, but I might have been producing illegal HTML code before. I think I'd better brush up on my HTML skills. Jim Alan Gauld wrote: > > "Jim Morcombe" wrote > >> The code I sent before had a silly mistake in it. Here is a better >> example of the things I am trying and failing at. > > Look at what you are doing in the two examples.... > >> # This next bit also works and I can see the value of the variable >> print "JQuiz_q01_score = ", data["JQuiz_q01_score"].value >> >> # However, whenever I try to iterate over all the keys, I get the >> print "
    "data[k].key > > Can you see what you are doing differently whwen accessing > the data? > > HTH, > > From dfjennings at gmail.com Sat Nov 8 13:59:33 2008 From: dfjennings at gmail.com (Don Jennings) Date: Sat, 8 Nov 2008 07:59:33 -0500 Subject: [Tutor] cgi scripts In-Reply-To: <22ce67f0811080458h7bc4323fj37dee86c79186913@mail.gmail.com> References: <49153E53.6080207@westnet.com.au> <491543F8.3020901@alchemy.com> <49154975.3030704@westnet.com.au> <49155007.7020304@westnet.com.au> <22ce67f0811080458h7bc4323fj37dee86c79186913@mail.gmail.com> Message-ID: <22ce67f0811080459h1bddf4e7qbdd3f791736d8def@mail.gmail.com> (Oops! Forgot to include tutor in recipient.) On 11/8/08, Don Jennings wrote: > Hi, Jim. Actually, improper HTML would cause a problem with the > browser and what it may or may not display. An "Internal Server Error" > does indicate that you had a problem with your code. I suggest > referring back to Alan's post again. > > Take care, > Don > From kent37 at tds.net Sat Nov 8 14:19:37 2008 From: kent37 at tds.net (Kent Johnson) Date: Sat, 8 Nov 2008 08:19:37 -0500 Subject: [Tutor] cgi scripts In-Reply-To: <49155007.7020304@westnet.com.au> References: <49153E53.6080207@westnet.com.au> <491543F8.3020901@alchemy.com> <49154975.3030704@westnet.com.au> <49155007.7020304@westnet.com.au> Message-ID: <1c2a2c590811080519t69c6ce20mc840e405628ed819@mail.gmail.com> On Sat, Nov 8, 2008 at 3:38 AM, Jim Morcombe wrote: > I think the problem wasn't in getting the keys and values, but I might have > been producing illegal HTML code before. > I think I'd better brush up on my HTML skills. Poorly formed HTML won't give an internal server error. That is due to something more serious such as a syntax error in your program. With bad HTML you will see *something* in the browser, even if only a blank page, and you can view source to see the actual code. Kent From denis.spir at free.fr Sat Nov 8 22:05:02 2008 From: denis.spir at free.fr (spir) Date: Sat, 08 Nov 2008 22:05:02 +0100 Subject: [Tutor] gnuplot from a python gui In-Reply-To: <25632507.1226102941237.JavaMail.root@elwamui-hound.atl.sa.earthlink.net> References: <25632507.1226102941237.JavaMail.root@elwamui-hound.atl.sa.earthlink.net> Message-ID: <4915FEFE.5070704@free.fr> dwbarne at earthlink.net a ?crit : > Hello tutors, > > I'm trying to generate a plot using gnuplot from within a python gui. In Windows, if after the plot is drawn I use a raw_input string demanding a 'RETURN' be hit, the plot will persist on the screen until the 'RETURN' is pressed. In *nix, one can use the 'persist' switch to easily and much more elegantly accomplish the same. > > My question is, is there a better way IN WINDOWS to keep the plot on the screen rather than having to leave the gui and find the console window in which a 'RETURN' must be pressed to continue? My gui will not 'quit' until I enter the 'RETURN' in the console window. Kind of a chintzy way to end the gui, really. > > There must be a better way than using raw_input??? > > Daniel B. Maybe a stupid question: as your application has a GUI, why do you use this raw_input() trick? As far as I know, this is a way to let the console open at the end of execution so that the user can watch results (otherwise it's autom. closed). What's the point in doing that in a GUI app? Denis From hooya27 at gmail.com Sun Nov 9 00:34:54 2008 From: hooya27 at gmail.com (Dan) Date: Sat, 8 Nov 2008 18:34:54 -0500 Subject: [Tutor] Upgrading from Python 2.5 to Python 2.6 - IDLE not working... Message-ID: Hi All, This is my first post, so I apologize in advance for any etiquette violations. I am interested in learning Python, and to that end, I undertook to upgrade my current version of Python 2.5 (available via openSUSE repositories and YaST) to Python 2.6. I have Python 2.6 running (compiled from source [I'm not a total bonehead]) but idle gives me the following when I invoke it in bash: dan at linux-ypm1:~> idle Traceback (most recent call last): File "/usr/local/bin/idle", line 3, in from idlelib.PyShell import main File "/usr/local/lib/python2.6/idlelib/PyShell.py", line 14, in import macosxSupport File "/usr/local/lib/python2.6/idlelib/macosxSupport.py", line 6, in import Tkinter File "/usr/local/lib/python2.6/lib-tk/Tkinter.py", line 39, in import _tkinter # If this fails your Python may not be configured for Tk ImportError: No module named _tkinter dan at linux-ypm1:~> I thought of unistalling and reinstalling (using YaST) the associated Python packages to make them aware of the version change, but the Idle package says it requires Python 2.5.2, nothing more or less, so I didn't attempt it. Thanks in advance for your patience. Dan -- -=-=-=-=-=-=-=-=- Science is what we have learned about how not to fool ourselves about the way the world is. - Richard Feynman -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Sun Nov 9 02:43:36 2008 From: kent37 at tds.net (Kent Johnson) Date: Sat, 8 Nov 2008 20:43:36 -0500 Subject: [Tutor] Upgrading from Python 2.5 to Python 2.6 - IDLE not working... In-Reply-To: References: Message-ID: <1c2a2c590811081743q4544f40es83ec91dfa001f520@mail.gmail.com> On Sat, Nov 8, 2008 at 6:34 PM, Dan wrote: > I am interested in learning Python, and to that end, I undertook to upgrade > my current version of Python 2.5 (available via openSUSE repositories and > YaST) to Python 2.6. I have Python 2.6 running (compiled from source [I'm > not a total bonehead]) but idle gives me the following when I invoke it in > bash: > > dan at linux-ypm1:~> idle > Traceback (most recent call last): > File "/usr/local/bin/idle", line 3, in > from idlelib.PyShell import main > File "/usr/local/lib/python2.6/idlelib/PyShell.py", line 14, in > import macosxSupport > File "/usr/local/lib/python2.6/idlelib/macosxSupport.py", line 6, in > > import Tkinter > File "/usr/local/lib/python2.6/lib-tk/Tkinter.py", line 39, in > import _tkinter # If this fails your Python may not be configured for Tk > ImportError: No module named _tkinter > dan at linux-ypm1:~> Are you running on MacOS or Linux? I'm confused by the import macosxSupport. There is a known problem with IDLE on MacOSX: http://bugs.python.org/issue4017 For linux I think there is a build option to include tkinter but someone else will have to answer that one. Kent From ichigo6420 at gmail.com Sun Nov 9 04:22:15 2008 From: ichigo6420 at gmail.com (Bap) Date: Sat, 08 Nov 2008 19:22:15 -0800 Subject: [Tutor] Question Message-ID: <49165767.8010308@gmail.com> Can I use notepad++ for Python? Thank you! ;-) From airchia at gmail.com Sun Nov 9 06:41:08 2008 From: airchia at gmail.com (Nick Scholtes) Date: Sat, 8 Nov 2008 23:41:08 -0600 Subject: [Tutor] Question In-Reply-To: <49165767.8010308@gmail.com> References: <49165767.8010308@gmail.com> Message-ID: Last I checked, Notepad ++ works with Python. I've never used it for Python, so I don't know how it works. Nick On Sat, Nov 8, 2008 at 9:22 PM, Bap wrote: > Can I use notepad++ for Python? > > Thank you! ;-) > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Art: http://www.coroflot.com/bellsoffreedom -------------- next part -------------- An HTML attachment was scrubbed... URL: From denis.spir at free.fr Sun Nov 9 11:34:37 2008 From: denis.spir at free.fr (spir) Date: Sun, 09 Nov 2008 11:34:37 +0100 Subject: [Tutor] get a module's own (top_level) dict? Message-ID: <4916BCBD.8080300@free.fr> Hello pyhonistas, Example: === module content === a = 1 b = 2 ====================== I'm looking for a way to get something like {'a':a, b':2}. Actually, names defind in the module will be instances of a custom type. I want to give them an attribute that holds their own name. E.g.: for key,obj in dict: obj.name = key From lie.1296 at gmail.com Sun Nov 9 13:28:53 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Sun, 9 Nov 2008 12:28:53 +0000 (UTC) Subject: [Tutor] Upgrading from Python 2.5 to Python 2.6 - IDLE not working... References: Message-ID: On Sat, 08 Nov 2008 18:34:54 -0500, Dan wrote: > Hi All, > > This is my first post, so I apologize in advance for any etiquette > violations. > > I am interested in learning Python, and to that end, I undertook to > upgrade my current version of Python 2.5 (available via openSUSE > repositories and YaST) to Python 2.6. I have Python 2.6 running > (compiled from source [I'm not a total bonehead]) but idle gives me the > following when I invoke it in bash: > > dan at linux-ypm1:~> idle > Traceback (most recent call last): > File "/usr/local/bin/idle", line 3, in from idlelib.PyShell > import main > File "/usr/local/lib/python2.6/idlelib/PyShell.py", line 14, in > import macosxSupport > File "/usr/local/lib/python2.6/idlelib/macosxSupport.py", line 6, in > > import Tkinter > File "/usr/local/lib/python2.6/lib-tk/Tkinter.py", line 39, in > import _tkinter # If this fails your Python may not be > configured for Tk > ImportError: No module named _tkinter dan at linux-ypm1:~> > > I thought of unistalling and reinstalling (using YaST) the associated > Python packages to make them aware of the version change, but the Idle > package says it requires Python 2.5.2, nothing more or less, so I didn't > attempt it. > > Thanks in advance for your patience. > > Dan FYI, I've got idle running with python2.6 Python 2.6 (r26:66714, Oct 19 2008, 19:48:03) [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2 Type "copyright", "credits" or "license()" for more information. **************************************************************** Personal firewall software may warn about the connection IDLE makes to its subprocess using this computer's internal loopback interface. This connection is not visible on any external interface and no data is sent to or received from the Internet. **************************************************************** IDLE 2.6 >>> From kent37 at tds.net Sun Nov 9 13:41:13 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 9 Nov 2008 07:41:13 -0500 Subject: [Tutor] get a module's own (top_level) dict? In-Reply-To: <4916BCBD.8080300@free.fr> References: <4916BCBD.8080300@free.fr> Message-ID: <1c2a2c590811090441re8e2c95lf5334ba07995392b@mail.gmail.com> On Sun, Nov 9, 2008 at 5:34 AM, spir wrote: > Hello pyhonistas, > > Example: > === module content === > a = 1 > b = 2 > ====================== > > I'm looking for a way to get something like {'a':a, b':2}. Actually, names > defind in the module will be instances of a custom type. I want to give them > an attribute that holds their own name. E.g.: > for key,obj in dict: > obj.name = key >From within the module, globals() returns the dict you want. However I would say that needing to know the name of something is a code smell. The usual way to do this is to keep an explicit dict of the objects of interest. Why do you need objects to know their name? Why can't you tell it it's name when you create it? Kent From lie.1296 at gmail.com Sun Nov 9 14:44:34 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Sun, 9 Nov 2008 13:44:34 +0000 (UTC) Subject: [Tutor] get a module's own (top_level) dict? References: <4916BCBD.8080300@free.fr> Message-ID: On Sun, 09 Nov 2008 11:34:37 +0100, spir wrote: > Hello pyhonistas, > > Example: > === module content === > a = 1 > b = 2 > ====================== > > I'm looking for a way to get something like {'a':a, b':2}. Actually, > names defind in the module will be instances of a custom type. I want to > give them an attribute that holds their own name. E.g.: for key,obj in > dict: > obj.name = key > _______________________________________________ Tutor maillist - > Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor Are you looking for dir() (built-in function) dir() -> returns names in current scope dir(module/class/object) -> module/class/object's attributes From roadierich at googlemail.com Sun Nov 9 15:24:37 2008 From: roadierich at googlemail.com (Rich Lovely) Date: Sun, 9 Nov 2008 14:24:37 +0000 Subject: [Tutor] Question In-Reply-To: <49165767.8010308@gmail.com> References: <49165767.8010308@gmail.com> Message-ID: All you really need for python is a basic text editor, and the interpretter. Everything else is icing. Notepad++ has syntax highlighting support for python, and sounds as if it has brace and bracket completion. Most people here will tell you that auto- completion in python is a complex issue (most objects can have dynamic attributes defined at runtime that most auto-complete engines will miss). Notepad++ also supports auto-indentation, which is probably the most useful feature of any editor used for python. Note I've never used it myself, just took a quick look through it's website. --- Richard "Roadie Rich" Lovely Part of the JNP|UK Famille www.theJNP.com (Sent from my iPod - please allow me a few typos: it's a very small keyboard) On 9 Nov 2008, at 03:22 AM, Bap wrote: > Can I use notepad++ for Python? > > Thank you! ;-) > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From tim at johnsons-web.com Sun Nov 9 21:48:19 2008 From: tim at johnsons-web.com (Tim Johnson) Date: Sun, 9 Nov 2008 11:48:19 -0900 Subject: [Tutor] cgi scripts In-Reply-To: <1c2a2c590811080519t69c6ce20mc840e405628ed819@mail.gmail.com> References: <49153E53.6080207@westnet.com.au> <49155007.7020304@westnet.com.au> <1c2a2c590811080519t69c6ce20mc840e405628ed819@mail.gmail.com> Message-ID: <200811091148.19199.tim@johnsons-web.com> On Saturday 08 November 2008, Kent Johnson wrote: > On Sat, Nov 8, 2008 at 3:38 AM, Jim Morcombe wrote: > > I think the problem wasn't in getting the keys and values, but I might > > have been producing illegal HTML code before. > > I think I'd better brush up on my HTML skills. > > Poorly formed HTML won't give an internal server error. That is due to > something more serious such as a syntax error in your program. I always configure cgi scripts so that I can also run them from the command line. That can be an effective way to catch errors otherwise obfuscated by the browser. Although I don't use windows any longer, I recall that pythonwin was a nice IDE to use and it probably has a syntax checker. tim From kent37 at tds.net Sun Nov 9 22:54:36 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 9 Nov 2008 16:54:36 -0500 Subject: [Tutor] get a module's own (top_level) dict? In-Reply-To: <49174B50.1020103@free.fr> References: <4916BCBD.8080300@free.fr> <49174B50.1020103@free.fr> Message-ID: <1c2a2c590811091354y6f8d9d76y2b39850a0d9eec82@mail.gmail.com> On Sun, Nov 9, 2008 at 3:42 PM, spir wrote: > Thank you Lie & Kent, that's it. Excuse me, Lie, I answered too fast. > Now, to answer Kent questions, there are several reasons why I wish to do > that. > These objects will be of a 'pattern' type that (unlike function, for > instance), don't know how they're called. They need to hold their name to > pass it to further objects (say, tokens) that will be generated according to > these patterns, but who are not instances of the patterns. Actually, the > pattern's name is a kind of token 'type'. You see what I mean? No, not at all. Why can't you assign the pattern's name when you create it? > Concretely, I need to instanciate object with a type specified by the > pattern's name and init data given by the result of the parsing. This can be done with a dict mapping pattern names to types. I don't see how having a pattern know its own name helps here. For example: In [22]: class Foo: ....: def __init__(self, x): ....: print "Foo(%s)" % x In [24]: class Bar: ....: def __init__(self, x): ....: print "Bar(%s)" % x In [25]: types = dict(foo=Foo, bar=Bar) In [26]: types['foo'](3) Foo(3) In [27]: types['bar'](42) Bar(42) > Also, I want to write the pattern --> name --> type --> object toolset in a > general to be able to reuse it. Also, simply because I want it so! > There will be many such names, too. > Also: the patterns will actually be generated at runtime according to a > config file -- and can also change at runtime (--> reload() grammar module), > following user customization. So that I don't even know the names at design > time. How are you going to create all these named objects? Kent From denis.spir at free.fr Mon Nov 10 10:25:58 2008 From: denis.spir at free.fr (spir) Date: Mon, 10 Nov 2008 10:25:58 +0100 Subject: [Tutor] [Fwd: Re: get a module's own (top_level) dict?] Message-ID: <4917FE26.3030904@free.fr> (forwarded to the list) >> Hello pyhonistas, >> >> Example: >> === module content === >> a = 1 >> b = 2 >> ====================== >> >> I'm looking for a way to get something like {'a':a, b':2}. Actually, >> names defind in the module will be instances of a custom type. I want to >> give them an attribute that holds their own name. E.g.: for key,obj in >> dict: >> obj.name = key Thank you Lie & Kent, that's it. Excuse me, Lie, I answered too fast. Now, to answer Kent questions, there are several reasons why I wish to do that. These objects will be of a 'pattern' type that (unlike function, for instance), don't know how they're called. They need to hold their name to pass it to further objects (say, tokens) that will be generated according to these patterns, but who are not instances of the patterns. Actually, the pattern's name is a kind of token 'type'. You see what I mean? Concretely, I need to instanciate object with a type specified by the pattern's name and init data given by the result of the parsing. Also, I want to write the pattern --> name --> type --> object toolset in a general to be able to reuse it. Also, simply because I want it so! There will be many such names, too. Also: the patterns will actually be generated at runtime according to a config file -- and can also change at runtime (--> reload() grammar module), following user customization. So that I don't even know the names at design time. Denis From pythonnutter at gmail.com Mon Nov 10 10:33:12 2008 From: pythonnutter at gmail.com (Python Nutter) Date: Mon, 10 Nov 2008 20:33:12 +1100 Subject: [Tutor] Question In-Reply-To: References: <49165767.8010308@gmail.com> Message-ID: I use Notepad++ on my Windows box for Python, but my feeling about it is a bit "Blah..." but thats my feeling with Windows in general ;-) I think I'm one of the rare ones who do not like its choice of Syntax Highlighting colours. But too lazy to change them since I don't do much development on my Windows box to warrant it now that I got a Mac on the desk as well. I use ipython a lot and linked to Notepad++ in it so on Windows just typing >>>edit somefile.py will auto launch Notepad++ and let me code then when I save/exit it will load the file automatically back into ipython and start interpreting it. On the Mac I just linked ipython in the config file to nano On the iPhone 3G I just linked ipython in the config file to nano On the Linux/Ubuntu box I also linked to nano... hmmm looks like I use nano a lot more than I though ;-) Cheers, PN From jmorcombe at westnet.com.au Mon Nov 10 13:00:50 2008 From: jmorcombe at westnet.com.au (Jim Morcombe) Date: Mon, 10 Nov 2008 21:00:50 +0900 Subject: [Tutor] cgi scripts In-Reply-To: <22ce67f0811080458h7bc4323fj37dee86c79186913@mail.gmail.com> References: <49153E53.6080207@westnet.com.au> <491543F8.3020901@alchemy.com> <49154975.3030704@westnet.com.au> <49155007.7020304@westnet.com.au> <22ce67f0811080458h7bc4323fj37dee86c79186913@mail.gmail.com> Message-ID: <49182272.7080108@westnet.com.au> Actually, that's good to know. I was thinking it was going to be pretty hard to debug if I couldn't tell the difference between HTML errors and Python errors. I have been using import cgitb; cgitb.enable() It seems to re-direct some of the errors to the browser, but obviously not all. Jim Don Jennings wrote: > Hi, Jim. Actually, improper HTML would cause a problem with the > browser and what it may or may not display. An "Internal Server Error" > does indicate that you had a problem with your code. I suggest > referring back to Alan's post again. > > Take care, > Don > > > From kent37 at tds.net Mon Nov 10 13:57:50 2008 From: kent37 at tds.net (Kent Johnson) Date: Mon, 10 Nov 2008 07:57:50 -0500 Subject: [Tutor] cgi scripts In-Reply-To: <49182272.7080108@westnet.com.au> References: <49153E53.6080207@westnet.com.au> <491543F8.3020901@alchemy.com> <49154975.3030704@westnet.com.au> <49155007.7020304@westnet.com.au> <22ce67f0811080458h7bc4323fj37dee86c79186913@mail.gmail.com> <49182272.7080108@westnet.com.au> Message-ID: <1c2a2c590811100457j30a774aara4068c6957b64e69@mail.gmail.com> On Mon, Nov 10, 2008 at 7:00 AM, Jim Morcombe wrote: > I have been using > import cgitb; cgitb.enable() > > It seems to re-direct some of the errors to the browser, but obviously not > all. Right, if the script fails before that line runs, of course it will have no effect. Kent From alan.gauld at btinternet.com Mon Nov 10 16:40:49 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 10 Nov 2008 15:40:49 -0000 Subject: [Tutor] Question References: <49165767.8010308@gmail.com> Message-ID: "Python Nutter" wrote > On the Mac I just linked ipython in the config file to nano > On the iPhone 3G I just linked ipython in the config file to nano > On the Linux/Ubuntu box I also linked to nano... > > hmmm looks like I use nano a lot more than I though ;-) Nothing to do with Python directly, but I'm curious... nano is a very popular editor in Unix/Linux circles but I confess I never could figure out why? Is there something I'm missing? What does nano do that vi (or emacs) doesn't? Given that vi is the "standard" editor on *nix ity would seem the obvious choice. But everyone seems to be using nano? Why? PS. I should explain that I used to use Unix a lot but it was before nano appeared to proliferate so I never used it. Now I only use *nix occasionally but nano is everywhere it seems. Alan G. From srilyk at gmail.com Mon Nov 10 16:59:16 2008 From: srilyk at gmail.com (W W) Date: Mon, 10 Nov 2008 09:59:16 -0600 Subject: [Tutor] Question In-Reply-To: References: <49165767.8010308@gmail.com> Message-ID: <333efb450811100759p2cacd5b6v37969fd2ed15d363@mail.gmail.com> On Mon, Nov 10, 2008 at 9:40 AM, Alan Gauld wrote: > What does nano do that vi (or emacs) doesn't? Given that vi is the > "standard" editor on *nix ity would seem the obvious choice. But everyone > seems to be using nano? Why? AFAIK, it's a little smaller/faster than emacs... but since I'm a vi(m) fan, I'm probably the wrong person for the question ;) -Wayne > > PS. I should explain that I used to use Unix a lot but it was before nano > appeared to proliferate so I never used it. Now I only use *nix occasionally > but nano is everywhere it seems. > > Alan G. > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- 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 -------------- next part -------------- An HTML attachment was scrubbed... URL: From connorsml at gmail.com Mon Nov 10 17:07:38 2008 From: connorsml at gmail.com (Michael Connors) Date: Mon, 10 Nov 2008 17:07:38 +0100 Subject: [Tutor] Question In-Reply-To: <333efb450811100759p2cacd5b6v37969fd2ed15d363@mail.gmail.com> References: <49165767.8010308@gmail.com> <333efb450811100759p2cacd5b6v37969fd2ed15d363@mail.gmail.com> Message-ID: 2008/11/10 W W > On Mon, Nov 10, 2008 at 9:40 AM, Alan Gauld wrote: > >> > > What does nano do that vi (or emacs) doesn't? Given that vi is the >> "standard" editor on *nix ity would seem the obvious choice. But everyone >> seems to be using nano? Why? > > > AFAIK, it's a little smaller/faster than emacs... but since I'm a vi(m) > fan, I'm probably the wrong person for the question ;) > > > My guess is that, if you want to provide instructions to someone with no linux/unix experience. e.g. to edit a config file, you can safely tell them to: nano myfile.conf and expect them to be able to save the file and return to the command line. If you want to give the same instructions using vim or emacs, you would also need to specify how to save and exit. I imagine this to be the reason it is popular in tutorials, and if all the tutorials you use, use nano, you will probably use it too. -- Michael Connors -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Mon Nov 10 17:24:23 2008 From: kent37 at tds.net (Kent Johnson) Date: Mon, 10 Nov 2008 11:24:23 -0500 Subject: [Tutor] Question In-Reply-To: References: <49165767.8010308@gmail.com> <333efb450811100759p2cacd5b6v37969fd2ed15d363@mail.gmail.com> Message-ID: <1c2a2c590811100824s3543832ds6130a9c948f12cb8@mail.gmail.com> On Mon, Nov 10, 2008 at 11:07 AM, Michael Connors wrote: > My guess is that, if you want to provide instructions to someone with no > linux/unix experience. e.g. to edit a config file, you can safely tell them > to: nano myfile.conf and expect them to be able to save the file and return > to the command line. If you want to give the same instructions using vim or > emacs, you would also need to specify how to save and exit. I imagine this > to be the reason it is popular in tutorials, and if all the tutorials you > use, use nano, you will probably use it too. Yes. I don't use vim or emacs. When I need a terminal-based editor I use nano because I can figure it out. Kent From t.gkikopoulos at dundee.ac.uk Mon Nov 10 18:12:43 2008 From: t.gkikopoulos at dundee.ac.uk (trias) Date: Mon, 10 Nov 2008 09:12:43 -0800 (PST) Subject: [Tutor] import data (txt/csv) into list/array and manipulation Message-ID: <20424075.post@talk.nabble.com> Hi, I have started learning python (any online help content suggestions are welcome) and want to write a couple of scripts to do simple numeric calculations on array data. filetype(1) I have reference files (ie file.csv) that contain three columns with variable rows, first column is type str contains a unique identifier name, and the other two columns are int type contain two reference values (start,stop(genomic location reference values). **maybe I should import this as dictionary list** filetype(2) The other file contains signal data in three columns, column one is a unique identifier type int, and the other two columns contain two type int values (genomic location reference values) ** import this as array/list I want to map the location of filetype(2) with respect to filetype(1) and be able to do averaging of signal if I align all filetype one objects. Thanks -- View this message in context: http://www.nabble.com/import-data-%28txt-csv%29-into-list-array-and-manipulation-tp20424075p20424075.html Sent from the Python - tutor mailing list archive at Nabble.com. From timmichelsen at gmx-topmail.de Mon Nov 10 23:58:13 2008 From: timmichelsen at gmx-topmail.de (Tim Michelsen) Date: Mon, 10 Nov 2008 23:58:13 +0100 Subject: [Tutor] import data (txt/csv) into list/array and manipulation In-Reply-To: <20424075.post@talk.nabble.com> References: <20424075.post@talk.nabble.com> Message-ID: > filetype(2) The other file contains signal data in three columns, column one > is a unique identifier type int, and the other two columns contain two type > int values (genomic location reference values) > ** import this as array/list > > I want to map the location of filetype(2) with respect to filetype(1) and be > able to do averaging of signal if I align all filetype one objects. > > Thanks import numpy as np data = np.loadtxt('file.csv', dtype='|S10') col1 = date[0] col2 = date[1].astype(int) ... From kent37 at tds.net Tue Nov 11 00:36:42 2008 From: kent37 at tds.net (Kent Johnson) Date: Mon, 10 Nov 2008 18:36:42 -0500 Subject: [Tutor] import data (txt/csv) into list/array and manipulation In-Reply-To: <20424075.post@talk.nabble.com> References: <20424075.post@talk.nabble.com> Message-ID: <1c2a2c590811101536j63dd545ya6f002ece60fd230@mail.gmail.com> On Mon, Nov 10, 2008 at 12:12 PM, trias wrote: > I have started learning python (any online help content suggestions are > welcome) and want to write a couple of scripts to do simple numeric > calculations on array data. Welcome! Have you seen http://wiki.python.org/moin/BeginnersGuide/NonProgrammers > filetype(1) I have reference files (ie file.csv) that contain three columns > with variable rows, first column is type str contains a unique identifier > name, and the other two columns are int type contain two reference values > (start,stop(genomic location reference values). > **maybe I should import this as dictionary list** I don't know what a dictionary list is, do you mean a list of dictionaries? I think a list of lists is probably fine. Python comes with a csv module that helps to read csv files. Then you will have to convert the second two columns from string to int. > filetype(2) The other file contains signal data in three columns, column one > is a unique identifier type int, and the other two columns contain two type > int values (genomic location reference values) > ** import this as array/list > > I want to map the location of filetype(2) with respect to filetype(1) and be > able to do averaging of signal if I align all filetype one objects. I don't know what you mean by this. I guess you want to search within filetype(1) for intervals that contain the locations from filetype(2) ? This is pretty straightforward but if you have long lists it may be slow. This recent thread has some suggestions for speeding up searching large data sets: http://thread.gmane.org/gmane.comp.python.tutor/51162/focus=51181 It looks like you and Srinivas are trying to solve similar problems. Kent From t.gkikopoulos at dundee.ac.uk Tue Nov 11 09:41:28 2008 From: t.gkikopoulos at dundee.ac.uk (trias) Date: Tue, 11 Nov 2008 00:41:28 -0800 (PST) Subject: [Tutor] import data (txt/csv) into list/array and manipulation In-Reply-To: <1c2a2c590811101536j63dd545ya6f002ece60fd230@mail.gmail.com> References: <20424075.post@talk.nabble.com> <1c2a2c590811101536j63dd545ya6f002ece60fd230@mail.gmail.com> Message-ID: <20435477.post@talk.nabble.com> Hi all, Thanks so much for the help, I will have a look at the suggestions as well as the other thread,links this week and should post here when I have tried them/need more help. Thanks -- View this message in context: http://www.nabble.com/import-data-%28txt-csv%29-into-list-array-and-manipulation-tp20424075p20435477.html Sent from the Python - tutor mailing list archive at Nabble.com. From denis.spir at free.fr Tue Nov 11 13:40:27 2008 From: denis.spir at free.fr (spir) Date: Tue, 11 Nov 2008 13:40:27 +0100 Subject: [Tutor] import data (txt/csv) into list/array and manipulation In-Reply-To: <49195422020000B300000F07@gw-out.dundee.ac.uk> References: <49195422020000B300000F07@gw-out.dundee.ac.uk> Message-ID: <49197D3B.5030504@free.fr> Triantafyllos Gkikopoulos a ?crit : > Hi, > > Thanks for the advice, > > I will do some more reading this week and look into your solution as > well as others. > > So basicaly my data is enrichement signal on yeast genomic locations, > and want to map this signal in respect to genes, and the averagomg > question is so that I can averga signal if I align all the signal based > on the start of every gene. > I guess another solution is to create an array with zeros that covers > then entire genome and then I replace the zeros with actual signal (int) > values, then I be able to call for individual locations within this > array and maybe easier to do the averaging as well based on the > reference file. There are numerous solutions for any problem. This one would be especially non-pythonic, I guess ;-) If I understand your problem: * Locations are gene ids. * They are key fields for your data -- strings and ints are not keys. * There can be several data items for a unique id. * Among the possible data, integers have to be processed (averaged). * What about string? If you want to be both pythonic and simple, as I see it, use a dict with locations as keys. Now, the data seems to be mainly a list of ints. Right? So, use a list for this, and add to it the relevant storing fields for additional data (strings?), and the relevant method to average your integers. Example: class GeneData(list): ''' holds int values in basic list calculates average value stores additional string data ''' def store_strings(self,strings): self.strings = strings def store_string(self,string): self.strings.append(string) def average(self): # record and/or return average, eg: sum = 0.0 for i in self: sum += i self.avrg = sum/len(self) return self.avrg gd = GeneData([1,2,3]) gd.append(4), gd.append(5) x = gd.pop() gd.store_strings(["string","data"]) gd.store_string("i'm relevant info") print gd, gd.strings print "average: %2.2f ; removed: %i" %(gd.average(), x) ==> [1, 2, 3, 4] ['string', 'data', "i'm relevant info"] average: 2.5 ; removed: 5 denis > cheers > > Dr Triantafyllos Gkikopoulos >>>> spir 11/10/08 7:55 PM >>> > trias a ?crit : > > Hi, > > > > I have started learning python (any online help content suggestions > are > > welcome) and want to write a couple of scripts to do simple numeric > > calculations on array data. > > > > filetype(1) I have reference files (ie file.csv) that contain three > columns > > with variable rows, first column is type str contains a unique > identifier > > name, and the other two columns are int type contain two reference > values > > (start,stop(genomic location reference values). > > **maybe I should import this as dictionary list** > > > > filetype(2) The other file contains signal data in three columns, > column one > > is a unique identifier type int, and the other two columns contain > two type > > int values (genomic location reference values) > > ** import this as array/list > > For both files, field 1 contains an id. So that using a dictionary seems > > appropriate. You may use a format like: > {id:(start,stop)} > Location could also be stored in a custom type, especially if you need > to > compare location (which is probably the case). Example (not tested): > class Location(object): > def __init__(self, start, stop): > delf.start = start > self.stop = stop > def __eq__(self, other): > return (self.start==other.start) and > (self.stop==other.stop) > The second method will be called when you test loc1==loc2 and will > return True > iif both positions are equal. > This custom type allows you to define other methods that be relevant for > your > problem. > > I want to map the location of filetype(2) with respect to > filetype(1)... > > Here is the problem reversed: if the location is to be used as link > between > tables, then it should be the key of both tables: > {location:id} > Fortunately, your location is a simple enough set of data to be stored > as a > (start,stop) tuple, so that you can actually use it as dict key (a > dict's key > must be of an immutable type). > Now, the question is: do you have multiple occurences of the same > location. If > yes, you will have to agglomerate the data in eg a list: > {location:[d1,d2,...]} > But, maybe I don't properly undestand what you have to do (see Q below). > > ...and be > able to do averaging of signal if I align all filetype one objects. > > Where/what are the data fields in your pattern? > > Denis > > > Thanks > > > > > The University of Dundee is a registered Scottish charity, No: SC015096 > > From bermanrl at embarqmail.com Wed Nov 12 15:50:14 2008 From: bermanrl at embarqmail.com (Robert Berman) Date: Wed, 12 Nov 2008 09:50:14 -0500 Subject: [Tutor] A tutorial for Python and QT4 Message-ID: <491AED26.5090801@embarqmail.com> An HTML attachment was scrubbed... URL: From ycbh7f302 at sneakemail.com Wed Nov 12 17:27:17 2008 From: ycbh7f302 at sneakemail.com (ycbh7f302 at sneakemail.com) Date: 12 Nov 2008 16:27:17 -0000 Subject: [Tutor] Running a script from another folder Message-ID: <2391-41291@sneakemail.com> Suppose I have a python script in /usr1/myID/bin and I want to run it from another folder. If I enter python ~myID/bin/myscript that works. Is there a way to get by with python myscript or even myscript.py I've tried specifying the PYTHONPATH environmental variable but it seems to be used only for importing modules. From srilyk at gmail.com Wed Nov 12 18:21:55 2008 From: srilyk at gmail.com (W W) Date: Wed, 12 Nov 2008 11:21:55 -0600 Subject: [Tutor] Running a script from another folder In-Reply-To: <2391-41291@sneakemail.com> References: <2391-41291@sneakemail.com> Message-ID: <333efb450811120921o1ab8a06buff27e05f510f1fdc@mail.gmail.com> On Wed, Nov 12, 2008 at 10:27 AM, wrote: > Suppose I have a python script in /usr1/myID/bin and I want to run it from > another folder. If I enter > > python ~myID/bin/myscript > > that works. Is there a way to get by with > > python myscript > > or even > > myscript.py > > I've tried specifying the PYTHONPATH > environmental variable but it seems to be used only for importing modules it looks like you're on linux - so at the beginning of your script put #!/usr/bin/env python (I believe) and then chmod +x myscript.py then you can call it from the command line. Alternatively you could create a shell script that would execute it with python. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From greg at thewhittiers.com Wed Nov 12 18:58:01 2008 From: greg at thewhittiers.com (greg whittier) Date: Wed, 12 Nov 2008 12:58:01 -0500 Subject: [Tutor] Running a script from another folder In-Reply-To: <333efb450811120921o1ab8a06buff27e05f510f1fdc@mail.gmail.com> References: <2391-41291@sneakemail.com> <333efb450811120921o1ab8a06buff27e05f510f1fdc@mail.gmail.com> Message-ID: > it looks like you're on linux - so at the beginning of your script put > #!/usr/bin/env python (I believe) and then chmod +x myscript.py > > then you can call it from the command line. > You'll also need to make sure ~myID/bin is in your PATH. From sinhvuhoang at yahoo.com Wed Nov 12 16:35:01 2008 From: sinhvuhoang at yahoo.com (iSinhCanon) Date: Wed, 12 Nov 2008 07:35:01 -0800 (PST) Subject: [Tutor] Python and Abaqus Message-ID: <452123.29963.qm@web53903.mail.re2.yahoo.com> It would be simply if you can use Python to explorer your file .odb for yours databases for exemples: displacements and stresses at node etc... I have a lot of exemples by using Python for file .odb, if you want i can send it to you. Sinh. Hello folks, This is something that must have been asked several times. I want to post process data obtained after running a FEM in ABAQUS. The requested results are usually printed to the .dat file or .rpt file. I would like to learn how to extract the information that I need (i.e. displacements and stresses at the nodes) from this file using Python. The fact is that I am kind of new at ABAQUS and have zero knowledge about Python. Therefore, any help with websites, examples, tutorials, etc. would be appreciated. Thank you! Andres -------------- next part -------------- An HTML attachment was scrubbed... URL: From Shawn at milochik.com Wed Nov 12 20:35:30 2008 From: Shawn at milochik.com (Shawn Milochik) Date: Wed, 12 Nov 2008 14:35:30 -0500 Subject: [Tutor] Running a script from another folder In-Reply-To: References: <2391-41291@sneakemail.com> <333efb450811120921o1ab8a06buff27e05f510f1fdc@mail.gmail.com> Message-ID: <2dc0c81b0811121135s770b6dbel19f87ca772581e42@mail.gmail.com> On Wed, Nov 12, 2008 at 12:58 PM, greg whittier wrote: >> it looks like you're on linux - so at the beginning of your script put >> #!/usr/bin/env python (I believe) and then chmod +x myscript.py >> >> then you can call it from the command line. >> > > You'll also need to make sure ~myID/bin is in your PATH. > _ This is the answer, assuming you have the shebang line and executable flags mentioned above. Method (assuming you are using bash): Add this to your .bashrc file in your home directory: export PATH=$PATH:${HOME}/bin I used ${HOME} instead of ~ to make this more portable. However, if your system doesn't work that way, use the ~ or the full path. From emile at fenx.com Wed Nov 12 21:20:25 2008 From: emile at fenx.com (Emile van Sebille) Date: Wed, 12 Nov 2008 12:20:25 -0800 Subject: [Tutor] get a module's own (top_level) dict? In-Reply-To: <4916BCBD.8080300@free.fr> References: <4916BCBD.8080300@free.fr> Message-ID: spir wrote: > Hello pyhonistas, > > Example: > === module content === > a = 1 > b = 2 > ====================== > > I'm looking for a way to get something like {'a':a, b':2}. Maybe this will get you started: [root at vsds2 root]# cat > testmod.py a=1 b=2 [root at vsds2 root]# python Python 2.5 (r25:51908, Nov 1 2006, 15:36:22) [GCC 2.96 20000731 (Red Hat Linux 7.1 2.96-98)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import testmod >>> dir(testmod) ['__builtins__', '__doc__', '__file__', '__name__', 'a', 'b'] >>> D=dict([(varname,getattr(testmod,varname)) for varname in dir(testmod) if not varname.startswith("_") ]) >>> D {'a': 1, 'b': 2} >>> HTH, Emile > Actually, > names defind in the module will be instances of a custom type. I want to > give them an attribute that holds their own name. E.g.: > for key,obj in dict: > obj.name = key > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From juryef at yahoo.com Wed Nov 12 23:34:03 2008 From: juryef at yahoo.com (Judith Flores) Date: Wed, 12 Nov 2008 14:34:03 -0800 (PST) Subject: [Tutor] Documentation on how to run complete R scripts from Python interpreter Message-ID: <99331.36231.qm@web34707.mail.mud.yahoo.com> Hello, I am very new to Python and I have long R scripts that I would like to run under the Python Interpreter. The reason for this is because I will try to construct a GUI using 'easygui' in Python. I read some of the the documentation regarding the RPy module, but it implies to add a 'r' at the beginning of every R function, plus the dot to underscore conversion in the names of the R functions. Or maybe, what I am intending to do is not possible? I originally built a GUI using Rtcltk, but easygui honors its name, and I need to add some text manipulation also, which is much more intuitive to do in Python than R. This is a diagram of what I would like to do: GUI constructed with "easygui" --> this will retrieve pathfiles and user's preferences (floating numbers and strings) --> The preceeding attributes will feed the R scripts-->R scripts will generate pdf files with plots. All this within the Python Interpreter, although I am suspecting that like the name indicates, this is only a 'Python' interpreter, nothing else... If you could orient me to where I can find documentation on what I would like to do, I would appreciate it very much. Thank you, Judith From alan.gauld at btinternet.com Thu Nov 13 00:07:28 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 12 Nov 2008 23:07:28 -0000 Subject: [Tutor] Documentation on how to run complete R scripts from Pythoninterpreter References: <99331.36231.qm@web34707.mail.mud.yahoo.com> Message-ID: "Judith Flores" wrote > I am very new to Python and I have long R scripts that I > would like to run under the Python Interpreter. I'm sorry I can't help for reasons that will become apparent. But I'd like to thank you for pointing me at R! I've just bought a commercial statistics package(Minitab) which cost me over $150, and it looks as if R could have done all I needed for free - or maybe the cost of a book... > some of the the documentation regarding the RPy module, I haven't read anything about RPy so can't help there (yet) but it did lead me to the R web site. > GUI constructed with "easygui" --> this will retrieve pathfiles > and user's preferences (floating numbers and strings) > --> The preceeding attributes will feed the R scripts-->R scripts > will generate pdf files with plots. It sounds like you could do this by just creating the scripts in vanilla Python then running the R scripts under R itself from Python usiing os.system or the Subprocess module. Once I've investigated R and RPy a bit more I might be able to help, but that will be a whjile... I hope someone else can shed some light meantime. Thanks again, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From kent37 at tds.net Thu Nov 13 00:44:38 2008 From: kent37 at tds.net (Kent Johnson) Date: Wed, 12 Nov 2008 18:44:38 -0500 Subject: [Tutor] Documentation on how to run complete R scripts from Pythoninterpreter In-Reply-To: References: <99331.36231.qm@web34707.mail.mud.yahoo.com> Message-ID: <1c2a2c590811121544y59725df6q56d4e042c769fcd1@mail.gmail.com> On Wed, Nov 12, 2008 at 6:07 PM, Alan Gauld wrote: > "Judith Flores" wrote >> >> I am very new to Python and I have long R scripts that I would like to >> run under the Python Interpreter. > But I'd like to thank you for pointing me at R! R is very powerful. I found it a bit opaque at first. You will probably want a book :-) You might be interested in these notes, which basically tell how to use R to do first-semester college statistics: http://personalpages.tds.net/~kent37/stories/00019.html >> some of the the documentation regarding the RPy module, I have not had any luck with RPy myself though presumably others have more success. The r() function might let you execute your scripts: http://rpy.sourceforge.net/rpy/doc/rpy_html/Miscellaneous.html#Miscellaneous > It sounds like you could do this by just creating the scripts in vanilla > Python then running the R scripts under R itself from Python usiing > os.system or the Subprocess module. I think that is probably the easiest approach if you can pass the script parameters on the command line. Kent From timothy.grant at gmail.com Thu Nov 13 02:00:24 2008 From: timothy.grant at gmail.com (Timothy Grant) Date: Wed, 12 Nov 2008 17:00:24 -0800 Subject: [Tutor] A tutorial for Python and QT4 In-Reply-To: <491AED26.5090801@embarqmail.com> References: <491AED26.5090801@embarqmail.com> Message-ID: On Wed, Nov 12, 2008 at 6:50 AM, Robert Berman wrote: > Hi, > > I am looking for a tutorial teaching how to use QT4 Designer with Python. > There are a number of very good tutorials for QT3, but I do not want to drop > back from QT4.I have no problem designing the form(s) using QT4 designer; > including signals and slots; but......I am not even certain why the form has > to be saved as a .ui file rather than a .frm file. I have no idea how to > generate the python shells I can use to fill in the code for my defined > events and the lack of a really good tutorial or two is certainly placing > me under a real handicap. > > Any pointers, literally, to some tutorials would be most appreciated. > > I am using Linux (ubuntu -- 8.10) with Eric as my editor. > > Thanks, > > Robert > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > It's been a long time since I played with Qt, but I firmly believe you need to learn how to code the GUI first before you start playing with the tools that will code the GUI for you. You'll have a much stronger understanding of how things work and fit together if you know how to code it all. -- Stand Fast, tjg. [Timothy Grant] From greg at thewhittiers.com Thu Nov 13 04:03:52 2008 From: greg at thewhittiers.com (greg whittier) Date: Wed, 12 Nov 2008 22:03:52 -0500 Subject: [Tutor] experience/opinions with deploying python GUI app to Linux, Win32, and Mac OS X Message-ID: Hi gang, I know this is probably like asking whether vi or emacs is better, but I'm looking for the best cross-platform (linux, windows, mac os x) user interface toolkit. Since the users won't be programmers, I'd like it to feel as much like a native app as possible in terms of installation. It should feel like installing any other mac/windows/linux application. I'm writing a very simple app to retrieve data from a device or import it from a file and then upload that data to a website (and possibly keep a local backup of the data using sqlite or similar). The main widget will be what in gtk would is called listview with a checkbox column for selecting which data to upload possibly as a panel within a wizard that would also have panels for selecting the device and logging into the web site. Deploying to the Mac seems to be the most difficult from what I've read. pygtk/glade seems natural for linux and even window, but 've read about difficulties with gtk on the mac, which at one point required installing X11, I believe. There's a "native" (no X11) port, but I'm not sure how mature that is. Here's what I've thought about with some pros/cons: - tkinter -- this is the obvious answer I suppose, but the widget set is limited and not pretty (out of the box at least) - pygtk -- not easy to deploy on mac? Non-native looking widgets - wxpython - complete widget set and native looking, but not sure if it's easy to deploy - jython/SWT -- I have no experience with this, but everybody has a JVM, so deploying should be easy - web app running locally -- no experience with this, but everybody has a web browser and there are frameworks like django I could use - curses -- probably not as pretty as mac/windows users would expect Any success stories out there? Thanks, Greg -------------- next part -------------- An HTML attachment was scrubbed... URL: From srilyk at gmail.com Thu Nov 13 04:31:11 2008 From: srilyk at gmail.com (W W) Date: Wed, 12 Nov 2008 21:31:11 -0600 Subject: [Tutor] experience/opinions with deploying python GUI app to Linux, Win32, and Mac OS X In-Reply-To: References: Message-ID: <333efb450811121931q6bb7e71alcd1be88873e159cd@mail.gmail.com> On Wed, Nov 12, 2008 at 9:03 PM, greg whittier wrote: > - web app running locally -- no experience with this, but everybody > has a web browser and there are frameworks like django I could use > - curses -- probably not as pretty as mac/windows users would expect > I'd probably roll with the web-app, especially if you're worried about it looking "native". GTK can look like windows, but you mentioned difficulty on macs. Of course I've never had my GTK apps /really/ look native on windows. For the reason you mentioned, I probably wouldn't use curses, unless you're not worried about it looking particularly "pretty". However, with some type of web framework, you can easily make it look the same cross-platform, with minimal maintenance and customizing (mainly only required if you use CSS and any client runs IE). Anyhow, that's just my 2? -Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Thu Nov 13 09:10:48 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 13 Nov 2008 08:10:48 -0000 Subject: [Tutor] experience/opinions with deploying python GUI app to Linux, Win32, and Mac OS X References: Message-ID: "greg whittier" wrote > Deploying to the Mac seems to be the most difficult from what I've > read. That's probably true in that for a truly native experience you need to pay a lot of attention to Apple's guidelines and use some kind of tool to produce the correct bundle of files etc. > - tkinter -- this is the obvious answer I suppose, but the widget > set is > limited and not pretty (out of the box at least) > - pygtk -- not easy to deploy on mac? Non-native looking widgets Neither is "pretty" IMHO. Tkinter is easy to deploy though. > - wxpython - complete widget set and native looking, but not sure if > it's > easy to deploy I'm not aware of any deployment issues beyond getting all the right files installed. > - jython/SWT -- I have no experience with this, but everybody has a > JVM, so > deploying should be easy Of the client GUI options this is probably the easiest, but also probably the hardest to use. > - web app running locally -- no experience with this, but everybody > has a > web browser and there are frameworks like django I could use This could work but has the disadvantage of being limited in functionality compared to other GUIIs. It will not look like a native GUI app it will look like a web site. For your project it is almost certainly adequate however and fairly easy to deploy. It is almost certainly the most portable in look. It also has the advantage of being most resource hungry on the client machine - a web server plus your app plus a browser. > - curses -- probably not as pretty as mac/windows users would expect curses on Windows is a big risk, none of the DOS ports of curses that I've found have been complete or totally reliable. Personally, for cross platform I'd tend to go for wxPython. Users get the look n feel they expect and the functionality is rich. Deployment is no more difficult that Tkinter/Gtk, Qt or any other GUI framework so far as I know. But this is based on very limited real experience. I use all 3 platforms but porting a personal app for own use is very different to building something for real-world deployment! HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From denis.spir at free.fr Thu Nov 13 14:13:00 2008 From: denis.spir at free.fr (spir) Date: Thu, 13 Nov 2008 14:13:00 +0100 Subject: [Tutor] experience/opinions with deploying python GUI app to Linux, Win32, and Mac OS X In-Reply-To: References: Message-ID: <491C27DC.50005@free.fr> You may have a look at easygui. Probably not for final release, rather for design stage. It's based on tkinter I guess. I found it very helpful as long as the app does not require sophisticated widgets and there is a proper separation of process and UI. Once everything works, it is fast enough to port the UI to any other GUI package, if needed. http://easygui.sourceforge.net/ denis Alan Gauld a ?crit : > > "greg whittier" wrote > >> Deploying to the Mac seems to be the most difficult from what I've read. > > That's probably true in that for a truly native experience you > need to pay a lot of attention to Apple's guidelines and use > some kind of tool to produce the correct bundle of files etc. > >> - tkinter -- this is the obvious answer I suppose, but the widget set is >> limited and not pretty (out of the box at least) >> - pygtk -- not easy to deploy on mac? Non-native looking widgets > > Neither is "pretty" IMHO. Tkinter is easy to deploy though. > >> - wxpython - complete widget set and native looking, but not sure if it's >> easy to deploy > > I'm not aware of any deployment issues beyond getting > all the right files installed. > >> - jython/SWT -- I have no experience with this, but everybody has a >> JVM, so >> deploying should be easy > > Of the client GUI options this is probably the easiest, but > also probably the hardest to use. > >> - web app running locally -- no experience with this, but everybody has a >> web browser and there are frameworks like django I could use > > This could work but has the disadvantage of being limited > in functionality compared to other GUIIs. It will not look like > a native GUI app it will look like a web site. For your project > it is almost certainly adequate however and fairly easy to > deploy. It is almost certainly the most portable in look. > It also has the advantage of being most resource hungry > on the client machine - a web server plus your app plus > a browser. > >> - curses -- probably not as pretty as mac/windows users would expect > > curses on Windows is a big risk, none of the DOS ports of > curses that I've found have been complete or totally reliable. > > Personally, for cross platform I'd tend to go for wxPython. > Users get the look n feel they expect and the functionality is rich. > Deployment is no more difficult that Tkinter/Gtk, Qt or > any other GUI framework so far as I know. > > > But this is based on very limited real experience. I use > all 3 platforms but porting a personal app for own use > is very different to building something for real-world > deployment! > > HTH, > > From jeff at dcsoftware.com Thu Nov 13 14:39:48 2008 From: jeff at dcsoftware.com (Jeff Johnson) Date: Thu, 13 Nov 2008 06:39:48 -0700 Subject: [Tutor] experience/opinions with deploying python GUI app to Linux, Win32, and Mac OS X In-Reply-To: References: Message-ID: <491C2E24.4040000@dcsoftware.com> Check out Dabo. It is a framework that wraps wxpython and is developed on the mac and is deployed on mac, windows and linux. It has great features like an app builder to get you up and running quickly. http://dabodev.com/ And for the email list: http://leafe.com/mailman/listinfo/dabo-users -- Jeff Jeff Johnson jeff at dcsoftware.com Phoenix Python User Group - sunpiggies at googlegroups.com greg whittier wrote: > Hi gang, > > I know this is probably like asking whether vi or emacs is better, but > I'm looking for the best cross-platform (linux, windows, mac os x) user > interface toolkit. Since the users won't be programmers, I'd like it to > feel as much like a native app as possible in terms of installation. It > should feel like installing any other mac/windows/linux application. > > I'm writing a very simple app to retrieve data from a device or import > it from a file and then upload that data to a website (and possibly keep > a local backup of the data using sqlite or similar). The main widget > will be what in gtk would is called listview with a checkbox column for > selecting which data to upload possibly as a panel within a wizard that > would also have panels for selecting the device and logging into the web > site. > > Deploying to the Mac seems to be the most difficult from what I've > read. pygtk/glade seems natural for linux and even window, but 've read > about difficulties with gtk on the mac, which at one point required > installing X11, I believe. There's a "native" (no X11) port, but I'm > not sure how mature that is. > > Here's what I've thought about with some pros/cons: > > - tkinter -- this is the obvious answer I suppose, but the widget set is > limited and not pretty (out of the box at least) > - pygtk -- not easy to deploy on mac? Non-native looking widgets > - wxpython - complete widget set and native looking, but not sure if > it's easy to deploy > - jython/SWT -- I have no experience with this, but everybody has a JVM, > so deploying should be easy > - web app running locally -- no experience with this, but everybody has > a web browser and there are frameworks like django I could use > - curses -- probably not as pretty as mac/windows users would expect > > Any success stories out there? > > Thanks, > Greg > > From greg at thewhittiers.com Thu Nov 13 15:05:56 2008 From: greg at thewhittiers.com (greg whittier) Date: Thu, 13 Nov 2008 09:05:56 -0500 Subject: [Tutor] experience/opinions with deploying python GUI app to Linux, Win32, and Mac OS X In-Reply-To: References: Message-ID: Thanks for all the great replies! You've reaffirmed my #1 and #2 seeds -- wxpython and a web app. I haven't really found any show stoppers for wxpython, but I guess I was unnecessarily suspicious. dabodev.com looks like it targets my problem so that's something I'll definitely look at. I had one question about this response. On Thu, Nov 13, 2008 at 3:10 AM, Alan Gauld wrote: >> - jython/SWT -- I have no experience with this, but everybody has a JVM, >> so deploying should be easy > > Of the client GUI options this is probably the easiest, but > also probably the hardest to use. Does "probably the easiest" mean "probably the easiest to develop?" Thanks again, Greg From pablo.englebienne at gmail.com Thu Nov 13 14:11:39 2008 From: pablo.englebienne at gmail.com (Pablo Englebienne) Date: Thu, 13 Nov 2008 08:11:39 -0500 Subject: [Tutor] Dictionary of dictionaries issue Message-ID: Hi, I'm trying to work with a dictionary of dictionaries and I'm having trouble accessing a specific element of it: $ python Python 2.6 (trunk:66714:66715M, Oct 1 2008, 18:36:04) [GCC 4.0.1 (Apple Computer, Inc. build 5370)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> r = ('a','b','c') >>> c = (1,2,3) >>> d = dict.fromkeys(r,dict.fromkeys(c)) >>> d {'a': {1: None, 2: None, 3: None}, 'c': {1: None, 2: None, 3: None}, 'b': {1: None, 2: None, 3: None}} >>> d['a'][1]=0 >>> d {'a': {1: 0, 2: None, 3: None}, 'c': {1: 0, 2: None, 3: None}, 'b': {1: 0, 2: None, 3: None}} >>> import copy As you can see, attempting to assign a specific member, d['a'][1] updates all values in d[*][1], not what I intended. I thought the solution could be in using copy.deepcopy, but I might not be using it right: >>> d2 = dict.fromkeys(r,copy.deepcopy(dict.fromkeys(c))) >>> d2 {'a': {1: None, 2: None, 3: None}, 'c': {1: None, 2: None, 3: None}, 'b': {1: None, 2: None, 3: None}} >>> d2['a'][1]=0 >>> d2 {'a': {1: 0, 2: None, 3: None}, 'c': {1: 0, 2: None, 3: None}, 'b': {1: 0, 2: None, 3: None}} Any suggestions/pointers would be appreciated! -- Pablo Englebienne pablo.englebienne at gmail.com From a.t.hofkamp at tue.nl Thu Nov 13 16:01:14 2008 From: a.t.hofkamp at tue.nl (A.T.Hofkamp) Date: Thu, 13 Nov 2008 16:01:14 +0100 Subject: [Tutor] Dictionary of dictionaries issue In-Reply-To: References: Message-ID: <491C413A.3050603@tue.nl> Pablo Englebienne wrote: > Hi, I'm trying to work with a dictionary of dictionaries and I'm having > trouble accessing a specific element of it: > > $ python > Python 2.6 (trunk:66714:66715M, Oct 1 2008, 18:36:04) > [GCC 4.0.1 (Apple Computer, Inc. build 5370)] on darwin > Type "help", "copyright", "credits" or "license" for more information. > >>> r = ('a','b','c') > >>> c = (1,2,3) > >>> d = dict.fromkeys(r,dict.fromkeys(c)) > >>> d This does d0 = dict.fromkeys(c) d = dict.fromkeys(r, d0) > {'a': {1: None, 2: None, 3: None}, 'c': {1: None, 2: None, 3: None}, > 'b': {1: None, 2: None, 3: None}} > >>> d['a'][1]=0 > >>> d > {'a': {1: 0, 2: None, 3: None}, 'c': {1: 0, 2: None, 3: None}, 'b': {1: > 0, 2: None, 3: None}} > >>> import copy > > As you can see, attempting to assign a specific member, d['a'][1] > updates all values in d[*][1], not what I intended. The d0 value is shared between all keys of d. As a result, you get the behaviour you noticed. (ie there is only 1 dict-value, it gets printed 3 times when you print 'd') > I thought the solution could be in using copy.deepcopy, but I might not > be using it right: > > >>> d2 = dict.fromkeys(r,copy.deepcopy(dict.fromkeys(c))) Here you do d0 = dict.fromkeys(c) d1 = copy.deepcopy(d0) d2 = dict.fromkeys(r, d1) d0 and d1 are completely seperate due to the deepcopy(), but the last line still uses the same d1 value for all its keys, as in your first attempt. for this reason, the problem does not disappear. > Any suggestions/pointers would be appreciated! To solve this, you need to construct a fresh value for each key. You can do this with an iterator and a dictionary constructor: >>> c = (1,2,3) >>> r = ('a','b','c') >>> d3 = dict(( (rv, dict.fromkeys(c)) for rv in r )) d3 is created by constructing a dict from a list of tuples (key, val), where the key rv is from your 'r' tuple, and val is constructed anew each time from 'c'. >>> d3 {'a': {1: None, 2: None, 3: None}, 'c': {1: None, 2: None, 3: None}, 'b': {1: None, 2: None, 3: None}} >>> d3['a'][1]=0 >>> d3 {'a': {1: 0, 2: None, 3: None}, 'c': {1: None, 2: None, 3: None}, 'b': {1: None, 2: None, 3: None}} Sincerely, Albert From kent37 at tds.net Thu Nov 13 16:24:27 2008 From: kent37 at tds.net (Kent Johnson) Date: Thu, 13 Nov 2008 10:24:27 -0500 Subject: [Tutor] Dictionary of dictionaries issue In-Reply-To: References: Message-ID: <1c2a2c590811130724o698d820bg59e0620d58c2368b@mail.gmail.com> On Thu, Nov 13, 2008 at 8:11 AM, Pablo Englebienne wrote: > Hi, I'm trying to work with a dictionary of dictionaries and I'm having > trouble accessing a specific element of it: > > $ python > Python 2.6 (trunk:66714:66715M, Oct 1 2008, 18:36:04) > [GCC 4.0.1 (Apple Computer, Inc. build 5370)] on darwin > Type "help", "copyright", "credits" or "license" for more information. >>>> r = ('a','b','c') >>>> c = (1,2,3) >>>> d = dict.fromkeys(r,dict.fromkeys(c)) >>>> d > {'a': {1: None, 2: None, 3: None}, 'c': {1: None, 2: None, 3: None}, 'b': > {1: None, 2: None, 3: None}} >>>> d['a'][1]=0 >>>> d > {'a': {1: 0, 2: None, 3: None}, 'c': {1: 0, 2: None, 3: None}, 'b': {1: 0, > 2: None, 3: None}} >>>> import copy > > As you can see, attempting to assign a specific member, d['a'][1] updates > all values in d[*][1], not what I intended. > > I thought the solution could be in using copy.deepcopy, The problem is, whether you use deepcopy() or not, the values of d are all the same - every key of d refers to the same value, which is your nested dict. So when you change it in one place, it changes everywhere. dict.fromkeys() is not going to work for this, because it always will give the same value for each key. You need to create a new dict for each value. One solution is just to use a loop, creating a new value dict each time through the loop: In [3]: r = ('a','b','c') In [4]: c = (1,2,3) In [5]: d = {} In [6]: for k in r: ...: d[k] = dict.fromkeys(c) In [7]: d Out[7]: {'a': {1: None, 2: None, 3: None}, 'b': {1: None, 2: None, 3: None}, 'c': {1: None, 2: None, 3: None}} In [8]: d['a'][1] = 0 In [9]: d Out[9]: {'a': {1: 0, 2: None, 3: None}, 'b': {1: None, 2: None, 3: None}, 'c': {1: None, 2: None, 3: None}} You could also create a sequence of (key, value) pairs as Albert suggests. Kent From kent37 at tds.net Thu Nov 13 16:26:38 2008 From: kent37 at tds.net (Kent Johnson) Date: Thu, 13 Nov 2008 10:26:38 -0500 Subject: [Tutor] Dictionary of dictionaries issue In-Reply-To: <491C413A.3050603@tue.nl> References: <491C413A.3050603@tue.nl> Message-ID: <1c2a2c590811130726j3ec39faeoda6acaec66d9b641@mail.gmail.com> On Thu, Nov 13, 2008 at 10:01 AM, A.T.Hofkamp wrote: >>>> d3 = dict(( (rv, dict.fromkeys(c)) for rv in r )) You don't need the double parentheses, this works just as well: d3 = dict( (rv, dict.fromkeys(c)) for rv in r ) A generator expression just has to be in parentheses, it's OK if the parens also have other meaning syntactically; in this case indicating a function call. Kent From t.gkikopoulos at dundee.ac.uk Thu Nov 13 15:50:20 2008 From: t.gkikopoulos at dundee.ac.uk (trias) Date: Thu, 13 Nov 2008 06:50:20 -0800 (PST) Subject: [Tutor] import data (txt/csv) into list/array and manipulation In-Reply-To: <20435477.post@talk.nabble.com> References: <20424075.post@talk.nabble.com> <1c2a2c590811101536j63dd545ya6f002ece60fd230@mail.gmail.com> <20435477.post@talk.nabble.com> Message-ID: <20481629.post@talk.nabble.com> Hi again, I got a bit better in python the last few days, but looking at some codes it almost looks impossible to catch up. but definitely want to fight it, looks well worth the effort, plus it probably works exponentially :) I read a little bit about the interval/segment trees, and it looks that their efficiency lies in the efficiency of the algorithms associated with the lookup/indexing modules. Now although I am too newbie to be able to implement the code from the bx-python guys (quicksect.py) understand some basics, disecting a list of objects str,int(start),int(end) on a median basis and store information on the nodes etc Assuming I get this to work some time, and I get back a list of intervals of interest. I would like to use these intervals (str,int,int) to search in a file that contains a fixed step range, where its int in that range is associated with an int(value) (probably best format this file as a dictionary=signaldict) to call all keys within range(interval) and plot values. I think it would be better to print these values in another array, so that I can then say sum the values from all the intervals for each step in the range (assuming I have exported a fixed length of keys from the signaldict) and plot in a graph Well don't mean to have the problem solved for me, but if you fancy to contribute with any kind of help you are welcome cheers PS I could maybe upload a couple of small example flies or a schematic to see what I mean -- View this message in context: http://www.nabble.com/import-data-%28txt-csv%29-into-list-array-and-manipulation-tp20424075p20481629.html Sent from the Python - tutor mailing list archive at Nabble.com. From mail at timgolden.me.uk Thu Nov 13 16:34:50 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 13 Nov 2008 15:34:50 +0000 Subject: [Tutor] Dictionary of dictionaries issue In-Reply-To: <1c2a2c590811130726j3ec39faeoda6acaec66d9b641@mail.gmail.com> References: <491C413A.3050603@tue.nl> <1c2a2c590811130726j3ec39faeoda6acaec66d9b641@mail.gmail.com> Message-ID: <491C491A.2010303@timgolden.me.uk> Kent Johnson wrote: > On Thu, Nov 13, 2008 at 10:01 AM, A.T.Hofkamp wrote: >>>>> d3 = dict(( (rv, dict.fromkeys(c)) for rv in r )) > > You don't need the double parentheses, this works just as well: > d3 = dict( (rv, dict.fromkeys(c)) for rv in r ) > > A generator expression just has to be in parentheses, it's OK if the > parens also have other meaning syntactically; in this case indicating > a function call. ... as long as it's the only argument to the function call. Otherwise you'll get a syntax error[*]. But you'll find this out pretty quickly when you try anyway! I realise that, strictly speaking, Kent's explanation already says this if you read "in parentheses" as meaning "the only thing in paren..." but just in case :) TJG >>> sum (x*x for x in range (10), 5) File "", line 1 SyntaxError: Generator expression must be parenthesized if not sole argument >>> >>> From jojo.mwebaze at gmail.com Thu Nov 13 16:56:12 2008 From: jojo.mwebaze at gmail.com (Jojo Mwebaze) Date: Thu, 13 Nov 2008 16:56:12 +0100 Subject: [Tutor] Classes and Databases Message-ID: <3124be320811130756p2dac86d9y8d591e583df7abd0@mail.gmail.com> Hello There, I would like store python classes in a database and then execute these classes from the database? Scientists do always want apply their own algorithms at the same time we want to keep this information. (knowing which class is responsible for which data) Because we have very many such cases, we can not incorporate such adhoc changes in the system.. we are thinking of storing such classes in the database and have classes run from the database. if anyone else feels they need to use someone's algorithm, they can run it/or extract it from the database and run on it on their data. Sorry for the long story! Any ideas will he highly appreciated. Johnson -------------- next part -------------- An HTML attachment was scrubbed... URL: From yoj11 at pitt.edu Thu Nov 13 17:12:42 2008 From: yoj11 at pitt.edu (Jiang, Yonghua) Date: Thu, 13 Nov 2008 11:12:42 -0500 Subject: [Tutor] cx_Oracle import problem in CGI Message-ID: <228A3B00817BCB4184DE05923F1986734AEB57DC27@PITT-EXCH-06.univ.pitt.edu> Dear Tutor, Although several posts discussed how to solve the problem about cx_Oralce import, I struggled with that for quite long time without success. Following is the code I wrote: ############################################# #!/opt/bin/python import cgi import sys import os os.environ['ORACLE_HOME']='/opt/local/sources/packages/oracle/product/8.1.7' if os.environ.has_key('LD_LIBRARY_PATH'): ld_library_path=os.environ['LD_LIBRARY_PATH'] os.environ['LD_LIBRARY_PATH']='%s/lib:%s' %(os.environ['ORACLE_HOME'],ld_library_path) try: import cx_Oracle except Exception,e: print ''' this is a test ''' print str(e) print sys.path print os.environ print ''' ''' The result shows as following: ld.so.1: python: fatal: libclntsh.so.8.0: open failed: No such file or directory '/home/----/public_html', '/opt/depot/Python-2.3.4/lib/python23.zip', '/opt/depot/Python-2.3.4/lib/python2.3', '/opt/depot/Python-2.3.4/lib/python2.3/plat-sunos5', '/opt/depot/Python-2.3.4/lib/python2.3/lib-tk', '/opt/depot/Python-2.3.4/lib/python2.3/lib-dynload', '/opt/depot/Python-2.3.4/lib/python2.3/site-packages' 'HTTP_COOKIE': '__utma=135525616.6248723.1198085016.1225140952.1226422259.108; __utmz=135525616.1222720014.104.1.utmccn=(referral)|utmcsr=chronicle.pitt.edu|utmcct=/media/pcc021014/hillman_main.html|utmcmd=referral', 'SERVER_PROTOCOL': 'HTTP/1.1', 'SERVER_SOFTWARE': 'SISWEB', 'SCRIPT_NAME': '/~-----/index.cgi', 'SERVER_SIGNATURE': '', 'REQUEST_METHOD': 'GET', 'HTTP_UA_CPU': 'x86', 'QUERY_STRING': '', 'PATH': '/usr/bin:bin:/opt/bin', 'HTTP_USER_AGENT': 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; InfoPath.1; .NET CLR 3.0.04506.648)', 'TZ': 'US/Eastern', 'SERVER_NAME': 'www.xxx.www.edu', 'REMOTE_ADDR': '111.111.11.11', 'SERVER_PORT': '80', 'SERVER_ADDR': '1111.111.11.19', 'DOCUMENT_ROOT': '/home/webadm2/public_html', 'SCRIPT_FILENAME': '/home/-----/public_html/index.cgi', 'SERVER_ADMIN': 'webdev at mail.xxx.xxx.xxx', 'HTTP_HOST': 'www.xxx.xxx.xxx', 'HTTP_CONNECTION': 'Keep-Alive', 'REQUEST_URI': '/---/index.cgi', 'HTTP_ACCEPT': '*/*', 'GATEWAY_INTERFACE': 'CGI/1.1', 'REMOTE_PORT': '1900', 'HTTP_ACCEPT_LANGUAGE': 'en-us', 'ORACLE_HOME': '/opt/local/sources/packages/oracle/product/8.1.7', 'HTTP_ACCEPT_ENCODING': 'gzip, deflate', 'UNIQUE_ID': 'RY1DY4iOdAkAADAC5SgAAAAs' Examining the sys.path and os.environ looks fine. The program works properly under Unix. Does anyone know how to solver this problem? Thanks in advance. yhjiang -------------- next part -------------- An HTML attachment was scrubbed... URL: From bricker.steve at imonmail.com Thu Nov 13 17:14:54 2008 From: bricker.steve at imonmail.com (Steve Bricker) Date: Thu, 13 Nov 2008 10:14:54 -0600 Subject: [Tutor] Converting EBCDIC characters to ASCII Message-ID: <22100.1226592894@imonmail.com> BODY { font-family:Arial, Helvetica, sans-serif;font-size:12px; }I am trying to build an application for work that FTPs a file from an IBM mainframe to my Windows desktop then process it. The EBCDIC-to-ASCII conversion works nicely (using a BAT file I created) except for three packed-decimal data fields (for example, X'0000000000000000014C' is equal to integer 14). I am assuming I need to go through this byte-by-byte to convert. Is that the best approach, or is there a better way? Steve Bricker -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Thu Nov 13 18:42:36 2008 From: kent37 at tds.net (Kent Johnson) Date: Thu, 13 Nov 2008 12:42:36 -0500 Subject: [Tutor] import data (txt/csv) into list/array and manipulation In-Reply-To: <20481629.post@talk.nabble.com> References: <20424075.post@talk.nabble.com> <1c2a2c590811101536j63dd545ya6f002ece60fd230@mail.gmail.com> <20435477.post@talk.nabble.com> <20481629.post@talk.nabble.com> Message-ID: <1c2a2c590811130942u2da65481g4a504b57cc16773c@mail.gmail.com> On Thu, Nov 13, 2008 at 9:50 AM, trias wrote: > PS I could maybe upload a couple of small example flies or a schematic to > see what I mean A small example would be very helpful. Also please subscribe to the list. Kent From kent37 at tds.net Thu Nov 13 18:51:00 2008 From: kent37 at tds.net (Kent Johnson) Date: Thu, 13 Nov 2008 12:51:00 -0500 Subject: [Tutor] Converting EBCDIC characters to ASCII In-Reply-To: <22100.1226592894@imonmail.com> References: <22100.1226592894@imonmail.com> Message-ID: <1c2a2c590811130951t27150648u20db1af16ca86b2a@mail.gmail.com> On Thu, Nov 13, 2008 at 11:14 AM, Steve Bricker wrote: > I am trying to build an application for work that FTPs a file from an IBM > mainframe to my Windows desktop then process it. The EBCDIC-to-ASCII > conversion works nicely (using a BAT file I created) except for three > packed-decimal data fields (for example, X'0000000000000000014C' is equal to > integer 14). I am assuming I need to go through this byte-by-byte to > convert. Is that the best approach, or is there a better way? Python includes an EBCDIC codec. If s is a byte string containing EBCDIC characters, then s.decode('EBCDIC-CP-BE').encode('ascii') should give you the ASCII equivalent. Kent From bgailer at gmail.com Thu Nov 13 18:58:48 2008 From: bgailer at gmail.com (bob gailer) Date: Thu, 13 Nov 2008 12:58:48 -0500 Subject: [Tutor] Converting EBCDIC characters to ASCII In-Reply-To: <22100.1226592894@imonmail.com> References: <22100.1226592894@imonmail.com> Message-ID: <491C6AD8.5050902@gmail.com> Steve Bricker wrote: > I am trying to build an application for work that FTPs a file from an > IBM mainframe to my Windows desktop then process it. The > EBCDIC-to-ASCII conversion works nicely (using a BAT file I created) > except for three packed-decimal data fields (for example, > X'0000000000000000014C' is equal to integer 14). I am assuming I need > to go through this byte-by-byte to convert. Is that the best > approach, or is there a better way? What does a BAT file have to do with Python? Yes you will have to process the packed-decimal data fields byte-by byte. If the data volume is high then I'd construct a dictionary with a key for each possible byte value, lookup each byte in the dictionary and accumulate the total: d={} for l in range(10): for r in range(10): k = l*16+r v = l*10+r d[chr(k)] = v This gives a lookup table for all but the rightmost byte. If a byte contains for example '\x91' then d[byte] gives 91 The rightmost byte holds 1 digit and the sign (C=plus) in your example. Extend the dictionary to handle these: for l in range(10): for r in (11, 13): k = l*16+r v = l*10 d[chr(k)] = (v, 1) for l in range(10): for r in (11, 13): k = l*16+r v = l*10 d[chr(k)] = (v, -1) m = 10 value, sign = d[bcdstring[-1]] for byte in bcdstring[-2::-1]: value += m*d[byte] m *= 100 value = value * sign -- Bob Gailer Chapel Hill NC 919-636-4239 When we take the time to be aware of our feelings and needs we have more satisfying interatctions with others. Nonviolent Communication provides tools for this awareness. As a coach and trainer I can assist you in learning this process. What is YOUR biggest relationship challenge? From bricker.steve at imonmail.com Thu Nov 13 18:58:47 2008 From: bricker.steve at imonmail.com (Steve Bricker) Date: Thu, 13 Nov 2008 11:58:47 -0600 Subject: [Tutor] Converting EBCDIC characters to ASCII Message-ID: <46900.1226599127@imonmail.com> I see the scenario does not give enough to really allow someone to formulate an answer. Allow me to clarify a bit. The three PD fields are each 10 positions in length. Using the example below, a field with X'0000000000000000014C' would need to be expanded to a 19-character field of '0000000000000000014'. Steve Bricker On Thu 13/11/08 10:14 , Steve Bricker bricker.steve at imonmail.com sent: I am trying to build an application for work that FTPs a file from an IBM mainframe to my Windows desktop then process it. The EBCDIC-to-ASCII conversion works nicely (using a BAT file I created) except for three packed-decimal data fields (for example, X'0000000000000000014C' is equal to integer 14). I am assuming I need to go through this byte-by-byte to convert. Is that the best approach, or is there a better way? Steve Bricker -------------- next part -------------- An HTML attachment was scrubbed... URL: From bricker.steve at imonmail.com Thu Nov 13 19:07:31 2008 From: bricker.steve at imonmail.com (Steve Bricker) Date: Thu, 13 Nov 2008 12:07:31 -0600 Subject: [Tutor] Converting EBCDIC characters to ASCII Message-ID: <16566.1226599651@imonmail.com> BODY { font-family:Arial, Helvetica, sans-serif;font-size:12px; }I stand corrected. There was enough information. Thank you. BAT file has nothing to do with Python. I used it because I knew how. Once I figure it out in Python, I'll use that instead. Steve Bricker On Thu 13/11/08 11:58 , bob gailer bgailer at gmail.com sent: Steve Bricker wrote: > I am trying to build an application for work that FTPs a file from an > IBM mainframe to my Windows desktop then process it. The > EBCDIC-to-ASCII conversion works nicely (using a BAT file I created) > except for three packed-decimal data fields (for example, > X'0000000000000000014C' is equal to integer 14). I am assuming I need > to go through this byte-by-byte to convert. Is that the best > approach, or is there a better way? What does a BAT file have to do with Python? Yes you will have to process the packed-decimal data fields byte-by byte. If the data volume is high then I'd construct a dictionary with a key for each possible byte value, lookup each byte in the dictionary and accumulate the total: d={} for l in range(10): for r in range(10): k = l*16+r v = l*10+r d[chr(k)] = v This gives a lookup table for all but the rightmost byte. If a byte contains for example 'x91' then d[byte] gives 91 The rightmost byte holds 1 digit and the sign (C=plus) in your example. Extend the dictionary to handle these: for l in range(10): for r in (11, 13): k = l*16+r v = l*10 d[chr(k)] = (v, 1) for l in range(10): for r in (11, 13): k = l*16+r v = l*10 d[chr(k)] = (v, -1) m = 10 value, sign = d[bcdstring[-1]] for byte in bcdstring[-2::-1]: value += m*d[byte] m *= 100 value = value * sign -- Bob Gailer Chapel Hill NC 919-636-4239 When we take the time to be aware of our feelings and needs we have more satisfying interatctions with others. Nonviolent Communication provides tools for this awareness. As a coach and trainer I can assist you in learning this process. What is YOUR biggest relationship challenge? -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Thu Nov 13 19:15:21 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 13 Nov 2008 18:15:21 -0000 Subject: [Tutor] experience/opinions with deploying python GUI app toLinux, Win32, and Mac OS X References: Message-ID: "greg whittier" wrote >>> - jython/SWT -- I have no experience with this, but everybody has >>> a JVM, >> Of the client GUI options this is probably the easiest, but > Does "probably the easiest" mean "probably the easiest to develop?" Sorry, I meant easiest to deploy. Hardest (or one of the harder ones) to develop IMHO. HTH, Alan G. From alan.gauld at btinternet.com Thu Nov 13 19:18:04 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 13 Nov 2008 18:18:04 -0000 Subject: [Tutor] Classes and Databases References: <3124be320811130756p2dac86d9y8d591e583df7abd0@mail.gmail.com> Message-ID: "Jojo Mwebaze" wrote > Because we have very many such cases, we can not incorporate such > adhoc > changes in the system.. we are thinking of storing such classes in > the > database and have classes run from the database. if anyone else > feels they > need to use someone's algorithm, they can run it/or extract it from > the > database and run on it on their data. Sorry if I'm missing the point but this sounds like a traditional version control system like CVS or SVN would do the job using the normal python files. Or is that too simple? -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From bgailer at gmail.com Thu Nov 13 19:36:21 2008 From: bgailer at gmail.com (bob gailer) Date: Thu, 13 Nov 2008 13:36:21 -0500 Subject: [Tutor] Converting EBCDIC characters to ASCII In-Reply-To: <46900.1226599127@imonmail.com> References: <46900.1226599127@imonmail.com> Message-ID: <491C73A5.70109@gmail.com> Steve Bricker wrote: > I see the scenario does not give enough to really allow someone to > formulate an answer. An excellent reminder to write no code until the user's requirements are fully understood! OTOH a little rapid prototyping can be a fast path to discovery of requirements. > Allow me to clarify a bit. The three PD fields are each 10 positions > in length. Using the example below, a field with > X'0000000000000000014C' would need to be expanded to a 19-character > field of '0000000000000000014'. So you are going to ignore the sign nibble? Modify the code I wrote - ignore the sign; treat results as positive. At the end add "%019i" % value > > Steve Bricker > > On Thu 13/11/08 10:14 , Steve Bricker bricker.steve at imonmail.com sent: > > I am trying to build an application for work that FTPs a file from > an IBM mainframe to my Windows desktop then process it. The > EBCDIC-to-ASCII conversion works nicely (using a BAT file I > created) except for three packed-decimal data fields (for example, > X'0000000000000000014C' is equal to integer 14). I am assuming I > need to go through this byte-by-byte to convert. Is that the best > approach, or is there a better way? > > Steve Bricker > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Bob Gailer Chapel Hill NC 919-636-4239 When we take the time to be aware of our feelings and needs we have more satisfying interatctions with others. Nonviolent Communication provides tools for this awareness. As a coach and trainer I can assist you in learning this process. What is YOUR biggest relationship challenge? From jojo.mwebaze at gmail.com Fri Nov 14 00:04:53 2008 From: jojo.mwebaze at gmail.com (Jojo Mwebaze) Date: Fri, 14 Nov 2008 00:04:53 +0100 Subject: [Tutor] Classes and Databases In-Reply-To: References: <3124be320811130756p2dac86d9y8d591e583df7abd0@mail.gmail.com> Message-ID: <3124be320811131504o76883286l5aaf3a4a07fd1554@mail.gmail.com> Thanks Allan... we have used CVS for the base system.. but for users provided functions, we think for having them persistent in the database.. Cheers Johnson On Thu, Nov 13, 2008 at 7:18 PM, Alan Gauld wrote: > > "Jojo Mwebaze" wrote > > Because we have very many such cases, we can not incorporate such adhoc >> changes in the system.. we are thinking of storing such classes in the >> database and have classes run from the database. if anyone else feels >> they >> need to use someone's algorithm, they can run it/or extract it from the >> database and run on it on their data. >> > > Sorry if I'm missing the point but this sounds like a traditional version > control system like CVS or SVN would do the job using the normal > python files. > > Or is that too simple? > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.freenetpages.co.uk/hp/alan.gauld > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From pablo.englebienne at gmail.com Thu Nov 13 20:30:14 2008 From: pablo.englebienne at gmail.com (Pablo Englebienne) Date: Thu, 13 Nov 2008 14:30:14 -0500 Subject: [Tutor] Dictionary of dictionaries issue In-Reply-To: <1c2a2c590811130726j3ec39faeoda6acaec66d9b641@mail.gmail.com> References: <491C413A.3050603@tue.nl> <1c2a2c590811130726j3ec39faeoda6acaec66d9b641@mail.gmail.com> Message-ID: <491C8046.5040103@gmail.com> Thank you all, this is exactly what I was trying to do and the syntax is beautiful... :-) -- Pablo Englebienne "Progress is made by lazy men looking for easier ways to do things." - Robert A. Heinlein Kent Johnson wrote: > On Thu, Nov 13, 2008 at 10:01 AM, A.T.Hofkamp wrote: > >>>>> d3 = dict(( (rv, dict.fromkeys(c)) for rv in r )) >>>>> > > You don't need the double parentheses, this works just as well: > d3 = dict( (rv, dict.fromkeys(c)) for rv in r ) > > A generator expression just has to be in parentheses, it's OK if the > parens also have other meaning syntactically; in this case indicating > a function call. > > Kent > -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Fri Nov 14 02:21:51 2008 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Fri, 14 Nov 2008 01:21:51 +0000 (GMT) Subject: [Tutor] Classes and Databases Message-ID: <568127.37330.qm@web86709.mail.ird.yahoo.com> > Thanks Allan... we have used CVS for the base system.. but for users provided functions, > we think for having them persistent in the database.. I'm puzzled. CVS provides much better facilities for handling code, especially with multiple versions (visibility of diffs, who changed what and when etc) that I can't think of a single good reason to put it in a database. I can see the point of using a database as an indexing system for searching, filtering etc but storing code in a database, extracting it and then trying to execute it is just so much more difficult than fetching a version file and importing or running it directly. Plus you need to write a basic version control system on top of the database anyway. I really think I must be missing something about your requirements? Alan G On Thu, Nov 13, 2008 at 7:18 PM, Alan Gauld wrote: "Jojo Mwebaze" wrote Because we have very many such cases, we can not incorporate such adhoc changes in the system.. we are thinking of storing such classes in the database and have classes run from the database. if anyone else feels they need to use someone's algorithm, they can run it/or extract it from the database and run on it on their data. Sorry if I'm missing the point but this sounds like a traditional version control system like CVS or SVN would do the job using the normal python files. Or is that too simple? -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From denis.spir at free.fr Fri Nov 14 12:43:32 2008 From: denis.spir at free.fr (spir) Date: Fri, 14 Nov 2008 12:43:32 +0100 Subject: [Tutor] list output -- float output Message-ID: <491D6464.3000201@free.fr> Below an illustration of what troubles me a bit. denis class Seq(list): ''' specialized sequence type with improved str Override list's behaviour that list.__str__ calls __repr__ instead of __str__ on items. ??? ''' def __str__(self): if len(self) == 0: return '[]' text = str(self[0]) for item in self[1:]: text += " ,%s" %item return "[%s]" %text print 1.1, repr(1.1) print [1.1], Seq([1.1]) ==> 1.1 1.1000000000000001 [1.1000000000000001] [1.1] # By the way, I do not understand at all the behaviour of repr on rounded floats: x = round(1.1,1) print x, repr(x), "%s" %x 1.1 1.1000000000000001 1.1 ??? From a.t.hofkamp at tue.nl Fri Nov 14 13:04:49 2008 From: a.t.hofkamp at tue.nl (A.T.Hofkamp) Date: Fri, 14 Nov 2008 13:04:49 +0100 Subject: [Tutor] list output -- float output In-Reply-To: <491D6464.3000201@free.fr> References: <491D6464.3000201@free.fr> Message-ID: <491D6961.5010708@tue.nl> spir wrote: > # By the way, I do not understand at all the behaviour of repr on > rounded floats: > x = round(1.1,1) > print x, repr(x), "%s" %x > 1.1 1.1000000000000001 1.1 This is a FAQ question: http://www.python.org/doc/faq/general/#why-are-floating-point-calculations-so-inaccurate Sincerely, Albert From bermanrl at embarqmail.com Fri Nov 14 13:56:40 2008 From: bermanrl at embarqmail.com (Robert Berman) Date: Fri, 14 Nov 2008 07:56:40 -0500 Subject: [Tutor] referencing external functions Message-ID: <491D7588.4030808@embarqmail.com> An HTML attachment was scrubbed... URL: From Karen at smarttech.co.za Fri Nov 14 09:39:00 2008 From: Karen at smarttech.co.za (Karen Bester) Date: Fri, 14 Nov 2008 10:39:00 +0200 Subject: [Tutor] floating point accuracy [working with Fractions] Message-ID: <037a01c94634$7843c200$0300000a@SmartTech.local> Hi Is there a method to determine the accuracy that you can get given a double precision number. I'm looking for a formula or table that can tell me what accuracy I can get depending on "where" the decimal point lies. Thank you Karen ____________________________________________________________________ SmartTech 34 Firgrove Way Constantia Hills Cape Town South Africa 7806 Phone: +27-21-7130126 Fax: +27-21-7130127 Cell: +27-(0)82-7882223 E-mail: sales at smarttech.co.za WebSite: www.smarttech.co.za ____________________________________________________________________ This message may contain information which is confidential, private or privileged in nature and subject to legal privilege. If you are not the intended recipient or the agent responsible for delivering this message to the intended recipient, you may not peruse, use, disseminate, distribute, store or copy this message or any files attached to this message. If you have received this message in error, please notify the sender immediately by e-mail, facsimile or telephone and thereafter return and/or destroy the original message. All reasonable precautions have been taken to ensure no viruses are present in the message and attachments. Please note that the recipient must scan this e-mail and any attached files for viruses and the like. The sender accepts no liability of whatever nature for any loss, liability, damage or expense resulting directly or indirectly from the access of this message or any attachments to this message. Any views expressed in this message are those of the individual sender and do not necessarily reflect those of SmartTech (Spencer Allen Technologies cc), except where the sender specifically states them to be the view of SmartTech (Spencer Allen Technologies cc). ____________________________________________________________________ -------------- next part -------------- An HTML attachment was scrubbed... URL: From a.t.hofkamp at tue.nl Fri Nov 14 14:23:53 2008 From: a.t.hofkamp at tue.nl (A.T.Hofkamp) Date: Fri, 14 Nov 2008 14:23:53 +0100 Subject: [Tutor] referencing external functions In-Reply-To: <491D7588.4030808@embarqmail.com> References: <491D7588.4030808@embarqmail.com> Message-ID: <491D7BE9.80401@tue.nl> Robert Berman wrote: > I have a number of functions written in a python script called script1.py. In > another script, script2.py, I need to use a number of the functions residing in > script1.py. How do I make these functions known to script2.py. > > Thank you, script1.py: def f(n): return n + 1 script2.py: import script1 y = script1.f(3) (I would suggest to use more meaningful names than scriptX.py) Sincerely, Albert From bgailer at gmail.com Fri Nov 14 14:30:05 2008 From: bgailer at gmail.com (bob gailer) Date: Fri, 14 Nov 2008 08:30:05 -0500 Subject: [Tutor] referencing external functions In-Reply-To: <491D7BE9.80401@tue.nl> References: <491D7588.4030808@embarqmail.com> <491D7BE9.80401@tue.nl> Message-ID: <491D7D5D.4040207@gmail.com> A.T.Hofkamp wrote: > Robert Berman wrote: >> I have a number of functions written in a python script called >> script1.py. In another script, script2.py, I need to use a number of >> the functions residing in script1.py. How do I make these functions >> known to script2.py. >> >> Thank you, > > script1.py: > > def f(n): > return n + 1 > > > > script2.py: > > import script1 > > y = script1.f(3) > > > (I would suggest to use more meaningful names than scriptX.py) Perhaps Robert uses (as I do) Python for Windows. "Save" proposes script1, script2, ... as the initial filename. WIBNI it could cleverly guess a meaningful name as Word attempts to? Bob Gailer Chapel Hill NC 919-636-4239 When we take the time to be aware of our feelings and needs we have more satisfying interatctions with others. Nonviolent Communication provides tools for this awareness. As a coach and trainer I can assist you in learning this process. What is YOUR biggest relationship challenge? From kent37 at tds.net Fri Nov 14 14:28:57 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 14 Nov 2008 08:28:57 -0500 Subject: [Tutor] referencing external functions In-Reply-To: <491D7588.4030808@embarqmail.com> References: <491D7588.4030808@embarqmail.com> Message-ID: <1c2a2c590811140528t1480f1cfmc61c291c50193ed9@mail.gmail.com> On Fri, Nov 14, 2008 at 7:56 AM, Robert Berman wrote: > I have a number of functions written in a python script called script1.py. > In another script, script2.py, I need to use a number of the functions > residing in script1.py. How do I make these functions known to script2.py. By importing script1. script1.py must be in a directory on PYTHONPATH; if it is in the same dir as script2.py that will work. Then in script2.py you can say e.g. import script1 script1.some_function() More here or any Python book or tutorial should cover modules and importing: http://docs.python.org/tutorial/modules.html Kent From denis.spir at free.fr Fri Nov 14 14:59:15 2008 From: denis.spir at free.fr (spir) Date: Fri, 14 Nov 2008 14:59:15 +0100 Subject: [Tutor] list output -- float output In-Reply-To: <491D6464.3000201@free.fr> References: <491D6464.3000201@free.fr> Message-ID: <491D8433.2050807@free.fr> [addendum] Well, actually, the previous Seq didn't solve all problems. Obvious case of nested lists. Below a modified version. denis class Seq(list): ''' specialized sequence type with improved str Override list's behaviour that str(list) calls repr instead of str on items: print 2.2, [2.2], seq([2.2]) --> 2.2 [2.2000000000000002] [2.2] ''' def __str__(self): if len(self) == 0: return '[]' text = str(self[0]) for item in self[1:]: if isinstance(item, list): item = Seq(item) # will now call str on nested Seqs text += " ,%s" %item return "[%s]" %text spir a ?crit : > Below an illustration of what troubles me a bit. > denis > > class Seq(list): > ''' specialized sequence type with improved str > Override list's behaviour that list.__str__ > calls __repr__ instead of __str__ on items. > ??? > ''' > def __str__(self): > if len(self) == 0: > return '[]' > text = str(self[0]) > for item in self[1:]: > text += " ,%s" %item > return "[%s]" %text > > print 1.1, repr(1.1) > print [1.1], Seq([1.1]) > ==> > 1.1 1.1000000000000001 > [1.1000000000000001] [1.1] > > # By the way, I do not understand at all the behaviour of repr on > rounded floats: > x = round(1.1,1) > print x, repr(x), "%s" %x > 1.1 1.1000000000000001 1.1 > > ??? > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From bermanrl at embarqmail.com Fri Nov 14 15:08:16 2008 From: bermanrl at embarqmail.com (Robert Berman) Date: Fri, 14 Nov 2008 09:08:16 -0500 Subject: [Tutor] referencing external functions In-Reply-To: <491D7D5D.4040207@gmail.com> References: <491D7588.4030808@embarqmail.com> <491D7BE9.80401@tue.nl> <491D7D5D.4040207@gmail.com> Message-ID: <491D8650.6020008@embarqmail.com> An HTML attachment was scrubbed... URL: From denis.spir at free.fr Fri Nov 14 15:21:17 2008 From: denis.spir at free.fr (spir) Date: Fri, 14 Nov 2008 15:21:17 +0100 Subject: [Tutor] list output -- float output In-Reply-To: <491D6961.5010708@tue.nl> References: <491D6464.3000201@free.fr> <491D6961.5010708@tue.nl> Message-ID: <491D895D.7030202@free.fr> A.T.Hofkamp a ?crit : > spir wrote: >> # By the way, I do not understand at all the behaviour of repr on >> rounded floats: >> x = round(1.1,1) >> print x, repr(x), "%s" %x >> 1.1 1.1000000000000001 1.1 > > This is a FAQ question: > > http://www.python.org/doc/faq/general/#why-are-floating-point-calculations-so-inaccurate Well, actually not really I guess. I asked for rounded floats, not full-precision ones. Now, after more reflexion on the topic, I understand that even rounded floats need to keep full precision internally, because of the 'modular' difference between decimal and binary representations that causes 'epsilon' errors; which still applies on rounded floats, for the rounding operates at the decimal level. In other words, (decimal) rounding does not eliminate the source of 'little errors' -- it should be binary rounding instead, but this is probably not very useful for us in the real world ;-). The reason why repr(), that shows inner representation, is still full of junk digits for rounded floats, while str() shows the expected format. denis > Sincerely, > Albert > > > > From GDI at teamlog.com Fri Nov 14 14:23:05 2008 From: GDI at teamlog.com (=?iso-8859-1?Q?DIAGORN_Genevi=E8ve?=) Date: Fri, 14 Nov 2008 14:23:05 +0100 Subject: [Tutor] referencing external functions In-Reply-To: <491D7588.4030808@embarqmail.com> Message-ID: At the beginning of script2.py, write: >From script1 import , ..., Sincerely, Genevi?ve _____ De : tutor-bounces+gdi=teamlog.com at python.org [mailto:tutor-bounces+gdi=teamlog.com at python.org] De la part de Robert Berman Envoy? : vendredi 14 novembre 2008 13:57 ? : [tutor python] Objet : [Tutor] referencing external functions I have a number of functions written in a python script called script1.py. In another script, script2.py, I need to use a number of the functions residing in script1.py. How do I make these functions known to script2.py. Thank you, Robert -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Fri Nov 14 17:01:04 2008 From: bgailer at gmail.com (bob gailer) Date: Fri, 14 Nov 2008 11:01:04 -0500 Subject: [Tutor] floating point accuracy [working with Fractions] In-Reply-To: <037a01c94634$7843c200$0300000a@SmartTech.local> References: <037a01c94634$7843c200$0300000a@SmartTech.local> Message-ID: <491DA0C0.9060003@gmail.com> Karen Bester wrote: > Hi > > Is there a method to determine the accuracy that you can get given a > double precision number. I'm looking for a formula or table that can > tell me what accuracy I can get depending on "where" the decimal point > lies. What do you mean by "accuracy"? How do you measure it? In my vocabulary accuracy means how close to a real world measurement the number is. There are 2 factors affecting floating point accuracy: # of bits for the magnitude and whether the real world value can be expressed exactly as a binary fraction of that many bits. http://en.wikipedia.org/wiki/Floating_point asserts that "any integer less than or equal to 2^53 can be exactly represented in the double precision format". 2^53 = 18014398509481984. math.pi shows up in Python as 3.1415926535897931. This is an approximation, as pi can't be expressed in a finite # of digits. You can say that math.pi is within 1/18014398509481984 of the value of pi. I don't think it matters where the decimal point lies. -- Bob Gailer Chapel Hill NC 919-636-4239 When we take the time to be aware of our feelings and needs we have more satisfying interatctions with others. Nonviolent Communication provides tools for this awareness. As a coach and trainer I can assist you in learning this process. What is YOUR biggest relationship challenge? From kent37 at tds.net Fri Nov 14 17:11:39 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 14 Nov 2008 11:11:39 -0500 Subject: [Tutor] floating point accuracy [working with Fractions] In-Reply-To: <037a01c94634$7843c200$0300000a@SmartTech.local> References: <037a01c94634$7843c200$0300000a@SmartTech.local> Message-ID: <1c2a2c590811140811t12103876mddb8402a5a825582@mail.gmail.com> On Fri, Nov 14, 2008 at 3:39 AM, Karen Bester wrote: > Hi > > Is there a method to determine the accuracy that you can get given a double > precision number. I'm looking for a formula or table that can tell me what > accuracy I can get depending on "where" the decimal point lies. I'm not really sure what you are looking for but you might be interested in sys.float_info, available in Python 2.6. I think you may want the mant_dig property: http://docs.python.org/library/sys.html#sys.float_info There is no straightforward way to determine this in Python 2.5. If you know the C compiler that was used to build Python, then you can investigate its implementation of double. Kent From jojo.mwebaze at gmail.com Fri Nov 14 17:42:22 2008 From: jojo.mwebaze at gmail.com (Jojo Mwebaze) Date: Fri, 14 Nov 2008 17:42:22 +0100 Subject: [Tutor] Classes and Databases In-Reply-To: <568127.37330.qm@web86709.mail.ird.yahoo.com> References: <568127.37330.qm@web86709.mail.ird.yahoo.com> Message-ID: <3124be320811140842x726e4196h488c481e95fcdd61@mail.gmail.com> Sorry Alan, What u described below is exactly what i want to do.. if given x, y as two datatums and such that f(x) --> y, given y can we determine f or x? Assuming the x, y and f are stored in the database, then we can be able to write queries to search/extract for the f's that are responsible for the 'y' or use links, database catalogs etc Thanks for the help. Johnson On Fri, Nov 14, 2008 at 2:21 AM, ALAN GAULD wrote: > > Thanks Allan... we have used CVS for the base system.. but for users > provided functions, > > we think for having them persistent in the database.. > I'm puzzled. CVS provides much better facilities for handling code, > especially with multiple > versions (visibility of diffs, who changed what and when etc) that I can't > think of a single > good reason to put it in a database. I can see the point of using a > database as an indexing > system for searching, filtering etc but storing code in a database, > extracting it and then trying > to execute it is just so much more difficult than fetching a version file > and importing > or running it directly. Plus you need to write a basic version control > system on top of > the database anyway. > > I really think I must be missing something about your requirements? > > Alan G > > On Thu, Nov 13, 2008 at 7:18 PM, Alan Gauld wrote: > >> >> "Jojo Mwebaze" wrote >> >> Because we have very many such cases, we can not incorporate such adhoc >>> changes in the system.. we are thinking of storing such classes in the >>> database and have classes run from the database. if anyone else feels >>> they >>> need to use someone's algorithm, they can run it/or extract it from the >>> database and run on it on their data. >>> >> >> Sorry if I'm missing the point but this sounds like a traditional version >> control system like CVS or SVN would do the job using the normal >> python files. >> >> Or is that too simple? >> >> -- >> Alan Gauld >> Author of the Learn to Program web site >> http://www.freenetpages.co.uk/hp/alan.gauld >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From lie.1296 at gmail.com Fri Nov 14 18:23:59 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Fri, 14 Nov 2008 17:23:59 +0000 (UTC) Subject: [Tutor] list output -- float output References: <491D6464.3000201@free.fr> <491D6961.5010708@tue.nl> <491D895D.7030202@free.fr> Message-ID: On Fri, 14 Nov 2008 15:21:17 +0100, spir wrote: > Well, actually not really I guess. I asked for rounded floats, not > full-precision ones. > Now, after more reflexion on the topic, I understand that even rounded > floats need to keep full precision internally, because of the 'modular' > difference between decimal and binary representations that causes > 'epsilon' errors; which still applies on rounded floats, for the > rounding operates at the decimal level. In other words, (decimal) > rounding does not eliminate the source of 'little errors' -- it should > be binary rounding instead, but this is probably not very useful for us > in the real world ;-). The reason why repr(), that shows inner > representation, is still full of junk digits for rounded floats, while > str() shows the expected format. denis If you wanted a more controllable precision and can tolerate being a bit slow, you can use the Decimal module instead. From Humphrey.Ifeozor at wlv.ac.uk Fri Nov 14 19:11:36 2008 From: Humphrey.Ifeozor at wlv.ac.uk (Ifeozor, Humphrey O.) Date: Fri, 14 Nov 2008 18:11:36 -0000 Subject: [Tutor] pygame1.py Message-ID: <5405021022F03A45B8A0543FF2A8AEAB0751B28B@exchange04.unv.wlv.ac.uk> Dear Tutor, I have problem runing the attached pygame code, there's been error message "could not open ("ball.bmp")". what do i need to make it run as expected or how do i import the library which contains "ball.bmp" thank you for your help. Humphrey -- Scanned by iCritical. -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: import pygame.docx Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document Size: 10788 bytes Desc: import pygame.docx URL: From wferguson1 at socal.rr.com Fri Nov 14 19:27:59 2008 From: wferguson1 at socal.rr.com (WM.) Date: Fri, 14 Nov 2008 10:27:59 -0800 Subject: [Tutor] PYTHON ON DOS Message-ID: <491DC32F.6050004@socal.rr.com> Some say that Python programs run better on DOS. I cannot find a way to do that. I can go 'Python Command Line' to wind up on a black screen version of IDLE but I can't get from the interactive to executive mode. Is there any advantage to running .py on DOS? From bgailer at gmail.com Fri Nov 14 19:32:42 2008 From: bgailer at gmail.com (bob gailer) Date: Fri, 14 Nov 2008 13:32:42 -0500 Subject: [Tutor] pygame1.py In-Reply-To: <5405021022F03A45B8A0543FF2A8AEAB0751B28B@exchange04.unv.wlv.ac.uk> References: <5405021022F03A45B8A0543FF2A8AEAB0751B28B@exchange04.unv.wlv.ac.uk> Message-ID: <491DC44A.5030403@gmail.com> Ifeozor, Humphrey O. wrote: > Dear Tutor, > > I have problem runing the attached pygame code, there's been error > message "could not open ("ball.bmp")". what do i need to make it run > as expected or how do i import the library which contains "ball.bmp" I have no way to view that attachment. Please just send us a plain text file or put the code in the body of the email. -- Bob Gailer Chapel Hill NC 919-636-4239 When we become aware of our feelings and needs, and express them with care, we can more satisfying interactions with others. Nonviolent Communication provides tools for this awareness and expression. Want to learn more? Just ask. From lie.1296 at gmail.com Fri Nov 14 19:45:22 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Fri, 14 Nov 2008 18:45:22 +0000 (UTC) Subject: [Tutor] PYTHON ON DOS References: <491DC32F.6050004@socal.rr.com> Message-ID: On Fri, 14 Nov 2008 10:27:59 -0800, WM. wrote: > Some say that Python programs run better on DOS. I cannot find a way to > do that. I can go 'Python Command Line' to wind up on a black screen > version of IDLE but I can't get from the interactive to executive mode. > > Is there any advantage to running .py on DOS? 1. XP: Start > Run > type "cmd" > OK Vista: Start > type "cmd" > Enter 2. then cd to the folder where you put the script: C:\> cd C:\mypython\ 3. then run the program by typing "python blah.py" C:\mypython\> python blah.py PS: strictly speaking Windows doesn't have true DOS since NT-family. The black window is a command prompt, somewhat an emulator for DOS. From denis.spir at free.fr Fri Nov 14 20:07:01 2008 From: denis.spir at free.fr (spir) Date: Fri, 14 Nov 2008 20:07:01 +0100 Subject: [Tutor] list output -- float output In-Reply-To: References: <491D6464.3000201@free.fr> <491D6961.5010708@tue.nl> <491D895D.7030202@free.fr> Message-ID: <491DCC55.9090206@free.fr> Thank you for the advice. Actually, what annoys me is that list textual output, either with print or str(), calls repr() for each item of the list, instead of str(). That's why I had these strange things with floats, as illustrated in my first post on the topic: class Seq(list): ''' sequence for proper output of items ''' def __str__(self): if len(self) == 0: return '[]' text = str(self[0]) for item in self[1:]: if isinstance(item, list): item = Seq(item) text += " ,%s" %item return "[%s]" %text l = [1, 1.1, [1, 1.1]] s= Seq(l) print "repr:%s str:%s\nl: %s\ns:%s" %(repr(1.1), str(1.1), l, s) ==> repr:1.1000000000000001 str:1.1 l: [1, 1.1000000000000001, [1, 1.1000000000000001]] s:[1 ,1.1 ,[1 ,1.1]] Lie Ryan a ?crit : > On Fri, 14 Nov 2008 15:21:17 +0100, spir wrote: >> Well, actually not really I guess. I asked for rounded floats, not >> full-precision ones. >> Now, after more reflexion on the topic, I understand that even rounded >> floats need to keep full precision internally, because of the 'modular' >> difference between decimal and binary representations that causes >> 'epsilon' errors; which still applies on rounded floats, for the >> rounding operates at the decimal level. In other words, (decimal) >> rounding does not eliminate the source of 'little errors' -- it should >> be binary rounding instead, but this is probably not very useful for us >> in the real world ;-). The reason why repr(), that shows inner >> representation, is still full of junk digits for rounded floats, while >> str() shows the expected format. denis > > > If you wanted a more controllable precision and can tolerate being a bit > slow, you can use the Decimal module instead. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From mlknack at gmail.com Fri Nov 14 20:11:00 2008 From: mlknack at gmail.com (Mary Lou Knack) Date: Fri, 14 Nov 2008 12:11:00 -0700 Subject: [Tutor] problem running iptest on windows Message-ID: <00DC33DC1EF345BC9E3FCBAFBA995582@MLKsHP> Hi I just installed Ipython 0.9.1.win32 (and Python 2.5.1) under Windows XP. I added C:\Python25\Scripts to my path environment variable but nothing else. Out of curiosity, I then decided to try running the iptest script (after installing the nose code) but I keep getting import errors. Here is error message when I ran the following command while in the Python25/Lib/site-packages directory: C:\Python25\Lib\site-packages>iptest E ====================================================================== ERROR: Failure: ImportError (cannot import name Release) ---------------------------------------------------------------------- Traceback (most recent call last): File "c:\python25\lib\site-packages\nose-0.10.4-py2.5.egg\nose\loader.py", lin e 364, in loadTestsFromName addr.filename, addr.module) File "c:\python25\lib\site-packages\nose-0.10.4-py2.5.egg\nose\importer.py", l ine 39, in importFromPath return self.importFromDir(dir_path, fqname) File "c:\python25\lib\site-packages\nose-0.10.4-py2.5.egg\nose\importer.py", l ine 82, in importFromDir mod = load_module(part_fqname, fh, filename, desc) File "C:\Python25\Lib\site-packages\IPython\__init__.py", line 63, in from IPython import Release # do it explicitly so pydoc can see it - pydoc b ug ImportError: cannot import name Release ---------------------------------------------------------------------- Ran 1 test in 0.000s FAILED (errors=1) and my path: C:\Python25\Lib\site-packages>path PATH=C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\Program Files\Qu ickTime\QTSystem\;C:\bin;C:\Python25\Scripts I assume I have a path error but I don't know what to change. Any suggestions? (BTW, I checked and there is a Release.py in the C:\Python25\Lib\site-packages\IPython directory. Mary Lou -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Fri Nov 14 21:12:03 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 14 Nov 2008 15:12:03 -0500 Subject: [Tutor] pygame1.py In-Reply-To: <5405021022F03A45B8A0543FF2A8AEAB0751B28B@exchange04.unv.wlv.ac.uk> References: <5405021022F03A45B8A0543FF2A8AEAB0751B28B@exchange04.unv.wlv.ac.uk> Message-ID: <1c2a2c590811141212w36d4bfcdy8406845d41908cdf@mail.gmail.com> On Fri, Nov 14, 2008 at 1:11 PM, Ifeozor, Humphrey O. wrote: > Dear Tutor, > > I have problem runing the attached pygame code, there's been error message > "could not open ("ball.bmp")". what do i need to make it run as expected or > how do i import the library which contains "ball.bmp" Ball.bmp is an image file that it expects to find in the same directory as the program. I guess you should get the image from the same place you got the Python code. Kent From kent37 at tds.net Fri Nov 14 21:13:49 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 14 Nov 2008 15:13:49 -0500 Subject: [Tutor] PYTHON ON DOS In-Reply-To: <491DC32F.6050004@socal.rr.com> References: <491DC32F.6050004@socal.rr.com> Message-ID: <1c2a2c590811141213n9145d2fi18acdb9353fbacd7@mail.gmail.com> On Fri, Nov 14, 2008 at 1:27 PM, WM. wrote: > Some say that Python programs run better on DOS. I cannot find a way to do > that. I can go 'Python Command Line' to wind up on a black screen version > of IDLE but I can't get from the interactive to executive mode. > > Is there any advantage to running .py on DOS? If you write Tkinter programs they don't always run well inside of IDLE (which itself uses Tkinter). Running from the command line (what you call running from DOS) is one alternative. Kent From alan.gauld at btinternet.com Sat Nov 15 02:14:12 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 15 Nov 2008 01:14:12 -0000 Subject: [Tutor] PYTHON ON DOS References: <491DC32F.6050004@socal.rr.com> Message-ID: "WM." wrote > Some say that Python programs run better on DOS. What they mean is running python scripts within a command window (aka DOS box). (You can run Python under real 16 bit DOS but its slow and clunky, don't do it unless you really must!) You can start a command window in Windows using Start->Run and typing CMD in the dialog. That will open a window with a DOS prompt. You can then type python myscript.py > Is there any advantage to running .py on DOS? Yes, you don't get any strange side effects from the IDE environment. Basically, whatever your program does in DOS is what it will do if you just double click it in Explorer - except you get to see any error messages etc. So for debugging a program before its final form its usually best to run it under DOS. Once it works pefectly you can just double click on the script and it will automatically start under DOS. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Sat Nov 15 02:17:10 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 15 Nov 2008 01:17:10 -0000 Subject: [Tutor] PYTHON ON DOS References: <491DC32F.6050004@socal.rr.com> Message-ID: "Lie Ryan" wrote > strictly speaking Windows doesn't have true DOS since NT-family. The > black window is a command prompt, somewhat an emulator for DOS. Being picky CMD is an enhanced version of the DOS COMMAND program. It doesn't emulate DOS as such but it runs a backwardly compatible command shell. But for most purposes Lie is right, it is a good emulation of MS DOS. Alan G From michael at arpsorensen.dk Sat Nov 15 12:53:03 2008 From: michael at arpsorensen.dk (=?UTF-8?Q?Michael_Bernhard_Arp_S=C3=B8rensen?=) Date: Sat, 15 Nov 2008 12:53:03 +0100 Subject: [Tutor] Python on Sony Ericsson phones Message-ID: <1618520811150353g7ab04317k4fefa144e0c3c339@mail.gmail.com> Hi there. Does any of you know if it's possible to run python on newer Sony Ericsson phones? I'm thinking of buying the C905 phone. Its a knock out if I can't run python on that phone. My older Nokia N73 can run python 2.2 as far as I know. Med venlig hilsen/Kind regards Michael B. Arp S?rensen Programm?r / BOFH "Ride out and meet them." -------------- next part -------------- An HTML attachment was scrubbed... URL: From roadierich at googlemail.com Sat Nov 15 17:25:57 2008 From: roadierich at googlemail.com (Rich Lovely) Date: Sat, 15 Nov 2008 16:25:57 +0000 Subject: [Tutor] Classes and Databases In-Reply-To: <3124be320811140842x726e4196h488c481e95fcdd61@mail.gmail.com> References: <568127.37330.qm@web86709.mail.ird.yahoo.com> <3124be320811140842x726e4196h488c481e95fcdd61@mail.gmail.com> Message-ID: <3B49A061-009A-42F5-9B1C-947084E54D16@googlemail.com> Jojo, am reading your problem correctly? If you have (for example) x=2 and y=4, you want the database to return functions like x+2, 2x and 3x-2? (I know this is probably much simpler than the actual functions you'll be using). And you the want to use those functions in your code? @list: pickle? --- Richard "Roadie Rich" Lovely Part of the JNP|UK Famille www.theJNP.com (Sent from my iPod - please allow me a few typos: it's a very small keyboard) On 14 Nov 2008, at 04:42 PM, "Jojo Mwebaze" wrote: > Sorry Alan, > > What u described below is exactly what i want to do.. if given x, y > as two datatums and such that f(x) --> y, given y can we determine f > or x? > > Assuming the x, y and f are stored in the database, then we can be > able to write queries to search/extract for the f's that are > responsible for the 'y' or use links, database catalogs etc > > Thanks for the help. > > Johnson > > > > > On Fri, Nov 14, 2008 at 2:21 AM, ALAN GAULD > wrote: > > Thanks Allan... we have used CVS for the base system.. but for > users provided functions, > > we think for having them persistent in the database.. > > I'm puzzled. CVS provides much better facilities for handling code, > especially with multiple > versions (visibility of diffs, who changed what and when etc) that I > can't think of a single > good reason to put it in a database. I can see the point of using a > database as an indexing > system for searching, filtering etc but storing code in a database, > extracting it and then trying > to execute it is just so much more difficult than fetching a > version file and importing > or running it directly. Plus you need to write a basic version > control system on top of > the database anyway. > > I really think I must be missing something about your requirements? > > Alan G > > > On Thu, Nov 13, 2008 at 7:18 PM, Alan Gauld > wrote: > > "Jojo Mwebaze" wrote > > > Because we have very many such cases, we can not incorporate such > adhoc > changes in the system.. we are thinking of storing such classes in > the > database and have classes run from the database. if anyone else > feels they > need to use someone's algorithm, they can run it/or extract it from > the > database and run on it on their data. > > Sorry if I'm missing the point but this sounds like a traditional > version > control system like CVS or SVN would do the job using the normal > python files. > > Or is that too simple? > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.freenetpages.co.uk/hp/alan.gauld > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From wferguson1 at socal.rr.com Sun Nov 16 05:11:35 2008 From: wferguson1 at socal.rr.com (WM.) Date: Sat, 15 Nov 2008 20:11:35 -0800 Subject: [Tutor] IDLE CAN'T FIND SOCKET... In-Reply-To: References: Message-ID: <491F9D77.7020701@socal.rr.com> I keep getting the error message & must re-boot to enable IDLE work. Is there some rule about 'saving' or about having too many windows open? It seems to happen if I am doing a lot of saving & re-saving. From sierra_mtnview at sbcglobal.net Sun Nov 16 10:41:38 2008 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sun, 16 Nov 2008 01:41:38 -0800 Subject: [Tutor] Python 2.5 on a Win 98 Machine Message-ID: <491FEAD2.5070701@sbcglobal.net> An HTML attachment was scrubbed... URL: From wferguson1 at socal.rr.com Sun Nov 16 11:06:30 2008 From: wferguson1 at socal.rr.com (WM.) Date: Sun, 16 Nov 2008 02:06:30 -0800 Subject: [Tutor] Running Python from REVO screen??? Message-ID: <491FF0A6.8000405@socal.rr.com> I asked tutor how to get to the black screen to run Python programs. I got a three step answer but could not get step 1. to work; 1. XP: Start > Run > type "cmd" > OK C:\Documents and Settings The above line is where I wind up & I cannot get out of it. I can get into it with Start > Programs > Accessories > Command Prompt. The below lines I have not yet gotten to. What is 'cd'? 2. then cd to the folder where you put the script: C:\> cd C:\mypython\ 'cd'? 3. then run the program by typing "python blah.py" C:\mypython\> python blah.py From lie.1296 at gmail.com Sun Nov 16 12:19:53 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Sun, 16 Nov 2008 11:19:53 +0000 (UTC) Subject: [Tutor] Running Python from REVO screen??? References: <491FF0A6.8000405@socal.rr.com> Message-ID: On Sun, 16 Nov 2008 02:06:30 -0800, WM. wrote: > I asked tutor how to get to the black screen to run Python programs. I > got a three step answer but could not get step 1. to work; > > 1. > XP: Start > Run > type "cmd" > OK > > C:\Documents and Settings > The above line is where I wind up & I cannot get out of it. I can get > into it with Start > Programs > Accessories > Command Prompt. > > The below lines I have not yet gotten to. What is 'cd'? > > 2. > then cd to the folder where you put the script: > C:\> cd C:\mypython\ > 'cd'? cd is for _c_hange _d_irectory short tutorial on 'cd': cd .. -> go to parent directory cd -> go to the path cd -> go to the path relative to the current directory is a path that starts with drive letter, e.g. C:\mydir\blah doesn't start with drive letter, e.g. mydir if the path contains a space, enclose the path in double quote (I think Windows' cd is not as strict as linux's cd, but just in case) type "help cd" for more information the current directory is denoted before the prompt (i.e. if the prompt is "C:\mypath> " then the current directory is "C:\mypath"). The parent directory is the directory above the current directory, i.e. if current directory is C:\mypath, the parent directory is C:\ other useful commands: dir -- lists the file and folders in the current directory > 3. > then run the program by typing "python blah.py" C:\mypython\> python > blah.py From kent37 at tds.net Sun Nov 16 14:00:33 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 16 Nov 2008 08:00:33 -0500 Subject: [Tutor] Python 2.5 on a Win 98 Machine In-Reply-To: <491FEAD2.5070701@sbcglobal.net> References: <491FEAD2.5070701@sbcglobal.net> Message-ID: <1c2a2c590811160500v3cf6b492j63486a630737f493@mail.gmail.com> On Sun, Nov 16, 2008 at 4:41 AM, Wayne Watson wrote: > A fellow I work with is having lots of trouble with py 2.5 on his Win 98 > machine. It may be because of some use of numpy or plotmatlib. Further, he > used 2.4 (without plotmatlib) successfully. He did install 2.5 on his > machine without removing 2.4, but seems to have gotten 2.4 off of it. He should be able to have both 2.4 and 2.5 on one machine. Using numpy or matplotlib should not cause trouble, unless you mean he is having trouble with numpy and matplotlib. "Lots of trouble" is pretty vague. Perhaps you should start here: http://www.catb.org/~esr/faqs/smart-questions.html Kent From kent37 at tds.net Sun Nov 16 14:04:31 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 16 Nov 2008 08:04:31 -0500 Subject: [Tutor] Running Python from REVO screen??? In-Reply-To: <491FF0A6.8000405@socal.rr.com> References: <491FF0A6.8000405@socal.rr.com> Message-ID: <1c2a2c590811160504w1f86cabg6e0def9b4708faba@mail.gmail.com> On Sun, Nov 16, 2008 at 5:06 AM, WM. wrote: > I asked tutor how to get to the black screen to run Python programs. I got > a three step answer but could not get step 1. to work; > > 1. > XP: Start > Run > type "cmd" > OK > > C:\Documents and Settings > The above line is where I wind up & I cannot get out of it. You need to learn a little about the command prompt window. This is not specific to Python, it is part of Windows that you use to run Python programs. Here is a brief introduction: http://www.python.org/doc/faq/windows/#how-do-i-run-a-python-program-under-windows Kent From sierra_mtnview at sbcglobal.net Sun Nov 16 16:57:37 2008 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sun, 16 Nov 2008 07:57:37 -0800 Subject: [Tutor] Python 2.5 on a Win 98 Machine In-Reply-To: <1c2a2c590811160500v3cf6b492j63486a630737f493@mail.gmail.com> References: <491FEAD2.5070701@sbcglobal.net> <1c2a2c590811160500v3cf6b492j63486a630737f493@mail.gmail.com> Message-ID: <492042F1.8060506@sbcglobal.net> An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Sun Nov 16 16:58:28 2008 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sun, 16 Nov 2008 07:58:28 -0800 Subject: [Tutor] Python 2.5 on a Win 98 Machine In-Reply-To: <1c2a2c590811160500v3cf6b492j63486a630737f493@mail.gmail.com> References: <491FEAD2.5070701@sbcglobal.net> <1c2a2c590811160500v3cf6b492j63486a630737f493@mail.gmail.com> Message-ID: <49204324.5020003@sbcglobal.net> An HTML attachment was scrubbed... URL: From kent37 at tds.net Sun Nov 16 17:49:30 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 16 Nov 2008 11:49:30 -0500 Subject: [Tutor] Python 2.5 on a Win 98 Machine In-Reply-To: <492042F1.8060506@sbcglobal.net> References: <491FEAD2.5070701@sbcglobal.net> <1c2a2c590811160500v3cf6b492j63486a630737f493@mail.gmail.com> <492042F1.8060506@sbcglobal.net> Message-ID: <1c2a2c590811160849t4cf2b391n9ab6002c4bacd3ad@mail.gmail.com> On Sun, Nov 16, 2008 at 10:57 AM, Wayne Watson wrote: > A fundamental question is will py 2.5 work under win98? >From the python.org site it looks like Win98 is supported. This support was explicitly dropped for Python 2.6 - the What's New document for 2.6 says, "The support for Windows 95, 98, ME and NT4 has been dropped." The ActiveState site only lists Windows 2000, XP or Vista. So it may depend on which installer you use. You should also check compatibility of numpy and matplotlib with win 98. Kent From lidereshumanistas at gmail.com Sun Nov 16 15:55:22 2008 From: lidereshumanistas at gmail.com (Lideres Humanistas) Date: Sun, 16 Nov 2008 11:55:22 -0300 Subject: [Tutor] Saludos y comfirmacion de participacion Message-ID: Hola a todos: Estoy probando si estoy en la lista tutor de Python. Estoy en mis primeros pasos con la programacion en Python. Emilio Castro. -- Inter?s Cehum.cl: Desarrollar el conocimiento por encima de los pre-dialogales aceptados o impuestos al pensamiento como verdades consideradas intencionalmente como absolutas e inamovibles. Sitios Web de inter?s humanizador: http://humanistasenaccion.org http://www.cehum.cl http://groups.google.es/group/punta-de-vacas-2010 http://groups.google.es/group/revolucion-industrial-humanista http://groups.google.es/group/revolucion-educacional-humanista http://groups.google.es/group/revolucion-salud-humanista http://groups.google.es/group/revolucion-deportiva-humanista http://groups.google.es/group/desarme-nuclear-universal http://flickr.com/photos/humanizador/ http://flickr.com/photos/humanizate/ http://humanizador.blogspot.com/ http://www.youtube.com/humanizador http://www.panoramio.com/user/650187 http://www.florcitamotuda.tk http://www.yonopago.cl http://www.silo.net http://www.silo.ws http://www.parquemanantiales.org http://www.parquepuntadevacas.org -------------- next part -------------- An HTML attachment was scrubbed... URL: From denis.spir at free.fr Sun Nov 16 20:57:07 2008 From: denis.spir at free.fr (spir) Date: Sun, 16 Nov 2008 20:57:07 +0100 Subject: [Tutor] /not/ instanciating Message-ID: <49207B13.506@free.fr> Hello, I have a type (say: T) which normally receives as main init argument an object that can be of any other type. Occasionally, this arg object may precisely be of type T. In this case, for several reasons, I wish not to "over-instanciate", rather that the constructor returns the source object unchanged. I did some research and trials on the topic, and found as sole solution to overload __new__ as shown below. Still, as said in the doc, __init__ was not skipped (what for?), I need to do it myself. The following example seems to work. I have 3 questions: * Is there anything I should pay attention to? * Why, then, is __init__ still executed when the instanciated object is 'manually' returned? What's the use of that feature? * I find this an ugly distorsive practice. Isn't there a more graceful way not to instanciate? Or to simply return the desired object without caring of side-effects? Or am I so far to undestand what's up that I would better stop typing? denis class T(object): def __new__(self,source): print "_new_ -- source: %s:%s" %(source.__class__,source) if source.__class__ == T: print "source is T object" return source print "new T object instanciated" return object.__new__(T,self,source) def __init__(self,source): print "_init_ -- source: %s:%s" %(source.__class__,source) if source.__class__ != T: print "def attribs" self.typ = source.__class__.__name__ self.dat = source def __repr__(self): return "<%s>:%s" %(self.typ,self.dat) x = "xxx" t = T(x) tt = T(t) print "x=%s t=%s tt=%s" %(x,t,tt) ===>> _new_ -- source: :xxx new T object instanciated _init_ -- source: :xxx def attribs _new_ -- source: ::xxx source is T object _init_ -- source: ::xxx x=xxx t=:xxx tt=:xxx From mhoy06 at gmail.com Sun Nov 16 19:21:39 2008 From: mhoy06 at gmail.com (Mike Hoy) Date: Sun, 16 Nov 2008 11:21:39 -0700 Subject: [Tutor] Scrolling through output in shell Message-ID: I'm writing a small program that writes to a text file. I want to be able to view the contents of the text file inside of shell. But the file is too large for a small shell window. Is there a way for the user to 'scroll' through the contents of file that has been read into the program? I noticed that on the man pages that you can do that although I'm sure it's not written in python. Do I need to find a new language to write this in? Maybe use a different language for the output and still use python? Any help appreciated. -- Mike Hoy http://www.mikehoy.net From kent37 at tds.net Sun Nov 16 23:02:42 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 16 Nov 2008 17:02:42 -0500 Subject: [Tutor] /not/ instanciating In-Reply-To: <49207B13.506@free.fr> References: <49207B13.506@free.fr> Message-ID: <1c2a2c590811161402p42b3fbc9wa517e7ab265960ae@mail.gmail.com> On Sun, Nov 16, 2008 at 2:57 PM, spir wrote: > Hello, > > I have a type (say: T) which normally receives as main init argument an > object that can be of any other type. Occasionally, this arg object may > precisely be of type T. In this case, for several reasons, I wish not to > "over-instanciate", rather that the constructor returns the source object > unchanged. I did some research and trials on the topic, and found as sole > solution to overload __new__ as shown below. A simpler way to do this would be with a staticmethod or classmethod that acts as an object factory. For example, class T(object): @staticmethod def make(source): if type(source) == T: return source return T(source) Then your client code calls T.make(source). Kent From alan.gauld at btinternet.com Sun Nov 16 23:28:07 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 16 Nov 2008 22:28:07 -0000 Subject: [Tutor] Scrolling through output in shell References: Message-ID: "Mike Hoy" wrote > I'm writing a small program that writes to a text file. I want to be > able to view the contents of the text file inside of shell. But the > file is too large for a small shell window. Can you explain a bity more about what you are doing? Which shell are you talking about? Are you using IDLE or some other IDE? Or is it the Unix shell? > Is there a way for the user to 'scroll' through the contents > of file that has been read into the program? Only if you provide a window for the output to be displayed within. Are you writing a GUI? Or are you using the console for output? If the latter you can build a paging facility to display the file a page at a time. > I noticed that on the man pages that you can do that > although I'm sure it's not written in python. Which man pages? How are you viewing them? > Do I need to find a new language to write this in? > Maybe use a different language for the output > and still use python? Any help appreciated. No you can do anything like this in Python, but I suspect you may be confused about the difference between Python the language and the Python interactive prompt. The >>> prompt is not where you write programs, it is only for experimenting to find out how features work, or for testing modules. If you want to write a program you should do so as a separate file (perhaps using IDLEs File-New menu) and run it once finished) outside of IDLE. But I may be misunderstanding things. Can you answer the questions above to clarify exactly what you are doing? -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Sun Nov 16 23:41:08 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 16 Nov 2008 22:41:08 -0000 Subject: [Tutor] /not/ instanciating References: <49207B13.506@free.fr> Message-ID: "spir" wrote > I have a type (say: T) which normally receives as main init argument > an object that can be of any other type. Occasionally, this arg > object may precisely be of type T. In this case, for several > reasons, I wish not to "over-instanciate", rather that the > constructor returns the source object unchanged. I did some research > and trials on the topic, and found as sole solution to overload > __new__ as shown below. That's right because new is the constructor. init is the initialiser. They are slightly different concepts which Python makes explicit. > Still, as said in the doc, __init__ was not skipped (what for?), I > need to do it myself. Because creating an object and initialising it are two different steps. > * Is there anything I should pay attention to? You should always be careful of managing resources directly in Python, its very rarely necessary. Kent has suggested an alternative that avoids messing with new... > * Why, then, is __init__ still executed when the instanciated object > is 'manually' returned? What's the use of that feature? Because you may want to control how an object is created but also control how it is initialised. For example you may create it in any of several different ways depending on context (from a file or database, in memory, over a steam) but then want to initialise it with the same data values regardless of how it was created. If you don't want init to do anything you can just use pass... Or if the superclasses don't do anything just leave it out. > * I find this an ugly distorsive practice. Isn't there a more > graceful way not to instanciate? Its very similar to how several other OOP languages work. Lisp, Smalltalk, Objective C to name but 3 all have split creatiion/initialisation. It is a powerful protocol for managing object instantiation. In the vast majority of cases initialisation is all that's needed. > Or to simply return the desired object without caring of > side-effects? The factory method approach suggested by Kent might be better for your needs. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From sierra_mtnview at sbcglobal.net Mon Nov 17 00:23:26 2008 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sun, 16 Nov 2008 15:23:26 -0800 Subject: [Tutor] Python 2.5 on a Win 98 Machine In-Reply-To: <1c2a2c590811160849t4cf2b391n9ab6002c4bacd3ad@mail.gmail.com> References: <491FEAD2.5070701@sbcglobal.net> <1c2a2c590811160500v3cf6b492j63486a630737f493@mail.gmail.com> <492042F1.8060506@sbcglobal.net> <1c2a2c590811160849t4cf2b391n9ab6002c4bacd3ad@mail.gmail.com> Message-ID: <4920AB6E.2010604@sbcglobal.net> An HTML attachment was scrubbed... URL: From kent37 at tds.net Mon Nov 17 02:31:27 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 16 Nov 2008 20:31:27 -0500 Subject: [Tutor] Python 2.5 on a Win 98 Machine In-Reply-To: <4920AB6E.2010604@sbcglobal.net> References: <491FEAD2.5070701@sbcglobal.net> <1c2a2c590811160500v3cf6b492j63486a630737f493@mail.gmail.com> <492042F1.8060506@sbcglobal.net> <1c2a2c590811160849t4cf2b391n9ab6002c4bacd3ad@mail.gmail.com> <4920AB6E.2010604@sbcglobal.net> Message-ID: <1c2a2c590811161731kc3d5ca1l6adbf00bd99f6a67@mail.gmail.com> On Sun, Nov 16, 2008 at 6:23 PM, Wayne Watson wrote: > How does one check for the computability of the two? I would check their respective web sites and mailing lists. Kent From alan.gauld at btinternet.com Mon Nov 17 02:38:28 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 17 Nov 2008 01:38:28 -0000 Subject: [Tutor] Classes and Databases References: <3124be320811130756p2dac86d9y8d591e583df7abd0@mail.gmail.com> <3124be320811131504o76883286l5aaf3a4a07fd1554@mail.gmail.com> Message-ID: "Jojo Mwebaze" wrote > Thanks Allan... we have used CVS for the base system.. but for users > provided functions, we think for having them persistent in the > database.. Thats what I don't understand. I can't think of a single good reason to do that. I can see the point of putting the metadata in a database to allow searches but storing code in a database just seems like making things much harder than it needs be. Why not just store links into the source files? Alan G From kent37 at tds.net Mon Nov 17 12:45:45 2008 From: kent37 at tds.net (Kent Johnson) Date: Mon, 17 Nov 2008 06:45:45 -0500 Subject: [Tutor] Python 2.5 on a Win 98 Machine In-Reply-To: <4920EF34.60804@sbcglobal.net> References: <491FEAD2.5070701@sbcglobal.net> <1c2a2c590811160500v3cf6b492j63486a630737f493@mail.gmail.com> <492042F1.8060506@sbcglobal.net> <1c2a2c590811160849t4cf2b391n9ab6002c4bacd3ad@mail.gmail.com> <4920AB6E.2010604@sbcglobal.net> <1c2a2c590811161731kc3d5ca1l6adbf00bd99f6a67@mail.gmail.com> <4920EF34.60804@sbcglobal.net> Message-ID: <1c2a2c590811170345v4bd3fabeiee91b81b568662b@mail.gmail.com> On Sun, Nov 16, 2008 at 11:12 PM, Wayne Watson wrote: > I'm attaching the screen image the user of the program rcvd. If you'd like > me to place it somewhere that everyone can see it, I'll do so if you provide > the URL. You can copy and paste from the dos prompt, you don't have to post screen shots. > Is there something worthwhile pursing with this screen message? If not, then > I'm just going to turn his problem over to the sponsoring organization, and > let them worry about it. Apparently it is not finding a DLL that it needs, either matplotlib._path or something required by _path. I would look for the _path module, if you have it and it is Python, look at what it imports. Do you have numpy installed on this machine? It is required by matplotlib. What happens if you try to import numpy? Please reply to the list, not to me personally. Kent From Shawn at milochik.com Mon Nov 17 15:20:55 2008 From: Shawn at milochik.com (Shawn Milochik) Date: Mon, 17 Nov 2008 09:20:55 -0500 Subject: [Tutor] Scrolling through output in shell In-Reply-To: References: Message-ID: <2dc0c81b0811170620u4e39ecc1h56f48e7b6dcd7a32@mail.gmail.com> On Sun, Nov 16, 2008 at 1:21 PM, Mike Hoy wrote: > I'm writing a small program that writes to a text file. I want to be > able to view the contents of the text file inside of shell. But the > file is too large for a small shell window. Is there a way for the > user to 'scroll' through the contents of file that has been read into > the program? I noticed that on the man pages that you can do that > although I'm sure it's not written in python. Do I need to find a new > language to write this in? Maybe use a different language for the > output and still use python? Any help appreciated. > > -- > Mike Hoy > http://www.mikehoy.net As Alan has noted, your request isn't perfectly clear. So, I'm going to change your question and answer it. If I picked the wrong question, please be more explicit in your next reply. Question: How can I read a text file from the command line if the file is too large to fit on the screen at once? Answer: more or less If you're in Windows, you can use the more command: more file.txt That will allow you to scroll up and down. If you're on pretty much any other OS, you can use more or less. I prefer less, because it has more features. You use it the same way you use more: less file.txt From malaclypse2 at gmail.com Mon Nov 17 15:58:00 2008 From: malaclypse2 at gmail.com (Jerry Hill) Date: Mon, 17 Nov 2008 09:58:00 -0500 Subject: [Tutor] /not/ instanciating In-Reply-To: <49207B13.506@free.fr> References: <49207B13.506@free.fr> Message-ID: <16651e80811170658i663cf147t9640e9b83d6497e4@mail.gmail.com> On Sun, Nov 16, 2008 at 2:57 PM, spir wrote: > * Why, then, is __init__ still executed when the instanciated object is > 'manually' returned? What's the use of that feature? The manual (http://www.python.org/doc/2.5.2/ref/customization.html) says: "If __new__() returns an instance of cls, then the new instance's __init__() method will be invoked like "__init__(self[, ...])", where self is the new instance and the remaining arguments are the same as were passed to __new__(). " That seems to explain why you're seeing what you're seeing. I don't know how you would avoid that if that's not the behavior you want, though. I suppose you could then repeat your check of the type of source in __init__, just like you did in __new__ to avoid re-initializing. -- Jerry From lhaig at haigmail.com Mon Nov 17 18:27:46 2008 From: lhaig at haigmail.com (Lance Haig) Date: Mon, 17 Nov 2008 17:27:46 +0000 Subject: [Tutor] Convert a text logfile to RSS xml. Message-ID: Hi, I was just thinking how to improve our opensource Website and was wondering if there is an easy way to convert say an IRC logfile to an rss feed using pyton? I was thinking about running the script with cron that will scan the latest logfile for the day and convert it to rss xml std it would overwrite the rss feed file everytime and then when a new day starts the xml file is overwritten. How would you do this? and do you have any suggestions? I was also thinking of importing the logfiles into a small sqllite db and then convertinbg the sqldb into a feed. Regards Lance -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Nov 17 20:27:43 2008 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Mon, 17 Nov 2008 19:27:43 +0000 (GMT) Subject: [Tutor] Scrolling through output in shell Message-ID: <175056.81021.qm@web86701.mail.ird.yahoo.com> Forwarding to the group. Please use Reply All when responding. ----- Original Message ---- From: Mike Hoy To: Alan Gauld > I'm writing a program that reads a text file onto the screen. The text > file is too large to read so I want to be able to scroll through it > with the arrow key or something like that. I am not using GUI. In that case you need to write some screen handling code to do the paging. Ideally that means working out how many lines the screen can display then displaying the data in chunks of that size. Basic screen handling can be as simple as hit return to contnue. But if you want to page up as well then you need a bit more. Here is some pseudo (ie. incomplete and untested) code: data = myfile.readlines() size = 25 ## get real screen length here! top = 0 while True: try: for line in data[top:top+size]: print line key = raw_input("N for Next page, P for Previous page, Q to Quit") if key in 'Nn': top += size elif key in 'Pp': top -= size elif key in 'Qq': break except IndexError: break Obviously you can make the control keys as sophisticated as you want! HTH, Alan G. From mhoy06 at gmail.com Mon Nov 17 20:35:05 2008 From: mhoy06 at gmail.com (Mike Hoy) Date: Mon, 17 Nov 2008 12:35:05 -0700 Subject: [Tutor] Scrolling through output in shell In-Reply-To: <175056.81021.qm@web86701.mail.ird.yahoo.com> References: <175056.81021.qm@web86701.mail.ird.yahoo.com> Message-ID: Ok thanks Alan for looking into it. I'll give it a try. On Mon, Nov 17, 2008 at 12:27 PM, ALAN GAULD wrote: > Forwarding to the group. > Please use Reply All when responding. > > > ----- Original Message ---- > From: Mike Hoy > To: Alan Gauld > > >> I'm writing a program that reads a text file onto the screen. The text >> file is too large to read so I want to be able to scroll through it >> with the arrow key or something like that. I am not using GUI. > > In that case you need to write some screen handling code to > do the paging. Ideally that means working out how many lines > the screen can display then displaying the data in chunks of > that size. Basic screen handling can be as simple as hit return > to contnue. But if you want to page up as well then you need a > bit more. Here is some pseudo (ie. incomplete and untested) code: > > data = myfile.readlines() > size = 25 ## get real screen length here! > top = 0 > > while True: > try: > for line in data[top:top+size]: > print line > key = raw_input("N for Next page, P for Previous page, Q to Quit") > if key in 'Nn': top += size > elif key in 'Pp': top -= size > elif key in 'Qq': break > except IndexError: break > > Obviously you can make the control keys as sophisticated as you want! > > HTH, > > Alan G. > > -- Mike Hoy From eike.welk at gmx.net Tue Nov 18 13:53:31 2008 From: eike.welk at gmx.net (Eike Welk) Date: Tue, 18 Nov 2008 13:53:31 +0100 Subject: [Tutor] Scrolling through output in shell In-Reply-To: <175056.81021.qm@web86701.mail.ird.yahoo.com> References: <175056.81021.qm@web86701.mail.ird.yahoo.com> Message-ID: <200811181353.31919.eike.welk@gmx.net> On Monday 17 November 2008, ALAN GAULD wrote: > > I'm writing a program that reads a text file onto the screen. The > > text file is too large to read so I want to be able to scroll > > through it with the arrow key or something like that. I am not > > using GUI. You could also output the text, and give it to 'less' to display it. This is exactly what 'man' does. You start other programs from python with the 'subprocess' module: http://docs.python.org/library/subprocess.html You could also go the classical Unix way and output the text to standard output (just use print). If necessary you could then give the output to 'less'. Your program(s) would be used in the following fashion: my_program --foo -a -b -c --be-cool --read this-file.txt | less Command line options are parsed with the 'optparse' module: http://docs.python.org/library/optparse.html Kind regards, Eike. From amit.pureenergy at gmail.com Wed Nov 19 12:18:34 2008 From: amit.pureenergy at gmail.com (amit sethi) Date: Wed, 19 Nov 2008 16:48:34 +0530 Subject: [Tutor] sqlite3 lists to database conversion/ using python variables in sqlite3 Message-ID: Hi , i am trying to learn python and this is my first time with any databases . I am using sqlite3 to create a database of my music files and its metadata tags so here is what i wanted to do . Two list one of the attributes and one of their values ,how do i put it in the database.Here is a simple code i think should work but isn't? >>> import sqlite3 >>> conn=sqlite3.connect('/tmp/example2') >>> c = conn.cursor() >>> list1=['hello','hi'] >>> list2=['a','b'] >>>c.execute('''create table ABC(hello text,hi text)''') >>> list1_value= ",".join(list1) >>> list2_value= ",".join(list2) >>> c.execute('''insert into ABC (%s) values (%s)''')%(list1_value,list2_value) This is the error it generates sqlite3.OperationalError: near "%": syntax error why doesn't this work . Can someone please explain A-M-I-T S|S -------------- next part -------------- An HTML attachment was scrubbed... URL: From shantanoo at gmail.com Wed Nov 19 12:48:31 2008 From: shantanoo at gmail.com (=?UTF-8?Q?=E0=A4=B6=E0=A4=82=E0=A4=A4=E0=A4=A8=E0=A5=82_(Shantanoo)?=) Date: Wed, 19 Nov 2008 17:18:31 +0530 Subject: [Tutor] sqlite3 lists to database conversion/ using python variables in sqlite3 In-Reply-To: References: Message-ID: <230174700811190348o216251e3kf39356bfdefd4b13@mail.gmail.com> On Wed, Nov 19, 2008 at 4:48 PM, amit sethi wrote: > Hi , i am trying to learn python and this is my first time with any > databases . I am using sqlite3 to create a database of my music files and > its > metadata tags so here is what i wanted to do . Two list one of the > attributes and one of their values ,how do i put it in the database.Here is > a simple code i think should work but isn't? >>>> import sqlite3 >>>> conn=sqlite3.connect('/tmp/example2') >>>> c = conn.cursor() > >>>> list1=['hello','hi'] >>>> list2=['a','b'] >>>>c.execute('''create table ABC(hello text,hi text)''') >>>> list1_value= ",".join(list1) >>>> list2_value= ",".join(list2) >>>> c.execute('''insert into ABC (%s) values >>>> (%s)''')%(list1_value,list2_value) You may try: c.execute("insert into ABC(%s) values('%s')" % (list1_value, list2_value)) regards, shantanoo -- Fred Allen - "An associate producer is the only guy in Hollywood who will associate with a producer." -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Wed Nov 19 12:48:41 2008 From: kent37 at tds.net (Kent Johnson) Date: Wed, 19 Nov 2008 06:48:41 -0500 Subject: [Tutor] sqlite3 lists to database conversion/ using python variables in sqlite3 In-Reply-To: References: Message-ID: <1c2a2c590811190348w7759c574pc70921387198d5d0@mail.gmail.com> On Wed, Nov 19, 2008 at 6:18 AM, amit sethi wrote: >>>> list1=['hello','hi'] >>>> list2=['a','b'] >>>>c.execute('''create table ABC(hello text,hi text)''') >>>> list1_value= ",".join(list1) >>>> list2_value= ",".join(list2) >>>> c.execute('''insert into ABC (%s) values >>>> (%s)''')%(list1_value,list2_value) The parenthesis are in the wrong place to do what you intend, and the double quotes are not needed. But this is not the right way to do it. You should pass the values separately, not in the sql string. This allows the database program to correctly escape values containing special characters such as quote or comma, and it prevents sql injection attacks. There is probably no reason to put the field names in a list. Try this: c.execute('insert into ABC hello, hi values ?, ?', list2) Notice that list2 is passed as a parameter to execute. Kent From roadierich at googlemail.com Wed Nov 19 14:13:18 2008 From: roadierich at googlemail.com (Richard Lovely) Date: Wed, 19 Nov 2008 13:13:18 +0000 Subject: [Tutor] Help Optimise Code Message-ID: I'm pretty new to code optimisation, so I thought I'd ask you all for advice. I'm making an iterative prime number generator. This is what I've got so far: Code: Select all import math, array def count2(start_at=0): 'Yield every third integer, beginning with start_at' # this has been tested as faster than using itertools.count while True: yield start_at start_at += 2 def iprimes(): 'generate an endless sequence of prime numbers' yield 2 yield 3 yield 5 sqrt = math.sqrt knownPrimes = array.array("L",(3,5)) # 'L' for unsigned long - not tested if using a smaller type is faster for x in count2(7): sqrtX = sqrt(x) # take extra function calls out of the inner loop for p in knownPrimes): test = (not x % p) and -1 or p > sqrtX if test == -1: # (not x % p) == true break elif test: # (p > sqrtX) == true yield x knownPrimes.append(x) break I've tried a the sieve of erath-whatever as in test_generator, implemented using itertools functions, but it hit max recusion depth somewhere before 1000 primes, and I'm after millions of primes. I'm not particularly bothered about startup overheads, just the loops. Quick thought: would the following work (I'm on a public computer without python, so can't test): Code: Select all def iprimes(): 'generate an endless sequence of prime numbers' yield 2 yield 3 yield 5 sqrt = math.sqrt knownPrimes = array.array("L",(3,5)) # 'L' for unsigned long - not tested if using a smaller type is faster for x in count2(7): sqrtX = sqrt(x) # take extra function calls out of the inner loop for test in ((not x % p) and -1 or p > sqrtX for p in knownPrimes)): # a generator _should_ be faster... if test == -1: # (not x % p) == true break elif test: # (p > sqrtX) == true yield x knownPrimes.append(x) break Please don't suggest changing languages. I like python. Although if you want to write an extension for me, and provide the source and a makefile, please feel free. I have a MinGW install that's doing nothing. (Just kidding - almost.) This is NOT homework. -- Richard "Roadie Rich" Lovely, part of the JNP|UK Famile www.theJNP.com From kent37 at tds.net Wed Nov 19 14:39:37 2008 From: kent37 at tds.net (Kent Johnson) Date: Wed, 19 Nov 2008 08:39:37 -0500 Subject: [Tutor] sqlite3 lists to database conversion/ using python variables in sqlite3 In-Reply-To: References: <1c2a2c590811190348w7759c574pc70921387198d5d0@mail.gmail.com> Message-ID: <1c2a2c590811190539u18e9fee9r54ca44e656d1e9fc@mail.gmail.com> On Wed, Nov 19, 2008 at 7:21 AM, amit sethi wrote: > Thanks Kent , very useful reply but the thing is i actually want to use this > in a program that stores ID3 tags and they are broken more usually than not > .. so I actually don't know what keys/attributes i would be sending can I > send attribute list as a parameter? > I believe this is more elegant. >>>>c.execute("insert into Music_tags (%s) values (%s)") %(audio_keys, >>>> audio_values) Again, the parentheses are in the wrong place for this to work. It should be c.execute("insert into Music_tags (%s) values (%s)" % (audio_keys, audio_values)) but I don't recommend this. It's OK to supply the field names by string interpolation, it's the values that should be supplied as a separate sequence. > however i have to use this instead >>>>c.execute("insert into Music_tags (File,Artist,Album,Title,date,Genre) >>>> values(?,?,?,?,?,?)"\ > ,(iter,audio['Artist'].pop() or None,audio['Album'].pop() or > None,audio['Title'].pop() or None,audio['date'].pop() or > None,audio['Genre'].pop() or None)) > > Notice the audio['Artist'].pop() or None > None has to added to account for a case where their are no tags. I don't understand this requirement. If 'Artist' is not present in the audio dict, then audio['Artist'] will raise an exception. So I think there is already a value for Artist. It may be an empty string rather than None, so this would change it to None. I don't know why you need the pop() either. Kent PS Please use Reply All to reply to the list. From kent37 at tds.net Wed Nov 19 14:40:13 2008 From: kent37 at tds.net (Kent Johnson) Date: Wed, 19 Nov 2008 08:40:13 -0500 Subject: [Tutor] sqlite3 lists to database conversion/ using python variables in sqlite3 In-Reply-To: <230174700811190348o216251e3kf39356bfdefd4b13@mail.gmail.com> References: <230174700811190348o216251e3kf39356bfdefd4b13@mail.gmail.com> Message-ID: <1c2a2c590811190540y1854d9ebo4ff4e59d5ef23b12@mail.gmail.com> On Wed, Nov 19, 2008 at 6:48 AM, ????? (Shantanoo) wrote: > You may try: > c.execute("insert into ABC(%s) values('%s')" % (list1_value, list2_value)) This is a bad idea for reasons I gave in a previous email. Kent From kent37 at tds.net Wed Nov 19 14:53:32 2008 From: kent37 at tds.net (Kent Johnson) Date: Wed, 19 Nov 2008 08:53:32 -0500 Subject: [Tutor] Help Optimise Code In-Reply-To: References: Message-ID: <1c2a2c590811190553v36441529uc1acc106631d8dd7@mail.gmail.com> On Wed, Nov 19, 2008 at 8:13 AM, Richard Lovely wrote: > I'm pretty new to code optimisation, so I thought I'd ask you all for advice. > > I'm making an iterative prime number generator. You might be interested in this recipe and discussion: http://code.activestate.com/recipes/366178/ According to Wikipedia, the siev of Atkin is faster than sieve of Eratosthenes: http://en.wikipedia.org/wiki/Sieve_of_Atkin > This is what I've got so far: > test = (not x % p) and -1 or p > sqrtX > if test == -1: # (not x % p) == true > break > elif test: # (p > sqrtX) == true > yield x > knownPrimes.append(x) > break You are duplicating your tests, why not if (not x % p): break elif p > sqrtX: ... ? Kent From lie.1296 at gmail.com Wed Nov 19 22:26:55 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Wed, 19 Nov 2008 21:26:55 +0000 (UTC) Subject: [Tutor] Help Optimise Code References: Message-ID: On Wed, 19 Nov 2008 13:13:18 +0000, Richard Lovely wrote: > I'm pretty new to code optimisation, so I thought I'd ask you all for > advice. > > I'm making an iterative prime number generator. This is what I've got so > far: > > Code: Select all > import math, array > > def count2(start_at=0): > 'Yield every third integer, beginning with start_at' > # this has been > tested as faster than using itertools.count > while True: > yield start_at > start_at += 2 > > def iprimes(): > 'generate an endless sequence of prime numbers' > yield 2 > yield 3 > yield 5 > sqrt = math.sqrt > # 'L' for unsigned long - not tested if > # using a smaller type is faster > knownPrimes = array.array("L",(3,5)) > for x in count2(7): > # take extra function calls out of the inner loop > sqrtX = sqrt(x) > for p in knownPrimes: > test = (not x % p) and -1 or p > sqrtX > if test == -1: # (not > x % p) == true > break > elif test: # (p > sqrtX) == true > yield x > knownPrimes.append(x) > break > Do you know that every prime number is in the form 6*x+1 or 6*x-1, except 2 and 3. This means that instead of checking all odd numbers, you could loop over 6 numbers then yield n - 1 and n + 1. def count6(start): while True: start += 6 yield start - 1 yield start + 1 And I've seen that you generated prime by dividing things up (actually modulus). Division and modulus is the slowest arithmetic operator, avoid it if you can. If you knows the upper bound beforehand, it is faster to use multiplication and an array of fixed size, i.e. "Sieve of Erasthotenes". If you intend to generate primes without known upper bound though, using sieve complexify things up. From lie.1296 at gmail.com Wed Nov 19 22:34:58 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Wed, 19 Nov 2008 21:34:58 +0000 (UTC) Subject: [Tutor] Scrolling through output in shell References: <2dc0c81b0811170620u4e39ecc1h56f48e7b6dcd7a32@mail.gmail.com> Message-ID: On Mon, 17 Nov 2008 09:20:55 -0500, Shawn Milochik wrote: > On Sun, Nov 16, 2008 at 1:21 PM, Mike Hoy wrote: >> I'm writing a small program that writes to a text file. I want to be >> able to view the contents of the text file inside of shell. But the >> file is too large for a small shell window. Is there a way for the user >> to 'scroll' through the contents of file that has been read into the >> program? I noticed that on the man pages that you can do that although >> I'm sure it's not written in python. Do I need to find a new language >> to write this in? Maybe use a different language for the output and >> still use python? Any help appreciated. >> >> -- >> Mike Hoy >> http://www.mikehoy.net > > > > As Alan has noted, your request isn't perfectly clear. So, I'm going to > change your question and answer it. If I picked the wrong question, > please be more explicit in your next reply. > > Question: How can I read a text file from the command line if the file > is too large to fit on the screen at once? > > Answer: more or less > If you're in Windows, you can use the more command: more file.txt That > will allow you to scroll up and down. > > If you're on pretty much any other OS, you can use more or less. I > prefer less, because it has more features. You use it the same way you > use more: less file.txt If that explanations mixing up "more" and "less" as names of programs and more and less for real more and less doesn't confuse you, I think you must already know what "more" and "less" is. "more" and "less" is a pager program, used to provide scroll facility to a file or a stream. Windows only have "more", many Unix-like OS provide both "more" and "less". The most striking difference between "more" and "less" is that "more" is simple forward-only, you can't scroll up, only down. "less" support both backward and forward navigation. As the manpage of "less" explains: 'less - opposite of more' From denis.spir at free.fr Wed Nov 19 23:07:06 2008 From: denis.spir at free.fr (spir) Date: Wed, 19 Nov 2008 23:07:06 +0100 Subject: [Tutor] what do you use @staticmethod for? In-Reply-To: <1c2a2c590811161402p42b3fbc9wa517e7ab265960ae@mail.gmail.com> References: <49207B13.506@free.fr> <1c2a2c590811161402p42b3fbc9wa517e7ab265960ae@mail.gmail.com> Message-ID: <49248E0A.9020605@free.fr> Good night, I have not yet found any use for this feature. Also, I do not really understand the difference with @classmethod, from the programmer's points of view (even if I get the difference on the python side). As I see it, a classmethod is a very ordinary method, except its 'owner' is a type. [But we cannnot express its definition with standard syntax, because it conflicts with instance method definition syntax.] I would be pleased to read your views about staticmethods, and the use cases you have for them -- that could not be done (the same way) with classmethods. Thank you, Denis From alan.gauld at btinternet.com Thu Nov 20 00:58:42 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 19 Nov 2008 23:58:42 -0000 Subject: [Tutor] Scrolling through output in shell References: <2dc0c81b0811170620u4e39ecc1h56f48e7b6dcd7a32@mail.gmail.com> Message-ID: "Lie Ryan" wrote > both "more" and "less". The most striking difference between "more" > and > "less" is that "more" is simple forward-only, you can't scroll up, > only > down. "less" support both backward and forward navigation. On very early Unices that was true but for the last 20 years more has had two direction paging plus searching etc. more also usually supports the v key which takes you into view (which is read-only vi) and some mores even have an e key to take you to the EDITOR. less is like many of the GNU tools an early equivalent to more which grew extra features and some slight inconsistencies. The biggest difference that I find vbetween more and less is that you always have to exit from less whereas more usually exits automatically at the end of file - which is a real pain if you want to go back to the second last page! And for that reason alone I usually use less. (I believe less can also be configured to use the emacs keystrokes rather than the vi keys of more although I've never tried that.) Alan G. From alan.gauld at btinternet.com Thu Nov 20 01:04:44 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 20 Nov 2008 00:04:44 -0000 Subject: [Tutor] what do you use @staticmethod for? References: <49207B13.506@free.fr><1c2a2c590811161402p42b3fbc9wa517e7ab265960ae@mail.gmail.com> <49248E0A.9020605@free.fr> Message-ID: "spir" wrote > I have not yet found any use for this feature. While there are subtle differences I believe the biggest reason for both being present is history. static methods were there first then class methods were added soon after and are slightly more flexible. But statics were kept because people were already using them. Personally I usually use classmethod nowadays. > Also, I do not really understand the difference with @classmethod, > from the programmer's points of view (even if I get the difference > on the python side). > As I see it, a classmethod is a very ordinary method, except its > 'owner' is a type. Which makes it very different to an instance method. instance methods act on instances. class methods act on the entire class - ie they can affect all of the instances or none. You don't need to use class methods(or statics) very often but when you do they are invaluable. The example of a factory method, or a selection method (from a database say), or a cache of instances. All of these can be done elegantly with class methods. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From wescpy at gmail.com Thu Nov 20 01:29:51 2008 From: wescpy at gmail.com (wesley chun) Date: Wed, 19 Nov 2008 16:29:51 -0800 Subject: [Tutor] what do you use @staticmethod for? In-Reply-To: References: <49207B13.506@free.fr> <1c2a2c590811161402p42b3fbc9wa517e7ab265960ae@mail.gmail.com> <49248E0A.9020605@free.fr> Message-ID: <78b3a9580811191629n7d09a53dq65eced789f4df345@mail.gmail.com> On 11/19/08, Alan Gauld wrote: > "spir" wrote > >> I have not yet found any use for this feature. > > Which makes it very different to an instance method. instance > methods act on instances. class methods act on the entire > class - ie they can affect all of the instances or none. > > You don't need to use class methods(or statics) very often > but when you do they are invaluable. the good news is that all of these fancy features are *optional*. if you don't know what they're useful for, that probably means you don't need them yet, so no need to stress that you *have* to learn what they are as you're learning the language. at some point, you'll come across a situation where you *wished* that Python had some feature you wanted, like a function used only in relation to a class or its instances but don't want to define it as an external function (@staticmethod) or to have a method where the class object itself is passed in for you to be able to modify a class value global to all instances (@classmethod), and to discover that features *are* there! cheers, -- 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 From webmaster at mikehoy.net Thu Nov 20 01:43:43 2008 From: webmaster at mikehoy.net (Mike Hoy) Date: Wed, 19 Nov 2008 17:43:43 -0700 Subject: [Tutor] Scrolling through output in shell In-Reply-To: References: <2dc0c81b0811170620u4e39ecc1h56f48e7b6dcd7a32@mail.gmail.com> Message-ID: os.system("cat textfile | less") did the trick, thanks everyone. On Wed, Nov 19, 2008 at 2:34 PM, Lie Ryan wrote: > On Mon, 17 Nov 2008 09:20:55 -0500, Shawn Milochik wrote: > >> On Sun, Nov 16, 2008 at 1:21 PM, Mike Hoy wrote: >>> I'm writing a small program that writes to a text file. I want to be >>> able to view the contents of the text file inside of shell. But the >>> file is too large for a small shell window. Is there a way for the user >>> to 'scroll' through the contents of file that has been read into the >>> program? I noticed that on the man pages that you can do that although >>> I'm sure it's not written in python. Do I need to find a new language >>> to write this in? Maybe use a different language for the output and >>> still use python? Any help appreciated. >>> >>> -- >>> Mike Hoy >>> http://www.mikehoy.net >> >> >> >> As Alan has noted, your request isn't perfectly clear. So, I'm going to >> change your question and answer it. If I picked the wrong question, >> please be more explicit in your next reply. >> >> Question: How can I read a text file from the command line if the file >> is too large to fit on the screen at once? >> >> Answer: more or less >> If you're in Windows, you can use the more command: more file.txt That >> will allow you to scroll up and down. >> >> If you're on pretty much any other OS, you can use more or less. I >> prefer less, because it has more features. You use it the same way you >> use more: less file.txt > > If that explanations mixing up "more" and "less" as names of programs and > more and less for real more and less doesn't confuse you, I think you > must already know what "more" and "less" is. > > "more" and "less" is a pager program, used to provide scroll facility to > a file or a stream. Windows only have "more", many Unix-like OS provide > both "more" and "less". The most striking difference between "more" and > "less" is that "more" is simple forward-only, you can't scroll up, only > down. "less" support both backward and forward navigation. > > As the manpage of "less" explains: 'less - opposite of more' > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Mike Hoy From btkuhn at email.unc.edu Thu Nov 20 09:01:04 2008 From: btkuhn at email.unc.edu (btkuhn at email.unc.edu) Date: Thu, 20 Nov 2008 03:01:04 -0500 Subject: [Tutor] List of lists help Message-ID: <20081120030104.pl1r8n1dkw4k48gs@webmail4.isis.unc.edu> Hello, I am completely baffled by this action and would appreciate any help. My problem is occurring within a class which is within a larger program; if I need to post the entire program let me know and I will. It's only about 250 lines so far. Anyways, I am using a list of lists to store data in a GUI game called goMoku. It is kind of like a connect five game, pretty simple. When a user clicks a certain square, this line is called to store the "move": self.boardarray[row][col] = self.currentPlayer self.currentPlayer is either "White" or "Black" which are constants set to 1 and 2, so that when, say, the black player clicks on row 2 column 4, self.boardarray[2][4] will be set to "2". Instead, the program is setting multiple values within the list as 2. Here is an example output, when I click on (0,0): [[2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], etc. The board is 13X13 and position 0 for each list in the list of lists is being set to 2, while only position 0 in the first list should be changed to 2. To check for errors, I've surrounded the statement by print statements to see what's going on, like this: print self.boardarray print row,col,self.currentPlayer,self.boardarray[row][col] self.boardarray[row][col] = self.currentPlayer print self.boardarray My output is: [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], etc. 0 0 2 0 [[2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], etc. I do not understand what is going on. Everything is as expected except that the extra positions are being assigned as "2". Can anyone suggest what is going wrong? Thanks, Ben From a.t.hofkamp at tue.nl Thu Nov 20 09:28:58 2008 From: a.t.hofkamp at tue.nl (A.T.Hofkamp) Date: Thu, 20 Nov 2008 09:28:58 +0100 Subject: [Tutor] List of lists help In-Reply-To: <20081120030104.pl1r8n1dkw4k48gs@webmail4.isis.unc.edu> References: <20081120030104.pl1r8n1dkw4k48gs@webmail4.isis.unc.edu> Message-ID: <49251FCA.9000108@tue.nl> btkuhn at email.unc.edu wrote: > Hello, > > I am completely baffled by this action and would appreciate any help. My > problem is occurring within a class which is within a larger program; if > I need to post the entire program let me know and I will. It's only > about 250 lines so far. Anyways, I am using a list of lists to store > data in a GUI game called goMoku. It is kind of like a connect five > game, pretty simple. When a user clicks a certain square, this line is > called to store the "move": > > self.boardarray[row][col] = self.currentPlayer The problem is most likely in how you construct your data structure. If you want to post a follow-up with code, extract those lines and see if you can construct the problem in <= 10 lines of code. (any code with more than 15 lines is most likely too large to understand in the time that people take to read a post here) With respect to your problem, a similar problem has been discussed recently at this list with dictionaries instead of lists, please read http://mail.python.org/pipermail/tutor/2008-November/065283.html If it doesn't answer your question, try to re-construct the problem in a small example, and post that. Sincerely, Albert From mail at timgolden.me.uk Thu Nov 20 09:58:34 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 20 Nov 2008 08:58:34 +0000 Subject: [Tutor] what do you use @staticmethod for? In-Reply-To: <49248E0A.9020605@free.fr> References: <49207B13.506@free.fr> <1c2a2c590811161402p42b3fbc9wa517e7ab265960ae@mail.gmail.com> <49248E0A.9020605@free.fr> Message-ID: <492526BA.2080104@timgolden.me.uk> spir wrote: > Good night, > > I have not yet found any use for this feature. > > Also, I do not really understand the difference with @classmethod, from > the programmer's points of view (even if I get the difference on the > python side). > As I see it, a classmethod is a very ordinary method, except its 'owner' > is a type. [But we cannnot express its definition with standard syntax, > because it conflicts with instance method definition syntax.] > > I would be pleased to read your views about staticmethods, and the use > cases you have for them -- that could not be done (the same way) with > classmethods. For me, the difference is a somewhat conceptual one: I use class methods when the operation they're performing is not (possibly cannot be) tied to a specific instance of that class. The canonical application is as a class factory. So I have classmethods called things like .from_string which return an instance of the class which is their first parameter. This will therefore work from subclasses. On the other side of the coin, static methods don't (and can't) even rely on the class they're in so they're not very different from, say, module global functions. I use them if they are in concept a part of whatever functionality the class is offering, but don't (and shouldn't) depend on any instance or any class data. Examples in my own code include a method which returns login sessions from the Windows LSA within an LSA class: you don't need any kind of LSA policy handle to enumerate logons, but it fits conceptually within the idea of an LSA class whose other operations do rely on a policy handle, so I left it there and made it static. HTH TJG From alan.gauld at btinternet.com Thu Nov 20 10:03:07 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 20 Nov 2008 09:03:07 -0000 Subject: [Tutor] List of lists help References: <20081120030104.pl1r8n1dkw4k48gs@webmail4.isis.unc.edu> Message-ID: wrote > > self.boardarray[row][col] = self.currentPlayer > > 4, self.boardarray[2][4] will be set to "2". Instead, the program is > setting multiple values within the list as 2. Here is an example > output, when I click on (0,0): > > [[2, 0, 0, 0, 0], [2, 0, 0, 0, 0], [2, 0, 0, 0, 0], etc. This is almost always caused by you initialising the data wrongly. You have set every item in your list to point to the same sublist. Something like >>> L = [[0,0,0] *3] Now L contains 3 copies of the same list so when you change any one copy it is reflected in all of the other copies. >>> L[0][1] = 6 >>> L [[0,6,0],[0,6,0],[0,6,0]] You can avoid this by constricting the list using a list comprehension (or any of several other solutions) L = [[0,0,0] for n in range(3)] L[0][1] = 7 L [[0, 7, 0], [0, 0, 0], [0, 0, 0]] Remember that Python does everything by references so a = foo b = foo leaves a and b pointing at the same foo object not two copies of foo. The same applies to lists. If you want a copy you need to explicitly make a copy. L1 = [1,2] L2 = L1[:] Now L1 and L2 are two separate lists. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From t.gkikopoulos at dundee.ac.uk Thu Nov 20 12:43:03 2008 From: t.gkikopoulos at dundee.ac.uk (trias) Date: Thu, 20 Nov 2008 03:43:03 -0800 (PST) Subject: [Tutor] import data (txt/csv) into list/array and manipulation In-Reply-To: <1c2a2c590811130942u2da65481g4a504b57cc16773c@mail.gmail.com> References: <20424075.post@talk.nabble.com> <1c2a2c590811101536j63dd545ya6f002ece60fd230@mail.gmail.com> <20435477.post@talk.nabble.com> <20481629.post@talk.nabble.com> <1c2a2c590811130942u2da65481g4a504b57cc16773c@mail.gmail.com> Message-ID: <20599488.post@talk.nabble.com> Hi, so for this part of the problem it goes a bit like this: I have a CSV file (file1) that contains three columns, column one contains a unique ID type str, columns two and three contain start and stop coordinates type int. the other file (file2) contains two columns, column one contains a single coordinate type int and the second column contains a value type float. What I would like to do is for example be able to grab the values from file2 that lies within range defind by the start,stop coordinates associated with an ID from file1. But most importantly I would like to be able to grab say the values from file1 that are from range((start-300),start) for every single ID in file1, I guess plot them in an array and then calculate the sum/ of these values and plot them, ie for ob1 in file get values from range((1025-300),1025), for ob2((1090-300),1090) for ob3((2200-300),2200) and then plot/calculate the sum assuming the have the same start coordinate, so x axis would be (step) values from 0-300 and y axis would be the sum of values from ob1,2,3 for every single step value from 0-300. does this make sense/ cheers http://www.nabble.com/file/p20599488/file1.csv file1.csv http://www.nabble.com/file/p20599488/file2.csv file2.csv Kent Johnson wrote: > > On Thu, Nov 13, 2008 at 9:50 AM, trias wrote: >> PS I could maybe upload a couple of small example flies or a schematic to >> see what I mean > > A small example would be very helpful. Also please subscribe to the list. > > Kent > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- View this message in context: http://www.nabble.com/import-data-%28txt-csv%29-into-list-array-and-manipulation-tp20424075p20599488.html Sent from the Python - tutor mailing list archive at Nabble.com. From madzientist at gmail.com Thu Nov 20 12:54:20 2008 From: madzientist at gmail.com (Suresh Krishna) Date: Thu, 20 Nov 2008 12:54:20 +0100 Subject: [Tutor] first python program to find citeulike duplicates Message-ID: hi everybody, i wrote this to solve the problem of exact duplicate entries in my citeulike library, that i wanted to remove. so i exported my entries in ris format, and then parsed the entries to find exact duplicates based on matching fields. the exact duplicates came about because i uploaded the same RIS file twice to my citeulike library, as a result of the upload being interrupted the first time. it works (i think), but since this is my very first python program, i would really appreciate feedback on how the program could be improved.. thanks much !!!! suresh ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~???? InFileName= "original_library.ris"; INBIBFILE=open(InFileName,'r') OutFileName= "C:/users/skrishna/desktop/library_without_duplicates.ris"; OUTBIBFILE=open(OutFileName,'w') OutDupFileName= "C:/users/skrishna/desktop/library_of_duplicates.ris"; OUTDUPBIBFILE=open(OutDupFileName,'w') current_entry=[] current_keyval=[] current_keys=[] numduplicates=0 for line in INBIBFILE: #large file, so prefer not to use readlines() if not current_entry and line.isspace(): continue #dont write out successive blanks or initial blanks elif current_entry and line.isspace(): #reached a blank that demarcates end of current entry keyvalue=''.join(current_keyval) #generated a key based on certain fields if keyvalue not in current_keys: #is a unique entry current_keys.append(keyvalue) #append current key to list of keys current_entry.append(line) #add the blank line to current entry OUTBIBFILE.writelines(current_entry) #write out to new bib file without duplicates current_entry=[] #clear current entry for next one current_keyval=[] #clear current key else: numduplicates=numduplicates+1 #increment the number of duplicates current_entry.append(line) #add the blank line at end of entry OUTDUPBIBFILE.writelines(current_entry) #write out to list of duplicates file current_entry=[] #clear current entry for next one current_keyval=[] #clear current key elif len(line)>2: #not a blank, so more stuff in currrent entry current_entry.append(line) if line[0:2] in ('TY','JF','EP','TI','SP','KW','AU','PY','UR'): #only if line starts with these fields current_keyval.append(line) #append to current key INBIBFILE.close() OUTBIBFILE.close() OUTDUPBIBFILE.close() print numduplicates From a.t.hofkamp at tue.nl Thu Nov 20 13:47:29 2008 From: a.t.hofkamp at tue.nl (A.T.Hofkamp) Date: Thu, 20 Nov 2008 13:47:29 +0100 Subject: [Tutor] import data (txt/csv) into list/array and manipulation In-Reply-To: <20599488.post@talk.nabble.com> References: <20424075.post@talk.nabble.com> <1c2a2c590811101536j63dd545ya6f002ece60fd230@mail.gmail.com> <20435477.post@talk.nabble.com> <20481629.post@talk.nabble.com> <1c2a2c590811130942u2da65481g4a504b57cc16773c@mail.gmail.com> <20599488.post@talk.nabble.com> Message-ID: <49255C61.5050004@tue.nl> trias wrote: > Hi, > > so for this part of the problem it goes a bit like this: > > I have a CSV file (file1) that contains three columns, column one contains > a unique ID type str, > columns two and three contain start and stop coordinates type int. > the other file (file2) contains two columns, column one contains a single > coordinate type int and the second column contains a value type float. > > What I would like to do is for example be able to grab the values from > file2 that lies within range defind by the start,stop coordinates associated > with an ID from file1. > > But most importantly I would like to be able to grab say the values from > file1 that are from range((start-300),start) for every single ID in file1, I > guess plot them in an array and then calculate the sum/ of these values and > plot them, ie for ob1 in file get values from range((1025-300),1025), for > ob2((1090-300),1090) for ob3((2200-300),2200) and then plot/calculate the > sum assuming the have the same start coordinate, so x axis would be (step) > values from 0-300 and y axis would be the sum of values from ob1,2,3 for > every single step value from 0-300. > > does this make sense/ mostly, although you lost me when you started talking about ranges. Computer programming is often about making small steps at a time (trying to do everything at the same time tends to make yourself get lost in what to do first). In your case, I'd start with reading your first csv file (with the csv Python module) into memory. Once you have done that, get for example a list of start/stop coordinates from the loaded data. Then start loading the second csv file, see how you can find a value, and then a range of values. Once you have done that, you can implement you first objective. After that start thinking about storing in arrays, plotting, etc. Sincerely, Albert From a.t.hofkamp at tue.nl Thu Nov 20 14:44:04 2008 From: a.t.hofkamp at tue.nl (A.T.Hofkamp) Date: Thu, 20 Nov 2008 14:44:04 +0100 Subject: [Tutor] first python program to find citeulike duplicates In-Reply-To: References: Message-ID: <492569A4.1000506@tue.nl> Suresh Krishna wrote: > it works (i think), but since this is my very first python program, i > would really appreciate feedback on how the program could be improved.. First of all, welcome, new Python programmer, My main trouble with the program is lack of structure, some lines deal with individual lines of the input file, while other deal with complete citation-records. I think the program would improve if this is more clearly expressed in the code. One of the reasons that you got the current structure may be due to the use of the 'for line in bibfile' loop, which gives you a new line at only one point in the program. Such a for-loop is good for simple line processing (for each line do ...), but your program has grown beyond that imho. For this reason I'd like to propose to throw out the for-loop, and use a while-loop with three parts instead. For simplicity, I left out the handling of the records (which we can discuss later perhaps) inbibfile = open(InFileName,'r') finished = False while not finished: # Read & skip blank lines while True: line = inbibfile.readline() if len(line) == 0: finished = True break # end of file detected if len(line.rstrip()) > 0: # Line contains non-white-space break # else it was a blank line, skip, read next line if finished: break # line contains the first non-whitespace line of a new record # read the entire record until the next empty line or EOF current_entry = [line] while True: line = inbibfile.readline() if len(line) == 0: finished = True break # Found EOF if len(line.rstrip()) > 0: current_entry.append(line) else: # Found an empty line, finished with current record break # finished reading (empty line or EOF encountered) ## Do something with current_entry # if not finished, do the next record inbibfile.close() You can go further by introducing a few functions: inbibfile = open(InFileName,'r') finished = False while not finished: finished, line = read_blank_lines(inbibfile) if finished: break # line contains the first non-whitespace line of a new record current_entry = make_new_record(line) finished, current_entry = read_record_lines(current_entry, inbibfile) # finished reading (empty line or EOF encountered) ## Do something with current_entry inbibfile.close() and the functions then contain the details of each step. A few comments about your current program: > > > InFileName= "original_library.ris"; In Python, you don't end a line with a ';'. Also, 'InFileName' is a constant, which is normally given an all-uppercase name. > OUTDUPBIBFILE=open(OutDupFileName,'w') > current_entry=[] > numduplicates=0 One of the most difficult things to do in programming is achieving consistency. Above you have 3 global variables, and you use several different way of writing their names. You should try to write them the same. The big advantage of consistent names is that just by looking at a name you know what kind of thing it is, which reduces the chance of making errors in your program. (Don't feel bad about it, this seems a very simple and obvious problem but in fact it is very hard to achieve, especially for larger programs and projects with several people). > if keyvalue not in current_keys: #is a unique entry > current_keys.append(keyvalue) #append current key to list of > keys > current_entry.append(line) #add the blank line to current entry > OUTBIBFILE.writelines(current_entry) #write out to new bib > file without duplicates > current_entry=[] #clear current entry for next one > current_keyval=[] #clear current key Look at the code of each line above, then look at the comment at the same line. What does the comment tell you that the code didn't? > continue #dont write out successive blanks or initial blanks > elif current_entry and line.isspace(): #reached a blank that demarcates end of current entry > keyvalue=''.join(current_keyval) #generated a key based on certain fields > elif len(line)>2: #not a blank, so more stuff in currrent entry Now do the same here. You see the difference? In the first lines you repeat your code in words. In the second lines, you tell what you aim to achieve at that line, ie WHY do you do what you are doing rather than just WHAT does the line do (since that is already defined in the code). In general, there is no need to comment each line. You may also assume that the reader knows Python (otherwise there is little value for him reading the code). Try to make 'blocks' of code with one or more empty lines in between (see my example code), and write a comment what that block as a whole aims to do. Hope I didn't critize you too much. For a first Python program it is quite nice. Sincerely, Albert From sruiz at canterburyschool.org Thu Nov 20 15:26:35 2008 From: sruiz at canterburyschool.org (=?ISO-8859-1?Q?=22Sim=F3n_A=2E_Ruiz=22?=) Date: Thu, 20 Nov 2008 09:26:35 -0500 Subject: [Tutor] Scrolling through output in shell In-Reply-To: References: <2dc0c81b0811170620u4e39ecc1h56f48e7b6dcd7a32@mail.gmail.com> Message-ID: <4925739B.2030602@canterburyschool.org> Lie Ryan wrote: > As the manpage of "less" explains: 'less - opposite of more' I've always heard it explained that "more" is the original paging program of UNIX, and when a new pager was created (by GNU?) they named it "less" because, as we all know, "less is more"[1]. Sim?n [1] http://www.phrases.org.uk/meanings/226400.html (for those to whom English is not a primary language, or just anyone who doesn't get the "joke".) From sruiz at canterburyschool.org Thu Nov 20 15:26:30 2008 From: sruiz at canterburyschool.org (=?ISO-8859-1?Q?=22Sim=F3n_A=2E_Ruiz=22?=) Date: Thu, 20 Nov 2008 09:26:30 -0500 Subject: [Tutor] Scrolling through output in shell In-Reply-To: References: <2dc0c81b0811170620u4e39ecc1h56f48e7b6dcd7a32@mail.gmail.com> Message-ID: <49257396.2000507@canterburyschool.org> Lie Ryan wrote: > As the manpage of "less" explains: 'less - opposite of more' I've always heard it explained that "more" is the original paging program of UNIX, and when a new pager was created (by GNU?) they named it "less" because, as we all know, "less is more"[1]. Sim?n [1] http://www.phrases.org.uk/meanings/226400.html (for those to whom English is not a primary language, or just anyone who doesn't get the "joke".) From metolone+gmane at gmail.com Thu Nov 20 16:54:40 2008 From: metolone+gmane at gmail.com (Mark Tolonen) Date: Thu, 20 Nov 2008 07:54:40 -0800 Subject: [Tutor] List of lists help References: <20081120030104.pl1r8n1dkw4k48gs@webmail4.isis.unc.edu> Message-ID: "Alan Gauld" wrote in message news:gg394h$k1f$1 at ger.gmane.org... [snip] > Something like > >>>> L = [[0,0,0] *3] I think you meant: >>> [[0,0,0]]*3 [[0, 0, 0], [0, 0, 0], [0, 0, 0]] -Mark > > Now L contains 3 copies of the same list so when you change > any one copy it is reflected in all of the other copies. > >>>> L[0][1] = 6 >>>> L > [[0,6,0],[0,6,0],[0,6,0]] From denis.spir at free.fr Thu Nov 20 17:20:03 2008 From: denis.spir at free.fr (spir) Date: Thu, 20 Nov 2008 17:20:03 +0100 Subject: [Tutor] [Fwd: Re: what do you use @staticmethod for?] Message-ID: <49258E33.5050003@free.fr> [forwarded to the list] Thank you for your answers. I found Tim's example below especially helpful. Still, I am a bit surprised. Would you agree with the following: -1- Methods are usually defined as functions "bound to" an object, often called 'owner', meaning especially that the object is then available from insidethe method for operations to apply on it, or with it. Static methods aren't bound, no object is passed as arg, so they are not methods in fact. Simply the calling syntax looks like a method call because of the prefix. From this point of view, static methods may alternatively be called "class functions" instead. -2- The differences between a standard function (defined e.g. at module level) and a static method are that the latter is defined inside a class's scope, and called using the class name as prefix. This can be appropriate, or even relevant, for the developper or reader. -3- Semantically speaking: at the process/python level, there is no real difference, behind the scene a static method actually is a function. At the programmer's level, defining a static method is (can be) meaningful, for it matches the problem, his/her point of view, or design choice. In short: it makes sense. If this is True ;-), then it is the first Python feature I notice that simply exists for such a (relevant, imo) reason. Now, I will probably find many appropriate use cases for static methods. Denis Tim Golden a ?crit : > spir wrote: >> Good night, >> >> I have not yet found any use for this feature. >> >> Also, I do not really understand the difference with @classmethod, >> from the programmer's points of view (even if I get the difference on >> the python side). >> As I see it, a classmethod is a very ordinary method, except its >> 'owner' is a type. [But we cannnot express its definition with >> standard syntax, because it conflicts with instance method definition >> syntax.] >> >> I would be pleased to read your views about staticmethods, and the use >> cases you have for them -- that could not be done (the same way) with >> classmethods. > > For me, the difference is a somewhat conceptual one: I use class methods > when the operation they're performing is not (possibly cannot be) tied > to a specific instance of that class. The canonical application is as a > class > factory. So I have classmethods called things like .from_string which > return an instance of the class which is their first parameter. This will > therefore work from subclasses. > > On the other side of the coin, static methods don't (and can't) even > rely on the class they're in so they're not very different from, say, > module > global functions. I use them if they are in concept a part of whatever > functionality the class is offering, but don't (and shouldn't) depend on > any instance or any class data. Examples in my own code include a > method which returns login sessions from the Windows LSA within an LSA > class: you don't need any kind of LSA policy handle to enumerate logons, > but it fits conceptually within the idea of an LSA class whose other > operations do rely on a policy handle, so I left it there and made it > static. > > HTH > > TJG From alan.gauld at btinternet.com Thu Nov 20 17:32:23 2008 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Thu, 20 Nov 2008 16:32:23 +0000 (GMT) Subject: [Tutor] what do you use @staticmethod for? Message-ID: <78599.56721.qm@web86704.mail.ird.yahoo.com> Forwarded to group. > Would you mind telling me what you think of the following? > > /Inside/ class definition, conflict may happen between class > an instance attributes. > Non-callable attributes (say, properties) are diffenreciated using the > syntactic convention that instance properties are prefixed with a special > placeholder (usually self) taking the place of future instance name: Its not merely a syntactic convention. self is a very real local variable within the method. It is no different to any other local variable. > For methods, the same convention applies at method call: > * class : Clas.method(args) > * instance : self.method(ergs) > Strangely enough (from my point of view), this nice rule is broken > at method definition: > * class : None expected def method(args) > * instance : def method(self,args) expected def self.method(args) But self is not defined at the class level. It is not just a naming feature, self is a real local variable with a value assigned at call time just like any other function/method parameter. It does not exist outside of a method definition. In fact the self parameter of each method is different: class C: def m1(self): pass def m2(this): pass def m3(xyz): pass self, xyz and this are all independant and equally valid names for the instance reference that will be passed in when the method is called. Indeed the following is perfectly valid code: c = C() C.m3(c) # same as c.m3() > As I see it, the syntax for instance method definition conflicts with 'regular' > class method def. Regular class method definition is not regular. Thats the real issue! We define instance methods far more often thabn class methods so that has been optimised. The class method definition has been simplified as far as possible by the decorator but it is admittedly "differenmt" to the normal function definition protocol. But... > If 'self' (or any other word) would be used as prefix for method def, this would be very irregular. It would not fit well with normal function definition. An instance method definition currently looks exactly like (and operates like) a normal function except its inside a class. It just happens to have some syntactic sugar added to make the calling usage more convenient. > could define class methods normally. We do define them normally but we assign them as class methods as an extra step. Its not the definition of the method that is different its the step of assigning them to be class methods thats awkward. > Additionally, this would allow instance attributes to be present at class > top-level scope, not only inside methods. Which may be good for readibility Perhaps, but would you still allow instanc attributes to be assigned outside of the class definition, for that too is possible: class D: pass d = D() d.foo = 42 # add an attribute to the instance print d.foo > allowing to clearly show for instance objects fields, which presently are > randomly created here and there inside methods. Or as above, outside methods. Object instances are just data structures like any other, so we can add to them at any time once created. > programmers use __init__ as field list declaration by doing false > initialisations: > def __init__(self, arg1): > self.arg1 = arg1 # real init > self.arg2 = 0 # false init 'showing' arg2 Yes, that's a matter of taste, and to a large extent background. Personally I like it but many don't do that. Remember that class methods, and indeed class attributes, are used so rarely that this is simply not an issue for most programmers. If you come from another OOP language it can seem, a bit odd in Python initially but it does have an elegant simplicity that exposes the underlying implementation while retaining ease of use. When you read Python code it's very easy to see how the underlying dictionary upon which classes and objects are built are being used. HTH Alan G From alan.gauld at btinternet.com Thu Nov 20 19:35:45 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 20 Nov 2008 18:35:45 -0000 Subject: [Tutor] List of lists help References: <20081120030104.pl1r8n1dkw4k48gs@webmail4.isis.unc.edu> Message-ID: "Mark Tolonen" wrote >>>>> L = [[0,0,0] *3] > > I think you meant: > >>>> [[0,0,0]]*3 > [[0, 0, 0], [0, 0, 0], [0, 0, 0]] Yes indeed, to much haste and not enough testing! Alan G From dineshbvadhia at hotmail.com Thu Nov 20 22:45:02 2008 From: dineshbvadhia at hotmail.com (Dinesh B Vadhia) Date: Thu, 20 Nov 2008 13:45:02 -0800 Subject: [Tutor] Decimal fixed point representation Message-ID: I'm trying to get my head around the Decimal module to understand how to represent a decimal floating point number as an integer (or integers). Am I barking mad or is this possible? Dinesh -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Thu Nov 20 22:54:46 2008 From: bgailer at gmail.com (bob gailer) Date: Thu, 20 Nov 2008 16:54:46 -0500 Subject: [Tutor] Decimal fixed point representation In-Reply-To: References: Message-ID: <4925DCA6.3040208@gmail.com> Dinesh B Vadhia wrote: > I'm trying to get my head around the Decimal module to understand how > to represent a decimal floating point number as an integer (or integers). Huh? That makes no sense to me! Examples please. -- Bob Gailer Chapel Hill NC 919-636-4239 From alan.gauld at btinternet.com Fri Nov 21 02:03:05 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 21 Nov 2008 01:03:05 -0000 Subject: [Tutor] Decimal fixed point representation References: Message-ID: "Dinesh B Vadhia" wrote > I'm trying to get my head around the Decimal module to > understand how to represent a decimal floating point > number as an integer (or integers). I'm not sure what you mean by that. Is it the use of the Decimal module you are querying? Is it how to represent a ecimal fraction as an integer - ie how to lose the numbers after the point? Is it how to represent it as a common/vulgar fraction eg 1.234 = 1234/1000 Or something else? > Am I barking mad or is this possible? It is possible that you are barking mad I suppose. As to whether what you are asking about decimals is possible, that depends on what you are actually asking :-) Alan G From roadierich at googlemail.com Fri Nov 21 11:46:51 2008 From: roadierich at googlemail.com (Rich Lovely) Date: Fri, 21 Nov 2008 10:46:51 +0000 Subject: [Tutor] Help Optimise Code In-Reply-To: References: Message-ID: On a small side note, the docs say array.array is supposed to be efficient. Testing has shown in this function, a list is faster (at least for x<100000). A set is faster still - at least over the same range on my computer,, but you can't guarantee ordering, which makes it inconsistent - and potentially broken. The version I've got in my original post (using a single variable and short-circuiting logic) is almost twice as fast as the version using two separate tests. I don't know why, so suggestions would be appreciated. I'll add in a version of the count6 function. I must have forgotten that maths lesson. I've just thought of something that might be faster than using mod, but I'll have to wait until I get home to test it. (using a list of itertools.cycle's to produce a true/false from a tuple with prime length, yielding a number iff not any(l[:sqrtX]). No division involved...) If that make no sense to anyone, it makes less sense to me, sounds ok, though... --- Richard "Roadie Rich" Lovely Part of the JNP|UK Famille www.theJNP.com (Sent from my iPod - please allow me a few typos: it's a very small keyboard) On 19 Nov 2008, at 09:26 PM, Lie Ryan wrote: > On Wed, 19 Nov 2008 13:13:18 +0000, Richard Lovely wrote: > >> I'm pretty new to code optimisation, so I thought I'd ask you all for >> advice. >> >> I'm making an iterative prime number generator. This is what I've >> got so >> far: >> >> Code: Select all >> import math, array >> >> def count2(start_at=0): >> 'Yield every third integer, beginning with start_at' >> # this has been >> tested as faster than using itertools.count >> while True: >> yield start_at >> start_at += 2 >> >> def iprimes(): >> 'generate an endless sequence of prime numbers' >> yield 2 >> yield 3 >> yield 5 >> sqrt = math.sqrt >> # 'L' for unsigned long - not tested if >> # using a smaller type is faster >> knownPrimes = array.array("L",(3,5)) >> for x in count2(7): >> # take extra function calls out of the inner loop >> sqrtX = sqrt(x) >> for p in knownPrimes: >> test = (not x % p) and -1 or p > sqrtX >> if test == -1: # (not > x % p) == true >> break >> elif test: # (p > sqrtX) == true >> yield x >> knownPrimes.append(x) >> break >> > > Do you know that every prime number is in the form 6*x+1 or 6*x-1, > except > 2 and 3. This means that instead of checking all odd numbers, you > could > loop over 6 numbers then yield n - 1 and n + 1. > > def count6(start): > while True: > start += 6 > yield start - 1 > yield start + 1 > > And I've seen that you generated prime by dividing things up (actually > modulus). Division and modulus is the slowest arithmetic operator, > avoid > it if you can. If you knows the upper bound beforehand, it is faster > to > use multiplication and an array of fixed size, i.e. "Sieve of > Erasthotenes". If you intend to generate primes without known upper > bound > though, using sieve complexify things up. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From dineshbvadhia at hotmail.com Fri Nov 21 14:22:22 2008 From: dineshbvadhia at hotmail.com (Dinesh B Vadhia) Date: Fri, 21 Nov 2008 05:22:22 -0800 Subject: [Tutor] Decimal fixed point representation Message-ID: Hi Alan That's right, it is the Decimal module I'm trying to understand. And, it is how to represent a decimal floating point number as a common/vulgar fraction eg 1.234 = 1234/1000. How do you do this using the Decimal module? The motivation is to avoid floating point calculations and use integers only (don't ask why!). Cheers! Dinesh -------------------------------------------------------------------------------- Date: Fri, 21 Nov 2008 01:03:05 -0000 From: "Alan Gauld" Subject: Re: [Tutor] Decimal fixed point representation To: tutor at python.org Message-ID: Content-Type: text/plain; format=flowed; charset="iso-8859-1"; reply-type=original "Dinesh B Vadhia" wrote > I'm trying to get my head around the Decimal module to > understand how to represent a decimal floating point > number as an integer (or integers). I'm not sure what you mean by that. Is it the use of the Decimal module you are querying? Is it how to represent a ecimal fraction as an integer - ie how to lose the numbers after the point? Is it how to represent it as a common/vulgar fraction eg 1.234 = 1234/1000 Or something else? > Am I barking mad or is this possible? It is possible that you are barking mad I suppose. As to whether what you are asking about decimals is possible, that depends on what you are actually asking :-) Alan G -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Fri Nov 21 15:32:12 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 21 Nov 2008 09:32:12 -0500 Subject: [Tutor] Decimal fixed point representation In-Reply-To: References: Message-ID: <1c2a2c590811210632y3d53342frf4b515210191e903@mail.gmail.com> On Fri, Nov 21, 2008 at 8:22 AM, Dinesh B Vadhia wrote: > Hi Alan > > That's right, it is the Decimal module I'm trying to understand. And, it is > how to represent a decimal floating point number as a common/vulgar fraction > eg 1.234 = 1234/1000. How do you do this using the Decimal module? The > motivation is to avoid floating point calculations and use integers only > (don't ask why!). Cheers! The Decimal type does not represents numbers as fractions, it represents them as decimal floating point, i.e. a floating point representation using base 10 instead of base 2. A fractions module was introduced in Python 2.6 that does represent numbers as a numerator and denominator: http://docs.python.org/library/fractions.html Kent From amit.pureenergy at gmail.com Fri Nov 21 16:06:01 2008 From: amit.pureenergy at gmail.com (amit sethi) Date: Fri, 21 Nov 2008 20:36:01 +0530 Subject: [Tutor] python reverse engineering tools Message-ID: Can somebody tell me about any python to UML reverse engineering tools . I was trying pynsource but it uses the old opengl namespace (this is what i assume the problem is from what i read from the openGL documentation) and thus it gives an import error from wxPython.ogl import * ImportError: No module named ogl now i tried changing it to (again from documentation) import wx.lib.ogl as ogl but it still does not work. Can somebody tell me what the problem might be . -- A-M-I-T S|S -------------- next part -------------- An HTML attachment was scrubbed... URL: From t.gkikopoulos at dundee.ac.uk Fri Nov 21 16:32:13 2008 From: t.gkikopoulos at dundee.ac.uk (trias) Date: Fri, 21 Nov 2008 07:32:13 -0800 (PST) Subject: [Tutor] import data (txt/csv) into list/array and manipulation In-Reply-To: <49255C61.5050004@tue.nl> References: <20424075.post@talk.nabble.com> <1c2a2c590811101536j63dd545ya6f002ece60fd230@mail.gmail.com> <20435477.post@talk.nabble.com> <20481629.post@talk.nabble.com> <1c2a2c590811130942u2da65481g4a504b57cc16773c@mail.gmail.com> <20599488.post@talk.nabble.com> <49255C61.5050004@tue.nl> Message-ID: <20623480.post@talk.nabble.com> Cool, Does anyone else have any other thoughts on this problem? -- View this message in context: http://www.nabble.com/import-data-%28txt-csv%29-into-list-array-and-manipulation-tp20424075p20623480.html Sent from the Python - tutor mailing list archive at Nabble.com. From bill at celestial.net Fri Nov 21 19:23:14 2008 From: bill at celestial.net (Bill Campbell) Date: Fri, 21 Nov 2008 10:23:14 -0800 Subject: [Tutor] Decimal fixed point representation In-Reply-To: References: Message-ID: <20081121182314.GB31728@ayn.mi.celestial.com> On Fri, Nov 21, 2008, Dinesh B Vadhia wrote: > > That's right, it is the Decimal module I'm trying to understand. And, > it is how to represent a decimal floating point number as a > common/vulgar fraction eg 1.234 = 1234/1000. How do you do this using > the Decimal module? The motivation is to avoid floating point > calculations and use integers only (don't ask why!). Cheers! I can understand why if one is writing accounting applications that have to be accurate to the penny (or whatever in the local currency). Accountants and auditors don't like rounding errors. The accounting system I wrote in the mid-80s, and still use today, is written mostly in C, and handles all monitary calculations in cents in long integers with appropriate input and output routines to make them look to the world as it would expect. There was (is?) a FixedPoint package in python that I use for handling dollar amounts. It came out before the Decimal type, and I am not fixing something that works. The only machines I worked on extensively that handled decimal arithmatic very well were the Burroughs Medium Systems B-2500 through B-4800 which did everything in decimal which made a lot of sense since they were designed primarily to run COBOL accounting applications. Bill -- INTERNET: bill at celestial.com Bill Campbell; Celestial Software LLC URL: http://www.celestial.com/ PO Box 820; 6641 E. Mercer Way Voice: (206) 236-1676 Mercer Island, WA 98040-0820 Fax: (206) 232-9186 Scientists are explorers. Philosophers are tourists. -- Richard Feynman From constantfables at gmail.com Fri Nov 21 19:31:35 2008 From: constantfables at gmail.com (Daniel J Kramer) Date: Fri, 21 Nov 2008 13:31:35 -0500 Subject: [Tutor] python question Message-ID: Hi I have just joined this list. I need some help working on a Python application I am working on. I am working on a quiz game where the users gain points when the answer questions correctly. I have written the skeleton of the quiz with If, Elif and Else statements. it runs perfectly. I am very unclear on how to score points at the end of each round and how to import images. Can anyone help out here or have any ideas on the best way to execute this? I have included a copy of the quiz so you can get an idea of what I am trying to do thank you so much and I look forward to hearing from you soon -- Daniel J Kramer Constant Fables 249 12th st #3 Brooklyn, NY 11215 (h) 347 223 4571 (m) 646 427 7430 -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: test.py Type: application/octet-stream Size: 9147 bytes Desc: not available URL: From kent37 at tds.net Fri Nov 21 20:28:34 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 21 Nov 2008 14:28:34 -0500 Subject: [Tutor] Help Optimise Code In-Reply-To: References: Message-ID: <1c2a2c590811211128i5ccc3410s12fac0553d9bd0e4@mail.gmail.com> On Wed, Nov 19, 2008 at 8:13 AM, Richard Lovely wrote: > Please don't suggest changing languages. I like python. Although if > you want to write an extension for me, and provide the source and a > makefile, please feel free. I have a MinGW install that's doing > nothing. (Just kidding - almost.) Take a look at psyco, Cython, ShedSkin, Pyrex... Kent From alan.gauld at btinternet.com Sat Nov 22 01:47:52 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 22 Nov 2008 00:47:52 -0000 Subject: [Tutor] python reverse engineering tools References: Message-ID: "amit sethi" wrote > Can somebody tell me about any python to UML reverse engineering > tools . I can't help wit the specific but I can give a word of caution on reverse engineering from code to UML - don't expect too much! The problem is that in a dynamic language it is very hard for the reverse engineering to determine types of attributes etc so everything tends to end up pointing at object - the common superclass. That results in class diagrams that are less than meaningful and an unreadable mess of spaghetti pointing to one place. Actually this tends to happen even on well designed static language programs too since most OOP interrfaces should be defined in terms of superclasses. UML to code works well because the designer controls the connectivity in the diagram, code to UML tends to be less successful in my experience (Lisp, Smalltalk and C++) and leaves almost as much work as manually reverse engineering. However if you do find something that works please let us know! -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From david at abbottdavid.com Sat Nov 22 02:36:48 2008 From: david at abbottdavid.com (David) Date: Fri, 21 Nov 2008 20:36:48 -0500 Subject: [Tutor] python question In-Reply-To: References: Message-ID: <49276230.6070104@abbottdavid.com> Daniel J Kramer wrote: > Hi > > I have just joined this list. I need some help working on a Python > application I am working on. I am working on a quiz game where the > users gain points when the answer questions correctly. I have written > the skeleton of the quiz with If, Elif and Else statements. it runs > perfectly. > > I am very unclear on how to score points at the end of each round and > how to import images. > > Can anyone help out here or have any ideas on the best way to execute > this? I have included a copy of the quiz so you can get an idea of what > I am trying to do > > thank you so much and I look forward to hearing from you soon > > -- > Daniel J Kramer > Constant Fables > 249 12th st #3 > Brooklyn, NY 11215 > (h) 347 223 4571 > (m) 646 427 7430 > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor I am new also, but something like; score = 0 # check answer if answer == correct: print "\nRight!", score += 1 else: print "\nWrong.", print "Score:", score, "\n\n" -- Powered by Gentoo GNU/LINUX http://www.linuxcrazy.com From amit.pureenergy at gmail.com Sat Nov 22 05:57:53 2008 From: amit.pureenergy at gmail.com (amit sethi) Date: Sat, 22 Nov 2008 10:27:53 +0530 Subject: [Tutor] python reverse engineering tools In-Reply-To: References: Message-ID: Well actually there was an interesting tool i discovered, Lumpy . http://www.greenteapress.com/thinkpython/swampy/lumpy.html which was developed with the intention of being a teaching tool. Although it would be a nice idea if the people in this list evaluate it and give their response because I as a beginner don't think can comment on its effectiveness. On Sat, Nov 22, 2008 at 6:17 AM, Alan Gauld wrote: > > "amit sethi" wrote > > Can somebody tell me about any python to UML reverse engineering tools . >> > > I can't help wit the specific but I can give a word of caution on > reverse engineering from code to UML - don't expect too much! > > The problem is that in a dynamic language it is very hard > for the reverse engineering to determine types of attributes > etc so everything tends to end up pointing at object - the > common superclass. That results in class diagrams that > are less than meaningful and an unreadable mess of > spaghetti pointing to one place. > > Actually this tends to happen even on well designed > static language programs too since most OOP interrfaces > should be defined in terms of superclasses. UML to code > works well because the designer controls the connectivity > in the diagram, code to UML tends to be less successful > in my experience (Lisp, Smalltalk and C++) and leaves > almost as much work as manually reverse engineering. > > However if you do find something that works please > let us know! > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.freenetpages.co.uk/hp/alan.gauld > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- A-M-I-T S|S -------------- next part -------------- An HTML attachment was scrubbed... URL: From ptmcg at austin.rr.com Sat Nov 22 14:27:31 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Sat, 22 Nov 2008 07:27:31 -0600 Subject: [Tutor] python reverse engineering tools In-Reply-To: References: Message-ID: It's not free, but I have had good success with Enterprise Architect from Sparx Systems (http://www.sparxsystems.com.au/). It will generate class diagrams from Python, C/C++, C#, Java. It also supports the full complement of UML diagrams - sequence diagrams are a special treat when you just drag a message arrow and get a drop-down list of the defined interface on the target object. When you go to their website, they refer to several license levels - here is the Rosetta Stone for figuring out what you want: http://www.sparxsystems.com.au/products/ea/editions.html. The low-end Desktop version is pretty stripped down, you will need to get at least the Pro level to get the reverse engineering feature. (We use the Pro edition at our office.) There is an academic Pro license for US$105, and there is an annual fee for getting updates. We use it at work to generate class diagrams during design, review, and as part of the code handoff to our clients. It's also great for reverse engineering when you get handed an only-partially-documented API, or a big mess of source code. There is also a free trial, so you could download that and try your hand at reverse engineering some Python code - maybe an existing package like PIL or something. Sadly, I've even used it to reverse engineer some of my *own* C# code - it was a project I hadn't touched for about 2 years, and the generated diagrams were a useful memory jogger as to what I had put where. (If you have ever downloaded pyparsing, the included class diagrams were created using EA - by hand, unfortunately, as Python support had not yet been added when I first started creating these diagrams.) -- Paul From kent37 at tds.net Sat Nov 22 14:33:52 2008 From: kent37 at tds.net (Kent Johnson) Date: Sat, 22 Nov 2008 08:33:52 -0500 Subject: [Tutor] python question In-Reply-To: References: Message-ID: <1c2a2c590811220533n39329fb3yd6b486e3c9b5cc32@mail.gmail.com> On Fri, Nov 21, 2008 at 1:31 PM, Daniel J Kramer wrote: > Hi > > I have just joined this list. I need some help working on a Python > application I am working on. I am working on a quiz game where the users > gain points when the answer questions correctly. I have written the > skeleton of the quiz with If, Elif and Else statements. it runs perfectly. > > I am very unclear on how to score points at the end of each round and how to > import images. > > Can anyone help out here or have any ideas on the best way to execute this? > I have included a copy of the quiz so you can get an idea of what I am > trying to do David has given you a hint about scoring points. Images are more difficult because you can't display an image directly in the console, you have to use a GUI toolkit. The EasyGUI buttonbox might do what you need, or provide a starting point for customization: http://easygui.sourceforge.net/tutorial.html#contents_item_9.4 Some tips about your program: Rather than checking for upper- and lower-case versions of the answer, you can convert the answer to lowercase and just check once, for example A11 = raw_input("...") A11 = A11.lower() Do you know about lists and loops yet? Your program would be much simpler if you kept the questions and answers in a list. For each question, you could store question text answer1, answer1 response, answer1 score answer2, answer2 response, answer2 score default response Then your code would just loop over the questions. Kent From ricaraoz at gmail.com Sat Nov 22 15:52:43 2008 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Sat, 22 Nov 2008 11:52:43 -0300 Subject: [Tutor] extend my re Message-ID: <49281CBB.1090607@gmail.com> Hi, I've got a half working re but I can't find a way to give it the final touch. Let's say I have (it would actually be source code file) : >>> import re >>> MyString = """Algo ... Start ... otro ... comment ... otro ... comment ... comment ... otro ... end ... """ >>> MyPattern = re.compile(r'(.*?Start.*?)((comment.*?)*)(comment)(.*?end)', re.S) >>> print MyString Algo Start otro comment otro comment comment otro end >>> print MyPattern.sub(r'\1\2/*\4*/\5', MyString) Algo Start otro comment otro comment /*comment*/ otro end Which is basically ok. I have to find the last "comment" in the block and comment it. But I'd like to comment the whole line, my desired output would be : Algo Start otro comment otro comment /* comment*/ otro end And if there was something after the "comment" I would also like it to be commented : from: comment and something else to : /* comment and something else*/ any help? From sierra_mtnview at sbcglobal.net Sat Nov 22 15:43:12 2008 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sat, 22 Nov 2008 06:43:12 -0800 Subject: [Tutor] Size of Python Console Message-ID: <49281A80.7070105@sbcglobal.net> An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Sat Nov 22 16:13:22 2008 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sat, 22 Nov 2008 07:13:22 -0800 Subject: [Tutor] Size of Python Console In-Reply-To: References: <49281A80.7070105@sbcglobal.net> Message-ID: <49282192.5020404@sbcglobal.net> An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Sat Nov 22 16:24:50 2008 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sat, 22 Nov 2008 07:24:50 -0800 Subject: [Tutor] pylab Failure In-Reply-To: <48F17BBB.4010005@sbcglobal.net> References: <48F17BBB.4010005@sbcglobal.net> Message-ID: <49282442.80208@sbcglobal.net> An HTML attachment was scrubbed... URL: From kent37 at tds.net Sat Nov 22 16:28:50 2008 From: kent37 at tds.net (Kent Johnson) Date: Sat, 22 Nov 2008 10:28:50 -0500 Subject: [Tutor] Size of Python Console In-Reply-To: <49281A80.7070105@sbcglobal.net> References: <49281A80.7070105@sbcglobal.net> Message-ID: <1c2a2c590811220728x369fb54ay7f3e65a9e6ba9cfc@mail.gmail.com> On Sat, Nov 22, 2008 at 9:43 AM, Wayne Watson wrote: > How do I make the console window bigger? On Windows click on the window icon (top left) and pick Properties. There are lots of goodies in there including window size and buffer size (how much the window will scroll). Kent From denis.spir at free.fr Sat Nov 22 16:42:29 2008 From: denis.spir at free.fr (spir) Date: Sat, 22 Nov 2008 16:42:29 +0100 Subject: [Tutor] the sense of brackets Message-ID: <49282865.7040303@free.fr> I have long thought "[]" /simply/ is a list constructor syntax. What do you think of the following? t = "aze" print t, list(t), [t] print list(list(t)), list([t]), [list(t)], [[t]] ==> aze ['a', 'z', 'e'] ['aze'] ['a', 'z', 'e'] ['aze'] [['a', 'z', 'e']] [['aze']] From sierra_mtnview at sbcglobal.net Sat Nov 22 16:52:15 2008 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sat, 22 Nov 2008 07:52:15 -0800 Subject: [Tutor] Size of Python Console In-Reply-To: <1c2a2c590811220728x369fb54ay7f3e65a9e6ba9cfc@mail.gmail.com> References: <49281A80.7070105@sbcglobal.net> <1c2a2c590811220728x369fb54ay7f3e65a9e6ba9cfc@mail.gmail.com> Message-ID: <49282AAF.5030302@sbcglobal.net> An HTML attachment was scrubbed... URL: From ricaraoz at gmail.com Sat Nov 22 19:22:38 2008 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Sat, 22 Nov 2008 15:22:38 -0300 Subject: [Tutor] extend my re In-Reply-To: <7be339f90811220617i4a9b49e1qe77bdcd3bfbac2d9@mail.gmail.com> References: <49281CBB.1090607@gmail.com> <7be339f90811220617i4a9b49e1qe77bdcd3bfbac2d9@mail.gmail.com> Message-ID: <49284DEE.7020203@gmail.com> Marco Catunda wrote: > Ricardo, > > Try this pattern > > MyPattern = re.compile(r'(.*?Start.*?)((^.*?comment.*?)*)(^.*?comment)(.*?end)', > re.S | re.M ) > > Almost did it. But if there was something after and in the same line of the "comment" I want commented it wouldnt be taken. from : comment xxx to : /* comment*/ xxx and I wanted : /* comment xxx*/ But it helped a lot, I finally got : >>> MyPattern = re.compile(r'(.*?Start.*?)((^.*?comment.*?)*)(^.*?comment.*?$)(.*?end)', re.S | re.M ) which did the trick. Thanks a lot Marco! > On Sat, Nov 22, 2008 at 12:52 PM, Ricardo Ar?oz wrote: > >> Hi, I've got a half working re but I can't find a way to give it the >> final touch. >> Let's say I have (it would actually be source code file) : >> >>>>> import re >>>>> MyString = """Algo >>>>> >> ... Start >> ... otro >> ... comment >> ... otro >> ... comment >> ... comment >> ... otro >> ... end >> ... """ >> >>>>> MyPattern = >>>>> >> re.compile(r'(.*?Start.*?)((comment.*?)*)(comment)(.*?end)', re.S) >> >> >>>>> print MyString >>>>> >> Algo >> Start >> otro >> comment >> otro >> comment >> comment >> otro >> end >> >> >>>>> print MyPattern.sub(r'\1\2/*\4*/\5', MyString) >>>>> >> Algo >> Start >> otro >> comment >> otro >> comment >> /*comment*/ >> otro >> end >> >> Which is basically ok. I have to find the last "comment" in the block >> and comment it. But I'd like to comment the whole line, my desired >> output would be : >> Algo >> Start >> otro >> comment >> otro >> comment >> /* comment*/ >> otro >> end >> >> And if there was something after the "comment" I would also like it to >> be commented : >> from: >> comment and something else >> to : >> /* comment and something else*/ >> >> any help? >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> >> > > From alan.gauld at btinternet.com Sat Nov 22 19:27:46 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 22 Nov 2008 18:27:46 -0000 Subject: [Tutor] Size of Python Console References: <49281A80.7070105@sbcglobal.net><1c2a2c590811220728x369fb54ay7f3e65a9e6ba9cfc@mail.gmail.com> <49282AAF.5030302@sbcglobal.net> Message-ID: "Wayne Watson" wrote > is there a way I can begin with something other than the default? > It's an inconvenience to the user to do this every time. Create a shortcut that specifies the window parameters. (use properties and adjust the font and layout tab settings) Distribute the shortcut with the program. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From metolone+gmane at gmail.com Sat Nov 22 20:07:32 2008 From: metolone+gmane at gmail.com (Mark Tolonen) Date: Sat, 22 Nov 2008 11:07:32 -0800 Subject: [Tutor] extend my re References: <49281CBB.1090607@gmail.com> Message-ID: "Ricardo Ar?oz" wrote in message news:49281CBB.1090607 at gmail.com... > Hi, I've got a half working re but I can't find a way to give it the > final touch. > Let's say I have (it would actually be source code file) : >>>> import re >>>> MyString = """Algo > ... Start > ... otro > ... comment > ... otro > ... comment > ... comment > ... otro > ... end > ... """ >>>> MyPattern = > re.compile(r'(.*?Start.*?)((comment.*?)*)(comment)(.*?end)', re.S) > >>>> print MyString > Algo > Start > otro > comment > otro > comment > comment > otro > end > >>>> print MyPattern.sub(r'\1\2/*\4*/\5', MyString) > Algo > Start > otro > comment > otro > comment > /*comment*/ > otro > end > > Which is basically ok. I have to find the last "comment" in the block > and comment it. But I'd like to comment the whole line, my desired > output would be : > Algo > Start > otro > comment > otro > comment > /* comment*/ > otro > end > > And if there was something after the "comment" I would also like it to > be commented : > from: > comment and something else > to : > /* comment and something else*/ > > any help? A quick attempt that works for your example: MyPattern = re.compile(r'(.*?Start.*?)((\n\s*comment.*?)*\n)(\s*comment.*?)(\n.*?end)', re.S) You might look into something like pyparsing instead of a complicated re. -Mark From srilyk at gmail.com Sat Nov 22 20:17:38 2008 From: srilyk at gmail.com (W W) Date: Sat, 22 Nov 2008 13:17:38 -0600 Subject: [Tutor] the sense of brackets In-Reply-To: <49282865.7040303@free.fr> References: <49282865.7040303@free.fr> Message-ID: <333efb450811221117w3915b34bo659c16ef089cbb1b@mail.gmail.com> On Sat, Nov 22, 2008 at 9:42 AM, spir wrote: > I have long thought "[]" /simply/ is a list constructor syntax. > What do you think of the following? > > t = "aze" > print t, list(t), [t] > print list(list(t)), list([t]), [list(t)], [[t]] > ==> > aze ['a', 'z', 'e'] ['aze'] > ['a', 'z', 'e'] ['aze'] [['a', 'z', 'e']] [['aze']] Consider the following: In [1]: list("Hello") Out [1]: ['H', 'e', 'l', 'l', 'e', 'o'] and the list docstring: list() -> new list list(sequence) -> new list initialized from sequence's items so list(list(t)) makes perfect sense: list(t) is ['a', 'z' ,'e'] and list(list(t)) simply creates a new list initialized from that list's items HTH, 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 -------------- next part -------------- An HTML attachment was scrubbed... URL: From denis.spir at free.fr Sat Nov 22 20:39:05 2008 From: denis.spir at free.fr (spir) Date: Sat, 22 Nov 2008 20:39:05 +0100 Subject: [Tutor] python question In-Reply-To: References: Message-ID: <49285FD9.6060308@free.fr> Some comments on your code, after David & Kent: * repetition You have probably noticed that your programm repeats over and over the same pattern, that could be called "process of a question". One major point of programming is precisely to cope with such a repetitive task (this was true even before electronics was invented with mechanical programms!). The trick is to write down the overall pattern, and then use it each time it is needed. It will build a kind of brick that you have to put inside a function to be able to call it. Ask us if you need help or tips for that. * main script There seems to be a kind of script that guides the progression of your quizz (esp. when music comes into play, sic:-)). This, not the repetition of questions, can form the main part of your programm. From there would then be called the question-process function. If there is no real change instead, no progression, then this main prog simply is a loop, as Kent says. You just need to define a way to get out of it! Meaning when/why/how to quit the programm? Both of these points lead you to *structure* your code. Presently your programm is 'flat'; meaning it has not yet a shape that shows off its logic. When a programm is properly organised, then its shape looks like what it does. And it tells the reader -- yourself, first -- about it. * text Get rid of all that mass of text! There are several ways to do that: -1- Give each of your texts a name (Qn,An,...). Use these names to program the logic. Associate a value to all of these names, creating 'constants', at e.g. the head of your programm. -2- Do the same, but in a separate file, called a 'module'. Then import this module at start. If you need help for that, ask. -3- When everything works good, then an interesting challenge may be to make your set of texts be a real text file. Much better to manage and edit. You need to write a fonction that is able to cope with a file, read it, analyse it, properly process the data hidden in it... Denis Daniel J Kramer a ?crit : > Hi > > I have just joined this list. I need some help working on a Python > application I am working on. I am working on a quiz game where the users > gain points when the answer questions correctly. I have written the > skeleton of the quiz with If, Elif and Else statements. it runs perfectly. > > I am very unclear on how to score points at the end of each round and how to > import images. > > Can anyone help out here or have any ideas on the best way to execute this? > I have included a copy of the quiz so you can get an idea of what I am > trying to do > > thank you so much and I look forward to hearing from you soon From denis.spir at free.fr Sat Nov 22 22:58:48 2008 From: denis.spir at free.fr (spir) Date: Sat, 22 Nov 2008 22:58:48 +0100 Subject: [Tutor] the sense of brackets In-Reply-To: <333efb450811221117w3915b34bo659c16ef089cbb1b@mail.gmail.com> References: <49282865.7040303@free.fr> <333efb450811221117w3915b34bo659c16ef089cbb1b@mail.gmail.com> Message-ID: <49288098.4010606@free.fr> W W a ?crit : > On Sat, Nov 22, 2008 at 9:42 AM, spir wrote: > >> I have long thought "[]" /simply/ is a list constructor syntax. >> What do you think of the following? >> >> t = "aze" >> print t, list(t), [t] >> print list(list(t)), list([t]), [list(t)], [[t]] >> ==> >> aze ['a', 'z', 'e'] ['aze'] >> ['a', 'z', 'e'] ['aze'] [['a', 'z', 'e']] [['aze']] > > Consider the following: > In [1]: list("Hello") > Out [1]: ['H', 'e', 'l', 'l', 'e', 'o'] > and the list docstring: > list() -> new list > list(sequence) -> new list initialized from sequence's items > so list(list(t)) makes perfect sense: list(t) is ['a', 'z' ,'e'] and > list(list(t)) simply creates a new list initialized from that list's items > HTH, > Wayne Yep! What surprises me is the behaviour of [] instead. I can understand that list(t) != [t] but [list(t)], [[t]] --> [['a', 'z', 'e']] [['aze']] is a bit strange to me. denis From kent37 at tds.net Sat Nov 22 23:04:16 2008 From: kent37 at tds.net (Kent Johnson) Date: Sat, 22 Nov 2008 17:04:16 -0500 Subject: [Tutor] the sense of brackets In-Reply-To: <49282865.7040303@free.fr> References: <49282865.7040303@free.fr> Message-ID: <1c2a2c590811221404w5f0883b9ic615d24d54944980@mail.gmail.com> On Sat, Nov 22, 2008 at 10:42 AM, spir wrote: > I have long thought "[]" /simply/ is a list constructor syntax. list(x) and [x] are not equivalent, as you have discovered. list(x) requires that x is a sequence - something that can be iterated - and it makes a new list out of the elements of the sequence. If x is not iterable then list(x) is an error; for example In [10]: list(1) TypeError Traceback (most recent call last) /Users/kent/ in () TypeError: 'int' object is not iterable OTOH [x] just takes whatever x is and makes it the single element of a list. Kent From kent37 at tds.net Sat Nov 22 23:07:26 2008 From: kent37 at tds.net (Kent Johnson) Date: Sat, 22 Nov 2008 17:07:26 -0500 Subject: [Tutor] python question In-Reply-To: <49285FD9.6060308@free.fr> References: <49285FD9.6060308@free.fr> Message-ID: <1c2a2c590811221407r6febb57fuc2e2e1d4c1b6ca8e@mail.gmail.com> On Sat, Nov 22, 2008 at 2:39 PM, spir wrote: > -1- Give each of your texts a name (Qn,An,...). Use these names to program > the logic. Associate a value to all of these names, creating 'constants', at > e.g. the head of your programm. > -2- Do the same, but in a separate file, called a 'module'. Then import this > module at start. If you need help for that, ask. If you give names to each separate question you will still end up with a lot of similar code, even if it is just a function call like score += ask_question(Q1, A1A, A1B) Better is to think about structuring the data into lists and processing in a loop. Kent From emmanuel.ruellan at laposte.net Sun Nov 23 00:44:21 2008 From: emmanuel.ruellan at laposte.net (Emmanuel Ruellan) Date: Sun, 23 Nov 2008 00:44:21 +0100 Subject: [Tutor] Regular expression oddity Message-ID: <7296745c0811221544o4d9d97aevd2edc10d48a27aed@mail.gmail.com> Hi tutors! While trying to write a regular expression that would split a string the way I want, I noticed a behaviour I didn't expect. >>> re.findall('.?', 'some text') ['s', 'o', 'm', 'e', ' ', 't', 'e', 'x', 't', ''] Where does the last string, the empty one, come from? I find this behaviour rather annoying: I'm getting one group too many. Regards, Emmanuel From bgailer at gmail.com Sun Nov 23 01:05:50 2008 From: bgailer at gmail.com (bob gailer) Date: Sat, 22 Nov 2008 19:05:50 -0500 Subject: [Tutor] Regular expression oddity In-Reply-To: <7296745c0811221544o4d9d97aevd2edc10d48a27aed@mail.gmail.com> References: <7296745c0811221544o4d9d97aevd2edc10d48a27aed@mail.gmail.com> Message-ID: <49289E5E.9080708@gmail.com> Emmanuel Ruellan wrote: > Hi tutors! > > While trying to write a regular expression that would split a string > the way I want, I noticed a behaviour I didn't expect. > > >>>> re.findall('.?', 'some text') >>>> > ['s', 'o', 'm', 'e', ' ', 't', 'e', 'x', 't', ''] > > Where does the last string, the empty one, come from? > I find this behaviour rather annoying: I'm getting one group too many. > The ? means 0 or 1 occurrence. I think re is matching the null string at the end. Drop the ? and you'll get what you want. Of course you can get the same thing using list('some text') at lower cost. -- Bob Gailer Chapel Hill NC 919-636-4239 From sierra_mtnview at sbcglobal.net Sun Nov 23 09:49:55 2008 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sun, 23 Nov 2008 00:49:55 -0800 Subject: [Tutor] Size of Python Console In-Reply-To: References: <49281A80.7070105@sbcglobal.net><1c2a2c590811220728x369fb54ay7f3e65a9e6ba9cfc@mail.gmail.com> <49282AAF.5030302@sbcglobal.net> Message-ID: <49291933.3000206@sbcglobal.net> An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sun Nov 23 10:05:37 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 23 Nov 2008 09:05:37 -0000 Subject: [Tutor] Size of Python Console References: <49281A80.7070105@sbcglobal.net><1c2a2c590811220728x369fb54ay7f3e65a9e6ba9cfc@mail.gmail.com> <49282AAF.5030302@sbcglobal.net> <49291933.3000206@sbcglobal.net> Message-ID: "Wayne Watson" wrote > find away to set the size. One just brings up the program > and sets the width-height using the properties option in the > upper-left corner. Next one saves them when exiting. That only works on your PC, any other user needs to do the same thing. Creating a shortcut means you can redistribute it and the recipient gets whatever settings you set. The shortcut needs to be to python.exe not the program file. Thus if your script is C:\MYSCRIPT\FOO.PY and Python is in C:\Python25\python25.exe you need a shortcut to C:\Python25\python25.exe C:\MYSCRIPT\FOO.PY That should then have all the usual console properties. If you build an installer to install the program at some other location then you can write a WSH script to create a shortcut programmatically at install time, but thats more tricky. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From roka100 at gmail.com Sun Nov 23 13:02:52 2008 From: roka100 at gmail.com (Jia Lu) Date: Sun, 23 Nov 2008 21:02:52 +0900 Subject: [Tutor] (no subject) Message-ID: <9a1e512f0811230402q2babe603p65cbd98173e19a0d@mail.gmail.com> -------------- next part -------------- An HTML attachment was scrubbed... URL: From ldl08 at gmx.net Sun Nov 23 12:37:09 2008 From: ldl08 at gmx.net (David) Date: Sun, 23 Nov 2008 19:37:09 +0800 Subject: [Tutor] faulty code (maths) Message-ID: <49294065.7010704@gmx.net> Hello everybody, I recently came across a book by Prof. Langtangen: Indroduction to Computer Programming: http://folk.uio.no/hpl/INF1100/INF1100-ebook-Aug08.pdf I am trying to solve exercise 1.18 ("Why does the following program not work correctly?"), but I don't find the mistake: why does the line q = sqrt(b*b - 4*a*c) cause an error? I was playing around with the code, but got nowhere. Here the entire code: a = 2; b = 1; c = 2 from math import sqrt q = sqrt(b*b - 4*a*c) x1 = (-b + q)/2*a x2 = (-b - q)/2*a print x1, x2 Many thanks for a pointer! David From kent37 at tds.net Sun Nov 23 13:53:04 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 23 Nov 2008 07:53:04 -0500 Subject: [Tutor] faulty code (maths) In-Reply-To: <49294065.7010704@gmx.net> References: <49294065.7010704@gmx.net> Message-ID: <1c2a2c590811230453g47d6f74bq2581fdd5f26bbeac@mail.gmail.com> On Sun, Nov 23, 2008 at 6:37 AM, David wrote: > I am trying to solve exercise 1.18 ("Why does the following program not work > correctly?"), but I don't find the mistake: why does the line > > q = sqrt(b*b - 4*a*c) > > cause an error? I was playing around with the code, but got nowhere. Did you get an error? What was it? Please show the entire error message, including the stack trace, when you have a question about an error. What is the value of (b*b - 4*a*c) ? Does that give you a hint? Kent From denis.spir at free.fr Sun Nov 23 13:23:22 2008 From: denis.spir at free.fr (spir) Date: Sun, 23 Nov 2008 13:23:22 +0100 Subject: [Tutor] Regular expression oddity In-Reply-To: <49289E5E.9080708@gmail.com> References: <7296745c0811221544o4d9d97aevd2edc10d48a27aed@mail.gmail.com> <49289E5E.9080708@gmail.com> Message-ID: <49294B3A.2090000@free.fr> bob gailer a ?crit : > Emmanuel Ruellan wrote: >> Hi tutors! >> >> While trying to write a regular expression that would split a string >> the way I want, I noticed a behaviour I didn't expect. >> >> >>>>> re.findall('.?', 'some text') >>>>> >> ['s', 'o', 'm', 'e', ' ', 't', 'e', 'x', 't', ''] >> >> Where does the last string, the empty one, come from? >> I find this behaviour rather annoying: I'm getting one group too many. >> > The ? means 0 or 1 occurrence. I think re is matching the null string at > the end. > > Drop the ? and you'll get what you want. > > Of course you can get the same thing using list('some text') at lower cost. > I find this fully consistent, for your regex means matching * either any char * or no char at all Logically, you first get n chars, then one 'nothing'. Only after that will parsing be stopped because of end of string. Maybe clearer: print re.findall('.?', '') ==> [''] print re.findall('.', '') ==> [] denis From ldl08 at gmx.net Sun Nov 23 14:39:01 2008 From: ldl08 at gmx.net (David) Date: Sun, 23 Nov 2008 21:39:01 +0800 Subject: [Tutor] faulty code (maths) In-Reply-To: <1c2a2c590811230453g47d6f74bq2581fdd5f26bbeac@mail.gmail.com> References: <49294065.7010704@gmx.net> <1c2a2c590811230453g47d6f74bq2581fdd5f26bbeac@mail.gmail.com> Message-ID: <49295CF5.3010102@gmx.net> Hello Kent, yes, the error message - sorry: When I just run line 3, I get: In [7]: q = sqrt(b*b - 4*a*c) ...: --------------------------------------------------------------------------- Traceback (most recent call last) /home/david/Documents/Python/myCode/Langtangen/py1st/ in () : math domain error In [8]: Ah! It's a not a Python, but a math error - I am trying to take a root of a negative number! Thanks for the help! David Kent Johnson wrote: > On Sun, Nov 23, 2008 at 6:37 AM, David wrote: > > >> I am trying to solve exercise 1.18 ("Why does the following program not work >> correctly?"), but I don't find the mistake: why does the line >> >> q = sqrt(b*b - 4*a*c) >> >> cause an error? I was playing around with the code, but got nowhere. >> > > Did you get an error? What was it? Please show the entire error > message, including the stack trace, when you have a question about an > error. > > What is the value of (b*b - 4*a*c) ? Does that give you a hint? > > Kent > > From tomar.arun at gmail.com Sun Nov 23 15:09:54 2008 From: tomar.arun at gmail.com (Arun Tomar) Date: Sun, 23 Nov 2008 19:39:54 +0530 Subject: [Tutor] faulty code (maths) In-Reply-To: <49294065.7010704@gmx.net> References: <49294065.7010704@gmx.net> Message-ID: <202c460811230609v12fb7c0q67ebc081092e03e9@mail.gmail.com> hi! On Sun, Nov 23, 2008 at 5:07 PM, David wrote: > Hello everybody, > > I recently came across a book by Prof. Langtangen: Indroduction to Computer > Programming: http://folk.uio.no/hpl/INF1100/INF1100-ebook-Aug08.pdf > > I am trying to solve exercise 1.18 ("Why does the following program not work > correctly?"), but I don't find the mistake: why does the line > > q = sqrt(b*b - 4*a*c) problem here is that the method sqrt doesn't accepts -negative numbers which in this case is the outcome of the expression above. to rectify that u can use the following q = sqrt(math.fabs(b*b - 4*a*c)) basically convert the negative number to absolute number, rest of the stuff will work. > > cause an error? I was playing around with the code, but got nowhere. > > Here the entire code: > > a = 2; b = 1; c = 2 > from math import sqrt > q = sqrt(b*b - 4*a*c) > x1 = (-b + q)/2*a > x2 = (-b - q)/2*a > print x1, x2 > > > Many thanks for a pointer! > > David > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Regards, Arun Tomar blog: http://linuxguy.in From sierra_mtnview at sbcglobal.net Sun Nov 23 15:30:04 2008 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sun, 23 Nov 2008 06:30:04 -0800 Subject: [Tutor] Size of Python Console In-Reply-To: References: <49281A80.7070105@sbcglobal.net><1c2a2c590811220728x369fb54ay7f3e65a9e6ba9cfc@mail.gmail.com> <49282AAF.5030302@sbcglobal.net> <49291933.3000206@sbcglobal.net> Message-ID: <492968EC.7050501@sbcglobal.net> An HTML attachment was scrubbed... URL: From ldl08 at gmx.net Sun Nov 23 15:44:01 2008 From: ldl08 at gmx.net (David) Date: Sun, 23 Nov 2008 22:44:01 +0800 Subject: [Tutor] faulty code (maths) In-Reply-To: <202c460811230609v12fb7c0q67ebc081092e03e9@mail.gmail.com> References: <49294065.7010704@gmx.net> <202c460811230609v12fb7c0q67ebc081092e03e9@mail.gmail.com> Message-ID: <49296C31.1070603@gmx.net> Hello, yes, that did the trick, though I had to change the "from math import ~" line to "import math". I also changed in line three the sqrt() function to math.sqrt(). Otherwise there would be complaints: : name 'sqrt' is not defined WARNING: Failure executing file: The working code: a = 2; b = 1; c = 2 import math q = math.sqrt(math.fabs(b*b - 4*a*c)) x1 = (-b + q)/2*a x2 = (-b - q)/2*a print x1, x2 Thanks a lot! David Arun Tomar wrote: > hi! > > > On Sun, Nov 23, 2008 at 5:07 PM, David wrote: > >> Hello everybody, >> >> I recently came across a book by Prof. Langtangen: Indroduction to Computer >> Programming: http://folk.uio.no/hpl/INF1100/INF1100-ebook-Aug08.pdf >> >> I am trying to solve exercise 1.18 ("Why does the following program not work >> correctly?"), but I don't find the mistake: why does the line >> >> q = sqrt(b*b - 4*a*c) >> > > problem here is that the method sqrt doesn't accepts -negative numbers > which in this case is the outcome of the expression above. to rectify > that u can use the following > > q = sqrt(math.fabs(b*b - 4*a*c)) > > basically convert the negative number to absolute number, rest of the > stuff will work. > > >> cause an error? I was playing around with the code, but got nowhere. >> >> Here the entire code: >> >> a = 2; b = 1; c = 2 >> from math import sqrt >> q = sqrt(b*b - 4*a*c) >> x1 = (-b + q)/2*a >> x2 = (-b - q)/2*a >> print x1, x2 >> >> >> Many thanks for a pointer! >> >> David >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> >> > > > > From kent37 at tds.net Sun Nov 23 16:10:59 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 23 Nov 2008 10:10:59 -0500 Subject: [Tutor] faulty code (maths) In-Reply-To: <49296C31.1070603@gmx.net> References: <49294065.7010704@gmx.net> <202c460811230609v12fb7c0q67ebc081092e03e9@mail.gmail.com> <49296C31.1070603@gmx.net> Message-ID: <1c2a2c590811230710u2462bc11ye7d3e40c35f136dc@mail.gmail.com> On Sun, Nov 23, 2008 at 9:44 AM, David wrote: > The working code: > > a = 2; b = 1; c = 2 > import math > q = math.sqrt(math.fabs(b*b - 4*a*c)) > x1 = (-b + q)/2*a > x2 = (-b - q)/2*a > print x1, x2 Working in the sense of "completes without an error message and prints a result", anyway. Not working in the sense of "gives the correct answer". Using your code above gives In [17]: print x1, x2 2.87298334621 -4.87298334621 In [18]: a*x1*x1 + b*x1 + c Out[18]: 21.381049961377752 which should be 0. Some quadratic equations do not have a solution in the real numbers, only in complex numbers. You might want to look at cmath.sqrt() which will take the square root of a negative number, giving a complex result. Using the above values for a, b, c: In [19]: import cmath In [20]: cmath.sqrt(b*b - 4*a*c) Out[20]: 3.872983346207417j Kent From eike.welk at gmx.net Sun Nov 23 17:03:57 2008 From: eike.welk at gmx.net (Eike Welk) Date: Sun, 23 Nov 2008 17:03:57 +0100 Subject: [Tutor] [Re: class/type methods/functions] In-Reply-To: <490C8226.4080809@free.fr> References: <490A13E4.5000206@free.fr> <490B0099.90803@tue.nl> <490C8226.4080809@free.fr> Message-ID: <200811231703.58299.eike.welk@gmx.net> Hey Spir! Maybe you should read the book "Design Patterns" from Erich Gamma and the rest of "the gang of four". (A.T.Hofkamp, mentioning its terminology, got me thinking.) You ask complicated questions that normal newbies don't ask, so you should maybe read an advanced book. The book's idea is: There are certain problems in programming that appear frequently (called "design patterns" in the book). These problems can be categorized, and there exist well working solutions for these probelms. Additionally, when programmers adopt a common terminology for those problems, it will be more easy to talk about computer programs. One of those patterns is "factory" which A.T mentioned. Kind regards, Eike. From lie.1296 at gmail.com Sun Nov 23 20:45:18 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Sun, 23 Nov 2008 19:45:18 +0000 (UTC) Subject: [Tutor] faulty code (maths) References: <49294065.7010704@gmx.net> <202c460811230609v12fb7c0q67ebc081092e03e9@mail.gmail.com> Message-ID: On Sun, 23 Nov 2008 19:39:54 +0530, Arun Tomar wrote: > hi! > > > On Sun, Nov 23, 2008 at 5:07 PM, David wrote: >> Hello everybody, >> >> I recently came across a book by Prof. Langtangen: Indroduction to >> Computer Programming: >> http://folk.uio.no/hpl/INF1100/INF1100-ebook-Aug08.pdf >> >> I am trying to solve exercise 1.18 ("Why does the following program not >> work correctly?"), but I don't find the mistake: why does the line >> >> q = sqrt(b*b - 4*a*c) > > problem here is that the method sqrt doesn't accepts -negative numbers > which in this case is the outcome of the expression above. to rectify > that u can use the following > > q = sqrt(math.fabs(b*b - 4*a*c)) > > basically convert the negative number to absolute number, rest of the > stuff will work. > An alternative solution would be to use the sqrt from cmath module, which does handle negative root by outputting complex number: a = 2; b = 1; c = 2 from cmath import sqrt q = sqrt(b*b - 4*a*c) x1 = (-b + q)/2*a x2 = (-b - q)/2*a print x1, x2 output: (-1+3.87298334621j) (-1-3.87298334621j) This would be the most mathematically correct solution without changing what the program _seems_ to meant. However, what the program _actually_ meant, I don't know. Python's math module does not handle complex numbers because many day-to- day scripters doesn't have strong mathematical background to handle complex number, or they simply doesn't need to use complex number, or sometimes complex number solution is -- for their particular problem -- an indication that something is not right. From rschroev_nospam_ml at fastmail.fm Mon Nov 24 09:34:03 2008 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Mon, 24 Nov 2008 09:34:03 +0100 Subject: [Tutor] faulty code (maths) In-Reply-To: <49294065.7010704@gmx.net> References: <49294065.7010704@gmx.net> Message-ID: David schreef: > Hello everybody, > > I recently came across a book by Prof. Langtangen: Indroduction to > Computer Programming: http://folk.uio.no/hpl/INF1100/INF1100-ebook-Aug08.pdf > > I am trying to solve exercise 1.18 ("Why does the following program not > work correctly?"), but I don't find the mistake: why does the line > > q = sqrt(b*b - 4*a*c) > > cause an error? I was playing around with the code, but got nowhere. > > Here the entire code: > > a = 2; b = 1; c = 2 > from math import sqrt > q = sqrt(b*b - 4*a*c) > x1 = (-b + q)/2*a > x2 = (-b - q)/2*a > print x1, x2 > > > Many thanks for a pointer! Apart from the problem of taking the square root of a negative number, there is another problem in the code in the book: to calculate the roots of a * x**2 + b*x + c, there should be parentheses around 2*a in the calculation of x1 and x2: x1 = (-b + q)/(2*a) x2 = (-b - q)/(2*a) Otherwise the code multiplies by a instead while it should instead divide by a. -- The saddest aspect of life right now is that science gathers knowledge faster than society gathers wisdom. -- Isaac Asimov Roel Schroeven From lie.1296 at gmail.com Mon Nov 24 12:04:14 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Mon, 24 Nov 2008 11:04:14 +0000 (UTC) Subject: [Tutor] the sense of brackets References: <49282865.7040303@free.fr> <333efb450811221117w3915b34bo659c16ef089cbb1b@mail.gmail.com> <49288098.4010606@free.fr> Message-ID: On Sat, 22 Nov 2008 22:58:48 +0100, spir wrote: > W W a ?crit : > > On Sat, Nov 22, 2008 at 9:42 AM, spir wrote: > > > >> I have long thought "[]" /simply/ is a list constructor syntax. What > >> do you think of the following? > >> > >> t = "aze" > >> print t, list(t), [t] > >> print list(list(t)), list([t]), [list(t)], [[t]] ==> > >> aze ['a', 'z', 'e'] ['aze'] > >> ['a', 'z', 'e'] ['aze'] [['a', 'z', 'e']] [['aze']] > > > > Consider the following: > > In [1]: list("Hello") > > Out [1]: ['H', 'e', 'l', 'l', 'e', 'o'] and the list docstring: > > list() -> new list > > list(sequence) -> new list initialized from sequence's items so > > list(list(t)) makes perfect sense: list(t) is ['a', 'z' ,'e'] and > > list(list(t)) simply creates a new list initialized from that list's > > items HTH, > > Wayne > > Yep! What surprises me is the behaviour of [] instead. I can understand > that list(t) != [t] > but > [list(t)], [[t]] --> [['a', 'z', 'e']] [['aze']] is a bit strange to me. > what do you expect [] should do on that case? I think it's perfectly reasonable and consistent with the semantic for [] to just simply "enclose" whatever inside it with []s instead of converting an iterable to a list as list() does. From peter at avirtualhome.com Mon Nov 24 17:00:59 2008 From: peter at avirtualhome.com (Peter van der Does) Date: Mon, 24 Nov 2008 11:00:59 -0500 Subject: [Tutor] My horrible looking program needs improvement. Message-ID: <20081124110059.6a3386eb@montecarlo.grandprix.int> I wrote my 1st Python program and it works as I want it to work but ,IMHO, it looks horrible. As to what my program does: It downloads a file from the web, downloads .htaccess and Apache log file from a FTP site, using the IP's from the Apache log it checks if the IP exists in the web-file, if it is it's added to the .htaccess as a deny from. Most actions are logged to file and console. Why I think it looks horrible: Everything is in main(), I would like to use functions but ran into problems with the scope of my variables. The CLI arguments check is just a bunch of IF's Is this the place where somebody could go over my program and give some pointers on how to improve the structure or is there a forum out on the Net that can help me out. If this is the place, how do I show the program, in-line or attached? Thanks in advance. -- Peter van der Does GPG key: E77E8E98 WordPress Plugin Developer http://blog.avirtualhome.com GetDeb Package Builder/GetDeb Site Coder http://www.getdeb.net - Software you want for Ubuntu -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 197 bytes Desc: not available URL: From srilyk at gmail.com Mon Nov 24 19:21:44 2008 From: srilyk at gmail.com (W W) Date: Mon, 24 Nov 2008 12:21:44 -0600 Subject: [Tutor] My horrible looking program needs improvement. In-Reply-To: <20081124110059.6a3386eb@montecarlo.grandprix.int> References: <20081124110059.6a3386eb@montecarlo.grandprix.int> Message-ID: <333efb450811241021l56ae41efteb7f830d39c6ed69@mail.gmail.com> On Mon, Nov 24, 2008 at 10:00 AM, Peter van der Does wrote: > I wrote my 1st Python program and it works as I want it to work but > ,IMHO, it looks horrible. Nothing to be ashamed of, unless you don't mind it looking horrible. The fact that you want a clean program is a good sign! > > Why I think it looks horrible: > Everything is in main(), I would like to use functions but ran into > problems with the scope of my variables. > The CLI arguments check is just a bunch of IF's You would probably benefit from using a class then (especially if you have worries about your "main" program looking clean). You can create global class variables that each of the methods/functions have access to with the self. - for instance In [11]: class IP: ....: address = "192.168.1.1" ....: def printAddress(self): ....: print self.address ....: ....: In [12]: x = IP() In [13]: x.printAddress() 192.168.1.1 --- Then you just declare a new instance of your class (see In[12]) and you have access to all its methods and variables; In [15]: x.address = "127.0.0.1" In [16]: x.printAddress() 127.0.0.1 > Is this the place where somebody could go over my program and give > some pointers on how to improve the structure or is there a forum out > on the Net that can help me out. I don't know about anyone else, but I suspect most people are at least as busy as myself, but perfectly willing to help answer your questions, but I doubt anyone has the time (even if they want) to re-write your program /for/ you, but we'll be glad to help if you get stuck on a problem (or even need pointers on where else to look, if Google or your favourite search engine fails to turn up any information) Using a class should really help clean up your program and help eliminate your scope problems. Here's a nifty little tutorial on python classes: http://www.diveintopython.org/object_oriented_framework/defining_classes.html Give classes a try and see if helps. If you're still having issues or you don't understand something, feel free to ask! HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Nov 24 19:25:56 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 24 Nov 2008 18:25:56 -0000 Subject: [Tutor] My horrible looking program needs improvement. References: <20081124110059.6a3386eb@montecarlo.grandprix.int> Message-ID: > Everything is in main(), I would like to use functions but ran into > problems with the scope of my variables. Did your functions have parameters? Thats usually how to deal with passing names between scopes. > Is this the place where somebody could go over my program Yes. > If this is the place, how do I show the program, in-line or > attached? If its short (<100 lines?) just paste it into a mail - try to preserve formatting please! Otherwise posting it on a web site like pastebin is a good option - provides good formatting and colouring... HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From kent37 at tds.net Mon Nov 24 19:26:40 2008 From: kent37 at tds.net (Kent Johnson) Date: Mon, 24 Nov 2008 13:26:40 -0500 Subject: [Tutor] My horrible looking program needs improvement. In-Reply-To: <20081124110059.6a3386eb@montecarlo.grandprix.int> References: <20081124110059.6a3386eb@montecarlo.grandprix.int> Message-ID: <1c2a2c590811241026n202ce2bewcc84528187d60360@mail.gmail.com> On Mon, Nov 24, 2008 at 11:00 AM, Peter van der Does wrote: > I wrote my 1st Python program and it works as I want it to work but > ,IMHO, it looks horrible. > > Is this the place where somebody could go over my program and give > some pointers on how to improve the structure or is there a forum out > on the Net that can help me out. > > If this is the place, how do I show the program, in-line or attached? Yes, we can help with that. If the program is not too long (maybe 40-50 lines max), in-line or attached is fine. For longer programs you can use something like http://pastebin.com/. The shorter your program is, the more likely someone will read and respond to it - we are all volunteers. You might also consider asking specific questions, for example post a short code snippet and ask how to solve a particular problem. Kent From jeffpeery at yahoo.com Mon Nov 24 20:10:06 2008 From: jeffpeery at yahoo.com (Jeff Peery) Date: Mon, 24 Nov 2008 11:10:06 -0800 (PST) Subject: [Tutor] file locations Message-ID: <905132.96392.qm@web43144.mail.sp1.yahoo.com> Hello, I have a wxapp from which I would like to execute another wxapp. the 'child' wxapp is located in a sub directory of the 'parent' wxapp. The problem I'm having is that I execute the child app from the parent app and it cannot find the modules/images/files etc that it needs because it is looking in the parents directory location and not its own. I want to keep the child wxapp in its own sub directory for organizational purposes, but what is the best way to deal with this problem? thanks, Jeff -------------- next part -------------- An HTML attachment was scrubbed... URL: From srilyk at gmail.com Mon Nov 24 20:21:30 2008 From: srilyk at gmail.com (W W) Date: Mon, 24 Nov 2008 13:21:30 -0600 Subject: [Tutor] file locations In-Reply-To: <905132.96392.qm@web43144.mail.sp1.yahoo.com> References: <905132.96392.qm@web43144.mail.sp1.yahoo.com> Message-ID: <333efb450811241121q1e03cf48qf6e4a6f3eda30b0d@mail.gmail.com> On Mon, Nov 24, 2008 at 1:10 PM, Jeff Peery wrote: > Hello, > I have a wxapp from which I would like to execute another wxapp. the > 'child' wxapp is located in a sub directory of the 'parent' wxapp. The > problem I'm having is that I execute the child app from the parent app and > it cannot find the modules/images/files etc that it needs because it is > looking in the parents directory location and not its own. I want to keep > the child wxapp in its own sub directory for organizational purposes, but > what is the best way to deal with this problem? > > I don't know much (read just about zero) about wxapp, but at first blush I would think you should be able to give an absolute directory for all the modules/images/files, etc. rather than relative. Though I have no clue how you would do that. HTH, good luck, 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 -------------- next part -------------- An HTML attachment was scrubbed... URL: From peter at avirtualhome.com Mon Nov 24 20:21:31 2008 From: peter at avirtualhome.com (Peter van der Does) Date: Mon, 24 Nov 2008 14:21:31 -0500 Subject: [Tutor] My horrible looking program needs improvement. In-Reply-To: <20081124110059.6a3386eb@montecarlo.grandprix.int> References: <20081124110059.6a3386eb@montecarlo.grandprix.int> Message-ID: <20081124142131.57989d7d@montecarlo.grandprix.int> On Mon, 24 Nov 2008 11:00:59 -0500 Peter van der Does wrote: > I wrote my 1st Python program and it works as I want it to work but > ,IMHO, it looks horrible. > > As to what my program does: > It downloads a file from the web, downloads .htaccess and Apache log > file from a FTP site, using the IP's from the Apache log it checks if > the IP exists in the web-file, if it is it's added to the .htaccess as > a deny from. > > Most actions are logged to file and console. > > Why I think it looks horrible: > Everything is in main(), I would like to use functions but ran into > problems with the scope of my variables. > The CLI arguments check is just a bunch of IF's > > Is this the place where somebody could go over my program and give > some pointers on how to improve the structure or is there a forum out > on the Net that can help me out. > > If this is the place, how do I show the program, in-line or attached? > > Thanks in advance. > OK, I put the code here: http://pdoes.pastebin.com/m47109194 Thanks people. -- Peter van der Does GPG key: E77E8E98 WordPress Plugin Developer http://blog.avirtualhome.com GetDeb Package Builder/GetDeb Site Coder http://www.getdeb.net - Software you want for Ubuntu -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 197 bytes Desc: not available URL: From kent37 at tds.net Mon Nov 24 22:43:42 2008 From: kent37 at tds.net (Kent Johnson) Date: Mon, 24 Nov 2008 16:43:42 -0500 Subject: [Tutor] file locations In-Reply-To: <905132.96392.qm@web43144.mail.sp1.yahoo.com> References: <905132.96392.qm@web43144.mail.sp1.yahoo.com> Message-ID: <1c2a2c590811241343k4b5f2bfei9d0303b11ba9475e@mail.gmail.com> On Mon, Nov 24, 2008 at 2:10 PM, Jeff Peery wrote: > Hello, > I have a wxapp from which I would like to execute another wxapp. the 'child' > wxapp is located in a sub directory of the 'parent' wxapp. The problem I'm > having is that I execute the child app from the parent app and it cannot > find the modules/images/files etc that it needs because it is looking in the > parents directory location and not its own. I want to keep the child wxapp > in its own sub directory for organizational If the child app is being run in a separate process, then specify the child dir as the working dir of the process. For example if you are using subprocess.Popen() use the cwd parameter. If the child app is imported and run in the parent process, then you need to add the child dir to sys.path, and not have any duplicate module names between the parent and child directories. Kent From mikem at blazenetme.net Tue Nov 25 01:19:30 2008 From: mikem at blazenetme.net (Mike Meisner) Date: Mon, 24 Nov 2008 19:19:30 -0500 Subject: [Tutor] Open Source database software Message-ID: <26ACFFD49660472CB6E4FA69E87F9DE4@MikePC> Y'all have been so good with suggestions on my programming problems in the past, I wonder if anyone could provide a suggestion on a more general topic. I'd like to get away from using Microsoft Access. I have a number of Access databases to convert. My needs are: 1. A relational database management system for a single user (i.e, I don't need client/server and all the extra baggage that goes with it). The RDMS must be able to handle graphics objects. 2. Open source with a decent track record. 3. A good GUI front end for creating the database, creating forms for user data input, queries, reports, etc. 4. Smart enough to easily read and convert an Access (.mdb) database file. 5. And, everything either in Python or with APIs that Python can easily use. Has anyone used products that would meet my needs? Thanks. Mike -------------- next part -------------- An HTML attachment was scrubbed... URL: From srilyk at gmail.com Tue Nov 25 02:31:53 2008 From: srilyk at gmail.com (W W) Date: Mon, 24 Nov 2008 19:31:53 -0600 Subject: [Tutor] Open Source database software In-Reply-To: <26ACFFD49660472CB6E4FA69E87F9DE4@MikePC> References: <26ACFFD49660472CB6E4FA69E87F9DE4@MikePC> Message-ID: <333efb450811241731s2970ceb6i8d9899e7d33831ef@mail.gmail.com> On Mon, Nov 24, 2008 at 6:19 PM, Mike Meisner wrote: > Y'all have been so good with suggestions on my programming problems in > the past, I wonder if anyone could provide a suggestion on a more general > topic. > 5. And, everything either in Python or with APIs that Python can > easily use. > > Has anyone used products that would meet my needs? > I haven't used anything, but you can connect to mysql databases with python, from what I've read it seems to have all the bells & whistles (and then go ahead and add the ability to do whatever you want/can do with python). I'm sure there are plenty of folks with more experience, but that's something to get you started! HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue Nov 25 10:24:09 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 25 Nov 2008 09:24:09 -0000 Subject: [Tutor] Open Source database software References: <26ACFFD49660472CB6E4FA69E87F9DE4@MikePC> Message-ID: "Mike Meisner" wrote > I'd like to get away from using Microsoft Access. > I have a number of Access databases to convert. The obvious choice would be the OpenOffice DB. I believe it can read Access format - although I've never tried... > 1. A relational database management system for a single user > (i.e, I don't need client/server and all the extra baggage A server based RDBMS is not a lot of extra baggage, especially small ones like Firebird but if you really don't want a server solution then SQLite which comes with Python is file based and good enough for anything but enormous databases. > 3. A good GUI front end for creating the database, > creating forms for user data input, queries, reports, etc. With opensource the GUI tends to be an add on so you get a separate choice over which front end you want. Personally I don't ever use them so can make no comment, I prefer SQL. > Smart enough to easily read and convert an Access > (.mdb) database file. THat is likely to be another tool too. Apart from OpenOffice I don't think the databases typically feature conversion tools. > everything either in Python or with APIs that Python can > easily use. Again SQLite is the obvious choice here but most databases can be accessed from Python via the standard DBAPI and a suitable driver.. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From kent37 at tds.net Tue Nov 25 12:38:08 2008 From: kent37 at tds.net (Kent Johnson) Date: Tue, 25 Nov 2008 06:38:08 -0500 Subject: [Tutor] Open Source database software In-Reply-To: <26ACFFD49660472CB6E4FA69E87F9DE4@MikePC> References: <26ACFFD49660472CB6E4FA69E87F9DE4@MikePC> Message-ID: <1c2a2c590811250338m7d425217l59ace806e20a5783@mail.gmail.com> On Mon, Nov 24, 2008 at 7:19 PM, Mike Meisner wrote: > 3. A good GUI front end for creating the database, creating forms for user > data input, queries, reports, etc. For this you might look at Dabo: http://dabodev.com/ I haven't worked with it myself but some people like it a lot. PostgreSQL has pgAdmin which is very nice for basic admin but not for user applications. Kent From denis.spir at free.fr Tue Nov 25 13:14:12 2008 From: denis.spir at free.fr (spir) Date: Tue, 25 Nov 2008 13:14:12 +0100 Subject: [Tutor] [Fwd: Re: My horrible looking program needs improvement.] Message-ID: <492BEC14.3050907@free.fr> Hello Peter, Your program's structure is rather well designed... with words and whitespace. You just need to export each consistent part of your main() into a specialised section: module, object, function. I would suggest (use the names that make sense for you, not mine): * "Config" class that copes with *all* config. ~ read/store to attributes 'period' args ~ read/store ini file 'access' params ~ ... * "AccessData" class that copes with data -- central thing -- uses config ~ read/store spam ~ read/store htaccess list ~ sort ~ update access list ~ ... * function to output results -- uses data I do not have enough time to help you and properly shape these objects. Still, the AccessData class may look like that. class AccessData(object): ''' blah blah ''' def __init__(self): def update(): ''' this method only if process is always purely sequential & identical -- then may also contain init actions''' self.read_spam(self) self.read_htaccess(self) self.sorted(self) self.updated(self) self.write_to_file def read_spam(self): <...> store on attribute def read_htaccess(self): <...> store on attribute def sorted(self): <...> return sorted def updated(self): <...> return updated? def write_to_file(self): <...> And main() could be (not more!): def main(): ''' blah ''' # config config = Config() config.read_args() # from command line/ optparse config.get_access() # from ini file /ConfigParser # update access data # uses params from config access_data=AccessData() access_data.update() # output: from access_data to ... output() Possibly some of the above proposal is wrong or not the best appropriate -- I did it fast --, then adapt to reality and your taste. I'm rather surprised that you are able to cope with such complicated problem as web access, and not to properly structure your code. Feel free to ask the list for more help on what a class is, or what it is intended for. And why it seems appropriate such alien things in the case of you present code. denis Ps: Are you dutch? From jasdebord at gmail.com Tue Nov 25 13:43:43 2008 From: jasdebord at gmail.com (Jason DeBord) Date: Tue, 25 Nov 2008 13:43:43 +0100 Subject: [Tutor] Leaving PHP for Python Message-ID: Hello All, This is my first message on the mailing list. I am excited to get started developing content / backend for the web with Python. I have a background in PHP, but am convinced that Python is a better, more powerful language. I am on a Windows XP machine and I have been using XAMPP for server, php, mysql... I installed Python 2.5 and mod_python successfully. I can serve pages with .py extension to http://localhost . The following for example: from mod_python import apache def handler(req): req.write("Hello World!") return apache.OK Frankly, I don't understand what is going on in the above. This is a bit different compared to what I am used to. So, my question, would you all please point me to some introductory resources, tutorials, books, that focus on Python programming for the web? I am eventually going to interface with some web services, notably Amazon Web Services. Also, I'd like to write some server side scripts to serve as a backend to some Adobe AIR apps. Any and all advice is extremely appreciated. Thanks for your time! Sincerely, Jason -------------- next part -------------- An HTML attachment was scrubbed... URL: From dfjennings at gmail.com Tue Nov 25 14:12:37 2008 From: dfjennings at gmail.com (Don Jennings) Date: Tue, 25 Nov 2008 08:12:37 -0500 Subject: [Tutor] Leaving PHP for Python In-Reply-To: References: Message-ID: <22ce67f0811250512nba62e6at1f5495aef3a7c3bf@mail.gmail.com> Welcome! I suggest you take a look at django [1]. You'll find that it has documentation [2] and an active developer community [3]. Of course, for your questions about learning python, you've already found a very helpful community : >) Take care, Don [1] http://www.djangoproject.com/ [2] http://docs.djangoproject.com/en/dev/ [3] http://www.djangoproject.com/community/ On 11/25/08, Jason DeBord wrote: > Hello All, > > This is my first message on the mailing list. I am excited to get started > developing content / backend for the web with Python. > > I have a background in PHP, but am convinced that Python is a better, more > powerful language. > > I am on a Windows XP machine and I have been using XAMPP for server, php, > mysql... > > I installed Python 2.5 and mod_python successfully. I can serve pages with > .py extension to http://localhost . > > The following for example: > > from mod_python import apache > > def handler(req): > req.write("Hello World!") > return apache.OK > > Frankly, I don't understand what is going on in the above. This is a bit > different compared to what I am used to. > > So, my question, would you all please point me to some introductory > resources, tutorials, books, that focus on Python programming for the web? I > am eventually going to interface with some web services, notably Amazon Web > Services. Also, I'd like to write some server side scripts to serve as a > backend to some Adobe AIR apps. > > Any and all advice is extremely appreciated. > > Thanks for your time! > > Sincerely, > > Jason > From dfjennings at gmail.com Tue Nov 25 14:13:39 2008 From: dfjennings at gmail.com (Don Jennings) Date: Tue, 25 Nov 2008 08:13:39 -0500 Subject: [Tutor] Leaving PHP for Python In-Reply-To: <22ce67f0811250512nba62e6at1f5495aef3a7c3bf@mail.gmail.com> References: <22ce67f0811250512nba62e6at1f5495aef3a7c3bf@mail.gmail.com> Message-ID: <22ce67f0811250513n1e9bc489mb32efa6abbd95524@mail.gmail.com> Oops, I meant to say that django "has EXCELLENT documentation" Take care, Don On 11/25/08, Don Jennings wrote: > Welcome! I suggest you take a look at django [1]. You'll find that it > has documentation [2] and an active developer community [3]. Of > course, for your questions about learning python, you've already found > a very helpful community : >) > > Take care, > Don > > [1] http://www.djangoproject.com/ > [2] http://docs.djangoproject.com/en/dev/ > [3] http://www.djangoproject.com/community/ > > On 11/25/08, Jason DeBord wrote: >> Hello All, >> >> This is my first message on the mailing list. I am excited to get started >> developing content / backend for the web with Python. >> >> I have a background in PHP, but am convinced that Python is a better, more >> powerful language. >> >> I am on a Windows XP machine and I have been using XAMPP for server, php, >> mysql... >> >> I installed Python 2.5 and mod_python successfully. I can serve pages with >> .py extension to http://localhost . >> >> The following for example: >> >> from mod_python import apache >> >> def handler(req): >> req.write("Hello World!") >> return apache.OK >> >> Frankly, I don't understand what is going on in the above. This is a bit >> different compared to what I am used to. >> >> So, my question, would you all please point me to some introductory >> resources, tutorials, books, that focus on Python programming for the web? >> I >> am eventually going to interface with some web services, notably Amazon >> Web >> Services. Also, I'd like to write some server side scripts to serve as a >> backend to some Adobe AIR apps. >> >> Any and all advice is extremely appreciated. >> >> Thanks for your time! >> >> Sincerely, >> >> Jason >> > From kent37 at tds.net Tue Nov 25 14:22:51 2008 From: kent37 at tds.net (Kent Johnson) Date: Tue, 25 Nov 2008 08:22:51 -0500 Subject: [Tutor] My horrible looking program needs improvement. In-Reply-To: <20081124142131.57989d7d@montecarlo.grandprix.int> References: <20081124110059.6a3386eb@montecarlo.grandprix.int> <20081124142131.57989d7d@montecarlo.grandprix.int> Message-ID: <1c2a2c590811250522l5ab7a686i850e6dedf591325c@mail.gmail.com> On Mon, Nov 24, 2008 at 2:21 PM, Peter van der Does wrote: > On Mon, 24 Nov 2008 11:00:59 -0500 > Peter van der Does wrote: > >> I wrote my 1st Python program and it works as I want it to work but >> ,IMHO, it looks horrible. > OK, I put the code here: > > http://pdoes.pastebin.com/m47109194 I would work on breaking this up into functions. The main problem with this is the need to access the logger. I would make that a module (global) variable so it is accessible to each function without being passed as a parameter. Then some possible functions are - read and parse command line options, returning the options object. (You might want to combine the command-line options and the Config options into a single configuration object that can be passed as a single parameter. A couple of ways to do that: Set the command-line options into the Config object yourself http://www.red-dove.com/python_config.html#integrating-with-command-line-options http://cfgparse.sourceforge.net/ - read the banned IP list, returning spamip - setup FTP, returning the ftp object - fetch the access log - fetch .htaccess - parse the access log, returning ip_list - process the .htaccess file Kent From peter at avirtualhome.com Tue Nov 25 14:28:31 2008 From: peter at avirtualhome.com (Peter van der Does) Date: Tue, 25 Nov 2008 08:28:31 -0500 Subject: [Tutor] My horrible looking program needs improvement. In-Reply-To: <492BE9D3.2020704@free.fr> References: <20081124110059.6a3386eb@montecarlo.grandprix.int> <492AEAE3.6030205@free.fr> <20081124131727.59aa1411@montecarlo.grandprix.int> <492BE9D3.2020704@free.fr> Message-ID: <20081125082831.72a4c9d8@montecarlo.grandprix.int> On Tue, 25 Nov 2008 13:04:35 +0100 spir wrote: > Hello Peter, > > Your program's structure is rather well designed... with words and > whitespace. You just need to export each consistent part of your > main() into a specialised section: module, object, function. I would > suggest (use the names that make sense for you, not mine): > > * "Config" class that copes with *all* config. > ~ read/store to attributes 'period' args > ~ read/store ini file 'access' params > ~ ... > * "AccessData" class that copes with data -- central thing -- uses > config ~ read/store spam > ~ read/store htaccess list > ~ sort > ~ update access list > ~ ... > * function to output results -- uses data > > I do not have enough time to help you and properly shape these > objects. Still, the AccessData class may look like that. > > class AccessData(object): > ''' blah blah > ''' > def __init__(self): > > > def update(): > ''' this method only if process is always > purely sequential & identical > -- then may also contain init actions''' > self.read_spam(self) > self.read_htaccess(self) > self.sorted(self) > self.updated(self) > self.write_to_file > def read_spam(self): > <...> > store on attribute > def read_htaccess(self): > <...> > store on attribute > def sorted(self): > <...> > return sorted > def updated(self): > <...> > return updated? > def write_to_file(self): > <...> > > And main() could be (not more!): > > def main(): > ''' blah ''' > # config > config = Config() > config.read_args() # from command line/ optparse > config.get_access() # from ini file /ConfigParser > # update access data > # uses params from config > access_data=AccessData() > access_data.update() > # output: from access_data to ... > output() > > Possibly some of the above proposal is wrong or not the best > appropriate -- I did it fast -- adapt to reality and your taste. I'm > rather surprised that you are able to cope with such complicated > problem as web access, and not to properly structure your code. > > denis > > Ps: Are you dutch? Thanks Denis, Those are the kind of pointers I was looking for. I wasn't expecting somebody to hand me the solution on a silver platter, as a matter of fact I prefer not to. The structure is more complicated, IMHO, as finding and writing a solution. For me programming is like a spoken language. When learning a new language you learn the words and the basics of the grammar. The Internet is full of dictionaries (programming language reference guides), giving explanations of what functions do but to get to know the grammar you'll have to read good written programs or ask for advice :) because there aren't a lot, if any, sites out there that teach you the grammar. Right now the program is a book for children, the grammar is easy. I prefer to write a bit more complex grammar because if I ever decide to write a bigger program, the kids grammar won't work anymore. Oh and yes I am Dutch, currently living in the US. -- Peter van der Does GPG key: E77E8E98 WordPress Plugin Developer http://blog.avirtualhome.com GetDeb Package Builder/GetDeb Site Coder http://www.getdeb.net - Software you want for Ubuntu -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 197 bytes Desc: not available URL: From bgailer at gmail.com Tue Nov 25 15:17:58 2008 From: bgailer at gmail.com (bob gailer) Date: Tue, 25 Nov 2008 09:17:58 -0500 Subject: [Tutor] Leaving PHP for Python In-Reply-To: References: Message-ID: <492C0916.4040400@gmail.com> Jason DeBord wrote: > Hello All, > > This is my first message on the mailing list. I am excited to get > started developing content / backend for the web with Python. > > I have a background in PHP, but am convinced that Python is a better, > more powerful language. > > I am on a Windows XP machine and I have been using XAMPP for server, > php, mysql... > > I installed Python 2.5 and mod_python successfully. I can serve pages > with .py extension to http://localhost . > > The following for example: > > from mod_python import apache > > def handler(req): > req.write("Hello World!") > return apache.OK > > Frankly, I don't understand what is going on in the above. Exactly what don't you understand. Or ... what DO you understand. There is a lot to explain here. Narrowing it down will make it easier. -- Bob Gailer Chapel Hill NC 919-636-4239 From kent37 at tds.net Tue Nov 25 15:30:32 2008 From: kent37 at tds.net (Kent Johnson) Date: Tue, 25 Nov 2008 09:30:32 -0500 Subject: [Tutor] Leaving PHP for Python In-Reply-To: References: Message-ID: <1c2a2c590811250630u57ee1163uecf8d3a08579c54@mail.gmail.com> On Tue, Nov 25, 2008 at 7:43 AM, Jason DeBord wrote: > The following for example: > > from mod_python import apache > > def handler(req): > req.write("Hello World!") > return apache.OK > > Frankly, I don't understand what is going on in the above. This is a bit > different compared to what I am used to. > > So, my question, would you all please point me to some introductory > resources, tutorials, books, that focus on Python programming for the web? You might start with some general Python tutorials. Try one of these lists, depending on your background: http://wiki.python.org/moin/BeginnersGuide/NonProgrammers http://wiki.python.org/moin/BeginnersGuide/Programmers Presumably you have found the mod_python docs? It has a tutorial also: http://www.modpython.org/live/current/doc-html/ You don't say why you chose mod_python...you should know that writing directly to mod_python is not the most popular method of writing Python web apps. It is fine for something simple but for complex apps you might want to look at one of the Python web frameworks such as Django, TurboGears or web.py. Kent From srilyk at gmail.com Tue Nov 25 15:39:08 2008 From: srilyk at gmail.com (W W) Date: Tue, 25 Nov 2008 08:39:08 -0600 Subject: [Tutor] Leaving PHP for Python In-Reply-To: References: Message-ID: <333efb450811250639y773e565cqcc76de1e64c8fa6a@mail.gmail.com> On Tue, Nov 25, 2008 at 6:43 AM, Jason DeBord wrote: > > The following for example: > > from mod_python import apache > > def handler(req): > req.write("Hello World!") > return apache.OK > > Frankly, I don't understand what is going on in the above. This is a bit > different compared to what I am used to. I don't know if you did much OOP (Object Oriented Programming) in PHP, or anything else, but that's what python does, and does well. There are some tutorials out there that explain what objects really are... but I read somewhere that in python /everything/ is an object, and that's pretty much true to my experience. The line starting with from is similar to an include statement in php. Though what you're doing is including "apache" that happens to be inside the "mod_python" library. The next line: def means you're defining a function (or method, if it's in a class, where it would be def handler(self, req), but that's another story) handler is the name you're calling the function and req is the name of your argument. At this point, it really doesn't matter what req is... it's just a name that will point to (or become a copy of) whatever you pass to it. In this case, you're passing it a class that has the method "write". Consider this example(I'm using the IPython active interpreter, so you see In instead of >>>): In [15]: class foo: ....: def write(self, mystr): ....: print mystr ....: ....: In [17]: def handler(req): ....: req.write("Hello World!") ....: ....: In [18]: x = foo() In [19]: handler(x) Hello World! And then return apache.OK is returning... well, the object "OK" in the apache class. Of course, I've never used mod_python/apache, that's just me applying what I know about python, so I may not be 100% accurate, but I don't think I'm too far off. > So, my question, would you all please point me to some introductory > resources, tutorials, books, that focus on Python programming for the web? I > am eventually going to interface with some web services, notably Amazon Web > Services. Also, I'd like to write some server side scripts to serve as a > backend to some Adobe AIR apps. If you plan on doing much command line/admin type stuff, I'd recommend "Python for Unix and Linux System Adminstration" by Noah Gift & Jeremy M. Jones, available through O'Reilly, at least as one resource (ISBN: 978-0-596-51582-9) Noah spoke at our un-conference in October, and I learned a lot, hence, my recommendation. It does a great job of throwing you into a lot of various administration tasks, which instruction can be applied to (and is also useful for) many other tasks. Definitely check out the links others have provided, they'll be packed full of helpful information, and I hope this helped as well. -Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From bryan.fodness at gmail.com Tue Nov 25 15:41:22 2008 From: bryan.fodness at gmail.com (Bryan Fodness) Date: Tue, 25 Nov 2008 09:41:22 -0500 Subject: [Tutor] accessing list from a string Message-ID: I have a list in a text file that is in the python format., Positions = [2.5,2.8] and would like to grab the values. for line in file('list.txt'): if line == Positions: x1,x2=Positions I know this does not work. Is there a direct way to get my x1 and x2 values. Thanks, Bryan -------------- next part -------------- An HTML attachment was scrubbed... URL: From metolone+gmane at gmail.com Tue Nov 25 15:59:13 2008 From: metolone+gmane at gmail.com (Mark Tolonen) Date: Tue, 25 Nov 2008 06:59:13 -0800 Subject: [Tutor] accessing list from a string References: Message-ID: "Bryan Fodness" wrote in message news:fbf64d2b0811250641i208054f6h2a8f965942b356f0 at mail.gmail.com... > I have a list in a text file that is in the python format., > > Positions = [2.5,2.8] > > and would like to grab the values. > > for line in file('list.txt'): > if line == Positions: > x1,x2=Positions > > I know this does not work. Is there a direct way to get my x1 and x2 > values. >>> line = '[2.5,2.8]' >>> x1,x2 = eval(line) >>> x1,x2 (2.5, 2.7999999999999998) -Mark From a.t.hofkamp at tue.nl Tue Nov 25 16:05:28 2008 From: a.t.hofkamp at tue.nl (A.T.Hofkamp) Date: Tue, 25 Nov 2008 16:05:28 +0100 Subject: [Tutor] accessing list from a string In-Reply-To: References: Message-ID: <492C1438.2000409@tue.nl> Bryan Fodness wrote: > I have a list in a text file that is in the python format., > > Positions = [2.5,2.8] Why do you use Python format for storing data? (Python format is for storing programs, usually) > and would like to grab the values. > > for line in file('list.txt'): > if line == Positions: > x1,x2=Positions > I know this does not work. Is there a direct way to get my x1 and x2 > values. You can import the Python file, then get the value of Positions. import myfile print myfile.Positions You can read the lines from the file, and use regular expression matching to extract the values. That however brings problems like 'what to do when there are more such lines', or 'what to do if there are 3 numbers instead of 2' In general, it is much easier to use a different file format for storing such information, eg you could use a .ini file format instead, and use the ConfigParser module to load it. Sincerely, Albert From marc.tompkins at gmail.com Tue Nov 25 18:33:03 2008 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Tue, 25 Nov 2008 09:33:03 -0800 Subject: [Tutor] Open Source database software In-Reply-To: <26ACFFD49660472CB6E4FA69E87F9DE4@MikePC> References: <26ACFFD49660472CB6E4FA69E87F9DE4@MikePC> Message-ID: <40af687b0811250933m46e31afs522aede78dbfd402@mail.gmail.com> On Mon, Nov 24, 2008 at 4:19 PM, Mike Meisner wrote: > I'd like to get away from using Microsoft Access. I have a number of > Access databases to convert. > There's an open source package out there called "mdbtools", specifically for working with Access databases. The Python port (or wrapper? I don't really know) of it can be found here: http://www.parit.ca/software/pscproject.2008-04-21.9636009485 I've never used it, so don't know whether it would be a stable long-term way to work with MDB files, or whether it would be best to write a one-time conversion to a different format... -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Tue Nov 25 18:38:19 2008 From: kent37 at tds.net (Kent Johnson) Date: Tue, 25 Nov 2008 12:38:19 -0500 Subject: [Tutor] python question In-Reply-To: References: <1c2a2c590811220533n39329fb3yd6b486e3c9b5cc32@mail.gmail.com> Message-ID: <1c2a2c590811250938x49a8c22ciad05563e2f955975@mail.gmail.com> On Tue, Nov 25, 2008 at 11:52 AM, Daniel J Kramer wrote: > Hi Kent > > I have been playing with the ,lower command and am not having much luck. It > seems like a simple task, but it is not working for me. Here is the code > > def main(): > score = 0 > print"Welcome to the Music Quiz. Today's game has 8 rounds for you. > There will be audio rounds, visual rounds and straight ahead qustions. We > will begin with the round Journey to the Centre of New York" > print > A11 = raw_input ("We see the Ramones on the Bowery with rolled up > towels under their arms chewing out a rhythm on their bubble gum. Where are > they planning to hitch a ride? ") > A11 = A11.lower() A11 now contains all lowercase characters. > if A11 == "Rockaway Beach" : try if A11 == "rockaway beach": Kent PS Please use Reply All to reply to the list. > score += 5 > print "Correct" > elif A11 == "CBGB" : > print "That's where they are, not where they are going" > else: > print "Wrong, they all hitched a ride to Rockaway Beach" > > print "Your total score ", score > > main() > > Is the placement of the .lower function in the wrong place? When I run the > code, the program does not recognize my input and will not give me a score. > This happens even if I enter text with capitals. When I remove the .lower > function Python recognizes my answer, but only if it has capitals. > > any suggestions? > > cheers > Daniel > > From constantfables at gmail.com Tue Nov 25 18:45:41 2008 From: constantfables at gmail.com (Daniel J Kramer) Date: Tue, 25 Nov 2008 12:45:41 -0500 Subject: [Tutor] python question In-Reply-To: <1c2a2c590811250938x49a8c22ciad05563e2f955975@mail.gmail.com> References: <1c2a2c590811220533n39329fb3yd6b486e3c9b5cc32@mail.gmail.com> <1c2a2c590811250938x49a8c22ciad05563e2f955975@mail.gmail.com> Message-ID: Hi Kent got it! Is it because Python must recognize the answer as lower case? sorry if that might seem like a dumb question, but I am looking to understand this program. cheers Daniel On Tue, Nov 25, 2008 at 12:38 PM, Kent Johnson wrote: > On Tue, Nov 25, 2008 at 11:52 AM, Daniel J Kramer > wrote: > > Hi Kent > > > > I have been playing with the ,lower command and am not having much luck. > It > > seems like a simple task, but it is not working for me. Here is the code > > > > def main(): > > score = 0 > > print"Welcome to the Music Quiz. Today's game has 8 rounds for > you. > > There will be audio rounds, visual rounds and straight ahead qustions. We > > will begin with the round Journey to the Centre of New York" > > print > > A11 = raw_input ("We see the Ramones on the Bowery with rolled up > > towels under their arms chewing out a rhythm on their bubble gum. Where > are > > they planning to hitch a ride? ") > > A11 = A11.lower() > > A11 now contains all lowercase characters. > > > if A11 == "Rockaway Beach" : > try > if A11 == "rockaway beach": > > Kent > > PS Please use Reply All to reply to the list. > > > score += 5 > > print "Correct" > > elif A11 == "CBGB" : > > print "That's where they are, not where they are > going" > > else: > > print "Wrong, they all hitched a ride to Rockaway Beach" > > > > print "Your total score ", score > > > > main() > > > > Is the placement of the .lower function in the wrong place? When I run > the > > code, the program does not recognize my input and will not give me a > score. > > This happens even if I enter text with capitals. When I remove the > .lower > > function Python recognizes my answer, but only if it has capitals. > > > > any suggestions? > > > > cheers > > Daniel > > > > > -- Daniel J Kramer Constant Fables 249 12th st #3 Brooklyn, NY 11215 (h) 347 223 4571 (m) 646 427 7430 -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Tue Nov 25 19:47:41 2008 From: kent37 at tds.net (Kent Johnson) Date: Tue, 25 Nov 2008 13:47:41 -0500 Subject: [Tutor] python question In-Reply-To: References: <1c2a2c590811220533n39329fb3yd6b486e3c9b5cc32@mail.gmail.com> <1c2a2c590811250938x49a8c22ciad05563e2f955975@mail.gmail.com> Message-ID: <1c2a2c590811251047w3de25595g70fb0871173990a3@mail.gmail.com> On Tue, Nov 25, 2008 at 12:45 PM, Daniel J Kramer wrote: > Hi Kent > > got it! Is it because Python must recognize the answer as lower case? It's because you change the user input to lower case, so you have to compare it against a lower case answer. Maybe this helps: In [1]: s="Abc" In [2]: s.lower() Out[2]: 'abc' In [3]: s.lower() == "Abc" Out[3]: False In [4]: s.lower() == "abc" Out[4]: True Kent From lie.1296 at gmail.com Tue Nov 25 21:14:20 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Tue, 25 Nov 2008 20:14:20 +0000 (UTC) Subject: [Tutor] accessing list from a string References: Message-ID: On Tue, 25 Nov 2008 06:59:13 -0800, Mark Tolonen wrote: > "Bryan Fodness" wrote in message > news:fbf64d2b0811250641i208054f6h2a8f965942b356f0 at mail.gmail.com... >> I have a list in a text file that is in the python format., >> >> Positions = [2.5,2.8] >> >> and would like to grab the values. >> >> for line in file('list.txt'): >> if line == Positions: >> x1,x2=Positions >> >> I know this does not work. Is there a direct way to get my x1 and x2 >> values. > >>>> line = '[2.5,2.8]' >>>> x1,x2 = eval(line) >>>> x1,x2 > (2.5, 2.7999999999999998) > Don't give recommendations on eval without mentioning its danger. eval can execute anything a python statement can, and that includes dangerous statements that can be of security risk. Instead, in python 2.6, you may use ast.literal_eval(). Which restrict the eval to literal syntax only, and prohibit any function calling. Alternatively, for previous versions of python, or for more flexibility, you may use the safeeval like here: http://lybniz2.sourceforge.net/ safeeval.html From zebra05 at gmail.com Tue Nov 25 22:26:13 2008 From: zebra05 at gmail.com (OkaMthembo) Date: Tue, 25 Nov 2008 23:26:13 +0200 Subject: [Tutor] Python GIL Message-ID: Hi all, I wish to find out what the Global Interpreter Lock is and its relevance regarding the serving of high traffic Python sites. My understanding from what i read is that its a state whereby only one interpreter can be invoked on a physical machine. How does this impact performance of web apps that receive a high rate of requests? Do scripts wait in some marshalled queue for a certain period until their turn to be interpreted, or can multiple simultaneous requests be processed in parallel by the Python interpreter? Please clear my confusion regarding this topic. Any explanation would be appreciated. Best regards, -- Lloyd Dube -------------- next part -------------- An HTML attachment was scrubbed... URL: From inthefridge at gmail.com Tue Nov 25 23:15:13 2008 From: inthefridge at gmail.com (Spencer Parker) Date: Tue, 25 Nov 2008 15:15:13 -0700 Subject: [Tutor] Leaving PHP for Python In-Reply-To: References: Message-ID: You might also want to look at Pylons...its another excellent web framework built for Python. The community around it, I feel, is better than Django. People are pretty willing to answer any and all questions you have. It gives more control to the developer as oppiosed to Django. I just switched from Django to Pylons...so far it fits me better. Not for everyone...ya know... On Tue, Nov 25, 2008 at 5:43 AM, Jason DeBord wrote: > Hello All, > > This is my first message on the mailing list. I am excited to get started > developing content / backend for the web with Python. > > I have a background in PHP, but am convinced that Python is a better, more > powerful language. > > I am on a Windows XP machine and I have been using XAMPP for server, php, > mysql... > > I installed Python 2.5 and mod_python successfully. I can serve pages with > .py extension to http://localhost . > > The following for example: > > from mod_python import apache > > def handler(req): > req.write("Hello World!") > return apache.OK > > Frankly, I don't understand what is going on in the above. This is a bit > different compared to what I am used to. > > So, my question, would you all please point me to some introductory > resources, tutorials, books, that focus on Python programming for the web? I > am eventually going to interface with some web services, notably Amazon Web > Services. Also, I'd like to write some server side scripts to serve as a > backend to some Adobe AIR apps. > > Any and all advice is extremely appreciated. > > Thanks for your time! > > Sincerely, > > Jason > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Spencer Parker -------------- next part -------------- An HTML attachment was scrubbed... URL: From cfuller084 at thinkingplanet.net Tue Nov 25 23:09:54 2008 From: cfuller084 at thinkingplanet.net (Chris Fuller) Date: Tue, 25 Nov 2008 16:09:54 -0600 Subject: [Tutor] Python GIL In-Reply-To: References: Message-ID: <200811251609.54535.cfuller084@thinkingplanet.net> Python interpreters running in separate processes have no affect on each other. This is the easiest way to get around the limitations of the GIL. The GIL generally has limited effect on multithreaded applications on a single-core machine. It can be a serious bottleneck on multicore machines, however. Other implementations of Python, such as Jython or IronPython, do not have the GIL and are not subject to these limitations. However, any modules written in C will not be available unless they have been ported. A little poking around with google should tell you more. Cheers On Tuesday 25 November 2008 15:26, OkaMthembo wrote: > Hi all, > > I wish to find out what the Global Interpreter Lock is and its relevance > regarding the serving of high traffic Python sites. My understanding from > what i read is that its a state whereby only one interpreter can be invoked > on a physical machine. How does this impact performance of web apps that > receive a high rate of requests? Do scripts wait in some marshalled queue > for a certain period until their turn to be interpreted, or can multiple > simultaneous requests be processed in parallel by the Python interpreter? > > Please clear my confusion regarding this topic. Any explanation would be > appreciated. > > Best regards, From bgailer at gmail.com Tue Nov 25 23:44:58 2008 From: bgailer at gmail.com (bob gailer) Date: Tue, 25 Nov 2008 17:44:58 -0500 Subject: [Tutor] Leaving PHP for Python In-Reply-To: References: <492C0916.4040400@gmail.com> Message-ID: <492C7FEA.6060306@gmail.com> Please always reply all so a copy goes to the tutor list. We all participate and learn. Jason DeBord wrote: > Bob, > > Thanks for the reply. > > When I said I don't understand the above, that was just to give you > guys a reference for where I am at. > > At my current job I rarely touch the web server. I have just been > using php for server side development, thus, installing python and > mod_python was new territory for me, though I managed to get it > working surprisingly quick. As we speak I am trying to get Django up > and running. This is proving difficult and I think I am getting ahead > of myself. > > I'm lost with the code below because up to this point all I have ever > had to do is type in " OK - line - by - line commentary: mod_python is an apache add-on that creates a "long-running" Python process. This means the Python interpreter is load once (maximizing response time) and there is memory from one invocation by a request to the next. > from mod_python import apache Here mod_python is a python module that cooperates with the add-on. import loads the module (once) and brings the object apache from the module namespace into the local namespace. The reference to apache.OK is resolved by looking at the imported object for a property (attribute) named OK. > > def handler(req): Defines a function handler. Apache by default calls handler for each request, and passes the request object (here named req - arbitrarily). > req.write("Hello World!") calls the req object's write method passing a character string. The write method adds the string to the response under construction. > return apache.OK Terminates the function and returns apache.OK (whatever that is). I believe that returning apache.OK from the handler call tells apache that the request is complete and to return the page to the browser. -- Bob Gailer Chapel Hill NC 919-636-4239 From pixelspics at gmail.com Wed Nov 26 00:16:04 2008 From: pixelspics at gmail.com (Gilbert) Date: Wed, 26 Nov 2008 07:16:04 +0800 Subject: [Tutor] text file to excel csv file using python programming Message-ID: <6a9c9ac70811251516r19d33cabt5b832447ed19a0d5@mail.gmail.com> Hi People, I tried to look for some answers but I see only same data format processing ( *.txt to *.txt ) in python. my question is how to convert a text file ( e.g. *.log, *.dlg ) to excel *.csv using python programming. any suggestion and where I can get this information for further learning. thanks. best regards, Gilbert -------------- next part -------------- An HTML attachment was scrubbed... URL: From zstumgoren at gmail.com Wed Nov 26 00:21:10 2008 From: zstumgoren at gmail.com (Serdar Tumgoren) Date: Tue, 25 Nov 2008 18:21:10 -0500 Subject: [Tutor] text file to excel csv file using python programming In-Reply-To: References: <6a9c9ac70811251516r19d33cabt5b832447ed19a0d5@mail.gmail.com> Message-ID: Hi Gilbert, Check out the csv module in python's standard library. It can convert from .txt into Excel and vice versa http://www.python.org/doc/2.5.2/lib/module-csv.html -------------- next part -------------- An HTML attachment was scrubbed... URL: From pixelspics at gmail.com Wed Nov 26 00:36:10 2008 From: pixelspics at gmail.com (Gilbert) Date: Wed, 26 Nov 2008 07:36:10 +0800 Subject: [Tutor] text file to excel csv file using python programming In-Reply-To: References: <6a9c9ac70811251516r19d33cabt5b832447ed19a0d5@mail.gmail.com> Message-ID: <6a9c9ac70811251536p12ee765ck751a99ed1da6ae9f@mail.gmail.com> Hi Serdar, ok thanks for your quick reply. I'll try to check this module. Hi people & serdar, in case you have some websites or books you can recoomend that have some sample python codes for converting text files ( e.g. *.dlg, *.log ) to *.csv, kindly share. best regards, Gilbert On Wed, Nov 26, 2008 at 7:21 AM, Serdar Tumgoren wrote: > Hi Gilbert, > Check out the csv module in python's standard library. > > It can convert from .txt into Excel and vice versa > > > http://www.python.org/doc/2.5.2/lib/module-csv.html > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From zstumgoren at gmail.com Wed Nov 26 00:40:25 2008 From: zstumgoren at gmail.com (Serdar Tumgoren) Date: Tue, 25 Nov 2008 18:40:25 -0500 Subject: [Tutor] text file to excel csv file using python programming In-Reply-To: <6a9c9ac70811251536p12ee765ck751a99ed1da6ae9f@mail.gmail.com> References: <6a9c9ac70811251516r19d33cabt5b832447ed19a0d5@mail.gmail.com> <6a9c9ac70811251536p12ee765ck751a99ed1da6ae9f@mail.gmail.com> Message-ID: Hey Gilbert, The below link leads to a very basic script I put together with some assistance from several of the tutors on this list. It might give you a basic idea on how to use the csv module. http://forjournalists.com/cookbook/index.php?title=Itemizer -------------- next part -------------- An HTML attachment was scrubbed... URL: From pixelspics at gmail.com Wed Nov 26 00:44:24 2008 From: pixelspics at gmail.com (Gilbert) Date: Wed, 26 Nov 2008 07:44:24 +0800 Subject: [Tutor] text file to excel csv file using python programming In-Reply-To: References: <6a9c9ac70811251516r19d33cabt5b832447ed19a0d5@mail.gmail.com> <6a9c9ac70811251536p12ee765ck751a99ed1da6ae9f@mail.gmail.com> Message-ID: <6a9c9ac70811251544haa02740u5d8f28571045402e@mail.gmail.com> Hi Serdar, I will check on this. thanks a lot. best regards, Gilbert On Wed, Nov 26, 2008 at 7:40 AM, Serdar Tumgoren wrote: > Hey Gilbert, > The below link leads to a very basic script I put together with some > assistance from several of the tutors on this list. It might give you a > basic idea on how to use the csv module. > > http://forjournalists.com/cookbook/index.php?title=Itemizer > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From tchomby at googlemail.com Wed Nov 26 00:50:06 2008 From: tchomby at googlemail.com (tchomby) Date: Tue, 25 Nov 2008 23:50:06 +0000 Subject: [Tutor] How to get smooth, terminal-like interaction over the web Message-ID: <20081125235004.GA10919@oh> I have an idea for a python program I want to write. I want to make this program accessible over the web for people to play with. And that's where I'm stuck -- I don't know what module, framework, protocol, or whatever to use to webify it. It's a simple text-based program, the interaction would work perfectly in a terminal with the computer printing out lines of text to the user, and the user typing in lines of text and pressing return, and this is the kind of interaction I want to enable on a web page. Can anyone point me in the direction I should be looking, if I want to implement this kind of interaction over the net using python? I'm aware of CGI and HTML forms and the python modules for it, but I think that would require the entire page to be reloaded every time there's an input or output. So am I looking at ajax, javascript, etc.? I'm a little bit lost, not knowing what's available out there. I'm looking for simplicity and ease of use for a python programmer. From alan.gauld at btinternet.com Wed Nov 26 01:43:46 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 26 Nov 2008 00:43:46 -0000 Subject: [Tutor] accessing list from a string References: Message-ID: "Bryan Fodness" wrote >I have a list in a text file that is in the python format., > > Positions = [2.5,2.8] When you say "in the Python format" do you mean it is real Python codfe or just that it happens to look like Python? If the latter what format is it really? If its a config file then the config parser will extract the string based on the key (positions) for you. But you will still need to convert the string "[2.5,2.8]" to a list or tuple. You could use eval to evaluate the string but that would be dangerous since the striong could be a malicious piece of code. But you can make it a lot safer by wrapping it in a function with known effect, thus: s = "[2.5,2.8]" # your string from the file e = "tuple(" + e + ")" x,y = eval(e) # x -> 2.5, y -> 2.8 Now if some crazy code gets read by error the eval will throw an error. Its not foolproof but it works for all but the most devious attacks. If you don't like that then it's down to parsing the string and I'd suggest a regular expression is best to pull out the numbers unless the string is definitely fixed format/length. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Wed Nov 26 01:50:00 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 26 Nov 2008 00:50:00 -0000 Subject: [Tutor] How to get smooth, terminal-like interaction over the web References: <20081125235004.GA10919@oh> Message-ID: "tchomby" wrote > It's a simple text-based program, the interaction would work > perfectly in a > terminal with the computer printing out lines of text to the user, > and the user > typing in lines of text and pressing return, and this is the kind of > interaction I want to enable on a web page. For small apps I'd suggest biting the bullet and learning JavaScript and coding it in the browser. The next best thing is either a Java applet - which can be written in Jython - or an Ajax application. Both of these have a steepish learning curve which is why I suggest learning JavaScript! > the entire page to be reloaded every time there's an input or > output. So am I > looking at ajax, javascript, etc.? I'm a little bit lost, not > knowing what's > available out there. Yes I think one of JavaScript, Jython, or Ajax will be best. I believe that Django supports Ajax and I know TurboGears does. If you go the JavaScript route check out Mochikit which makes JS more like Python! HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From kent37 at tds.net Wed Nov 26 03:24:36 2008 From: kent37 at tds.net (Kent Johnson) Date: Tue, 25 Nov 2008 21:24:36 -0500 Subject: [Tutor] accessing list from a string In-Reply-To: References: Message-ID: <1c2a2c590811251824r48fc4851y3d22eb5a7863277f@mail.gmail.com> On Tue, Nov 25, 2008 at 3:14 PM, Lie Ryan wrote: > Instead, in python 2.6, you may use ast.literal_eval(). Which restrict > the eval to literal syntax only, and prohibit any function calling. That's very cool, thanks! > Alternatively, for previous versions of python, or for more flexibility, > you may use the safeeval like here: http://lybniz2.sourceforge.net/ > safeeval.html It looks like it wouldn't be hard to port ast.literal_eval to Python 2.5... Kent From john at fouhy.net Wed Nov 26 03:40:08 2008 From: john at fouhy.net (John Fouhy) Date: Wed, 26 Nov 2008 15:40:08 +1300 Subject: [Tutor] accessing list from a string In-Reply-To: References: Message-ID: <5e58f2e40811251840ofc05035kfe5900c50fab57d9@mail.gmail.com> On 26/11/2008, Alan Gauld wrote: > You could use eval to evaluate the string but that would be dangerous since > the striong could be a malicious piece of code. But you can make it a lot > safer by wrapping it in a function with known effect, thus: > > s = "[2.5,2.8]" # your string from the file > > e = "tuple(" + e + ")" > > x,y = eval(e) # x -> 2.5, y -> 2.8 > > Now if some crazy code gets read by error the eval will throw an error. Its > not foolproof but it works for all but the most devious attacks. If I, as an evildoer, can control e, it seems that I could set it to: ,), __import__('os').system('rm -rf /' I've never thought of myself as all that devious :-) -- John. From kent37 at tds.net Wed Nov 26 03:43:58 2008 From: kent37 at tds.net (Kent Johnson) Date: Tue, 25 Nov 2008 21:43:58 -0500 Subject: [Tutor] text file to excel csv file using python programming In-Reply-To: <6a9c9ac70811251516r19d33cabt5b832447ed19a0d5@mail.gmail.com> References: <6a9c9ac70811251516r19d33cabt5b832447ed19a0d5@mail.gmail.com> Message-ID: <1c2a2c590811251843j10a3b4b6s12446c9d7624f71d@mail.gmail.com> On Tue, Nov 25, 2008 at 6:16 PM, Gilbert wrote: > Hi People, > > I tried to look for some answers but I see only same data format > processing ( *.txt to *.txt ) in python. > my question is how to convert a text file ( e.g. *.log, *.dlg ) to excel > *.csv using python programming. This kind of program can be pretty simple, depending on the format of your text file. It generally will have the form open input file open output file open csv writer for output file for each line in input: split the line into fields write the fields to the csv writer close input file close output file The real program may not be much longer than that. I really depends on what you need to do with the input lines. Can you show an example? Kent From alan.gauld at btinternet.com Wed Nov 26 09:49:00 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 26 Nov 2008 08:49:00 -0000 Subject: [Tutor] accessing list from a string References: <5e58f2e40811251840ofc05035kfe5900c50fab57d9@mail.gmail.com> Message-ID: "John Fouhy" wrote >> s = "[2.5,2.8]" # your string from the file >> >> e = "tuple(" + e + ")" This should of course be >> e = "tuple(" + s + ")" > If I, as an evildoer, can control e, it seems that I could set it > to: > > ,), __import__('os').system('rm -rf /' Assuming you now mean s rather than e... That wouldn't work since tuple() would fail on that expression. HTH, Alan G From alan.gauld at btinternet.com Wed Nov 26 10:16:00 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 26 Nov 2008 09:16:00 -0000 Subject: [Tutor] accessing list from a string References: <5e58f2e40811251840ofc05035kfe5900c50fab57d9@mail.gmail.com> Message-ID: "John Fouhy" wrote >> e = "tuple(" + e + ")" >> >> x,y = eval(e) # x -> 2.5, y -> 2.8 >> > If I, as an evildoer, can control e, it seems that I could set it > to: > > ,), __import__('os').system('rm -rf /' > > I've never thought of myself as all that devious :-) Sorry John, too fast in hitting reply. I didn't notice the closing quote in the original - too early in the morning! - yes that would trip it up. But that would be a specific bit of code aimed at a specific eval - in other words the perp would need to know that the eval had a function call in it. So yes you do classify as devious in my definition! :-) Someone just typing valid Python code into an input in the hope of causing havoc would not succeed, you need to know to close parens and leave an unclosed paren at the end. But yes, the eval is not foolproof and if that is a cause for concern then parse the string. Alan g From bgailer at gmail.com Wed Nov 26 12:48:52 2008 From: bgailer at gmail.com (bob gailer) Date: Wed, 26 Nov 2008 06:48:52 -0500 Subject: [Tutor] How to get smooth, terminal-like interaction over the web In-Reply-To: <20081125235004.GA10919@oh> References: <20081125235004.GA10919@oh> Message-ID: <492D37A4.8070207@gmail.com> tchomby wrote: > I have an idea for a python program I want to write. I want to make this > program accessible over the web for people to play with. And that's where I'm > stuck -- I don't know what module, framework, protocol, or whatever to use to > webify it. > > It's a simple text-based program, the interaction would work perfectly in a > terminal with the computer printing out lines of text to the user, and the user > typing in lines of text and pressing return, and this is the kind of > interaction I want to enable on a web page. > > Can anyone point me in the direction I should be looking, if I want to > implement this kind of interaction over the net using python? I'm aware of CGI > and HTML forms and the python modules for it, but I think that would require > the entire page to be reloaded every time there's an input or output. So am I > looking at ajax, javascript, etc.? I'm a little bit lost, not knowing what's > available out there. > See http://code.google.com/p/pythoninthebrowser/. > I'm looking for simplicity and ease of use for a python programmer. > -- Bob Gailer Chapel Hill NC 919-636-4239 From kent37 at tds.net Wed Nov 26 13:17:08 2008 From: kent37 at tds.net (Kent Johnson) Date: Wed, 26 Nov 2008 07:17:08 -0500 Subject: [Tutor] accessing list from a string In-Reply-To: References: <5e58f2e40811251840ofc05035kfe5900c50fab57d9@mail.gmail.com> Message-ID: <1c2a2c590811260417w6cea481eodf3a0cf874066dbc@mail.gmail.com> On Wed, Nov 26, 2008 at 4:16 AM, Alan Gauld wrote: > "John Fouhy" wrote > >>> e = "tuple(" + e + ")" >>> >>> x,y = eval(e) # x -> 2.5, y -> 2.8 >>> >> If I, as an evildoer, can control e, it seems that I could set it to: >> >> ,), __import__('os').system('rm -rf /' > > But that would be a specific bit of code aimed at a > specific eval - in other words the perp would need to > know that the eval had a function call in it. So yes > you do classify as devious in my definition! :-) This works just as well: s = '__import__("os").system("rm -rf /")' I've no actual experience with this sort of attacker but it's not hard to imagine a bored attacker trying many combinations of input, or having a priori knowledge of the code under attack. Tangentially related I have to mention this lovely SQL injection attack: http://xkcd.com/327/ Kent From tchomby at googlemail.com Wed Nov 26 13:23:39 2008 From: tchomby at googlemail.com (tchomby) Date: Wed, 26 Nov 2008 12:23:39 +0000 Subject: [Tutor] How to get smooth, terminal-like interaction over the web In-Reply-To: <492D37A4.8070207@gmail.com> References: <20081125235004.GA10919@oh> <492D37A4.8070207@gmail.com> Message-ID: <20081126122339.GA785@kisimul> On Wed, Nov 26, 2008 at 06:48:52AM -0500, bob gailer wrote: > > See http://code.google.com/p/pythoninthebrowser/. > >> I'm looking for simplicity and ease of use for a python programmer. I was just thinking that I'm sure I've seen Python and Ruby interpreters implemented in javascript or something like that. Thanks, I'll check it out. I guess the problem may be that I don't really want to give the user access to a full Python shell, that sounds exploitable. But I'll look into it. If not, I guess I'll have to learn javascript instead. From kent37 at tds.net Wed Nov 26 13:25:25 2008 From: kent37 at tds.net (Kent Johnson) Date: Wed, 26 Nov 2008 07:25:25 -0500 Subject: [Tutor] How to get smooth, terminal-like interaction over the web In-Reply-To: <20081125235004.GA10919@oh> References: <20081125235004.GA10919@oh> Message-ID: <1c2a2c590811260425g391d8883lcc8230fe0c90bcfb@mail.gmail.com> On Tue, Nov 25, 2008 at 6:50 PM, tchomby wrote: > It's a simple text-based program, the interaction would work perfectly in a > terminal with the computer printing out lines of text to the user, and the user > typing in lines of text and pressing return, and this is the kind of > interaction I want to enable on a web page. > > Can anyone point me in the direction I should be looking, if I want to > implement this kind of interaction over the net using python? You might look for chat programs. IIRC Twisted includes a demo chat server. Or these might be useful models: http://www-ai.ijs.si/eliza/eliza.html http://nlp-addiction.com/eliza/ Kent From denis.spir at free.fr Wed Nov 26 14:22:52 2008 From: denis.spir at free.fr (spir) Date: Wed, 26 Nov 2008 14:22:52 +0100 Subject: [Tutor] poll question Message-ID: <492D4DAC.5000005@free.fr> Hello pythonistas, I need some information about a topic. A list like python tutor is the proper place to get it. Take this as a (stupid) game: would you like to answer the following question? Imagine you are writing code. Then, you realise you need a tool function you have not yet written. You don't want to stop coding now, rather plan to write the func later. So that your code will hold some calls to a not yet defined function. Right? The function is a very short and simple one, indeed: it will return a character range, in form of a string such as "0123456789", when passed ASCII ordinals as parameters. How would you call this function? e.g. digits = char_range(...) In other words: which is, for you personly, the most practicle or natural way of calling this func? Would you give me one or more calling example(s)? Below a list of ASCII characters. Note: Yes, this is trivial ;-) But there is no trick, no trap. I cannot tell the purpose now, because it would invalid the results. I will explain it in 3 or 4 days when I have some data. Additional question if you wish: You may try and guess the point of this. But do it after answering... Thank you very much. Denis DEC OCTAL HEX CHR MEANING ---- + ------ + ---- + - + -------- + #000 | \x0000 | \x00 | | NUL #001 | \x0001 | \x01 | | SOH #002 | \x0002 | \x02 | | STX #003 | \x0003 | \x03 | | ETX #004 | \x0004 | \x04 | | EOT #005 | \x0005 | \x05 | | ENQ #006 | \x0006 | \x06 | | ACK #007 | \x0007 | \x07 | | BEL #008 | \x0010 | \x08 | | BS #009 | \x0011 | \x09 | | HT #010 | \x0012 | \x0A | | LF or NL #011 | \x0013 | \x0B | | VT #012 | \x0014 | \x0C | | NP #013 | \x0015 | \x0D | | CR #014 | \x0016 | \x0E | | SO #015 | \x0017 | \x0F | | SI #016 | \x0020 | \x10 | | DLE #017 | \x0021 | \x11 | | DC1 #018 | \x0022 | \x12 | | DC2 #019 | \x0023 | \x13 | | DC3 #020 | \x0024 | \x14 | | DC4 #021 | \x0025 | \x15 | | NAK #022 | \x0026 | \x16 | | SYN #023 | \x0027 | \x17 | | ETB #024 | \x0030 | \x18 | | CAN #025 | \x0031 | \x19 | | EM #026 | \x0032 | \x1A | | SUB #027 | \x0033 | \x1B | | ESC #028 | \x0034 | \x1C | | FS #029 | \x0035 | \x1D | | GS #030 | \x0036 | \x1E | | RS #031 | \x0037 | \x1F | | US #032 | \x0040 | \x20 | | Space SP #033 | \x0041 | \x21 | ! | Exclamation mark #034 | \x0042 | \x22 | " | Quotation mark " #035 | \x0043 | \x23 | # | Number sign #036 | \x0044 | \x24 | $ | Dollar sign #037 | \x0045 | \x25 | % | Percent sign #038 | \x0046 | \x26 | & | Ampersand & #039 | \x0047 | \x27 | ' | Apostrophe right single quote #040 | \x0050 | \x28 | ( | Left parenthesis #041 | \x0051 | \x29 | ) | Right parenthesis #042 | \x0052 | \x2A | * | Asterisk #043 | \x0053 | \x2B | + | Plus sign #044 | \x0054 | \x2C | , | Comma #045 | \x0055 | \x2D | - | Hyphen #046 | \x0056 | \x2E | . | Period fullstop #047 | \x0057 | \x2F | / | Solidus slash #048 | \x0060 | \x30 | 0 | Digit 0 ...... ... ... ... #057 | \x0071 | \x39 | 9 | Digit 9 #058 | \x0072 | \x3A | : | Colon #059 | \x0073 | \x3B | ; | Semi-colon #060 | \x0074 | \x3C | < | Less than < #061 | \x0075 | \x3D | = | Equals sign #062 | \x0076 | \x3E | > | Greater than > #063 | \x0077 | \x3F | ? | Question mark #064 | \x0100 | \x40 | @ | Commercial at-sign #065 | \x0101 | \x41 | A | Uppercase letter A ...... ... ... ... #090 | \x0132 | \x5A | Z | Uppercase letter Z #091 | \x0133 | \x5B | [ | Left square bracket #092 | \x0134 | \x5C | 0 | Reverse solidus backslash #093 | \x0135 | \x5D | ] | Right square bracket #094 | \x0136 | \x5E | ^ | Caret #095 | \x0137 | \x5F | _ | Horizontal bar underscore #096 | \x0140 | \x60 | ` | Reverse apostrophe left single quote #097 | \x0141 | \x61 | a | Lowercase letter a . . . #122 | \x0172 | \x7A | z | Lowercase letter z #123 | \x0173 | \x7B | { | Left curly brace #124 | \x0174 | \x7C | | | Vertical bar #125 | \x0175 | \x7D | } | Right curly brace #126 | \x0176 | \x7E | ~ | Tilde #127 | \x0177 | \x7F | | DEL From pixelspics at gmail.com Wed Nov 26 14:57:51 2008 From: pixelspics at gmail.com (Gilbert) Date: Wed, 26 Nov 2008 21:57:51 +0800 Subject: [Tutor] text file to excel csv file using python programming In-Reply-To: <1c2a2c590811251843j10a3b4b6s12446c9d7624f71d@mail.gmail.com> References: <6a9c9ac70811251516r19d33cabt5b832447ed19a0d5@mail.gmail.com> <1c2a2c590811251843j10a3b4b6s12446c9d7624f71d@mail.gmail.com> Message-ID: <6a9c9ac70811260557s290dab4ct2793fba714a12533@mail.gmail.com> Hi Kent, thanks for the valuable suggestion. to make it more clearer here is my example... Below is my input text file in dlg format. this dlg file contains 2 information. one is for coordinate x=50, y=55 and another is for coordinate x=60, y=65. ***************************************************************** Machine No.: ABC Date: March 03,2006 11:22AM Program Name: DEF Version: B0 Lot: GHI Operator: Jane Item 0.A00.000.001 print_x_y_coordinate 0.A00.***.*** print_x_y_coordinate ===================================================================================== 0.A00.***.*** print_x_y_coordinate >>>>> 50,55 0.A00.***.*** print_x_y_coordinate ===================================================================================== 0.A00.***.*** print_x_y_coordinate Item 5004.A00.000.001 current_item 5004.A00.***.*** current_item A 5004.A00.***.*** current_item -16.737uA, 5004.A00.***.*** current_item 5004.A00.***.*** current_item description:, 50, 55,0, 16,16.737 400.A00.***.*** curr_log_item curr:,x_coor,y_coor,v3d3,v1d8,curr1,curr2,curr3,curr4,curr5,curr6 400.A00.***.*** curr_log_curr curr:, 50, 55,2.9,1.5, 18.00760, 17.84030, 18.06844, 0.10003, 0.06925, -0.00769 400.A00.***.*** curr_log_item curr:, 50, 55,3.3,1.8, 21.52091, 21.64259, 21.68821, -0.00769, 0.08464, 0.00769 400.A00.***.*** curr_log_item curr:, 50, 55,3.7,2.1, 24.42586, 24.48669, 24.50190, 0.02308, -0.06925, -0.14620 Item 0.A00.000.001 get_time_item 0.A00.***.*** get_time_item Time:, 50, 55,47.733332s b00 Result=OK, Number=2 Machine No.: ABC Date: March 03,2006 11:24AM Program Name: DEF Version: B0 Lot: GHI Operator: Jane Item 0.A00.000.001 print_x_y_coordinate 0.A00.***.*** print_x_y_coordinate ===================================================================================== 0.A00.***.*** print_x_y_coordinate >>>>> 60,65 0.A00.***.*** print_x_y_coordinate ===================================================================================== 0.A00.***.*** print_x_y_coordinate Item 5004.A00.000.001 current_item 5004.A00.***.*** current_item A 5004.A00.***.*** current_item -25.737uA, 5004.A00.***.*** current_item 5004.A00.***.*** current_item description:, 60, 65,1, 16,25.737 400.A00.***.*** curr_log_item curr:,x_coor,y_coor,v3d3,v1d8,curr1,curr2,curr3,curr4,curr5,curr6 400.A00.***.*** curr_log_curr curr:, 60, 65,2.9,1.5, 19.00760, 18.84030, 19.06844, 0.20003, 0.16925, -0.10769 400.A00.***.*** curr_log_item curr:, 60, 65,3.3,1.8, 22.52091, 22.64259, 22.68821, -0.10769, 0.18464, 0.10769 400.A00.***.*** curr_log_item curr:, 60, 65,3.7,2.1, 25.42586, 25.48669, 25.50190, 0.12308, -0.16925, -0.24620 Item 0.A00.000.001 get_time_item 0.A00.***.*** get_time_item Time:, 60, 65,57.444455s b00 Result=OK, Number=3 ******************************************************************************************************************************************************************* the output file below in csv excel format ******************************************************************************************************************************************************************************************************************** Machine No. Lot Date Time X Y current item curr1_2.9_1.5 curr2_2.9_1.5 curr5_2.9_1.5 curr3_3.7_2.1 curr5_3.7_2.1 Time Number ABC GHI March 03, 2006 11:22AM 50 55 16.737 18.00760 17.84030 0.06925 24.50190 -0.06925 47.733332s 2 ABC GHI March 03, 2006 11:24AM 60 65 25.737 19.00760 18.84030 0.16925 25.50190 -0.16925 57.444455s 3 ********************************************************************************************************************************************************************************************************************** if my explanation is not so clear let me know. thanks. best regards, Gilbert On Wed, Nov 26, 2008 at 10:43 AM, Kent Johnson wrote: > On Tue, Nov 25, 2008 at 6:16 PM, Gilbert wrote: > > Hi People, > > > > I tried to look for some answers but I see only same data format > > processing ( *.txt to *.txt ) in python. > > my question is how to convert a text file ( e.g. *.log, *.dlg ) to excel > > *.csv using python programming. > > This kind of program can be pretty simple, depending on the format of > your text file. It generally will have the form > open input file > open output file > open csv writer for output file > > for each line in input: > split the line into fields > write the fields to the csv writer > > close input file > close output file > > > The real program may not be much longer than that. I really depends on > what you need to do with the input lines. Can you show an example? > > Kent > -------------- next part -------------- An HTML attachment was scrubbed... URL: From peter at avirtualhome.com Wed Nov 26 15:39:54 2008 From: peter at avirtualhome.com (Peter van der Does) Date: Wed, 26 Nov 2008 09:39:54 -0500 Subject: [Tutor] poll question In-Reply-To: <492D4DAC.5000005@free.fr> References: <492D4DAC.5000005@free.fr> Message-ID: <20081126093954.73787827@montecarlo.grandprix.int> On Wed, 26 Nov 2008 14:22:52 +0100 spir wrote: > Hello pythonistas, > > I need some information about a topic. A list like python tutor is > the proper place to get it. Take this as a (stupid) game: would you > like to answer the following question? > > Imagine you are writing code. Then, you realise you need a tool > function you have not yet written. You don't want to stop coding now, > rather plan to write the func later. So that your code will hold some > calls to a not yet defined function. Right? The function is a very > short and simple one, indeed: it will return a character range, in > form of a string such as "0123456789", when passed ASCII ordinals as > parameters. How would you call this function? e.g. digits = > char_range(...) In other words: which is, for you personly, the most > practicle or natural way of calling this func? Would you give me one > or more calling example(s)? Below a list of ASCII characters. > > Note: Yes, this is trivial ;-) But there is no trick, no trap. I > cannot tell the purpose now, because it would invalid the results. I > will explain it in 3 or 4 days when I have some data. Additional > question if you wish: You may try and guess the point of this. But do > it after answering... > > Thank you very much. > Denis I would split it up in two functions: The main function would be: getStringFromOrd(list,what-ord) You'll loop through the passed parameter, a list delimited by comma. what-ord defines what you are using (dec, octal, hex) For each value in the list you call getCharFromOrd(ord,what-ord) which returns the true character Examples: MyName = getStringFromOrd((80,101,116,101,114),'Dec') MyName = getStringFromOrd((0x50,0x65,0x74,0x65,0x72),'hex') -- Peter van der Does GPG key: E77E8E98 WordPress Plugin Developer http://blog.avirtualhome.com GetDeb Package Builder/GetDeb Site Coder http://www.getdeb.net - Software you want for Ubuntu -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 197 bytes Desc: not available URL: From alan.gauld at btinternet.com Wed Nov 26 20:46:52 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 26 Nov 2008 19:46:52 -0000 Subject: [Tutor] accessing list from a string References: <5e58f2e40811251840ofc05035kfe5900c50fab57d9@mail.gmail.com> <1c2a2c590811260417w6cea481eodf3a0cf874066dbc@mail.gmail.com> Message-ID: "Kent Johnson" wrote >>>> e = "tuple(" + s + ")" >>>> >>>> x,y = eval(e) # x -> 2.5, y -> 2.8 > > This works just as well: > s = '__import__("os").system("rm -rf /")' > I don' think it would since the eval would call tuple which would return a tuple of characters which would not unpack into x,y so throwing an error. But John's example with the closing paren definitely would work. So the moral is don't be lazy parse the input if theere is any possibility of hostile (or just uncontrolled) access to the input.... -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From juryef at yahoo.com Wed Nov 26 20:51:13 2008 From: juryef at yahoo.com (Judith Flores) Date: Wed, 26 Nov 2008 11:51:13 -0800 (PST) Subject: [Tutor] Subprocess module Message-ID: <350066.9571.qm@web34705.mail.mud.yahoo.com> Hello, A couple of weeks ago I posted a question about what documentation I should read in order to implement a way to communicate Python and R. I read about the module 'subprocess', but have not been able to do something very simple. I was wondering if you could tell me how to transfer a Python variable to R. For example, a variable called 'fileforR' will acquire a pathfile from the user through a GUI. This file will be a csv file that will be processed in a R script for statistical analysis. Let's suppose the R script is called: 'read_file.R', and that it contains the following code: read.csv(fileforR) q() In the Python interpreter: import easygui import subprocess fileforR = fileopenbox() After this, I have tried different combinations to try to call R and the mentioned R script, for example: subprocess.call('R') opens the R console, but I can't access the R script. And there's another problem I can't solve: passing the 'fileforR' variable from Python to the R environment. I am working on SUSE Linux, and using Python 2.5.2. Thank you very much, Judith From alan.gauld at btinternet.com Wed Nov 26 20:52:41 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 26 Nov 2008 19:52:41 -0000 Subject: [Tutor] poll question References: <492D4DAC.5000005@free.fr> Message-ID: "spir" wrote > How would you call this function? e.g. > digits = char_range(...) > In other words: which is, for you personly, the most practicle or > natural way of calling this func? Would you give me one or more > calling example(s)? I'm not sure what you are asking for. Do you mean what name would I give the function? Or are you asking for the function prototype? Or both? And given that youve provided the ASCII table are you asking for a working function definition? Not sure what that achieves? Alan G From kent37 at tds.net Wed Nov 26 21:15:28 2008 From: kent37 at tds.net (Kent Johnson) Date: Wed, 26 Nov 2008 15:15:28 -0500 Subject: [Tutor] accessing list from a string In-Reply-To: References: <5e58f2e40811251840ofc05035kfe5900c50fab57d9@mail.gmail.com> <1c2a2c590811260417w6cea481eodf3a0cf874066dbc@mail.gmail.com> Message-ID: <1c2a2c590811261215g41a33d58jec9a33e3177ab1ee@mail.gmail.com> On Wed, Nov 26, 2008 at 2:46 PM, Alan Gauld wrote: > > "Kent Johnson" wrote > >>>>> e = "tuple(" + s + ")" >>>>> >>>>> x,y = eval(e) # x -> 2.5, y -> 2.8 >> >> This works just as well: >> s = '__import__("os").system("rm -rf /")' >> > > I don' think it would since the eval would call tuple > which would return a tuple of characters which would > not unpack into x,y so throwing an error. Care to try it? It does raise an exception but not until after the import expression is evaluated and the damage is done. In [4]: s = '__import__("os").system("dir")' In [5]: e = "tuple(" + s + ")" In [6]: eval(e) echo off Volume in drive C is unlabeled Serial number is 5487:d172 Directory of C:\Project\Play\* 7,757,694 bytes in 3 files and 18 dirs 7,766,016 bytes allocated 96,700,784,640 bytes free --------------------------------------------------------------------------- TypeError Traceback (most recent call last) C:\Project\Play\ in () C:\Project\Play\ in () TypeError: 'int' object is not iterable Kent From david at abbottdavid.com Wed Nov 26 22:08:05 2008 From: david at abbottdavid.com (David) Date: Wed, 26 Nov 2008 16:08:05 -0500 Subject: [Tutor] [Fwd: Re: Subprocess module] Message-ID: <492DBAB5.3020704@abbottdavid.com> -- Powered by Gentoo GNU/LINUX http://www.linuxcrazy.com -------------- next part -------------- An embedded message was scrubbed... From: David Subject: Re: [Tutor] Subprocess module Date: Wed, 26 Nov 2008 16:07:05 -0500 Size: 2030 URL: From denis.spir at free.fr Wed Nov 26 21:36:47 2008 From: denis.spir at free.fr (spir) Date: Wed, 26 Nov 2008 21:36:47 +0100 Subject: [Tutor] poll question In-Reply-To: <492D4DAC.5000005@free.fr> References: <492D4DAC.5000005@free.fr> Message-ID: <492DB35F.5050708@free.fr> Hol?, I forgot to ask for replies outside the list -- to avoid 'pollution' with off-topic posts. denis.spir at free.fr Thank you, denis spir a ?crit : > Hello pythonistas, [...] From alan.gauld at btinternet.com Wed Nov 26 23:56:57 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 26 Nov 2008 22:56:57 -0000 Subject: [Tutor] accessing list from a string References: <5e58f2e40811251840ofc05035kfe5900c50fab57d9@mail.gmail.com><1c2a2c590811260417w6cea481eodf3a0cf874066dbc@mail.gmail.com> <1c2a2c590811261215g41a33d58jec9a33e3177ab1ee@mail.gmail.com> Message-ID: "Kent Johnson" wrote >>> This works just as well: >>> s = '__import__("os").system("rm -rf /")' >>> >> >> I don' think it would since the eval would call tuple >> which would return a tuple of characters which would >> not unpack into x,y so throwing an error. > > Care to try it? It does raise an exception but not until after the > import expression is evaluated and the damage is done. Rats, so it does! My initial test didn't fail because I put the literal string into the tuple() call but when you use the string addition you lose the quotes. But then you need to lose the quotes for the eval of the list to work too so just adding quotes doesn't work either. Pity, I've used that technique with lisp and its been OK but obviously not with Python. Back to the drawing board! Thanks for keeping me straight Kent! (and John) Alan G. From denis.spir at free.fr Wed Nov 26 23:56:07 2008 From: denis.spir at free.fr (spir) Date: Wed, 26 Nov 2008 23:56:07 +0100 Subject: [Tutor] [Fwd: Re: poll question] Message-ID: <492DD407.6060001@free.fr> Alan Gauld a ?crit : > > "spir" wrote > >> How would you call this function? e.g. >> digits = char_range(...) >> In other words: which is, for you personly, the most practicle or >> natural way of calling this func? Would you give me one or more >> calling example(s)? > > I'm not sure what you are asking for. [...] Actually, my question is so trivial that it is difficult to let you understand what I want. Imagine you know there is a "char_range" function that returns a char string -- provided you properly inform it about the range you want. But, as you do not know exactly its interface, you have to guess. How would imagine this function should be called? Or, how would you call it spontaneously? I only ask for the calling format. I can't give an example, unfortunately, as it will influence your response. But I can illustrate with an artificial example. If I need a function that rounds decimal numbers, but have not yet written it, or if this func exists but I don't or remember its calling format, then I would write e.g. rounded_decimal = round(decimal, precision) and e.g. writing x = round(4.0/3, 2) *should* let x = 1.33 That's what I expect -- but I may be wrong if I'm not the author. If I write it personly, then I will let it work so. That's all I ask for: the calling format. You can write the func if you like -- but it's really not very challenging ;-) And I would prefere you to do that *after* answering, because it may change your answer. You can also try and guess the issue behind my asking -- same problem... From alan.gauld at btinternet.com Thu Nov 27 01:40:14 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 27 Nov 2008 00:40:14 -0000 Subject: [Tutor] poll question] References: <492DD407.6060001@free.fr> Message-ID: "spir" wrote > Actually, my question is so trivial that it is difficult to let you > understand > what I want. Imagine you know there is a "char_range" function that > returns a > char string -- provided you properly inform it about the range you > want. But, > as you do not know exactly its interface, you have to guess. How > would imagine > this function should be called? Or, how would you call it > spontaneously? I wouldn't guess, I'd go into the interpreter and try using help() on it. Or I'd try something that wouldn't work (like not passing any args) to see what it told me - usually the expected number of args for example. If we assume that the module where it is defined is not available for inspection and there are no doc strings for help to grok then and only then might I try guesswork, but more likely I'd just write my own function or go look for another on the net! Guessing a functions interface is so frought with danger that I just wouldn't even try except in extremis. If I was writing such a function from scratch and somebody gave me your description as a spec I'd start off with something like: def char_range(start, end): # code here Or maybe def char_range(start, length): # code... Does that help in any way? -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From sierra_mtnview at sbcglobal.net Thu Nov 27 05:38:12 2008 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Wed, 26 Nov 2008 20:38:12 -0800 Subject: [Tutor] Installing the Numeric Module for 2.4 Again? Message-ID: <492E2434.3090509@sbcglobal.net> An HTML attachment was scrubbed... URL: From kent37 at tds.net Thu Nov 27 13:44:35 2008 From: kent37 at tds.net (Kent Johnson) Date: Thu, 27 Nov 2008 07:44:35 -0500 Subject: [Tutor] Installing the Numeric Module for 2.4 Again? In-Reply-To: <492E2434.3090509@sbcglobal.net> References: <492E2434.3090509@sbcglobal.net> Message-ID: <1c2a2c590811270444i7b6dd8am47eb565cd1b18cf3@mail.gmail.com> On Wed, Nov 26, 2008 at 11:38 PM, Wayne Watson wrote: > A fellow user of an application that I share with others may not have > installed Numeric-24.2.win32-py2.4.exe. If I tell him to try it, will it > replace the duplicate module if in fact he has already done it? It should be fine to reinstall it. It's also easy to test: kent $ python -c "import Numeric" Traceback (most recent call last): File "", line 1, in ImportError: No module named Numeric If you get an ImportError it is not installed. Kent From ptmcg at austin.rr.com Thu Nov 27 15:58:59 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Thu, 27 Nov 2008 08:58:59 -0600 Subject: [Tutor] poll question] In-Reply-To: References: Message-ID: <9B6ACBAD38AC4A869C75E7AC9938E032@AWA2> I guess PEP8 gives some tips on how things should be named, and what case to use, but I think Denis's question goes beyond that. I think the point of Denis's question was not to imply that resources like help or docstrings are not useful, or would not be available. I think he is polling to see what the typical Pythonista's intuitive expectation would be for such a routine. Much of the value of Python (and any Pythonically designed module API) is to make naming and interface choices that are, well, Pythonic, and that client code can be productively written without *having* to consult docstrings at every call. One point that I think goes along with parameter order is the choice for defaults. For example, given his round function example, I think a reasonable expectation would be that his precision argument would have a default of 0, so that round(1.23456) would round to the nearest integer. I write this even for his hypothetical example, with no help or docstrings. Joshua Bloch gave a Google talk on the topic of good API design (http://www.slideshare.net/guestbe92f4/how-to-design-a-good-a-p-i-and-why-it -matters-g-o-o-g-l-e/), unfortunately, the video no longer seems to be up on the Google server. But while one can make general recommendations on "what is good API design", different languages have their own idioms (idia?) that might dictate a style or convention consistent with the "feel" of that language. In Python, for instance, there is the added feature of named arguments, which would not be covered in a Java or C++ discussion. So I think Denis's question was more one of API design, not about guessing. -- Paul From sierra_mtnview at sbcglobal.net Thu Nov 27 17:02:32 2008 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Thu, 27 Nov 2008 08:02:32 -0800 Subject: [Tutor] Installing the Numeric Module for 2.4 Again? In-Reply-To: <1c2a2c590811270444i7b6dd8am47eb565cd1b18cf3@mail.gmail.com> References: <492E2434.3090509@sbcglobal.net> <1c2a2c590811270444i7b6dd8am47eb565cd1b18cf3@mail.gmail.com> Message-ID: <492EC498.7020003@sbcglobal.net> An HTML attachment was scrubbed... URL: From kent37 at tds.net Thu Nov 27 18:59:12 2008 From: kent37 at tds.net (Kent Johnson) Date: Thu, 27 Nov 2008 12:59:12 -0500 Subject: [Tutor] Installing the Numeric Module for 2.4 Again? In-Reply-To: <492EC498.7020003@sbcglobal.net> References: <492E2434.3090509@sbcglobal.net> <1c2a2c590811270444i7b6dd8am47eb565cd1b18cf3@mail.gmail.com> <492EC498.7020003@sbcglobal.net> Message-ID: <1c2a2c590811270959q6ded615fte986c11aafe9dd7a@mail.gmail.com> On Thu, Nov 27, 2008 at 11:02 AM, Wayne Watson wrote: > Good. > > How about a test for Win XP? It's the same, just get to a command line and type python -c "import Numeric" python.exe has to be in your PATH, of course. Kent > Kent Johnson wrote: > > On Wed, Nov 26, 2008 at 11:38 PM, Wayne Watson > wrote: > > > A fellow user of an application that I share with others may not have > installed Numeric-24.2.win32-py2.4.exe. If I tell him to try it, will it > replace the duplicate module if in fact he has already done it? > > > It should be fine to reinstall it. It's also easy to test: > kent $ python -c "import Numeric" > Traceback (most recent call last): > File "", line 1, in > ImportError: No module named Numeric > > If you get an ImportError it is not installed. > > Kent > > > > -- > > Wayne Watson (Watson Adventures, Prop., Nevada City, CA) > > (121.01 Deg. W, 39.26 Deg. N) GMT-8 hr std. time) > > "Dreaming permits each and every one of us to be > quietly insane every night of our lives." > -- William Dement > Web Page: From jasdebord at gmail.com Fri Nov 28 16:51:33 2008 From: jasdebord at gmail.com (Jason DeBord) Date: Fri, 28 Nov 2008 16:51:33 +0100 Subject: [Tutor] mod_python Message-ID: Is mod_python the only way to integrate python and apache2 ? I am interested in using Python instead of PHP and would like to use Python's template style as well as a framework such as Pylons or Django. Thanks in advance! -- - - - - - - - - - - - - - Jason Limoges, France -------------- next part -------------- An HTML attachment was scrubbed... URL: From zstumgoren at gmail.com Fri Nov 28 16:59:46 2008 From: zstumgoren at gmail.com (Serdar Tumgoren) Date: Fri, 28 Nov 2008 10:59:46 -0500 Subject: [Tutor] mod_python In-Reply-To: References: Message-ID: mod_wsgi is another option that supposedly has a smaller memory footprint and, in my case, proved easier to configure than mod_python http://code.google.com/p/modwsgi/ http://code.djangoproject.com/wiki/django_apache_and_mod_wsgi -------------- next part -------------- An HTML attachment was scrubbed... URL: From roadierich at googlemail.com Fri Nov 28 17:35:22 2008 From: roadierich at googlemail.com (Rich Lovely) Date: Fri, 28 Nov 2008 16:35:22 +0000 Subject: [Tutor] mod_python In-Reply-To: References: Message-ID: Wsgi is also more portable than mod_python: mod_python is solely available on the Apache httpd, whereas wsgi is available on many more. --- Richard "Roadie Rich" Lovely Part of the JNP|UK Famille www.theJNP.com (Sent from my iPod - please allow me a few typos: it's a very small keyboard) On 28 Nov 2008, at 03:59 PM, "Serdar Tumgoren" wrote: > mod_wsgi is another option that supposedly has a smaller memory > footprint and, in my case, proved easier to configure than mod_python > > http://code.google.com/p/modwsgi/ > > http://code.djangoproject.com/wiki/django_apache_and_mod_wsgi > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Fri Nov 28 20:33:54 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 28 Nov 2008 19:33:54 -0000 Subject: [Tutor] mod_python References: Message-ID: "Jason DeBord" wrote > in using Python instead of PHP and would like to use Python's > template style > as well as a framework such as Pylons or Django. I can't speak for those two but ISTR that TurboGears had a fairly comprehensive set of notes on how to configure with lots of front ends including mod_python. Try checking out your preferred framework site you might find all you need there. mod_python is almost certainly not the *only* option, but it might be the best for you. Alan G From denis.spir at free.fr Fri Nov 28 21:55:59 2008 From: denis.spir at free.fr (spir) Date: Fri, 28 Nov 2008 21:55:59 +0100 Subject: [Tutor] attribute of built-in type Message-ID: <49305ADF.7090706@free.fr> Hello, I try to find a way to give a cutom type ('s instances) attributes like some built-in types have, for instance __name__. (For any reason, such attributes are not equally shared by all kinds of objects.) I tried to achieve that with inheritance, but I couldn't make it work with built-in types. I suspect I should use metatypes -- but have no experience in that field. It is probably not a proper use, anyway. Any hints welcome, thank you, denis From kent37 at tds.net Fri Nov 28 23:18:51 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 28 Nov 2008 17:18:51 -0500 Subject: [Tutor] attribute of built-in type In-Reply-To: <49305ADF.7090706@free.fr> References: <49305ADF.7090706@free.fr> Message-ID: <1c2a2c590811281418x5f46b1ddrbe96e2be9bf7900b@mail.gmail.com> On Fri, Nov 28, 2008 at 3:55 PM, spir wrote: > I try to find a way to give a cutom type ('s instances) attributes like some > built-in types have, for instance __name__. (For any reason, such attributes > are not equally shared by all kinds of objects.) > I tried to achieve that with inheritance, but I couldn't make it work with > built-in types. I suspect I should use metatypes -- but have no experience > in that field. It is probably not a proper use, anyway. I'm not sure what you are trying to accomplish. Custom classes have __name__ attributes; instances of built-in and custom classes don't have __name__ attributes. Kent From kent37 at tds.net Sat Nov 29 14:29:14 2008 From: kent37 at tds.net (Kent Johnson) Date: Sat, 29 Nov 2008 08:29:14 -0500 Subject: [Tutor] attribute of built-in type In-Reply-To: <49307855.9090900@free.fr> References: <49305ADF.7090706@free.fr> <1c2a2c590811281418x5f46b1ddrbe96e2be9bf7900b@mail.gmail.com> <49307855.9090900@free.fr> Message-ID: <1c2a2c590811290529n3a46150exc07a647e41f339dc@mail.gmail.com> On Fri, Nov 28, 2008 at 6:01 PM, spir wrote: > Kent Johnson a ?crit : >> I'm not sure what you are trying to accomplish. Custom classes have >> __name__ attributes; instances of built-in and custom classes don't >> have __name__ attributes. > > Hem, what do you mean? Functions, methods, classic and new style classes, > also modules etc... all have a __name__. They are instances of built-in > types (Er, for modules, I actually don't know -- yes, just checked it). As I > understand it, only instances of custom types and of "value" types (such as > int, str) do not have it. OK, functions (and methods, which are also functions, both of which are instances of some builtin type), classes (which are instances of type or classobj) and modules all have __name__ attributes. I guess what these all have in common is that there is special support in the compiler for creating them. In the case of new-style clases, this support is exposed in the metaclass mechanism - the class name is passed to the metaclass constructor explicitly. For functions and modules, the mechanism is not exposed AFAIK. > Anyway, do you have an idea how to let custom objects inherit such > attributes (*)? If they were of a custom type, one would just do it with > inheritance (multiple, if needed). Now, this does not seem to work with > buil-tins -- or I was unable to find the proper way. I don't understand this paragraph. When you say "custom objects" do you mean classes or instances? Custom classes do have __name__ attributes; instances in general do not, other than the special cases mentioned above. I *think* what you want is to be able to say something like class Foo(object): pass myFoo = Foo() and then have foo.__name__ == 'myFoo' Is that right? If so, first recognize that the object can be assigned to many names: foo = bar = baz = Foo() so what you are asking is not well defined. Second, search on comp.lang.python for some ideas, this request comes up there from time to time. Third, how about passing the name to the constructor, or assigning the attribute yourself? myFoo = Foo('myFoo') or myFoo = Foo() myFoo.__name__ = 'myFoo' Yes, you have to type the name more than once... AFAIK Python does not have any hook to modify assignment which I think is what you want. You might be able to do something like this with the ast module in Python 2.6. You would have to load the code for a module, compile it to the AST, modify the AST and compile it to code. Some examples of this: http://code.activestate.com/recipes/533145/ http://pyside.blogspot.com/2008/03/ast-compilation-from-python.html http://lucumr.pocoo.org/cogitations/2008/03/30/high-level-ast-module-for-python/ I know you explained before but I still don't understand *why* you want to do this... > (*) The point is that they can't be written by hand. How would you do it > e.g. that an attribute automatically holds the objects own name? You can > play with the namespace's dict, but it's the same thing. (It's like > inheriting for instance an integer's behaviour: yes, you can rewrite it from > scratch.) > class myInt(int): works > class myFunc(function): works not > TypeError: Error when calling the metaclass bases > type 'function' is not an acceptable base type I don't understand your point here. How would creating your own function class help? You can create classes whose instances are callable by defining a __call__() method in the class. Kent From sanelson at gmail.com Sun Nov 30 10:19:18 2008 From: sanelson at gmail.com (Stephen Nelson-Smith) Date: Sun, 30 Nov 2008 09:19:18 +0000 Subject: [Tutor] Capturing and parsing over telnet Message-ID: I want to write a program that connects to a TCP port using telnet, and issues commands, parsing the output the command provides, and then issuing another command. This might look like this: $ telnet water.fieldphone.net 7456 Welcome to water, enter your username >_ sheep Enter your password >_ sheep123 >_ examine here [some info to parse] [.] [.] >_ some command based on parsing the previous screen [more info to parse] [.] [.] I am confident I can parse the info, if I can read it in. I am not sure how to handle the telnet I/O How should I proceed? S. From david at abbottdavid.com Sun Nov 30 10:26:42 2008 From: david at abbottdavid.com (David) Date: Sun, 30 Nov 2008 04:26:42 -0500 Subject: [Tutor] Capturing and parsing over telnet In-Reply-To: References: Message-ID: <49325C52.2010403@abbottdavid.com> Stephen Nelson-Smith wrote: > I want to write a program that connects to a TCP port using telnet, > and issues commands, parsing the output the command provides, and then > issuing another command. > > This might look like this: > > $ telnet water.fieldphone.net 7456 > Welcome to water, enter your username >> _ sheep > Enter your password >> _ sheep123 >> _ examine here > [some info to parse] > [.] > [.] >> _ some command based on parsing the previous screen > [more info to parse] > [.] > [.] > > I am confident I can parse the info, if I can read it in. > > I am not sure how to handle the telnet I/O > > How should I proceed? > > S. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > How about pexpect; http://www.noah.org/wiki/Pexpect -- Powered by Gentoo GNU/LINUX http://www.linuxcrazy.com From sanelson at gmail.com Sun Nov 30 11:41:37 2008 From: sanelson at gmail.com (Stephen Nelson-Smith) Date: Sun, 30 Nov 2008 10:41:37 +0000 Subject: [Tutor] Capturing and parsing over telnet In-Reply-To: <49325C52.2010403@abbottdavid.com> References: <49325C52.2010403@abbottdavid.com> Message-ID: Hi, > How about pexpect; > http://www.noah.org/wiki/Pexpect Ah yes - I've used that before to good effect. ATM I'm playing with telnetlib. Is there a way to read everything on the screen, even if I don't know what it will be? eg: c = telnetlib.Telnet("test.lan") c.read_until("name: ") c.write("test\n") c.read_until("word: ") c.write("test\n") And now I don't know what I will see - nor is there a prompt which indicates that the output is complete. I effectively want something like c.read_everything() I tried c.read_all() but I don't get anything from that. Suggestions? S. From sanelson at gmail.com Sun Nov 30 12:55:21 2008 From: sanelson at gmail.com (Stephen Nelson-Smith) Date: Sun, 30 Nov 2008 11:55:21 +0000 Subject: [Tutor] Capturing and parsing over telnet In-Reply-To: References: <49325C52.2010403@abbottdavid.com> Message-ID: Hi, > I effectively want something like c.read_everything() Looks like read_very_eager() does what I want. S. From kent37 at tds.net Sun Nov 30 14:20:37 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 30 Nov 2008 08:20:37 -0500 Subject: [Tutor] attribute of built-in type In-Reply-To: <4931BD94.9000809@free.fr> References: <49305ADF.7090706@free.fr> <1c2a2c590811281418x5f46b1ddrbe96e2be9bf7900b@mail.gmail.com> <49307855.9090900@free.fr> <1c2a2c590811290529n3a46150exc07a647e41f339dc@mail.gmail.com> <4931BD94.9000809@free.fr> Message-ID: <1c2a2c590811300520y3a69329fp1a042461c46d640b@mail.gmail.com> On Sat, Nov 29, 2008 at 5:09 PM, spir wrote: > Kent Johnson a ?crit : >> On Fri, Nov 28, 2008 at 6:01 PM, spir wrote: >>> Kent Johnson a ?crit : >> OK, functions (and methods, which are also functions, both of which >> are instances of some builtin type), classes (which are instances of >> type or classobj) and modules all have __name__ attributes. > > You're right, actually, as I was studying a bit how /some/ built-in types > work, and they all had a __name__, I had a wrong impression about that > attribute. > >>> Anyway, do you have an idea how to let custom objects inherit such >>> attributes (*)? If they were of a custom type, one would just do it with >>> inheritance (multiple, if needed). Now, this does not seem to work with >>> buil-tins -- or I was unable to find the proper way. >> >> I don't understand this paragraph. When you say "custom objects" do >> you mean classes or instances? Custom classes do have __name__ >> attributes; instances in general do not, other than the special cases >> mentioned above. >> >> I *think* what you want is to be able to say something like >> class Foo(object): pass >> myFoo = Foo() >> and then have >> foo.__name__ == 'myFoo' > > Exactly, "custom objects" was a shortcut for "objects that are instances of > custom types". > >> Is that right? If so, first recognize that the object can be assigned >> to many names: >> foo = bar = baz = Foo() >> so what you are asking is not well defined. > > Right. I just need the first one. The object's birthname ;-) ; whatever it > may be in case of "sequential naming", like in your example (which can > happen in my case). > >> Second, search on comp.lang.python for some ideas, this request comes >> up there from time to time. >> >> Third, how about passing the name to the constructor, or assigning the >> attribute yourself? >> myFoo = Foo('myFoo') >> or >> myFoo = Foo() >> myFoo.__name__ = 'myFoo' >> Yes, you have to type the name more than once... > > Actually, it is not an big issue. There are workarounds, anyway (such as > exploring the current scope's dict /after/ object creation, and assigning > its name back to an attribute -- this can also be automatised for numerous > objects). > Still, it would help & spare time & energy... This is also for me (and > hopefully other readers) an opportunity to explore corners of the python > universe ;-) > >> AFAIK Python does not have any hook to modify assignment which I think >> is what you want. You might be able to do something like this with the >> ast module in Python 2.6. You would have to load the code for a >> module, compile it to the AST, modify the AST and compile it to code. >> Some examples of this: >> http://code.activestate.com/recipes/533145/ >> http://pyside.blogspot.com/2008/03/ast-compilation-from-python.html >> >> http://lucumr.pocoo.org/cogitations/2008/03/30/high-level-ast-module-for-python/ >> >> I know you explained before but I still don't understand *why* you >> want to do this... > > First, this problem occurs while I'm trying to use code of an external > module for a project of mine. My case is probably specific, otherwise this > issue would have been adressed long ago. > These objects are kinds of "models" -- they control the generation of other > objects -- but they are not classes, and can't be. As a consequence, the > generated objects do not know what they actually are. They have a type, of > course, but this type is general and not related to the real nature of the > objects that share it. It would be a first step if the generators first > would themselves know 'who' they are; then they would be able to pass this > information to their respective "chidren". This would be a very small and > harmful hack in the module's code (which is nice to study, not only for its > organisation, also because it is not built upon further modules). Do you know that you can probably just assign a __name__ attribute to the objects? Or name, or whatever you like? In [13]: class Foo(object): pass ....: In [14]: f=Foo() In [15]: f.name --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) /Users/kent/ in () AttributeError: 'Foo' object has no attribute 'name' In [16]: f.name = 'f' In [17]: f.name Out[17]: 'f' This will work for custom objects that do not have a __slots__ attribute. Perhaps you could wrap the creation of the objects in a function that gives them a name? >>> (*) The point is that they can't be written by hand. How would you do it >>> e.g. that an attribute automatically holds the objects own name? You can >>> play with the namespace's dict, but it's the same thing. (It's like >>> inheriting for instance an integer's behaviour: yes, you can rewrite it >>> from >>> scratch.) >>> class myInt(int): works >>> class myFunc(function): works not >>> TypeError: Error when calling the metaclass bases >>> type 'function' is not an acceptable base type >> >> I don't understand your point here. How would creating your own >> function class help? > > It is an illustration of what i'm trying to do: let a class inherit from > 'function' so that its instances get a __name__. This wouldn't be a harmful > overload I guess, as these objects have a __call__ method anyway (the reason > why I chose 'function'). I doubt this would do what you want. AFAICT the function name is assigned by the compiler, not by the function constructor. (That is a bit of oversimplification but close enough. I think the compiler creates a code object, passing its name to the constructor; when a function object is wrapped around the code object, it pulls its name from the code object.) >> Kent PS Please use Reply All to reply to the list. > > Thank you for your attention and help, > Denis > > > From kent37 at tds.net Sun Nov 30 17:14:10 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 30 Nov 2008 11:14:10 -0500 Subject: [Tutor] Text Scatter Plots? In-Reply-To: <48E0BD38.9000904@sbcglobal.net> References: <48E0BD38.9000904@sbcglobal.net> Message-ID: <1c2a2c590811300814sb14909fhddac1155fc0f1cec@mail.gmail.com> On Mon, Sep 29, 2008 at 6:34 AM, Wayne Watson wrote: > Is there a text graphics module that does say scatter plots or histograms? > I'm thinking of stuff prior to the graphics era of computing. I'm looking > for something really simple. Not simple but maybe helpful: http://www-rcf.usc.edu/~kaizhu/work/asciiporn/ Despite the name it has nothing to do with porn, AFAICT. Kent From dineshbvadhia at hotmail.com Sun Nov 30 23:51:08 2008 From: dineshbvadhia at hotmail.com (Dinesh B Vadhia) Date: Sun, 30 Nov 2008 14:51:08 -0800 Subject: [Tutor] Reading gzip files Message-ID: I'm reading gzip files and writing the content out to a text file line by line. The code is simply: import gzip list_zipfiles = dircache.listdir(zipfolder) writefile = "out_file.txt" fw = open(writefile, 'w') for ziparchive in list_zipfiles: zfile = gzip.GzipFile(zipfolder + ziparchive, "r") for line in zfile: fw.write(line) zfile.close() fw.close() The Traceback is: Traceback (most recent call last): File "....py", line 47, in for line in zfile: File "C:\Python25\lib\gzip.py", line 444, in next line = self.readline() File "C:\Python25\lib\gzip.py", line 399, in readline c = self.read(readsize) File "C:\Python25\lib\gzip.py", line 227, in read self._read(readsize) File "C:\Python25\lib\gzip.py", line 275, in _read self._read_eof() File "C:\Python25\lib\gzip.py", line 311, in _read_eof raise IOError, "CRC check failed" IOError: CRC check failed I've checked the Python docs and online but cannot find a solution to the problem. Thanks. Dinesh -------------- next part -------------- An HTML attachment was scrubbed... URL: