ANN: 3 new ShowMeDo.com videos on Python Objects
Summary: At http://ShowMeDo.com we have 3 new videos by Jerol Harrington introducing Python Objects: http://showmedo.com/videoListPage?listKey=IntroductionToPythonObjectsUsingIPython_JerolH and 5 videos for beginners to wxPython: http://showmedo.com/videoListPage?listKey=PythonWxPythonBeginnersSeries making a total of 20 ShowMeDo videos, mostly about Python, all free. Detail: Jerol Harrington's ShowMeDos use the IPython shell to give an introduction to using 'class', '__init__', inheritance and attributes. I have been using Python for 3 years and I got something out of each of the videos. These videos represent our first user-contribution - thanks Jerol! In the 5 wxPython videos Kyran Dale walks you through the first steps of using wxPython - from downloading, installing (MS Windows), a first application and on to menubars and event handling. Also, in our latest update we have enabled voting on other user's requests: http://showmedo.com/requests There are 14 requests right now, feel free to share your view on which videos you would like to see. Some of the requests include List Comprehensions, py2exe, wxGlade, PyDev and other IDEs. Please get in touch if we're missing a topic that ought to be included, we will do our best to have new ShowMeDos made. About ShowMeDo.com: Free videos (we call them ShowMeDos) showing you how to do things. The videos are made by us and our users, for everyone. Ian Ozsvald, Kyran Dale [EMAIL PROTECTED] http://ShowMeDo.com (http://blog.showmedo.com) -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html
Furius on-site Python training course
Hello to all Python fiddlers and hackers! I thought I would send a short notice on this list about my Python training course offering. If you or people in your company would be interested in getting professional on-site Python training, I'm offering a 3-day intensive course on the Python language. Full details about the course are available from: http://furius.ca/training/ * The course aims at teaching Python beginner and intermediate programmers, and I can adapt it for various audiences. I have taught the course to C++ hackers wanting to learn Python and to beginning programmers alike. * The course alternates between presentations and sessions of exercises, to make sure that the students get to experiment and to give them a chance to ask more questions. * The students are provided with an set of course notes to keep and refer to later on. * On the last day, a few custom modules that pertain specifically to your area of interest are tacked on the generic course--there are many modules to choose from: from web applications to creating development automation tools, building GUI apps, database access, and more. * The course may be offered in english and french. * I'm currently based in Canada, but I can fly anywhere for the course. Any further questions (or for a quote), please let me know at [EMAIL PROTECTED]. Best regards, -- Martin Blais [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: Should I learn Python instead?
Thanks guys. I picked up the Apress book on Python and downloaded the Komodo IDE trial to get me started. I'm going to try using Django to build my website and since my brother already has hosting I'll just borrow some space. He does PHP for a living, so it would probably be better for me to use that instead. Unfortunately, I'm allergic to dollar signs ;) -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem involving sets...
wowowow now THAT is what I call simple! -- http://mail.python.org/mailman/listinfo/python-list
OneAtATime
#!/usr/bin/python #+ # This script ensures there is only one instance of a particular command # running at a time. It may be useful, for example, for potentially # lengthy cron tasks, to ensure that a new task is not started if the # previous one has not finished yet. # # Invoke this script from the command line as follows: # # OneAtATime [opts] cmd # # where cmd is the Shell command line to execute. Valid options are: # # --id=s # use the string s as the unique identifier for this command # (should not contain / or nul characters). Any other execution # of OneAtATime specifying the same id will not proceed as long as # this instance is still executing. # If omitted, the id is computed as a hash on the cmd string. # # --timeout=n # If an existing instance has been executing for at least n # seconds, assume it's taking too long and try to kill it # before proceeding. If omitted, the timeout is infinity. # # --verbose # increases the verbosity level by 1 each time it is specified. # The initial default verbosity level is 0. # # --wait # If specified, then this invocation should sleep until any # previous instance is finished (or until the timeout elapses, # if specified). If not specified, then this invocation will # simply exit if an existing instance is already running. # Note that, if more than one invocation is waiting on a # previous instance to complete, there is no guarantee in # what order they'll execute. # # Start of development 2006 March 23 by Lawrence D'Oliveiro # [EMAIL PROTECTED]. # First working version 2006 March 24. # Fix hang if previous process dies without freeing instance lock and # --timeout was not specified 2006 March 24. # Ensure lock-breaking recovery is still invoked even without --wait, # include effective user ID in instance lock name for uniqueness # 2006 March 25. # Last modified 2006 March 27. #- import sys import os import time import errno import signal import getopt import sha SignalName = {} for Name in dir(signal) : # collect symbolic names for all signals Value = getattr(signal, Name) if Name.startswith(SIG) and type(Value) == int : SignalName[Value] = Name #end if #end for #+ # Mainline #- (Opts, Args) = getopt.getopt \ ( sys.argv[1:], , [id=, timeout=, verbose, wait] ) if len(Args) != 1 : raise getopt.GetoptError(need exactly one arg, the cmd to execute) #end if Cmd = Args[0] ID = None Timeout = None Wait = False Verbosity = 0 for Keyword, Value in Opts : if Keyword == --id : ID = Value elif Keyword == --timeout : Timeout = int(Value) elif Keyword == --verbose : Verbosity += 1 elif Keyword == --wait : Wait = True #end if #end for if ID == None : ID = sha.new(Cmd).hexdigest()[:16] # less than 40-char file name should be OK #end if def Debug(Level, Msg) : if Verbosity = Level : print Msg #end if #end Debug PidFileName = /tmp/OneAtATime-pid-%d % os.getpid() PidFile = file(PidFileName, w) PidFile.write(%s\n % os.getpid()) PidFile.close() InstanceLockName = /tmp/OneAtATime-lock-%d-%s % (os.geteuid(), ID) # presence of this file is used to guard against more than one # invocation of a task with the same id at once InstanceLock2Name = /tmp/OneAtaTime-lock2-%s % ID # presence of this file is used to serialize checking for # presence of InstanceLockName and of the process whose PID is # contained in that file GotLock = False GotLock2 = False LastLastMod = None OtherPid = None while True : # try to get instance lock if not GotLock2 : while True : # grab the secondary lock for checking the instance lock try : os.symlink(PidFileName, InstanceLock2Name) # guaranteed atomic operation that will fail if # destination name already exists. Note use of # symlink rather than link because my pid file # might be older than secondary lock timeout # if I've been waiting a while. GotLock2 = True break except OSError, (ErrNo, Msg) : if ErrNo != errno.EEXIST : # Not bothering to recover from privilege failures raise OSError(ErrNo, Msg) #end if #end try # Somebody else has the lock, check it looks reasonable try : LastMod = os.lstat(InstanceLock2Name).st_mtime # note use of lstat to find out how long symlink has # been present, not age of pid file except OSError, (ErrNo, Msg) : if ErrNo == errno.ENOENT : LastMod = None else : # Not bothering to recover from privilege
wxPython - antialiased drawing
Hello, can anybody tell me if and how I do antialiased drawing in wxPython. Andy -- http://mail.python.org/mailman/listinfo/python-list
Improvements for import this
As the capabilities of core Python have increased, I've noticed that the logic in import this can be simplified to one line: print s.decode(rot13) ;) At the very least the last line: print .join([d.get(c, c) for c in s]) could use a generator expression instead of a list comprehension. -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: PEP 359: The make Statement
Tim Hochberg ha scritto: I think this PEP is going off the rails. It's primary virtue was that it was a simpler, clearer way to write: class Foo(args): __metaclass__ = some_metaclass #... Once it starts calling secret magic methods behind the scenes it's losing that virture. And for what? Supporting some use cases that have reasonable solutions already? FWIW, this is my feeling too. Let's keep it simple, please! Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
Re: requestion regarding regular expression
Thanks to both of you, Kent and Scott. -- http://mail.python.org/mailman/listinfo/python-list
Re: A problem with exec statement
TPJ wrote: (...) Even allowing for the difficulties you've already experienced, it's nearly always better in practical cases to use assignment to the keys of a dictionary. Then no exec is required, and you have direct control over your own namespace. Well... Is this a sugestion, that instead of messing up with the exec statements used to modify local namespaces I should use dictionaries? Perhaps you're right. In fact, the problem, that I'm trying to solve is as follows: def funcA(): def funcB(): ... var1, var2, var3, ..., varN = ( None, ) * N t = ( (regexp1, 'var1'), (regexp2, 'var2'), ..., (regexpN, 'varN') ) for regexp, var_name in t: match = regexp.match( some_string ) if match != None: # now the *magic* exec statement comes... exec var_name + ' = match.groups()[0]' in globals(), locals() return var1, var2, var3, ..., varN ... k1, k2, k3, ..., kN = funcB() My problem is more complicated, that the presented example. In general, my problem is: how to create a local variable by executing the Python code, that isn't known at the moment of writing the program? In another words: I have to create a local variable, whose name will be known at the runtime, in a nested function. Is it possible, or have I to use dictionaries, instead of exec statement used to modify local namespaces? There is a mismatch between your example code and the problem description you are giving. The example can easily be rewritten without nested scopes and exec: # of course untested def funcB(some_string): for r in [regexp1, regexp2, regexp3, ..., regexpN]: match = r.match(some_string) if match: yield match.group(1) else: yield None def funcA(): k1, k2, k3, ..., kN = funcB(some_string) The uniform ki variable names are an indication that you may be able to simplify this even further. I'm therefore confident that rewriting your real code without exec will be more rewarding than digging deeper into the quirks of exec (which admittedly I find puzzling, too). Peter PS: Here is another gem showing that my original assertion that inside a function locals() is always a copy is wrong: def f(): ... locals()[a] = 42 ... print a ... f() Traceback (most recent call last): File stdin, line 1, in ? File stdin, line 3, in f NameError: global name 'a' is not defined def f(): ... locals()[a] = 42 ... print a ... if False: exec ... f() 42 -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem involving sets...
Kent Johnson wrote: flamesrock wrote: Kind of a fun but confusing problem... I have two lists. Each list contains elements of two-element lists. l1 = [['c1',1],['c2',2],['c3',4]] l2 = [['c1',1],['c2',2],['c4',4],['c3',3]] Exactly in this format, where superlist[0][0] is always a string superlist[0][1] is always an integer Now what I would like to do is find the intersect of those two super-lists based on superlist[0][0] and then compare the integers to find ultimately: A list of strings of the intersect of l1/l2, where the l1[x][1] l2[x][1] In the case of the above example, that would be simply: ['c3'] In [5]: l1 = [['c1',1],['c2',2],['c3',4]] In [6]: l2 = [['c1',1],['c2',2],['c4',4],['c3',3]] In [7]: d=dict(l1) In [10]: [k for k,v in l2 if k in d and v d[k]] Out[10]: ['c3'] Kent The dict solution posted above is definitely better than the following, but purely out of idle curiosity I was interested to see if this could be done in one line using just list comprehensions ... Python 2.4.2 (#1, Nov 15 2005, 15:54:06) [GCC 3.3.6 (Gentoo 3.3.6, ssp-3.3.6-1.0, pie-8.7.8)] on linux2 Type help, copyright, credits or license for more information. l1 = [['c1',1],['c2',2],['c3',4]] l2 = [['c1',1],['c2',2],['c4',4],['c3',3]] [k2 for [k2,v2] in l2 if k2 in [k1 for k1,v1 in l1] and v2 [v1 for k1,v1 in l1 if k1 == k2][0]] ['c3'] ... yup :-) Dave. -- -- http://mail.python.org/mailman/listinfo/python-list
Re: HELP PLEASE: What is wrong with this?
Ralph H. Stoos Jr. enlightened us with: File autotp.py, line 21 ready = raw_input(Ready to proceed ? TYPE (y)es or (n)o: ) ^ Please post the entire traceback, so we can see the actual error message. Posting the context of the bad line also wouldn't hurt. Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa -- http://mail.python.org/mailman/listinfo/python-list
Re: VB to Python
Vielen Dank. Es funktioniert. Mit freundlichen gruessen, Aleksandar Cikota Gregor Horvath [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Aleksandar Cikota schrieb: Can someone translate the VB code to Python? VB code: Dim chsr as New DriverHelper.Chooser chsr.DeviceType = Telescope scopeProgID = chsr.Choose(scopeProgID) Set scope = CreateObject(scopeProgID) scope.Connected = True (untested; late binding): import win32com.client chsr = win32com.client.Dispatch(DriverHelper.Chooser) #you may have to choose the ProdID of the class from the registry here chsr.DeviceType = Telescope scopeProgID = chsr.Choose(scopeProgID) scope = win32com.client.Dispatch(scopeProgID) scope.Connected = True -- Mit freundlichen Grüßen, Ing. Gregor Horvath, Industrieberatung Softwareentwicklung Mobil: +43(0)69910879004 Fax: +43(0)1/25330333931 http://www.gregor-horvath.com -- Mit freundlichen Grüßen, Ing. Gregor Horvath, Industrieberatung Softwareentwicklung http://www.gregor-horvath.com -- http://mail.python.org/mailman/listinfo/python-list
Re: nested functions
Lawrence D'Oliveiro wrote: BUT 'b' and 'c' simply do not exist outside the 'a' world. It's worth distinguishing between the _names_ 'b' and 'c' and the _functions_ referred to by those names. The _names_ certainly do not exist outside of the scope of the function referred to by 'a' (any occurrences of 'b' and 'c' outside that scope refer to _different_ names), but the _functions_ they refer to certainly do exist. that's a bit misleading. def is an executable statement, and it *creates* a function object when it's executed. that object is handled in exactly the same way as any other object. in the following example, the function referred to by c doesn't exist before a call to a, and it doesn't exist after the function has returned: def a(): def c(): print c c() if you call the function again, a new function object is created. /F -- http://mail.python.org/mailman/listinfo/python-list
Re: [Python-Dev] Building Python with the free MS Toolkit compiler
Paul Moore wrote: I've just added some instructions on how to build Python on Windows with the free MS Toolkit C++ compiler. They are at http://wiki.python.org/moin/Building_Python_with_the_free_MS_C_Toolkit. Cool! If you think that adding/changing files in Python would simplify the process, don't hesitate to produce patches. Regards, Martin -- http://mail.python.org/mailman/listinfo/python-list
Re: help me ( import cx_Oracle ) 失�
[EMAIL PROTECTED] enlightened us with: ???d???b cx_Oracle (Oracle 9i, Python 2.4) ???b??windows xp ??python???a??C:\Python24\cx_Oracle-doc?? import cx_Oracle ???F Traceback (most recent call last): File interactive input, line 1, in ? ImportError: DLL load failed: ???M?? ?}???Q, help me Posting in ASCII and in English might help... Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa -- http://mail.python.org/mailman/listinfo/python-list
Re: Should I learn Python instead?
fyleow wrote: Hi guys, I'm a student/hobbyist programmer interested in creating a web project. It's nothing too complicated, I would like to get data from an RSS feed and store that into a database. I want my website to get the information from the database and display parts of it depending on the criteria I set. [...] This is how to access an RSS feed and create an XML document to manipulate it. System.Net.WebRequest myRequest = System.Net.WebRequest.Create(//feed url here); System.Net.WebResponse myResponse = myRequest.GetResponse(); System.IO.Stream rssStream = myResponse.GetResponseStream(); System.Xml.XmlDocument rssDoc = new System.Xml.XmlDocument(); rssDoc.Load(rssStream); Here's PHP. $rss_feed = file_get_contents($rss_url); I've never used it myself but maybe this would be useful: http://feedparser.org/ From the Homepage: import feedparser d = feedparser.parse(http://feedparser.org/docs/examples/atom10.xml;) d.feed.title u'Sample Feed' d.channel.title u'Sample Feed' d.feed.link u'http://example.org/' d.feed.subtitle # parses escaped HTML u'For documentation emonly/em' d.channel.description u'For documentation emonly/em' Gerard -- http://mail.python.org/mailman/listinfo/python-list
The whitespaceless frontend
It had to happen :) http://pyvm32.infogami.com/EPL Seriously, this is not so much about the whitespace as for the new features, which might interest people who are thinking about new features. More specifically, methods and the $ operator are really great and seem to solve the problem with having to type self. all the time. The new syntax has been tested in core libraries of pyvm. Feedback is welcome, but preferably not in c.l.py because indentation can be a dangerous topic :) Cheers, Stelios -- http://mail.python.org/mailman/listinfo/python-list
Re: list.clear() missing?!?
Ben C wrote: I used to think it assigned with things like integers, because if you write: a = 5 b = a b += 1 print a a is still 5. So it looked like a and b stored values and b got a copy of a's value. But this is the wrong interpretation, b += 1 is really b = b + 1, and rebinds b. almost: b += obj is really b = b.__iadd__(obj) with b = b + obj as a fallback if __iadd__ isn't supported by b. If it weren't for the id() function I think the difference between variable stores value, variable stores immutable reference and variable stores copy-on-write reference would be implementation detail and never visible to the programmer. except when they are: a = [1, 2, 3] b = a b += [4] a [1, 2, 3, 4] b [1, 2, 3, 4] /F -- http://mail.python.org/mailman/listinfo/python-list
Re: Why new Python 2.5 feature class C() return old-style class ?
Wildemar Wildenburger wrote: But I guess I'll just keep adding the (object) appendix even after that, so all my class definitions get syntax highlighting. why are you using an IDE that doesn't understand Python syntax ? /F -- http://mail.python.org/mailman/listinfo/python-list
py2exe problem
First time trying to create an executable with py2exe. I have a small program which makes use of python23 (2.3.5?), wxpython ('2.6.2.1'), matplotlib ('0.83.2'), win32com (latest?), Numeric ('23.7') on Windows XP Win2000. The program runs without problem but as an exe it doesn't even get to showing the GUI. I get the following error log when I run the executable. Traceback (most recent call last): File mpival3.py, line 1264, in ? File wx\_core.pyc, line 7668, in __init__ File wx\_core.pyc, line 7320, in _BootstrapApp File mpival3.py, line 364, in OnInit File mpival3.py, line 79, in __init__ File mpival3.py, line 204, in restore_inputs File mpival3.py, line 275, in setConfig File wx\_controls.pyc, line 621, in SetValue TypeError: String or Unicode type required Line 621 in wx\_controls.pyc refers to setting the value of a combobox at the start up of my code. The initial values of various widgets (checkboxes, textboxes and comboboxes) are stored in a pickled file which is read at the program start. Running the program, not the exe, shows that the variables are retrieved properly and of the correct type for the combobox.SetValue method. Furthermore, if I comment out the code to set the combobox value and recreate the exe, then I get the same sort of error message for a different (textbox) widget. I've read all the py2exe WIKI entries, forum posts and Googled myself senseless ... now I'm stuck. Can anyone shed any light on this problem, or have some experience to share? As an aside, I've found this a very frustrating process at this stage. Never thought it would be so much trouble. Am I just dreaming in thinking I can package up my program with this combination of modules?. fwiw my py2exe setup.py file is included below. It's obviously a concoction of includes, excludes and other options pieced together from hours of browsing wiki's etc. Thanks. Chris == # setup.py from distutils.core import setup import py2exe import sys # If run without args, build executables, in quiet mode. if len(sys.argv) == 1: sys.argv.append(py2exe) sys.argv.append(-q) # Matplotlib # We need to import the glob module to search for all files. import glob # We need to exclude matplotlib backends not being used by this executable. You may find # that you need different excludes to create a working executable with your chosen backend. # We also need to include matplotlib.numerix.random_array options = {py2exe: { includes: [matplotlib.numerix.random_array, matplotlib.backends.backend_tkagg, encodings, encodings.*], # includes: [matplotlib, Numeric, scipy, scipy_base], # excludes: [_gtkagg, _tkagg], packages: [pytz], dll_excludes: ['libgdk-win32-2.0-0.dll', 'libgobject-2.0-0.dll'] } } # Additional data files are required by matplotlib. Note that the glob.glob routine # doesn't seem to pick up the .matplotlib resource file, so I copy that separately. # Do the same if you need to #datf = [(r'matplotlibdata', glob.glob(r'c:\python23\share\matplotlib\*')), #(r'matplotlibdata', [r'c:\python23\share\matplotlib\.matplotlibrc'])] datf = [(r'matplotlibdata', glob.glob(r'c:\python23\share\matplotlib\*'))] # for scipy excludes = [] includes = [scipy.special.__cvs_version__, scipy.linalg.__cvs_version__, scipy.special.cephes] options[py2exe][includes].extend(includes) # other #options[py2exe][compressed] = 1 #options[py2exe][optimize] = 2 #options[py2exe][ascii] = 1 #options[py2exe][bundle_files] = 3 #options[py2exe][skip_archive] = 1 setup( options = options, data_files = datf, name = 'validation', description = 'Validation Program', windows = ['mpival3.py'] ) -- http://mail.python.org/mailman/listinfo/python-list
Re: HELP PLEASE: What is wrong with this?
Ralph H. Stoos Jr. wrote: File autotp.py, line 21 ready = raw_input(Ready to proceed ? TYPE (y)es or (n)o: ) ^ please post the entire output and the surrounding code (as much as reasonable). It may well be some paranthesis error, as alreasy stated. -- Thomas Jollans - http://jollybox.de/ GNU/Linux - freedom, functionality, power - what more do you want ? When in doubt, follow the penguins. -- http://mail.python.org/mailman/listinfo/python-list
Re: The whitespaceless frontend
This seems nice: global.x = 1 is the same as global x x = 1 but maybe instead of the global.name something to refer to the upper namespace (that can be the global one or the namespace of the function that contains this one) can be more general: upper.x = 1 upper.upper.x = 1 I think that making self a reserved word that can be used only for its usual purpose can be positive. The $ and method statement seem interesting too, but the first is a little perlish (but Ruby has something similar, and people like it), and the method statement look a little redundant. I think the $ can be acceptable (Mostly to reduce typing), even if it doesn't look very nice. Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list
Re: The whitespaceless frontend
Stelios Xanthakis wrote: It had to happen :) http://pyvm32.infogami.com/EPL Seriously, this is not so much about the whitespace as for the new features, which might interest people who are thinking about new features. More specifically, methods and the $ operator are really great and seem to solve the problem with having to type self. all the time. The new syntax has been tested in core libraries of pyvm. Feedback is welcome, but preferably not in c.l.py because indentation can be a dangerous topic :) Very nice work. Lotta good ideas (of course that will never show up in in standard python, but who cares). I would mention though if you had used end for block delimiters (like ruby) instead of curly braces, there would be no conflict with dictionary literals. I made such a parser for another project. Just my opinion but end looks a bit cleaner too than curly braces. Now if only you could make python 100 times faster, too. -- http://mail.python.org/mailman/listinfo/python-list
Re: Announce: Construct's wiki!
tomer so now we have one place where people can share inventory tomer constructs, questions-and-answers, patches, documentation and tomer more. enjoy. I've never seen Construct before, but when you say parser I think of parsing programming languages. The couple of examples on the Construct wiki look more like what I'd use the struct module for. Can you define constructs to parse, say, common arithmetic expressions like (a + b) *4? Does it return some sort of abstract syntax tree? Skip -- http://mail.python.org/mailman/listinfo/python-list
XML-RPC server via xinetd
Hi, I'm trying to figure out how to implement a XML-RPC server that is called by xinetd i.s.o. listening on a TCP socket itself. I already have implemented a stand-alone XML-RPC server using SimpleXMLRPCServer, but I now want something similar, that is started via xinetd (i.e. reading/writing via stdin/stdout). Any hints or code examples? Thanks, -- --Jos Vos [EMAIL PROTECTED] --X/OS Experts in Open Systems BV | Phone: +31 20 6938364 --Amsterdam, The Netherlands| Fax: +31 20 6948204 -- http://mail.python.org/mailman/listinfo/python-list
Calling Python from Matlab
I am desperately looking for a way to call Python from Matlab. I have become used to Python's rich syntax and large number of libraries, and feel ridiculously clumsy being stuck with Matlab's rather restricted facilities for doing other things than standard mathematical work. Does anyone know of good techniques (or readily available software) for achieving a cross-language support between Python and Matlab? Carl -- http://mail.python.org/mailman/listinfo/python-list
Re: Help for a complete newbie
You can also access this group through Google Groups: http://groups.google.com/group/comp.lang.python which has nice search features. I found O'Reilly's Learning Python to be helpful in combination with O'Reilly's Python in a Nutshell. Learning python is a nice introduction to Python but is (intentionally) *far* from complete. Python In a Nutshell is a reference work. The two complement each other nicely. Both are a bit out of date. The current python version is 2.4. Learning Python covers 2.3. Nutshell covers up to 2.2. One of these days Alex will come out with a 2nd Edition of Nutshell and there will be much rejoicing. ;-) -- http://mail.python.org/mailman/listinfo/python-list
Re: Calling Python from Matlab
I am desperately looking for a way to call Python from Matlab. I have become used to Python's rich syntax and large number of libraries, and feel ridiculously clumsy being stuck with Matlab's rather restricted facilities for doing other things than standard mathematical work. Does anyone know of good techniques (or readily available software) for achieving a cross-language support between Python and Matlab? Carl Perhaps you will find this useful: http://claymore.engineer.gvsu.edu/~steriana/Python/pymat.html -- http://mail.python.org/mailman/listinfo/python-list
Re: Should I learn Python instead?
There is also TurboGears, which (IMO) is greatness in the making. Though unfortunately, the documentation is still catching up to the greatness. I'm using it and loving it, though. http://www.turbogears.org DJango is great for content management. TurboGears is (IMO) a more generalized framework. It all depends on what kind of site you are wanting to create. -- http://mail.python.org/mailman/listinfo/python-list
Re: Help with python output redirection
Thank you. Also this script is PublicDomain right? Steven D'Aprano wrote: On Fri, 14 Apr 2006 16:59:13 -0700, fatalserpent wrote: Here is the basic code (yes, I know its tiny). x = ['print x =, x', 'for m in x: print m'] print x =, x for m in x: print m I want to modify this so it will output to a file called 1. What I want is to have that file direct its output to a file called 2 and 2 direct to 3 and so on. Hopefully this will be an easy-to-answer question. THX in advance. From the shell, you are probably doing something like this: $ python mymodule.py Change it to this: $ python mymodule.py 2 $ python 2 3 $ python 3 4 and so on. Alternatively, you can do this: x = ['f = file(2, w)', 'print f, x =, x', 'for m in x: f, print m'] print f, x =, x for m in x: print f, m I'll leave changing the file name from 2 to 3 etc. as an exercise for you. -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
Re: Help for a complete newbie
Steve Bergman wrote: One of these days Alex will come out with a 2nd Edition of Nutshell and there will be much rejoicing. ;-) Rumor has it he is trying to hit print for OSCON (so soon, soon). --Scott David Daniels [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
ANN: Urwid 0.9.3 - Console UI Library
Announcing Urwid 0.9.3 -- Urwid home page: http://excess.org/urwid/ Tarball: http://excess.org/urwid/urwid-0.9.3.tar.gz About this release: === This release adds support for gpm and mouse dragging to the raw_display module, improves mouse release reporting and fixes a few text layout bugs. If you are interested in Urwid's mouse support please try the input test example program and let me know if it works properly in your environment. [EMAIL PROTECTED]:~/urwid-0.9.3$ ./input_test.py will test the input of the curses_display module. [EMAIL PROTECTED]:~/urwid-0.9.3$ ./input_test.py raw will test the input of the raw_display module. Please post your results and details about your environment to the mailing list. New in this release: - Improved mouse reporting. The raw_display module now detects gpm mouse events by reading /usr/bin/mev output. The curses_display module already supports gpm directly. Mouse drag events are now reported by raw_display in terminals that provide button event tracking and on the console with gpm. Note that gpm may report coordinates off the screen if the user drags the mouse off the edge. Button release events now report which button was released if that information is available, currently only on the console with gpm. - Added display of raw keycodes to the input_test.py example program. - Fixed a text layout bug affecting clipped text with blank lines, and another related to wrapped text starting with a space character. - Fixed a Frame.keypress(..) bug that caused it to call keypress on unselectable widgets. About Urwid === Urwid is a console UI library for Python. It features fluid interface resizing, UTF-8 support, multiple text layouts, simple attribute markup, powerful scrolling list boxes and flexible interface design. Urwid is released under the GNU LGPL. -- http://mail.python.org/mailman/listinfo/python-list
Re: Kross - Start of a Unified Scripting Approach
RM 写道: This is from the new KOffice Announcement. http://www.koffice.org/announcements/announce-1.5.php '''This version of KOffice features a start of a unified scripting solution called Kross. Kross provides cross-language support for scripting (thus its name) and at present supports Python and Ruby. Kross is easy to include into programs previously lacking scripting abilities, and is included in this version as a technology preview. So far, only Krita and Kexi are improved by means of the Kross engine.We would also like to point out that the API might change in the future and expect Kross to be fully integrated into KOffice version 2.0.''' Interesting isn't it? Just like the .Net vision , Good idea ! -- http://mail.python.org/mailman/listinfo/python-list
Re: The whitespaceless frontend
On 4/15/06, Stelios Xanthakis [EMAIL PROTECTED] wrote: It had to happen :) Did it? http://pyvm32.infogami.com/EPL Seriously, this is not so much about the whitespace as for the new features, which might interest people who are thinking about new features. More specifically, methods and the $ operator are really great and seem to solve the problem with having to type self. all the time. The new syntax has been tested in Exactly what is the problem with having to type self all the time? -- http://mail.python.org/mailman/listinfo/python-list
Re: PEP 359: The make Statement
Tim Hochberg wrote: Steven Bethard wrote: Steven Bethard wrote: Tim Hochberg wrote: Steven Bethard wrote: Steven Bethard wrote: Duncan Booth wrote: make Element html: make Element body: make Element p: text('But this ') make Element strong: text('could') text(' be made to work') This is nice. I'll have to play around with it a bit to see how hard it would be to make it work. Okay, I think it'll work[1]. I'm going to update this section to something more like: Open Issues === ... Should users of the make statement be able to determine in which dict object the code is executed? This would allow the make statement to be used in situations where a normal dict object would not suffice, e.g. if order and repeated names must be allowed. Allowing this sort of customization could allow XML to be written like:: I think this PEP is going off the rails. It's primary virtue was that it was a simpler, clearer way to write: class Foo(args): __metaclass__ = some_metaclass #... Once it starts calling secret magic methods behind the scenes it's losing that virture. And for what? Supporting some use cases that have reasonable solutions already? That's why it's in the Open Issues section. I expect most of these open issues to be resolved by rejection. (At least, that's my preferred resolution.) But since they people have brought them up, I think they need to be addressed as completely as possible. But I think you make a good point that this particular case can be just as easily done using a with-statement (I think). I'll add that to this part of the PEP (once I'm sure it works). Hmm... Actually, while the with-statement can probably help out with the nesting, it doesn't help out with the DRY; you still have to repeat the element name (once for the call to Element, and once as the name that Element object is bound to). I don't think that's correct. I think that with a suitably designed HtmlDocument object, the following should be possible: with HtmlDocument(Title) as doc: with doc.element(body): doc.text(before first h1) with doc.element(h1, style=first): doc.text(first h1) # I don't understand the point of tail, but you could do that too doc.text(after first h1) with doc.element(h1, style=second): doc.text(second h1) doc.text(after second h1) Here's code to do this. It would be probably be better to use elment tree or some such instead of pushing out the HTML directly, but this should get the idea across (testing using 2.5a1): class HtmlTag(object): def __init__(self, document, type, attribs): self.document = document self.type = type self.attribs = attribs def __context__(self): return self def _format_attribs(self): if not self.attribs: return '' return ' ' + ' '.join('%s=%s' % (k,v) for k, v in self.attribs.items()) def __enter__(self): self.document.entities.append('%s%s' % (self.type, self._format_attribs())) return self def __exit__(self, type, value, traceback): self.document.entities.append('/%s' % self.type) def add(self): self.document.entities.append('%s%s/' % (self.type, self._format_attribs())) class HtmlDocument(object): def __init__(self): self.entities = [] def tag(self, type, **atribs): return HtmlTag(self, type, atribs) def text(self, value): self.entities.append(value) def tostring(self): return ''.join(self.entities) def __context__(self): return self def __enter__(self): self.entities.append('html') return self def __exit__(self, type, value, traceback): if not (type is value is traceback is None): raise type(value) self.entities.append('/html') And here are some simple examples: with HtmlDocument() as doc: with doc.tag(body): doc.text(before first h1) with doc.tag(h1, style=first): doc.text(first h1) doc.text(after first h1) with doc.tag(h1, style=second): doc.text(second h1) doc.text(after second h1) expected = '''\ html\ body\ before first h1\ h1 style=firstfirst h1/h1\ after first h1\ h1 style=secondsecond h1/h1\ after second h1\ /body\ /html\ ''' print doc.tostring() == expected some_list = [foo, bar, 'bazz', froodle] with HtmlDocument() as doc: with doc.tag(body): with doc.tag(h1): doc.text(An ordered list) with
Re: [Python-Dev] Building Python with the free MS Toolkit compiler
On 4/15/06, Martin v. Löwis [EMAIL PROTECTED] wrote: Paul Moore wrote: I've just added some instructions on how to build Python on Windows with the free MS Toolkit C++ compiler. They are at http://wiki.python.org/moin/Building_Python_with_the_free_MS_C_Toolkit. Cool! If you think that adding/changing files in Python would simplify the process, don't hesitate to produce patches. I've just submitted http://www.python.org/sf/1470875 and assigned it to you. I hope that's OK. It's basically a documentation patch plus 2 supporting build files. Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Help for a complete newbie
Ralph H. Stoos Jr. wrote: Tim, After a little more research, I did find that out. It is funny, but in the tutorial Non-Programmers Tutorial For Python, it makes no mention of the indentation issue, at least in the beginning portions which I had read. This is an age old problem of learning. Once you know something, much of it seems simple and the knowledge of it can become assumed. One of the first things that should be done when providing training is to assess your audience. There are only a few FAQ / gotchas lists for python wink: http://www.ferg.org/projects/python_gotchas.html http://zephyrfalcon.org/labs/python_pitfalls.html http://zephyrfalcon.org/labs/beginners_mistakes.html http://www.python.org/doc/faq/ http://diveintopython.org/appendix/abstracts.html http://blog.ianbicking.org/my-python-4k.html http://www.onlamp.com/pub/a/python/2004/02/05/learn_python.html http://www.norvig.com/python-iaq.html http://www.faqts.com/knowledge_base/index.phtml/fid/245 http://www.faqts.com/knowledge_base/index.phtml/fid/199 http://amk.ca/python/writing/warts http://c2.com/cgi/wiki?PythonProblems -- http://mail.python.org/mailman/listinfo/python-list
Re: Unified web API for CGI and mod_python?
I've been digging around, but can't seem to come up with the right combo of words to google for to get helpful results. Is there some handy wrapper/module that allows code to target existance as both a CGI script and a mod_python script, with only one import statement? Perhaps some common object model? You could try WebStack - it provides a common API which would probably be suitable for your purposes: http://www.python.org/pypi/WebStack Paul, I meant to thank you (even if I already have) for this link as it's just what I've been looking for. Thanks! I've had some trouble installing it on one of my boxes and was hoping you might be able to tell me where I've gone awry: It's a Debian/Testing box with Apache 1.x running with both CGI and mod_python enabled for testing purposes (my aim is to make use of at least the CGI, mod_python, and BaseHTTPRequestHandler). When I run the setup.py script (either as myself or as root) I get back [EMAIL PROTECTED] cd ~tim/WebStack-1.1.2 [EMAIL PROTECTED] python2.3 setup.py install running install error: invalid Python installation: unable to open /usr/lib/python2.3/config/Makefile (No such file or directory) Now this makes sense, as I don't have a config/ in my /usr/lib/python2.3 directory. However, I've not had trouble with any other packages (though everything else has been added via apt-get, not via setup.py files). Is this a file that should be there? If so, where would I go about finding it? If not, is there a simple way to do an install without setup.py (or to tell setup.py to get over it)? Or is there a Debian repository with a .deb package for it that I can point at (I noticed you may have some Debian sort of leaning while hunting through the help)? Push come to shove, it would be possible to manually copy files to their associated locations: docs and apidocs to a WebStack directory in /usr/share/docs, and the WebStack python files to /usr/lib/python2.3/WebStack ...is there anything else I'm missing here? Thanks, -tim -- http://mail.python.org/mailman/listinfo/python-list
How to Convert a string into binary
Hello All i am new to python language. i am working on a gnuradio project where it uses python as the primary programming language. i am trying to convert a message, text, or numbers into binary code so that i can process it. i googled many times and tried many of the answers out there, no luck so far. is there a way to convert a string into its binary representation of the ascii table.?? an example of what i want would be: hi -- 011011101001 Thanks -HNT -- http://mail.python.org/mailman/listinfo/python-list
Re: How to Convert a string into binary
Em Sáb, 2006-04-15 às 19:25 +, HNT20 escreveu: is there a way to convert a string into its binary representation of the ascii table.?? I'm very curious... why? And no, I don't have the answer. -- Felipe. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to Convert a string into binary
HNT20 wrote: Hello All def ascii_to_bin(char): ascii = ord(char) bin = [] while (ascii 0): if (ascii 1) == 1: bin.append(1) else: bin.append(0) ascii = ascii 1 bin.reverse() binary = .join(bin) zerofix = (8 - len(binary)) * '0' return zerofix + binary some_string = 'Time to go now, Rummy?' binary = [] for char in some_string: binary.append(ascii_to_bin(char)) print binary print .join(binary) some_string = 'Time to go now, Rummy?' binary = [] for char in some_string: binary.append(ascii_to_bin(char)) print binary print .join(binary) ['01010100', '01101001', '01101101', '01100101', '0010', '01110100', '0110', '0010', '01100111', '0110', '0010', '01101110', '0110', '01110111', '00101100', '0010', '01010010', '01110101', '01101101', '01101101', '0001', '0011'] 01010100 01101001 01101101 01100101 0010 01110100 0110 0010 01100111 0110 0010 01101110 0110 01110111 00101100 0010 01010010 01110101 01101101 01101101 0001 0011 -- http://mail.python.org/mailman/listinfo/python-list
Re: ANN: 3 new ShowMeDo.com videos on Python Objects
Ian Ozsvald wrote: Summary: At http://ShowMeDo.com we have 3 new videos by Jerol Harrington introducing Python Objects: http://showmedo.com/videoListPage?listKey=IntroductionToPythonObjectsUsingIPython_JerolH and 5 videos for beginners to wxPython: http://showmedo.com/videoListPage?listKey=PythonWxPythonBeginnersSeries making a total of 20 ShowMeDo videos, mostly about Python, all free. Detail: Jerol Harrington's ShowMeDos use the IPython shell to give an introduction to using 'class', '__init__', inheritance and attributes. I have been using Python for 3 years and I got something out of each of the videos. These videos represent our first user-contribution - thanks Jerol! In the 5 wxPython videos Kyran Dale walks you through the first steps of using wxPython - from downloading, installing (MS Windows), a first application and on to menubars and event handling. Also, in our latest update we have enabled voting on other user's requests: http://showmedo.com/requests There are 14 requests right now, feel free to share your view on which videos you would like to see. Some of the requests include List Comprehensions, py2exe, wxGlade, PyDev and other IDEs. Please get in touch if we're missing a topic that ought to be included, we will do our best to have new ShowMeDos made. About ShowMeDo.com: Free videos (we call them ShowMeDos) showing you how to do things. The videos are made by us and our users, for everyone. Ian Ozsvald, Kyran Dale [EMAIL PROTECTED] http://ShowMeDo.com (http://blog.showmedo.com) A small hint for everyone interested in gaining deep understanding about Python objects: To gain deep understanding of what objects in Python are is one of the biggest challenges when learning Python. There are so many different ways of understanding what Python objects are and how Python works with them (depending on how deep you want your understanding to be, how deep you are ready to dig into this subject and how experienced in programming and smart you are), that whenever in the past someone asked a question related to such deep understanding in this or other Python related newsgroups, the outcome was a never ending discussion thread with many controversial postings. Please be aware, that the video about Python objects (I have checked out myself part I) is not consistent in using terms and explaining things, so take care assuming that you get enlightened about Python objects watching it. Claudio -- http://mail.python.org/mailman/listinfo/python-list
Re: How to Convert a string into binary
HNT20 wrote: is there a way to convert a string into its binary representation of the ascii table.?? an example of what i want would be: hi -- 011011101001 Why not just write some code to do it? e.g. def b1(n): return 01[n%2] def b2(n): return b1(n1)+b1(n) def b3(n): return b2(n2)+b2(n) def b4(n): return b3(n4)+b3(n) bytes = [ b4(n) for n in range(256)] def binstring(s): return ''.join(bytes[ord(c)] for c in s) binstring('hi') '011011101001' -- http://mail.python.org/mailman/listinfo/python-list
Re: How to Convert a string into binary
If (assuming this is correct, you can do more tests) the given strings are many and/or long, this can be a fast version. With Psyco this same version can become quite faster. Bye, bearophile from array import array class ToBinary(object): ToBinary: class to convert a given string to a binary string. def __init__(self): _nibbles = {0:, 1:0001, 2:0010, 3:0011, 4:0100, 5:0101, 6:0110, 7:0111, 8:1000, 9:1001, A:1010, B:1011, C:1100, D:1101, E:1110, F:} self._bytes = [.join(_nibbles[h] for h in %X%i).zfill(8) for i in xrange(256)] def conv(self, s): if s: result = [self._bytes[el] for el in array(B, s)] result[0] = result[0].lstrip(0) return .join(result) else: return 0 # Tests Conv2 = ToBinary() data = [, a, b, ab, hello, 123456789] for s in data: print s, Conv2.conv(s) -- http://mail.python.org/mailman/listinfo/python-list
Re: How to Convert a string into binary
HNT20 [EMAIL PROTECTED] wrote: i am new to python language. i am working on a gnuradio project where it uses python as the primary programming language. i am trying to convert a message, text, or numbers into binary code so that i can process it. umm. characters and numbers are stored in binary code, inside your com- puter. what exactly makes you think you have to convert them to binary strings in order to process them ? /F -- http://mail.python.org/mailman/listinfo/python-list
Re: py2exe problem
bwaha wrote: First time trying to create an executable with py2exe. I have a small program which makes use of python23 (2.3.5?), wxpython ('2.6.2.1'), matplotlib ('0.83.2'), win32com (latest?), Numeric ('23.7') on Windows XP Win2000. The program runs without problem but as an exe it doesn't even get to showing the GUI. Do you have more than one wxwindows installed? Check you site-packages. Do you follow documentation http://wiki.wxpython.org/index.cgi/MultiVersionInstalls ? Seems like py2exe picks wrong wxwindows. Insert printing of wx.VERSION and wx.PlatformInfo and try to run it packaged and non-packaged. Serge -- http://mail.python.org/mailman/listinfo/python-list
Best wx IDE
Hi, which is the best wx IDE for GUI development? Thanks. -- http://mail.python.org/mailman/listinfo/python-list
Re: Announce: Construct's wiki!
[EMAIL PROTECTED] wrote: tomer so now we have one place where people can share inventory tomer constructs, questions-and-answers, patches, documentation and tomer more. enjoy. I've never seen Construct before, but when you say parser I think of parsing programming languages. The couple of examples on the Construct wiki look more like what I'd use the struct module for. Kind of. Except that struct module does not scale and is less readable. You can say struct is not pythonic, construct is. IMHO construct is a good candidate for stdlib Serge. -- http://mail.python.org/mailman/listinfo/python-list
Python used to animate a compiled C program
SailChallenge was originally a program in C. It simulates a sailboat being navigated by an ANN (Artificial Neural Network). Now a Python front end has been created which invokes the compiled C program, and then captures the real time text output, converting it into an animation. A screen shot can be seen on our website. SailChallenge-2.0 is a free download from http://sourceforge.net/projects/annevolve. All source code is included, both C and Python. It will run on linux or Windows. Windows .exe files are available for Windows users who don't wish to compile the C code. Mitchell Timin -- I'm proud of http://ANNEvolve.sourceforge.net. If you want to write software, or articles, or do testing or research for ANNEvolve, let me know. Humans may know that my email address is: (but remove the 3 digit number) zenguy at shaw666 dot ca -- http://mail.python.org/mailman/listinfo/python-list
Re: How to Convert a string into binary
[EMAIL PROTECTED] wrote: If (assuming this is correct, you can do more tests) the given strings are many and/or long, this can be a fast version. With Psyco this same version can become quite faster. Bye, bearophile from array import array class ToBinary(object): ToBinary: class to convert a given string to a binary string. def __init__(self): _nibbles = {0:, 1:0001, 2:0010, 3:0011, 4:0100, 5:0101, 6:0110, 7:0111, 8:1000, 9:1001, A:1010, B:1011, C:1100, D:1101, E:1110, F:} self._bytes = [.join(_nibbles[h] for h in %X%i).zfill(8) for i in xrange(256)] def conv(self, s): if s: result = [self._bytes[el] for el in array(B, s)] result[0] = result[0].lstrip(0) return .join(result) else: return 0 # Tests Conv2 = ToBinary() data = [, a, b, ab, hello, 123456789] for s in data: print s, Conv2.conv(s) Thanks you very much, i will give this code a try. i hope it will work. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to Convert a string into binary
Rune Strand wrote: HNT20 wrote: Hello All def ascii_to_bin(char): ascii = ord(char) bin = [] while (ascii 0): if (ascii 1) == 1: bin.append(1) else: bin.append(0) ascii = ascii 1 bin.reverse() binary = .join(bin) zerofix = (8 - len(binary)) * '0' return zerofix + binary some_string = 'Time to go now, Rummy?' binary = [] for char in some_string: binary.append(ascii_to_bin(char)) print binary print .join(binary) some_string = 'Time to go now, Rummy?' binary = [] for char in some_string: binary.append(ascii_to_bin(char)) print binary print .join(binary) ['01010100', '01101001', '01101101', '01100101', '0010', '01110100', '0110', '0010', '01100111', '0110', '0010', '01101110', '0110', '01110111', '00101100', '0010', '01010010', '01110101', '01101101', '01101101', '0001', '0011'] 01010100 01101001 01101101 01100101 0010 01110100 0110 0010 01100111 0110 0010 01101110 0110 01110111 00101100 0010 01010010 01110101 01101101 01101101 0001 0011 Thanks very much. this code looks really promising. i will try to implement this code and see if i get any luck HNT -- http://mail.python.org/mailman/listinfo/python-list
Re: How to Convert a string into binary
Felipe Almeida Lessa wrote: Em Sáb, 2006-04-15 às 19:25 +, HNT20 escreveu: is there a way to convert a string into its binary representation of the ascii table.?? I'm very curious... why? And no, I don't have the answer. well, once i get the binary representations, i can group the data and modulate it to a higher frequency and transmit it for example, if i am using BPSK modulation, i will then convert each zero into -1 and multiply it with the sin function with the sampling frequency with a hamming window. and so forth. yet, the first step is to have a successful representation of the data. HNT -- http://mail.python.org/mailman/listinfo/python-list
Re: How to Convert a string into binary
HNT20 [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] i am new to python language. i am working on a gnuradio project where it uses python as the primary programming language. i am trying to convert a message, text, or numbers into binary code so that i can process it. hi -- 011011101001 I would start by making a lookup table to translate the ordinals of ascii chars to binary strings: a2b = ['', '0001', '0010', etc ... using something that generates the binary strings (such as that posted). If you don't want any or all of the initial 32 control chars translated, replace the corresponding string with ''. Then your main program is very simple: # given string s binchars = [] for c in s: binchars.append(a2b[ord(c)]) #if you really then need one long string instead of the list of strings longstring = ''.join(binchars) #or use any other connector than '', such as ' '. Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: Help with python output redirection
On 16/04/2006 12:36 AM, fatal.serpent top-posted: Thank you. Also this script is PublicDomain right? Wrong. If you attempt to turn The D'Aprano Code into a best-seller, and don't donate assign all of your royalties to the PSF, they will pursue you and your descendants to the ends of the universe. Steven D'Aprano wrote: On Fri, 14 Apr 2006 16:59:13 -0700, fatalserpent wrote: [snip] From the shell, you are probably doing something like this: $ python mymodule.py Change it to this: $ python mymodule.py 2 $ python 2 3 $ python 3 4 and so on. Alternatively, you can do this: x = ['f = file(2, w)', 'print f, x =, x', 'for m in x: f, print m'] print f, x =, x for m in x: print f, m I'll leave changing the file name from 2 to 3 etc. as an exercise for you. -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
shutil.copy time stamp errors on win XP
I'm working on various backup scripts, using filecmp and shutil. When I run a script to copy files to a mapped network drive, shutil creates a backup file with a date of 2002 or so. If I use shutil.copy2 it copies the dates of the original files, but creates folders with similary old dates and times. Anybody ever seen that before? My system clock is fine. I don't know what else to try. Thanks for any help. rick -- http://mail.python.org/mailman/listinfo/python-list
Re: shutil.copy time stamp errors on win XP
Hi! Warning : Win-XP manage many date/time for files : creation, last access, last modification, year (?), day of photo And, this can to change, depending on format of disk (NTFS, FAT, etc.) and/or type of files (Jpeg, exe, etc.) On a LAN, the date/time can also to depend of the date/time and the time zone from the server (and, perhaps, from the domain). @-salutations MCI *sorry for my bad english* -- http://mail.python.org/mailman/listinfo/python-list
Re: Calling Python from Matlab
I'm afraid I can't be very helpful to you, but you could be most helpful to some of us. Can you elaborate on what specifically you found difficult? In some circles Python is regarded as a direct competitor to Matlab. Your preference for Python for other things than standard mathematical work in a scientific or engineering context could be most useful if you have some real-world examples. Also, can you elaborate on what (if anything) it is about Matlab that you feel you can't replicate in Python? Are you aware of matplotlib and numpy? thanks mt -- http://mail.python.org/mailman/listinfo/python-list
Re: shutil.copy time stamp errors on win XP
Thank you! I went into the set up of my network storage device and found the time settings all wrong. Fixed it. Sorry for the trouble. rick -- http://mail.python.org/mailman/listinfo/python-list
Re: How to Convert a string into binary
Em Sáb, 2006-04-15 às 18:09 -0400, Terry Reedy escreveu: # given string s binchars = [] for c in s: binchars.append(a2b[ord(c)]) Faster: binchars = [a2b[ord(c)] for c in s] -- Felipe. -- http://mail.python.org/mailman/listinfo/python-list
Re: Calling Python from Matlab
I have a suspicion it is the collaborative effort that is the problem here -- I try to use Python whenever possible for engineering/numerical analysis, but the established industry standard (for most disciplines of engineering) is still MATLAB. Although Python is arguably better in most respects, especially being a full-blown programming language (and modules such as SciPy and NumPy are just great), but it's hard to expect your co-workers to be using Python for analysis also. On 15 Apr 2006 16:00:08 -0700, Michael Tobis [EMAIL PROTECTED] wrote: I'm afraid I can't be very helpful to you, but you could be most helpful to some of us. Can you elaborate on what specifically you found difficult? In some circles Python is regarded as a direct competitor to Matlab. Your preference for Python for other things than standard mathematical work in a scientific or engineering context could be most useful if you have some real-world examples. Also, can you elaborate on what (if anything) it is about Matlab that you feel you can't replicate in Python? Are you aware of matplotlib and numpy? thanks mt -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Async Sleep?
Hi all, Does a async sleep exist? How to check this every 10 sec, but that the CPU is free? Code: import win32com.client import time import os Document = win32com.client.Dispatch('MaxIm.Document') Application = win32com.client.dynamic.Dispatch('MaxIm.Application') path_to_watch = F:/Images/VRT/ before = dict ([(f, None) for f in os.listdir (path_to_watch)]) ##check this every 10 sec after = dict ([(f, None) for f in os.listdir (path_to_watch)]) added = [f for f in after if not f in before] if added: name= ' ,'.join (added) print name if str(name[-3:])=='fit': Document.OpenFile('F:/Images/VRT/'+name) Document.SaveFile('F:/Images/VRT/'+ str(name[0:-4])+'.jpeg', 6, False) Application.CloseAll() before = after Tkank You! Regards, Aleksandar -- http://mail.python.org/mailman/listinfo/python-list
multiple parameters in if statement
I am trying to make an if-statement that will not do anything and print 'nothing entered' if there is nothing entered in a form. I have the following code that does that, however, now even if I enter something into the form, the code still outputs 'nothing entered'. This violates the if statement and I am wondering what I did wrong. if form.has_key(delete_id) and form[delete_id].value != and form.has_key(delete_date) and form[delete_date].value != and form.has_key(delete_purchasetype) and form[delete_purchasetype].value != and form.has_key(delete_price) and form[delete_price].value != and form.has_key(delete_comment) and form[delete_comment].value != : delete_id=form['delete_id'].value delete_date=form['delete_date'].value delete_purchasetype=form['delete_purchasetype'].value delete_price=form['delete_price'].value delete_comment=form['delete_comment'].value else: print ERROR: Nothing entered! raise Exception -- http://mail.python.org/mailman/listinfo/python-list
Re: How to Convert a string into binary
On 16/04/2006 5:25 AM, HNT20 wrote: hi -- 011011101001 This implies that the bits in a byte are transmitted MSB first. I haven't done anything anywhere near this area since about the time that acoustic couplers went the way of buggy whips, but my vague recollection is LSB first. -- http://mail.python.org/mailman/listinfo/python-list
Re: multiple parameters in if statement...
Kun wrote: I am trying to make an if-statement that will not do anything and print 'nothing entered' if there is nothing entered in a form. I have the following code that does that, however, now even if I enter something Yes, but did you enter everything? into the form, the code still outputs 'nothing entered'. The logic doesn't imply nothing, it implies not everything. The else clause will execute if ANY item is not enetered. This violates the if statement and I am wondering what I did wrong. if form.has_key(delete_id) and form[delete_id].value != and form.has_key(delete_date) and form[delete_date].value != and form.has_key(delete_purchasetype) and form[delete_purchasetype].value != and form.has_key(delete_price) and form[delete_price].value != and form.has_key(delete_comment) and form[delete_comment].value != : delete_id=form['delete_id'].value delete_date=form['delete_date'].value delete_purchasetype=form['delete_purchasetype'].value delete_price=form['delete_price'].value delete_comment=form['delete_comment'].value else: print ERROR: Nothing entered! raise Exception -- http://mail.python.org/mailman/listinfo/python-list
Re: symbolic links, aliases, cls clear
On 2006-04-13, Barry Margolin wrote: In article [EMAIL PROTECTED], Chris F.A. Johnson [EMAIL PROTECTED] wrote: In fact, my scripts are portable to other terminal types by use of files for each terminal, generated with tput. Using a different terminal is as easy as . /usr/share/term-sh/$TERM or something similar. I generated a lot of files a few years ago, but I have never had any call for them, so I'd have to hunt for them. So you've essentially reinvented the whole termcap/terminfo mechanism? No, I've used the termcap/terminfo mechanism via tput to create a more efficient (and customizable) method of terminal-dependent control. -- Chris F.A. Johnson, author |http://cfaj.freeshell.org Shell Scripting Recipes: | My code in this post, if any, A Problem-Solution Approach | is released under the 2005, Apress | GNU General Public Licence -- http://mail.python.org/mailman/listinfo/python-list
Re: The whitespaceless frontend
Stelios == Stelios Xanthakis [EMAIL PROTECTED] writes: Stelios It had to happen :) http://pyvm32.infogami.com/EPL Stelios Seriously, this is not so much about the whitespace as Stelios for the new features, which might interest people who are Stelios thinking about new features. More specifically, methods Stelios and the $ operator are really great and seem to solve Stelios the problem with having to type self. all the time. Stelios The new syntax has been tested in core libraries of pyvm. Stelios Feedback is welcome, but preferably not in c.l.py because Stelios indentation can be a dangerous topic :) Stelios Cheers, Stelios Stelios I submit that this kind of work will make generated code a lot easier. There is this perverse joy I take in writing polyglot code, but I wouldn't want to consider, say, some kind of UML model-driven python code generator--the significant whitespace that's so dandy on the human eye would be un-fun for non-trivial code. Props, Chris -- http://mail.python.org/mailman/listinfo/python-list
Re: Help with python output redirection
On Sat, 15 Apr 2006 07:36:30 -0700, fatal.serpent wrote: Thank you. Also this script is PublicDomain right? Oh heavens, I never even thought about that... the world was a much better place when you actually needed to *claim copyright* rather than just have it apply automatically on every stupid little doodle or comment. I've heard from authorities I trust that under US law private citizens can't not copyright something you write, even if you want it to go into the Public Domain. I've also heard the opposite from experts I equally trust. So, let me say firstly that I wish the following code to be put into the public domain, and if there is any reason why it has not been, I hereby give everybody an unlimited, non-exclusive, transferable, free of all charges and royalties, licence to use the following code in any way they see fit, with no conditions attached except there is no warranty. You don't even have to credit me. If you try to make a warranty claim against me for this code, the licence is instantly revoked. There. It probably won't stand up in a court of law, but I promise not to sue if you promise the same. Steven D'Aprano wrote: On Fri, 14 Apr 2006 16:59:13 -0700, fatalserpent wrote: Here is the basic code (yes, I know its tiny). x = ['print x =, x', 'for m in x: print m'] print x =, x for m in x: print m I want to modify this so it will output to a file called 1. What I want is to have that file direct its output to a file called 2 and 2 direct to 3 and so on. Hopefully this will be an easy-to-answer question. THX in advance. From the shell, you are probably doing something like this: $ python mymodule.py Change it to this: $ python mymodule.py 2 $ python 2 3 $ python 3 4 and so on. Alternatively, you can do this: x = ['f = file(2, w)', 'print f, x =, x', 'for m in x: f, print m'] print f, x =, x for m in x: print f, m I'll leave changing the file name from 2 to 3 etc. as an exercise for you. -- Steven. -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
Re: multiple parameters in if statement...
[EMAIL PROTECTED] wrote: Kun wrote: I am trying to make an if-statement that will not do anything and print 'nothing entered' if there is nothing entered in a form. I have the following code that does that, however, now even if I enter something Yes, but did you enter everything? into the form, the code still outputs 'nothing entered'. The logic doesn't imply nothing, it implies not everything. The else clause will execute if ANY item is not enetered. This violates the if statement and I am wondering what I did wrong. if form.has_key(delete_id) and form[delete_id].value != and form.has_key(delete_date) and form[delete_date].value != and form.has_key(delete_purchasetype) and form[delete_purchasetype].value != and form.has_key(delete_price) and form[delete_price].value != and form.has_key(delete_comment) and form[delete_comment].value != : delete_id=form['delete_id'].value delete_date=form['delete_date'].value delete_purchasetype=form['delete_purchasetype'].value delete_price=form['delete_price'].value delete_comment=form['delete_comment'].value else: print ERROR: Nothing entered! raise Exception How do I make this so that it only prints 'nothing entered' when none of the fields are entered? -- http://mail.python.org/mailman/listinfo/python-list
Re: print without newline halts program execution
Jay Parlar [EMAIL PROTECTED] wrote in news:[EMAIL PROTECTED]: Your problem is that the 'print' statement is sending the text to sys.stdout, and sys.stdout is buffered. I thought it was something like this, but I couldn't find it in the docs : (. print 'Start: %f,'% st, sys.stdout.flush() sleep(10) sp = time() print 'Stop: %f, Duration: %f' % (sp, (st-sp)) This works excellent, *thank* you. There are other ways to do this, but try this: And for purely academical purposes, what are those other ways to do it? I'm curious :). -- ___Karlo Lozovina - Mosor | | |.-.-. web: http://www.mosor.net || ICQ#: 10667163 | || _ | _ | Parce mihi domine quia Dalmata sum. |__|_|__||_|_| -- http://mail.python.org/mailman/listinfo/python-list
Re: multiple parameters in if statement
On Sat, 15 Apr 2006 20:28:47 -0400, Kun wrote: I am trying to make an if-statement that will not do anything and print 'nothing entered' if there is nothing entered in a form. I have the following code that does that, however, now even if I enter something into the form, the code still outputs 'nothing entered'. This violates the if statement and I am wondering what I did wrong. if form.has_key(delete_id) and form[delete_id].value != and form.has_key(delete_date) and form[delete_date].value != and form.has_key(delete_purchasetype) and form[delete_purchasetype].value != and form.has_key(delete_price) and form[delete_price].value != and form.has_key(delete_comment) and form[delete_comment].value != : delete_id=form['delete_id'].value delete_date=form['delete_date'].value delete_purchasetype=form['delete_purchasetype'].value delete_price=form['delete_price'].value delete_comment=form['delete_comment'].value else: print ERROR: Nothing entered! raise Exception That's rather, um, unfortunate looking code. Instead of making lots of tests like this: if form.has_key(key) and form[key].value != ... you might find it useful to create a helper function: def get(form, key): if form.has_key(key): return form[key].value else: return Now you don't need to test for existence and non-emptiness, because missing values will be empty. You just use it like this: if get(form, key) != and ... Using the get helper function, your test becomes much simpler: if get(form, delete_id) != and get(form, delete_date) != \ and get(form, delete_purchasetype) != and \ get(form, delete_price) != and get(form, delete_comment) != : do_something() else: raise ValueError(nothing entered) But that's still too complicated. In Python, every object can be tested by if...else directly. Strings are all True, except for the empty string, which is False. As an experiment, try this: if something: print Something is not nothing. else: print Empty string. if : print Something is not nothing else: print Empty string. So your if...else test becomes simpler: if get(form, delete_id) and get(form, delete_date) and \ get(form, delete_purchasetype) and get(form, delete_price) and \ get(form, delete_comment): do_something() else: raise ValueError(nothing entered) Now your test checks that every field is non-empty, and if so, calls do_something(), otherwise it raises an error. But in fact, that gets the logic backwards. You want to raise an error only if every field is empty. So your test becomes: if get(form, delete_id) or get(form, delete_date) or \ get(form, delete_purchasetype) or get(form, delete_price) or \ get(form, delete_comment): do_something() else: raise ValueError(nothing entered) -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to Convert a string into binary
The short version: def str2bin(s): return ''.join([''.join(['10'[not (mord(x))] for m in (128,64,32,16,8,4,2,1)]) for x in s]) Notes: Split into 3 lines for newsgroup post, 3rd line is actually the end of the 2nd. It will run as shown above. Returns digits in MSB order, to return LSB first, reverse the order of the bit weights. (1,2,4,8,16,32,64,128) To support 16-bit Unicode, add powers of two to the bit weights up to 32768. To put a separator between digits for each character put it between first set of empty quote chars. ',' - ',' To put a separator between digits of the same character, put it between the second set of empty quotes. '.' - '0.1.0.1.0.1.0.1' This is probably slower than one based on lookup tables like the others are proposing. -- Jesse Hager email = [EMAIL PROTECTED].decode(rot13) -- http://mail.python.org/mailman/listinfo/python-list
Why aren't these more popular (Myghty Pylons)?
I've been browsing what Python has to offer in the world of web programming for past few weeks, while preparing to select something for small, quick and dirty projects where my favorable solution, Zope3, is an overkill. There sure are handfull of solutions out there, but I didn't quite like any of them, starting from those with more of a framework approach (TG, Django, ...), and ending with really small ones, like Karrigell and Webpy. Ofourse, I haven't tested each and everyone, but I've read a lot of docs, and even more examples (Btw, those TG screencasts are really awesome for introduction), and found nothing that 'fits my brain' :). But, reading some old posts on c.l.py I found out about Myghty (http://www.myghty.org), and by reading the docs and examples, I came to like it. First of all, it's built with HTML::Mason as a role model, and although I haven't worked with Mason first hand, I heard about quite a few success stories. Besides that, the idea of components and MVC is also a plus in my book, API is quite clear and the documentation is really useful. It is hard to explain, but I fell in love at the first sight :). There's only one thing bothering me, and that is it's lack of publicity. There are only few posts on thig NG with some refference to Myghty, and even less when it comes to Pylons (http://pylonshq.com/), framework built on top of Myghy. Myghy project isn't that new to explain why people don't know about it, so is something fundamentaly wrong with it? Anyway, to make a long story short, those who haven't heard about it, be sure to check it out, you just might like it, but I would really like to hear from people (if there are such) using it in real world applications... -- ___Karlo Lozovina - Mosor | | |.-.-. web: http://www.mosor.net || ICQ#: 10667163 | || _ | _ | Parce mihi domine quia Dalmata sum. |__|_|__||_|_| -- http://mail.python.org/mailman/listinfo/python-list
Re: How to Convert a string into binary
On 2006-04-16, John Machin [EMAIL PROTECTED] wrote: On 16/04/2006 5:25 AM, HNT20 wrote: hi -- 011011101001 This implies that the bits in a byte are transmitted MSB first. I haven't done anything anywhere near this area since about the time that acoustic couplers went the way of buggy whips, but my vague recollection is LSB first. It depends. Normal UARTs send LSB first. Some other types of serial links are MSB first. -- Grant Edwards [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: multiple parameters in if statement
On 16/04/2006 10:28 AM, Kun wrote: I am trying to make an if-statement that will not do anything and print 'nothing entered' if there is nothing entered in a form. I have the following code that does that, however, now even if I enter something into the form, the code still outputs 'nothing entered'. This violates the if statement and I am wondering what I did wrong. if form.has_key(delete_id) and form[delete_id].value != and Unless your code needs to run on Python 2.1, consider using the key in dict construct instead of dict.has_key(key) -- it's not only less wear and tear on the the eyeballs and fingers, it's faster. Python 2.1.3 (#35, Apr 8 2002, 17:47:50) [MSC 32 bit (Intel)] on win32 foo = {}; foo['bar'] = 'zot' foo.has_key('bar') 1 'bar' in foo Traceback (most recent call last): File stdin, line 1, in ? TypeError: 'in' or 'not in' needs sequence right argument Python 2.2.3 (#42, May 30 2003, 18:12:08) [MSC 32 bit (Intel)] on win32 foo = {}; foo['bar'] = 'zot' foo.has_key('bar') 1 'bar' in foo 1 -- http://mail.python.org/mailman/listinfo/python-list
Sending part of a page as the body of an email
I currently have a python-cgi script that extracts data from a mysql table. I would like to save this data as a string and send it to a recipient via email. I know how to send email using the smtp lib, but what I do not know his how to save a portion of the page as a string. Any pointers? -- http://mail.python.org/mailman/listinfo/python-list
Iterating through a nested list
I have a newbie question, and I have seen reference to this mentioned in many places, but all just say this has been discussed frequently in (other places) so we won't discuss it here... and I am unable to find the actual answer... I expected : Array = [topdir, [/subdir1, [/file1, /file2], /subdir2, [/file1, /file2], /subdir3, [/file1, /file2]]] for i in range(len(Array)): print Array[i] for x in range(len(Array[i])): print Array[i][x] for y in range(len(Array[i][x])): print Array[i][x][y] to produce output like this: topdir ['/subdir1', ['/file1', '/file2'], '/subdir2', ['/file1', '/file2'], '/subdir3', ['/file1', '/file2']] /subdir1 ['/file1', '/file2'] /file1 /file2 /subdir2 ['/file1', '/file2'] /file1 /file2 /subdir3 ['/file1', '/file2'] /file1 /file2 but instead, it is iterating through each character in the elements, like this: topdir t t o o p p d d i i r r ['/subdir1', ['/file1', '/file2'], '/subdir2', ['/file1', '/file2'], '/subdir3', ['/file1', '/file2']] /subdir1 / s u b d i r 1 ['/file1', '/file2'] /file1 /file2 /subdir2 / s u b d i r 2 ['/file1', '/file2'] /file1 /file2 /subdir3 / s u b d i r 3 ['/file1', '/file2'] /file1 /file2 so what am I doing wrong? I would really appreciate any advice or pointers... Thanks! -- http://mail.python.org/mailman/listinfo/python-list
Re: multiple parameters in if statement
Try this: if form.get(delete_id,) != and form.get(delete_data,) != and... the get method lets you have an optional second argument that gets returned if the key is not in the dictionary. Also, am I reading your code right? If I enter some fields but not all, you print a message that says Nothing entered. Nothing? The other thing I'd recommend is stick that long list of fields in a list, and then do operations on that list: fields = ['delete_id', 'delete_date', 'delete_purchasetype', 'delete_price', 'delete_comment'] then to see if all those fields are empty: everything = for field in fields: everything += form.get(field,) if everything == : print Absolutely nothing entered! Kun wrote: I am trying to make an if-statement that will not do anything and print 'nothing entered' if there is nothing entered in a form. I have the following code that does that, however, now even if I enter something into the form, the code still outputs 'nothing entered'. This violates the if statement and I am wondering what I did wrong. if form.has_key(delete_id) and form[delete_id].value != and form.has_key(delete_date) and form[delete_date].value != and form.has_key(delete_purchasetype) and form[delete_purchasetype].value != and form.has_key(delete_price) and form[delete_price].value != and form.has_key(delete_comment) and form[delete_comment].value != : delete_id=form['delete_id'].value delete_date=form['delete_date'].value delete_purchasetype=form['delete_purchasetype'].value delete_price=form['delete_price'].value delete_comment=form['delete_comment'].value else: print ERROR: Nothing entered! raise Exception -- http://mail.python.org/mailman/listinfo/python-list
My python can not get addr info
D:\python24\Lib\idlelibpyshell.py Traceback (most recent call last): File D:\python24\Lib\idlelib\PyShell.py, line 1388, in ? main() File D:\python24\Lib\idlelib\PyShell.py, line 1361, in main if not flist.open_shell(): File D:\python24\Lib\idlelib\PyShell.py, line 277, in open_shell if not self.pyshell.begin(): File D:\python24\Lib\idlelib\PyShell.py, line 962, in begin client = self.interp.start_subprocess() File D:\python24\Lib\idlelib\PyShell.py, line 389, in start_subprocess self.rpcclt.accept() File D:\python24\lib\idlelib\rpc.py, line 524, in accept working_sock, address = self.listening_sock.accept() File D:\python24\lib\socket.py, line 169, in accept sock, addr = self._sock.accept() socket.gaierror: (10104, 'getaddrinfo failed') D:\python24\Lib\idlelib -- http://mail.python.org/mailman/listinfo/python-list
My python can not get addr info
D:\python24\Lib\idlelibpyshell.py Traceback (most recent call last): File D:\python24\Lib\idlelib\PyShell.py, line 1388, in ? main() File D:\python24\Lib\idlelib\PyShell.py, line 1361, in main if not flist.open_shell(): File D:\python24\Lib\idlelib\PyShell.py, line 277, in open_shell if not self.pyshell.begin(): File D:\python24\Lib\idlelib\PyShell.py, line 962, in begin client = self.interp.start_subprocess() File D:\python24\Lib\idlelib\PyShell.py, line 389, in start_subprocess self.rpcclt.accept() File D:\python24\lib\idlelib\rpc.py, line 524, in accept working_sock, address = self.listening_sock.accept() File D:\python24\lib\socket.py, line 169, in accept sock, addr = self._sock.accept() socket.gaierror: (10104, 'getaddrinfo failed') D:\python24\Lib\idlelib -- http://mail.python.org/mailman/listinfo/python-list
Re: My python can not get addr info
一首诗 wrote: socket.gaierror: (10104, 'getaddrinfo failed') You're using a buggy firewall, write to your firewall vendor about this bug. IDLE shell is making a connection over loopback network interface in other words making a connection from your computer to your computer, this type of connection should not be blocked by a firewall. -- http://mail.python.org/mailman/listinfo/python-list
Re: Iterating through a nested list
On Sat, 15 Apr 2006 22:36:17 -0500, CamelR wrote: I have a newbie question, and I have seen reference to this mentioned in many places, but all just say this has been discussed frequently in (other places) so we won't discuss it here... and I am unable to find the actual answer... I expected : Array = [topdir, [/subdir1, [/file1, /file2], /subdir2, [/file1, /file2], /subdir3, [/file1, /file2]]] for i in range(len(Array)): print Array[i] for x in range(len(Array[i])): print Array[i][x] for y in range(len(Array[i][x])): print Array[i][x][y] If you don't actually need the index of each item, don't use for i in range(), just iterate over the list: for obj in Array: print obj Notice that your list has two items, the first is a string and the second is a sub-list. The natural way of proceeding would be: for obj in Array: for item in obj: print item but that gives too much: it iterates over the string, giving you individual characters. Instead, do this: for obj in Array: if isinstance(obj, list): for item in obj: print item else: print obj which helps, but not enough: it only prints two levels down, and your data has three. This time -- next time it might have two, or fifteen, or one... Instead, create a helper function like this: def walk(seq): Walk over a sequence of items, printing each one in turn, and recursively walking over sub-sequences. print seq if isinstance(seq, list): for item in seq: walk(item) Notice that this function calls itself. This version of walk() prints the entire sequence at every level. Here is a version which doesn't: def walk2(seq): if isinstance(seq, list): for item in seq: walk2(item) else: print seq -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
List operation: Removing an item
Hi, I've been (self) studying Python for the past two months and I have had no background in OOP whatsoever. I was able to write an interactive program that randomly selects an item from a list. From a Main Menu, the user has the option to add items to an empty list, show the list, run the random selector, and of course quit the program. The program also complains if a user tries to add an item that is already in the list prompting the user to enter another item. I am trying to create a function that removes an item as specified by the user. Apparently, the list operation del list[:] deletes the entire list. Below is the sample function. Any ideas, suggestions, or tips on the list operation I should be using, or a better way of writing this? TIA shopList = ['eggs', 'milk', 'bread', 'juice', 'fruit', 'deli'] def removeItem(): Remove an item from the list print for items in shopList: print items print dlete = raw_input(Enter the item you want to remove: ) print for item in shopList: if dlete in shopList: del shopList[:] # --What is the correct function to use? print %s has been removed % dlete print The new list is now, shopList else: print Item is not in the list -- http://mail.python.org/mailman/listinfo/python-list
Re: Numpy and cPickle
Martin Manns wrote: Robert Kern wrote: Martin Manns wrote: If I cPickle a numpy array under Linux and un-cPickle it under Solaris 10, my arrays seem to be transposed. Transposed? That's odd. There was a byteorder issue with pickles going across differently-endianed platforms that was fixed in the past few days. Could you come up with a small bit of code that shows the problem and post it and the incorrect output to the bug tracker? Sorry, I my ad-hoc small example does not reproduce the error even though the files generated on both platforms differ. I will try to set up the code tomorrow. Somehow, the bug does not show up any more. I believe it was due to the numpy version that is fetched by cPickle. Is there any way to control (or even determine), which library version cPickle grabs for unpickling a numpy array (numpy, scipy, etc)? -- http://mail.python.org/mailman/listinfo/python-list
Re: List operation: Removing an item
On Sat, 15 Apr 2006 22:39:37 -0600, Miguel E. wrote: I am trying to create a function that removes an item as specified by the user. Apparently, the list operation del list[:] deletes the entire list. Below is the sample function. If you know the value of the item, and not its position: somelist.remove(value) This will raise an exception if value is not in somelist. If you know the item's position: del somelist[position] or somelist[position:position+1] = [] or even: somelist = somelist[:position] + somelist[position+1:] (That last example is quite inefficient for lists, but it is a useful technique to remember for immutable sequences like strings.) -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
Re: Why aren't these more popular (Myghty Pylons)?
Karlo Lozovina wrote: There's only one thing bothering me, and that is it's lack of publicity. There are only few posts on thig NG with some refference to Myghty, and even less when it comes to Pylons (http://pylonshq.com/), framework built on top of Myghy. Myghy project isn't that new to explain why people don't know about it, so is something fundamentaly wrong with it? The whims of mindshare are indeed mysterious. Anyway, to make a long story short, those who haven't heard about it, be sure to check it out, you just might like it, but I would really like to hear from people (if there are such) using it in real world applications... http://techspot.zzzeek.org/index.php?/archives/7-Bittorrent.com,-running-Myghty-Again.html -Jonathan -- http://mail.python.org/mailman/listinfo/python-list
Re: Numpy and cPickle
Mr. M wrote: Somehow, the bug does not show up any more. I believe it was due to the numpy version that is fetched by cPickle. Is there any way to control (or even determine), which library version cPickle grabs for unpickling a numpy array (numpy, scipy, etc)? You can import the appropriate module first. Then it will be in sys.modules and be picked up during unpickling. You may have to do some sys.path manipulation if you have more than one version lieing about on your filesystem. -- Robert Kern [EMAIL PROTECTED] I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth. -- Umberto Eco -- http://mail.python.org/mailman/listinfo/python-list
Re: List operation: Removing an item
Miguel E. [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Hi, I've been (self) studying Python for the past two months and I have had no background in OOP whatsoever. I was able to write an interactive program that randomly selects an item from a list. From a Main Menu, the user has the option to add items to an empty list, show the list, run the random selector, and of course quit the program. The program also complains if a user tries to add an item that is already in the list prompting the user to enter another item. Do you really need the items sorted? I strongly suspect that a set would work better. Much easier to randomly add, delete, and check membership. Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
[ python-Bugs-1464056 ] curses library in python 2.4.3 broken
Bugs item #1464056, was opened at 2006-04-04 10:47 Message generated for change (Comment added) made by loewis You can respond by visiting: https://sourceforge.net/tracker/?func=detailatid=105470aid=1464056group_id=5470 Please note that this message will contain a full copy of the comment thread, including the initial issue submission, for this request, not just the latest update. Category: Python Library Group: Python 2.4 Status: Open Resolution: None Priority: 5 Submitted By: nomind (vnainar) Assigned to: Nobody/Anonymous (nobody) Summary: curses library in python 2.4.3 broken Initial Comment: My python programs using curses library do not work with version 2.4.3.Even the 'ncurses.py ' demo program in the Demo/curses directory does not work correctly. The problem seems to be in the 'panels' library -- Comment By: Martin v. Löwis (loewis) Date: 2006-04-15 09:05 Message: Logged In: YES user_id=21627 I couldn't reproduce the problem on a Linux console (although my console had a different size); so it remains unreproducable for me. -- Comment By: nomind (vnainar) Date: 2006-04-13 13:00 Message: Logged In: YES user_id=1493752 Well , it is the linux console (in VGA mode ). The local is en_US.The size of the console is 100X37. -- Comment By: Martin v. Löwis (loewis) Date: 2006-04-11 07:32 Message: Logged In: YES user_id=21627 Ah, ok. vnainar, atler_: What terminal had you been using to make it crash? What is your locale? Any other conditions that might be relevant (e.g. dimension of the terminal)? -- Comment By: nomind (vnainar) Date: 2006-04-11 07:13 Message: Logged In: YES user_id=1493752 Removing 'ncursesw' (there are two references to it in 'setup.py') seems to solve the problem. I noticed one more oddity. Even before the above recompilation , it ran fine on an Xterm ! -- Comment By: Martin v. Löwis (loewis) Date: 2006-04-11 00:28 Message: Logged In: YES user_id=21627 That's hard to tell. Somebody would have to debug ncurses to find out why it crashes. Notice that it crashes only on some installations, so it is likely rather a problem with your ncurses installation, than with Python (or even with ncurses itself). -- Comment By: Jan Palus (atler_) Date: 2006-04-10 23:24 Message: Logged In: YES user_id=1497957 loewis: removing lines refering to ncursesw solves the problem. ncurses.py runs fine as well as other programs. What is actual problem then? Something with ncursesw or with python? Anyway, Thanks for your help. -- Comment By: Martin v. Löwis (loewis) Date: 2006-04-09 22:58 Message: Logged In: YES user_id=21627 atler_: around line 427, you find if self.compiler.find_library_file(lib_dirs, 'ncursesw'): readline_libs.append('ncursesw') elif self.compiler.find_library_file(lib_dirs, 'ncurses'): Replace that with if self.compiler.find_library_file(lib_dirs, 'ncurses'): (i.e. dropping the ncursesw part), and rebuild. -- Comment By: Jan Palus (atler_) Date: 2006-04-09 15:48 Message: Logged In: YES user_id=1497957 More complete backtrace, I hope it will help: http://pastebin.com/649445 -- Comment By: Anthony Baxter (anthonybaxter) Date: 2006-04-09 14:14 Message: Logged In: YES user_id=29957 The buildbot boxes don't show this problem. You might need to rebuild a Python with -g and unstripped to get a useful backtrace. -- Comment By: Jan Palus (atler_) Date: 2006-04-09 12:51 Message: Logged In: YES user_id=1497957 $ ldd /usr/lib/python2.4/lib-dynload/_curses.so libncursesw.so.5 = /usr/lib/libncursesw.so.5 (0x7004c000) libpthread.so.0 = /lib/libpthread.so.0 (0x7008) libc.so.6 = /lib/libc.so.6 (0x700e4000) libdl.so.2 = /lib/libdl.so.2 (0x70228000) libtinfow.so.5 = /usr/lib/libtinfow.so.5 (0x7023c000) /lib/ld-linux.so.2 (0x7000) ... Program received signal SIGSEGV, Segmentation fault. 0x7063947c in hide_panel () from /usr/lib/libpanel.so.5 gdb) bt #0 0x7063947c in hide_panel () from /usr/lib/libpanel.so.5 #1 0x706254b8 in ?? () from /usr/lib/python2.4/lib-dynload/_curses_panel.so #2 0x706254b8 in ?? () from
[ python-Bugs-1470353 ] test_ctypes fails on FreeBSD 4.x
Bugs item #1470353, was opened at 2006-04-14 23:11 Message generated for change (Comment added) made by aimacintyre You can respond by visiting: https://sourceforge.net/tracker/?func=detailatid=105470aid=1470353group_id=5470 Please note that this message will contain a full copy of the comment thread, including the initial issue submission, for this request, not just the latest update. Category: None Group: None Status: Open Resolution: None Priority: 5 Submitted By: Andrew I MacIntyre (aimacintyre) Assigned to: Thomas Heller (theller) Summary: test_ctypes fails on FreeBSD 4.x Initial Comment: $ ./python Lib/test/regrtest.py test_ctypes test_ctypes test test_ctypes failed -- Traceback (most recent call last): File /home/andymac/dev/python-svn-head/Lib/ctypes/test/test_functions.py, line 333, in test_struct_return_2H self.failUnlessEqual((s2h.x, s2h.y), (99*2, 88*3)) AssertionError: (-1004, 2123) != (198, 264) 1 test failed: test_ctypes [41158 refs] This is with a subversion checkout updated to 5am AEST (Aust) 14Apr06, debug build. The returned tuple values (s2h.x, s2h.y) appear to vary from run to run, so it looks like something isn't where its expected. This is with a FreeBSD 4.8 i386 system (not particularly recent), using gcc 2.95.4. A quick and dirty test (in C) suggests that its not an alignment issue for the 2 shorts in the S2H struct. Ideas for trying to debug this further? -- Comment By: Andrew I MacIntyre (aimacintyre) Date: 2006-04-15 21:18 Message: Logged In: YES user_id=250749 Your suggested change does indeed get the test to pass on this system. Given the history and relationship of [Free/Net/Open]BSD, I would suggest that for x86 it is very likely that you will need to add defined(__NetBSD__) clauses as well. From my POV this bug can now be closed. Thanks, Thomas. BTW, the actual patch applied was: --- ffi.c.orig Tue Apr 4 05:26:32 2006 +++ ffi.c Sat Apr 15 21:02:16 2006 @@ -121,7 +121,7 @@ switch (cif-rtype-type) { case FFI_TYPE_VOID: -#if !defined(X86_WIN32) !defined(__OpenBSD__) +#if !defined(X86_WIN32) !defined(__OpenBSD__) !defined(__FreeBSD__) case FFI_TYPE_STRUCT: #endif case FFI_TYPE_SINT64: @@ -135,7 +135,7 @@ cif-flags = FFI_TYPE_SINT64; break; -#if defined(X86_WIN32) || defined(__OpenBSD__) +#if defined(X86_WIN32) || defined(__OpenBSD__) || defined(__FreeBSD__) case FFI_TYPE_STRUCT: if (cif-rtype-size == 1) { -- Comment By: Thomas Heller (theller) Date: 2006-04-15 05:09 Message: Logged In: YES user_id=11105 Of course I meant FreeBSD instead of NetBSD, sorry. -- Comment By: Thomas Heller (theller) Date: 2006-04-15 05:08 Message: Logged In: YES user_id=11105 This looks very similar to a problem I recently 'fixed' on OpenBSD - maybe it is even a bug in libffi. On OpenBSD x86 the problem seemed to be that small structures are passed like short or int. You could try to fix it by adding the appropriate definition in Modules/_ctypes/libffi/src/x86/ffi.c, at lines 124 and lines 138. Maybe changing them to #if !defined(X86_WIN32) !defined(__OpenBSD__) !defined(__NetBSD__) or whatever the magic symbol for Netbsd is. Unfortunately I do not have access to a netbsd machine myself. -- You can respond by visiting: https://sourceforge.net/tracker/?func=detailatid=105470aid=1470353group_id=5470 ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[ python-Bugs-1464056 ] curses library in python 2.4.3 broken
Bugs item #1464056, was opened at 2006-04-04 10:47 Message generated for change (Comment added) made by atler_ You can respond by visiting: https://sourceforge.net/tracker/?func=detailatid=105470aid=1464056group_id=5470 Please note that this message will contain a full copy of the comment thread, including the initial issue submission, for this request, not just the latest update. Category: Python Library Group: Python 2.4 Status: Open Resolution: None Priority: 5 Submitted By: nomind (vnainar) Assigned to: Nobody/Anonymous (nobody) Summary: curses library in python 2.4.3 broken Initial Comment: My python programs using curses library do not work with version 2.4.3.Even the 'ncurses.py ' demo program in the Demo/curses directory does not work correctly. The problem seems to be in the 'panels' library -- Comment By: Jan Palus (atler_) Date: 2006-04-15 16:48 Message: Logged In: YES user_id=1497957 Half day of debugging and it seems that I found an answer... just by accident ;). When curses module is linked against ncursesw it seems that it also should be linked against panelw not plain panel. After changing this in setup.py, ncurses.py demo finally runs fine. -- Comment By: Martin v. Löwis (loewis) Date: 2006-04-15 09:05 Message: Logged In: YES user_id=21627 I couldn't reproduce the problem on a Linux console (although my console had a different size); so it remains unreproducable for me. -- Comment By: nomind (vnainar) Date: 2006-04-13 13:00 Message: Logged In: YES user_id=1493752 Well , it is the linux console (in VGA mode ). The local is en_US.The size of the console is 100X37. -- Comment By: Martin v. Löwis (loewis) Date: 2006-04-11 07:32 Message: Logged In: YES user_id=21627 Ah, ok. vnainar, atler_: What terminal had you been using to make it crash? What is your locale? Any other conditions that might be relevant (e.g. dimension of the terminal)? -- Comment By: nomind (vnainar) Date: 2006-04-11 07:13 Message: Logged In: YES user_id=1493752 Removing 'ncursesw' (there are two references to it in 'setup.py') seems to solve the problem. I noticed one more oddity. Even before the above recompilation , it ran fine on an Xterm ! -- Comment By: Martin v. Löwis (loewis) Date: 2006-04-11 00:28 Message: Logged In: YES user_id=21627 That's hard to tell. Somebody would have to debug ncurses to find out why it crashes. Notice that it crashes only on some installations, so it is likely rather a problem with your ncurses installation, than with Python (or even with ncurses itself). -- Comment By: Jan Palus (atler_) Date: 2006-04-10 23:24 Message: Logged In: YES user_id=1497957 loewis: removing lines refering to ncursesw solves the problem. ncurses.py runs fine as well as other programs. What is actual problem then? Something with ncursesw or with python? Anyway, Thanks for your help. -- Comment By: Martin v. Löwis (loewis) Date: 2006-04-09 22:58 Message: Logged In: YES user_id=21627 atler_: around line 427, you find if self.compiler.find_library_file(lib_dirs, 'ncursesw'): readline_libs.append('ncursesw') elif self.compiler.find_library_file(lib_dirs, 'ncurses'): Replace that with if self.compiler.find_library_file(lib_dirs, 'ncurses'): (i.e. dropping the ncursesw part), and rebuild. -- Comment By: Jan Palus (atler_) Date: 2006-04-09 15:48 Message: Logged In: YES user_id=1497957 More complete backtrace, I hope it will help: http://pastebin.com/649445 -- Comment By: Anthony Baxter (anthonybaxter) Date: 2006-04-09 14:14 Message: Logged In: YES user_id=29957 The buildbot boxes don't show this problem. You might need to rebuild a Python with -g and unstripped to get a useful backtrace. -- Comment By: Jan Palus (atler_) Date: 2006-04-09 12:51 Message: Logged In: YES user_id=1497957 $ ldd /usr/lib/python2.4/lib-dynload/_curses.so libncursesw.so.5 = /usr/lib/libncursesw.so.5 (0x7004c000) libpthread.so.0 = /lib/libpthread.so.0 (0x7008) libc.so.6 = /lib/libc.so.6 (0x700e4000)
[ python-Bugs-1464056 ] curses library in python 2.4.3 broken
Bugs item #1464056, was opened at 2006-04-04 10:47 Message generated for change (Comment added) made by loewis You can respond by visiting: https://sourceforge.net/tracker/?func=detailatid=105470aid=1464056group_id=5470 Please note that this message will contain a full copy of the comment thread, including the initial issue submission, for this request, not just the latest update. Category: Python Library Group: Python 2.4 Status: Open Resolution: None Priority: 5 Submitted By: nomind (vnainar) Assigned to: Nobody/Anonymous (nobody) Summary: curses library in python 2.4.3 broken Initial Comment: My python programs using curses library do not work with version 2.4.3.Even the 'ncurses.py ' demo program in the Demo/curses directory does not work correctly. The problem seems to be in the 'panels' library -- Comment By: Martin v. Löwis (loewis) Date: 2006-04-15 17:30 Message: Logged In: YES user_id=21627 Good spotting! Can everybody please confirm that the attached patch fixes the problem? -- Comment By: Jan Palus (atler_) Date: 2006-04-15 16:48 Message: Logged In: YES user_id=1497957 Half day of debugging and it seems that I found an answer... just by accident ;). When curses module is linked against ncursesw it seems that it also should be linked against panelw not plain panel. After changing this in setup.py, ncurses.py demo finally runs fine. -- Comment By: Martin v. Löwis (loewis) Date: 2006-04-15 09:05 Message: Logged In: YES user_id=21627 I couldn't reproduce the problem on a Linux console (although my console had a different size); so it remains unreproducable for me. -- Comment By: nomind (vnainar) Date: 2006-04-13 13:00 Message: Logged In: YES user_id=1493752 Well , it is the linux console (in VGA mode ). The local is en_US.The size of the console is 100X37. -- Comment By: Martin v. Löwis (loewis) Date: 2006-04-11 07:32 Message: Logged In: YES user_id=21627 Ah, ok. vnainar, atler_: What terminal had you been using to make it crash? What is your locale? Any other conditions that might be relevant (e.g. dimension of the terminal)? -- Comment By: nomind (vnainar) Date: 2006-04-11 07:13 Message: Logged In: YES user_id=1493752 Removing 'ncursesw' (there are two references to it in 'setup.py') seems to solve the problem. I noticed one more oddity. Even before the above recompilation , it ran fine on an Xterm ! -- Comment By: Martin v. Löwis (loewis) Date: 2006-04-11 00:28 Message: Logged In: YES user_id=21627 That's hard to tell. Somebody would have to debug ncurses to find out why it crashes. Notice that it crashes only on some installations, so it is likely rather a problem with your ncurses installation, than with Python (or even with ncurses itself). -- Comment By: Jan Palus (atler_) Date: 2006-04-10 23:24 Message: Logged In: YES user_id=1497957 loewis: removing lines refering to ncursesw solves the problem. ncurses.py runs fine as well as other programs. What is actual problem then? Something with ncursesw or with python? Anyway, Thanks for your help. -- Comment By: Martin v. Löwis (loewis) Date: 2006-04-09 22:58 Message: Logged In: YES user_id=21627 atler_: around line 427, you find if self.compiler.find_library_file(lib_dirs, 'ncursesw'): readline_libs.append('ncursesw') elif self.compiler.find_library_file(lib_dirs, 'ncurses'): Replace that with if self.compiler.find_library_file(lib_dirs, 'ncurses'): (i.e. dropping the ncursesw part), and rebuild. -- Comment By: Jan Palus (atler_) Date: 2006-04-09 15:48 Message: Logged In: YES user_id=1497957 More complete backtrace, I hope it will help: http://pastebin.com/649445 -- Comment By: Anthony Baxter (anthonybaxter) Date: 2006-04-09 14:14 Message: Logged In: YES user_id=29957 The buildbot boxes don't show this problem. You might need to rebuild a Python with -g and unstripped to get a useful backtrace. -- Comment By: Jan Palus (atler_) Date: 2006-04-09 12:51 Message: Logged In:
[ python-Bugs-1448934 ] urllib2+https+proxy not working
Bugs item #1448934, was opened at 2006-03-13 15:55 Message generated for change (Comment added) made by jjlee You can respond by visiting: https://sourceforge.net/tracker/?func=detailatid=105470aid=1448934group_id=5470 Please note that this message will contain a full copy of the comment thread, including the initial issue submission, for this request, not just the latest update. Category: Python Library Group: Python 2.4 Status: Open Resolution: None Priority: 5 Submitted By: Rui Martins (ruibmartins) Assigned to: Nobody/Anonymous (nobody) Summary: urllib2+https+proxy not working Initial Comment: Using urllib2 to access an https site using a proxy doesn't work. It always returns HTML /HTML I've been looking around for bug reports on this and code samples, but all that I've got were emails/forum posts dating back to 2003 warning that the HTTPS over Proxy in urllib2 isn't implemented in Python! Is this true? -- Comment By: John J Lee (jjlee) Date: 2006-04-15 18:27 Message: Logged In: YES user_id=261020 Yes, there is no special support for using https proxies (via the CONNECT method) in httplib or urllib2. http://python.org/sf/515003 shows how to do it, but the patch is not good enough to be added to the standard library. Feel free to write a better patch! Please close this, since it's really a feature request, not a bug. -- You can respond by visiting: https://sourceforge.net/tracker/?func=detailatid=105470aid=1448934group_id=5470 ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[ python-Bugs-900898 ] urllib2 AuthHandlers can pass a bad host to HTTPPasswordMgr
Bugs item #900898, was opened at 2004-02-20 06:51 Message generated for change (Comment added) made by jjlee You can respond by visiting: https://sourceforge.net/tracker/?func=detailatid=105470aid=900898group_id=5470 Please note that this message will contain a full copy of the comment thread, including the initial issue submission, for this request, not just the latest update. Category: Python Library Group: Python 2.3 Status: Open Resolution: None Priority: 5 Submitted By: James Kruth (jk7) Assigned to: Nobody/Anonymous (nobody) Summary: urllib2 AuthHandlers can pass a bad host to HTTPPasswordMgr Initial Comment: If the Request object being used returns a URI with a port included (e.g. http://www.mysite.com:/index.html) If Request.get_full_url() or Request.get_host() returns a URI or host with a port included (e.g. http://www.mysite.com:/index.html or www.mysite.com:, respectively), and authentication (proxy or http, basic only) is required, then the respective AuthHandlers (HTTPBasicAuthHandler, ProxyBasicAuthHandler) end up calling http_error_auth_reqed with a host looking like www.mysite.com:. http_error_auth_reqed then precedes to call retry_http_basic_auth with the same host parameter, which in turn calls HTTPPasswordMgr.find_user_password. The problem is that find_user_password appears to expect a full URI, and attempts to reduce it to just a host, by calling reduce_uri. If a bare host with a port is passed (like www.mysite.com:), then reduce_uri returns just the port number in the netloc position - which find_user_password then attempts to compare against the correct host name you've stored in your HTTPPasswordMgr object along with your user name and password. I believe either find_user_password should not reduce the host, or the Auth Handler objects should pass full hostnames to find_user_password. -- Comment By: John J Lee (jjlee) Date: 2006-04-15 18:59 Message: Logged In: YES user_id=261020 This is fixed by patch 1470846, which includes tests and doc fix / update (though I neglected to mention that the patch fixes this problem in the initial patch comment; I'll rectify that now). -- Comment By: Brad Clements (bkc) Date: 2004-04-06 20:58 Message: Logged In: YES user_id=4631 I ran into this problem today with Python 2.3.3 on RedHat 9. I'm using port numbers in my URLs, and I found that the Auth Handler did NOT correctly find the userid and password registered. ie: authinfo = urllib2.HTTPPasswordMgrWithDefaultRealm() authinfo.add_password(None, host, userid, password) authHandler = urllib2.HTTPBasicAuthHandler(authinfo) opener = urllib2.build_opener(authHandler) where host = http://localhost:7993; I've tested the proposed fix shown in urllib2_bug.py at line 31, to whit, this: class HTTPBasicAuthHandlerF(AbstractBasicAuthHandler, BaseHandler): auth_header = 'Authorization' def http_error_401(self, req, fp, code, msg, headers): host = req.get_full_url() return self.http_error_auth_reqed('www-authenticate', host, req, headers) This appears to have corrected the problem. test_urllib2.py and test_urllib.py both pass after making this change. I did not test the ProxyBasicAuthHandler change (I don't have a proxy) -- Comment By: James Kruth (jk7) Date: 2004-02-20 21:25 Message: Logged In: YES user_id=979977 Here's a sample of the problem... -- Comment By: James Kruth (jk7) Date: 2004-02-20 14:39 Message: Logged In: YES user_id=979977 I've made up a file with some source code and comments that will hopefully clarify what I posted. I will post an example of the problem a bit later today. -- You can respond by visiting: https://sourceforge.net/tracker/?func=detailatid=105470aid=900898group_id=5470 ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[ python-Bugs-680577 ] urllib2 authentication problem
Bugs item #680577, was opened at 2003-02-05 00:22 Message generated for change (Comment added) made by jjlee You can respond by visiting: https://sourceforge.net/tracker/?func=detailatid=105470aid=680577group_id=5470 Please note that this message will contain a full copy of the comment thread, including the initial issue submission, for this request, not just the latest update. Category: Python Library Group: Python 2.3 Status: Open Resolution: None Priority: 5 Submitted By: GaryD (gazzadee) Assigned to: Nobody/Anonymous (nobody) Summary: urllib2 authentication problem Initial Comment: I've found a problem using the authentication in urllib2. When matching up host-names in order to find a password, then putting the protocol in the address makes it seem like a different address. eg... I create a HTTPBasicAuthHandler with a HTTPPasswordMgrWithDefaultRealm, and add the tuple (None, quot;http://proxy.blah.com:17828quot;, quot;fooquot;, quot;barquot;) to it. I then setup the proxy to use http://proxy.blah.com:17828 (which requires authentication). When I connect, the password lookup fails, because it is trying to find a match for quot;proxy.blah.com:17828quot; rather than quot;http://proxy.blah.com:17828quot; This problem doesn't exist if I pass quot;proxy.blah.com:17828quot; to the password manager. There seems to be some stuff in HTTPPasswordMgr to deal with variations on site names, but I guess it's not working in this case (unless this is intentional). Version Info: Python 2.2 (#1, Feb 24 2002, 16:21:58) [GCC 2.96 2731 (Mandrake Linux 8.2 2.96-0.76mdk)] on linux-i386 -- Comment By: John J Lee (jjlee) Date: 2006-04-15 19:45 Message: Logged In: YES user_id=261020 This issue is fixed by patch 1470846. -- Comment By: John J Lee (jjlee) Date: 2003-12-16 12:49 Message: Logged In: YES user_id=261020 Thanks! It seems .reduce_uri() tries to cope with hostnames as well as absoluteURIs. I don't understand why it wants to do that, but it fails, because it doesn't anticipate what urlparse does when a port is present: gt;gt;gt; urlparse.urlparse(quot;foo.bar.comquot;) ('', '', 'foo.bar.com', '', '', '') gt;gt;gt; urlparse.urlparse(quot;foo.bar.com:80quot;) ('foo.bar.com', '', '80', '', '', '') I haven't checked, but I assume it's just incorrect use of urlparse to pass it a hostname. Of course, if it's quot;fixedquot; to only accept absoluteURIs, it will break existing code, so I guess it must be fixed for hostnames. :-(( Also, I think .is_suburi(quot;/foo/spamquot;, quot;/foo/eggsquot;) should return False, but returns True, and .http_error_40x() use req.get_host() when they should be using req.get_full_url() (from a quick look at RFC 2617). -- Comment By: GaryD (gazzadee) Date: 2003-12-16 03:10 Message: Logged In: YES user_id=693152 Okay, I have attached a file that replicates this problem. If you run it as is (replacing the proxy name and address with something suitable), then it will fail (requiring proxy authentication). If you uncomment line 23 (which specifies the password without the scheme), then it will work successfully. Technical Info: * For a proxy, I am using Squid Cache version 2.4.STABLE7 for i586-mandrake-linux-gnu... * I have replicated the problem with Python 2.2.2 on Linux, and Python 2.3.2 on Windows XP. -- Comment By: GaryD (gazzadee) Date: 2003-12-16 02:08 Message: Logged In: YES user_id=693152 This was a while ago, and my memory has faded. I'll try to respond intelligently. I think the question was with the way the password manager looks up passwords, rather than anything else. I am pretty sure that the problem is not to do with the URI passed to urlopen(). In the code shown below, the problem was solely dependent on whether I added the line: (None, quot;blah.com:17828quot;, quot;fooquot;, quot;barquot;) ...to the HTTPPasswordMgrWithDefaultRealm object. If that password set was added, then the password lookup for the proxy was successful, and urlopen() worked. If that password set was not included, then the password lookup for the proxy was unsuccessful (despite the inclusion of the other 2, similar, password sets - quot;http://blah.com:17828quot; and quot;blah.comquot;), and urlopen() would fail. Hence my suspicion that the password manager did not fully remove the scheme, despite attempts to do so. I'll see if I can set it up on the latest python and get it to happen again. Just as an explanation, the situation was that I was running an authenticating proxy on a non-standard port (in order to avoid clashing with the normal proxy), in order to test out how my download code would work through an authenticating proxy.
[ python-Bugs-944394 ] No examples or usage docs for urllib2
Bugs item #944394, was opened at 2004-04-29 12:02 Message generated for change (Comment added) made by jjlee You can respond by visiting: https://sourceforge.net/tracker/?func=detailatid=105470aid=944394group_id=5470 Please note that this message will contain a full copy of the comment thread, including the initial issue submission, for this request, not just the latest update. Category: Python Library Group: None Status: Open Resolution: None Priority: 5 Submitted By: Chris Withers (fresh) Assigned to: Nobody/Anonymous (nobody) Summary: No examples or usage docs for urllib2 Initial Comment: Hi there, I'm sure I reported this before, but it's a couple of major releases later, and there's still no usage docs for urllib2. The examples given are too trivial to be helpful, but I'm guessing people are using the module so there must be some examples out there somewhere ;-) With a bit o fhelp from Moshez, I found the docstring in the module source. At the very least, it'd be handy if that appeared somewhere at: http://docs.python.org/lib/module-urllib2.html But really, mroe extensive and helpful documentation on this cool new module would be very handy. Chris -- Comment By: John J Lee (jjlee) Date: 2006-04-15 19:49 Message: Logged In: YES user_id=261020 They are here: http://docs.python.org/lib/urllib2-examples.html -- Comment By: Chris Withers (fresh) Date: 2006-04-15 19:07 Message: Logged In: YES user_id=24723 Where are these examples you're referring to? I don't see any at: http://docs.python.org/lib/module-urllib2.html I've already commented that the existing ones in the docstring would be a start but still don't really much help in taking full advantage of this module. -- Comment By: John J Lee (jjlee) Date: 2006-04-15 18:34 Message: Logged In: YES user_id=261020 Examples for urllib2 were added some time ago, so I suggest this bug is closed. -- Comment By: Chris Withers (fresh) Date: 2004-06-01 09:17 Message: Logged In: YES user_id=24723 I'm certainly willing, but I am totally incapable :-S The reason I opened this issue is because it would seem that urllib2 is better the urllib, but seems to be severely underdocumented, and hence I don't understand how to use it and so can't provide examples. As I said in the original submission, including the module's docstring in the Python module documentation would be a start, but doesn't cover what appears to be the full potential of a great module... -- Comment By: Martin v. Löwis (loewis) Date: 2004-05-31 22:15 Message: Logged In: YES user_id=21627 Are you willing to provide examples? -- You can respond by visiting: https://sourceforge.net/tracker/?func=detailatid=105470aid=944394group_id=5470 ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[ python-Bugs-1281692 ] urllib violates rfc 959
Bugs item #1281692, was opened at 2005-09-04 18:30 Message generated for change (Comment added) made by jjlee You can respond by visiting: https://sourceforge.net/tracker/?func=detailatid=105470aid=1281692group_id=5470 Please note that this message will contain a full copy of the comment thread, including the initial issue submission, for this request, not just the latest update. Category: Python Library Group: Python 2.4 Status: Open Resolution: None Priority: 5 Submitted By: Matthias Klose (doko) Assigned to: Nobody/Anonymous (nobody) Summary: urllib violates rfc 959 Initial Comment: [forwarded from http://bugs.debian.org/324023] python's urllib does the following things on the line when retrieving a file by ftp: send(3, PASV\r\n, 6, 0) = 6 send(3, NLST ftp-master.debian.org\r\n, 28, 0) = 28 But RFC 959 states: This command [NLST] causes a directory listing to be sent from server to user site. The pathname should specify a directory or other system-specific file group descriptor So, according to the robustness principle, it is wrong that python aborts file transfer if the server refuses to support NLST on files. -- Comment By: John J Lee (jjlee) Date: 2006-04-15 21:06 Message: Logged In: YES user_id=261020 Patch 1470976 fixes this bug. -- Comment By: John J Lee (jjlee) Date: 2006-02-06 01:16 Message: Logged In: YES user_id=261020 Bug 1357260 reports the same issue for both urllib and urllib2. -- Comment By: Josiah Carlson (josiahcarlson) Date: 2005-09-08 07:18 Message: Logged In: YES user_id=341410 The pathname should specify a directory or other system-specific file group descriptor. If the system (ftp server) does not support a particular 'file name' as a 'file group descriptor', it seems to me that the system (ftp server) is braindead. -- You can respond by visiting: https://sourceforge.net/tracker/?func=detailatid=105470aid=1281692group_id=5470 ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[ python-Bugs-1357260 ] urllib/urllib2 cannot ftp files which are not listable.
Bugs item #1357260, was opened at 2005-11-15 10:35 Message generated for change (Comment added) made by jjlee You can respond by visiting: https://sourceforge.net/tracker/?func=detailatid=105470aid=1357260group_id=5470 Please note that this message will contain a full copy of the comment thread, including the initial issue submission, for this request, not just the latest update. Category: Python Library Group: None Status: Open Resolution: None Priority: 5 Submitted By: Bugs Fly (mozbugbox) Assigned to: Nobody/Anonymous (nobody) Summary: urllib/urllib2 cannot ftp files which are not listable. Initial Comment: For whatever reason (security, privacy), there are ftp sites which will not allow ftp list command while normal downloading can be performed blindly. This mostly happens on direct linked ftp urls. In urllib.py, the ftp wrapper first check with self.ftp.nlst(file) before downloading, thus prevent the above sites from being useful. From the codes around, I saw no reason this extra step/check was performed at all. If the file really did not exist, RETR would return a suitable error anyway as checked by the code below. -- Comment By: John J Lee (jjlee) Date: 2006-04-15 21:06 Message: Logged In: YES user_id=261020 Patch 1470976 fixes this bug. -- Comment By: John J Lee (jjlee) Date: 2006-02-06 01:16 Message: Logged In: YES user_id=261020 Bug 1281692 reports the same issue for the urllib case, and includes a reference to the RFC. -- Comment By: Bugs Fly (mozbugbox) Date: 2005-11-17 05:38 Message: Logged In: YES user_id=1033842 File /usr/lib/python2.4/ftplib.py, line 241, in sendcmd return self.getresp() File /usr/lib/python2.4/ftplib.py, line 216, in getresp raise error_perm, resp IOError: [Errno ftp error] [Errno ftp error] 550 tompda_685692_Professional.Palm.OS.Programming.part12.rar: No such file or directory. -- Comment By: Thomas Lee (krumms) Date: 2005-11-15 13:34 Message: Logged In: YES user_id=315535 what's the expected response/error code from the FTP server if the NLST fails? -- Comment By: Bugs Fly (mozbugbox) Date: 2005-11-15 11:37 Message: Logged In: YES user_id=1033842 This might be related to bug #635453 but this is a bigger bug than a directory list is returned. If an existing file cannot be retrieved, then functionally is totally broken, there are no work around in this case. -- You can respond by visiting: https://sourceforge.net/tracker/?func=detailatid=105470aid=1357260group_id=5470 ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[ python-Bugs-1470353 ] test_ctypes fails on FreeBSD 4.x
Bugs item #1470353, was opened at 2006-04-14 15:11 Message generated for change (Comment added) made by theller You can respond by visiting: https://sourceforge.net/tracker/?func=detailatid=105470aid=1470353group_id=5470 Please note that this message will contain a full copy of the comment thread, including the initial issue submission, for this request, not just the latest update. Category: None Group: None Status: Closed Resolution: Fixed Priority: 5 Submitted By: Andrew I MacIntyre (aimacintyre) Assigned to: Thomas Heller (theller) Summary: test_ctypes fails on FreeBSD 4.x Initial Comment: $ ./python Lib/test/regrtest.py test_ctypes test_ctypes test test_ctypes failed -- Traceback (most recent call last): File /home/andymac/dev/python-svn-head/Lib/ctypes/test/test_functions.py, line 333, in test_struct_return_2H self.failUnlessEqual((s2h.x, s2h.y), (99*2, 88*3)) AssertionError: (-1004, 2123) != (198, 264) 1 test failed: test_ctypes [41158 refs] This is with a subversion checkout updated to 5am AEST (Aust) 14Apr06, debug build. The returned tuple values (s2h.x, s2h.y) appear to vary from run to run, so it looks like something isn't where its expected. This is with a FreeBSD 4.8 i386 system (not particularly recent), using gcc 2.95.4. A quick and dirty test (in C) suggests that its not an alignment issue for the 2 shorts in the S2H struct. Ideas for trying to debug this further? -- Comment By: Thomas Heller (theller) Date: 2006-04-15 22:26 Message: Logged In: YES user_id=11105 Committed as 45440. For NetBSD, this change seems not to be required - ctypes works fine as it is (I'm testing this on the SF compilefarm host, which has NetBSD 2.0.2). -- Comment By: Andrew I MacIntyre (aimacintyre) Date: 2006-04-15 13:18 Message: Logged In: YES user_id=250749 Your suggested change does indeed get the test to pass on this system. Given the history and relationship of [Free/Net/Open]BSD, I would suggest that for x86 it is very likely that you will need to add defined(__NetBSD__) clauses as well. From my POV this bug can now be closed. Thanks, Thomas. BTW, the actual patch applied was: --- ffi.c.orig Tue Apr 4 05:26:32 2006 +++ ffi.c Sat Apr 15 21:02:16 2006 @@ -121,7 +121,7 @@ switch (cif-rtype-type) { case FFI_TYPE_VOID: -#if !defined(X86_WIN32) !defined(__OpenBSD__) +#if !defined(X86_WIN32) !defined(__OpenBSD__) !defined(__FreeBSD__) case FFI_TYPE_STRUCT: #endif case FFI_TYPE_SINT64: @@ -135,7 +135,7 @@ cif-flags = FFI_TYPE_SINT64; break; -#if defined(X86_WIN32) || defined(__OpenBSD__) +#if defined(X86_WIN32) || defined(__OpenBSD__) || defined(__FreeBSD__) case FFI_TYPE_STRUCT: if (cif-rtype-size == 1) { -- Comment By: Thomas Heller (theller) Date: 2006-04-14 21:09 Message: Logged In: YES user_id=11105 Of course I meant FreeBSD instead of NetBSD, sorry. -- Comment By: Thomas Heller (theller) Date: 2006-04-14 21:08 Message: Logged In: YES user_id=11105 This looks very similar to a problem I recently 'fixed' on OpenBSD - maybe it is even a bug in libffi. On OpenBSD x86 the problem seemed to be that small structures are passed like short or int. You could try to fix it by adding the appropriate definition in Modules/_ctypes/libffi/src/x86/ffi.c, at lines 124 and lines 138. Maybe changing them to #if !defined(X86_WIN32) !defined(__OpenBSD__) !defined(__NetBSD__) or whatever the magic symbol for Netbsd is. Unfortunately I do not have access to a netbsd machine myself. -- You can respond by visiting: https://sourceforge.net/tracker/?func=detailatid=105470aid=1470353group_id=5470 ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[ python-Bugs-1460514 ] ctypes extension does not compile on Mac OS 10.3.9
Bugs item #1460514, was opened at 2006-03-29 10:28 Message generated for change (Comment added) made by theller You can respond by visiting: https://sourceforge.net/tracker/?func=detailatid=105470aid=1460514group_id=5470 Please note that this message will contain a full copy of the comment thread, including the initial issue submission, for this request, not just the latest update. Category: None Group: Python 2.5 Status: Open Resolution: None Priority: 7 Submitted By: Andrew Dalke (dalke) Assigned to: Thomas Heller (theller) Summary: ctypes extension does not compile on Mac OS 10.3.9 Initial Comment: I compiled Python from CVS this morning. It silently failed to compile ctypes. Here is the text surrounding the failure gcc [deleted] -c /Users/dalke/cvses/python-svn/Modules/_ctypes/ libffi/src/powerpc/darwin_closure.S -o build/temp.darwin-7.9.0- Power_Macintosh-2.5/darwin_closure.o darwin_closure.S:249:unknown section attribute: live_support darwin_closure.S:249:Rest of line ignored. 1st junk character valued 69 (E). building 'itertools' extension ... Python installed but when I tried to import ctypes I got File /usr/local/lib/python2.5/ctypes/__init__.py, line 8, in module from _ctypes import Union, Structure, Array ImportError: No module named _ctypes I tracked it down to the '+live_support' attribute from the darwin_closure.S. My compiler does not understand that. Thomas Heller (in private email) pointed out the text from the ctypes README On OS X, the segment attribute live_support must be defined. If your compiler doesn't know about it, upgrade or set the environment variable CCASFLAGS=-Dno_live_support. Upgrading is out of the option. I set the environment variable but that did not fix things when I tried to recompile Python. However, editing the file to remove the +live_support works. All the self-tests passed, and my experimentation this afternoon was successful. -- Comment By: Thomas Heller (theller) Date: 2006-04-15 22:33 Message: Logged In: YES user_id=11105 Thanks for the feedback. For the warnings in Modules/_ctypes/cfield.c, I have no idea what is wrong there. For the warnings in the libffi-sources I tend to ignore them because I don't want to change them too much. For the test-failure: can you find out why this fails? (In the meantime I'm trying to get hold of 10.3 installation disks - any tips how to shrink the only existing partition on my mac mini running 10.4 and setting up a multi-boot system would be appreciated, if anyone wants to help. As an alternative ssh-access to an existing osx installation for testing would of course also help. I don't know if this is feasible or not ;-) -- Comment By: Andrew Dalke (dalke) Date: 2006-04-14 02:51 Message: Logged In: YES user_id=190903 Sorry - was ill and not doing anything for a week. I've built the latest code from SVN. No problems with the compilation and I am able to import just fine. I did get the following compiler warnings /Users/dalke/cvses/python-svn/Modules/_ctypes/cfield.c: In function `CField_repr': /Users/dalke/cvses/python-svn/Modules/_ctypes/cfield.c:259: warning: signed size_t format, Py_ssize_t arg (arg 3) /Users/dalke/cvses/python-svn/Modules/_ctypes/cfield.c:267: warning: signed size_t format, Py_ssize_t arg (arg 3) /Users/dalke/cvses/python-svn/Modules/_ctypes/libffi/src/powerpc/ ffi_darwin.c:383: warning: function declaration isn't a prototype /Users/dalke/cvses/python-svn/Modules/_ctypes/libffi/src/powerpc/ ffi_darwin.c:384: warning: function declaration isn't a prototype /Users/dalke/cvses/python-svn/Modules/_ctypes/libffi/src/powerpc/ ffi_darwin.c:388: warning: function declaration isn't a prototype /Users/dalke/cvses/python-svn/Modules/_ctypes/libffi/src/powerpc/ ffi_darwin.c:389: warning: function declaration isn't a prototype /Users/dalke/cvses/python-svn/Modules/_ctypes/libffi/src/powerpc/ ffi_darwin.c:394: warning: function declaration isn't a prototype /Users/dalke/cvses/python-svn/Modules/_ctypes/libffi/src/powerpc/ ffi_darwin.c: In function `ffi_closure_helper_DARWIN': /Users/dalke/cvses/python-svn/Modules/_ctypes/libffi/src/powerpc/ ffi_darwin.c:622: warning: unused variable `temp_ld' When I run the self test I get one error FAILED (errors=1) Traceback (most recent call last): File Lib/test/test_ctypes.py, line 12, in module test_main() File Lib/test/test_ctypes.py, line 9, in test_main run_suite(unittest.TestSuite(suites)) File /Users/dalke/cvses/python-svn/Lib/test/test_support.py, line 285, in run_suite raise TestFailed(err) test.test_support.TestFailed: Traceback (most recent call last): File /Users/dalke/cvses/python-svn/Lib/ctypes/test/test_loading.py, line 30, in test_load cdll.load(libc_name) File /Users/dalke/cvses/python-svn/Lib/ctypes/_loader.py, line 112, in