Re: Redirecting to a third party site with injected HTML
On 09/06/2013 18:09, guytam...@gmail.com wrote: Hi all, new to group and pretty new to python. I'm working on a new project and i want to receive a request from a user and to redirect him to a third party site, but on the page after i redirect my users i want to them to see injected html (on the third party site.) i'm not really sure how to approach this problem.. hints :) regards, Guy Hi Guy, It appears to me that you have thought "Inject html" as the solution to your problem. Sorry, but you can't solve your problem that way. Basic security. What is the problem you are trying to solve? Ian -- http://mail.python.org/mailman/listinfo/python-list
Re: FACTS: WHY THE PYTHON LANGUAGE FAILS.
On 27/06/2013 11:52, rusi wrote: On Thursday, June 27, 2013 12:35:14 PM UTC+5:30, Russel Walker wrote: On Thursday, June 27, 2013 6:19:18 AM UTC+2, Thrinaxodon wrote: I was hoping to have a good laugh. :| Although I wouldn't call it hostile. I think the python community is being educated in how to spam and troll at the same time. I to have problems spolling. -- http://mail.python.org/mailman/listinfo/python-list
Re: Encapsulation, inheritance and polymorphism
On 17/07/2012 19:43, Ethan Furman wrote: Mark Lawrence wrote: On 17/07/2012 18:29, Ethan Furman wrote: Terry Reedy wrote: On 7/17/2012 10:23 AM, Lipska the Kat wrote: Well 'type-bondage' is a strange way of thinking about compile time type checking and making code easier to read (and therefor debug 'type-bondage' is the requirement to restrict function inputs and output to one declared type, where the type declaration mechanisms are usually quite limited. >>> def max(a, b): if a <= b: return a return b Surely you meant 'if a >= b: . . .' No worries, I'm sure your unittests would have caught it. ;) ~Ethan~ Wouldn't the compiler have caught it before the unittests? :-) Silly me, the word processor would have caught it! ~Ethan~ No compiler can find as many faults as publishing your code on a mailing list!!! :) Ian -- http://mail.python.org/mailman/listinfo/python-list
Help needed installing easy_install and lxml2
Hi, On a reasonably fresh (3 day old) install of 64 bit windows 7, I have installed the 64 bit Python 2.7.3 from http://www.python.org/download/ Then I installed the 64 bit version of easy_install using http://pypi.python.org/pypi/setuptools And then install lxml 2.3.5, for which I use the instructions at http://lxml.de/installation.html#installation This ends with: Processing lxml-2.3.5.tgz Running lxml-2.3.5\setup.py -q bdist_egg --dist-dir c:\users\ian\appdata\local\temp\easy_install-9__rq7\lxml-2.3.5\egg-dist-tmp-uj_v_2 Building lxml version 2.3.5. Building without Cython. ERROR: 'xslt-config' is not recognized as an internal or external command, operable program or batch file. ** make sure the development packages of libxml2 and libxslt are installed ** Using build configuration of libxslt error: Setup script exited with error: Unable to find vcvarsall.bat C:\Users\ian> Now what? I thought I was installing the binary package do I would not need any development versions. What do these errors mean, and how can I overcome them? Thanks Ian -- http://mail.python.org/mailman/listinfo/python-list
Re: Help needed installing easy_install and lxml2
On 16/08/2012 08:01, Stefan Behnel wrote: http://lxml.de/FAQ.html#where-are-the-binary-builds Stefan Hi Stefan, Thanks Stefan, everything is working fine now. Regards Ian -- http://mail.python.org/mailman/listinfo/python-list
Want to improve my code.
Hi all, I'm using lxml etree, and have written a routine to remove nodes in the parsed tree. Typically, I load html, and remove tags, so I am moving the font tags children up and moving the text and tail data about. The code of the deleteElem routine is here http://snipt.org/GSoo0 It troubles me that there is so much repetition in the lines that call joiner. How can I improve the code? Regards Ian -- http://mail.python.org/mailman/listinfo/python-list
Re: Guide to: Learning Python Decorators
On 09/02/2012 21:41, Aaron France wrote: How many pages is that? The amazon page conveniently left that off. There is an average of 5.1 chars per word in English, and usually about 350 words an A4 page. The 215K file is a) Compressed - typically by 60% b) Contains simple html and images as its source. c) Must contain the cover image. As a *very* rough guess, that means the files expands to 344K. Remove the cover image at 250-300kb leaves 44 to 94KB That is 8700 words to 18400 words or approx 25 to 50 pages. But that is *very* *very* rough. Regards Ian -- http://mail.python.org/mailman/listinfo/python-list
Re: how to avoid leading white spaces
On 03/06/2011 03:58, Chris Torek wrote: - This is a bit surprising, since both "s1 in s2" and re.search() could use a Boyer-Moore-based algorithm for a sufficiently-long fixed string, and the time required should be proportional to that needed to set up the skip table. The re.compile() gets to re-use the table every time. Is that true? My immediate thought is that Boyer-Moore would quickly give the number of characters to skip, but skipping them would be slow because UTF8 encoded characters are variable sized, and the string would have to be walked anyway. Or am I misunderstanding something. Ian -- http://mail.python.org/mailman/listinfo/python-list
Re: Any Better logic for this problem..
On 09/06/2011 09:31, Ganapathy Subramanium wrote: Hi Guru's, I'm working on a solution to find the prime factor of the number This part of the code works.. http://www.pastie.org/2041584 When the number gets bigger, the range cannot iterate through bigger number and it does not work. When I googled , I came across creating our own range function to solve this. I was just wondering if there was a better algorithm to get the prime numbers / prime factors of a long number? Any inputs is highly appreciated. If I was attempting this problem, I would pre-compute a file of prime numbers, in increasing order (probably use the Sieve of Erastothenes approach). You need a list of primes from 2 to the square root of the largest num you will have to process. With that, you simply work through the prime numbers, Divide num by this prime. If no remainder, replace num with num // prime (so you divide by the same prime again). else step on to next prime without changing num Stop when num becomes 1. e.g. 50 divides by 2 so factors are (2) and 25 into next iteration with 3 25 which won't divide by 3,so factors remain (2) and 25 goes into next iteration with 5 25 // 5 is 5 so factors become (2,5) and 5 into next iteration with 5 5 // 5 is 1so factors are (2,5,5) and computation complete. Ian -- http://mail.python.org/mailman/listinfo/python-list
How to get return values of a forked process
Hello all, I need some helped with forking. In my script, I fork a process. I want to get return values from the child process. This is the script that does the forking: for x in (mylist): pid = os.fork() if pid: pidList.append(pid) else: os.execv('/usr/bin/python',('/usr/bin/ python',myForkedScript)) for pid in pidList: childPid, status = os.waitpid(pid,0) # I think status should be the return value of the forked process; I would expect status to be a 1 or a 0 myForkedScript has code like this: if fail: os._exit(1) else: os._exit(os.EX_OK) Is using os._exit() the correct way to get a return value back to the main process? I thought the value 'n', passed in os._exit(n) would be the value I get returned. In the case of a failure, I get 256 returned rather than 1. Thanks for the assistance! IL -- http://mail.python.org/mailman/listinfo/python-list
Re: How to get return values of a forked process
On Jun 21, 1:54 pm, Ian Kelly wrote: > On Tue, Jun 21, 2011 at 12:26 PM, Ian wrote: > > myForkedScript has code like this: > > if fail: > > os._exit(1) > > else: > > os._exit(os.EX_OK) > > > Is using os._exit() the correct way to get a return value back to the > > main process? > > sys.exit() is the preferred way. > > > I thought the value 'n', passed in os._exit(n) would be the value I > > get returned. In the case of a failure, I get 256 returned rather > > than 1. > > According to the docs, on Unix: > > """ > Wait for completion of a child process, and return a tuple containing > its pid and exit status indication: a 16-bit number, whose low byte is > the signal number that killed the process, and whose high byte is the > exit status (if the signal number is zero); the high bit of the low > byte is set if a core file was produced. > """ > > And on Windows: > > """ > Wait for completion of a process given by process handle pid, and > return a tuple containing pid, and its exit status shifted left by 8 > bits (shifting makes cross-platform use of the function easier). > """ > > (256 >> 8) == 1 > > However, I would advise using the subprocess module for this instead > of the os module (which is just low-level wrappers around system > calls). Where did you find the Unix docs you pasted in? I didn't find it in the man pages. Thank you. Based on what you say, I will change my os._exit() to sys.exit(). -- http://mail.python.org/mailman/listinfo/python-list
Re: web browsing short cut
On 03/07/2011 02:21, Dustin Cheung wrote: Hey guys, I am new to python. I want to make a shortcut that opens my websites and re-sizes them to display on different areas on the screen. I looked around but i had no luck. Is that possible with python? if so can someone point to to the right direction? Here is what I came up with so far.. I suggest you create a dummy page on your disk with an onload event that uses javascript to open, size and load all the windows you want. Then create a short cut to the dummy page. Regards Ian -- http://mail.python.org/mailman/listinfo/python-list
Re: changing to function what works like a function
On 07/03/2011 11:33, Victor Paraschiv wrote: Hi everyone i understood that the goal of Python is to make programing easy (of course, powerful at the same time). I think one way to do it is to eliminate unnecessary syntax exceptions. One is the following: for a complex number "z", to get the real and imaginary part, you type: "z.real" and "z.imag". At the same time, the most obvious way would be to call it like a function, say: "real(z)", and, respectively, "imag(z)". Just like it was changed from " print 'something' " , to " print('something') " . What do you think? There are more examples like this. I think it a crazy idea. Python intends to be object oriented so the "obvious" way is to call a method, or access an attribute. If there was a risk that the structure of complex numbers might change (there isn't), and if that would mean that z.real and z.imag could not work (it doesn't), then z.real() and z.imag() might be an improvement. As there is no such risk, the current syntax is as good as it can get. Ian -- http://mail.python.org/mailman/listinfo/python-list
Re: Absolutely Insane Problem with Gmail
On 06/03/2011 13:56, Victor Subervi wrote: gmail, for whatever reason, filters out emails send to the same address from which they are sent. Its possibly a protection against circular forwarding. Ian -- http://mail.python.org/mailman/listinfo/python-list
Re: Don't Want Visitor To See Nuttin'
On 09/03/2011 21:01, Victor Subervi wrote: The problem is that it prints "Content-Type: text/html" to the screen If you can see what is intended to be a header, then it follows that you are not sending the header correctly. Sorry - can't tell you how to send a header. You don't say what framework you are using. Ian -- http://mail.python.org/mailman/listinfo/python-list
Re: Deadlock and a rather weird stacktrace
On 10/03/2011 09:48, Vincent wrote: Can nobody explain this? Please. how can a sleep() continue in a __bootstrap() ? Regards, Vincent On 4 feb, 13:39, Vincent van Beveren wrote: Hi everyone, I'm currently working on a multithreaded GUI system in Python 2.6. In this system I use conditions to coordinate synchronization. However, one condition suddenly locks, without any cause. As a last resort I have written a small routine to dump all the stack traces. def dumpAllStacks(self): for threadId, stack in sys._current_frames().items(): print "Thread with Id: %s" % threadId traceback.print_stack(stack) When the system is dead-locked, I invoke this method. One stack-trace strikes me as odd: Thread with Id: 1568 File "c:\PYTHON26\lib\threading.py", line 497, in __bootstrap self.__bootstrap_inner() File "c:\PYTHON26\lib\threading.py", line 525, in __bootstrap_inner self.run() File "c:\PYTHON26\lib\threading.py", line 477, in run self.__target(*self.__args, **self.__kwargs) File "c:\PYTHON26\lib\site-packages\magnum\gui\autogui.py", line 2558, in __sendDataLoop self.__sendDataCondition.wait(1) File "c:\PYTHON26\lib\threading.py", line 256, in wait _sleep(delay) File "c:\PYTHON26\lib\threading.py", line 497, in __bootstrap self.__bootstrap_inner()<<= What? File "c:\PYTHON26\lib\threading.py", line 525, in __bootstrap_inner self.run() File "c:\PYTHON26\lib\site-packages\magnum\subsys\__init__.py", line 2242, in run self.updateTask() File "c:\PYTHON26\lib\site-packages\magnum\subsys\__init__.py", line 2214, in updateTask self.statusServerModule.updateTaskWithConnection(self.statusServerConnection) File "c:\PYTHON26\lib\site-packages\magnum\subsys\shared\modules.py", line 2450, in updateTaskWithConnection self.updateDataWithConnection(connection, updateAll) File "c:\PYTHON26\lib\site-packages\magnum\subsys\shared\modules.py", line 2488, in updateDataWithConnection self.updateVariableData(varDataDict, frozenset(varDataDict)) File "c:\PYTHON26\lib\site-packages\magnum\subsys\shared\modules.py", line 796, in updateVariableData self.cmdMgr.updateVariableData(self.moduleId, varDataDict, forceVarIdSet) # after this varMgr makes deepcopy File "c:\PYTHON26\lib\site-packages\magnum\subsys\shared\managers.py", line 441, in updateVariableData self.notifyUpdateReport(updatedData) File "c:\PYTHON26\lib\site-packages\magnum\subsys\shared\managers.py", line 493, in notifyUpdateReport with self.updateReportCondition: File "c:\PYTHON26\lib\threading.py", line 205, in __enter__ return self.__lock.__enter__() File "c:\PYTHON26\lib\threading.py", line 121, in acquire rc = self.__block.acquire(blocking) Can someone tell me how the sleep of one thread can continue as the 'run' of another? Is this normal? Thanks in advance! Regards,Vincentvan Beveren ___ Ing. V. van Beveren Software Engineer, FOM Rijnhuizen T: +31 (0) 30-6096769 E: v.vanbeve...@rijnhuizen.nl Hi Vincent, I can't explain it, - I am no expert - but I did have some thoughts that I put forward anyway. It would appear from the stack trace that self.run() is being called within self.run(). Did you perhaps start a third thread from within a second thread? The first thread is the only one with a stack at start-up, and therefore it has to be the thread that sets up the stack swapping needed for multi-threading. If a background thread later starts to create threads, it is doing so from an unusual situation, and its stack could result in the sort of double run() stack you see above. I don't think it matters - the thread will die or return to the pool when its run() exits, and the extra stack is used only by the creating thread, and not the new threads. It might also be that anything above the first run() call is reported incorrectly when dumped from another thread. Have you checked the caveats at the bottom of http://docs.python.org/library/thread.html#module-thread You might be tripping up on one of those. Regards Ian -- http://mail.python.org/mailman/listinfo/python-list
Re: Questions about GIL and web services from a n00b
On 15/04/2011 20:17, Dan Stromberg wrote: On Fri, Apr 15, 2011 at 9:33 AM, Chris H wrote: 1. Are you sure you want to use python because threading is not good due to the Global Lock (GIL)? Is this really an issue for multi-threaded web services as seems to be indicated by the articles from a Google search? If not, how do you avoid this issue in a multi-threaded process to take advantage of all the CPU cores available? Concurrency in Python is a largish topic. It's true that CPython's multithreading is poor. In fact, running a multithreaded CPython application on n vs 2n cores can actually take more time on the 2n cores. However: 1) In Jython, and likely IronPython, threading is good. The load times of Iron Python are ssslllow! (My tests showed startup times 4 to 6 times that of cpython on the same kit). 3) There's something called "stackless" and (similar to stackless) "greenlets". While stackless allows you to use thousands of threads comfortably, it's still pretty single-core. It's essentially a fork of CPython, and is being made a part of PyPy. I believe greenlets are an attempt to bring what's good about stackless to CPython, in the form of a C extension module. Greenlets are green threads - cooperative switching all in one system thread and therefore one core. Very lightweight. 4) I've heard that in CPython 3.2, the GIL is less troublesome, though I've not yet heard in what way. Multiple threads still cannot run at the same time, however, if one thread runs too long without a context switch, it relinquishes control and forces another thread to run. This stops a low priority thread on one core, locking out a high-priority thread on another. That this was happening is why 2 cores can be slower than one. (The overhead of starting the second thread, finding it can't get the GIL and closing down again). 5) Even in CPython, I/O-bound processes are not slowed significantly by the GIL. It's really CPU-bound processes that are. Its ONLY when you have two or more CPU bound threads that you may have issues. Regards Ian -- http://mail.python.org/mailman/listinfo/python-list
Re: checking if a list is empty
On 11/05/2011 20:13, Hans Georg Schaathun wrote: On Wed, 11 May 2011 12:17:33 -0700, Ethan Furman wrote: : 'if li' *is* KISS. It /might/ be in some contexts, but a priori it is not, as it superimposes a truth value on a data type which is otherwise a pretty accurate model of real objects (outside python). One principle of object oriented programming is to bestow the objects with properties reflecting known properties from the domain being modelled. Lists do not have truth values in the application domain, and therefore truth values in the implementation domain is complicated. Exactly. Its just a convention. If it exists, its true, if if doesn't its false. In the "real world" lists of zero items do not exist. You don't go shopping with a shopping list of zero items. You don't take a journey going nowhere. You wouldn't have a party and invite nobody. What kind of building is one with zero floors? Would you have an Aircraft Carrier with no aircraft? Oh Wait - the UK has one of those coming into service soon. Regards Ian -- http://mail.python.org/mailman/listinfo/python-list
Re: checking if a list is empty
On 12/05/2011 04:51, Chris Angelico wrote: On Thu, May 12, 2011 at 7:02 AM, Ian wrote: In the "real world" lists of zero items do not exist. You don't go shopping with a shopping list of zero items. Actually, yes you do. You maintain your shopping list between trips; whenever you need something, you put it on the list immediately. Then when you go shopping, you just take the list with you (if you're lucky, you don't need to move or copy it at all, you just get another reference to it). Once you're done, you empty the list - you now have a shopping list with zero items (until you get home and realize you forgot something). Chris Angelico He He. I didn't claim an empty list was not useful! If you maintain it between trips, then yes, you arrive back with an empty list. Ian -- http://mail.python.org/mailman/listinfo/python-list
Re: Anaconda Navigator : Add App
Anaconda is v3.6 very 2017'ish by now... ;-) -- https://mail.python.org/mailman/listinfo/python-list
Re: ctypes NULL pointers; was: Python To Send Emails Via Outlook Express
Thanks again Lenard!! -- http://mail.python.org/mailman/listinfo/python-list
Re: ctypes NULL pointers; was: Python To Send Emails Via Outlook Express
Hi Lenard Hopefully I have understood you properly. The updated script is now as follows, or you can download it from http://www.kirbyfooty.com/simplemapi.py Thanks again for all your help!!! Kindest regards Ian Cook -- import os from ctypes import * FLAGS = c_ulong LHANDLE = c_ulong LPLHANDLE = POINTER(LHANDLE) # Return codes SUCCESS_SUCCESS = 0 # Recipient class MAPI_ORIG = 0 MAPI_TO = 1 class STRUCT(Structure): _fields_ = [('voidptr', c_void_p)] #NULL = c_void_p(None) NULL=STRUCT( None ) # Create an instance with voidptr field NULL class MapiRecipDesc(Structure): _fields_ = [('ulReserved', c_ulong), ('ulRecipClass', c_ulong), ('lpszName', c_char_p), ('lpszAddress', c_char_p), ('ulEIDSize', c_ulong), ('lpEntryID', c_void_p), ] lpMapiRecipDesc = POINTER(MapiRecipDesc) class MapiFileDesc(Structure): _fields_ = [('ulReserved', c_ulong), ('flFlags', c_ulong), ('nPosition', c_ulong), ('lpszPathName', c_char_p), ('lpszFileName', c_char_p), ('lpFileType', c_void_p), ] lpMapiFileDesc = POINTER(MapiFileDesc) class MapiMessage(Structure): _fields_ = [('ulReserved', c_ulong), ('lpszSubject', c_char_p), ('lpszNoteText', c_char_p), ('lpszMessageType', c_char_p), ('lpszDateReceived', c_char_p), ('lpszConversationID', c_char_p), ('flFlags', FLAGS), ('lpOriginator', lpMapiRecipDesc), # ignored? ('nRecipCount', c_ulong), ('lpRecips', lpMapiRecipDesc), ('nFileCount', c_ulong), ('lpFiles', lpMapiFileDesc), ] lpMapiMessage = POINTER(MapiMessage) MAPI = windll.mapi32 MAPISendMail=MAPI.MAPISendMail MAPISendMail.restype = c_ulong # Error code MAPISendMail.argtypes = (LHANDLE, # lhSession c_ulong, # ulUIParam lpMapiMessage, # lpMessage FLAGS, # lpFlags c_ulong, # ulReserved ) def SendMail(recipient, subject, body, attachfiles): """Post an e-mail message using Simple MAPI Special thanks to Lenard Lindstrom! recipient - string: address to send to (multiple address sperated with a semicolin) subject - string: subject header body - string: message text attach - string: files to attach (multiple attachments sperated with a semicolin) Example usage import simplemapi simplemapi.SendMail("[EMAIL PROTECTED];[EMAIL PROTECTED]","My Subject","My message body","c:\attachment1.txt;c:\attchment2") """ # get list of file attachments attach = [] AttachWork = attachfiles.split(';') #verify the attachment file exists for file in AttachWork: if os.path.exists(file): attach.append(file) attach = map( os.path.abspath, attach ) nFileCount = len(attach) if attach: MapiFileDesc_A = MapiFileDesc * len(attach) fda = MapiFileDesc_A() for fd, fa in zip(fda, attach): fd.ulReserved = 0 fd.flFlags = 0 fd.nPosition = -1 fd.lpszPathName = fa fd.lpszFileName = None fd.lpFileType = None lpFiles = fda else: # No attachments lpFiles = cast(NULL, lpMapiFileDesc) # Make NULL # Get the number of recipients RecipWork = recipient.split(';') RecipCnt = len(RecipWork) # Formulate the recipients MapiRecipDesc_A = MapiRecipDesc * len(RecipWork) rda = MapiRecipDesc_A() for rd, ra in zip(rda, RecipWork): rd.ulReserved = 0 rd.ulRecipClass = MAPI_TO rd.lpszName = None rd.lpszAddress = ra rd.ulEIDSize = 0 rd.lpEntryID = None recip = rda # send the message msg = MapiMessage(0, subject, body, None, None, None, 0, cast(NULL, lpMapiRecipDesc), RecipCnt, recip, nFileCount, lpFiles) rc = MAPISendMail(0, 0, byref(msg), 0, 0) if rc != SUCCESS_SUCCESS: raise WindowsError, "MAPI error %i" % rc -- http://mail.python.org/mailman/listinfo/python-list
Re: Help! Host is reluctant to install Python
On Wed, 26 Jan 2005 01:40:39 GMT, [EMAIL PROTECTED] wrote: ... >I think you should look into some type of virtual hosting that gives >you more ability to install your own software. Typing "uml hosting" >(UML is user-mode Linux) into Google finds a lot of such services. If >you find one that you like, post it here, I'm interested in this myself. I'm very happy with uml from tummy.com for 25 USD/month, with good support by email for configuring mod_python in my case. They are also a Pycon sponsor. Ian -- http://mail.python.org/mailman/listinfo/python-list
Python To Send Emails Via Outlook Express
Hi, I'm a newbie (oh no I can here you say another one...) How can I get Python to send emails using the default windows email client (eg outlook express)? I thought I could just do the following import win32com.client s = win32com.client.Dispatch('CDO.Message') s.From = "[EMAIL PROTECTED]" s.To = "[EMAIL PROTECTED]" s.Subject = "The subject" s.Send ... but nothing happens. What am I doing wrong? Does anyone have some sample code to share with me please? Thank you! Ian Cook (freeware author of Kirby Alarm And Task Scheduler www.kirbyfooty.com) -- http://mail.python.org/mailman/listinfo/python-list
Re: Python To Send Emails Via Outlook Express
Hi Ganesan I tried changing s.Send to s.Send(). It now comes up with an exception error.. The details are below. Ian Traceback (most recent call last): File "C:\Python23\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", line 307, in RunScript debugger.run(codeObject, __main__.__dict__, start_stepping=0) File "C:\Python23\Lib\site-packages\pythonwin\pywin\debugger\__init__.py", line 60, in run _GetCurrentDebugger().run(cmd, globals,locals, start_stepping) File "C:\Python23\Lib\site-packages\pythonwin\pywin\debugger\debugger.py", line 595, in run exec cmd in globals, locals File "D:\MyPython\emailtest.py", line 7, in ? s.Send() File "C:\Python23\lib\site-packages\win32com\gen_py\CD00-8B95-11D1-82DB-00C04FB1625Dx0x1x0.py", line 686, in Send return self._oleobj_.InvokeTypes(158, LCID, 1, (24, 0), (),) com_error: (-2147352567, 'Exception occurred.', (0, None, 'The server rejected one or more recipient addresses. The server response was: 554 <[EMAIL PROTECTED]>: Relay access denied\r\n', None, 0, -2147220977), None) -- http://mail.python.org/mailman/listinfo/python-list
Re: Python To Send Emails Via Outlook Express
Thanks Fredrik, That was my first impression too. But all I want to do is use Python to instruct Outlook Express to send an email. That way the user would not have to do any setting up etc of the mail server properties etc and Outlook Express will magage all the connection side of things. I have seen other python scripts that will talk to Excel etc but so far (despite a lot of searching) I cannot see how Python can talk to Outlook Express. I know I can do this in Clarion by accessing MapiSendEmail but because I'm new to Python I don't know how to do it in Python. I'm really impressed with the power of Python. It seems just about anything you can think of is there already so I know th eanswer is out there somewhere! Can this be done using Python? Does anyone have a sample script please? Pretty please?? Ian -- http://mail.python.org/mailman/listinfo/python-list
Re: Python To Send Emails Via Outlook Express
Hi Keith Thanks for your reply. I am aware of the smtplib module and it works very well! (refer script below) The problem is that I have a developed a freeware application called Kirby Alarm And Task Scheduler (see www.kirbyfooty.com). The program can pop up a note, run a program, play a sound, or send an email at whatever intervals the user wants.. When it comes to sending emails the user has the option of sending them via smtp, or via there email client (eg outlook express). I prefer the send method as this makes setting up the email parameters a lot easier for the user. As the program is used by over 16,000 people around the world I don't want to complicate things by asking them to enter the mail server properties. Because Python is so powerful I want to develop a suite of applications in Python that Kirby Alarm can run. Things like FTP, Backup, Speech etc would be excellent There has to be a way for Python to send emails via Outlook Express Kind regards Ian PS Here is the working script for sending emails via SMTP.. - # Import smtplib for the actual sending function import os import sys import smtplib import mimetypes from email.Encoders import encode_base64 from email.MIMEAudio import MIMEAudio from email.MIMEBase import MIMEBase from email.MIMEImage import MIMEImage from email.MIMEMultipart import MIMEMultipart from email.MIMEText import MIMEText FROM = '[EMAIL PROTECTED]' TO = '[EMAIL PROTECTED];[EMAIL PROTECTED]' SUBJECT = 'This is the subject' MSGBODY = 'This the body of the message ' ATTACHSTR = 'c:/ian.txt;c:/c55/footytip/2003finalresults.txt;c:/snap.jpg' MAILSERVER = 'insert mail server' port = 25 username = 'insert username' password = 'insert password' # trim the strings of any leading or trailing spaces FROM = FROM.strip() TO = TO.strip() SUBJECT = SUBJECT.strip() MSGBODY = MSGBODY.strip() ATTACHSTR = ATTACHSTR.strip() MAILSERVER = MAILSERVER.strip() username = username.strip() password = password.strip() # function to attach files def getAttachment(path, filename): ctype, encoding = mimetypes.guess_type(path) if ctype is None or encoding is not None: ctype = 'application/octet-stream' maintype, subtype = ctype.split('/', 1) fp = open(path, 'rb') if maintype == 'text': attach = MIMEText(fp.read(),_subtype=subtype) elif maintype == 'message': attach = email.message_from_file(fp) elif maintype == 'image': attach = MIMEImage(fp.read(),_subtype=subtype) elif maintype == 'audio': attach = MIMEAudio(fp.read(),_subtype=subtype) else: print maintype, subtype attach = MIMEBase(maintype, subtype) attach.set_payload(fp.read()) encode_base64(attach) fp.close attach.add_header('Content-Disposition', 'attachment', filename=filename) return attach #Connect to server print 'Connecting to mail server ', MAILSERVER try: s = smtplib.SMTP(MAILSERVER,port) #s.set_debuglevel(1) except: print 'ERROR: Unable to connect to mail server', MAILSERVER sys.exit(1) #login to server if password <> '': print 'Logging into mail erver' try: s.login(username,password) except: print 'ERROR: Unable to login to mail server', MAILSERVER print 'Please recheck your password' sys.exit(1) # get list of email addresses to send to ToList = TO.split(';') print 'Sending email to ', ToList # set up email parameters msg = MIMEMultipart() msg['From'] = FROM msg['To'] = TO msg['Subject'] = SUBJECT msg.attach(MIMEText(MSGBODY)) # get list of file attachments AttachList = ATTACHSTR.split(';') for file in AttachList: try: attach = getAttachment(file,os.path.basename(file)) msg.attach(attach) except: print 'Error attaching ',file pass # send email s.sendmail(FROM, ToList, msg.as_string()) s.quit() s.close() print 'done' - -- http://mail.python.org/mailman/listinfo/python-list
Re: Python To Send Emails Via Outlook Express
Hi Fredrik, Thank you for the suggestion. I tried different from/to settings and guess what? The mail came thru. The script is now.. import win32com.client s = win32com.client.Dispatch('CDO.Message') s.From = "[EMAIL PROTECTED]"(was "[EMAIL PROTECTED]") s.To = "[EMAIL PROTECTED]" (was "[EMAIL PROTECTED]") s.Subject = "The subject" s.Send() My problem is thought, the message is still not being sent via Outlook Express. What am I missing? Thanks again for your help so far!! Kind regards Ian -- http://mail.python.org/mailman/listinfo/python-list
Re: Python To Send Emails Via Outlook Express
Hi Ganesan Wow, I'm REALLY impressed with the high level of support in this forum. (Another great reason to continue learning Python I tried what you suggested. After trying a different from/to address the message is sent. But it is NOT sent via Outlook Express. I would appreciate any other suggestions. Thanks in advance The script is now.. import win32com.client s = win32com.client.Dispatch('CDO.Message') s.From = "[EMAIL PROTECTED]" s.To = "[EMAIL PROTECTED]" s.Subject = "The subject" cdoSourceOutlookExpress= 2 s.Configuration.Load(cdoSourceOutlookExpress) s.Send() -- http://mail.python.org/mailman/listinfo/python-list
Re: Python To Send Emails Via Outlook Express
Hi Steve, > Why the insistence on using Outlook Express, is you don;t mind me asking? Good question. The problem is that I have a developed a freeware application called Kirby Alarm And Task Scheduler (see www.kirbyfooty.com). The program can pop up a note, run a program, play a sound, or send an email at whatever intervals the user wants.. When it comes to sending emails the user has the option of sending them via smtp, or via there email client (eg outlook express). I prefer the send method as this makes setting up the email parameters a lot easier for the user. As the program is used by over 16,000 people around the world I don't want to complicate things by asking them to enter the mail server properties. I have written Kirby Alarm in Clarion. It can currently send the email via outlook express by calling MapiSendMail. I wanted to do the same thing in Python so I can build up a suite of useful utilities and therefore try an keep the program size relatively small. Ian -- http://mail.python.org/mailman/listinfo/python-list
Re: Python To Send Emails Via Outlook Express
Hi Max, Thanks for the suggestion. I'm always open to new ideas. Can you please tell me how to retrieve the default account settings from Outlook Express? Ian -- http://mail.python.org/mailman/listinfo/python-list
Re: Python To Send Emails Via Outlook Express
Hi Ganesan, I'm on the verge of giving up I don't suppose you could write a small script to send the email for me via the default windows email client. I will then try running your script and my end to see if it works ok. I may have missed something and would really appreciate your help. Thanks in advance Ian -- http://mail.python.org/mailman/listinfo/python-list
Re: Python To Send Emails Via Outlook Express
Heavy sigh... == This script WILL send the email import win32com.client s = win32com.client.Dispatch('CDO.Message') c = win32com.client.Dispatch('CDO.Configuration') cdoSourceOutlookExpress = 2 c.Load(cdoSourceOutlookExpress) s.Configuration = c s.From = "[EMAIL PROTECTED]" s.To = "[EMAIL PROTECTED]" s.Subject = "The subject" s.Send() == == But if a change the TO email address to a yahoo address the server rejects it import win32com.client s = win32com.client.Dispatch('CDO.Message') c = win32com.client.Dispatch('CDO.Configuration') cdoSourceOutlookExpress = 2 c.Load(cdoSourceOutlookExpress) s.Configuration = c s.From = "[EMAIL PROTECTED]" s.To = "[EMAIL PROTECTED]" s.Subject = "The subject" s.Send() == It's official. I have given up sending emails any other way but via smtp. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python To Send Emails Via Outlook Express
That sound really promising. Is there any chance you could forward me a copy of the script. I'm still very new to Python and it would help me a lot. Thanks again Ian -- http://mail.python.org/mailman/listinfo/python-list
Re: Python To Send Emails Via Outlook Express
Hi Lenard, Absolutely fantastic!! That worked like a charm. Now onto adapting it to send attachments. Thanks again Ian -- http://mail.python.org/mailman/listinfo/python-list
Re: Python To Send Emails Via Outlook Express
Hi Lenard, Absolutely fantastic!! That worked like a charm. Now onto adapting it to send attachments. Thanks again Ian -- http://mail.python.org/mailman/listinfo/python-list
Re: Python To Send Emails Via Outlook Express
Hi Lenard, As the risk of severely embarassing myself can I ask for your help one more time. I have tried changing your script to include attachments, but guess what, (and this should come as no suprise) I can't do it. So Here is my feeble attempt at changing the script.. import os from ctypes import * FLAGS = c_ulong LHANDLE = c_ulong LPLHANDLE = POINTER(LHANDLE) # Return codes SUCCESS_SUCCESS = 0 # Recipient class MAPI_ORIG = 0 MAPI_TO = 1 NULL = c_void_p(None) class MapiRecipDesc(Structure): _fields_ = [('ulReserved', c_ulong), ('ulRecipClass', c_ulong), ('lpszName', c_char_p), ('lpszAddress', c_char_p), ('ulEIDSize', c_ulong), ('lpEntryID', c_void_p), ] lpMapiRecipDesc = POINTER(MapiRecipDesc) class MapiFileDesc(Structure): _fields_ = [('ulReserved', c_ulong), ('flFlags', c_ulong), ('nPosition', c_ulong), ('lpszPathName', c_char_p), ('lpszFileName', c_char_p), ('lpFileType', c_void_p), ] lpMapiFileDesc = POINTER(MapiFileDesc) class MapiMessage(Structure): _fields_ = [('ulReserved', c_ulong), ('lpszSubject', c_char_p), ('lpszNoteText', c_char_p), ('lpszMessageType', c_char_p), ('lpszDateReceived', c_char_p), ('lpszConversationID', c_char_p), ('flFlags', FLAGS), ('lpOriginator', lpMapiRecipDesc), # ignored? ('nRecipCount', c_ulong), ('lpRecips', lpMapiRecipDesc), ('nFileCount', c_ulong), ('lpFiles', lpMapiFileDesc), ] lpMapiMessage = POINTER(MapiMessage) MAPI = windll.mapi32 MAPISendMail=MAPI.MAPISendMail MAPISendMail.restype = c_ulong # Error code MAPISendMail.argtypes = (LHANDLE, # lhSession c_ulong, # ulUIParam lpMapiMessage, # lpMessage FLAGS, # lpFlags c_ulong, # ulReserved ) def SendMail(recipient, subject, body, attach=[]): """Post an e-mail message using Simple MAPI recipient - string: address to send to subject - string: subject header body - string: message text attach - string: files to attach """ attach = map( os.path.abspath, attach ) nFileCount = len(attach) if attach: MapiFileDesc_A = MapiFileDesc * len(attach) fda = MapiFileDesc_A() for fd, fa in zip(fda, attach): fd.ulReserved = 0 fd.flFlags = 0 fd.nPosition = -1 fd.lpszPathName = fa fd.lpszFileName = None fd.lpFileType = None lpFiles = fda recip = MapiRecipDesc(0, MAPI_TO, None, recipient, 0, None) #msg = MapiMessage(0, subject, body, None, None, None, 0, # cast(NULL, lpMapiRecipDesc), 1, pointer(recip), # nFileCount, cast(NULL, lpMapiFileDesc)) msg = MapiMessage(0, subject, body, None, None, None, 0, cast(NULL, lpMapiRecipDesc), 1, pointer(recip), nFileCount, cast(NULL, lpFiles)) rc = MAPISendMail(0, 0, byref(msg), 0, 0) if rc != SUCCESS_SUCCESS: raise WindowsError, "MAPI error %i" % rc -- http://mail.python.org/mailman/listinfo/python-list
Re: Python To Send Emails Via Outlook Express
Hello again, Thanks for the advice! Unfortunately I still cannot get it to send attachments. It comes up with the following windows error.. (I have a feeling it has something to do with the file count) >>> import simplemapi >>> simplemapi.SendMail("[EMAIL PROTECTED]","The Subject","The body","c:\ian\ian.txt") nFileCount 14 Traceback (most recent call last): File "", line 1, in ? File "simplemapi.py", line 111, in SendMail raise WindowsError, "MAPI error %i" % rc WindowsError: MAPI error 2 This is the updated script.. -- import os from ctypes import * FLAGS = c_ulong LHANDLE = c_ulong LPLHANDLE = POINTER(LHANDLE) # Return codes SUCCESS_SUCCESS = 0 # Recipient class MAPI_ORIG = 0 MAPI_TO = 1 NULL = c_void_p(None) class MapiRecipDesc(Structure): _fields_ = [('ulReserved', c_ulong), ('ulRecipClass', c_ulong), ('lpszName', c_char_p), ('lpszAddress', c_char_p), ('ulEIDSize', c_ulong), ('lpEntryID', c_void_p), ] lpMapiRecipDesc = POINTER(MapiRecipDesc) class MapiFileDesc(Structure): _fields_ = [('ulReserved', c_ulong), ('flFlags', c_ulong), ('nPosition', c_ulong), ('lpszPathName', c_char_p), ('lpszFileName', c_char_p), ('lpFileType', c_void_p), ] lpMapiFileDesc = POINTER(MapiFileDesc) class MapiMessage(Structure): _fields_ = [('ulReserved', c_ulong), ('lpszSubject', c_char_p), ('lpszNoteText', c_char_p), ('lpszMessageType', c_char_p), ('lpszDateReceived', c_char_p), ('lpszConversationID', c_char_p), ('flFlags', FLAGS), ('lpOriginator', lpMapiRecipDesc), # ignored? ('nRecipCount', c_ulong), ('lpRecips', lpMapiRecipDesc), ('nFileCount', c_ulong), ('lpFiles', lpMapiFileDesc), ] lpMapiMessage = POINTER(MapiMessage) MAPI = windll.mapi32 MAPISendMail=MAPI.MAPISendMail MAPISendMail.restype = c_ulong # Error code MAPISendMail.argtypes = (LHANDLE, # lhSession c_ulong, # ulUIParam lpMapiMessage, # lpMessage FLAGS, # lpFlags c_ulong, # ulReserved ) def SendMail(recipient, subject, body, attach=[]): """Post an e-mail message using Simple MAPI recipient - string: address to send to subject - string: subject header body - string: message text attach - string: files to attach """ attach = map( os.path.abspath, attach ) nFileCount = len(attach) if attach: MapiFileDesc_A = MapiFileDesc * len(attach) fda = MapiFileDesc_A() for fd, fa in zip(fda, attach): fd.ulReserved = 0 fd.flFlags = 0 fd.nPosition = -1 fd.lpszPathName = fa fd.lpszFileName = None fd.lpFileType = None lpFiles = fda else: # No attachments lpFiles = cast(NULL, lpMapiFileDesc) # Make NULL print "nFileCount ",nFileCount recip = MapiRecipDesc(0, MAPI_TO, None, recipient, 0, None) #msg = MapiMessage(0, subject, body, None, None, None, 0, # cast(NULL, lpMapiRecipDesc), 1, pointer(recip), # nFileCount, cast(NULL, lpMapiFileDesc)) msg = MapiMessage(0, subject, body, None, None, None, 0, cast(NULL, lpMapiRecipDesc), 1, pointer(recip), nFileCount, lpFiles) rc = MAPISendMail(0, 0, byref(msg), 0, 0) if rc != SUCCESS_SUCCESS: raise WindowsError, "MAPI error %i" % rc -- Thanks again for your help so far on this. I really appreciate it! Have a safe and very merry Christmas. God bless!! Ian -- http://mail.python.org/mailman/listinfo/python-list
Re: Windows XP - cron or scheduler for Python?
Hi, I thought I'd throw in my 2 cents worth. I have written a freeware task scheduler that might be of interest to you. It's called Kirby Alarm And Task Scheduler. Over 16000 people around the world use it. Kirby Alarm will run a program, pop up a note, play a sound, or send an email at whatever intervals you like. Have a look at http://www.kirbyfooty.com/ or read what others have to say about it at http://www.download.com/Kirby-Alarm-And-Task-Scheduler/3000-2084_4-10260143.html?tag=stbc.gp To run a python script just put the following into the program name. (The quotes MUST be included wherever there are spaces in the command line) "C:\Python23\python.exe" "d:\mypython\Say Time.py" Have a great Christmas! God bless Ian -- http://mail.python.org/mailman/listinfo/python-list
Re: Python To Send Emails Via Outlook Express
Hi Lenard, You just beat me to it. Suprise, suprise, I discovered the answer myself this time. I have modified the script to allow the attachment(s) to still be passed as a string. Some error checking is also done to verify the attachment file exists. I have also modified it so it can be used for multiple email addresses. Here is the updated working script ... - import os from ctypes import * FLAGS = c_ulong LHANDLE = c_ulong LPLHANDLE = POINTER(LHANDLE) # Return codes SUCCESS_SUCCESS = 0 # Recipient class MAPI_ORIG = 0 MAPI_TO = 1 NULL = c_void_p(None) class MapiRecipDesc(Structure): _fields_ = [('ulReserved', c_ulong), ('ulRecipClass', c_ulong), ('lpszName', c_char_p), ('lpszAddress', c_char_p), ('ulEIDSize', c_ulong), ('lpEntryID', c_void_p), ] lpMapiRecipDesc = POINTER(MapiRecipDesc) class MapiFileDesc(Structure): _fields_ = [('ulReserved', c_ulong), ('flFlags', c_ulong), ('nPosition', c_ulong), ('lpszPathName', c_char_p), ('lpszFileName', c_char_p), ('lpFileType', c_void_p), ] lpMapiFileDesc = POINTER(MapiFileDesc) class MapiMessage(Structure): _fields_ = [('ulReserved', c_ulong), ('lpszSubject', c_char_p), ('lpszNoteText', c_char_p), ('lpszMessageType', c_char_p), ('lpszDateReceived', c_char_p), ('lpszConversationID', c_char_p), ('flFlags', FLAGS), ('lpOriginator', lpMapiRecipDesc), # ignored? ('nRecipCount', c_ulong), ('lpRecips', lpMapiRecipDesc), ('nFileCount', c_ulong), ('lpFiles', lpMapiFileDesc), ] lpMapiMessage = POINTER(MapiMessage) MAPI = windll.mapi32 MAPISendMail=MAPI.MAPISendMail MAPISendMail.restype = c_ulong # Error code MAPISendMail.argtypes = (LHANDLE, # lhSession c_ulong, # ulUIParam lpMapiMessage, # lpMessage FLAGS, # lpFlags c_ulong, # ulReserved ) def SendMail(recipient, subject, body, attachfiles): """Post an e-mail message using Simple MAPI recipient - string: address to send to (multiple address sperated with a semicolin) subject - string: subject header body - string: message text attach - string: files to attach (multiple attachments sperated with a semicolin) Example usage import simplemapi simplemapi.SendMail("[EMAIL PROTECTED];[EMAIL PROTECTED]","My Subject","My message body","c:\attachment1.txt;c:\attchment2") """ # get list of file attachments attach = [] AttachWork = attachfiles.split(';') #verify the attachment file exists for file in AttachWork: if os.path.exists(file): attach.append(file) attach = map( os.path.abspath, attach ) nFileCount = len(attach) if attach: MapiFileDesc_A = MapiFileDesc * len(attach) fda = MapiFileDesc_A() for fd, fa in zip(fda, attach): fd.ulReserved = 0 fd.flFlags = 0 fd.nPosition = -1 fd.lpszPathName = fa fd.lpszFileName = None fd.lpFileType = None lpFiles = fda else: # No attachments lpFiles = cast(NULL, lpMapiFileDesc) # Make NULL # Get the number of recipients RecipWork = recipient.split(';') RecipCnt = len(RecipWork) # Formulate the recipients MapiRecipDesc_A = MapiRecipDesc * len(RecipWork) rda = MapiRecipDesc_A() for rd, ra in zip(rda, RecipWork): rd.ulReserved = 0 rd.ulRecipClass = MAPI_TO rd.lpszName = None rd.lpszAddress = ra rd.ulEIDSize = 0 rd.lpEntryID = None recip = rda # send the message msg = MapiMessage(0, subject, body, None, None, None, 0, cast(NULL, lpMapiRecipDesc), RecipCnt, recip, nFileCount, lpFiles) rc = MAPISendMail(0, 0, byref(msg), 0, 0) if rc != SUCCESS_SUCCESS: raise WindowsError, "MAPI error %i" % rc --- -- http://mail.python.org/mailman/listinfo/python-list
Re: Python To Send Emails Via Outlook Express
I wish I new why google doesn't show nicely aligned python code when you paste the script. Anyways, in case this helps someone else you can download the script from http://www.kirbyfooty.com/simplemapi.py Ian -- http://mail.python.org/mailman/listinfo/python-list
Re: Python To Send Emails Via Outlook Express
Hey guys, I'm just thankful the answer has been found and hope this helps someone else. To everyone (especially Lenard) that responded to my request for help, thank you!! Merry Christmas everyone!!! God bless Ian -- http://mail.python.org/mailman/listinfo/python-list
Re: Python To Send Emails Via Outlook Express
Hi David, I'd be happy to post it to python-win32 but don't know how. Ian -- http://mail.python.org/mailman/listinfo/python-list
Re: Windows XP - cron or scheduler for Python?
Hi Esmail, Kirby Alarm is written in Clarion. Sorry, but I want to keep the source code to myself. Ian -- http://mail.python.org/mailman/listinfo/python-list
Re: Python 3 regex?
On 12/01/2015 18:03, Jason Bailey wrote: Hi all, I'm working on a Python _3_ project that will be used to parse ISC DHCPD configuration files for statistics and alarming purposes (IP address pools, etc). Anyway, I'm hung up on this one section and was hoping someone could provide me with some insight. My script first reads the DHCPD configuration file into memory - variable "filebody". It then utilizes the re module to find the configuration details for the wanted "shared network". Hi Jason, If you actually look at the syntax of what you are parsing, it is very simple. My recommendation would be to write a recursive decent parser for your files. That way will be easier to write, much easier to modify and almost certainly faster that a RE solution - and it can easily give you all the information in the file thus future proofing it. 'Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems.' - Jamie Zawinski. Regards Ian -- https://mail.python.org/mailman/listinfo/python-list
Re: Deep vs. shallow copy?
On 13/03/2014 03:09, Rustom Mody wrote: Call the action-world the 'imperative' world. Call the value-world the 'functional' world ('declarative' would be better but 'functional' is too entrenched). [Following table meant to be read with fixed (courier) font] | | Imperative | Functional | | Language entity | Statement | Expression | | Denote (and think with) | Action | Value | | Abstracted into | Procedure | Function| | Atoms are | Assignment | Constant/Variable | | Data Structures | Mutable| Immutable | | Loop primitive | Recursion | Iteration | | World is| In time| Timeless (Platonic) | Small typo I think in that the looping Primitives are switched about? Regards Ian -- Ian Hobson 29 Manorfield Close, Northampton NN3 9SL, Tel: 01604 513875 Preparing eBooks for Kindle and ePub formats to give the best reader experience. -- https://mail.python.org/mailman/listinfo/python-list
python.org appears to be down
Hopefully someone who can do something about it will read this. -- http://mail.python.org/mailman/listinfo/python-list
Re: Need some help here
"Frank Drackman" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] : : "Kareem840" <[EMAIL PROTECTED]> wrote in message : news:[EMAIL PROTECTED] : > Hello. Unfortunately, I am in need of money to pay my credit card : > bills. If you could spare just $1, I would be grateful. I have a Paypal : > account. [EMAIL PROTECTED] I swear this will go to my card : > balances. Thank you. : > : : Sell your sperm, we don't want you to reproduce. erm can i just point out the flaw in your suggestion frank... -- http://mail.python.org/mailman/listinfo/python-list
Problem with time
Hi, i have a problem with time in python. 1) i got 2 values from mysql db (fields are "time" type) 2) python get it as "" (why timedelta???) 3) i need to compare 2 fields with actual time ... EG: if ArrOutputsAuto[i].TimeFrom >= GNow and ArrOutputsAuto[i].TimeTo <= GNow: i need actual time, and 2 fields from DB in datetime.time type (correct me if i'm wrong) so i can do my test "if time>= ..." I think i can grab time from DB in string and parse it in datetime.time(x,x,x) but its not very optimized Any idea ? Thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem with time
"Steve Holden" <[EMAIL PROTECTED]> a écrit dans le message de news: [EMAIL PROTECTED] > import time > import datetime > > dbtd = > h, m, s = time.localtime()[3:6] > timenow = s + (60 * (m + 60 * h)) Look like ok, thanks all :) -- http://mail.python.org/mailman/listinfo/python-list
sys.excepthook and threads
Hi, sys.excepthook don't work if an exception come in a thread... It's normal or its a bug ? There are any tip ? look here : http://spyced.blogspot.com/2005_06_01_archive.html Thx -- http://mail.python.org/mailman/listinfo/python-list
list property fires get on append
I've created a class that has a property which points at a private list. When I try to use the append() function on this list property, the fget method is fired rather than the fset method. If I directly set my property to a literal list, the set method fires. Here's a stripped down version of my code: class Hierarchy(object): _children = [] def __init__(self): return def get_children(self): print("GETTING") return self._children def set_children(self, value): print("SETTING") self._children = value children = property(get_children, set_children) -USAGE-- import Hierarchy hierarchy = Hierarchy.Hierarchy() # this fires a get for some reason hierarchy.children.append( Hierarchy.Hierarchy()) # this fires a set as expected hierarchy.children = [Hierarchy.Hierarchy()] --RESULT-- it prints: GETTING SETTING -- http://mail.python.org/mailman/listinfo/python-list
style question - hasattr
In old python code i would use 'has_key' to determine if an element was present in a dictionary. Python 3.0 will even removed 'has_key'. The reason for removal is that using the 'in' operator is a cleaner syntax and having two ways to achieve the same result is against the principle of the language. Ok, so what about 'hasattr' ?? hasattr(myObject,'property') seems equivalent to 'property' in dir(myObject) I would suggest that using the 'in' is cleaner in this case also. Is there a performance penalty here? Or is there reason why the two are not actually the same? Which style is preferred?? -- http://mail.python.org/mailman/listinfo/python-list
Re: SQLite3 and lastrowid
On Nov 16, 1:00 pm, fuglyducky wrote: > Before I added the second table I could simply run > 'print(cursor.lastrowid)' and it would give me the id number. However, > with two tables I am unable to do this. It would help if you would show the code where you're trying to do this. Without your actual code to look at, we can't tell you why it doesn't work. > Does anyone know if there is a way to reference one table or another > to get lastrowid? cursor.lastrowid is always in reference to the last query executed by the cursor, not in reference to a table. If you don't capture the value, and then you execute another query on the same cursor, the previous value of cursor.lastrowid no longer exists. If you need it now, then either you should have captured it when you had the chance, or you should not have executed another query on the same cursor. But perhaps this is not what you're actually trying to do. I can't tell, because I haven't seen the code. Cheers, Ian -- http://mail.python.org/mailman/listinfo/python-list
Re: SQLite3 and lastrowid
On Nov 16, 2:08 pm, fuglyducky wrote: > db_connect = sqlite3.connect('test.db') > cursor = db_connect.cursor() > > print(cursor.lastrowid) At this point you haven't executed a query yet, so there is no meaningful value that cursor.lastrowid can take. > # Choose random index from DB - need to understand lastrowid > #row_count = cursor.lastrowid > #random_row = random.randrange(0, row_count) This is wrong. The lastrowid is not the number of rows in the table. It's the row-id of the row that was inserted (if any) by the last query executed by the cursor. In the case of sqlite3, I think the row- id is just the primary key if it's an integer (but in general the row- id is database-dependent), so you *might* be able to get away with it if you always let it autoincrement when inserting, never delete any rows, and never change their primary keys. But it's unreliable and only available immediately after an insert, so don't do it that way. The proper way to get the number of rows is to use the COUNT aggregate function, e.g., "SELECT COUNT(*) FROM TABLE1", which will return a single row with a single column containing the number of rows in table1. Cheers, Ian -- http://mail.python.org/mailman/listinfo/python-list
Re: Collect output to string
On Nov 23, 1:59 pm, Burton Samograd wrote: > Thanks for the tip. Here's my function: > > def with_output_to_string(f, args): > oldstdout = sys.stdout > buffer = StringIO.StringIO() > sys.stdout = buffer > apply(f, args) > sys.stdout = oldstdout > return buffer.getvalue() > > Any way I could improve it? You should wrap the inner function call in a try-finally call to ensure that the old stdout gets restored even if f raises an exception. Also, the `apply` function is deprecated. Use `f(*args)` instead. The function as a whole would be a bit more Pythonic if written as a decorator IMO, but that's your call. Cheers, Ian -- http://mail.python.org/mailman/listinfo/python-list
Re: Style question for conditional execution
On Nov 24, 11:46 am, Gerald Britton wrote: > Say that I have some function "f" that I will execute if some variable > "v" evaluates true. Using a classical procedural approach, I might > write: > > if v: > f() > > I might, however, think more in a functional-programming direction. > Then I might write: > > v and f() The idea that "if" is inherently procedural is mistaken. Functional programming emphasizes the use of functions (in the mathematical sense) over changes in state. Assuming that f has no side effects, either of the above could equally be viewed as functional. (Of course, the fact that the return value is simply discarded in both of the above cases suggests that f *does* have side effects, in which case neither of the above should be viewed as functional.) That said, the 'if' version is clearer, so I would nearly always go with that. The rare exception would be if I were genuinely interested in capturing the value of "v" if it evaluated false. I can't remember the last time that was the case. Cheers, Ian -- http://mail.python.org/mailman/listinfo/python-list
Re: Packages at Python.org
On Dec 1, 1:38 pm, "kirby.ur...@gmail.com" wrote: > http://packages.python.org/dbf/ > > So how *do* you get source code from such a web place? I'm not > finding > a tar ball or installer. Sorry if I'm missing something obvious, like > a link > to Sourceforge. That site only contains documentation. Try this page instead: http://pypi.python.org/pypi/dbf/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Google AI challenge: planet war. Lisp won.
On Dec 2, 5:59 pm, tivrfoa wrote: > On Dec 2, 3:06 pm, Xah Lee wrote: > > > > > discovered this rather late. > > > Google has a AI Challenge: planet wars.http://ai-contest.com/index.php > > > it started sometimes 2 months ago and ended first this month. > > > the winner is Gábor Melis, with his code written in lisp. > > > Congrats lispers! > > > Gábor wrote a blog about it > > herehttp://quotenil.com/Planet-Wars-Post-Mortem.html > > > (not sure if this has been mentioned here but quick search didn't find > > it) > > > Xah ∑http://xahlee.org/☄ > > this game is very cool and it's hard .. > arghhttp://www.galcon.com/flash/play.php For what it's worth, I recollect that the original GalCon was written in Python as part of one of the PyWeek competitions. ;-) Cheers, Ian -- http://mail.python.org/mailman/listinfo/python-list
Re: win32com pythonwin extensions part of stdlib?
On Dec 7, 11:02 am, harijay wrote: > Hi I am using Python 2.6.5 on Windows. > > I wanted to start using the win32com extensions which I understand are > "essentially part of the stdlib" ( quoted > inhttp://tgolden.sc.sabren.com/python/win32_how_do_i.html) > Since I didnt have the extensions as standard I went to sourceforge > to get the module. > > However when I tried to do a distutils install of the python > extensions for windows downloaded from sourceforge , I found out I > need some proprietary components from Microsoft visual studio > 7)."vcsvarsall.bat" needed. > > My question is : Can I use the win32com extensions on a licensed > windows setup without having access to Visual Studio components. > > I did see some places where they suggested compiling with mingw32 , > but the compilation didnt work. > > Any help in getting the module running would be greatly appreciated There are pre-built binary distributions available on sourceforge. Why not just use one of those? -- http://mail.python.org/mailman/listinfo/python-list
Re: Collision of rotated rectangles without pygame
On Dec 7, 4:11 pm, Steve Holden wrote: > >>> timeit.timeit(fm) > 0.58099985122680664 > >>> timeit.timeit(fd) > 0.5524577636719 > > Of course it's possible that the random number generation is dominating, I think that it is. Moving the random number generation out into setup: >>> t1 = timeit.Timer("sin(x.next())", "from math import sin, radians; import >>> random; x = iter([random.random() for i in xrange(100)])") >>> t1.timeit(100) 0.45154733352978838 >>> t2 = timeit.Timer("d[x.next()]", "import math, random; x = >>> iter([random.randrange(360) for i in xrange(100)]); d = dict((i, >>> math.sin(math.radians(i))) for i in xrange(360))") >>> t2.timeit(100) 0.21765364033694823 Of course, the dict approach assumes that all angles will be an integer number of degrees. One could add precision, but looking up specific float values in a dict is dicey, so then one has to switch to decimal math, and that's going to add extra overhead -- probably enough to tip the scales in favor of math.sin. Cheers, Ian -- http://mail.python.org/mailman/listinfo/python-list
Re: continuing development on modules after they're installed
On Dec 10, 9:57 am, hoesley wrote: > I just started using distutils to install the modules I'm working on > to site-packages. Now, however, if I make changes in my development > directory, then import the modules into python, it always loads up the > installed version. Thus, I can't continue development without first > uninstalling the modules I'm working on, so that the interpreter finds > them in the local directory instead of site-packages. Is there any > simple way around this? I figure this must be a very common thing to > encounter. Thanks! Do you need the installed version to be distinct from the development version? If not, you can "install" the module using a simple soft link (on Unix) or a .pth file (on Windows) that points to your development directory. If you do need them to be distinct, a simple way to preferentially get the development version is to add it to the *beginning* of sys.path: sys.path.insert(0, '/path/to/development/directory/') This process can be simplified further by putting it in a PYTHONSTARTUP script. HTH, Ian -- http://mail.python.org/mailman/listinfo/python-list
Re: surprised by import in python 2.6
On Dec 10, 3:06 pm, Stefaan Himpe wrote: > Somehow, in the first session I cannot modify the global variable a > returned from f, but in the second session I can. To my eye, the only > difference seems to be a namespace. Can anyone shine some light on this > matter? It's not the same global variable. In the second session, you import the module test and bind it to the name "test" in the main namespace. "test.a" and "test.f" refer to the objects named "a" and "f" in the test namespace. In the first session, you import all the variables exported by the module test and bind them using the same names in the main namespace. Thus "a" and "test.a" refer to the same int; and "f" and "test.f" refer to the same function, but they are not the same variables. When you rebind the name "a", it does not also magically rebind "test.a", and vice versa. Cheers, Ian -- http://mail.python.org/mailman/listinfo/python-list
Re: while True or while 1
On Dec 16, 4:34 pm, "BartC" wrote: > def p2(n): > p=1 > whileTrue: > if n<=p: return p > p<<=1 > return 0 > > for i in xrange(100): > x=p2(i) > > p2() calculates the smallest power of 2 >= it's operand. def p2(n): return 1 << n.bit_length() -- http://mail.python.org/mailman/listinfo/python-list
Re: Convert arbitrary function inputs to string
On Jan 6, 9:23 am, David wrote: > Hi, > > I'd like to have a function that takes arbitrary inputs and returns > them as a single string, with proper escapes for special characters I > can define. For example: What sorts of arbitrary inputs? Strings? Sequences of strings? Something else? It's not clear from your examples, which use invalid syntax. If you're looking for something like the "quote" form from Lisp, you can't really do that in Python. Just use a string. Cheers, Ian -- http://mail.python.org/mailman/listinfo/python-list
Re: Convert arbitrary function inputs to string
On Jan 6, 9:42 am, David Dreisigmeyer wrote: > Yes, I'm calling Gambit-C from Python and would like to make this > cleaner. Instead of having to do something like: > > gambit.eval ("(print \"Hello\n\")") > > I want to do this: > > gambit.eval (print "Hello\n") > > so that the expression following gambit.eval is a standard scheme expression. That's much clearer. As I indicated in my previous email, there is no way to do this in Python. You might try using a raw multi-line string literal to reduce the amount of escaping you need to do. So this: "(print \"Hello\\n\")" becomes this: r"""(print "Hello\n")""" Cheers, Ian -- http://mail.python.org/mailman/listinfo/python-list
Re: PEP: possibility of inline using of a symbol instead of "import"
On Jan 6, 9:32 am, Tim Harig wrote: > 2. Your so-called PEP probably clashes with Python's use of @ for > decorators. > > 3. Do you really expect a language holding the mantra that there should be > a single way of doing things to embrace a language bloating feature > for what is effectively already possible with the language as it > exists? Isn't "Python's use of @ for decorators" a "language bloating feature for what [was] effectively already possible with the language as it [existed]?" ;-) Cheers, Ian -- http://mail.python.org/mailman/listinfo/python-list
Re: type of methods of builtin exceptions
On Jan 6, 9:41 am, Eva Maia wrote: > Hi, > > anyone has a list of the types of methods of builtin exceptions. For > example, for the exception BaseException i need to know the type of > arguments method __reduce__ and type of your return. http://docs.python.org/library/pickle.html?highlight=__reduce__#object.__reduce__ Another good place to start would be: http://docs.python.org/reference/datamodel.html#special-method-names Cheers, Ian -- http://mail.python.org/mailman/listinfo/python-list
Re: python only prints integers
On Jan 6, 3:49 pm, francesco wrote: > I'm pretty new in Python language. I have a problem with numbers: it > seems python doesn't know any more how to count! > I get only the down rounded integer > 20/8 = 2 > 8/3=2 > I probably changed some option to round the numbers, but I don't > remember how. > Is there a way to reset the number of digits to default? In Python 2, the '/' operator performs integer division by default when both its operands are integers. To change this, either place this at the top of the file: from __future__ import division or convert your numbers to floats: >>> 20.0 / 8.0 2.5 >>> float(20) / float(8) 2.5 In Python 3, the '/' operator always performs true division. -- http://mail.python.org/mailman/listinfo/python-list
Re: Nothing to repeat
On 09/01/2011 16:49, Tom Anderson wrote: Hello everyone, long time no see, This is probably not a Python problem, but rather a regular expressions problem. I want, for the sake of arguments, to match strings comprising any number of occurrences of 'spa', each interspersed by any number of occurrences of the 'm'. 'any number' includes zero, so the whole pattern should match the empty string. Here's the conversation Python and i had about it: Python 2.6.4 (r264:75706, Jun 4 2010, 18:20:16) [GCC 4.4.4 20100503 (Red Hat 4.4.4-2)] on linux2 Type "help", "copyright", "credits" or "license" for more information. import re re.compile("(spa|m*)*") Traceback (most recent call last): File "", line 1, in File "/usr/lib/python2.6/re.py", line 190, in compile return _compile(pattern, flags) File "/usr/lib/python2.6/re.py", line 245, in _compile raise error, v # invalid expression sre_constants.error: nothing to repeat What's going on here? Why is there nothing to repeat? Is the problem having one *'d term inside another? Now, i could actually rewrite this particular pattern as '(spa|m)*'. But what i neglected to mention above is that i'm actually generating patterns from structures of objects (representations of XML DTDs, as it happens), and as it stands, patterns like this are a possibility. Any thoughts on what i should do? Do i have to bite the bullet and apply some cleverness in my pattern generation to avoid situations like this? Thanks, tom I think you want to anchor your list, or anything will match. Perhaps re.compile('/^(spa(m)+)*$/') is what you need. Regards Ian -- http://mail.python.org/mailman/listinfo/python-list
Re: Nothing to repeat
On 09/01/2011 17:49, Ian wrote: I think you want to anchor your list, or anything will match. Perhaps My bad - this is better re.compile('^((spa)*(m)*)+$') search finds match in 'spa', 'spaspaspa', 'spammmspa', '' and 'mmm' search fails on 'spats', 'mats' and others. -- http://mail.python.org/mailman/listinfo/python-list
Re: Help needed with unittest and global
On 09/01/2011 19:53, Dave Angel wrote: On 01/-10/-28163 02:59 PM, Ian Hobson wrote: Hi all, I am trying to develop a PyQt application, and I want to unittest it. snip D:\work\ian>python testAll.py E == ERROR: test001_walkingSkeleton (testCubic.testCubic) -- Traceback (most recent call last): File "D:\work\ian\testCubic.py", line 8, in test001_walkingSkeleton app.processEvents() # fails NameError: global name 'app' is not defined You have two global variables called app, one is in the testCubic module and the other is in the testAll.py script. They do not automatically refer to the same thing. To use a global from another module, you can either do an import, or you can pass it as an argument. But beware of mutual imports. DaveA Thanks David, I found http://mail.python.org/pipermail/tutor/2002-November/018353.html and created a shared module that both modules can import. Then I refer to shared.app, no use of global and it works as desired. I am on to the next step - actually running my code. Regards Ian -- http://mail.python.org/mailman/listinfo/python-list
Re: WxPython versus Tkinter.
On Jan 25, 4:01 pm, Nicholas Devenish wrote: > Personally, no, it probably wouldn't have caused me not to use wx. But > it certainly would have put a mental tick in the against box, because a > frameworks community matters. As a little aside, a personal example is > Django, whose tutorial contained what to my un-django-trained eye looked > like an inconsistency bug, without explanation. I filed a bug report, > and apparently many other people have had the same misassumption > (indicating a problem with the tutorial). The bug was closed with words > effectively equivalent to "Stupid newbie". Ignoring the fact that > documentation being consistently misinterpreted should indicate a real > problem, why should I put my time and effort into learning a framework > with a community that is so hostile, when there are plenty of alternatives? Speaking as a Django user and occasional developer, I'm sorry to hear that you had a bad experience with the Django community. I have generally found it to be friendly and helpful, at least on the mailing list and the IRC channel. The ticket triagers have 1800+ open tickets to organize, so they can get ornery about duplicates at times. Are you referring to ticket #14081? I expect the reason this hasn't been addressed is because nobody has submitted a patch or suggested an improved wording. If you were to make a suggestion, I doubt that anybody would be hostile to the idea of improving the tutorial. Cheers, Ian -- http://mail.python.org/mailman/listinfo/python-list
Re: Style question: Nicknames for deeply nested objects
On 30/01/2011 17:51, Gerald Britton wrote: Hi all, Today I was thinking about a problem I often encounter. Say that I have (seems I often do!) a deeply nested object, by which I mean object within object with object, etc. For example: x = some.deeply.nested.object.method(some.other.deeply.nested.object.value) Well, that's extreme but I've worked with code approaching that level of nested-ness. Now, consider two scenarios: 1. You need to call this thing many times with different arguments, so you wind up with: x = some.deeply.nested.object.method(some.other.deeply.nested.object.value1) y = some.deeply.nested.object.method(some.other.deeply.nested.object.value2) z = some.deeply.nested.object.method(some.other.deeply.nested.object.value3) Neither. You should tell. Don't ask if you can avoid it. Compare... queen.getButter() and queen.dairymaid.alderney.getButter() see http://www.timelessteacherstuff.com/readerstheater/KingsBreakfast.pdf king doesn't care where or how the butter is brought. Neither should your code! What are you doing with value1, value2 and value3 when you have them anyway? Stuffing them 3 levels deep into something else? Stop writing procedural code, and write object oriented code instead! If you you make some tell deeply.nested.object about other.deeply.nested.object it can fetch its own values, but it might be better to have some tell other.deeply.nested.object about deeply.nested.object to it can issue the correct commands. Then you tell some to do Somthing by writing some.takeMeaningfullAction() and it all happens "under the covers". Regards Ian -- http://mail.python.org/mailman/listinfo/python-list
Re: Create classes at runtnime
On Feb 4, 2:32 pm, Peter Otten <__pete...@web.de> wrote: > > (note: "" means that the number of attributes can be variable) > > > class VirtualUserLimitForm(ModelForm): > > swap_limit = forms.CharField(max_length=100, > > initial=monitor1.default_limit) > > memory_limit = forms.CharField(max_length=100, > > initial=monitor2.default_limit) > > ... > > > class Meta: > > model = model > > > def __init__(self, *args, **kwargs): > > super(VirtualUserLimitForm, self).__init__(*args, **kwargs) > > if 'instance' in kwargs: > > self.fields['swap_limit'].initial = > > kwargs['instance'].monitoring.filter(monitor=monitor1)[0].current > > self.fields['memory_limit'].initial = > > kwargs['instance'].monitoring.filter(monitor=monitor2)[0].current > > ... > > > I can generate all the needed code as string and then use exec(), but > > it seems ugly to me. I'm wondering if there is another way more > > elegant to do that? metaclasses maybe? > > The metaclass does indeed take a dictionary argument where you can provide > class attributes, e. g.: > > >>> C = type("C", (), dict(a=1, b=lambda self: 42)) > >>> C().a, C().b() > > (1, 42) This approach will basically work, but since you're subclassing the Django ModelForm, note that it already has its own metaclass: >>> django.forms.ModelForm.__class__ So you will need to either subclass ModelFormMetaclass for your metaclass and override the __init__ method, or modify what Peter posted like so: >>> C = django.forms.ModelForm.__class__("VirtualUserLimitForm", >>> (django.forms.ModelForm,), dict(a=1, b=lambda self: 42)) Cheers, Ian -- http://mail.python.org/mailman/listinfo/python-list
Re: Create classes at runtnime
On Feb 4, 5:49 pm, Steven D'Aprano wrote: > Just add in the class attributes you want after creating the class. > > class VirtualUserLimitForm(ModelForm): > pass > > f = forms.CharField # alias for brevity > for name, value in [ > ('swap_limit', f(max_length=100, initial=monitor1.default_limit)), > ('memory_limit', f(max_length=100, initial=monitor2.default_limit)), > ('spam', 'spam spam spam spam'), > ('eggs', 'fried sunny side up'), > ]: > setattr(VirtualUserLimitForm, name, value) This would probably cause some problems with the Django metaclass. It inspects the class dictionary for fields at the time the class in constructed, and so it would miss any fields added after construction time. -- http://mail.python.org/mailman/listinfo/python-list
Re: Are Small Dogs Good with Kids?
On Feb 7, 12:19 am, Bob Martin wrote: > You cannot generalise. It depends on how they are brought up. > My two terriers absolutely love children. Please don't reply to spam. -- http://mail.python.org/mailman/listinfo/python-list
Re: splitting by double newline
On Feb 7, 10:43 am, Nikola Skoric wrote: > Hello everybody, > > I'd like to split a file by double newlines, but portably. Now, > splitting by one or more newlines is relatively easy: > > self.tables = re.split("[\r\n]+", bulk) > > But, how can I split on double newlines? I tried several approaches, > but none worked... self.tables = re.split(r'(?:\r\n){2,}|\r{2,}|\n{2,}', bulk) -- http://mail.python.org/mailman/listinfo/python-list
Re: Arrays/List, filters, Pytho, Ruby
On Feb 11, 2:24 pm, "LL.Snark" wrote: > Hi, > > I'm looking for a pythonic way to translate this short Ruby code : > t=[6,7,8,6,7,9,8,4,3,6,7] > i=t.index {|x| xhttp://mail.python.org/mailman/listinfo/python-list
Re: Problems of Symbol Congestion in Computer Languages
On 18/02/2011 07:50, Chris Jones wrote: Always struck me as odd that a country like Japan for instance, with all its achievements in the industrial realm, never came up with one single major piece of software. I think there are two reasons for this. 1) Written Japanese is so hard that the effective illiteracy rate in Japan is astonishingly high. Both UK and Japan claim 99% literacy rate, but UK has 10-20% who find reading so hard they don't read. In Japan by some estimates the proportion is about half. Figures from memory. Result - too many users struggle to read instructions and titles on screen. Help texts? Forgetaboutit. 2) Culture. In the West, a designer will decide the architecture of a major system, and it is a basis for debate and progress. If he gets it wrong, it is not a personal disgrace or career limiting. If it is nearly right, then that is a major success. In Japan, the architecture has to be a debated and agreed. This takes ages, costs lots, and ultimately fails. The failure is because architecture is always a trade off - there is no perfect answer. I was involved in one software project where a major Japanese company had done the the feasibility study. It was much much too expensive. The UK company I worked for was able, not only to win the bid, but complete the job profitably for less than the Japanese giant had charged for the feasibility study. We ignored their study - we did not have time to read through the documentation which took 10 foot of shelf space to house. Ian -- http://mail.python.org/mailman/listinfo/python-list
Re: python and parsing an xml file
On 21/02/2011 22:08, Matt Funk wrote: Why? mmmh. not sure how to answer this question exactly. I guess it's a design decision. I am not saying that it is best one, but it seemed suitable to me. I am certainly open to suggestions. But here are some requirements: 1) My boss needs to be able to read the input and make sense out of it. XML seems fairly self explanatory, at least when you choose suitable names for the properties/tags etc ... 2) I want reproducability of a given run without changes to the code. I.e. all the inputs need to be stored external to the code such that the state of the run is captured from the input files entirely. Hi Mark, Having tried XML for something similar, I would strongly advise against it. It has been nothing but a nightmare. XML is acceptable for machine to machine communication where the two sides cannot agree a common language in advance or they can't coordinate format changes. Even then it is slow and verbose. Use the config module if the configuration is simple to moderately complex. Consider JSON or Python (source) if your requirements are really complicated. Regards Ian -- http://mail.python.org/mailman/listinfo/python-list
Re: Python fails on math
On 22/02/2011 13:20, christian schulze wrote: Hey guys, I just found out, how much Python fails on simple math. I checked a simple equation for a friend. [code] from math import e as e from math import sqrt as sqrt 2*e*sqrt(3) - 2*e == 2*e*(sqrt(3) - 1) False [/code] So WTF? The equation is definitive equivalent. (See http://mathbin.net/59158) PS: #1: 2.0 * e * sqrt(3.0) - 2.0 * e 3.9798408154464964 #2: 2.0 * e * (sqrt(3.0) -1.0) 3.979840815446496 I was wondering what exactly is failing here. The math module? Python, or the IEEE specifications? -- What has failed you is your understanding of what floating point means. Both sides of your equation contain e which is an irrational number. No irrational number and many rational ones cannot be expressed exactly in IEEE format. (1/3, 1/7) All that has happened is that the two sides have come out with very slightly different approximations to numbers that they cannot express exactly. Regards Ian -- http://mail.python.org/mailman/listinfo/python-list
Re: non-uniform distribution
On 12/06/10 11:05, Javier Montoya wrote: Dear all, I need to generate a vector of random float numbers between [0,1] such that their sum equals 1 and that are distributed non-uniformly. Is there any python function that generates such a vector? Best wishes Hi Javier, The answer to your question is "No", and the reason is that your requirement is impossible. Whatever distribution you choose - and you have not said what you require - will be altered by any scaling to meet the constraint that the total is 1. What exactly are you trying to achieve? Regards Ian -- http://mail.python.org/mailman/listinfo/python-list
Re: a +b ?
On 14/06/2010 02:35, alex23 wrote: Python isn't PHP, its built-ins are nowhere near as exhaustive, something like 80ish vs 2000+ functions? Not exactly a huge lookup burden. The problem is not learning Python, its learning about the standard libraries that Python gives you access to! .NET from Iron Python anyone? Regards Ian -- http://mail.python.org/mailman/listinfo/python-list
Re: Where is StackPanel in IronPython / .Net 4?
Hi Benjamin - and thanks for your reply. I'm now really confused. On 27/06/2010 20:05, Benjamin Kaplan wrote: You don't add references to namespaces. You add references to assemblies and you then you import the namespace. > From the documentation: ''' Namespace: System.Windows.Controls Assembly: PresentationFramework (in PresentationFramework.dll) ''' So you would do clr.AddReference("PresentationFramework") import System.Windows.Controls I tried from System.Windows.Controls import StackPanel and it worked fine. Now I need VerticalAlignment.Top From http://msdn.microsoft.com/en-us/library/system.windows.verticalalignment%28v=VS.95%29.aspx I learn that this is in the VerticalAlignment Enumeration Quote *Namespace:* System.Windows <http://msdn.microsoft.com/en-us/library/system.windows%28v=VS.95%29.aspx> *Assembly:* System.Windows (in System.Windows.dll) ^^^ End quote So I write clr.AddReference('System.Windows') and it errors - Could not add reference to System.Windows So clearly I still don't understand something rather basic. More help please. Thanks Ian -- http://mail.python.org/mailman/listinfo/python-list
Re: Is This Open To SQL Injection?
On 07/07/2010 19:38, Victor Subervi wrote: Hi; I have this code: sql = 'insert into personalDataKeys values (%s, %s, %s)' % (store, user, ', %s'.join('%s' * len(col_vals)) cursor.execute(sql, col_vals) Is this open to injection attacks? If so, how correct? TIA, beno Yes, it is trivially open to injection attacks. What would happen if someone enters the next line into one of your col_vals x,y);DROP DATABASE personalDataKeys; ha ha Your sql statement would be closed early by the semicolon, and the DROP TABLE personalDataKeys is then executed and would cause some unexpected data loss. Things could be more serious - DROP DATABASE mysql; for a mysql installation for example. You must always always every time and without any exceptions what-so-ever, put all and every piece of data that comes from outside the program through the appropriate routine to make whatever has been entered into storable data and not part of the sql statement. In php this is mysql_real_escape_string(). In your favourite language there will be an equivalent. If you miss just one occurrence its like leaving the side window unlocked! Someone will get in one day. Regards Ian p.s. Did I mention that there are no exceptions to the "sanitise every piece of data" rule? -- http://mail.python.org/mailman/listinfo/python-list
Re: Visitor pattern and separating iteration
Hi Karsten, On 22/07/2010 12:03, Karsten Wutzke wrote: What is it I'm missing? I think you are making it more complicated than it really is. The visitor pattern is about bringing all the little bits that would otherwise be scattered all over many node classes into one visitor class. For code generation this means that all the code generation is done in your visitor class. For pretty-printing you have another visitor class. For code optimization a third visitor class. If there is only one sequence in which the nodes should be visited, then you can build it in to the nodes of the tree. If you need to visit your nodes in different orders you might be better off building a separated tree-walker class for each order. Thus you might have a post-order-walker for use with the code generating visitor, and a in-order-walker for a pretty-printing visitor. The optimizing walker may need to take different routes through the tree depending upon what it finds. For example, it may compute the value of the RHS of an assignment before computing the address of the LHS, so it can make better use of registers. Here the visitor class itself needs to do the walking. Regards Ian -- http://mail.python.org/mailman/listinfo/python-list
Re: Smith-Waterman Algorithm in Python
On 06/08/2010 17:54, Daniel Fetchinson wrote: Does any one about any implementation of classical Smith Waterman local alignment algorithm and it's variants for aligning natural language text? Please see http://tinyurl.com/2wy43fh Every one of the first 20 entries is either the OP questions or your reply. Daniel - you are no help at all, and no funny. Ian -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie question - calculating prime numbers
On 10/08/2010 12:57, Matty Sarro wrote: Hey Everyone, I'm currently trying to work through MIT's opencourseware and am using python. The second assignment they offer is to determine the 1000th prime number. Below is the code I am using: #Assignment 1a #Determine the 1000th prime number candidate=3 #Already know that 2 is prime primeCount=1 while (primeCount<=1000): for i in range (2,candidate): if ((candidate%i)==0): print(candidate, " is not a prime") else: print(candidate, " is a prime!") primeCount+=1 candidate+=2 Now I'm not looking for a solution, but I'm hoping that someone can at least tell me where the error in my logic is. Hi Matty, Dave Angel has already given you some helpful stuff. I would only like to add that you need three states inside your loop a) Candidate is known to be prime b) Candidate is known to be not prime c) Candidate may or may not be prime and the code has to keep working on it. You are detecting the "is not prime" case correctly. The other two situations are confused. A candidate is only prime if it is not divisible by *any* number other than 1 or itself. Two hints for efficiency: If candidate has a factor, one of those factors MUST be <= square root of candidate - so you don't need to loop through so many. If x is prime, all multiples of x are not prime. See sieve of Eratosthenes. Regards Ian -- http://mail.python.org/mailman/listinfo/python-list
Re: Iterative vs. Recursive coding
On 21/08/2010 00:17, Ben Finney wrote: Steven D'Aprano writes: On Thu, 19 Aug 2010 22:00:16 +, Martin Gregorie wrote: Recursion can be quite a trick to get your mind round at first Really? Do people actually find the *concept* of recursion to be tricky? Evidently so. It's folk wisdom that some adults find recursion an easy concept, and those people will find programming significantly easier; and the majority of people have a great deal of difficulty with recursion and so find programming correspondingly difficult. There is evidence that the phenomenon is at least significant and measurablehttp://portal.acm.org/citation.cfm?id=53033>. Eh? The cited abstract does not support your conjecture. I am rather more taken with the mapper/packer contrast explained in http://the-programmers-stone.com/the-original-talks/day-1-thinking-about-thinking/ There is all manner of speculation as to what might cause this divide in capability, but precious little scientific research has been done on the differences between such people AFAICT. I agree about the lack of research. And while it is a given that some will be better than others, I suspect that research into teaching and coaching methods and cultural expectations will prove more fruitful that looking at differences between learners. Regards Ian -- http://mail.python.org/mailman/listinfo/python-list
Re: Iterative vs. Recursive coding
On 21/08/2010 01:24, Martin Gregorie wrote: On Fri, 20 Aug 2010 16:22:44 -0700, Baba wrote: > For the purposes of learning programming i think it's a must to > understand Recursion so thanks all for your help! > That depends on the language and/or hardware. COBOL wouldn't understand recursion if hit on the head with a recursion brick and early computer hardware (those without a stack) made it VERY hard work. If you don't follow this, look at the CODASYL language specification for COBOL or the hardware design of ICL 1900 or IBM System/360 mainframes (which are still the heart of the financial world) and work out how to implement a recursive function for any of them. Its not easy but it can be done. That takes me back to Spring 1976 and my first program that wasn't a print or a validate! (I had 9 months programming experience!). It was a costing program for a huge Bill of Materials - ideal for recursion. It was a re-write (with extra functionality) from PLAN (the 1900's assembler) to COBOL ready for a hardware migration. You are right. Recursion on the 1904 in COBOL was hard work! The result however was a great success - the new program did more than the old, ran faster, was many fewer source lines and was easier to test, so it was really profitable to write - and the customer was delighted. :) Regards Ian -- http://mail.python.org/mailman/listinfo/python-list
Re: adodbapi help needed
On 24/08/2010 18:08, Emile van Sebille wrote: On 8/24/2010 8:25 AM Ian Hobson said... Hi all, I am just starting to learn Python and I have a setup problem - I think. Python 3.1. def connect(connection_string, timeout=30): I expected that to be called. What have I missed? The current revision includes the caveat: This module source should run correctly in CPython versions 2.3 and later, or IronPython version 2.6 and later, or, after running through 2to3.py, CPython 3.0 or later. Does that help? Emile Thanks for the response Emile, I have also removed all my Python installations and started again - with same result. After installing Python3.1 and pywin32-214.win32-py3.1.exe (which includes adodbapi) I was getting System does not exist. I have run 2to3.py on adodbapi and I still get this trackback. D:\websites\moschatel\sop\Printing>test.py Traceback (most recent call last): File "D:\websites\moschatel\sop\Printing\test.py", line 16, in import adodbapi File "C:\Python31\lib\site-packages\adodbapi\__init__.py", line 1, in from .adodbapi import * File "C:\Python31\lib\site-packages\adodbapi\adodbapi.py", line 57, in > from System import Activator, Type, DBNull, DateTime, Array, Byte ImportError: No module named System I suspect that is movement, not progress. :) Regards Ian -- http://mail.python.org/mailman/listinfo/python-list
Re: palindrome iteration
On 27/08/2010 09:53, Baba wrote: level: beginner the following code looks ok to me but it doesn't work. I would like some hints as to where my reasoning / thought goes wrong def i_palindrome(pal): while len(pal)>1: if pal[0] == pal[-1]: pal=pal[1:-1] return True print i_palindrome('annab') If you want to or must do it recursively. (Shown in pseudo code to make the logic clearer) def isPalindrome(pal) ''' test pal (a list) is a palindrome ''' if length of pal = 1 return True # all one letter strings are palindromes. if first equals last # pal could be a palindrome # so test inner part p = pal with first and last removed return isPalendrome(p) # and true - implied else return False # it can't be Of course, the simpler way is to use the definition of a Palindrome as the same backwards and forwards. def isPalindrome(pal) return pal == pal.reverse -- http://mail.python.org/mailman/listinfo/python-list
Re: palindrome iteration
On 27/08/2010 21:51, Jussi Piitulainen wrote: Meanwhile, I have decided to prefer this: def palindromep(s): def reversed(s): return s[::-1] return s == reversed(s) I like this. s[::-1] is obscure and non-obvious, especially to Python noobs. This makes it clear what is going on and why at a cost of very little code. Very helpful to the maintenance programming in 18 months time! Regards Ian -- http://mail.python.org/mailman/listinfo/python-list
Re: Performance: sets vs dicts.
On 31/08/2010 15:09, Aahz wrote: I suggest that we should agree on these guarantees and document them in the core. I suspect that documenting them will be the easy part ;) -- http://mail.python.org/mailman/listinfo/python-list
Re: Help needed with Windows Service in Python
On 02/09/2010 18:03, David wrote: Il Thu, 02 Sep 2010 16:22:04 +0100, Ian Hobson ha scritto: self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) You may try to give a WaitHint parameter to ReportServiceStatus call, otherwise the Service Manager will expect the service is stopped istantly. self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING, 1000) David Thanks David. Sadly that makes no difference. -- http://mail.python.org/mailman/listinfo/python-list
Re: MySQL Problem
On 02/09/2010 19:34, Victor Subervi wrote: for some reason running the command through python *omits* this one data!! The only difference is that a flag in spreadsheets (Temp) is set to 1. Why on earth doesn't it work in python?? Some ideas to follow up. (These are only guesses). 1) One of the enum type fields contains an invalid value (perhaps a value removed from the column definition). 2) The second id field (products.id?) appears to be very large. I wonder what would happen if it was larger than the auto-increment value? 3) A field in the one of the rows in the missing data contains bytes that are invalid in the character encoding you are using in python. 4) The python field type used for some column in the missing row, contains a value that cannot be held in the python variable assigned. Regards Ian -- http://mail.python.org/mailman/listinfo/python-list
Re: Help needed with Windows Service in Python
On 02/09/2010 20:06, Edward Kozlowski wrote: On Sep 2, 10:22 am, Ian Hobson wrote: Hi All, I am attempting to create a Windows Service in Python. I have the framework (from Mark Hammond and Andy Robinason's book) running - see below. It starts fine - but it will not stop. :( net stop "Python Service" and using the services GUI both leave the services showing it as "stopping" I guess this means SvcStop is called but it is not enough to get it out of the machine. Does anyone know why not? Python 2.7 with win32 extensions, sunning on Windows 7. Many thanks Ian the (complete) source code is #!/usr/bin/env python # coding=utf8 # service.py = testing services and Named pipes # import win32serviceutil import win32service import win32event class PythonService(win32serviceutil.ServiceFramework): _svc_name_ = "Python Service" _svc_display_name_ = "Test Service in Python" def __init__(self, args): win32serviceutil.ServiceFramework.__init__(self,args) self.hWaitStop = win32event.CreateEvent(None,0,0,None) def SvcStop(self): self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) wind32event.SetEvent(self.hWaitStop) def SvcDoRun(self): win32event.WaitForSingleObject(self.hWaitStop,win32event.INFINITE) if __name__ == '__main__': win32serviceutil.HandleCommandLine(PythonService) Looks to me like there may be a typo in your code. You probably meant win32event.SetEvent(self.hWaitStop), not wind32event. Regards, -Edward Kozlowski A huge big thank you Edward. That was the problem. Regards Ian -- http://mail.python.org/mailman/listinfo/python-list
Re: MySQL Problem
On 03/09/2010 14:29, Victor Subervi wrote: This is an addendum to my last post. Please observe the following: mysql> select * from spreadsheets where Temp=1; +-++---+-++--+ | ID | Client | Multi | Item| Markup | Temp | +-++---+-++--+ | 611 | Lincoln_Properties | 0 | 2030572 | 0.00 |1 | | 621 | Lincoln_Properties | 0 | 2030572 | 0.00 |1 | +-++---+-++--+ 2 rows in set (0.00 sec) mysql> describe spreadsheets; ++--+--+-+-++ | Field | Type | Null | Key | Default | Extra | ++--+--+-+-++ | ID | int(11) unsigned | NO | PRI | NULL| auto_increment | | Client | varchar(40) | YES | | NULL|| | Multi | tinyint(1) | YES | | NULL|| | Item | varchar(40) | YES | | NULL|| | Markup | float(6,2) | YES | | NULL|| | Temp | tinyint(1) | YES | | NULL|| ++--+--+-+-++ 6 rows in set (0.00 sec) Yet from my script: cursor.execute('select * from spreadsheets where Temp=1') print cursor.fetchall() print nothing but an empty set: () Why?? TIA, beno Hi Victor Find out exactly what character encoding are you using for each of the following places when using MySQL client. The MySQL installation The database definition The table definition The Field definition The Link between Python and MySQL The Python source / The Msql Client. And then find out what encoding is being forced/used by the code you have written in Python in each of the above situations? You may have to go to the source of the library routine to find this out. What I suspect may be happening is this. Say you have a field containing a character/code point that is in UTF-8 but not in the ISO-8859-1 set. If such a field was written using UTF-8 throughout, but then read using ISO-8859-1 or similar then the read will generate an error. That error may be being ignored or suppressed causing the code to drop your data rows. IIRC, MySQL calls UTF-8 by the (incorrect) name of utf-8. My recommendation is for you to use UTF-8 for everything. UTF-8 can store any character in any language(1), is really efficient for English text, and acceptable for other languages. Performance it excellent, because it involves no encoding/decoding as the data moves between disk, MySQL link or Python. (1) There are some minor human languages that cannot be encoded - usually because no written form has yet been devised or the code points have not been agreed. These languages will not be met in practise. Regards Ian -- http://mail.python.org/mailman/listinfo/python-list
Re: Help needed with Windows Service in Python
On 03/09/2010 01:38, Mark Hammond wrote: I expect that the Windows Event Log might have some clues, as would attempting to use it in "debug" mode. Thanks Mark. The error log holds the trackback - it identified the line with the typo. Now the typo is fixed, the service starts and stops properly. Regards Ian -- http://mail.python.org/mailman/listinfo/python-list