ANN pyftpdlib 0.1 released
Hi all, I'm proud to announce the first beta release of pyftpdlib available at the following urls: home: http://billiejoex.altervista.org/pyftpdlib.html google code: http://code.google.com/p/pyftpdlib/ About = pyftpdlib is an high-level FTP server library based on asyncore/ asychat frameworks. pyftpdlib is actually the most complete RFC959 FTP server implementation available for Python programming language. Requirements == Python 2.2 or higher Bug reports / Contacts billiejoex -_[AT]_- gmail (dot) com -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html
Building a dictionary from a tuple of variable length
Hi, I have the following tuple - t = (one,two) And I can build a dictionary from it as follows - d = dict(zip(t,(False,False))) But what if my tuple was - t = (one,two,three) then I'd have to use - d = dict(zip(t,(False,False,False))) Therefore, how do I build the tuple of Falses to reflect the length of my t tuple? Thanks for your help, Barry. -- http://mail.python.org/mailman/listinfo/python-list
Re: Project organization and import
On 5 mar, 01:21, Martin Unsal [EMAIL PROTECTED] wrote: I'm using Python for what is becoming a sizeable project and I'm already running into problems organizing code and importing packages. I feel like the Python package system, in particular the isomorphism between filesystem and namespace, It's not necessarily a 1:1 mapping. Remember that you can put code in the __init__.py of a package, and that this code can import sub- packages/modules namespaces, making the package internal organisation transparent to user code (I've quite often started with a simple module, latter turning it into a package as the source-code was growing too big). doesn't seem very well suited for big projects. However, I might not really understand the Pythonic way. cf above. I'm not sure if I have a specific question here, just a general plea for advice. 1) Namespace. Python wants my namespace heirarchy to match my filesystem heirarchy. I find that a well organized filesystem heirarchy for a nontrivial project will be totally unwieldy as a namespace. I'm either forced to use long namespace prefixes, or I'm forced to use from foo import * and __all__, which has its own set of problems. cf above. Also remember that you can import as, ie: import some_package.some_subpackage.some_module as some_module 1a) Module/class collision. I like to use the primary class in a file as the name of the file. Bad form IMHO. Packages and module names should be all_lower, classnames CamelCased. 1b) The Pythonic way seems to be to put more stuff in one file, Pythonic way is to group together highly related stuff. Not to put more stuff. but I believe this is categorically the wrong thing to do in large projects. Oh yes ? Why ? The moment you have more than one developer along with a revision control system, You *always* have a revision system, don't you ? And having more than one developper on a project - be it big or small - is quite common. you're going to want files to contain the smallest practical functional blocks. I feel pretty confident saying that put more stuff in one file is the wrong answer, even if it is the Pythonic answer. Is this actually based on working experience ? It seems that there are enough not-trivial Python projects around to prove that it works just fine. -- http://mail.python.org/mailman/listinfo/python-list
Getting external IP address
I have a PC behind a firewall, and I'm trying to programmatically determine the IP address visible from outside the firewall. If I do this: import socket socket.gethostbyname(socket.gethostname()) '127.0.0.1' socket.gethostbyname_ex(socket.gethostname()) ('localhost.localdomain', ['localhost'], ['127.0.0.1']) I get my internal IP address, which is not what I want. Other tricks, like parsing the output of os.system('/sbin/ifconfig eth0') also give me my internal IP address. I found this post on comp.lang.python a few years ago: http://mail.python.org/pipermail/python-list/2003-March/192495.html which seems like it _should_ do what I want, but it doesn't: I get an exception. from httplib import HTTPConnection from xml.dom.ext.reader.Sax import FromXmlStream conn = HTTPConnection('xml.showmyip.com') conn.request('GET', '/') doc = FromXmlStream(conn.getresponse()) print doc.getElementsByTagName('ip')[0].firstChild.data Traceback (most recent call last): File stdin, line 1, in ? File /usr/lib/python2.4/UserList.py, line 28, in __getitem__ def __getitem__(self, i): return self.data[i] IndexError: list index out of range conn.close() I don't know how to fix it so that it works. Can anyone help me fix that code snippet, or suggest another (better) way to get the externally visible IP address? -- Steven D'Aprano -- http://mail.python.org/mailman/listinfo/python-list
Re: How use XML parsing tools on this one specific URL?
[EMAIL PROTECTED] wrote: Chris http://moneycentral.msn.com/companyreport?Symbol=BBBY Chris I can't validate it and xml.minidom.dom.parseString won't work on Chris it. Chris If this was just some teenager's web site I'd move on. Is there Chris any hope avoiding regular expression hacks to extract the data Chris from this page? Tidy it perhaps or use BeautifulSoup? ElementTree can use tidy if it's available. ElementTree can also use BeautifulSoup: http://effbot.org/zone/element-soup.htm as noted on that page, tidy is a bit too picky for this kind of use; it's better suited for normalizing HTML that you're producing yourself than for parsing arbitrary HTML. /F -- http://mail.python.org/mailman/listinfo/python-list
Re: Building a dictionary from a tuple of variable length
In [EMAIL PROTECTED], bg_ie wrote: Therefore, how do I build the tuple of Falses to reflect the length of my t tuple? In [1]: dict.fromkeys(('one', 'two', 'three'), False) Out[1]: {'three': False, 'two': False, 'one': False} Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Building a dictionary from a tuple of variable length
[EMAIL PROTECTED] wrote: I have the following tuple - t = (one,two) And I can build a dictionary from it as follows - d = dict(zip(t,(False,False))) But what if my tuple was - t = (one,two,three) then I'd have to use - d = dict(zip(t,(False,False,False))) Therefore, how do I build the tuple of Falses to reflect the length of my t tuple? For dictionaries there is a special method: dict.fromkeys((one, two, three), False) {'three': False, 'two': False, 'one': False} When you are just interested in the list of tuples, use repeat(): from itertools import repeat zip(abc, repeat(False)) [('a', False), ('b', False), ('c', False)] Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: list-like behaviour of etree.Element
Raymond Hettinger wrote: On Mar 4, 12:48 pm, Daniel Nogradi [EMAIL PROTECTED] wrote: The etree.Element (or ElementTree.Element) supports a number of list-like methods: append, insert, remove. Any special reason why it doesn't support pop and extend (and maybe count)? Those methods would not be hard to add. Perhaps, submit a feature request to Fredrik Lundh on SourceForge and see what he thinks there is merit in more closely emulating the list API. Of the methods you listed, the case is probably strongest for extend(). extend() will be in the next release: http://effbot.org/zone/elementtree-changes-13.htm (lxml.etree already has it, btw). not sure I see the point of pop() and count(). a successful feature request would need to include some really compelling use cases. /F -- http://mail.python.org/mailman/listinfo/python-list
Re: Getting external IP address
Steven D'Aprano [EMAIL PROTECTED] wrote: from httplib import HTTPConnection from xml.dom.ext.reader.Sax import FromXmlStream conn = HTTPConnection('xml.showmyip.com') conn.request('GET', '/') doc = FromXmlStream(conn.getresponse()) print doc.getElementsByTagName('ip')[0].firstChild.data Traceback (most recent call last): File stdin, line 1, in ? File /usr/lib/python2.4/UserList.py, line 28, in __getitem__ def __getitem__(self, i): return self.data[i] IndexError: list index out of range conn.close() I don't know how to fix it so that it works. Can anyone help me fix that code snippet, or suggest another (better) way to get the externally visible IP address? Try running it interactively and looking at the data you receive: conn = HTTPConnection('xml.showmyip.com') conn.request('GET', '/') resp = conn.getresponse() print resp httplib.HTTPResponse instance at 0x00C58350 data = resp.read() print data htmlheadtitleObject moved/title/headbody h2Object moved to a href=http://www.showmyip.com/xml/;here/a. /h2 /body/html If you try connecting to 'www.showmyip.com' and requesting '/xml/' it should work. -- http://mail.python.org/mailman/listinfo/python-list
clientcookie/clientform and checking to see if a website accepted my login details
alright, i'm coding a program that will log me into yahoo.com (so far), now, the problem i have is that once i've submitted by login password, the program doesn't know whether yahoo.com accepted it. response = ClientCookie.urlopen(form.click()) now, when i get an error, the contents of 'response' will be different, ex: the contents of 'titleexample/title' will be 'titlelogged in!/title'. is there any function that can search through the code for that text to check if i'm logged in or not? all help is appreciated -- http://mail.python.org/mailman/listinfo/python-list
How to create pid.lock via python?
Hello, I write a program control a device via RS232, I hope to add some code to let the program canNOT be used by other people when one people using. Can you tell me how to create pid.lock file in python? Thank you!! -- LinuX Power -- http://mail.python.org/mailman/listinfo/python-list
Mod python - mysql lock
Hi, In my mod_python project I am using mysql as the database. There is table card in which unique cards are stored. When a user request comes he has to get a unique card. In this situation I want to use LOCK with which I can prevent other users accessing the table. I tried excuting LOCK command of mysql through python code, but it is not locking the database. Any ideas why this isn't working and how can I do the same. //python code sql = LOCK TABLES card WRITE cursor.execute(sql) Regards Roopesh -- http://mail.python.org/mailman/listinfo/python-list
Howto pass exceptions between threads
Hallo Alltogether, I've searched in this mailing list, but it seems to me that there is no general approach to pass exceptions from one thread to another. I think most application do a unique way of handling unhandled exceptions, at least they (should) try to log them. The following discussion seems to me most valuable (Sorry for the long URL, I don't know a way of shorter) http://groups.google.de/group/comp.lang.python/browse_frm/thread/a2ebb2a2f611779b/4b820c20ff3fcea8?lnk=gstq=%2Bexception+%2Bthreadrnum=6hl=de#4b820c20ff3fcea8 http://groups.google.de/group/comp.lang.python/browse_frm/thread/2c61c06795f525f3/348a8d9e85883fe3?lnk=gstq=pass+%2Bexception+%2Bthreadrnum=1hl=de#348a8d9e85883fe3 I've the feeling that if you're using the python class threading.Thread you've a unique interface of handling it. (thread synchronizing + exception raising) But' when you've a C++ extension, that uses it's own thread implementation and your exceptions happens in python code (but from a thread that is controlled by your extension) you have another problem. Maybe I've overseen something in the python docu, so I ask for the solutions, concepts, hints ... you solved the problem. Regards Alexander -- http://mail.python.org/mailman/listinfo/python-list
Re: list-like behaviour of etree.Element
The etree.Element (or ElementTree.Element) supports a number of list-like methods: append, insert, remove. Any special reason why it doesn't support pop and extend (and maybe count)? Those methods would not be hard to add. Perhaps, submit a feature request to Fredrik Lundh on SourceForge and see what he thinks there is merit in more closely emulating the list API. Of the methods you listed, the case is probably strongest for extend(). extend() will be in the next release: http://effbot.org/zone/elementtree-changes-13.htm (lxml.etree already has it, btw). not sure I see the point of pop() and count(). a successful feature request would need to include some really compelling use cases. Great! I also first thought of extend because that would be really useful, pop and count just came to mind because they exist for lists. But if extend will be added that'll already make life easier, pop/count is probably not that much needed. -- http://mail.python.org/mailman/listinfo/python-list
Re: MS SQL Database connection
Hitesh wrote: Hi currently I am using DNS and ODBC to connect to MS SQL database. Is there any other non-dns way to connect? If I want to run my script from different server I first have to create the DNS in win2k3. Here are several ways to connect to an MSSQL database w/o having to create DNS or anything else in win2k3 ;) There are other ways (the slightly stale MSSQL module from Object Craft, for example, which still works fine for Python = 2.3). TJG code def adodbapi_connection (server, database, username, password): # # http://adodbapi.sf.net # import adodbapi connectors = [Provider=SQLOLEDB] connectors.append (Data Source=%s % server) connectors.append (Initial Catalog=%s % database) if username: connectors.append (User Id=%s % username) connectors.append (Password=%s % password) else: connectors.append(Integrated Security=SSPI) return adodbapi.connect (;.join (connectors)) def pymssql_connection (server, database, username, password): # # http://pymssql.sf.net # import pymssql if not username: raise RuntimeError, Unable to use NT authentication for pymssql return pymssql.connect (user=username, password=password, host=server, database=database) def pyodbc_connection (server, database, username, password): # # http://pyodbc.sf.net # import pyodbc connectors = [Driver={SQL Server}] connectors.append (Server=%s % server) connectors.append (Database=%s % database) if username: connectors.append (UID=%s % username) connectors.append (PWD=%s % password) else: connectors.append (TrustedConnection=Yes) return pyodbc.connect (;.join (connectors)) /code -- http://mail.python.org/mailman/listinfo/python-list
Re: Mod python - mysql lock
Roopesh wrote: In my mod_python project I am using mysql as the database. There is table card in which unique cards are stored. When a user request comes he has to get a unique card. In this situation I want to use LOCK with which I can prevent other users accessing the table. I tried excuting LOCK command of mysql through python code, but it is not locking the database. Any ideas why this isn't working and how can I do the same. //python code sql = LOCK TABLES card WRITE cursor.execute(sql) How have you verified that the lock isn't actually working? From http://dev.mysql.com/doc/refman/5.0/en/lock-tables.html: UNLOCK TABLES explicitly releases any locks held by the current thread. All tables that are locked by the current thread are implicitly unlocked when the thread issues another LOCK TABLES, or when the connection to the server is closed. Note the last part -- the lock is apparently released when the connection is closed. Is that perhaps what is happening? Remember that once your request is done in mod_python, it will (probably) release any allocated resources, which means that your connection will be closed, and your lock released, if it wasn't previously. Database locks are, generally, bad. Avoid them, and only use them when they really are the only solution. From what little information you supply, it seems that what you need is simply automatic id generation. Essentially you to do this: INSERT INTO foobar (title) VALUES ('yuck') SELECT LAST_INSERTED_ID() foobar needs to have an auto_increment column, and LAST_INSERTED_ID() is probably called something else (long time since I used MySQL). This is actually more of a MySQL question. Or even a generic database design question. I would suggest you try asking in a more appropriate forum. -- Kind regards, Jan Danielsson -- http://mail.python.org/mailman/listinfo/python-list
Re: How to Read Bytes from a file
Bart Ogryczak [EMAIL PROTECTED] (BO) wrote: BO Any system with 8-bit bytes, which would mean any system made after BO 1965. I'm not aware of any Python implementation for UNIVAC, so I BO wouldn't worry ;-) 1965? I worked with non-8-byte machines (CDC) until the beginning of the 80's. :=( In fact in that time the institution where Guido worked also had such a machine, but Python came later. -- Piet van Oostrum [EMAIL PROTECTED] URL: http://www.cs.uu.nl/~piet [PGP 8DAE142BE17999C4] Private email: [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Source Code Beautifier
Il Sat, 03 Mar 2007 17:34:35 +1300, greg ha scritto: This was all discussed at *very* great length many years ago, and the addition of in-place operators to the language was held up for a long time until the present compromise was devised. You might not like it, but it's here to stay. Sure. I'm not a great programmer and I never thought about asking for such a removal. I'm sure that there're people smarter and more experienced than me out there designing Python, I'm glad I got it and I won't use such shortcuts on mutable objects in my own programs. At least, this is I what I think today; tomorrow, when I'm more experienced, I could think about them and say 'Hey! They're really cute, why haven't I used them before?' Bye! -- Alan Franzoni [EMAIL PROTECTED] - Togli .xyz dalla mia email per contattarmi. Remove .xyz from my address in order to contact me. - GPG Key Fingerprint (Key ID = FE068F3E): 5C77 9DC3 BD5B 3A28 E7BC 921A 0255 42AA FE06 8F3E -- http://mail.python.org/mailman/listinfo/python-list
Re: How to Read Bytes from a file
On Mar 5, 10:51 am, Piet van Oostrum [EMAIL PROTECTED] wrote: Bart Ogryczak [EMAIL PROTECTED] (BO) wrote: BO Any system with 8-bit bytes, which would mean any system made after BO 1965. I'm not aware of any Python implementation for UNIVAC, so I BO wouldn't worry ;-) 1965? I worked with non-8-byte machines (CDC) until the beginning of the 80's. :=( In fact in that time the institution where Guido worked also had such a machine, but Python came later. Right, I should have written 'designed' not 'made'. UNIVACs also have been produced until early 1980s. Anyway, I'd call it paleoinformatics ;-) -- http://mail.python.org/mailman/listinfo/python-list
Dictionary of Dictionaries
Hi, I have the following - messagesReceived = dict.fromkeys((one,two), {}) messagesReceived['one']['123'] = 1 messagesReceived['two']['121'] = 2 messagesReceived['two']['124'] = 4 This gives: {'two': {'121': 2, '123': 1, '124': 4}, 'one': {'121': 2, '123': 1, '124': 4}} but I expected - {'one': {'121': 2, }, 'two': {'123': 1, '124': 4}} What am I doing wrong? Thanks, Barry. -- http://mail.python.org/mailman/listinfo/python-list
Re: How use XML parsing tools on this one specific URL?
On 4 Mar, 20:21, Nikita the Spider [EMAIL PROTECTED] wrote: In article [EMAIL PROTECTED], I can't validate it and xml.minidom.dom.parseString won't work on it. [...] Valid XHTML is scarcer than hen's teeth. It probably doesn't need to be valid: being well-formed would be sufficient for the operation of an XML parser, and for many applications it'd be sufficient to consider the content as vanilla XML without the XHTML overtones. Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Dictionary of Dictionaries
On 5 Mar 2007 02:22:24 -0800, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote: Hi, I have the following - messagesReceived = dict.fromkeys((one,two), {}) This will create a dictionary messagesReceived, with all the keys referring to *same instance* of the (empty) dictionary. ( try: messagesReceived = dict( [(k,{}) for k in ('one', 'two') ] ) ) messagesReceived['one']['123'] = 1 messagesReceived['two']['121'] = 2 messagesReceived['two']['124'] = 4 This gives: {'two': {'121': 2, '123': 1, '124': 4}, 'one': {'121': 2, '123': 1, '124': 4}} And hence the results ! HTH, -- Amit Khemka -- onyomo.com Home Page: www.cse.iitd.ernet.in/~csd00377 Endless the world's turn, endless the sun's Spinning, Endless the quest; I turn again, back to my own beginning, And here, find rest. -- http://mail.python.org/mailman/listinfo/python-list
Re: Dictionary of Dictionaries
In [EMAIL PROTECTED], bg_ie wrote: What am I doing wrong? `dict.fromkeys()` stores the given object for all keys, so you end up with the *same* dictionary for 'one' and 'two'. In [18]: a = dict.fromkeys((one,two), {}) In [19]: a Out[19]: {'two': {}, 'one': {}} In [20]: a['one']['x'] = 42 In [21]: a Out[21]: {'two': {'x': 42}, 'one': {'x': 42}} In [22]: a['one'] is a['two'] Out[22]: True Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Source Code Beautifier
On 2 Mar, 14:45, Alan Franzoni [EMAIL PROTECTED] wrote: I mean... I don't like that. I'm not really a Python expert, I found this behaviour is documented in the language reference itself: http://docs.python.org/ref/augassign.html But... I don't know, still think it's confusing and not going to use it. One way to think of it is this: a += b ...is more or less the same as... if hasattr(a, __iadd__): a = a.__iadd__(b) else: a = a + b Since __iadd__ might mutate an object, returning the same object, it's possible to say that the name a still points to the same object in such circumstances using the above scheme. Whether any rebinding or resetting of a actually takes place in such a situation (in CPython) might be considered an issue of optimisation, but I suppose augmented assignments with attributes might bring out some semantic differences, too, as can be seen by the note about class attributes at the end of the referenced section of the manual. Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Dictionary of Dictionaries
On 5 Mar, 11:45, Amit Khemka [EMAIL PROTECTED] wrote: On 5 Mar 2007 02:22:24 -0800, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote: Hi, I have the following - messagesReceived = dict.fromkeys((one,two), {}) This will create a dictionary messagesReceived, with all the keys referring to *same instance* of the (empty) dictionary. ( try: messagesReceived = dict( [(k,{}) for k in ('one', 'two') ] ) ) messagesReceived['one']['123'] = 1 messagesReceived['two']['121'] = 2 messagesReceived['two']['124'] = 4 This gives: {'two': {'121': 2, '123': 1, '124': 4}, 'one': {'121': 2, '123': 1, '124': 4}} And hence the results ! HTH, -- Amit Khemka -- onyomo.com Home Page:www.cse.iitd.ernet.in/~csd00377 Endless the world's turn, endless the sun's Spinning, Endless the quest; I turn again, back to my own beginning, And here, find rest. Thanks for your help! -- http://mail.python.org/mailman/listinfo/python-list
Return type of operator on inherited class
Hi, my question is on this example: class MyStr(str): def hello(self): print 'Hello !' s1 = MyStr('My string') s2 = MyStr('My second string') s1.hello() s2.hello() s = s1 + s2 s.hello() Hello ! Hello ! Traceback (most recent call last): File string, line 204, in run_nodebug File module1, line 13, in module AttributeError: 'str' object has no attribute 'hello' How could I get a type MyStr from the 'plus' (__add__) operation without overriding it in my class ? I need to override *every* operator I like to use ? -- http://mail.python.org/mailman/listinfo/python-list
Re: Getting external IP address
Duncan Booth [EMAIL PROTECTED] writes: If you try connecting to 'www.showmyip.com' and requesting '/xml/' it should work. If the firewall is really obnoxious, it can bounce consecutive queries around between multiple originating IP addresses. That is uncommon but it's been done from time to time. -- http://mail.python.org/mailman/listinfo/python-list
Re: Return type of operator on inherited class
looping wrote: Hi, my question is on this example: class MyStr(str): def hello(self): print 'Hello !' s1 = MyStr('My string') s2 = MyStr('My second string') s1.hello() s2.hello() s = s1 + s2 s.hello() Hello ! Hello ! Traceback (most recent call last): File string, line 204, in run_nodebug File module1, line 13, in module AttributeError: 'str' object has no attribute 'hello' How could I get a type MyStr from the 'plus' (__add__) operation without overriding it in my class ? You can't. I need to override *every* operator I like to use ? Yes. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: list-like behaviour of etree.Element
On Mar 5, 8:00 pm, Fredrik Lundh [EMAIL PROTECTED] wrote: extend() will be in the next release: http://effbot.org/zone/elementtree-changes-13.htm Hi Fredrik, The library requires Python 2.2 or newer. -- Does this apply to cElementTree as well? Reason for asking: my xlrd package works with Python 2.1 or later. I'm using cElementTree in a so-far-so-good prototype of parsing Excel 2007 .XLSX files ... Regards, John Regards, John -- http://mail.python.org/mailman/listinfo/python-list
Re: Getting external IP address
Paul Rubin http://[EMAIL PROTECTED] wrote: Duncan Booth [EMAIL PROTECTED] writes: If you try connecting to 'www.showmyip.com' and requesting '/xml/' it should work. If the firewall is really obnoxious, it can bounce consecutive queries around between multiple originating IP addresses. That is uncommon but it's been done from time to time. Yes, each connection through the firewall needs to have a unique originating ip and port number. If there are too many machines inside the firewall then you may need to allocate multiple ip addresses on the outside. I would hope that in general a single internal IP should map to one external IP at a time (otherwise you would have problems with ip based session persistence connecting to load balanced systems), but you might expect to bounce round different IPs after periods of inactivity. Also you could have multiple levels of NAT in which case the question becomes whether Steven wants the IP as seen from outside the immediate firewall or outside the final one. Maybe he should be using IPv6 to avoid all this? -- http://mail.python.org/mailman/listinfo/python-list
Re: Python stock market analysis tools?
On 4 Mar 2007 19:52:56 -0800, Mudcat [EMAIL PROTECTED] wrote: I have done a bit of searching and can't seem to find a stock market tool written in Python that is active. Anybody know of any? I'm trying not to re-create the wheel here. Depends on what you mean by stock market tool. There's http://ta-lib.org which while written in C++ claims to have a python wrapper. That being said last time I looked at it I couldn't get the python binding working, but I didn't spend much time on it. Dag -- http://mail.python.org/mailman/listinfo/python-list
Re: Building a dictionary from a tuple of variable length
[EMAIL PROTECTED] kirjoitti: Hi, I have the following tuple - t = (one,two) And I can build a dictionary from it as follows - d = dict(zip(t,(False,False))) But what if my tuple was - t = (one,two,three) then I'd have to use - d = dict(zip(t,(False,False,False))) Therefore, how do I build the tuple of Falses to reflect the length of my t tuple? Thanks for your help, Barry. Another variation: d = dict((x, False) for x in t) Cheers, Jussi -- http://mail.python.org/mailman/listinfo/python-list
Re: Python GUI + OpenGL
On Fri, 02 Mar 2007 18:30:34 +0100, Diez B. Roggisch [EMAIL PROTECTED] wrote: Achim Domma wrote: Hi, I'm developing a GUI app in Python/C++ to visualize numerical results. Currently I'm using Python 2.4 with wx and PyOpenGLContext, but there are no windows binaries for Python 2.5 for quite some time now. I need a OpenGL context without restrictions and some settings dialogs. Is wx + PyOpenGL the way to go? Or could somebody recommend a better set of tools/libs? PyQt, but then there is the licensing question of course. I'm facing a similar problem. Would you care to explain why PyQt is better in this particular case. I've used both PyQt and wx for 'normal' GUI programming (but I'm more familiar with wx) so I know about their difference in general. But why is PyQt better than wx for working with OpenGL? Dag -- http://mail.python.org/mailman/listinfo/python-list
Re: Return type of operator on inherited class
looping wrote: Hi, my question is on this example: class MyStr(str): def hello(self): print 'Hello !' s1 = MyStr('My string') s2 = MyStr('My second string') s1.hello() s2.hello() s = s1 + s2 s.hello() Hello ! Hello ! Traceback (most recent call last): File string, line 204, in run_nodebug File module1, line 13, in module AttributeError: 'str' object has no attribute 'hello' How could I get a type MyStr from the 'plus' (__add__) operation without overriding it in my class ? I need to override *every* operator I like to use ? You will not need to override if you s = MyStr(s1 + s2) James -- http://mail.python.org/mailman/listinfo/python-list
CherryPy + Database questions
Hello, I have more of a conceptual question about the way databases work, in a web framework, but I will be implementing things with CherryPy and SQLAlchemy. If you make a web form that adds rows to a database, and use sqlite as the engine, is there a danger of a race condition if several users at the same time try to submit the form? I want a unique row id, and make a unique identifier for the submissions. Am I in danger of having multiple submissions given the same identifier? I know that if I implemented things without a database, but used a flat file or something like it, I would have that possibility, when two processes try to read and update the file at the same time. If you want something more specific, I can throw some code together, but I wanted to get an answer before that because it will change the way I develop the code. thanks, Brian Blais -- - [EMAIL PROTECTED] http://web.bryant.edu/~bblais -- http://mail.python.org/mailman/listinfo/python-list
Re: CherryPy + Database questions
Brian Blais wrote: Hello, I have more of a conceptual question about the way databases work, in a web framework, but I will be implementing things with CherryPy and SQLAlchemy. If you make a web form that adds rows to a database, and use sqlite as the engine, is there a danger of a race condition if several users at the same time try to submit the form? I want a unique row id, and make a unique identifier for the submissions. Am I in danger of having multiple submissions given the same identifier? I know that if I implemented things without a database, but used a flat file or something like it, I would have that possibility, when two processes try to read and update the file at the same time. If you want something more specific, I can throw some code together, but I wanted to get an answer before that because it will change the way I develop the code. Usually, that is exactly what a RDBMS gives you. See the database connector module's threadsaftey property to see what exactly you can expect. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: implementing SFTP using Python
@Ben Finney I have downloaded paramiko-1.6 package, pcrypto 2.0.1 package platform: windows XP Now Iam trying to run the demo scripts available with paramiko package. I have tried using the same system for both cleint(demo_simple.py) and the server(demo_server.py) but it is failing at socket.connect() Can you please tell me ..what all i need to setup , to establish a conection between Client and server. The log of error , when I run demo_simple: == Hostname: 10.220.10.15:22 hostnmae: 10.220.10.15 port: 22 Username [KiranKumar_Kadarla]: aditya Warning: Problem with getpass. Passwords may be echoed. Password for [EMAIL PROTECTED]: [EMAIL PROTECTED] *** Unable to open host keys file hostname:10.220.10.15 port:22 *** Caught exception: class 'paramiko.AuthenticationException': Authentication failed. Traceback (most recent call last): File C:\paramiko-1.6\paramiko-1.6\demos\demo_simple.py, line 85, in module t.connect(username=username, password=password, hostkey=hostkey) File C:\Python25\Lib\site-packages\paramiko\transport.py, line 851, in connect self.auth_password(username, password) File C:\Python25\Lib\site-packages\paramiko\transport.py, line 1012, in auth_password return self.auth_handler.wait_for_response(my_event) File C:\Python25\Lib\site-packages\paramiko\auth_handler.py, line 174, in wait_for_response raise e AuthenticationException: Authentication failed. Traceback (most recent call last): File C:\paramiko-1.6\paramiko-1.6\demos\demo_simple.py, line 102, in module sys.exit(1) SystemExit: 1 THANKS IN ADVANCE K. KIRAN KUMAR kadarla kiran kumar writes: I have to implement SFTP conection from client to the server using Python script. Iam very new new to python , and i dont't have much time to complete this. So I need some pointers from you. You will probably want to investigate the paramiko package, a pure-Python implementation of the SSH2 protocol. - The fish are biting. Get more visitors on your site using Yahoo! Search Marketing.-- http://mail.python.org/mailman/listinfo/python-list
ANN: pyftpdlib 0.1 released
Hi all, I'm proud to announce the first beta release of pyftpdlib available at the following urls: home: http://billiejoex.altervista.org/pyftpdlib.html google code: http://code.google.com/p/pyftpdlib/ About = pyftpdlib is an high-level FTP server library based on asyncore/ asychat frameworks. pyftpdlib is actually the most complete RFC959 FTP server implementation available for Python language. Requirements == Python 2.2 or higher Bug reports / Contacts billiejoex [EMAIL PROTECTED] gmail (dot) com -- http://mail.python.org/mailman/listinfo/python-list
ANN: pyftpdlib 0.1 released
Hi all, I'm proud to announce the first beta release of pyftpdlib available at the following urls: home: http://billiejoex.altervista.org/pyftpdlib.html google code: http://code.google.com/p/pyftpdlib/ About = pyftpdlib is an high-level FTP server library based on asyncore/ asychat frameworks. pyftpdlib is actually the most complete RFC959 FTP server implementation available for Python language. Requirements == Python 2.2 or higher Bug reports / Contacts billiejoex -_[AT]_- gmail (dot) com -- http://mail.python.org/mailman/listinfo/python-list
ANN: pyftpdlib 0.1 released
Hi all, I'm proud to announce the first beta release of pyftpdlib available at the following urls: home: http://billiejoex.altervista.org/pyftpdlib.html google code: http://code.google.com/p/pyftpdlib/ About = pyftpdlib is an high-level FTP server library based on asyncore/ asychat frameworks. pyftpdlib is actually the most complete RFC959 FTP server implementation available for Python programming language. Requirements == Python 2.2 or higher Bug reports / Contacts billiejoex -_[AT]_- gmail (dot) com -- http://mail.python.org/mailman/listinfo/python-list
Re: Python stock market analysis tools?
On Mar 5, 12:41 am, Raymond Hettinger [EMAIL PROTECTED] wrote: On Mar 4, 7:52 pm, Mudcat [EMAIL PROTECTED] wrote: I have done a bit of searching and can't seem to find a stock market tool written in Python that is active. Anybody know of any? I'm trying not to re-create the wheel here. What kind of tool do you want? Getting quotes is the easy part: import urllib symbols = 'ibm jpm msft nok'.split() quotes = urllib.urlopen( 'http://finance.yahoo.com/d/quotes.csv?s='+ '+'.join(symbols) + 'f=l1e=.csv').read().split() print dict(zip(symbols, quotes)) The hard part is raising capital and deciding what to buy, sell, or hold. Yes, and a discussion of investment approaches would be off-topic. Unfortunately, newsgroups such as misc.invest.stocks are dominated by spam -- the moderated newsgroup misc.invest.financial-plan is better. Some research says that mean variance portfolio optimization can give good results. I discussed this in a message http://groups.google.com/group/misc.invest.financial-plan/msg/3b9d13f3d399050c?dmode=source Newsgroups: misc.invest.financial-plan From: [EMAIL PROTECTED] Date: Mon, 26 Feb 2007 12:47:25 -0600 Local: Mon, Feb 26 2007 1:47 pm Subject: Re: Portfolio Optimization Software? To implement this approach, a needed input is the covariance matrix of returns, which requires historical stock prices, which one can obtain using Python quote grabber http://www.openvest.org/Databases/ovpyq . For expected returns -- hmmm. One of the papers I cited found that assuming equal expected returns of all stocks can give reasonable results. Then one needs a quadratic programming solver, which appears to be handled by the CVXOPT Python package. If someone implements the approach in Python, I'd be happy to hear about it. There is a backtest package in R (open source stats package callable from Python) http://cran.r-project.org/src/contrib/Descriptions/backtest.html for exploring portfolio-based hypotheses about financial instruments (stocks, bonds, swaps, options, et cetera). -- http://mail.python.org/mailman/listinfo/python-list
Help Deciphering Code
Good Morning, I am learning python and I am having to make some changes on an existing python script. What happens is that one scripts creates an xml document that looks like this: CommitOperation file=IPM2.1/Identity/IdentityWebApp/Source/com/fisc/prioss/dataservice/ component/profile ProfileUtil.java message=PATCH_BRANCH: N/A BUG_NUMBER: N/A FEATURE_AFFECTED: N/A OVERVIEW: Changes for not including the product configuration account, idmconfig in searches. module=IPM2.1 The first attribute file as you can see shows the path where the file is and then a space and the actual file name. This is put into a variable named file. Then in the script, there is a method called that passes in this variable. The first line in the method called is this: reg = re.compile(r'[\\]+[ ]+') I'm not 100% sure what this is doing, but I believe it is trying to parse the file variable so that you only get the file name. It is weird because this had been working just fine until about 2 months ago then it just started not parsing anything. If anyone can help please help:-) Thanks, Bryan Leber Developer Fischer International Corporation www.fischerinternational.com http://www.fischerinternational.com [EMAIL PROTECTED] mailto:[EMAIL PROTECTED] Cell:(239)963-5267 Secure Your Risk. Increase Your Bottom Line. (tm) ** This mail message may contain confidential and privileged information from Fischer International which is protected. Any unauthorized review, use, disclosure or distribution by any means is prohibited. If you are not the intended recipient, please contact the sender by reply email and destroy all copies of the original message. ** -- http://mail.python.org/mailman/listinfo/python-list
Re: implementing SFTP using Python
kadarla kiran kumar [EMAIL PROTECTED] writes: Please don't top-post; instead, place your reply directly beneath the quoted text you're responding to, and remove any quoted lines that aren't relevant to your response. Now Iam trying to run the demo scripts available with paramiko package. You've gone further than me, then. Hopefully you can find help from someone more experienced with that package; perhaps it has its own support mailing list, or a developer contact email address. -- \ He who laughs last, thinks slowest. -- Anonymous | `\ | _o__) | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Re: ANN: pyftpdlib 0.1 released
billiejoex [EMAIL PROTECTED] wrote: Hi all, I'm proud to announce the first beta release of pyftpdlib available at the following urls: Announcing it once will do. Three times with minor edits is a bit much. -- http://mail.python.org/mailman/listinfo/python-list
Can Epydoc exclude wxPython?
I would like to use Epydoc (3.0beta1) to document my wxPython (2.6.10) application. The problem is that I can't seem to instruct Epydoc to not also generate partial documentation of wxPython, which makes too much verbiage for a user to wade through in order see the documentation of my program. For example, if my module consists of only the three lines import wx class BasicPanel(wx.Panel): pass the generated documentation for BasicPanel is completely swamped by the over 100 instance methods and static methods for wx._core.Window, etc. I've tried using the exclude command in a config file and command line and also sprinkling around @undocumented commands in the .py file. Neither of these make any difference as far as I can see, but they aren't documented well in Epydocs so I'm not completely sure that I'm using them correctly, although I've tried many, many variations all to no avail. I've also tried turning off introspection and/or parsing, but then the Epydoc output isn't as good. Does anyone know of a way to avoid this? Short of fixing this in Epydoc, how about a different documentation package -- I chose Epydoc because it included clickable inheritance trees in the docs. Is there another package that does this? I installed Epydoc using epydoc-3.0beta1.win32.exe on Windows XP and am using Python 2.4.3. Thanks for any help, Tom P.S. - I haven't found any other group or mailing list that might be a more focused forum for this question. Please let me know if you know of one. -- http://mail.python.org/mailman/listinfo/python-list
Re: ANN: pyftpdlib 0.1 released
On 5 Mar, 15:13, Duncan Booth [EMAIL PROTECTED] wrote: billiejoex [EMAIL PROTECTED] wrote: Hi all, I'm proud to announce the first beta release of pyftpdlib available at the following urls: Announcing it once will do. Three times with minor edits is a bit much. I'm sorry. I removed them by using google groups interface but maybe with no success. -- http://mail.python.org/mailman/listinfo/python-list
Re: Dictionary of Dictionaries
On Mar 5, 11:22 am, [EMAIL PROTECTED] wrote: messagesReceived = dict.fromkeys((one,two), {}) This creates two references to just *one* instance of empty dictionary. I'd do it like: messagesReceived = dict([(key, {}) for key in (one,two)]) -- http://mail.python.org/mailman/listinfo/python-list
Re: Descriptor/Decorator challenge
On 5 Mar, 07:31, Raymond Hettinger [EMAIL PROTECTED] wrote: I had an idea but no time to think it through. Perhaps the under-under name mangling trick can be replaced (in Py3.0) with a suitably designed decorator. Your challenge is to write the decorator. Any trick in the book (metaclasses, descriptors, etc) is fair game. I had some time this lunchtimes and I needed to calm my nerves so I took up your challenge :) Here is my poor effort. I'm sure lots of things are wrong with it but I'm not sure I'll look at it again. from types import MethodType, FunctionType # The suggested localmethod decorator class localmethod(object): def __init__(self, f): self.f = f self.defclass = None self.nextmethod = None def __get__(self, obj, objtype=None): callobj = obj or objtype if callobj.callerclass == self.defclass: return MethodType(self.f, obj, objtype) elif self.nextmethod: return self.nextmethod.__get__(obj, objtype) else: raise AttributeError class BoundMethod(object): def __init__(self, meth, callobj, callerclass): self.meth = meth self.callobj = callobj self.callerclass = callerclass def __call__(self, *args, **kwargs): callobj = self.callobj try: callobj.callerclass = self.callerclass return self.meth(*args, **kwargs) finally: callobj.callerclass = None # A 'mormal' method decorator is needed as well class method(object): def __init__(self, f): self.f = f self.defclass = None def __get__(self, obj, objtype=None): callobj = obj or objtype return BoundMethod(MethodType(self.f, obj, objtype), callobj, self.defclass) class Type(type): def __new__(self, name, bases, attrs): for attr, val in attrs.items(): if type(val) == FunctionType: attrs[attr] = method(val) return type.__new__(self, name, bases, attrs) def __init__(self, name, bases, attrs): for attr, val in attrs.iteritems(): if type(val) == localmethod: val.defclass = self for base in self.mro()[1:]: if attr in base.__dict__: nextmethod = base.__dict__[attr] val.nextmethod = nextmethod break elif type(val) == method: val.defclass = self class Object(object): __metaclass__ = Type # Note: any class or object has to have a callerclass attribute for this to work. # That makes it thread - incompatible I guess. callerclass = None # Here is your example code class A(Object): @localmethod def m(self): print 'A.m' def am(self): self.m() class B(A): @localmethod def m(self): print 'B.m' def bm(self): self.m() m = B() m.am() # prints 'A.m' m.bm() # prints 'B.m' # Untested beyond this particular example! -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list
Re: ANN: pyftpdlib 0.1 released
billiejoex [EMAIL PROTECTED] wrote: I removed them by using google groups interface but maybe with no success. You were probably successful in removing them from Google groups, but that is just one amongst many usenet servers. In general you cannot expect to delete messages from other servers. The best thing is to always make a point of reading a post carefully before hitting the send button, live with any minor typos, and post a correction as a followup if you need to correct any major mistakes. -- http://mail.python.org/mailman/listinfo/python-list
Re: Dictionary of Dictionaries
Bart Ogryczak [EMAIL PROTECTED] wrote: On Mar 5, 11:22 am, [EMAIL PROTECTED] wrote: messagesReceived = dict.fromkeys((one,two), {}) This creates two references to just *one* instance of empty dictionary. I'd do it like: messagesReceived = dict([(key, {}) for key in (one,two)]) Alternatively use a defaultdict (Python 2.5) and you don't need to know the keys in advance: from collections import defaultdict messagesReceived = defaultdict(dict) messagesReceived['one']['123'] = 1 messagesReceived['two']['121'] = 2 messagesReceived['two']['124'] = 4 messagesReceived defaultdict(type 'dict', {'two': {'121': 2, '124': 4}, 'one': {'123': 1}}) -- http://mail.python.org/mailman/listinfo/python-list
Re: Why does SocketServer default allow_reuse_address = false?
Joshua J. Kugler wrote: Considering that UNIX Network Programming, Vol 1 (by W. Richard Stevens) recommends _All_ TCP servers should specify [SO_REUSEADDR] to allow the server to be restarted [if there are clients connected], and that self.allow_reuse_address = False makes restarting a server a pain if there were connected clients, why does SocketServer default allow_reuse_address to False? It's kind of bemusing to subclass ThreadingTCPServer just to change one variable that arguably should have been True in the first place. Is there some history to this of which I'm not aware? Is there a good reason for it to default to false? If any, don't know. Searched in already reported bugs to check if somebody already noticed. If not, please consider to open a bug. Regards, -- . Facundo . Blog: http://www.taniquetil.com.ar/plog/ PyAr: http://www.python.org/ar/ -- http://mail.python.org/mailman/listinfo/python-list
Re: writing a file:newbie question
kavitha thankaian wrote: say for example,,i have a file test.txt and the file has the list a,b,c,d, i would like to delete the trailing comma at the end,,, a,b,c,d,.rstrip(,) 'a,b,c,d' Regards, -- . Facundo . Blog: http://www.taniquetil.com.ar/plog/ PyAr: http://www.python.org/ar/ -- http://mail.python.org/mailman/listinfo/python-list
Re: how to convert an integer to a float?
[EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Hi, I have the following functions, but ' dx = abs(i2 - i1)/min(i2, i1)' always return 0, can you please tell me how can i convert it from an integer to float? I don't think that's what you really want to do. What you really want is for dx to be a float rather than being truncated to an integer. Division is going to behave that way in the future, so if you want it to behave that way now, you can write from __future__ import division at the beginning of your program. If for some reason you don't want to rely on using a version of Python that knows about this future behavior, you might consider dx = float(abs(i2 - i1))/min(i2, i1) as an alternative. -- http://mail.python.org/mailman/listinfo/python-list
Re: timeout in urllib.open()
Stefan Palme wrote: is there a way to modify the time a call of urllib.open(...) waits for an answer from the other side? Have a tool I'm working on adding a socket_timeout parametero to urllib2.urlopen. Regards, -- . Facundo . Blog: http://www.taniquetil.com.ar/plog/ PyAr: http://www.python.org/ar/ -- http://mail.python.org/mailman/listinfo/python-list
Re: threading a thread
tubby wrote: I have a program written in Python that checks a class B network (65536 hosts) for web servers. It does a simple TCP socket connect to port 80 and times out after a certain periods of time. The program is threaded and can do all of the hosts in about 15 minutes or so. I'd like to make it so that I can check for other open ports (instead of just port 80) and I'd like to thread the port checks as well. So far, I understand that you have a program with multithreading, but it only threads the host checking (because it actually scans one port only). Right now I'm just prototyping and the threaded hosts portion works very well for my needs. I'd just like to add a threaded ports check and wanted to know if anyone had done something similar in Python. What I do *not* understand if this is a question about: - port checking (asume not, because the program already checks a port, so you can actually see how it's done) - threading (asume not, because the program already is multithreading, so you can actually see how it's done) - modifying your program (asume not, you did not copy it here). So, for us be able to help you, what can not you do? Regards, -- . Facundo . Blog: http://www.taniquetil.com.ar/plog/ PyAr: http://www.python.org/ar/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Project organization and import
On Mar 5, 12:45 am, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote: Remember that you can put code in the __init__.py of a package, and that this code can import sub- packages/modules namespaces, making the package internal organisation transparent to user code Sure, but that doesn't solve the problem. Say you have a package widgets with classes ScrollBar, Form, etc. You want the end user to import widgets and then invoke widgets.ScrollBar(). As far as I know there are only two ways to do this, both seriously flawed: 1) Put all your code in one module widgets.py, 2) use from scrollbar import * in widgets/__init__.py, which is semi-deprecated and breaks reload(). Also remember that you can import as, ie: import some_package.some_subpackage.some_module as some_module Sure but that doesn't eliminate the unfortunate interaction between Python class organization and filesystem heirarchy. For example, say you want to organize the widgets package as follows: widgets/scrollbar/*.py widgets/form/*.py widgets/common/util.py Other than messing around with PYTHONPATH, which is horrible, I don't see how to import util.py from the widget code. Bad form IMHO. Packages and module names should be all_lower, classnames CamelCased. You're still stuck doing foo.Foo() everywhere in your client code, which is ugly and wastes space, or using from foo import * which is broken. but I believe this is categorically the wrong thing to do in large projects. Oh yes ? Why ? For myriad reasons, just one of them being the one I stated -- smaller files with one functional unit each are more amenable to source code management with multiple developers. We could discuss this till we're blue in the face but it's beside the point. For any given project, architecture, and workflow, the developers are going to have a preference for how to organize the code structurally into files, directories, packages, etc. The language itself should not place constraints on them. The mere fact that it is supposedly Pythonic to put more functionality in one file indicates to me that the Python package system is obstructing some of its users who have perfectly good reasons to organize their code differently. you're going to want files to contain the smallest practical functional blocks. I feel pretty confident saying that put more stuff in one file is the wrong answer, even if it is the Pythonic answer. Is this actually based on working experience ? It seems that there are enough not-trivial Python projects around to prove that it works just fine. Yes. I've worked extensively on several projects in several languages with multi-million lines of code and they invariably have coding styles that recommend one functional unit (such as a class), or at most a few closely related functional units per file. In Python, most of the large projects I've looked at use from foo import * liberally. I guess my question boils down to this. Is from foo import * really deprecated or not? If everyone has to use from foo import * despite the problems it causes, how do they work around those problems (such as reloading)? Martin -- http://mail.python.org/mailman/listinfo/python-list
Re: Python GUI + OpenGL
You don't necessarily need an OpenGL wrapper like PyOpenGL. If you only use a handful of OpenGL functions, it would be relatively straight-forward to make your own, using ctypes. Here is what it would look like: from ctypes import cdll, windll, c_double, c_float, c_int GL_POINTS = 0x GL_LINES = 0x0001 GL_LINE_LOOP = 0x0002 GL_LINE_STRIP = 0x0003 GL_TRIANGLES = 0x0004 GL_TRIANGLE_STRIP = 0x0005 GL_TRIANGLE_FAN = 0x0006 GL_QUADS = 0x0007 GL_QUAD_STRIP = 0x0008 GL_POLYGON= 0x0009 gl = windll.LoadLibrary(opengl32) glEnd = gl.glEnd glEnd.restype = None glBegin = gl.glBegin glBegin.argtypes = [c_int] glBegin.restype = None glVertex2f = gl.glVertex2d glVertex2f.argtypes = [c_double, c_double] glVertex2f.restype = None glColor3f = gl.glColor3d glColor3f.argtypes = [c_double, c_double, c_double] glColor3f.restype = None glClear = gl.glClear glClear.argtypes = [c_int] glClear.restype = None glClearColor = gl.glClearColor glClearColor.argtypes = [c_double, c_double, c_double, c_double] glClearColor.restype = None glViewport = gl.glViewport glViewport.argtypes = [c_int, c_int, c_int, c_int] glViewport.restype = None [...etc] Regards, Laurent On Mar 2, 4:17 pm, Achim Domma [EMAIL PROTECTED] wrote: Hi, I'm developing a GUI app in Python/C++ to visualize numerical results. Currently I'm using Python 2.4 with wx and PyOpenGLContext, but there are no windows binaries for Python 2.5 for quite some time now. I need a OpenGL context without restrictions and some settings dialogs. Is wx + PyOpenGL the way to go? Or could somebody recommend a better set of tools/libs? regards, Achim -- http://mail.python.org/mailman/listinfo/python-list
Re: Project organization and import
Jorge, thanks for your response. I replied earlier but I think my response got lost. I'm trying again. On Mar 4, 5:20 pm, Jorge Godoy [EMAIL PROTECTED] wrote: Why? RCS systems can merge changes. A RCS system is not a substitute for design or programmers communication. Text merges are an error-prone process. They can't be eliminated but they are best avoided when possible. When refactoring, it's much better to move small files around than to move chunks of code between large files. In the former case your SCM system can track integration history, which is a big win. Unit tests help being sure that one change doesn't break the project as a whole and for a big project you're surely going to have a lot of those tests. But unit tests are never an excuse for error prone workflow. Oh, don't worry, we'll catch that with unit tests is never something you want to say or hear. I don't reload... When my investigative tests gets bigger I write a script and run it with the interpreter. It is easy since my text editor can call Python on a buffer (I use Emacs). That's interesting, is this workflow pretty universal in the Python world? I guess that seems unfortunate to me, one of the big wins for interpreted languages is to make the development cycle as short and interactive as possible. As I see it, the Python way should be to reload a file and reinvoke the class directly, not to restart the interpreter, load an entire package and then run a test script to set up your test conditions again. Martin -- http://mail.python.org/mailman/listinfo/python-list
Re: Python GUI + OpenGL
Dag wrote: On Fri, 02 Mar 2007 18:30:34 +0100, Diez B. Roggisch [EMAIL PROTECTED] wrote: Achim Domma wrote: Hi, I'm developing a GUI app in Python/C++ to visualize numerical results. Currently I'm using Python 2.4 with wx and PyOpenGLContext, but there are no windows binaries for Python 2.5 for quite some time now. I need a OpenGL context without restrictions and some settings dialogs. Is wx + PyOpenGL the way to go? Or could somebody recommend a better set of tools/libs? PyQt, but then there is the licensing question of course. I'm facing a similar problem. Would you care to explain why PyQt is better in this particular case. I've used both PyQt and wx for 'normal' GUI programming (but I'm more familiar with wx) so I know about their difference in general. But why is PyQt better than wx for working with OpenGL? I didn't say so. I just pointed out an alternative, as the OP had issues with obtaining binary packages for wx + py2.5 Beside that, I do love the Qt library and would always use it in preference to wx, but this is a general thing and by no means tied to the OpenGL-programming. After all, that actually is done using PyOpenGL Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: MS SQL Database connection
On Mar 5, 4:44 am, Tim Golden [EMAIL PROTECTED] wrote: Hitesh wrote: Hi currently I am using DNS and ODBC to connect to MS SQL database. Is there any other non-dns way to connect? If I want to run my script from different server I first have to create the DNS in win2k3. Here are several ways to connect to an MSSQL database w/o having to create DNS or anything else in win2k3 ;) There are other ways (the slightly stale MSSQL module from Object Craft, for example, which still works fine for Python = 2.3). TJG code def adodbapi_connection (server, database, username, password): # #http://adodbapi.sf.net # import adodbapi connectors = [Provider=SQLOLEDB] connectors.append (Data Source=%s % server) connectors.append (Initial Catalog=%s % database) if username: connectors.append (User Id=%s % username) connectors.append (Password=%s % password) else: connectors.append(Integrated Security=SSPI) return adodbapi.connect (;.join (connectors)) def pymssql_connection (server, database, username, password): # #http://pymssql.sf.net # import pymssql if not username: raise RuntimeError, Unable to use NT authentication for pymssql return pymssql.connect (user=username, password=password, host=server, database=database) def pyodbc_connection (server, database, username, password): # #http://pyodbc.sf.net # import pyodbc connectors = [Driver={SQL Server}] connectors.append (Server=%s % server) connectors.append (Database=%s % database) if username: connectors.append (UID=%s % username) connectors.append (PWD=%s % password) else: connectors.append (TrustedConnection=Yes) return pyodbc.connect (;.join (connectors)) /code Thank you. And I yes I meant DSN not DNS (my mistake, thank you for catching it ;) hj -- http://mail.python.org/mailman/listinfo/python-list
worker thread catching exceptions and putting them in queue
All, in a worker thread setup that communicates via queues is it possible to catch exceptions raised by the worker executed, put them in an object and send them over the queue to another thread where the exception is raised in that scope? considering that an exception is an object I feel it ought to be possible, however I do not see how to go about it. does anyone have a pointer towards the solution? Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: worker thread catching exceptions and putting them in queue
Paul Sijben wrote: All, in a worker thread setup that communicates via queues is it possible to catch exceptions raised by the worker executed, put them in an object and send them over the queue to another thread where the exception is raised in that scope? considering that an exception is an object I feel it ought to be possible, however I do not see how to go about it. does anyone have a pointer towards the solution? Just raise the exception object found in the queue. Only make sure it _is_ an exception, as you can raise everything. So in your queue-putting-code you might consider discriminating between the two cases, like this: while True: try: result = 1, work() except: result = 2, sys.exc_info()[1] queue.put(result) --- while True: kind, result = queue.get() if kind == 1: do(result) elif kind == 2: raise result Diez -- 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
Re: worker thread catching exceptions and putting them in queue
Paul Sijben schrieb: All, in a worker thread setup that communicates via queues is it possible to catch exceptions raised by the worker executed, put them in an object and send them over the queue to another thread where the exception is raised in that scope? considering that an exception is an object I feel it ought to be possible, however I do not see how to go about it. does anyone have a pointer towards the solution? Paul You're right, even exceptions are objects in Python. For further studies, read http://docs.python.org/lib/module-exceptions.html You can catch an exception like this: try: worker.do_some_work_that_may_raise_an_exception() except Exception, e: # the first argument is the type of error you want to handle # it is Exception here, the baseclass of all computation exceptions # the second argument is the variable (name) where you want to save # the specific exception raised to # it's 'e' here, a common shortcut for exception exception_handler.handle(e) # notice that you can pass e around as you like For further information on exceptions and how to handle them, read chapter 8 of the tutorial, especially starting from 8.3: http://docs.python.org/tut/node10.html#SECTION001030 P.S. I don't know if what I told still applies to Python 3.0 -- a lot of changes are upcoming related to exception raising and handling. -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie question
Tommy Grav schrieb: 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 For this case, there are list comprehensions (or map, but you shouldn't use it any longer): a = 0.3434 0.5322 0.3345 b = a.split() map(float, b) [0.34338, 0.53221, 0.33452] [float(x) for x in b] [0.34338, 0.53221, 0.33452] I think it should be easy to apply this to your example above. Stargaming -- http://mail.python.org/mailman/listinfo/python-list
Re: Project organization and import
On 5 Mar 2007 08:32:34 -0800, Martin Unsal [EMAIL PROTECTED] wrote: Jorge, thanks for your response. I replied earlier but I think my response got lost. I'm trying again. On Mar 4, 5:20 pm, Jorge Godoy [EMAIL PROTECTED] wrote: Why? RCS systems can merge changes. A RCS system is not a substitute for design or programmers communication. Text merges are an error-prone process. They can't be eliminated but they are best avoided when possible. When refactoring, it's much better to move small files around than to move chunks of code between large files. In the former case your SCM system can track integration history, which is a big win. Unit tests help being sure that one change doesn't break the project as a whole and for a big project you're surely going to have a lot of those tests. But unit tests are never an excuse for error prone workflow. Oh, don't worry, we'll catch that with unit tests is never something you want to say or hear. That's actually the exact benefit of unit testing, but I don't feel that you've actually made a case that this workflow is error prone. You often have multiple developers working on the same parts of the same module? I don't reload... When my investigative tests gets bigger I write a script and run it with the interpreter. It is easy since my text editor can call Python on a buffer (I use Emacs). That's interesting, is this workflow pretty universal in the Python world? I guess that seems unfortunate to me, one of the big wins for interpreted languages is to make the development cycle as short and interactive as possible. As I see it, the Python way should be to reload a file and reinvoke the class directly, not to restart the interpreter, load an entire package and then run a test script to set up your test conditions again. If you don't do this, you aren't really testing your changes, you're testing your reload() machinery. You seem to have a lot of views about what the Python way should be and those are at odds with the actual way people work with Python. I'm not (necessarily) saying you're wrong, but you seem to be coming at this from a confrontational standpoint. Your claim, for example, that the language shouldn't place constraints on how you manage your modules is questionable. I think it's more likely that you've developed a workflow based around the constraints (and abilities) of other languages and you're now expecting Python to conform to that instead of its own. I've copied some of your responses from your earlier post below: Yes. I've worked extensively on several projects in several languages with multi-million lines of code and they invariably have coding styles that recommend one functional unit (such as a class), or at most a few closely related functional units per file. I wonder if you've ever asked yourself why this is the case. I know from my own experience why it's done in traditional C++/C environments - it's because compiling is slow and breaking things into as many files (with as few interdependencies) as possible speeds up the compilation process. Absent this need (which doesn't exist in Python), what benefit is there to separating out related functionality into multiple files? Don't split them up just because you've done so in the past - know why you did it in the past and if those conditions still apply. Don't split them up until it makes sense for *this* project, not the one you did last year or 10 years ago. I guess my question boils down to this. Is from foo import * really deprecated or not? If everyone has to use from foo import * despite the problems it causes, how do they work around those problems (such as reloading)? from foo import * is a bad idea at a top level because it pollutes your local namespace. In a package __init__, which exists expressly for the purpose of exposing it's interior namespaces as a single flat one, it makes perfect sense. In some cases you don't want to export everything, which is when __all__ starts to make sense. Clients of a package (or a module) shouldn't use from foo import * without a good reason. Nobody I know uses reload() for anything more than trivial as you work testing in the interpreter. It's not reliable or recommended for anything other than that. It's not hard to restart a shell, especially if you use ipython (which can save and re-create a session) or a script thats set up to create your testing environment. This is still a much faster way than compiling any but the most trivial of C/C++ modules. In fact, on my system startup time for the interpreter is roughly the same as the startup time of my compiler (that is to say, the amount of time it takes deciding what its going to compile, without actually compiling anything). You're still stuck doing foo.Foo() everywhere in your client code, which is ugly and wastes space, or using from foo import * which is broken. If you don't like working with explicit namespaces, you've probably chosen the
Re: Python GUI + OpenGL
On 3/5/07, Diez B. Roggisch [EMAIL PROTECTED] wrote: Dag wrote: On Fri, 02 Mar 2007 18:30:34 +0100, Diez B. Roggisch [EMAIL PROTECTED] wrote: Achim Domma wrote: Hi, I'm developing a GUI app in Python/C++ to visualize numerical results. Currently I'm using Python 2.4 with wx and PyOpenGLContext, but there are no windows binaries for Python 2.5 for quite some time now. I need a OpenGL context without restrictions and some settings dialogs. Is wx + PyOpenGL the way to go? Or could somebody recommend a better set of tools/libs? PyQt, but then there is the licensing question of course. I'm facing a similar problem. Would you care to explain why PyQt is better in this particular case. I've used both PyQt and wx for 'normal' GUI programming (but I'm more familiar with wx) so I know about their difference in general. But why is PyQt better than wx for working with OpenGL? I didn't say so. I just pointed out an alternative, as the OP had issues with obtaining binary packages for wx + py2.5 I believe he was having trouble with binary packages for PyOpenGL, wxPython has 2.5 binaries and has since it was released. That said, it's my understanding that the most recent version of PyOpenGL uses ctypes and no longer requires a windows binary, which is why they are not provided. Also, if you're writing a C++/Python app on Windows then you must have the correct environment to build Python extensions, so even if my understanding is incorrect, you should be able to build PyOpenGL via distutils with minimal if any trouble. Beside that, I do love the Qt library and would always use it in preference to wx, but this is a general thing and by no means tied to the OpenGL-programming. After all, that actually is done using PyOpenGL wx and Qt support OpenGL in essentially the same manner. I believe he took from your earlier post that Qt had its own built in OpenGL wrapper (and thus didn't rely on PyOpenGL) but to my knowledge that is not correct. Diez -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: How use XML parsing tools on this one specific URL?
[EMAIL PROTECTED] schrieb: I understand that the web is full of ill-formed XHTML web pages but this is Microsoft: http://moneycentral.msn.com/companyreport?Symbol=BBBY I can't validate it and xml.minidom.dom.parseString won't work on it. Interestingly, no-one mentioned lxml so far: http://codespeak.net/lxml http://codespeak.net/lxml/dev/parsing.html#parsers Parse it as HTML and then use anything from XPath to XSLT to treat it. Have fun, Stefan -- http://mail.python.org/mailman/listinfo/python-list
Re: Python stock market analysis tools?
What kind of tool do you want? Getting quotes is the easy part: import urllib symbols = 'ibm jpm msft nok'.split() quotes = urllib.urlopen( 'http://finance.yahoo.com/d/quotes.csv?s='+ '+'.join(symbols) + 'f=l1e=.csv').read().split() print dict(zip(symbols, quotes)) The hard part is raising capital and deciding what to buy, sell, or hold. Raymond Yeah, I have something that pulls quotes. So the data isn't hard to get, but I'm not really interested in building the graphs. I was hoping to find something already built with the common indicators already built in that I could add my own to. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python stock market analysis tools?
On Mar 5, 7:55 am, Beliavsky [EMAIL PROTECTED] wrote: Yes, and a discussion of investment approaches would be off-topic. Unfortunately, newsgroups such as misc.invest.stocks are dominated by spam -- the moderated newsgroup misc.invest.financial-plan is better. Some research says that mean variance portfolio optimization can give good results. I discussed this in a message I actually checked out some of those newsgroups in trying to find a tool to use. I think I even posted a question about it. But you're right in that there's so much spam, and all of the responses I got were people trying to hock their own wares. Didn't find much in the way of useful information. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python object to xml biding
raf wrote: I'm looking for a python to XSD/xml biding library to easy handling this very large protocol spec I need to tackle. I've searched google quite extensibly and I haven't found anything that properly fits the bill... I'm mostly interested at the xml - python and python-xml marshalling/unmarshalling much like jaxb for java. Consider using lxml.objectify. It's extremely powerful and simple to use at the same time. http://codespeak.net/lxml/dev/objectify.html#element-access-through-object-attributes http://codespeak.net/lxml/ Have fun, Stefan -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie question
Tommy Grav wrote: 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 Using a list comprehension you would write this as: for line in lines: xin, yin, zin=[float(x) for x in line.split()] This if course expects your data to be perfect. If you want error handling (e.g. less or more than 3 values, values that cause exception when passed to float, etc.) you will have to handle that differently. -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: list-like behaviour of etree.Element
On Mar 5, 1:00 am, Fredrik Lundh [EMAIL PROTECTED] wrote: Raymond Hettinger wrote: On Mar 4, 12:48 pm, Daniel Nogradi [EMAIL PROTECTED] wrote: The etree.Element (or ElementTree.Element) supports a number of list-like methods: append, insert, remove. Any special reason why it doesn't support pop and extend (and maybe count)? Those methods would not be hard to add. Perhaps, submit a feature request to Fredrik Lundh on SourceForge and see what he thinks there is merit in more closely emulating the list API. Of the methods you listed, the case is probably strongest for extend(). extend() will be in the next release: http://effbot.org/zone/elementtree-changes-13.htm (lxml.etree already has it, btw). not sure I see the point of pop() and count(). a successful feature request would need to include some really compelling use cases. /F Pop could be useful. I could use it. I'm working on a story and submission tracker. It stores everything in XML and I use a sax parser to build reports. If I have to update one bit of data (say, a submission returns a sale) I have to use a nasty extraction program that returns the submission node AND the rest of the document (minus that node). Then I make the changes of the individual submission, and append it to the end of submissions data document. (I don't care about the order of items in the file, since my reporting methods re-order everything anyway.) Josh -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie question
On Mar 5, 9:03 am, Stargaming [EMAIL PROTECTED] wrote: Tommy Grav schrieb: For this case, there are list comprehensions (or map, but you shouldn't use it any longer): I didn't see anything in the docs about this. Is map going away or is it considered un-Pythonic now? Josh -- http://mail.python.org/mailman/listinfo/python-list
Re: Mod python - mysql lock
If you use MySQL 5, you get atomic transactions. The old LOCK thing is becoming obsolete. Suggest getting a newer MySQL and a newer MySQL book. John Nagle Jan Danielsson wrote: Roopesh wrote: In my mod_python project I am using mysql as the database. There is table card in which unique cards are stored. When a user request comes he has to get a unique card. In this situation I want to use LOCK with which I can prevent other users accessing the table. I tried excuting LOCK command of mysql through python code, but it is not locking the database. Any ideas why this isn't working and how can I do the same. //python code sql = LOCK TABLES card WRITE cursor.execute(sql) -- http://mail.python.org/mailman/listinfo/python-list
Re: Howto pass exceptions between threads
Alexander Eisenhuth wrote: Hallo Alltogether, I've searched in this mailing list, but it seems to me that there is no general approach to pass exceptions from one thread to another. Very few languages have that. Actually, it could be made to work for Python, but it would have to be carefully designed. Something that raises an exception in another thread the next time the thread blocks would have relatively sane semantics. You couldn't raise an exception on a compute-bound thread, only at block points (locks, I/O, long system calls.) John Nagle -- http://mail.python.org/mailman/listinfo/python-list
Re: Help Deciphering Code
Bryan Leber [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] I am learning python and I am having to make some changes on an existing python script. What happens is that one scripts creates an xml document that looks like this: CommitOperation file=IPM2.1/Identity/IdentityWebApp/Source/com/fisc/prioss/dataservice/ component/profile ProfileUtil.java message=PATCH_BRANCH: N/A BUG_NUMBER: N/A FEATURE_AFFECTED: N/A OVERVIEW: Changes for not including the product configuration account, idmconfig in searches. module=IPM2.1 The first attribute file as you can see shows the path where the file is and then a space and the actual file name. This is put into a variable named file. Then in the script, there is a method called that passes in this variable. The first line in the method called is this: reg = re.compile(r'[\\]+[ ]+') I'm not 100% sure what this is doing, but I believe it is trying to parse the file variable so that you only get the file name. It is weird because this had been working just fine until about 2 months ago then it just started not parsing anything. If anyone can help please help:-) == I have no idea what changed, but splitting the file var into its two components is trivial: IPM2.1/Identity/IdentityWebApp/Source/com/fisc/prioss/dataservice/component/profile ProfileUtil.java.split() ['IPM2.1/Identity/IdentityWebApp/Source/com/fisc/prioss/dataservice/component/profile', 'ProfileUtil.java'] If the ' ' were a '/' instead, then the os.path module has a function for splitting off the last component, the file name. Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: Project organization and import
On Mar 5, 9:15 am, Chris Mellon [EMAIL PROTECTED] wrote: That's actually the exact benefit of unit testing, but I don't feel that you've actually made a case that this workflow is error prone. You often have multiple developers working on the same parts of the same module? Protecting your head is the exact benefit of bike helmets, that doesn't mean you should bike more more recklessly just because you're wearing a helmet. :) Doing text merges is more error prone than not doing them. :) There are myriad other benefits of breaking up large files into functional units. Integration history, refactoring, reuse, as I mentioned. Better clarity of design. Easier communication and coordination within a team. What's the down side? What's the advantage of big files with many functional units? If you don't do this, you aren't really testing your changes, you're testing your reload() machinery. Only because reload() is hard in Python! ;) You seem to have a lot of views about what the Python way should be and those are at odds with the actual way people work with Python. I'm not (necessarily) saying you're wrong, but you seem to be coming at this from a confrontational standpoint. When I refer to Pythonic all I'm talking about is what I've read here and observed in other people's code. I'm here looking for more information about how other people work, to see if there are good solutions to the problems I see. However when I talk about what I think is wrong with the Pythonic way, obviously that's just my opinion formed by my own experience. Your claim, for example, that the language shouldn't place constraints on how you manage your modules is questionable. I think it's more likely that you've developed a workflow based around the constraints (and abilities) of other languages and you're now expecting Python to conform to that instead of its own. I don't think so; I'm observing things that are common to several projects in several languages. I wonder if you've ever asked yourself why this is the case. I know from my own experience why it's done in traditional C++/C environments - it's because compiling is slow and breaking things into as many files (with as few interdependencies) as possible speeds up the compilation process. I don't think that's actually true. Fewer, bigger compilation units actually compile faster in C, at least in my experience. Absent this need (which doesn't exist in Python), Python still takes time to load precompile. That time is becoming significant for me even in a modest sized project; I imagine it would be pretty awful in a multimillion line project. No matter how fast it is, I'd rather reload one module than exit my interpreter and reload the entire world. This is not a problem for Python as scripting language. This is a real problem for Python as world class application development language. In a package __init__, which exists expressly for the purpose of exposing it's interior namespaces as a single flat one, it makes perfect sense. OK! That's good info, thanks. Nobody I know uses reload() for anything more than trivial as you work testing in the interpreter. It's not reliable or recommended for anything other than that. That too... although I think that's unfortunate. If reload() were reliable, would you use it? Do you think it's inherently unreliable, that is, it couldn't be fixed without fundamentally breaking the Python language core? This is still a much faster way than compiling any but the most trivial of C/C++ modules. I'm with you there! I love Python and I'd never go back to C/C++. That doesn't change my opinion that Python's import mechanism is an impediment to developing large projects in the language. If you don't like working with explicit namespaces, you've probably chosen the wrong language. I never said that. I like foo.Bar(), I just don't like typing foo.Foo() and bar.Bar(), which is a waste of space; syntax without semantics. I propose that the technique most amenable to source code management is for a single file (or RCS level module, if you have a locking RCS) to have everything that it makes sense to edit or change for a specific feature. Oh, I agree completely. I think we're using the exact same criterion. A class is a self-contained feature with a well defined interface, just what you'd want to put in it's own file. (Obviously there are trivial classes which don't implement features, and they don't need their own files.) You're also placing far too much emphasis on reload. Focus yourself on unit tests and environment scripts instead. These are more reliable and easier to validate than reload() in a shell. I think this is the crux of my frustration. I think reload() is unreliable and hard to validate because Python's package management is broken. I appreciate your suggestion of alternatives and I think I need to come to terms with the fact that reload() is just broken. That doesn't mean it has to be
New to Python
I am trying to get a program to add up input from the user to get to the number 100 using a loop. However, I am having some issues. Here is what I have so far. I know I am just trying to hard, but I am stuck. Thank you for any help. print We need to count to 100 high_number = 100 total = 0 number = input(Enter your first number ) sum = number + total while sum high_number: print Not there yet... number = input(Enter another number ) print We are there!!! -- http://mail.python.org/mailman/listinfo/python-list
Re: FloatCanvas in a wxpython application.... layout problems
On Feb 21, 1:40 pm, nelson - [EMAIL PROTECTED] wrote: Hi all, i'm developing an application that uses Floatcanvas to diplay a cartesian plane. how can i embed it into a complex layout? Your best bet is either the floatcanvas list: http://mail.mithis.com/cgi-bin/mailman/listinfo/floatcanvas or the wxPython-users list: http://www.wxpython.org/maillist.php In this case, putting a FloatCanvas in an app is no different than putting any wx.Panel in, so the wxPython list would be fine. -Chris -- http://mail.python.org/mailman/listinfo/python-list
Re: New to Python
[EMAIL PROTECTED] schrieb: I am trying to get a program to add up input from the user to get to the number 100 using a loop. However, I am having some issues. Here is what I have so far. I know I am just trying to hard, but I am stuck. Thank you for any help. print We need to count to 100 high_number = 100 total = 0 number = input(Enter your first number ) sum = number + total while sum high_number: print Not there yet... number = input(Enter another number ) print We are there!!! Just reading the error messages would be a good start. You assign `sum` to `number + total` but as I see it there's no `number` so far. You have to increment some variable with the user's input. (`sum += input(..)`) Additionally, `total` and `number` seem pretty redundant. You only need two variables, one containing the targeted number, one the current progress. By the way, input() is considered pretty evil because the user can enter arbitrary expressions. It is recommended to use raw_input() (till Python 3.0), in your case e. g. int(raw_input()) wrapped in a try-except block. HTH, Stargaming -- http://mail.python.org/mailman/listinfo/python-list
Re: New to Python
[EMAIL PROTECTED] wrote: I am trying to get a program to add up input from the user to get to the number 100 using a loop. However, I am having some issues. Please, if you have a problem post the exact error symptoms. Here is what I have so far. I know I am just trying to hard, but I am stuck. Thank you for any help. We can't tell by magic where you are stuck. Please state observed and expected behaviour. print We need to count to 100 high_number = 100 total = 0 number = input(Enter your first number ) (already mentioned: please don't use input) sum = number + total This is a one-time assignment. while sum high_number: print Not there yet... number = input(Enter another number ) print We are there!!! We won't reach this point since the while condition never becomes False. See above; sum is assigned just one time and will not change in your while loop. Having the program work as probably expected requires a sum += number inside the while loop. BTW, what's total expected to do? It's also assigned only one time. Regards, Björn -- BOFH excuse #150: Arcserve crashed the server again. -- http://mail.python.org/mailman/listinfo/python-list
Re: Descriptor/Decorator challenge
On 5 Mar, 14:38, Arnaud Delobelle [EMAIL PROTECTED] wrote: On 5 Mar, 07:31, Raymond Hettinger [EMAIL PROTECTED] wrote: I had an idea but no time to think it through. Perhaps the under-under name mangling trick can be replaced (in Py3.0) with a suitably designed decorator. Your challenge is to write the decorator. Any trick in the book (metaclasses, descriptors, etc) is fair game. I had some time this lunchtimes and I needed to calm my nerves so I took up your challenge :) Here is my poor effort. I'm sure lots of things are wrong with it but I'm not sure I'll look at it again. Well in fact I couldn't help but try to improve it a bit. Objects now don't need a callerclass attribute, instead all necessary info is stored in a global __callerclass__. Bits that didn't work now do. So here is my final attempt, promised. The awkward bits are: * how to find out where a method is called from * how to resume method resolution once it has been established a local method has to be bypassed, as I don't know how to interfere directly with mro. Feedback of any form is welcome (though I prefer when it's polite :) from types import MethodType, FunctionType class IdDict(object): def __init__(self): self.objects = {} def __getitem__(self, obj): return self.objects.get(id(obj), None) def __setitem__(self, obj, callerclass): self.objects[id(obj)] = callerclass def __delitem__(self, obj): del self.objects[id(obj)] # This stores the information about from what class an object is calling a method # It is decoupled from the object, better than previous version # Maybe that makes it easier to use with threads? __callerclass__ = IdDict() # The purpose of this class is to update __callerclass__ just before and after a method is called class BoundMethod(object): def __init__(self, meth, callobj, callerclass): self.values = meth, callobj, callerclass def __call__(self, *args, **kwargs): meth, callobj, callerclass = self.values if callobj is None and args: callobj = args[0] try: __callerclass__[callobj] = callerclass return meth(*args, **kwargs) finally: del __callerclass__[callobj] # A 'normal' method decorator is needed as well class method(object): def __init__(self, f): self.f = f def __get__(self, obj, objtype=None): return BoundMethod(MethodType(self.f, obj, objtype), obj, self.defclass) class LocalMethodError(AttributeError): pass # The suggested localmethod decorator class localmethod(method): def __get__(self, obj, objtype=None): callobj = obj or objtype defclass = self.defclass if __callerclass__[callobj] is defclass: return MethodType(self.f, obj, objtype) else: # The caller method is from a different class, so look for the next candidate. mro = iter((obj and type(obj) or objtype).mro()) for c in mro: # Skip all classes up to the localmethod's class if c == defclass: break name = self.name for base in mro: if name in base.__dict__: try: return base.__dict__[name].__get__(obj, objtype) except LocalMethodError: continue raise LocalMethodError, localmethod '%s' is not accessible outside object '%s' % (self.name, self.defclass.__name__) class Type(type): def __new__(self, name, bases, attrs): # decorate all function attributes with 'method' for attr, val in attrs.items(): if type(val) == FunctionType: attrs[attr] = method(val) return type.__new__(self, name, bases, attrs) def __init__(self, name, bases, attrs): for attr, val in attrs.iteritems(): # Inform methods of what class they are created in if isinstance(val, method): val.defclass = self # Inform localmethod of their name (in case they have to be bypassed) if isinstance(val, localmethod): val.name = attr class Object(object): __metaclass__ = Type # Here is your example code class A(Object): @localmethod def m(self): print 'A.m' def am(self): self.m() class B(A): @localmethod def m(self): print 'B.m' def bm(self): self.m() m = B() m.am() # prints 'A.m' m.bm() # prints 'B.m' # Added: B.am(m)# prints 'A.m' B.bm(m)# prints 'B.m' m.m() # LocalMethodError (which descends from AttributeError) # Untested beyond this particular example! -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list
Re: Project organization and import
On 5 Mar 2007 10:31:33 -0800, Martin Unsal [EMAIL PROTECTED] wrote: On Mar 5, 9:15 am, Chris Mellon [EMAIL PROTECTED] wrote: That's actually the exact benefit of unit testing, but I don't feel that you've actually made a case that this workflow is error prone. You often have multiple developers working on the same parts of the same module? Protecting your head is the exact benefit of bike helmets, that doesn't mean you should bike more more recklessly just because you're wearing a helmet. :) Doing text merges is more error prone than not doing them. :) There are myriad other benefits of breaking up large files into functional units. Integration history, refactoring, reuse, as I mentioned. Better clarity of design. Easier communication and coordination within a team. What's the down side? What's the advantage of big files with many functional units? I never advocated big files with many functional units - just files that are just big enough. You'll know you've broken them down small enough when you stop having to do text merges every time you commit. If you don't do this, you aren't really testing your changes, you're testing your reload() machinery. Only because reload() is hard in Python! ;) You seem to have a lot of views about what the Python way should be and those are at odds with the actual way people work with Python. I'm not (necessarily) saying you're wrong, but you seem to be coming at this from a confrontational standpoint. When I refer to Pythonic all I'm talking about is what I've read here and observed in other people's code. I'm here looking for more information about how other people work, to see if there are good solutions to the problems I see. However when I talk about what I think is wrong with the Pythonic way, obviously that's just my opinion formed by my own experience. Your claim, for example, that the language shouldn't place constraints on how you manage your modules is questionable. I think it's more likely that you've developed a workflow based around the constraints (and abilities) of other languages and you're now expecting Python to conform to that instead of its own. I don't think so; I'm observing things that are common to several projects in several languages. languages with similar runtime semantics and perhaps common ancestry? All languages place limitations on how you handle modules, either because they have infrastructure you need to use or because they lack it and you're left on your own. I wonder if you've ever asked yourself why this is the case. I know from my own experience why it's done in traditional C++/C environments - it's because compiling is slow and breaking things into as many files (with as few interdependencies) as possible speeds up the compilation process. I don't think that's actually true. Fewer, bigger compilation units actually compile faster in C, at least in my experience. If you're doing whole project compilation. When you're working, though, you want to be able to do incremental compilation (all modern compilers I know of support this) so you just recompile the files you've changed (and dependencies) and relink. Support for this is why we have stuff like precompiled headers, shadow headers like Qt uses, and why C++ project management advocates single class-per-file structures. Fewer dependencies between compilation units means a faster rebuild-test turnaround. Absent this need (which doesn't exist in Python), Python still takes time to load precompile. That time is becoming significant for me even in a modest sized project; I imagine it would be pretty awful in a multimillion line project. No matter how fast it is, I'd rather reload one module than exit my interpreter and reload the entire world. Sure, but whats your goal here? If you're just testing something as you work, then this works fine. If you're testing large changes, that affect many modules, then you *need* to reload your world, because you want to make sure that what you're testing is clean. I think this might be related to your desire to have everything in lots of little files. The more modules you load, the harder it is to track your dependencies and make sure that the reload is correct. This is not a problem for Python as scripting language. This is a real problem for Python as world class application development language. Considering that no other world class application development language supports reload even as well as Python does, I'm not sure I can agree here. A perfect reload might be a nice thing to have, but lack of it hardly tosses Python (or any language) out of the running. In a package __init__, which exists expressly for the purpose of exposing it's interior namespaces as a single flat one, it makes perfect sense. OK! That's good info, thanks. Nobody I know uses reload() for anything more than trivial as you work testing in the interpreter. It's
Re: New to Python
On Mar 5, 6:33 pm, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote: I am trying to get a program to add up input from the user to get to the number 100 using a loop. However, I am having some issues. Here is what I have so far. I know I am just trying to hard, but I am stuck. Thank you for any help. print We need to count to 100 high_number = 100 total = 0 number = input(Enter your first number ) sum = number + total while sum high_number: print Not there yet... number = input(Enter another number ) print We are there!!! There is no need for 'sum' and 'total'. Here's a working version of your program. Look at the differences with your attempt. -- print We need to count to 100 high_number = 100 total = input(Enter your first number ) # first total is the fist number while total high_number: print Not there yet... number = input(Enter another number ) total = total + number # Add the new number to the total print We are there!!! -- Good luck ! As others have pointed out, 'input' is a function to be careful with. You could use answer=raw_input(...) and then convert the result to an int by using number=int(answer). -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list
Re: New to Python
On Mar 5, 1:14 pm, Arnaud Delobelle [EMAIL PROTECTED] wrote: On Mar 5, 6:33 pm, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote: I am trying to get a program to add up input from the user to get to the number 100 using a loop. However, I am having some issues. Here is what I have so far. I know I am just trying to hard, but I am stuck. Thank you for any help. print We need to count to 100 high_number = 100 total = 0 number = input(Enter your first number ) sum = number + total while sum high_number: print Not there yet... number = input(Enter another number ) print We are there!!! There is no need for 'sum' and 'total'. Here's a working version of your program. Look at the differences with your attempt. -- print We need to count to 100 high_number = 100 total = input(Enter your first number ) # first total is the fist number while total high_number: print Not there yet... number = input(Enter another number ) total = total + number # Add the new number to the total print We are there!!! -- Good luck ! As others have pointed out, 'input' is a function to be careful with. You could use answer=raw_input(...) and then convert the result to an int by using number=int(answer). -- Arnaud- Hide quoted text - - Show quoted text - Thanks for the help guys!!! Before I got a chance to read your answer Arnaud, I came up with the below. Seems to work also. Yours is easier :). print We need to count to 100 high_number = 100 sum = 0 sum += input(Enter your first number ) print sum while sum high_number: print Not there yet... sum += input(Enter another number ) print sum print We are there!!! -- http://mail.python.org/mailman/listinfo/python-list
Re: Python 2.5, problems reading large ( 4Gbyes) files on win2k
On 3/4/07, Paul Duffy [EMAIL PROTECTED] wrote: Bill Tydeman wrote: Just curious, but since the file size limitation on NTFS is 4 GB, have you confirmed that it isn't some other part of the interaction that is causing the problem? What FS is hosting the files? I don't think that is correct. Groovy version of app runs just fine.' That should have been pre-NTFS (i.e. FAT32) but I have had problems with files larger than 4GB on NTFS. -- http://mail.python.org/mailman/listinfo/python-list
Webserver balance load
Can anyone suggest a way how to balance load on Apache server where I have Python scripts running? For example I have 3 webservers( Apache servers) and I would like to sent user's request to one of the three server depending on a load on the server. Thank you . L. -- http://mail.python.org/mailman/listinfo/python-list
Re: Webserver balance load
On 5 Mar 2007 11:47:15 -0800, Johny [EMAIL PROTECTED] wrote: Can anyone suggest a way how to balance load on Apache server where I have Python scripts running? For example I have 3 webservers( Apache servers) and I would like to sent user's request to one of the three server depending on a load on the server. Thank you . L. http://pythondirector.sourceforge.net/ might be interesting. -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: How to create pid.lock via python?
May this works for your case http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/498171. /Jean Brouwers On Mar 5, 3:12 am, Marco [EMAIL PROTECTED] wrote: Hello, I write a program control a device via RS232, I hope to add some code to let the program canNOT be used by other people when one people using. Can you tell me how to create pid.lock file in python? Thank you!! -- LinuX Power -- http://mail.python.org/mailman/listinfo/python-list
Using string as file
Hello, I have a function from a library thast expects a file object as argument. How can I manage to give the function a string resp. have the text it would have written to file object as a string? Thanks, Florian -- http://mail.python.org/mailman/listinfo/python-list
Re: Using string as file
On Mar 5, 8:13 pm, Florian Lindner [EMAIL PROTECTED] wrote: Hello, I have a function from a library thast expects a file object as argument. How can I manage to give the function a string resp. have the text it would have written to file object as a string? Thanks, Florian See http://docs.python.org/lib/module-StringIO.html -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list
Re: package_data question
On Mar 5, 1:56 am, bytecolor [EMAIL PROTECTED] wrote: I have a simple package. I'm trying to add an examples subdirectory with distutils. I'm using Python 2.4 on Linux. My file layout and setup.py can be found here: http://www.deadbeefbabe.org/paste/3870 I've tried using data_files as well, with the same result; examples/ fig2.3.apt is not added to the tarball. -- bytecolor I have a package along with a samples section. I have both a setup.py script along with a MANIFEST.in file to make sure everything gets in. You can see both of the files at https://springpython.python-hosting.com/browser/trunk/samples That is for the samples section. For my main package, I have something similar at https://springpython.python-hosting.com/browser/trunk/src -- http://mail.python.org/mailman/listinfo/python-list
Re: Building a dictionary from a tuple of variable length
Hi, Therefore, how do I build the tuple of Falses to reflect the length of my t tuple? Yet another solution : d = dict(zip(t,[False]*len(t))) Pierre -- http://mail.python.org/mailman/listinfo/python-list
Re: Webserver balance load
Jean-Paul Calderone a écrit : On 5 Mar 2007 11:47:15 -0800, Johny [EMAIL PROTECTED] wrote: Can anyone suggest a way how to balance load on Apache server where I have Python scripts running? For example I have 3 webservers( Apache servers) and I would like to sent user's request to one of the three server depending on a load on the server. Thank you . L. http://pythondirector.sourceforge.net/ might be interesting. See also pound: http://www.apsis.ch/pound/ -- http://mail.python.org/mailman/listinfo/python-list
Any way to determine test success from inside tearDown()?
This question pertains to PyUnit, esp. unittest.TestCase subclasses. Does anyone know of a way from within the TestCase tearDown() method to determine whether the current test succeeded or not? What I'm after is a specialized clean-up approach for error/failure cases. This is somewhat related to some earlier threads in this group about using fixtures across test invocations. I'm functionally testing a system that uses a database. Successful tests are guaranteed to restore the system's data fixtures to initial state, but when tests fail or error-out we want to do a brute-force re-initialization of the server so downstream tests can continue. This re-initialization takes time so we don't want to do it in every tearDown(), just on error/ failure tearDown()'s. TIA, Chris -- http://mail.python.org/mailman/listinfo/python-list
Re: New to Python
[EMAIL PROTECTED] a écrit : I am trying to get a program to add up input from the user to get to the number 100 using a loop. However, I am having some issues. Here is what I have so far. I know I am just trying to hard, but I am stuck. Where ? May I suggest this reading ? http://www.catb.org/~esr/faqs/smart-questions.html Thank you for any help. print We need to count to 100 high_number = 100 total = 0 number = input(Enter your first number ) Please re-read *very carefully* the doc for input(). Then switch to raw_input() and perform appropriate validation and conversion. sum = number + total don't use 'sum' as an identifier, unless you don't mind shadowing the builtin sum() function. while sum high_number: print Not there yet... number = input(Enter another number ) print We are there!!! We're not. number won't be automagically added to sum. -- http://mail.python.org/mailman/listinfo/python-list
ABC with Linux
Im tryin to make ABC (a bitorrent client) work under linux. I installed everything, that is ABC, wxpython, glib and gtk, and now I get a python error, saying it can't find wxpython. Am I supposed to set an environmental variable too? A little learning is a dangerous thing, but we must take that risk because a little is as much as our biggest heads can hold. George Bernard Shaw - Check out the all-new Yahoo! Mail beta - Fire up a more powerful email and get things done faster.-- http://mail.python.org/mailman/listinfo/python-list
Is every number in a list in a range?
I have a list ll of intergers. I want to see if each number in ll is within the range of 0..maxnum I can write it but I was wondering if there's a better way to do it? TIA -- Time flies like the wind. Fruit flies like a banana. Stranger things have .0. happened but none stranger than this. Does your driver's license say Organ ..0 Donor?Black holes are where God divided by zero. Listen to me! We are all- 000 individuals! What if this weren't a hypothetical question? steveo at syslang.net -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie question
Tommy Grav a écrit : 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? either map() or a list comprehension import sys fname = test.txt lines = open(fname,r) for numline, line in enumerate(lines): try: x, y, z = map(float, line.split()) # or: # x, y, z = [float(item) for item in line.split()] except (ValueError, IndexError), e: err = Invalid data format in %s line %s : %s (%s) \ % (fname, numline, line, e) print sys.stderr, err sys.exit(1) else: # do whatever appropriate here - anyway HTH -- http://mail.python.org/mailman/listinfo/python-list