newbie question
I am new to python; any insight on the following would be appreciated, even if it is the admonition to RTFM (as long as you can direct me to a relevant FM) Is there a standard approach to enumerated types? I could create a dictionary with a linear set of keys, but isn't this overkill? There is afterall a "True" and "False" enumeration for Boolean. Is there a way to ignore case in string comparisons? I want 'Oranges' to equal 'oranges' when using the evaluation operator (==). I don't care about string inequalities (<, >) If I am compelled to use dictionaries for enumerated types, is there a way to generate unique keys automatically: something like "myDict.appendWithAutoKey("Persimmons")"? Is there a way to overload operators to accommodate an enumeration? For example, newFruit = enumerationFruit('Cumquat')#use it like you would use list() new = newFruit + 14# this should throw an exception because of different types Finally, (for now at least) consider the following list. myList = [apple, 13, plum, cherry, 'Spam', tomato, 3.35] Exactly how does the "for x in myList" work? If the list is a heterogeneous list of disparate types, the == operator works fine, independent of type. For example, (if x == 'spam') evaluates as false if the item in the list is an integer. But if I try to do this: (if x.__abs()__) throws an exception if x "pulls" a non integer from the list. Wouldn't you think that an iterative would have the "sense" to understand that in this limited scope if a method didn't apply to the iterator just "fail" (i.e. evaluate to False) the evaluation and move along? Do I have to manually interrogate each iteration for the proper type before I test? Think about it; the interpreter has to evaluate disparate types for equality. How exactly does the it "know" that for this iteration, x is an integer, and the evaluation (if x == 'spam') is False, and doesn't throw an exception for a type mismatch? Thanks in advance for your insight, David, Melbourne, Florida. -- http://mail.python.org/mailman/listinfo/python-list
Newbie Question
Hi Everybody, I'm pretty new to Python and would like to ask a few questions. I have this setup on a Fedora Core 3 box. Python 2.3.4 wxPython-common-gtk-ansi-2.5.3.1-fc2_py2.3 mod_python-3.1.3-5 Apache/2.0.52 I have a test.py which looks like this: from mod_python import apache def handler(req): req.write("Hello World!") return apache.OK Whenever I access test.py from my browser it says "The page cannot be found" , I have the file on /var/www/html, what did I miss? Thanks in advance, Joel -- http://mail.python.org/mailman/listinfo/python-list
newbie question
Hello All, What is the python equivalent of the following statement? while (n--) Thank you. -d4 -- http://mail.python.org/mailman/listinfo/python-list
Newbie question
Hi all I'm wanting to use python to display some jpeg images, maybe present them at a percentage of their actual size etc. How do I display an image in Python? - I've run over Tkinter, but obviously in all the wrong places. Any help or sample code would be much appreciated. Ryan -- http://mail.python.org/mailman/listinfo/python-list
newbie question
Hello, How do i create two memory mapped buffers(mmap) and pass an index to select which one needs to be populated? Is it possible to define the size of the buffer? -SB -- http://mail.python.org/mailman/listinfo/python-list
newbie question
I heard that python or other script languages can be used as game scripting.. Actually It's so hard to understand what that means for newbies like me? What's mean being used as game script? Could show me simple example like 'hello world'? I'll be appreciated.. -- http://mail.python.org/mailman/listinfo/python-list
Newbie question
Hi, ive just started playing around with python and wondered if someone could poing me in the right way here. I have a xmlrpc server simple script: Server script: import SimpleXMLRPCServer class tpo: def retTPOXML(): theFile=open('tpo.xml') try: self.strXML = theFile.read() return self.strXML finally: theFile.close() tpo_object = tpo() server = SimpleXMLRPCServer.SimpleXMLRPCServer(("localhost",)) server.register_instance(tpo_object) print "Listening on port " server.serve_forever() and im trying to print the return value with any luck Client Code: import xmlrpclib server = xmlrpclib.ServerProxy("http://localhost:";) current = server.retTPOXML print current Any comment would be appriciated -- http://mail.python.org/mailman/listinfo/python-list
Newbie Question
I am trying to learn Python and I have a few questions. I have created a Class that is essentially a canvas with a red background. After creation I want to change the background to green. However I am having problems doing this. Here is my code: from Tkinter import * class MyApp: def __init__(self, parent): self.myParent = parent self.myContainer = Frame(parent) self.myContainer.pack() self.b1 = Canvas(self.myContainer, background="red").grid(row=0, column=0) def ChangebgColor(self): self(bg="green") root = Tk() myapp=MyApp(root) #Everything is fine at this point. raw_input() ChangebgColor(myapp.b1) # Error Message at this point raw_input() Any help will be greatly appreciated. -- http://mail.python.org/mailman/listinfo/python-list
newbie question
i have this program === from sys import * import math import math, Numeric from code import * from string import * from math import * from dataSet import * from string import * def drawAsciiFile(): _fileName=str(argv[1]) __localdataSet=DataSet(_fileName) #_PlotCols=string.split(str(argv[2]),' ') #_PlotColsInt=[] '''for s in _PlotCols: _PlotColsInt.append(int(s)) CountourPlots(__localdataSet,_PlotColsInt) ''' print __data=__localdataSet.GetData() print max(__data[:,11]) if __name__ == "__main__": drawAsciiFile() how i can link it to read my file examle.txt? thanks michael -- http://mail.python.org/mailman/listinfo/python-list
Newbie Question
I have a file that contains many lines, each of which consists of a string of comma-separated variables, mostly floats but some strings. Each line looks like an obvious tuple to me. How do I save each line of this file as a tuple rather than a string? Or, is that the right way to go? Thank you. Tom Strickland -- http://mail.python.org/mailman/listinfo/python-list
newbie question
Hi, I'm brand new to using/playing with Python, and I have what is likely a very simple question but can't seem to figure it out. I wrote up a script in my preferred text editor. It contains maybe ten lines of code. I want to be able to execute those code lines with a single command either from the inline mode or from IDLE. How do I do this? I saved the file (myscript.py) in a folder that I've specified in my PYTHONPATH environment variable, and when I type >>> import myscript the script runs. If, later during the same session, I type >>> myscript all I get for output is Somwhere in the beginning tutorial there's this line: "The script can be given a executable mode, or permission, using the chmod command: $ chmod +x myscript.py" Which I took to mean that if I enter that I would be able to do what I wanted. But no, it just highlights 'myscript' in red and says it's a syntax error. What am I missing? thanks for your help! -- http://mail.python.org/mailman/listinfo/python-list
newbie question
what does it mean when there are [0] or [1] after a variable? e.g. print 'Message %s\n%s\n' % (num, data[0][1]) -- http://mail.python.org/mailman/listinfo/python-list
Newbie Question
Hi everyone I'm sure this question is kinda stupid and has been answered a few times before... but I need your help! I'm writing a small application where the user can analyze some text based on a set of changing conditions , and right now I'm stuck on a point where I'd like to automatically generate new classes that operate based on those user-defined conditions. Is there a way in python to define a class in runtime? For instance, can I define a class which extends another(that I have previously defined in some module) , create some instance completely on the fly and then add/redefine methods to it? If affirmative, I've thought of a problem I would maybe have to face: as the class has been defined by direct input to the python interpreter, I could only create instances of it on the same session I entered the definition(because it's not on a module I can load on future uses) but not afterwards. Is there a way to keep that code? Even more newbie paranoia: what would happen if I make that 'on the fly" object persist via pickle? Where would Python find the code to handle it once unpickled on another session (once again, i take that no code with the definition of that instance would exist, as it was never stored on a module). Hope it wasn't too ridiculous an idea. Thank you for your time, guys. -- http://mail.python.org/mailman/listinfo/python-list
newbie question
Hi, i wrote a simple script (which follows) to insert a table in the database.i could execute this query and get the result in python shell.but when i open "my sql enterprise manager" i couldnt find the table"animals".it would be so kind of you if someone could help me,,, import dbi import odbc conn=odbc.odbc("DSN=mydatabase;UID=xxx;PWD=yyy") cursor=conn.cursor() cursor.execute("Create table animals(parent char(50),child char(50))") cursor.execute("insert into animals values('lion','cub')") cursor.execute("insert into animals values('goat','lamb')") cursor.execute("select * from animals") print cursor.fetchall() Rgds Kavitha - Heres a new way to find what you're looking for - Yahoo! Answers -- http://mail.python.org/mailman/listinfo/python-list
Newbie Question
Hello all I am just starting to play with programing again as a hobby. I have heard good things about python. I have not really looked into the language much. My question is, will python make programs with a gui under windows xp. If it will do this I will explore the language more, if not I will try some other language. Reid -- http://mail.python.org/mailman/listinfo/python-list
newbie question
>>> asd={} >>> asd={1:2,3:4,4:5} >>> print asd {1: 2, 3: 4, 4: 5} >>> asd.has_key(3) True >>> asd.update() >>> print asd {1: 2, 3: 4, 4: 5} >>> what does asd.update() signifies. What is the use of it. Any comments would help to understand it. Thanks Mohideen -- http://mail.python.org/mailman/listinfo/python-list
Newbie question
Hi list, this is somewhat of a newbie question that has irritated me for a while. I have a file test.txt: 0.3434 0.5322 0.3345 1.3435 2.3345 5.3433 and this script lines = open("test.txt","r").readlines() for line in lines: (xin,yin,zin) = line.split() x = float(xin) y = float(yin) z = float(zin) Is there a way to go from line.split() to x,y,z as floats without converting each variable individually? Cheers Tommy -- http://mail.python.org/mailman/listinfo/python-list
Newbie Question
I am new to programming, and I've chosen python to start with. I wrote a simple program that asks several questions and assings each one of them a variable via raw_input command. I then combined all the variables into one like this a = b + c + d. After this I wrote these values to a file. What I want to do now is be able to search through the file for any data in there. Is this possible? -- http://mail.python.org/mailman/listinfo/python-list
a newbie question
In what directory are the preinstalled python libraries located on a Linux RH9 machine? -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie question
Hello David, > Is there a standard approach to enumerated types? I could create a > dictionary with a linear set of keys, but isn't this overkill? There is > afterall a "True" and "False" enumeration for Boolean. Google for Python + enum. (A good one is: http://www.norvig.com/python-iaq.html) > Is there a way to ignore case in string comparisons? I want 'Oranges' to > equal 'oranges' when using the evaluation operator (==). I don't care about > string inequalities (<, >) s1.lower() == s2.lower() > If I am compelled to use dictionaries for enumerated types, is there a way > to generate unique keys automatically: something like > "myDict.appendWithAutoKey("Persimmons")"? http://docs.python.org/lib/typesmapping.html and "setdefault" > Is there a way to overload operators to accommodate an enumeration? For > example, > > newFruit = enumerationFruit('Cumquat')#use it like you would use > list() > new = newFruit + 14# this should throw an exception because of > different types http://www.python.org/doc/2.3.4/ref/numeric-types.html > Finally, (for now at least) consider the following list. > > myList = [apple, 13, plum, cherry, 'Spam', tomato, 3.35] > > Exactly how does the "for x in myList" work? It binds 'x' in the body of the loop to each item in sequence. > Wouldn't you think that an iterative would have the "sense" to understand > that in this limited scope if a method didn't apply to the iterator just > "fail" (i.e. evaluate to False) the evaluation and move along? How would it konw that a method don't apply to an object? > Do I have to manually interrogate each iteration > for the proper type before I test? Yes. Or you can filter the sequence: for x in [i for i in list if type(i) == type(1)] > Think about it; the interpreter has to evaluate disparate types for > equality. How exactly does the it "know" that for this iteration, x is an > integer, and the evaluation (if x == 'spam') is False, and doesn't throw an > exception for a type mismatch? Python is strongly type in the sense that each object has a type. I don't remember exactly how does Python resolve operators and methods, but if it's can't find one for == it'll return False (IMO). Bye. -- Miki Tebeka <[EMAIL PROTECTED]> http://tebeka.bizhat.com The only difference between children and adults is the price of the toys -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie question
David Wurmfeld wrote: I am new to python; any insight on the following would be appreciated, even if it is the admonition to RTFM (as long as you can direct me to a relevant FM) Your questions are esoteric enough that, even though the relevant information *is* in the FM, RTFM would be a really slow and painful way to learn it. . . Is there a standard approach to enumerated types? I could create a dictionary with a linear set of keys, but isn't this overkill? The problem is that enumerated types get used for so many different things that it isn't easy to come up with One Obvious Way To Do It. A fairly simple version: Py> class Enum(object): ... def __init__(self, attrs): ...for num, attr in enumerate(attrs): ... setattr(self, attr, num) ...self._values = attrs ... def get_name(self, value): ...return self._values[value] ... Py> Fruit = Enum(["apple", "banana", "pear"]) Py> Fruit.pear 2 Py> Fruit.banana 1 Py> Fruit.apple 0 Py> Fruit.get_name(0) 'apple' Py> Fruit.get_name(1) 'banana' Py> Fruit.get_name(2) 'pear' Py> Fruit.get_name(3) Traceback (most recent call last): File "", line 1, in ? File "", line 7, in get_name IndexError: list index out of range A more complete answer can be found at the link Miki gave: http://www.norvig.com/python-iaq.html (look for Enumerated Types) (Don't get too concerned about some of the other things Peter says on the rest of that page - the more glaring omissions he mentions have been addressed for Python 2.4) There is afterall a "True" and "False" enumeration for Boolean. True/False isn't actually an enumeration - they're special objects for boolean values (i.e. "True is 1" and "False is 0" both return False) Is there a way to ignore case in string comparisons? I want 'Oranges' to equal 'oranges' when using the evaluation operator (==). I don't care about string inequalities (<, >) The standard way is to invoke the string .lower() method, and compare the forced lowercase versions instead. If I am compelled to use dictionaries for enumerated types, is there a way to generate unique keys automatically: something like "myDict.appendWithAutoKey("Persimmons")"? The enumerate() function is generally the easiest way to get hold of a unique index for each item in a sequence. Is there a way to overload operators to accommodate an enumeration? For example, newFruit = enumerationFruit('Cumquat')#use it like you would use list() new = newFruit + 14# this should throw an exception because of different types Certainly - Python allows almost all operations to be overridden (id() is the only one I can think of that is off limits!) Again, Miki already pointed you in the right direction: http://www.python.org/doc/2.4/ref/specialnames.html (I'd advise *against* inheriting from int or long though - trying to prevent the base type from leaking through the API is a serious PITA) Finally, (for now at least) consider the following list. myList = [apple, 13, plum, cherry, 'Spam', tomato, 3.35] Exactly how does the "for x in myList" work? The specified operation is applied to each item in the sequence. The behaviour on heterogenous types will depend on the exact operation and how it handles type differences. evaluation and move along? Do I have to manually interrogate each iteration for the proper type before I test? It depends on the operation - checking the type can work, as can looking for an appropriate attribute: [abs(x) for x in myList if hasattr(x, "__abs__")] Think about it; the interpreter has to evaluate disparate types for equality. How exactly does the it "know" that for this iteration, x is an integer, and the evaluation (if x == 'spam') is False, and doesn't throw an exception for a type mismatch? Easy: if the types are different, the objects are almost certainly different, so the interpreter applies that rule as the default. It *is* possible to alter that determination though: Py> from decimal import Decimal Py> Decimal(1) == int(1) True Py> type(Decimal(1)) Py> type(int(1)) The reason your __abs__ example blows up is because the relevant attribute is missing for string objects - and there's nothing the interpreter can do about that. If you don't care, you need to tell the interpreter so (using either hasattr() or try/except) Cheers, Nick. -- Nick Coghlan | [EMAIL PROTECTED] | Brisbane, Australia --- http://boredomandlaziness.skystorm.net -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie question
David Wurmfeld wrote: > I am new to python; any insight on the following would be appreciated, even > if it is the admonition to RTFM (as long as you can direct me to a relevant > FM) http://www.python.org/doc/ > Is there a standard approach to enumerated types? I could create a > dictionary with a linear set of keys, but isn't this overkill? There is > afterall a "True" and "False" enumeration for Boolean. If you're lazy, you can just use ints, like the "calendar" module did for the weekday names: MONDAY = 0 TUESDAY = 1 WEDNESDAY = 2 THURSDAY = 3 FRIDAY = 4 SATURDAY = 5 SUNDAY = 6 This can be more concisely written as: MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY = xrange(7) If you want an enumeration like bool where printing an enumeration value prints its name instead of the int, you can do something like: class Weekday(int): _NAMES = ('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday') def __repr__(self): return Weekday._NAMES[self] # Monday = Weekday(0); Tuesday = Weekday(1); etc. for i, dayName in enumerate(Weekday._NAMES): globals()[dayName] = Weekday(i) If you'd rather refer to the names as, e.g., "Weekday.Monday", you can use setattr(Weekday, dayName, Weekday(i)) If you have multiple enum classes to write, you can do: def enum(*names): class Enum(int): _NAMES = names def __repr__(self): return Enum._NAMES[self] for i, name in enumerate(names): setattr(Enum, name, Enum(i)) return Enum Weekday = enum('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday') Sex = enum('Female', 'Male') > Is there a way to ignore case in string comparisons? I want 'Oranges' to > equal 'oranges' when using the evaluation operator (==). I don't care about > string inequalities (<, >) s1.lower() == s2.lower() > If I am compelled to use dictionaries for enumerated types, is there a way > to generate unique keys automatically: something like > "myDict.appendWithAutoKey("Persimmons")"? > > Is there a way to overload operators to accommodate an enumeration? There's a way to overload operators for any class, not just enumerations. See http://docs.python.org/ref/specialnames.html, and pay special attention to section 3.3.7. For operations that don't make sense, you can "return NotImplemented" or "raise TypeError()" > Finally, (for now at least) consider the following list. > > myList = [apple, 13, plum, cherry, 'Spam', tomato, 3.35] > > Exactly how does the "for x in myList" work? It works as if you had written: for _i in xrange(len(myList)): x = myList(_i) ... > If the list is a heterogeneous list of disparate types, the == operator > works fine, independent of type. > For example, (if x == 'spam') evaluates as false if the item in the list is > an integer. But if I try to do this: (if x.__abs()__) throws an exception It should always raise an exception. Perhaps you meant "if abs(x)", in which case you can just write "if x", which is equivalent in any class that correctly implements __abs__ and __nonzero__. If you meant to test whether x.__abs__ exists, you can use "if hasattr(x, '__abs__')". > if > x "pulls" a non integer from the list. Wouldn't you think that an iterative > would have the "sense" to understand that in this limited scope if a method > didn't apply to the iterator just "fail" (i.e. evaluate to False) the > evaluation and move along? No, for the same reason that 17 + 'x' should not just evaluate to False and move along. > Do I have to manually interrogate each iteration > for the proper type before I test? If the operations you want to use don't apply to all of your data, then they probably shouldn't be in the same list. > Think about it; the interpreter has to evaluate disparate types for > equality. How exactly does the it "know" that for this iteration, x is an > integer, Because type(x) == int. > and the evaluation (if x == 'spam') is False, It looks for the methods __eq__ and __cmp__ for the left-side object, in that order. If neither is implemented, it looks at the right side. > and doesn't throw an exception for a type mismatch? Originally, for technical reasons, comparisions couldn't throw exceptions at all, which is why the built-in types define meaningless comparisons like >>> 2004 < 'spam' 1 >>> [] < {} 0 For ==, the reasoning is that equality implies comparibility, and contrapositively, if two objects aren't even comparable they aren't equal. -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie question
> It works as if you had written: > > for _i in xrange(len(myList)): > x = myList(_i) No, as this implies that the variable has to support random access using indices. But all that's required is the iterable-interface beeing supported - by calling __iter__ and .next() on the resulting object. -- Regards, Diez B. Roggisch -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie question
David Wurmfeld wrote: I am new to python; any insight on the following would be appreciated, even if it is the admonition to RTFM (as long as you can direct me to a relevant FM) Is there a standard approach to enumerated types? I could create a dictionary with a linear set of keys, but isn't this overkill? There is afterall a "True" and "False" enumeration for Boolean. Not a standard one, but here's what I use: class Enum(int): __slots__ = ("_name") def __new__(cls, val, name): v = int.__new__(cls, val) v._name = str(name) return v def __str__(self): return self._name def __repr__(self): return "%s(%d, %r)" % (self.__class__.__name__, self, self._name) def __cmp__(self, other): if isinstance(other, int): return int.__cmp__(self, other) if type(other) is str: return cmp(self._name, other) raise ValueError, "Enum comparison with bad type" class Enums(list): def __init__(self, *init): for i, val in enumerate(init): if issubclass(type(val), list): for j, subval in enumerate(val): self.append(Enum(i+j, str(subval))) elif isinstance(val, Enum): self.append(val) else: self.append(Enum(i, str(val))) def __repr__(self): return "%s(%s)" % (self.__class__.__name__, list.__repr__(self)) -- ~ Keith Dart <[EMAIL PROTECTED]> public key: ID: F3D288E4 = -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie question
David Wurmfeld wrote: I am new to python; any insight on the following would be appreciated, even if it is the admonition to RTFM (as long as you can direct me to a relevant FM) Is there a standard approach to enumerated types? I could create a dictionary with a linear set of keys, but isn't this overkill? There is afterall a "True" and "False" enumeration for Boolean. To actually answer your question, no, there is no standard for enums in python. There are custom hacks for it that you can search for. Boo, a programming language that is virtually identical to python, does have standard enums: enum Color: Red Green Blue See http://boo.codehaus.org/ In fact, since not many seem to be aware of its existence, I encourage everyone here to check out boo as an alternative to python. Is there a way to ignore case in string comparisons? I want 'Oranges' to equal 'oranges' when using the evaluation operator (==). I don't care about string inequalities (<, >) No, not with the == operator, unless you use: s1.lower() == s2.lower() Visual Basic is the only language I am aware of that has case-insensitive strings. Finally, (for now at least) consider the following list. myList = [apple, 13, plum, cherry, 'Spam', tomato, 3.35] Exactly how does the "for x in myList" work? If the list is a heterogeneous list of disparate types, the == operator works fine, independent of type. For example, (if x == 'spam') evaluates as false if the item in the list is an integer. But if I try to do this: (if x.__abs()__) throws an exception if x "pulls" a non integer from the list. Wouldn't you think that an iterative would have the "sense" to understand that in this limited scope if a method didn't apply to the iterator just "fail" (i.e. evaluate to False) the evaluation and move along? Do I have to manually interrogate each iteration for the proper type before I test? Think about it; the interpreter has to evaluate disparate types for equality. How exactly does the it "know" that for this iteration, x is an integer, and the evaluation (if x == 'spam') is False, and doesn't throw an exception for a type mismatch? Because python is a strongly typed. If you want to perform a type specific operation like abs() or string.lower(), but the object's type may not be the right type, then you have to check its type first. In boo, we have an "isa" operator for this purpose: if x isa string: or: for item in myList: given typeof(item): when string: print item.ToLower() when int: print Math.Abs(item) -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie question
Doug Holton wrote: David Wurmfeld wrote: I am new to python; any insight on the following would be appreciated, even if it is the admonition to RTFM (as long as you can direct me to a relevant FM) Is there a standard approach to enumerated types? I could create a dictionary with a linear set of keys, but isn't this overkill? There is afterall a "True" and "False" enumeration for Boolean. To actually answer your question, no, there is no standard for enums in python. There are custom hacks for it that you can search for. Boo, a programming language that is virtually identical to python, does have standard enums: enum Color: Red Green Blue See http://boo.codehaus.org/ In fact, since not many seem to be aware of its existence, I encourage everyone here to check out boo as an alternative to python. Is there a way to ignore case in string comparisons? I want 'Oranges' to equal 'oranges' when using the evaluation operator (==). I don't care about string inequalities (<, >) No, not with the == operator, unless you use: s1.lower() == s2.lower() Visual Basic is the only language I am aware of that has case-insensitive strings. Finally, (for now at least) consider the following list. myList = [apple, 13, plum, cherry, 'Spam', tomato, 3.35] Exactly how does the "for x in myList" work? If the list is a heterogeneous list of disparate types, the == operator works fine, independent of type. For example, (if x == 'spam') evaluates as false if the item in the list is an integer. But if I try to do this: (if x.__abs()__) throws an exception if x "pulls" a non integer from the list. Wouldn't you think that an iterative would have the "sense" to understand that in this limited scope if a method didn't apply to the iterator just "fail" (i.e. evaluate to False) the evaluation and move along? Do I have to manually interrogate each iteration for the proper type before I test? Think about it; the interpreter has to evaluate disparate types for equality. How exactly does the it "know" that for this iteration, x is an integer, and the evaluation (if x == 'spam') is False, and doesn't throw an exception for a type mismatch? Because python is a strongly typed. If you want to perform a type specific operation like abs() or string.lower(), but the object's type may not be the right type, then you have to check its type first. In boo, we have an "isa" operator for this purpose: if x isa string: or: for item in myList: given typeof(item): when string: print item.ToLower() when int: print Math.Abs(item) It appears you should read your own remarks from the "Web forum (made by python)" thread :-) whereas-my-ego-couldn't-be-smaller-ly yr's - steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie question
David Wurmfeld wrote: I am new to python; any insight on the following would be appreciated, even if it is the admonition to RTFM (as long as you can direct me to a relevant FM) Is there a standard approach to enumerated types? I could create a dictionary with a linear set of keys, but isn't this overkill? There is afterall a "True" and "False" enumeration for Boolean. To actually answer your question, no, there is no standard for enums in python. There are custom hacks for it that you can search for. This is a good sugestion for Python 3.0, a.k.a. Python 3000: http://www.python.org/cgi-bin/moinmoin/Python3.0 In the future you may be able to to this: enum Color: Red Green Blue However, Python 3.0 is likely years away. If you want to know how to run this code today, consult Fredrik Lundh. -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie question
On Mon, 20 Dec 2004 18:06:36 -0600, Doug Holton <[EMAIL PROTECTED]> wrote: > To actually answer your question, no, there is no standard for enums in > python. There are custom hacks for it that you can search for. > > This is a good sugestion for Python 3.0, a.k.a. Python 3000: > http://www.python.org/cgi-bin/moinmoin/Python3.0 > > In the future you may be able to to this: > > enum Color: > Red > Green > Blue > > However, Python 3.0 is likely years away. If you want to know how to > run this code today, consult Fredrik Lundh. Is this a Sig? What is this referring to? You've said it in reply to more than one post in the last week. Got a url I can read about the Fredrik Lundh Python Syntax Manglation Consulting Service? Stephen. -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie question
Stephen Thorne wrote:' > Is this a Sig? What is this referring to? You've said it in reply to > more than one post in the last week. Got a url I can read about the > Fredrik Lundh Python Syntax Manglation Consulting Service? it's the new Boo marketing motto: "have you harrassed a Pythoneer today?" -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie question
Fredrik Lundh wrote: > it's the new Boo marketing motto: "have you harrassed a Pythoneer today?" Fredrik, I think you're being a little bit injust. As far as I could see, everythime the word "boo" is typed, some sort of censorship or plain bashing comes up, and I think this is not fair. In my case, if some topic or thread is not of my interest, I simply skip it. Why don't we all do the same and live in peace? :-) By the way, this is from comp.lang.python home page: "Pretty much anything Python-related is fair game for discussion, and the group is even fairly tolerant of off-topic digressions" Seeing what was going on in this thread, I think that we probably should delete this part, because this is getting far from "fairly tolerant". -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie question
Luis M. Gonzalez wrote: As far as I could see, everythime the word "boo" is typed, some sort of censorship or plain bashing comes up, and I think this is not fair. Luis, your defense of the genial nature of the newsgroup/mailing list is admirable, and I thank you for it. I think doing this by defending Doug's postings, however, might weaken the strength of your position just a little. (Okay, I mean "a lot".) About the only time the word "boo" _does_ come up, it comes up in one of Doug's posts, often in an apparent attempt to "help" a Python newbie by pointing him in a misleading manner to an entirely different language which just happens to have a syntax that was inspired by and looks a fair bit like Python's. Until Doug posted about "virtually identical" (and note he didn't mention the syntax at the time, thus my wondering if he meant the whole language), I had never noticed him or Boo. Yes, in spite of all the past postings. I look at postings by newbies and try to help; I rarely look carefully at the other replies, and if I ever saw a "there's also this thing called Boo" post, I suspect I just mentally blanked out of disinterest and moved on. As a result of all the activity in the "Boo who?" thread, however, I went and searched a bit to find out who this Doug character is. It turns out that he's been mentioning Boo in postings *to newbies* repeatedly over the last few months. These are people trying to use Python, having a question or difficulty about it, and he launches into a sales job about some other language. Would you defend someone who came into this group and responded (admittedly helpfully, sometimes, in other ways) to newbie questions by constantly saying "you can do this much more easily in Perl of course, see www.perl.codehaus.org"? I think you'd find that after the first few posts like that, it was getting tedious. Then downright offensive. And yet Perl has more in common with Python than Boo does! What Doug has been doing is like standing at the door of a mission run by a church and trying to redirect those coming for help to a different church down the street, with promises that the meals are better. And when one of the volunteers comes out and looks offended, he turns on them and accuses them of religious persecution, and being unfriendly to boot. By the way, this is from comp.lang.python home page: "Pretty much anything Python-related is fair game for discussion, and the group is even fairly tolerant of off-topic digressions" Boo is not Python related. It's that simple. Boo has some passing resemblance to Python, and claims that it's much more than that are patently false. And clearly designed to be marketing propaganda to get more Boo users onboard. I wouldn't have seen this with only one or two posts by Doug, but after reviewing his recent posting history I can only say that I'm actually appalled at his gall in the matter. Seeing what was going on in this thread, I think that we probably should delete this part, because this is getting far from "fairly tolerant". I believe the definition of "fairly tolerant" doesn't necessarily imply total tolerance of all topics under any circumstances. (And I know you didn't mean that.) If Doug wants to come in from time to time and mention Boo, however, he's welcome to do so. (And no, I'm not a moderator, I just get one opinion, like everybody else.) He might get a few people questioning Boo's merits each time, but that's par for the course. If he doesn't like the heat, he can stay out of the kitchen. More likely, if he can accept such posts, or ignore them, he'll be making his point, marketing his pet language, and making a few converts. If, on the other hand, he keeps jumping on newbies, who I imagine are often overwhelmed by Python as it is, and who just want an answer to their one simple question, and he shouts "Boo" at them all the time, then the rest of us are going to feel both offended that he's standing on our corner where we're trying to help people, and worried that he's misrepresenting Boo to Python newbies and confusing them even more than they might already be. Doug: move on, there's another street corner just down thataway, and it's called comp.lang.boo. Or the Boo mailing list or your own blog or something. I could go on, but that's enough of a rant as it is. Luis, I have appreciated reading your thoughtful and caring words on this whole subject, and I understand your point of view. I just don't share it in this instance and wanted to get this off my chest. Thanks for listening. :-) -Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie question
Peter, Thank you for taking the time to reply in such a detailed and polite way. I'm satisfied by your last post and, although I beg to disagree in a few points, I'm glad to see that we are all slowly going back to a civil way of expressing ourselves. Regarding my first post in this thread, I hope I didn't offend you. I just wanted to point out that there were some attitudes from you and from others that, in my oppinion, were a little bit too harsh. Sometimes it seems that instead of replying, you are making absolute statements intended to disqualify other people's oppinions, leaving no place for a continuing discussion of these matters. But I want to say that I recognize your labor here when it comes to help newbies and the time you spend in this list particicipating and contributing. And I also recognize that you are capable of "slowing down" and make your thoughts clear. As for your comment about Boo: > Boo is not Python related. It's that simple. Boo has some > passing resemblance to Python, and claims that it's much > more than that are patently false. And clearly designed > to be marketing propaganda to get more Boo users onboard Perhaps I don't measure that relativity with the same ruler, but as far as I could see when playing with Boo, it is very similar to Python. Anyway, I don't want to appear as a promoter or evangelist of Boo, I'm just someone who tested it and liked it. Also, you should consider that, preferences aside, there might be pythonistas in situations where they are forced to work with Microsoft technologies, and since programmers use tools (and we are discussing about tools here, not religions) I think it's pertinent to discuss it here. Amyway, I wouldn't want to use this list to talk about Boo, because I think that the best place to do it is comp.lang.boo. However, since I think it is definetely python related (I know you disagree, but others don't) I see no harm in mentioning it here occasionally. regards, Luis -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie question
Fredrik Lundh wrote: "have you harrassed a Pythoneer today?" Yes, you have. I'll ask again that you stop. Just because you make a living in part off of a CPython module, doesn't mean we cannot discuss python-related things on this list, or discuss things from the perspective of a python user, or suggest alternative solutions when someone asks for a feature that Python does not have. -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie question
Luis M. Gonzalez wrote: Amyway, I wouldn't want to use this list to talk about Boo, because I think that the best place to do it is comp.lang.boo. However, since I think it is definetely python related (I know you disagree, but others don't) I see no harm in mentioning it here occasionally. Luis, that is *exactly* Peter's position: Peter Hansen wrote: ... If Doug wants to come in from time to time and mention Boo, however, he's welcome to do so. ... ... so there is no need for you to say you see no harm in it, making it sound as though Peter *does* see harm in it. Steve -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie question
Stephen Waterbury wrote: Luis M. Gonzalez wrote: Amyway, I wouldn't want to use this list to talk about Boo, because I think that the best place to do it is comp.lang.boo. However, since I think it is definetely python related (I know you disagree, but others don't) I see no harm in mentioning it here occasionally. Luis, that is *exactly* Peter's position: Peter Hansen wrote: ... If Doug wants to come in from time to time and mention Boo, however, he's welcome to do so. ... ... so there is no need for you to say you see no harm in it, making it sound as though Peter *does* see harm in it. You can defend Peter all you want, but you can't take back the other things he has said which you did not cite. Quote: "I think doing this by defending Doug's postings, however, might weaken the strength of your position just a little. (Okay, I mean "a lot".) " A flame. Quote: "About the only time the word "boo" _does_ come up, it comes up in one of Doug's posts, often in an apparent attempt to "help" a Python newbie by pointing him in a misleading manner" A misrepresentation of my intentions. If someone asks if python has interfaces, and I say first, pyprotocols has something similar, but boo does have support for real interfaces, then that is "help" and that is not misleading in the slightest. Quote: "As a result of all the activity in the "Boo who?" thread, however, " He failed to mention that he is the one who started and propagated this very thread, which devolved into nothing more than a flame-fest, which was his intention all along. Quote: "I went and searched a bit to find out who this Doug character is. " Another flame, and we are still in the same note by Peter Hansen, folks. Quote: "It turns out that he's been mentioning Boo in postings *to newbies* repeatedly over the last few months." *to newbies* - oh my god, dare I mention the word boo to a newbie. Another mischaracterization of what I did. Quote: "These are people trying to use Python, having a question or difficulty about it, and he launches into a sales job about some other language. " I am not selling anything. This is a subtle flame related to calling me an "evangelist". Does Peter Hansen make money using python? Does he have something to sell at engcorp that uses CPython? Quote: "Would you defend someone who came into this group and responded (admittedly helpfully, sometimes, in other ways) to newbie questions by constantly saying "you can do this much more easily in Perl of course, see www.perl.codehaus.org"? " Another complete mischaracterization of what I did. When someone asks for something that they cannot do in python, then I noted alternative solutions, such as jython or boo or whatever tool is best for the job. Quote: "Then downright offensive." Another flame. Quote: "What Doug has been doing is like standing at the door of a mission run by a church a..." Yet again, another flame. Quote: "he turns on them and accuses them of religious persecution, and being unfriendly to boot. " Another mischaracterization. In fact, a complete lie. I'm only halfway through his message. It would take me all day to point out all his flames. -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie question
[Doug] > I'm only halfway through his message. It would take me all day to point > out all [Peter Hansen's] flames. Doug, this is not worth your time. It certainly isn't worth mine, nor that of the other thousands of people who are being subjected to this argument. Please, consider putting your energies into something more positive, either here or elsewhere. Peter, Fredrik: Please consider giving up the argument. Hopefully Doug will either lighten up and return to contributing usefully, or give up and go away. (For what it's worth, I'd rather it was the former.) the-last-haven-of-civilisation-on-the-net-is-under-threat-ly yrs, -- Richie Hindle [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie Question
On Tue, 01 Feb 2005 17:47:39 -0800, Joel Eusebio wrote: > Whenever I access test.py from my browser it says "The page cannot be > found" , I have the file on /var/www/html, what did I miss? > > Thanks in advance, > Joel In general, you will need to post the relevant entries from your Apache error log and access log. A lot of things can go wrong between your Python script and final output. However, if you're getting a 404, it means that you haven't associated the URL to the file correctly. Again, a lot of things can prevent this, so you're also going to need to post the relevant Apache configuration files. Without that, I can't be any more specific. I'm also concerned that you are conflating mod_python with Python CGI, which work completely differently when it comes to associating code to URLs. In general, you won't access a mod_python script by typing in a URL to a file; that will either try to run it as a CGI or just display it (depending on the configuration). But we'll work on this when you post the necessary information and we can see what you are trying to do. -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie Question
On Tue, 01 Feb 2005 17:47:39 -0800, Joel Eusebio wrote: > > Hi Everybody, > > I'm pretty new to Python and would like to ask a few questions. I have this > setup on a Fedora Core 3 box. > > Python 2.3.4 > wxPython-common-gtk-ansi-2.5.3.1-fc2_py2.3 > mod_python-3.1.3-5 > Apache/2.0.52 > > I have a test.py which looks like this: > from mod_python import apache > def handler(req): >req.write("Hello World!") >return apache.OK > This code looks like you are attempting to define a handler. In this case the handler needs to be properly set up in either your httpd.conf or a .htaccess (assuming your configuration allows for that). > Whenever I access test.py from my browser it says "The page cannot be found" > , I have the file on /var/www/html, what did I miss? You don't access handlers like you do CGI. This problem likely lies in your configuration and not in your code. I would look at mod_python's documentation some more and probably start with mod_python's PublisherHandler for initial testing and experimentation. -Robey Holderith > Thanks in advance, > Joel -- http://mail.python.org/mailman/listinfo/python-list
RE: Newbie Question
Hi Jeremy & Robey Acces_log: 172.16.38.6 - - [01/Feb/2005:17:36:14 -0800] "GET /test.py HTTP/1.1" 404 276 "-" "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.1.4322)" 172.16.38.6 - - [01/Feb/2005:17:41:44 -0800] "GET /test/mptest.py/formLogin HTTP/1.1" 404 293 "-" "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.1.4322)" Error_log: [Wed Feb 02 08:55:18 2005] [notice] mod_python: (Re)importing module 'mod_python.publisher' [Wed Feb 02 08:55:18 2005] [notice] mod_python: (Re)importing module 'test' with path set to '['/var/www/html']' Httpd.conf: LoadModule python_module modules/mod_python.so # Order allow,deny Allow from all AddHandler mod_python .py Options Indexes Includes FollowSymlinks Multiviews PythonHandler mod_python.publisher PythonDebug On AddHandler mod_python .py AllowOverride None PythonHandler mod_python.publisher PythonDebug On Thanks again, Joel -Original Message- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf Of Jeremy Bowers Sent: Tuesday, February 01, 2005 5:47 PM To: python-list@python.org Subject: Re: Newbie Question On Tue, 01 Feb 2005 17:47:39 -0800, Joel Eusebio wrote: > Whenever I access test.py from my browser it says "The page cannot be > found" , I have the file on /var/www/html, what did I miss? > > Thanks in advance, > Joel In general, you will need to post the relevant entries from your Apache error log and access log. A lot of things can go wrong between your Python script and final output. However, if you're getting a 404, it means that you haven't associated the URL to the file correctly. Again, a lot of things can prevent this, so you're also going to need to post the relevant Apache configuration files. Without that, I can't be any more specific. I'm also concerned that you are conflating mod_python with Python CGI, which work completely differently when it comes to associating code to URLs. In general, you won't access a mod_python script by typing in a URL to a file; that will either try to run it as a CGI or just display it (depending on the configuration). But we'll work on this when you post the necessary information and we can see what you are trying to do. -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie question
[EMAIL PROTECTED] wrote: What is the python equivalent of the following statement? while (n--) Thank you. That depends on a number of things, including whether "n" is declared as "volatile", and whether you consider the above as an executable piece of code (it is not), or just a code snippet... Roughly but somewhat facetiously speaking, the answer is this: n = -1 (Maybe describing what you are trying to accomplish would be more useful than showing snippets of code without explaining what you are expecting it to do.) -Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie question
Thanks for the reply. I am trying to convert some C code to python and i was not sure what the equivalent python code would be. I want to postdecrement the value in the while loop. Since i cannot use assignment in while statements is there any other way to do it in python? Thanks. -d4 -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie question
[EMAIL PROTECTED] wrote: Thanks for the reply. I am trying to convert some C code to python and i was not sure what the equivalent python code would be. I want to postdecrement the value in the while loop. Since i cannot use assignment in while statements is there any other way to do it in python? Generally in Python you simply put the assignment-based statement in a "while True:" block, and use "break" to exit as required. For example, here is one way to approach it in this case: while True: n = n - 1 if n == -1: break Having written the above, however, I'm uncertain whether this sort of thing is really required in Python. Although I have ported very little C code to Python (so I might be wrong), I definitely have never seen anything resembling the above pattern in Python code that I or others have written. My suspicion is that the code involves operations which are actually better handled in Python by some kind of builtin or standard library operation. For example, often the post-decrementing is part of a pointer operation involving manipulating a string character-by-character. This is effectively never required in Python, and will pretty much always result in a program written at a much lower level than what you should be shooting for in Python. But if you want a direct port, then the above should do... -Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie question
<[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > Hello All, > What is the python equivalent of the following statement? > > while (n--) Like other posters said, you should give more details with your question. What do you mean by equivalent? The following is *functionally* equivalent: for n in range(start, 0, -1): Of course, there is always: while n: ... n -= 1 But unfortunately, no, I don't think there is an equivalent in python that has the conciseness of the C statement. The pre- and post-increment and -decrement in C/C++/Java are very powerful and I miss them in python. -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie question
[EMAIL PROTECTED] wrote: Thanks for the reply. I am trying to convert some C code to python and i was not sure what the equivalent python code would be. I want to postdecrement the value in the while loop. Since i cannot use assignment in while statements is there any other way to do it in python? Roughly speaking, if you have a loop in C like while (n--) { func(n); } then the mechanical translation to Python would look like this: while True: n -= 1 if not n: break func(n) However, odds are fairly decent that a mechanical translation is not the best approach, and you may (as just one of many examples) be much better off with something more like: for i in range(n)[::-1]: func(n) The '[::-1]' iterates over the range in a reverse (decreasing) direction; this may or may not be necessary depending on the circumstances. Jeff Shannon Technician/Programmer Credit International -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie question
In article <[EMAIL PROTECTED]>, Dan Perl <[EMAIL PROTECTED]> wrote: . . . >has the conciseness of the C statement. The pre- and post-increment >and -decrement in C/C++/Java are very powerful and I miss them in python. > > Me, too. Which is, I suspect, evidence for the incompleteness of our Pythonhood. As Peter Hansen already hinted in this thread, an appetite for the increment and related operators probably is a symptom that there's an opportunity nearby to use an iterator or string method or such. C++ and Java wish they had it so good. -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie question
"Cameron Laird" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > In article <[EMAIL PROTECTED]>, > Dan Perl <[EMAIL PROTECTED]> wrote: > . > . > . >>has the conciseness of the C statement. The pre- and post-increment >>and -decrement in C/C++/Java are very powerful and I miss them in python. > > Me, too. > > Which is, I suspect, evidence for the incompleteness of our Pythonhood. > As Peter Hansen already hinted in this thread, an appetite for the > increment and related operators probably is a symptom that there's an > opportunity nearby to use an iterator or string method or such. C++ > and Java wish they had it so good. I can't say that is not part of the reason, but the example in the OP is a clear illustration of cases where something like an increment/decrement operator would be very useful. OTOH, I was thinking of saying in my previous posting that I prefer for n in range(start, 0, -1): to n = start while (n--) I think that the first form is more readable, although that may be just me. I would actually even prefer the 'for' statement in C to the 'while' statement: for (n=start; n<=0; n--) -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie question
Dan Perl wrote: I can't say that is not part of the reason, but the example in the OP is a clear illustration of cases where something like an increment/decrement operator would be very useful. The OP didn't show how he was using the "while (n--)" at all, so it can hardly be a clear illustration of how it's useful. In fact, it's even possible it was entirely unnecessary in the original code... at this point I'd be really interested in seeing just what code is inside the "while" statement, and possibly what follows it (if the following code relies on the value of "n"). OTOH, I was thinking of saying in my previous posting that I prefer for n in range(start, 0, -1): to n = start while (n--) I think that the first form is more readable, although that may be just me. I would actually even prefer the 'for' statement in C to the 'while' statement: for (n=start; n<=0; n--) I'm not sure if it's just picking nits, but I'd like to point out that neither of your alternatives is actually equivalent to the while (n--) form... nor was Jeff Shannon's attempt (in that case it leaves the loop with n equal to 0, not -1). The fact that it's so easy to get confused with post-decrement is perhaps an excellent reason to keep it out of Python. -Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie question
"Peter Hansen" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > Dan Perl wrote: >> OTOH, I was thinking of saying in my previous posting that I prefer >> for n in range(start, 0, -1): >> to >> n = start >> while (n--) >> I think that the first form is more readable, although that may be just >> me. I would actually even prefer the 'for' statement in C to the 'while' >> statement: >> for (n=start; n<=0; n--) > > I'm not sure if it's just picking nits, but I'd like to > point out that neither of your alternatives is actually > equivalent to the while (n--) form... nor was Jeff > Shannon's attempt (in that case it leaves the loop with > n equal to 0, not -1). You're right in your nit picking. I have to go back to using some C/C++ and Java also, I don't want to forget them completely. -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie question
Dennis Lee Bieber wrote: On Wed, 09 Feb 2005 18:10:40 -0800, Jeff Shannon <[EMAIL PROTECTED]> declaimed the following in comp.lang.python: for i in range(n)[::-1]: func(n) Shouldn't that be func(i) (the loop index?) You're right, that's what I *meant* to say. (What, the interpreter doesn't have a "do what I mean" mode yet? ;) ) The '[::-1]' iterates over the range in a reverse (decreasing) direction; this may or may not be necessary depending on the circumstances. Eeee sneaky... (I'm a bit behind on latest syntax additions) I'd probably have coded something like for n1 in range(n): func(n-n1) though, and note that I do admit it here [...] Given a need/desire to avoid extended slicing (i.e. being stuck with an older Python, as I often am), I'd actually do this by changing the input to range(), i.e. for i in range(n, 0, -1): # ... That (IMO) makes the decreasing-integer sequence a bit clearer than doing subtraction in the function parameter list does. Actually, it's possibly clearer than the extended slicing, too, so maybe this would be the better way all around... ;) I haven't done the detailed analysis to properly set the end point... And as Peter Hansen points out, none of the Python versions leave n in the same state that the C loop does, so that's one more way in which an exact translation is not really possible -- and (IMO again) further evidence that trying to do an exact translation would be ill-conceived. Much better to consider the context in which the loop is used and do a looser, idiomatic translation. Jeff Shannon Technician/Programmer Credit International -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie question
Dennis Lee Bieber wrote: On Thu, 10 Feb 2005 09:36:42 -0800, Jeff Shannon <[EMAIL PROTECTED]> declaimed the following in comp.lang.python: And as Peter Hansen points out, none of the Python versions leave n in the same state that the C loop does, so that's one more way in which an exact translation is not really possible -- and (IMO again) further evidence that trying to do an exact translation would be ill-conceived. Much better to consider the context in which the loop is used and do a looser, idiomatic translation. Yeah, though my background tends to be one which considers loop indices to be loop-local, value indeterminate after exit... Well, even though I've programmed mostly in langauges where loop indices to retain a determinate value after exit, I almost always *treat* them as loop-local -- it just seems safer that way. But not everyone does so, and especially with C while loops, often the point is to keep adjusting the control variable until it fits the requirements of the next section... Jeff Shannon Technician/Programmer Credit International -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie question
Dan Perl wrote: > <[EMAIL PROTECTED]> wrote in message > news:[EMAIL PROTECTED] > > Hello All, > > What is the python equivalent of the following statement? > > > > while (n--) > > Like other posters said, you should give more details with your question. > What do you mean by equivalent? The following is *functionally* equivalent: > for n in range(start, 0, -1): > > Of course, there is always: > while n: > ... > n -= 1 errrmmm it's a C while stmt with post-decrement; that's NOT the same as: for (; n; n--) ... If n is initially 3, the loop body is executed with n set to 2,1,0 and after exit n is -1. The nearest Python equivalents of "while (n--) func(n);" are (making the charitable assumption that initially n >= 0): ! while n: ! n -= 1 ! func(n) and ! for n in range(n-1, -1, -1): ! func(n) > > But unfortunately, no, I don't think there is an equivalent in python that > has the conciseness of the C statement. The pre- and post-increment > and -decrement in C/C++/Java are very powerful and I miss them in python. Unfortunately?? What are you missing? The ability to write cryptic crap that you don't understand & that's so "powerful" that you can get into deep kaka really quickly? Hope you weren't writing software for embedded devices -- like heart pacemakers :-) -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie question
Functions for manipulating images are contained in the 'PIL' extension - the Python Imaging Library. You'll find it with google. regards, Fuzzy http://www.voidsapce.org.uk/python/index.shtml -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie question
For future reference, an informative subject line like > How do I display an image in Python? is more likely to grab the attention of someone with the information sought. tjr -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie question
On Mon, 28 Feb 2005 16:17:03 +0200, "Ryan White" <[EMAIL PROTECTED]> wrote: > How do I display an image in Python? - I've run over Tkinter, but obviously > in all the wrong places. Someone else suggested PIL. But in Tkinter you create a PhotoImage object then insert it into either a Canvas or a Text widget. > Any help or sample code would be much appreciated. If you find the file hmgui.zip on Useless Python you will find the code for my games framework with an example Hangman game in Tkinter. It includes the display of a set of images(the hanged man) HTH, Alan G. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie question
On 28 Mar 2005 15:00:37 -0800, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote: > Hello, > > How do i create two memory mapped buffers(mmap) and pass an index to > select which one needs to be populated? > > Is it possible to define the size of the buffer? > > -SB > > -- > http://mail.python.org/mailman/listinfo/python-list > http://docs.python.org/lib/module-mmap.html I haven't tried it, but it should be pretty straightforward to create two mmaped buffers. Step 1: Import the mmap module. Step 2: Create or find the file you want to map. Open it, and get the fileno. Call mmap.mmap, passing the fileno and buffer size. Repeat Step 2 with a different file to create a second mmaped buffer. I'm not sure what you mean by "and pass an index to select which one needs to be populated". If you pack the buffers into a tuple/list/other sequence object, it should be easy to access them by index: >>> buffers = (buffer_1, buffer_2) >>> do_something_to(buffers[0]) >>> do_something_else_with(buffers[1]) To mmap buffers, you MUST define the size. I'm sorry I can't be more helpful; perhaps if you gave a higher-level description of what you are trying to accomplish, I could give better pointers in the right direction. -- Sean Blakey Saint of Mild Amusement, Evil Genius, Big Geek Python/Java/C++/C(Unix/Windows/Palm/Web) developer quine = ['print "quine =",quine,"; exec(quine[0])"'] ; exec(quine[0]) -- http://mail.python.org/mailman/listinfo/python-list
Numarray newbie question
I know there are probably alternatives for this with the standard library, but I think that would kill the speed I get with numarray: Say I have two 2-dimensional numarrays (x_mat and y_mat, say), and a function f(x,y) that I would like to evaluate at every index. Basically I want to be able to say f(x_mat,y_mat) and have it return a numarray with the same shape and element wise evaluation of f. I know, I want a ufunc, but they look scary to write my own. Are there any functions that do this? Or is writing ufuncs easier than it seems? Thanks, -Chris Neff -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie question
Whats the file that has to be mapped? Can this be a list? Can this list be initialized to 512? Thanks, -SB -- http://mail.python.org/mailman/listinfo/python-list
Super Newbie Question
I have recently started to use Python to develop a new version of my website. I'm working on a sort of "web engine" that takes the contents of a standardized file format I have designed and then outputs it using templates created by me. However, I'm only at the very beginning (i.e. opening and reading files) because I'm a newbie to Python. I want to spend a lot of time learning Python. I have searched with about 15 million different key phrases on Google and Google Groups but haven't come up with an answer to my following question: I want the "engine" to read the file, write its contents to another temporary file (for now it just writes the contents; later it will format it before writing the contents) and then deletes the *contents* of the temporary file after printing out the result, but not the temporary file itself. I want it to do this because that temporary file will be reused to write to for other pages as well. In short, how might I go about deleting just the contents of a file? I tried several methods with my limited knowledge but had no luck. Thank you very much for answering a lowly newbie's question. I really appreciate it. P.S. If there's a better that you think to perform what I am saying, I'd like to be enlightened. But I'd also like my question answered too, in case I ever need to do something similar again. -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie question
What is usually meant when Python is mentioned in the context of game scripting is that it's relatively easy for a game's developers to embed a Python interpreter into the game. Python would then be used to control higher-level gameplay elements like artificial intelligence while the game's native language (probably C) handles the heavy lifting (e.g. rendering, collision detection, etc). This does /not/ mean that you will be able to use Python to modify your favorite game, unless it happens to already have an interpreter built-in. Maybe some resident gamers here can list some games that use Python for user-accessible scripting; I don't know of any. -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie question
Just a few days earlier someone posted me the link to panda3d (www.panda3d.org) This is actually a gamengine/renderingengine on which u can develop games in python. If u want to achieve high performance you'd rather use c++ and directly access libs like nvidias cg, ms directx or opengl... for a "hello world", understanding how the 3d enviroment works and so on panda3d is a really good start. cheers tc -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie question
You might want to look at PyGame. http://pygame.org/ Newbies can go far using PyGame but the maths can be a bit complex no matter what language or package you use. For an alternative try Blender 3d. http://blender.org Blender is a 3d suite that can do it all and then some , it's free ,and it uses Python for it's scripting. You can create a game and never touch a piece of code if you use the builtin actuators and sensors, or you can script with Python. hth, M.E.Farmer -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie question
In article <[EMAIL PROTECTED]>, Tiziano Bettio <[EMAIL PROTECTED]> wrote: . . . >If u want to achieve high performance you'd rather use c++ and directly >access libs like nvidias cg, ms directx or opengl... . . . Yes. Well, maybe. Python-coded programs, even graphically-intense games, *can* exhibit good performance, and there are numerous anecdotes about applications LOSING speed on conversion to C++ from Python. Moreover, there's no inherent conflict between C++ and Python; some successful applications use both. My summary: it's a subtler matter than, "for performance, abandon Python on favor of C++". I think you know that, but I want to make it explicit for less-experienced readers. -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie question
Cameron Laird wrote: In article <[EMAIL PROTECTED]>, Tiziano Bettio <[EMAIL PROTECTED]> wrote: . . . If u want to achieve high performance you'd rather use c++ and directly access libs like nvidias cg, ms directx or opengl... . . . Yes. Well, maybe. Python-coded programs, even graphically-intense games, *can* exhibit good performance, and there are numerous anecdotes about applications LOSING speed on conversion to C++ from Python. Moreover, there's no inherent conflict between C++ and Python; some successful applications use both. My summary: it's a subtler matter than, "for performance, abandon Python on favor of C++". I think you know that, but I want to make it explicit for less-experienced readers. yeah well, i didn't intended to say it in this specific way. tough to be more exact: for a game you can realize up to 95% in python without losing the needed performance. but there's almost always a little part where u really need to get even the last bit of performance out of the hardware or where nobody has already ported the lib you need into python, where c++ comes in rather handy. I didn't ment to offend any pythonian (wouldn't want to offend myself...), but i think we all agree that sometimes all of us have seen or even programmed something in c++ (or other languages) what could come in really handy for a project one is working on. so again, didn't ment to say that it's a performance matter (there are thousands of bad c++ programmers out there which are hiding behind compiled code...) :) cheers tc -- http://mail.python.org/mailman/listinfo/python-list
WSDL.Proxy newbie question
Hello, I am new to implementing and consuming web services with Python. I have had some success setting up a simple SOAPServer and connecting to it and also using some of the simpler (one parameter) web services available from xmethods.org. I am currently stuck trying to use a simple hashing service that requires more than one parameter to be passed. I have done a lot of searching and tried passing the parameters in many ways. I think I am stuck on what type of data structure to pass the service. here's the xmethod service profile http://www.xmethods.net/ve2/ViewListing.po;jsessionid=zbLKBgtAiSjIS-KAclxRipnP(QHyMHiRM)?key=uuid:FD460436-81BF-86BD-F252-2AB6C00B624C Below is an example attempt. Thanks in advance for any suggestions. Python 2.3.3 (#1, May 7 2004, 10:31:40) [GCC 3.3.3 20040412 (Red Hat Linux 3.3.3-7)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import SOAPpy >>> wsdlFile = 'http://www.bs-byg.dk/hashclass.wsdl' >>> server.soapproxy.config.dumpSOAPOut =1 >>> server.soapproxy.config.dumpSOAPIn =1 >>> server.debug = 1 >>> server.HashString({'Str':'test','HashType':'MD5'}) *** Outgoing SOAP ** http://schemas.xmlsoap.org/soap/encoding/"; xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"; xmlns:xsi="http://www.w3.org/1999/XMLSchema-instance"; xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"; xmlns:xsd="http://www.w3.org/1999/XMLSchema"; > MD5 test *** Incoming SOAP ** http://schemas.xmlsoap.org/soap/envelope/"; xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"; xmlns:xsd="http://www.w3.org/2001/XMLSchema";>http://tempuri.org/HashService/HashClass"; /> : {} -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie question
Geirr wrote: > Hi, ive just started playing around with python and wondered if someone > could poing me in the right way here. > > > I have a xmlrpc server simple script: > > Server script: > import SimpleXMLRPCServer > class tpo: > > def retTPOXML(): > theFile=open('tpo.xml') > try: > self.strXML = theFile.read() > return self.strXML > finally: > theFile.close() > > tpo_object = tpo() > server = SimpleXMLRPCServer.SimpleXMLRPCServer(("localhost",)) > server.register_instance(tpo_object) > > print "Listening on port " > server.serve_forever() > > and im trying to print the return value with any luck > > Client Code: > import xmlrpclib > server = xmlrpclib.ServerProxy("http://localhost:";) > current = server.retTPOXML > print current > > > Any comment would be appriciated First: in python, class definitions require that you explicitly refer to the instance, such as self.myMethod(). In *self.strXML* the word *self* is a variable, it should be part of the method parameter list such as *def retTPOXML(self):*. The first parameter of methods (functions in classes) refers to the instance that is created. (BTW, it could be anything else than *self*, which is pure convention) Second: In the client, your not using the method you're refering to it (methods are yet another sort of objects), yu need the parenthesis such as *current = server.retTPOXML()* Notice that on calling the method the object is on the left side of the dot, and that is the object instance that will be adequated to the *self* in the class definition. but you should also read the tutorial. (others may propose things otherwise (better versed in the theory at work behind the scene... ;-)) -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie question
I obviously didnt read it good enough :) Tnxs anyway for extremly fast response -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie Question
solaris_1234 wrote: > I am trying to learn Python and I have a few questions. > > I have created a Class that is essentially a canvas with a red > background. After creation I want to change the background to green. > However I am having problems doing this. > > Here is my code: > > from Tkinter import * > > class MyApp: >def __init__(self, parent): > self.myParent = parent > self.myContainer = Frame(parent) > self.myContainer.pack() > > self.b1 = Canvas(self.myContainer, background="red").grid(row=0, > column=0) > > def ChangebgColor(self): >self(bg="green") > > > root = Tk() > myapp=MyApp(root) #Everything is fine at this point. > > raw_input() > > ChangebgColor(myapp.b1) # Error Message at this point > > raw_input() > > > > Any help will be greatly appreciated. here ya go. from Tkinter import * class MyApp: def __init__(self, parent): self.myParent = parent self.myContainer = Frame(parent) self.myContainer.pack() self.b1 = Canvas(self.myContainer, background="red") self.b1.grid(row=0,column=0) def ChangebgColor(self): self.b1.config(bg="green") root = Tk() myapp=MyApp(root) raw_input() myapp.ChangebgColor() raw_input() -- http://mail.python.org/mailman/listinfo/python-list
Another newbie question
I am a python newbie and have been trying to learn python. To this end, I have coded the following program creates: a 8 by 8 checker board Places two checkers on the board Checks the board and prints out which squares has a checker on them. It works. But I have a one question: 1) The stmt "board.Blist[10].DrawQueen(board.Blist[10].b1)" seems awkward. Is there another way (cleaner, more intuitive) to get the same thing done? I appreciate any and all input on how the following program could be improved. from Tkinter import * import time totalSolutionCount = 0 class MyBox: def __init__(self, myC, myrow, mycolumn, color): self.b1 = Canvas(myC, background=color, width=50, height=50) self.b1.grid(row=myrow, column=mycolumn) self.occupied = 0 def ChangebgColor(self, box): box.config(bg="black") def DrawQueen(self, box): box.item = box.create_oval(4,4,50,50,fill="black") self.occupied = 1 box.update() def unDrawQueen(self, box): box.delete(box.item) self.occupied = 0 box.update() class MyBoard(MyBox) : def __init__(self, myC): self.Blist = [] count=0 for i in range(8): count += 1 for j in range(8): count += 1 if (count%2): self.Blist.append(MyBox(myContainer,i,j, "red")) else: self.Blist.append(MyBox(myContainer,i,j, "green")) root=Tk() myContainer = Frame(root) myContainer.pack() board=MyBoard(myContainer) board.Blist[10].DrawQueen(board.Blist[10].b1) board.Blist[22].DrawQueen(board.Blist[22].b1) raw_input() # A Hack debug statement for i in range(64): if board.Blist[i].occupied == 1: print i, "is occupied" raw_input() # A Hack debug statement print "\n"*3 -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie question
How about this: python your_program.py examle.txt Bermi wrote: > > how i can link it to read my file examle.txt? -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie question
Dody Suria thank u. -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie question
"Bermi" <[EMAIL PROTECTED]> wrote: >i have this program >=== >from sys import * >import math >import math, Numeric >from code import * >from string import * >from math import * >from dataSet import * >from string import * I know you said you are a newbie. That means there is still time for you to learn to do things the proper way. Change all of that to: import sys import math import Numeric import dataSet You don't need to import string at all, and you will probably never use "code". >def drawAsciiFile(): >_fileName=str(argv[1]) argv is already an array of strings. The "str" is useless. >__localdataSet=DataSet(_fileName) > >#_PlotCols=string.split(str(argv[2]),' ') >#_PlotColsInt=[] >'''for s in _PlotCols: >_PlotColsInt.append(int(s)) >CountourPlots(__localdataSet,_PlotColsInt) >''' >print >__data=__localdataSet.GetData() >print max(__data[:,11]) >if __name__ == "__main__": >drawAsciiFile() > > >how i can link it to read my file examle.txt? Instead of referring to argv inside your function, you should pass the file name as a parameter. That way, at a later time, you can pass it file names from sources other than argv. Also, there is no point in using leading underscores for local variables. That's only interesting for members of the class. You are splitting argv[2]. Ordinarily, sys.argv has already been split. That is, "xxx.py file 1 3 5 7" will produce 6 elements in sys.argv. If you really want the columns as a single parameter, you'll have to use quoting: xxx.py file "1 3 5 7" Something like this, maybe: def drawAsciiFile(filename, columns): localdataSet = DataSet.DataSet( filename ) PlotCols = [int(s) for s in columns.split()] ContourPlots( localdataSet, PlotCols ) if __name__ == "__main__": if len(sys.argv) < 2: print 'Usage: .py filename "3 5 7"' ) drawAsciiFile( sys.argv[1], sys.argv[2] ) -- - Tim Roberts, [EMAIL PROTECTED] Providenza & Boekelheide, Inc. -- http://mail.python.org/mailman/listinfo/python-list
Small newbie question
How would I do this: Write a program that simply outputs a ramdom (in this case) name of (for this example) a Linux distibution. Heres the code ive tryed: from random import uniform from time import sleep x = 2 while x < 5: x = uniform(1, 5) if x >= 1 <= 1.999: print 'SuSE' elif x >= 2 <= 2.999: print 'Ubuntu' elif x >= 3 <= 3.999: print 'Mandriva' elif x >= 4 <= 4.999: print 'Fedora' sleep(2) It dosnt work: only keep printing SuSE. Please help, Thanks in advance, -- /usr/bin/byte -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie Question
look into the csv module. (for comma-separated-value text files.) Tom Strickland wrote: >I have a file that contains many lines, each of which consists of a string >of comma-separated variables, mostly floats but some strings. Each line >looks like an obvious tuple to me. How do I save each line of this file as a >tuple rather than a string? Or, is that the right way to go? > >Thank you. > >Tom Strickland > > -- http://mail.python.org/mailman/listinfo/python-list
RE: Newbie Question
Tom, Well, as one newbie to another, I tried this; >>> x = '22,44,66,88,"asd,asd","23,43,55"' >>> y = eval(x) >>> y (22, 44, 66, 88, 'asd,asd', '23,43,55') given that x some how comes from a single line in your file. BTW, do you get the tutor list as well? My guess is that the 'experts' over here might prefer that the newbies go over there for stuff like this. And now, a question for the experts. Does anyone have a pointer as to why my code might be dangerous? I get the feeling that eval might not be a 'good' ( safe ) thing to use. Michael -Original Message- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] n.org]On Behalf Of Tom Strickland Sent: Friday, August 19, 2005 10:05 AM To: python-list@python.org Subject: Newbie Question I have a file that contains many lines, each of which consists of a string of comma-separated variables, mostly floats but some strings. Each line looks like an obvious tuple to me. How do I save each line of this file as a tuple rather than a string? Or, is that the right way to go? Thank you. Tom Strickland -- http://mail.python.org/mailman/listinfo/python-list ___ The information contained in this message and any attachment may be proprietary, confidential, and privileged or subject to the work product doctrine and thus protected from disclosure. If the reader of this message is not the intended recipient, or an employee or agent responsible for delivering this message to the intended recipient, you are hereby notified that any dissemination, distribution or copying of this communication is strictly prohibited. If you have received this communication in error, please notify me immediately by replying to this message and deleting it and all copies and backups thereof. Thank you. -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie Question
[EMAIL PROTECTED] wrote: > >>> x = '22,44,66,88,"asd,asd","23,43,55"' > >>> y = eval(x) > >>> y > (22, 44, 66, 88, 'asd,asd', '23,43,55') > > And now, a question for the experts. I'm no expert, just experienced. > Does anyone have a pointer as to why my code might be > dangerous? Well, the smallest problem you have here is that you will get an SyntaxError exception on badly formated input. x = 'z,22,44,66,88,"asd,asd","23,43,55"' eval(x) NameError: name 'z' is not defined In worse case, somebody will send you a carefuly formated input that you will run blindy (just like in case of buffer overflows). CSV is easy with the module.. import csv cr = csv.reader((x,)) print cr.next() ['z', '22', '44', '66', '88', 'asd,asd', '23,43,55'] Usually, you will use the csv module, like this: import csv, sys for line in csv.reader(sys.stdin): # print line[3] BranoZ -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie Question
Tom Strickland <[EMAIL PROTECTED]> wrote: >I have a file that contains many lines, each of which consists of a string >of comma-separated variables, mostly floats but some strings. Each line >looks like an obvious tuple to me. How do I save each line of this file as a >tuple rather than a string? Or, is that the right way to go? Depending on exactly what format you've got, either .split(',') on the line, or if this is insufficient look at the csv module. You'll then need some way of turning the list of strings both of these will give you into the mixed float/string tuple you want, which could be somewhat tedious. Without knowing what these lines look like, or what they represent, I can't begin to guess how you might go about it. Actually, I can -- I'd start by considering whether a dict might be more appropriate than a tuple and use csv.DictReader. -- \S -- [EMAIL PROTECTED] -- http://www.chaos.org.uk/~sion/ ___ | "Frankly I have no feelings towards penguins one way or the other" \X/ |-- Arthur C. Clarke her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie Question
Yes, "eval" of data from a file is rather risky. Suppose someone gave you a file containing somewhere in the middle: ... 22,44,66,88,"asd,asd","23,43,55" os.system('rm -rf *') 33,47,66,88,"bsd,bsd","23,99,88" ... This would delete all the files in your directory! The csv module mentioned above is the tool of choice for this task, especially if there are strings that could contain quotes or commas. Doing this right is not at all easy. If you really want to roll your own, and the data is KNOWN to be fixed and very restricted, you can do something like: "myfile" contains: 13,2,'the rain',2.33 14,2,'in spain',2.34 for l in open('myfile'): x,y,comment,height = l.split(',') x=int(x) y=int(y) height=int(height) comment=comment.strip("' ") # strip spaces and quotes from front and back but beware this will break if the comment contains commas. -- George -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie Question
Tom Strickland wrote: > I have a file that contains many lines, each of which consists of a string > of comma-separated variables, mostly floats but some strings. Each line > looks like an obvious tuple to me. How do I save each line of this file as a > tuple rather than a string? Or, is that the right way to go? > > Thank you. > > Tom Strickland > > You will probably be able to read the file using the csv module. But what do you want to do with the data? Transcribe it into some other format just for a learning exercise? What do you mean by "save as tuple"? A few more clues might save you from being (a) ignored and/or (b) deluged with irrelevant responses from well-intentioned wanting-to-help people who have guessed wrongly what you are rabbiting on about ... -- http://mail.python.org/mailman/listinfo/python-list
fileinput.input - newbie question
I'm testing some writing/reading with a file and i'm not sure if it is possible to print/use the line with fileinput.input inplace=1 (see below) import fileinput thefile = fileinput.input('bla.txt',inplace=1,backup='.bak') for line in thefile: if line != "1\n": print line, #is it possible to 'use' / print the 'line' on the screen here? thefile.close() When its not possible then I use 2 file's filein.txt,fileout.txt Thanks, GC-Martijn -- http://mail.python.org/mailman/listinfo/python-list
Pyrex newbie question
Just starting to use pyrex on windows. Using pyrex version 0.9.3.1.win32 Using Activestate Python 2.4.3.12 Using Mingw compiler When I try to run the pyrex demo it fails with a message: "undefined reference to '_imp__Py_NoneStruct' " Anyone know why? -- http://mail.python.org/mailman/listinfo/python-list
python newbie question
I am new to python, can you please tell me how can I convert my python script into an executable on linux? i.e. instead of typing 'python myscript.py abc', I just need to do 'myscript.py abc'? and how can I get the input argument from my script , in my example, how can I read 'abc'? Thank you. -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie question
orangeDinosaur wrote: > Hi, > > I'm brand new to using/playing with Python, and I have what is likely a > very simple question but can't seem to figure it out. > > I wrote up a script in my preferred text editor. It contains maybe ten > lines of code. I want to be able to execute those code lines with a > single command either from the inline mode or from IDLE. How do I do > this? I saved the file (myscript.py) in a folder that I've specified > in my PYTHONPATH environment variable, and when I type > import myscript > > the script runs. If, later during the same session, I type > myscript > > all I get for output is > > documents\Python Modules\myscript.pyc'> > > Somwhere in the beginning tutorial there's this line: > > "The script can be given a executable mode, or permission, using the > chmod command: > > $ chmod +x myscript.py" This is a Unix-specific command (POSIX-specific, actually). It won't work on a Windows box. To run the script from a command line, `python C:\path\to\script\myscript.py' should do the trick, I can't say for sure, though because I'm a heathen Linux user. HTH -- Steve Juranich Tucson, AZ USA -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie question
Yep, that should work. Just keep in mind that if python.exe is not in your path, you will need to either specify the entire path to it (i.e. 'C:\python24\python C:\path\to\script\myscript.py'), or cd into its directory first (i.e. if you want to just run 'python C:\path\to\script\myscript.py'). Doug -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie question
> I'm brand new to using/playing with Python, and I have what is likely a > very simple question but can't seem to figure it out. > Python is fun and it's easier to use a real OS to develop the programs, then if need be, not that difficult to move them to windows:) > I wrote up a script in my preferred text editor. It contains maybe ten > lines of code. I want to be able to execute those code lines with a > single command either from the inline mode or from IDLE. How do I do > this? I saved the file (myscript.py) in a folder that I've specified > in my PYTHONPATH environment variable, and when I type If you are going to use a text editor to do python with, may I suggest gVim, or vim it will take care of ALOT of syntax errors dure to indentation for you. Grant it I am a command line junky, but still... > > >>> import myscript > > the script runs. If, later during the same session, I type > > >>> myscript > > all I get for output is > > documents\Python Modules\myscript.pyc'> > > Somwhere in the beginning tutorial there's this line: > > "The script can be given a executable mode, or permission, using the > chmod command: > > $ chmod +x myscript.py" > Ok, the above seems to me like you are useing windows. If so, the chmod commands are going to be just about worthless. If you install unix services for windows, you will get some functionality, but not also, and still what's the point. Linux is free and much more stable, secure, etc... > Which I took to mean that if I enter that I would be able to do what I > wanted. But no, it just highlights 'myscript' in red and says it's a > syntax error. > > What am I missing? OK, excuseing my editorial comments above, here is what I see and correct me if I'm wrong. 1) you use windows 2) You have not been around any OS other than windows and I mean this as no insult, just making sure I understand you. The answer to your questions are as follows. In Unix/Linux/XXix/Solaris and most anyother unixy(yes that's a word, I just made it up) OS you can add the first line of the script being something like #!/usr/bin/python or where ever you installed python to, then FROM A COMMAND LINE run chmod and it will make the script executable. What happens is when you tell the script to run, it looks at the line and then knows where to pull the inter. from. the # just comments it out so it don't try to run it with the rest of the script, the ! tells the computer to pay attention to it. As far as I know, you cannot do this in Windows. to run it in a single command, you would have to either compile it with py2exe which will give you the .exe and a dll or two or you can simple make a batch file that would look something like @ECHO OFF python script.py the @ECHO OFF is not needed, but I think it looks better and more professional, but that is just me. I do realize I have rambled on for a while here but I do hope it helps. I have been out of the python loop for a while, but am being forced back into it, which really don't hurt my feelings at all, just had to wait for a project that required it:) Anyway if you dont understand anything just let me know and i'll try to do a better job explaining it. Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie question
i keep on getting this message that says socket error, then says that python was unable to connect to its start up process. what does this mean and how can i fix it? D <[EMAIL PROTECTED]> wrote: Yep, that should work. Just keep in mind that if python.exe is not inyour path, you will need to either specify the entire path to it(i.e. 'C:\python24\python C:\path\to\script\myscript.py'), or cd intoits directory first (i.e. if you want to just run 'pythonC:\path\to\script\myscript.py').Doug-- http://mail.python.org/mailman/listinfo/python-list To help you stay safe and secure online, we've developed the all new Yahoo! Security Centre.-- http://mail.python.org/mailman/listinfo/python-list
Re: newbie question
orangeDinosaur wrote: > I wrote up a script in my preferred text editor. It contains maybe ten > lines of code. I want to be able to execute those code lines with a > single command either from the inline mode or from IDLE. How do I do > this? I saved the file (myscript.py) in a folder that I've specified > in my PYTHONPATH environment variable, and when I type From the Python shell, you can use execfile to run a script: >>> execfile("joshua.py") This works regardless of your OS. The file must be in your Python path. If it isn't, just specify the full path. Like: >>> execfile(r"C:\Code\WOPR\Backdoor\joshua.py") While viewing your code with IDLE, hit F5 to execute it. -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie question
I think the answers so far are unnecessarily confusing and off the mark. Here is what I think you think you want to know: 1) import only works once. If you try import again, it will see the module already exists, and will ignore you 2) the functionality you think you want is reload. >>> reload mymodule will essentially reimport mymodule after the first time. However, what you think you want is not what you want, which is why the experienced people are giving misleading and overcomplicated answers. Normally reload is a fairly advanced feature and beginners don't need it. Usually, an import statement invokes a module containing a bunch of definitions (usually functions or classes, but sometimes even constants), but it doesn't DO anything unless it is invoked as the main program. So after you satisfy yourself that "reload" does what you want, try to think about how you would work things so you don't need it. For instance, instead of something like #mystuff.py print "hello ", print "world" # end of file >>> import mystuff hello world >>> import mystuff >>> is ### newstuff.py def newstuff(): print "hello", print " world" # end of file >>> from newstuff import newstuff >>> newstuff() hello, world >>> newstuff() hello, world hth mt -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie question
Thanks!! This makes sense. And you were right about my misunderstanding. Michael Tobis wrote: > I think the answers so far are unnecessarily confusing and off the > mark. > > Here is what I think you think you want to know: > > 1) import only works once. If you try import again, it will see the > module already exists, and will ignore you > > 2) the functionality you think you want is reload. > >>> reload mymodule > will essentially reimport mymodule after the first time. > > However, what you think you want is not what you want, which is why the > experienced people are giving misleading and overcomplicated answers. > Normally reload is a fairly advanced feature and beginners don't need > it. > > Usually, an import statement invokes a module containing a bunch of > definitions (usually functions or classes, but sometimes even > constants), but it doesn't DO anything unless it is invoked as the main > program. > > So after you satisfy yourself that "reload" does what you want, try to > think about how you would work things so you don't need it. > > For instance, instead of something like > > #mystuff.py > > print "hello ", > print "world" > > # end of file > > > > >>> import mystuff > hello world > >>> import mystuff > > >>> > > is > > > > ### newstuff.py > > def newstuff(): >print "hello", >print " world" > > # end of file > > > > >>> from newstuff import newstuff > >>> newstuff() > hello, world > >>> newstuff() > hello, world > > > hth > mt -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie question
Dennis Lee Bieber <[EMAIL PROTECTED]> wrote: >On 1 Mar 2006 12:47:26 -0800, "D" <[EMAIL PROTECTED]> declaimed the >following in comp.lang.python: > >> Yep, that should work. Just keep in mind that if python.exe is not in >> your path, you will need to either specify the entire path to it >> (i.e. 'C:\python24\python C:\path\to\script\myscript.py'), or cd into >> its directory first (i.e. if you want to just run 'python >> C:\path\to\script\myscript.py'). >> > Actually, on XP at least, some combination of commands enables >things such that one can run without the "python" or the ".py" (but I >think it garbages I/O redirection and maybe command line arguments -- >though this one worked) That's the PATHEXT environment variable. C:\tmp>set PATHEXT PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.PY;.PYW;.tcl If you give a lone file name without an extension, it will try all of those extensions, in that order, to find an executable. Just add .PY to the end. There is a bug in NT's CMD.EXE that screws up redirection of stdin, but command line arguments and stdout work just fine. -- - Tim Roberts, [EMAIL PROTECTED] Providenza & Boekelheide, Inc. -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie question
Since you are a Windows user, I strongly recommend that you install activestate python instead of the one you download from python.org. The PythonWin from active state is much more user friendly. It's basically an IDE (integrated development environment), which includes interactive shell, editor, debugger, online help. Just to name a few. Good luck. -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie question
On 23/03/2006 1:53 PM, Kevin F wrote: > what does it mean when there are [0] or [1] after a variable? > > e.g. print 'Message %s\n%s\n' % (num, data[0][1]) Here's the section in the Python Tutorial that should answer your question: http://docs.python.org/tut/node5.html#SECTION00514 You may like to start at the *beginning* of the Tutorial :-) ... or you might like to ask another question, stating your experience if any with other languages, what you want to do with Python, and asking for general advice on how to learn Python. Cheers, John -- http://mail.python.org/mailman/listinfo/python-list
python's newbie question
Hi. I have some strange problem (this is usual for newbies :) ): #!/usr/bin/python #sample.py class Base1: def __init__(self): print "Base1.__init__", self def __del__(self): print "Base1.__del__", self class Base2: def __init__(self): print "Base2.__init__", self def __del__(self): print "Base2.__del__", self class Derived(Base1, Base2): def __init__(self): print "Derived.__init__:" Base1.__init__(self) Base2.__init__(self) def __del__(self): print "Derived.__del__:" Base1.__del__(self) Base2.__del__(self) print "begin..." d = Derived() b = d print "end..." The output of this script: begin... Derived.__init__: Base1.__init__ <__main__.Derived instance at 0x1869adcc> Base2.__init__ <__main__.Derived instance at 0x1869adcc> end... Derived.__del__: Base1.__del__ <__main__.Derived instance at 0x1869adcc> Base2.__del__ <__main__.Derived instance at 0x1869adcc> If I change this program a little: #!/usr/bin/python #skipped print "begin..." d = Derived() b1 = d #Here print "end..." The output is: begin... Derived.__init__: Base1.__init__ <__main__.Derived instance at 0x1869adcc> Base2.__init__ <__main__.Derived instance at 0x1869adcc> end... Derived.__del__: Exception exceptions.AttributeError: "'NoneType' object has no attribute '__del__'" in > ignored I tried different names instead of b1, sometimes programm works, sometimes I have an exception. So it's clear, that I've done some stupid mistake, but it's not clear for me, python's newbie, where :) -- http://mail.python.org/mailman/listinfo/python-list
Python Newbie question
Is it possible to combine or bundle separate .exe files into the compiled python .exe when using py2exe? If possible, how would that be described within setup.py . and how/where would I specify such .exe should be ran first in the pre-compiled scripts? My goal is to get the total package down to as few files as possible, so I appreciate understanding how I could do this. The .exe is some low-level commands that was compiled in a separate language but I hope this little .exe can be included gracefully. Thank you for your expertise! :) AMYMC -- http://mail.python.org/mailman/listinfo/python-list
Newbie Question : "grep"
Hello, I am attempting to write my first Python script to extract some information from a file, and place it into another file. (I am trying to find the physical postions of 4 cells within an FPGA) I have a working solution, and would appreciate any comments. for line in lines: if "placed" in line: if "i_a/i_b/ROM/" in line: pos = (line.split()[4]).split("_")[1] if "B18" in line: print "i_a/i_b/ROM/B18 [7:6] LOC =", pos elif "B14" in line: print "i_a/i_b/ROM/B14 [5:4] LOC =", pos elif "B10" in line: print "i_a/i_b/ROM/B10 [3:2] LOC =", pos elif "B6" in line: print "i_a/i_b/ROM/B6 [1:0] LOC =", pos else: print "Error" Specific questions - Use for "Phrase" in line or line.find("Phrase") >= 0 ? - If I increase number of elements I am searching for, then I have more elif...elif. Is there a cleaner solution? Thanks for any feedback. Steven -- http://mail.python.org/mailman/listinfo/python-list
another newbie question
Hello everyone, I have a question that google couldnt answer for me and thought that the brains on here might be able to help. I am trying to upload a file to a database using a (cgi) form and am having trouble doing this. I think that I need some way of escaping the file contents or making it so that mysql/python (not sure which) will ignore the files actual contents and store it in the db regardless of what is actually in the file. I hope that made sense. Thanks in advance for any help. Regards, MJ -- http://mail.python.org/mailman/listinfo/python-list
semi-Newbie question
Hi all I have a file that I receive from another party which is basicly a csv file containing the following type of information; Tagname Scope Value "first_name","POL01","John" "last_name","POL01","Doe" "birthday","POL01","04/03/61" etc I need to convert this file info into my file format used in my application. I have been given a file from the other company that gives me all of the tagname that could be used and their scope. I want to build a table which would have all of the various tagnames, scope, and put a fieldname equivalent in the fieldname in my file structure in my application. Then read through the vendors csv file index into my table file and get the field name of where to move the data into my data structure. Here is my question? basicly I need to get the data referenced by fieldname variable in my table and then use that data as a variable name in a python assignment statement. Thus changing the actual python code at each iteration through the lines in the csv file. for i in tagfile find tagname in tagtable *** the following line of code would change through each iteration *** myfirst = value *** next iteration mylast = value *** next iteration mybirth = value etc I hope this make sense. I remember seeing something like this somewhere. Any help appreciated. Len Sumnler Unique Insurance -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie question
kavitha thankaian wrote: > Hi, > > i wrote a simple script (which follows) to insert a table in the > database.i could execute this query and get the result in python > shell.but when i open "my sql enterprise manager" i couldnt find the > table"animals".it would be so kind of you if someone could help me,,, > > > import dbi > import odbc > conn=odbc.odbc("DSN=mydatabase;UID=xxx;PWD=yyy") > cursor=conn.cursor() > cursor.execute("Create table animals(parent char(50),child char(50))") > cursor.execute("insert into animals values('lion','cub')") > cursor.execute("insert into animals values('goat','lamb')") > cursor.execute("select * from animals") > print cursor.fetchall() > > > Rgds > Kavitha > > You've probably missed cursor.commit() ;) -- Sincerely, Eugene Antimirov PortaOne, Inc., SIP Support Engineer [EMAIL PROTECTED] * For further Billing and Technical information: => Please visit our website http://www.portaone.com => Please visit our forum http://forum.portaone.com * Meet us at Internet Telephony Conference & Expo * Ft. Lauderdale, FL - January 24-26, 2007 - Booth 1322 * http://www.tmcnet.com/voip/conference/ -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie question
Eugene Antimirov wrote: > You've probably missed cursor.commit() ;) Sorry, my bad: conn.commit() is correct one AFAIR. -- Sincerely, Eugene Antimirov PortaOne, Inc., SIP Support Engineer [EMAIL PROTECTED] * For further Billing and Technical information: => Please visit our website http://www.portaone.com => Please visit our forum http://forum.portaone.com * Meet us at Internet Telephony Conference & Expo * Ft. Lauderdale, FL - January 24-26, 2007 - Booth 1322 * http://www.tmcnet.com/voip/conference/ -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie question
Hi Eugene, I tried with conn.commit() as well,,but doesnt seem to work. Also i cannot even view the existing tables via python script.For example,,,i have manually added a customer table in my database.but if i execute the query, select * from customer,,,i get the following error: mxODBC.ProgrammingError: ('S0002', 208, "[Microsoft][ODBC SQL Server Driver][SQL Server]Invalid object name customer.", 4612) If someone knows the solution please help me,,, Kavitha Eugene Antimirov <[EMAIL PROTECTED]> wrote: Eugene Antimirov wrote: > You've probably missed cursor.commit() ;) Sorry, my bad: conn.commit() is correct one AFAIR. -- Sincerely, Eugene Antimirov PortaOne, Inc., SIP Support Engineer [EMAIL PROTECTED] * For further Billing and Technical information: => Please visit our website http://www.portaone.com => Please visit our forum http://forum.portaone.com * Meet us at Internet Telephony Conference & Expo * Ft. Lauderdale, FL - January 24-26, 2007 - Booth 1322 * http://www.tmcnet.com/voip/conference/ -- http://mail.python.org/mailman/listinfo/python-list - Heres a new way to find what you're looking for - Yahoo! Answers -- http://mail.python.org/mailman/listinfo/python-list
newbie question: ftp.storbinary()
Sorry for the lame question, I'm still trying to pick up Python and new to the list here. Question: I'm trying to write a python script that will access an FTP site and upload some files. I've gotten everything working except for the actual uploading of the files. I'm assuming that I should use storbinary( command, file[, blocksize]) to transfer the files. the documentation says "command should be an appropriate "STOR" command: "STOR filename"." I can't seem to figure out an `appropriate "STOR" command' is??? Thank for reading my post. Cheers, Scott -- http://mail.python.org/mailman/listinfo/python-list