Re: socket.rcv timeout while-loop
On 01/-10/-28163 02:59 PM, Dwayne Blind wrote: or rather timeout = s.gettimeout() b=time.clock() while time.clock()-b<3 : s.settimeout(3-time.clock()+b) try : data=s.recv(1024) except : break s.settimeout(timeout) Sorry for all these messages Dwayne You accidentally top-posted, so I had to delete all the history. Without knowing anything about "s", there are two problems with this logic: 1) if you loop through the while more than once, you'll be throwing out old data. So you might need something like data += s.recv(1024). Conversely, if an exception happens, data is completely undefined. Without defining a default value, your remaining code is likely to get an exception. 2) Your time spent might vary between 3 and 6 seconds. If you need a tighter control than that, play with the timeout a little. For example, you might want a 1/2 second timeout, and loop until the total is 3 seconds. That way the tolerance will be 3 to 3.5 seconds. Bonus: I don't know the behavior of the object, so I don't know what state it's in after you timeout. DaveA -- -- da...@ieee.org -- http://mail.python.org/mailman/listinfo/python-list
code structure advise for a model
Hi, I am translating some c++ code to python and just wanted to ask some advise on structure. The original has everything declared globally and nothing passed via function (I assume, but don't know, that this isn't just standard c++ practice!). So given this, I have a pretty much clean slate as I can't quite just copy the functions over. I was thinking something like this class Params: def __init__(self, fname): self.set_inital_condtions() self.read_input_file(fname) def set_inital_conditons(self): self.some_parm = 0.0 def read_input_file(fname): #read file, change initial params if specified then I thought I could pass this as an object to the model class class Model(Params): def __init__(self): # blah def some_func(self): if (Params.some_param == something): foo OR this just a very bad way to structure it? The other thing I can't decide on is how to pass the parameters and variables through the class. So because of the way the original is written (everything is global), I could just inherit things, but it does means there is a lot of self. syntax. So I wondered if it might be better to pass things as function arguments? Any thoughts? I am also half considering other users from non-python backgrounds and what might seem very alien (syntax) to them. thanks in advance (ps. I am cross posting this on comp.lang.python as I am not sure where is more appropriate). -- http://mail.python.org/mailman/listinfo/python-list
Re: Download an attachment from an IMAP email
On Fri, Feb 4, 2011 at 3:44 AM, Vincent Davis wrote: > I have a few emails I am trying to download from my google account. I seem > to be getting the message but each of these messages have an attachment. I > don't understand what I ned to do to get and save the attachment to a local > file. > Here is what I have so far. > M = imaplib.IMAP4_SSL(IMAP_SERVER, IMAP_PORT) > rc, resp = M.login('x@', 'X') > print rc, resp > M.select('[Gmail]/All Mail') > M.search(None, 'FROM', 'some...@logitech.com') > #M.fetch(121, '(body[header.fields (subject)])') > M.fetch(121, '(RFC822)') Take a look at the email module. The message_from_string() function can convert the string representation of the email (as obtained by M.fetch(121, '(RFC822)') into a message object. -- regards, kushal -- http://mail.python.org/mailman/listinfo/python-list
Re: socket.rcv timeout while-loop
On 2/3/11 3:02 PM, Dwayne Blind wrote: > Thanks Stephen. It's really nice of you. > > I have not understood everything though. (I have never used a context > manager before.) > > Here are some comments : > > timeout = s.gettimeout()# Is that the default timeout ? > s.settimeout(3) # I guess this is a 3 second timeout > s.recv(1024) > s.settimeout(timeout) # You change it back ? Yes. > So with a while loop, it should be : I don't understand why you're doing this while loop business. Your original question is asking for how to NOT do that, I thought. How to use a timeout instead. I showed you how to use a timeout instead-- now you're mixing it in with what you originally had? Why? -- Stephen Hansen ... Also: Ixokai ... Mail: me+list/python (AT) ixokai (DOT) io ... Blog: http://meh.ixokai.io/ signature.asc Description: OpenPGP digital signature -- http://mail.python.org/mailman/listinfo/python-list
Re: socket.rcv timeout while-loop
or rather timeout = s.gettimeout() b=time.clock() while time.clock()-b<3 : s.settimeout(3-time.clock()+b) try : data=s.recv(1024) except : break s.settimeout(timeout) Sorry for all these messages Dwayne 2011/2/4 Dwayne Blind > The solution would be > > > timeout = s.gettimeout() > s.settimeout(3) > b=time.clock() > while time.clock()-b<3 : >try : >data=s.recv(1024) > except : >break > s.settimeout(timeout) > > Am I right ? > > Dwayne > > 2011/2/4 Dwayne Blind > > Thanks Stephen. It's really nice of you. >> >> I have not understood everything though. (I have never used a context >> manager before.) >> >> Here are some comments : >> >> timeout = s.gettimeout()# Is that the default timeout ? >> s.settimeout(3) # I guess this is a 3 second timeout >> s.recv(1024) >> s.settimeout(timeout) # You change it back ? >> >> So with a while loop, it should be : >> >> >> timeout = s.gettimeout() >> s.settimeout(3) >> b=time.clock() >> while time.clock()-b<3 : >> >> data=s.recv(1024) >> s.settimeout(timeout) >> >> Am I right ? >> >> Thanks again, >> Dwayne >> >> >> 2011/2/3 Stephen Hansen >> >>> On 2/3/11 10:13 AM, Dwayne Blind wrote: >>> >>> > Thanks for your answer. I don't want to reset my socket. I want to >>> apply >>> > the timeout to the rcv method only. >>> >>> Setting the timeout does not "reset [your] socket", I don't think. And I >>> get that you want to only timeout recv... that's why I pointed out its a >>> socket method, not an argument to recv. If you don't want it to apply to >>> everything else, you just have to be sure to change it back after recv. >>> >>> Just: >>> timeout = s.gettimeout() >>> s.settimeout(3) >>> s.recv(1024) >>> s.settimeout(timeout) >>> >>> Personally, I'd prefer to do: >>> >>> with timeout(s, 3): >>>s.recv(1024) >>> >>> That's a lot more clear, and I'd roll this context manager to accomplish >>> it: >>> >>> --- start >>> >>> from contextlib import contextmanager >>> >>> @contextmanager >>> def timeout(sock, timeout): >>>old_timeout = sock.gettimeout() >>>sock.settimeout(timeout) >>>try: >>>yield sock >>>finally: >>>sock.settimeout(old_timeout) >>> >>> --- end >>> >>> The contextmanager decorator is an easy/quick way of making a context >>> manager. Everything up until the yield is executed before the 'with' >>> block is run, and everything after the yield is executed after the >>> 'with' block concludes. >>> >>> If the with block throws an exception, it'll be catchable at the yield >>> point. >>> >>> -- >>> >>> Stephen Hansen >>> ... Also: Ixokai >>> ... Mail: me+list/python (AT) ixokai (DOT) io >>> ... Blog: http://meh.ixokai.io/ >>> >>> >> > -- http://mail.python.org/mailman/listinfo/python-list
Re: os.path.join doubt
On Thu, 2011-02-03 at 17:57 -0600, Thomas L. Shinnick wrote: > At 05:33 PM 2/3/2011, Westley Martínez wrote: > > > On Thu, 2011-02-03 at 23:11 +, Steven D'Aprano wrote: > > > > > On Thu, 03 Feb 2011 > > > 07:58:55 -0800, Ethan Furman wrote: > > > > Steven D'Aprano wrote: > > > [snip] > > > > > > Yes. Is there a problem? All those paths should be usable from Windows. > > > If you find it ugly to see paths with a mix of backslashes and forward > > > slashes, call os.path.normpath, or just do a simple string replace: > > > > > > path = path.replace('/', '\\') > > > > > > before displaying them to the user. Likewise if you have to pass the > > > paths to some application that doesn't understand slashes. > > > > > > > > > -- > > > Steven > > > > Paths that mix /s and \s are NOT valid on Windows. In one of the > > setup.py scripts I wrote I had to write a function to collect the > > paths of data files for installation. On Windows it didn't work and > > it was driving me crazy. It wasn't until I realized os.path.join was > > joining the paths with \\ instead of / that I was able to fix it. > > > > def find_package_data(path): > > """Recursively collect EVERY file in path to a list.""" > > oldcwd = os.getcwd() > > os.chdir(path) > > filelist = [] > > for path, dirs, filenames in os.walk('.'): > > for name in filenames: > > filename = ((os.path.join(path, name)).replace('\\', > > '/')) > > filelist.append(filename.replace('./', 'data/')) > > os.chdir(oldcwd) > > return filelist > > > Please check out os.path.normpath() as suggested. Example: > >>> import os > >>> s = r"/hello\\there//yall\\foo.bar" > >>> s > '/hellothere//yallfoo.bar' > >>> v = os.path.normpath(s) > >>> v > '\\hello\\there\\yall\\foo.bar' > > The idea behind os.path is to cater to the host OS. Thus > os.path.normpath() will convert to the host's acceptable delimiters. > That is, you didn't need the .replace(), but rather to more fully use > the existing library to good advantage with .normpath(). > > However, note that delimiters becomes an issue only when directly > accessing the host OS, such as when preparing command line calls or > accessing native APIs. Within the Python library/environment, both > '/' and '\' are acceptable. External use is a different matter. > > So, you need to be specific on how and where your paths are to be > used. For instance os.chdir() will work fine with a mixture, but > command line apps or native APIs will probably fail. The reason why I use replace instead of normpath is because I want it to '/'s on ALL platforms. This is because distutils requires the use of '/'s. -- http://mail.python.org/mailman/listinfo/python-list
8-Day Python Power Course in Leipzig/Germany
Eight Days of Python Training - Can't get enough of Python? Then this course is for you. A three day introduction to Python as a warm-up, followed by five days of advanced Python training. All courses given in English. May 13 - 15, 2011 Python for Programmers May 16 - 20, 2011 Python Power Course May 16, 2011 Advanced Python Programming May 17, 2011 Optimizing Python Programs May 18, 2011 Python Extensions with Other Languages May 19, 2011 Fast Code with the Cython Compiler May 20, 2011 High Performance XML with Python Venue: Python Academy, Leipzig, Germany Trainers: Mike Müller, Stefan Behnel About the Trainers -- Mike Müller, Ph.D has been teaching Python since 2004. He is the founder of Python Academy and regularly gives open and in-house Python courses as well as tutorials at PyCon US, OSCON, EuroSciPy and PyCon Asia-Pacific. Stefan Behnel, Ph.D is Senior Software Developer at Senacor Technologies AG as well as freelance consultant and software developer specializing in Python and Open Source. He is core developer of both the Cython compiler and the lxml XML toolkit. More Information http://www.python-academy.com/courses/python_power_course.html -- Mike mmuel...@python-academy.de -- http://mail.python.org/mailman/listinfo/python-list
Re: os.path.join doubt
At 05:33 PM 2/3/2011, Westley Martínez wrote: On Thu, 2011-02-03 at 23:11 +, Steven D'Aprano wrote: On Thu, 03 Feb 2011 07:58:55 -0800, Ethan Furman wrote: > Steven D'Aprano wrote: [snip] Yes. Is there a problem? All those paths should be usable from Windows. If you find it ugly to see paths with a mix of backslashes and forward slashes, call os.path.normpath, or just do a simple string replace: path = path.replace('/', '\\') before displaying them to the user. Likewise if you have to pass the paths to some application that doesn't understand slashes. -- Steven Paths that mix /s and \s are NOT valid on Windows. In one of the setup.py scripts I wrote I had to write a function to collect the paths of data files for installation. On Windows it didn't work and it was driving me crazy. It wasn't until I realized os.path.join was joining the paths with \\ instead of / that I was able to fix it. def find_package_data(path): """Recursively collect EVERY file in path to a list.""" oldcwd = os.getcwd() os.chdir(path) filelist = [] for path, dirs, filenames in os.walk('.'): for name in filenames: filename = ((os.path.join(path, name)).replace('\\', '/')) filelist.append(filename.replace('./', 'data/')) os.chdir(oldcwd) return filelist Please check out os.path.normpath() as suggested. Example: >>> import os >>> s = r"/hello\\there//yall\\foo.bar" >>> s '/hellothere//yallfoo.bar' >>> v = os.path.normpath(s) >>> v '\\hello\\there\\yall\\foo.bar' The idea behind os.path is to cater to the host OS. Thus os.path.normpath() will convert to the host's acceptable delimiters. That is, you didn't need the .replace(), but rather to more fully use the existing library to good advantage with .normpath(). However, note that delimiters becomes an issue only when directly accessing the host OS, such as when preparing command line calls or accessing native APIs. Within the Python library/environment, both '/' and '\' are acceptable. External use is a different matter. So, you need to be specific on how and where your paths are to be used. For instance os.chdir() will work fine with a mixture, but command line apps or native APIs will probably fail. -- http://mail.python.org/mailman/listinfo/python-list
Re: os.path.join doubt
On Thu, 2011-02-03 at 23:11 +, Steven D'Aprano wrote: > On Thu, 03 Feb 2011 07:58:55 -0800, Ethan Furman wrote: > > > Steven D'Aprano wrote: > >> BTW, Windows accepts / as well as \ as a path separator. You will have > >> far fewer headaches if you use that. > > > > Just because Windows accepts / doesn't make it a good idea... > > No. Windows accepting slashes as the alternate path separator *enables* > you to use slash. What makes it a good idea is that you don't have to > worry about forgetting to escape backslashes: > > >>> print("C:\temp\file.txt") > C: emp >ile.txt > > > Nor do you have to care about the fact that raw strings are designed for > regular expressions, not Windows path names, and you can't have a raw > string ending in a single backslash: > > >>> location = r'C:\temp\' # Path ending in a backslash. > File "", line 1 > location = r'C:\temp\' > ^ > SyntaxError: EOL while scanning string literal > > > The fact is that Windows' use of backslash as the path separator > conflicts with Python's use of backslashes. Since our code is written in > Python, trying to uses backslashes causes problems. One work-around is to > take advantage of the fact that Windows has an alternate separator > character, and use that. If you'd rather use raw strings, and special- > case backslashes at the end of paths, go right ahead. > > > --> from glob import glob > > --> print '\n'.join(glob('c:/temp/*')) c:/temp\0C2O0007.TMP > > c:/temp\27421 > > c:/temp\3K540007.TMP > [...] > > > Yes. Is there a problem? All those paths should be usable from Windows. > If you find it ugly to see paths with a mix of backslashes and forward > slashes, call os.path.normpath, or just do a simple string replace: > > path = path.replace('/', '\\') > > before displaying them to the user. Likewise if you have to pass the > paths to some application that doesn't understand slashes. > > > -- > Steven Paths that mix /s and \s are NOT valid on Windows. In one of the setup.py scripts I wrote I had to write a function to collect the paths of data files for installation. On Windows it didn't work and it was driving me crazy. It wasn't until I realized os.path.join was joining the paths with \\ instead of / that I was able to fix it. def find_package_data(path): """Recursively collect EVERY file in path to a list.""" oldcwd = os.getcwd() os.chdir(path) filelist = [] for path, dirs, filenames in os.walk('.'): for name in filenames: filename = ((os.path.join(path, name)).replace('\\', '/')) filelist.append(filename.replace('./', 'data/')) os.chdir(oldcwd) return filelist -- http://mail.python.org/mailman/listinfo/python-list
Re: socket.rcv timeout while-loop
The solution would be timeout = s.gettimeout() s.settimeout(3) b=time.clock() while time.clock()-b<3 : try : data=s.recv(1024) except : break s.settimeout(timeout) Am I right ? Dwayne 2011/2/4 Dwayne Blind > Thanks Stephen. It's really nice of you. > > I have not understood everything though. (I have never used a context > manager before.) > > Here are some comments : > > timeout = s.gettimeout()# Is that the default timeout ? > s.settimeout(3) # I guess this is a 3 second timeout > s.recv(1024) > s.settimeout(timeout) # You change it back ? > > So with a while loop, it should be : > > > timeout = s.gettimeout() > s.settimeout(3) > b=time.clock() > while time.clock()-b<3 : > > data=s.recv(1024) > s.settimeout(timeout) > > Am I right ? > > Thanks again, > Dwayne > > > 2011/2/3 Stephen Hansen > >> On 2/3/11 10:13 AM, Dwayne Blind wrote: >> >> > Thanks for your answer. I don't want to reset my socket. I want to apply >> > the timeout to the rcv method only. >> >> Setting the timeout does not "reset [your] socket", I don't think. And I >> get that you want to only timeout recv... that's why I pointed out its a >> socket method, not an argument to recv. If you don't want it to apply to >> everything else, you just have to be sure to change it back after recv. >> >> Just: >> timeout = s.gettimeout() >> s.settimeout(3) >> s.recv(1024) >> s.settimeout(timeout) >> >> Personally, I'd prefer to do: >> >> with timeout(s, 3): >>s.recv(1024) >> >> That's a lot more clear, and I'd roll this context manager to accomplish >> it: >> >> --- start >> >> from contextlib import contextmanager >> >> @contextmanager >> def timeout(sock, timeout): >>old_timeout = sock.gettimeout() >>sock.settimeout(timeout) >>try: >>yield sock >>finally: >>sock.settimeout(old_timeout) >> >> --- end >> >> The contextmanager decorator is an easy/quick way of making a context >> manager. Everything up until the yield is executed before the 'with' >> block is run, and everything after the yield is executed after the >> 'with' block concludes. >> >> If the with block throws an exception, it'll be catchable at the yield >> point. >> >> -- >> >> Stephen Hansen >> ... Also: Ixokai >> ... Mail: me+list/python (AT) ixokai (DOT) io >> ... Blog: http://meh.ixokai.io/ >> >> > -- http://mail.python.org/mailman/listinfo/python-list
Re: os.path.join doubt
On Thu, 03 Feb 2011 07:58:55 -0800, Ethan Furman wrote: > Steven D'Aprano wrote: >> BTW, Windows accepts / as well as \ as a path separator. You will have >> far fewer headaches if you use that. > > Just because Windows accepts / doesn't make it a good idea... No. Windows accepting slashes as the alternate path separator *enables* you to use slash. What makes it a good idea is that you don't have to worry about forgetting to escape backslashes: >>> print("C:\temp\file.txt") C: emp ile.txt Nor do you have to care about the fact that raw strings are designed for regular expressions, not Windows path names, and you can't have a raw string ending in a single backslash: >>> location = r'C:\temp\' # Path ending in a backslash. File "", line 1 location = r'C:\temp\' ^ SyntaxError: EOL while scanning string literal The fact is that Windows' use of backslash as the path separator conflicts with Python's use of backslashes. Since our code is written in Python, trying to uses backslashes causes problems. One work-around is to take advantage of the fact that Windows has an alternate separator character, and use that. If you'd rather use raw strings, and special- case backslashes at the end of paths, go right ahead. > --> from glob import glob > --> print '\n'.join(glob('c:/temp/*')) c:/temp\0C2O0007.TMP > c:/temp\27421 > c:/temp\3K540007.TMP [...] Yes. Is there a problem? All those paths should be usable from Windows. If you find it ugly to see paths with a mix of backslashes and forward slashes, call os.path.normpath, or just do a simple string replace: path = path.replace('/', '\\') before displaying them to the user. Likewise if you have to pass the paths to some application that doesn't understand slashes. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: socket.rcv timeout while-loop
Thanks Stephen. It's really nice of you. I have not understood everything though. (I have never used a context manager before.) Here are some comments : timeout = s.gettimeout()# Is that the default timeout ? s.settimeout(3) # I guess this is a 3 second timeout s.recv(1024) s.settimeout(timeout) # You change it back ? So with a while loop, it should be : timeout = s.gettimeout() s.settimeout(3) b=time.clock() while time.clock()-b<3 : data=s.recv(1024) s.settimeout(timeout) Am I right ? Thanks again, Dwayne 2011/2/3 Stephen Hansen > On 2/3/11 10:13 AM, Dwayne Blind wrote: > > Thanks for your answer. I don't want to reset my socket. I want to apply > > the timeout to the rcv method only. > > Setting the timeout does not "reset [your] socket", I don't think. And I > get that you want to only timeout recv... that's why I pointed out its a > socket method, not an argument to recv. If you don't want it to apply to > everything else, you just have to be sure to change it back after recv. > > Just: > timeout = s.gettimeout() > s.settimeout(3) > s.recv(1024) > s.settimeout(timeout) > > Personally, I'd prefer to do: > > with timeout(s, 3): >s.recv(1024) > > That's a lot more clear, and I'd roll this context manager to accomplish > it: > > --- start > > from contextlib import contextmanager > > @contextmanager > def timeout(sock, timeout): >old_timeout = sock.gettimeout() >sock.settimeout(timeout) >try: >yield sock >finally: >sock.settimeout(old_timeout) > > --- end > > The contextmanager decorator is an easy/quick way of making a context > manager. Everything up until the yield is executed before the 'with' > block is run, and everything after the yield is executed after the > 'with' block concludes. > > If the with block throws an exception, it'll be catchable at the yield > point. > > -- > > Stephen Hansen > ... Also: Ixokai > ... Mail: me+list/python (AT) ixokai (DOT) io > ... Blog: http://meh.ixokai.io/ > > -- http://mail.python.org/mailman/listinfo/python-list
Download an attachment from an IMAP email
I have a few emails I am trying to download from my google account. I seem to be getting the message but each of these messages have an attachment. I don't understand what I ned to do to get and save the attachment to a local file. Here is what I have so far. M = imaplib.IMAP4_SSL(IMAP_SERVER, IMAP_PORT) rc, resp = M.login('x@', 'X') print rc, resp M.select('[Gmail]/All Mail') M.search(None, 'FROM', 'some...@logitech.com') #M.fetch(121, '(body[header.fields (subject)])') M.fetch(121, '(RFC822)') -- Thanks Vincent Davis 720-301-3003 -- http://mail.python.org/mailman/listinfo/python-list
JSONBOT 0.6.1 RELEASED
Hello every human out there ! i'm pleased to announce the release of JSONBOT 0.6.1 FINAL, a release that saw a lot of work into the shell side of things and no changes to GAE. 0.6.1 has the following changes: * the ! char is not used instead of | in a pipeline. This is to make it easier to use a pipeline on mobile phones. * a new commandline interface has been created. You can now do "jsb " .. no need to start up the console app when you have a single command to execute * ? is now used a query character, so things you learn the bot with ! learn can be queried with ? * auto_register and guestasuser config options are now disabled by default * core xmpp parsing code has been rewritten * many more bug fixes. You can grab a copy of the code (tarball or mercurial repo) at http://jsonbot.googlecode.com Hope you enjoy this release as much as i enjoyed making it ;] Have Fun ! Bart About JOSNBOT: JSONBOT is a remote event-driven framework for building bots that talk JSON to each other over XMPP. This distribution provides bots built on this framework for console, IRC, XMPP for the shell and WWW and XMPP for the Google Application engine. JSONBOT is all of the following: a shell console bot a shell IRC bot a shell XMPP bot a Web bot running on Google Application Engine a XMPP bot running on Google Application Engine a Google Wave bot running op Google Application Engine the XMPP bots are used to communicate between bots plugin infrastructure to write your own functionality event driven framework by the use of callbacks -- http://mail.python.org/mailman/listinfo/python-list
Re: returning all matching groups with re.search()
On Thu, Feb 3, 2011 at 3:32 PM, mhearne808[insert-at-sign-here]gmail[insert-dot-here]com wrote: > Here's a scenario: > > import re > m = re.search('e','fredbarneybettywilma') > > Now, here's a stupid question: > why doesn't m.groups() return ('e','e','e'). > > I'm trying to figure out how to match ALL of the instances of a > pattern in one call - the group() and groups() return subgroups... how > do I get my search to get me all of the matching subgroups? m.groups() doesn't give return ('e','e','e') because groups don't mean what you think they mean. Groups are subsections of a regular expression, enclosed by parenthesis. For example: >>> m = re.search('(e)','fredbarneybettywilma') >>> m.groups() ('e',) What you want seem to want is re.findall, not re.search -- http://mail.python.org/mailman/listinfo/python-list
Re: returning all matching groups with re.search()
On Thu, Feb 3, 2011 at 12:32 PM, mhearne808[insert-at-sign-here]gmail[insert-dot-here]com wrote: > Here's a scenario: > > import re > m = re.search('e','fredbarneybettywilma') > > Now, here's a stupid question: > why doesn't m.groups() return ('e','e','e'). Straight from the docs (http://docs.python.org/library/re.html ), emphasis mine: re.search(pattern, string[, flags]) "Scan through string looking for **a** location where the regular expression pattern produces **a** match [...]" Hence, it stops looking after the very first match. > I'm trying to figure out how to match ALL of the instances of a > pattern in one call - the group() and groups() return subgroups... how > do I get my search to get me all of the matching subgroups? I think you want re.finditer() or re.findall(). Cheers, Chris -- http://blog.rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
returning all matching groups with re.search()
Here's a scenario: import re m = re.search('e','fredbarneybettywilma') Now, here's a stupid question: why doesn't m.groups() return ('e','e','e'). I'm trying to figure out how to match ALL of the instances of a pattern in one call - the group() and groups() return subgroups... how do I get my search to get me all of the matching subgroups? -- http://mail.python.org/mailman/listinfo/python-list
ptrace vs. python-ptrace
I'd like to do some experimentation with the Linux ptrace facility. Before I jump in, I was wondering if anybody has any comments they'd like to offer on the relative merits of ptrace vs. python-ptrace: http://pypi.python.org/pypi/ptrace http://pypi.python.org/pypi/python-ptrace Ptrace appears to have been updated more recently that python-ptrace, but python-ptrace includes some sample applications that probably get me closer to my end-goal. Are the APIs compatible (or at all similar)? -- Grant Edwards grant.b.edwardsYow! On the road, ZIPPY at is a pinhead without a gmail.compurpose, but never without a POINT. -- http://mail.python.org/mailman/listinfo/python-list
Re: socket.rcv timeout while-loop
On 2/3/11 10:13 AM, Dwayne Blind wrote: > Thanks for your answer. I don't want to reset my socket. I want to apply > the timeout to the rcv method only. Setting the timeout does not "reset [your] socket", I don't think. And I get that you want to only timeout recv... that's why I pointed out its a socket method, not an argument to recv. If you don't want it to apply to everything else, you just have to be sure to change it back after recv. Just: timeout = s.gettimeout() s.settimeout(3) s.recv(1024) s.settimeout(timeout) Personally, I'd prefer to do: with timeout(s, 3): s.recv(1024) That's a lot more clear, and I'd roll this context manager to accomplish it: --- start from contextlib import contextmanager @contextmanager def timeout(sock, timeout): old_timeout = sock.gettimeout() sock.settimeout(timeout) try: yield sock finally: sock.settimeout(old_timeout) --- end The contextmanager decorator is an easy/quick way of making a context manager. Everything up until the yield is executed before the 'with' block is run, and everything after the yield is executed after the 'with' block concludes. If the with block throws an exception, it'll be catchable at the yield point. -- Stephen Hansen ... Also: Ixokai ... Mail: me+list/python (AT) ixokai (DOT) io ... Blog: http://meh.ixokai.io/ signature.asc Description: OpenPGP digital signature -- http://mail.python.org/mailman/listinfo/python-list
Pydev 1.6.5 Released
Hi All, Pydev 1.6.5 has been released Details on Pydev: http://pydev.org Details on its development: http://pydev.blogspot.com Release Highlights: --- * Syntax highlighting now has options to have {}, [] and () as well as operators in different colors * Code generation for classes and methods: Note that this is an initial implementation of the idea, aimed as those that use a TDD (Test Driven Development) approach, so, one can create the test first and generate the classes/methods later on from using shortcuts or quick-fixes (which is something that those using JDT -- Java Development Tools -- in Eclipse should be already familiar with). This feature should be already usable on a number of situations but it's still far from being 100% complete. * Alt+Shift+S C can be used to create a class for the currently selected token * Alt+Shift+S M can be used to create a method for the currently selected token * Ctrl+1 has as a quick fix for creating a class or method * Debugger * When discovering encoding on Python 3.x, the file is opened as binary * Remote debugger (pydevd.settrace()) properly synchronized * Fixed debugger issue on interpreter shutdown on Python 2.7 * Bug fixes: * Fixed issue when doing code-completion on a line that started with some token that started with 'import'. e.g.: import_foo = a * Fixed import when running unittest with coverage * Fixed extract local (could extract to wrong location) * Fixed NPE when requesting print of arguments in the context-information tooltips * Fixed AttributeError with pydevconsole on Python 3.x What is PyDev? --- PyDev is a plugin that enables users to use Eclipse for Python, Jython and IronPython development -- making Eclipse a first class Python IDE -- It comes with many goodies such as code completion, syntax highlighting, syntax analysis, refactor, debug and many others. Cheers, -- Fabio Zadrozny -- Software Developer Aptana http://aptana.com/ Pydev - Python Development Environment for Eclipse http://pydev.org http://pydev.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: socket.rcv timeout while-loop
Thanks for your answer. I don't want to reset my socket. I want to apply the timeout to the rcv method only. What about select ? http://docs.python.org/library/select.html#select.select How to implement it ? Thanks a lot, Dwayne 2011/2/3 Stephen Hansen > On 2/3/11 9:56 AM, Dwayne Blind wrote: > > However I would like to set timeout on the socket rcv method, so that > > the while loop stops exactly after 3 seconds. Is this possible ? > > I rarely do low-level socket stuff -- but I think s.settimeout() is what > you're looking for. It applies to the whole socket, and not just one > method -- so you may want to reset it after you're done recv'n. > > -- > > Stephen Hansen > ... Also: Ixokai > ... Mail: me+list/python (AT) ixokai (DOT) io > ... Blog: http://meh.ixokai.io/ > > > -- > http://mail.python.org/mailman/listinfo/python-list > > -- http://mail.python.org/mailman/listinfo/python-list
New article on grabbing city points from geonames, processing with Python, and rendering in MapPoint
Add City Coverage to MapPoint using the GeoNames Database by Richard Marsden http://www.mapforums.com/add-city-coverage-mappoint-using-geonames-database-15244.html -- m: 312-399-1586 http://www.MapForums.com http://www.MP2Kmag.com -- http://mail.python.org/mailman/listinfo/python-list
Re: socket.rcv timeout while-loop
On 2/3/11 9:56 AM, Dwayne Blind wrote: > However I would like to set timeout on the socket rcv method, so that > the while loop stops exactly after 3 seconds. Is this possible ? I rarely do low-level socket stuff -- but I think s.settimeout() is what you're looking for. It applies to the whole socket, and not just one method -- so you may want to reset it after you're done recv'n. -- Stephen Hansen ... Also: Ixokai ... Mail: me+list/python (AT) ixokai (DOT) io ... Blog: http://meh.ixokai.io/ signature.asc Description: OpenPGP digital signature -- http://mail.python.org/mailman/listinfo/python-list
socket.rcv timeout while-loop
Hi everybody, I am using Python 3.0. I have such a code : b=time.clock() while time.clock()-b<3 : data=s.recv(1024) However I would like to set timeout on the socket rcv method, so that the while loop stops exactly after 3 seconds. Is this possible ? Thanks a lot, Dwayne -- http://mail.python.org/mailman/listinfo/python-list
Re: Errors while using strip and remove on a variable.
On 2/3/11 7:21 AM, anand jeyahar wrote: > Hi, > I am trying to strip a string and then remove on the resulting list > to remove a set of characters. It works fine with the python shell. > > But after remove the list becomes None, when i am running it from within > a script. > > I am guessing it has something to do with the way python handles assignment. > please find the script below* > > a ='oe,eune,eueo, ,u' > b = a.split(',') > print b > c = b.remove('oe') As others have stated, the issue is that b.remove('oe') doesn't return b or a copy of b, but directly modifies b instead. I'll add that you will find that this behavior is consistent throughout the list api: the None is more then just a default thing that's returned when nothing else is returned, but in this case its also meant as a signal to clearly indicate that the list is modified in-place. Every once in awhile someone asks for these methods that modify the list itself to either return self, or return a copy of the list -- and I'm not going to get into that debate -- but the reason for the "None" is to make it so you WILL get errors like the above. You only run into this situation with mutable data-types by the way: strings ALWAYS return a copy or new string, because they can't actually modify the string itself. -- Stephen Hansen ... Also: Ixokai ... Mail: me+list/python (AT) ixokai (DOT) io ... Blog: http://meh.ixokai.io/ signature.asc Description: OpenPGP digital signature -- http://mail.python.org/mailman/listinfo/python-list
Re: IDLE: A cornicopia of mediocrity and obfuscation.
If anyone would like to see a good example of how IDLE code should be written. I highly suggest you check out the source for PyShell and PyCrust which is located in roughly... HOME\PythonXX\Lib\site-packages\wx-2.8-msw-ansi\wx\py: * shell.py * crust.py * filling.py Also run these scripts to see them all in action: * PyAlaCarte.py * PyAlaMode.py This is a code base that was laid out in a logical and sensible manner. This is a code base that can be built from. IDLE on the other hand is utter chaos. If you don't believe me, first look at the beautiful scripts i mentioned above, then check out these scripts in your idlelib... PythonXX\Lib\idlelib: * EditorWindow.py * PyShell.py It is like night and day people! NIGHT AND DAY!!! -- http://mail.python.org/mailman/listinfo/python-list
Re: Style question: Nicknames for deeply nested objects
Gerald Britton wrote: Nope. it's nothing to do with imports. It's about objects passed to methods at run time. Complicated objects with many levels. Not about modules at all. Who is providing these objects ? - Your code ? => as said before, you can fix your design with a proper object model - 3rd party libraries ? => I'd be curious to know which one, because they usually do a good job providing a clean minimal public interface. However, do not redesign anything to get only shorter names. You can easily live with that, the way you're doing it is up to you and suggestions have been given. But keep in mind that you should'nt have got nested names that long in the first pace, no matter how complicated the internal implementation. JM -- http://mail.python.org/mailman/listinfo/python-list
Fwd: 'Upload a valid image' errors with PIL 1.1.7/ Python 2.6/ Mac 10.6.2/ Django 1.2.3
I'm sorry, by admin site below, I mean Django Admin site. Hi, I am struggling with this for the past 2 days: first I got the above error, & googled around to find that I needed the libjpeg module as well, so I re-installed the lot, first libjpeg & then PIL; got a couple errors like JPEG decoder not available etc, fixed that. Now it passes the selftest, but when I try to upload images via the admin site, it throws up the error "Upload a valid image. The file you uploaded was either not an image or a corrupted image." Any help is appreciated. Thanks. -Ara -- http://mail.python.org/mailman/listinfo/python-list
Re: Perl Hacker, Python Initiate
On Wed, 2011-02-02, Gary Chambers wrote: > All, > > Given the following Perl script: > > #!/usr/bin/perl I'm a Perl user, but I generally refuse to read Perl code which doesn't utilize 'use warnings/-w' and 'use strict'. There are just too many crazy bugs and 1980s constructs which go unnoticed without them. > %dig = ( > solaris => "/usr/sbin/dig", > linux => "/usr/bin/dig", > darwin => "/usr/bin/dig" > ); Not related to your question, except that you'll have to deal with this in Python too: I really suggest letting the user's $PATH decide which dig to call. /usr/bin is always in the path. /usr/sbin may not be, but if that's a problem for your users, just let your script start by appending it to the pre-existing $PATH. You don't even have to do OS detection on that one -- it's safe to do everywhere. /Jorgen -- // Jorgen GrahnO o . -- http://mail.python.org/mailman/listinfo/python-list
'Upload a valid image' errors with PIL 1.1.7/ Python 2.6/ Mac 10.6.2
Hi, I am struggling with this for the past 2 days: first I got the above error, & googled around to find that I needed the libjpeg module as well, so I re-installed the lot, first libjpeg & then PIL; got a couple errors like JPEG decoder not available etc, fixed that. Now it passes the selftest, but when I try to upload images via the admin site, it throws up the error "Upload a valid image. The file you uploaded was either not an image or a corrupted image." Any help is appreciated. Thanks. -Ara -- http://mail.python.org/mailman/listinfo/python-list
Re: Perl Hacker, Python Initiate
you've already got a hint on how to do it using library functions in python. below is a more literal suggestion. On Feb 1, 10:36 pm, Gary Chambers wrote: > All, > > Given the following Perl script: > > #!/usr/bin/perl > > %dig = ( > solaris => "/usr/sbin/dig", > linux => "/usr/bin/dig", > darwin => "/usr/bin/dig" > ); dig = {"solaris":"/usr/sbin/dig", "linux":"/usr/bin/dig", "darwin":"/ usr/bin/dig"} > > $DIG = $dig{"$^O"}; dig = dig[os.uname()[0].lower()] > $DOMAIN = "example.com"; > $DNS = "ns.example.com"; domain, dns = ['%sexample.com'%p for p in ('', 'ns.')] # ;) > $DIGCMD = qq/$DIG \@$DNS $DOMAIN axfr/; digcmd = '%s @%s %s axfr' % (dig, dns, domain) > > open DIG, "$DIGCMD|" or die "$DIG: $!\n"; > while () { > next if (/^;/); # Skip any comments > # If we match a CNAME record, we have an alias to something. > # $1 = alias (CNAME), $2 = canonical hostname > if (/^(\S+)\.${DOMAIN}\.\s+\d+\s+IN\s*CNAME\s+(\S+)\.${DOMAIN}\.$/) { > # Push an alias (CNAME) onto an array indexed on canonical hostname > push(@{$cnames{$2}}, $1); > } > # Here's a standard A (canonical hostname) record > # $1 = canonical hostname, $2 = IPv4 address > if (/^(\S+)\.${DOMAIN}\.\s+\d+\s+IN\s*A\s+(\S+)$/) { > $ip{$1} = $2; > }} > > close DIG; lines = [line for line in os.popen(digcmd) if not re.match(';', line)] cname, ip = [re.compile(s.format(domain)) for s in (r'(\S+)\.{0}\.\s+\d+\s+IN\s*CNAME\s+(\S+)\.{0}\.$', r'(\S +)\.{0}\.\s+\d+\s+IN\s*A\s+(\S+)$')] cnames, ips = [dict(m.groups() for m in (p.match(l) for l in lines) if m) for p in cname, ip)] the rest is left as an exercise. i did not test this exact code because i don't have your data, but a modified version works on different data. vQ > > # Format and display it like niscat hosts: > # canonicalHostname alias1 [alias2 aliasN] ipAddress > for $host (sort keys %ip) { > print "$host "; > if (defined(@{$cnames{$host}})) { > print join(' ', @{$cnames{$host}}); > print " "; > } > print "$ip{$host}\n";} > > exit 0; > > Will someone please provide some insight on how to accomplish that task in > Python? I am unable to continually (i.e. it stops after displaying a single > line) loop through the output while testing for the matches on the two > regular expressions. Thank you. > > -- Gary Chambers -- http://mail.python.org/mailman/listinfo/python-list
Re: Perl Hacker, Python Initiate
On 2 Feb, 05:36, Gary Chambers wrote: > Given the following Perl script: (...) Let me quote the deceased Norwegian lisp hacker Erik Naggum: "Excuse me while I barf in Larry Wall's general direction." Sturla -- http://mail.python.org/mailman/listinfo/python-list
Re: IDLE: A cornicopia of mediocrity and obfuscation.
On Feb 3, 4:29 am, flebber wrote: > For an example of a brilliant beginners "ide" racket has it covered > with DrRackethttp://racket-lang.org/, it has selectable language > levels beginner, intermediate, advanced that allows the learner to > adjust the level of language features available as they learn, > teachpacks are installable to add extra features or options when > completing the tutorials(could easily be adapted to the python > tutorials). If idle is for teaching people to learn python shouldn't > it have the facility to do that? I think it would be a bad idea for us to follow in racket's footsteps. Primarily because these sorts of "handicapping" of the language do not actually help a new user. How is it going to help a beginner by removing certain features? If you don't understand a certain feature then removing the feature does not relieve the confusion. If the philosophy breaks down to "gentle learning curve" then a properly written tutorial is all you need. Ad Python has tons of them! You should read some of Guido's anecdotes about the ABC language where the developers attempted to change "tried and tested" terms to something they thought would be less esoteric for Luddites to learn -- in the end all they accomplished was to propagate more confusion. Multiplicity should never be a feature in programming languages... There should be one-- and preferably only one --obvious way to do it. Actually some could argue that Python breaks this rule many times over and they would be correct! However if you look at a language like Ruby you quickly understand that we rather benign by comparison. However i do believe that IDLE could use a few more beginner enhancements. First, we need to clean up the code base. We cannot keep bolting on features as an afterthought. -- http://mail.python.org/mailman/listinfo/python-list
Re: os.path.join doubt
Steven D'Aprano wrote: BTW, Windows accepts / as well as \ as a path separator. You will have far fewer headaches if you use that. Just because Windows accepts / doesn't make it a good idea... Python 2.5.4 (r254:67916, Dec 23 2008, 15:10:54) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. --> from glob import glob --> print '\n'.join(glob('c:/temp/*')) c:/temp\0C2O0007.TMP c:/temp\27421 c:/temp\3K540007.TMP c:/temp\AIF19780_01B_BACKUP.DBF c:/temp\Arabic.bin c:/temp\au-descriptor-1.6.0_23-b71.xml c:/temp\AUCHECK_CORE.txt c:/temp\AUCHECK_PARSER.txt c:/temp\bar.py c:/temp\bar.pyc c:/temp\caller.py c:/temp\caller.pyc c:/temp\choose_python.pdf c:/temp\CMD19639_B_BACKUP.DBF c:/temp\COA.pdf c:/temp\compress.py c:/temp\compress.pyc c:/temp\control.dbf c:/temp\control.FPT Or is there an option I'm missing so backslashes are not returned by stdlib functions? ~Ethan~ -- http://mail.python.org/mailman/listinfo/python-list
Re: Perl Hacker, Python Initiate
Gary Chambers writes: > Will someone please provide some insight on how to accomplish that > task in Python? I am unable to continually (i.e. it stops after > displaying a single line) loop through the output while testing for > the matches on the two regular expressions. Thank you. If I understand you correctly, here is the relevant part (untested): import subprocess, collections dig = subprocess.Popen(["dig", "ns.example.com", "example.com", "axfr"], stdout=subprocess.PIPE).stdout # defaultdict allows the equivalent of push @{$x{$y}}, $z cnames = collections.defaultdict(list) ip = {} for line in dig: if line.startswith(';'): continue # Skip any comments m = re.search(r'regexp1', line) if m: cnames[m.group(2)].append(m.group(1)) # push ... m = re.search(r'regexp2', line) if m: ip[m.group(1)] = m.group(2) -- http://mail.python.org/mailman/listinfo/python-list
Re: Errors while using strip and remove on a variable.
On 02/03/2011 07:21 AM, anand jeyahar wrote: Hi, I am trying to strip a string and then remove on the resulting list to remove a set of characters. It works fine with the python shell. But after remove the list becomes None, when i am running it from within a script. I am guessing it has something to do with the way python handles assignment. please find the script below* a ='oe,eune,eueo, ,u' b = a.split(',') print b c = b.remove('oe') print a print c On a list, the "remove" method does not create and return a new list -- instead it removes the element from the list in place.In your code, you "print a" and "print c", but you should have done "print b", where you will find the result you expect. Gary Herron == Anand Jeyahar http://sites.google.com/a/cbcs.ac.in/students/anand == The man who is really serious, with the urge to find out what truth is, has no style at all. He lives only in what is. ~Bruce Lee Love is a trade with lousy accounting policies. ~Aang Jie -- http://mail.python.org/mailman/listinfo/python-list
Re: Errors while using strip and remove on a variable.
On Thu, Feb 3, 2011 at 10:21 AM, anand jeyahar wrote: > Hi, > I am trying to strip a string and then remove on the resulting list to > remove a set of characters. It works fine with the python shell. > > But after remove the list becomes None, when i am running it from within a > script. > > I am guessing it has something to do with the way python handles assignment. > please find the script below* > > a ='oe,eune,eueo, ,u' > b = a.split(',') > print b > c = b.remove('oe') The remove method of a list modifies the list in place and doesn't return anything (Therefore, it returns None because every function/method in Python has to return something). There's no need to assign the result to a variable. -- http://mail.python.org/mailman/listinfo/python-list
Errors while using strip and remove on a variable.
Hi, I am trying to strip a string and then remove on the resulting list to remove a set of characters. It works fine with the python shell. But after remove the list becomes None, when i am running it from within a script. I am guessing it has something to do with the way python handles assignment. please find the script below* a ='oe,eune,eueo, ,u' b = a.split(',') print b c = b.remove('oe') print a print c == Anand Jeyahar http://sites.google.com/a/cbcs.ac.in/students/anand == The man who is really serious, with the urge to find out what truth is, has no style at all. He lives only in what is. ~Bruce Lee Love is a trade with lousy accounting policies. ~Aang Jie -- http://mail.python.org/mailman/listinfo/python-list
Re: os.path.join doubt
'C:\\Users\\me\\Documents\\..\\Pictures\\images\\my.jpg' is a valid path. .. means parent, not 'go back a directory'. But you should really be trying this: p1 = os.environ['HOMEPATH'] p2 = os.path.join(p1, 'Pictures', 'images', 'my.jpg') On Wed, 2011-02-02 at 20:46 -0800, harryos wrote: > In windows ,I tried this > > p1 = "C:\Users\me\Documents" > p2 = "..\Pictures\images\my.jpg" > > print os.path.join(p1,p2) > This gives > 'C:\\Users\\me\\Documents\\..\\Pictures\\images\\my.jpg' > > I expected I would get > 'C:\\Users\\me\\Pictures\\images\\my.jpg' > > I thought os.path.join would join the paths more intelligently..Any > idea why this happens ? > harry > > -- http://mail.python.org/mailman/listinfo/python-list
Re: locale settings and date parsing under windows
Matt, > I'm now just using a handbuilt dict that holds translations like > > 'fr_FR' : 'French_France' > 'da_DK' : 'Danish_Denmark' What sources are you using for your dict keys and dict values? I'm struggling with the same issue and I'm looking for master references for both sets of code. Thank you, Malcolm -- http://mail.python.org/mailman/listinfo/python-list
Re: IDLE: A cornicopia of mediocrity and obfuscation.
On Thu, Feb 3, 2011 at 5:29 AM, flebber wrote: > On Feb 1, 11:38 pm, rantingrick wrote: >> On Feb 1, 4:20 am, flebber wrote: >> >> > Sorry Rick too boringtrying to get bored people to bite at your >> > ultra lame post yawn... >> >> Well reality and truth both has a tendency to be boring. Why? Well >> because we bathe in them daily. We have come accustomed, acclimated, >> and sadly complacent of the ill state of our stdlib. Yes, boring. >> However we must be aware of these things. > > Yes but fixing idle just gives us another editor, there isn't a > shortage of editors. There is a shortage of a common community code > base for an ide framework, logical, reusable and extensible. > > For an example of a brilliant beginners "ide" racket has it covered > with DrRacket http://racket-lang.org/ , it has selectable language > levels beginner, intermediate, advanced that allows the learner to > adjust the level of language features available as they learn, > teachpacks are installable to add extra features or options when > completing the tutorials(could easily be adapted to the python > tutorials). If idle is for teaching people to learn python shouldn't > it have the facility to do that? Python is a general purpose language that's designed to be easy to use. Racket is a language that was designed for teaching programming. It's almost exclusively tied to a single IDE. Something like language levels would be impossible to do in Python unless you re-do the parser. There's no feature that allows you to strip for loops or list comprehensions out of the language. And we already have something better than teachpacks- the import mechanism and the ability to install 3rd party extensions. > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: locale settings and date parsing under windows
On Feb 3, 12:13 pm, "Martin P. Hellwig" wrote: > On 02/03/11 10:59, AlienBaby wrote: > > > > > > > On Feb 3, 10:22 am, AlienBaby wrote: > >> Hi, > > >> I'm attempting to convert some date-time strings from a text file > >> under windows into a datetime object as returned by strptime() > > >> However, the strings can represent dates in various formats based on > >> the country of origin, for example shortened month names etc.. are > >> different between countries. > > >> I am trying to set the correct locale for strptime to work, but I'm > >> having a lot of trouble doing this under windows. > > >> IE, wher the date is in the Danish Language, > > >> import locale > >> locale.setlocale('LC_ALL',locale.normalize('da_DK')) > > >> gives > > >> locale.Error: unsupported locale string. > > >> I have tried various ways but always hit the same error. > > >> I understand setting LC_ALL may not be what I require, I was first > >> looking to simply get the locale setting correctly before I started > >> changing only the date-time specific elements. > > >> Any help or pointers much appreciated. Current searching around is > >> revealing a fair amount of confusion..! > > >> Thanks, > > >> Matt. > > > As often happens, writing that out and the working through a bit more, > > I resolved my own question. > > > It ended up being a simple matter of translating from posix codes to > > windows codes, so 'fr_FR' becomes 'French_France'... > > > thanks, > > > MAtt. > > You might also want to have a look at the contents of: > locale.locale_alias > > -- > mph- Hide quoted text - > > - Show quoted text - I did for a bit.. I tried, for example with French from locale.locale_alias, you can find 'fr_FR' aliases to 'fr_FR.ISO8859-1' but trying, locale.setlocale(locale.LC_ALL,'fr_FR.ISO8859-1') gives locale.Error: unsupported locale setting I'm now just using a handbuilt dict that holds translations like 'fr_FR' : 'French_France' 'da_DK' : 'Danish_Denmark' etc.. Thanks, MAtt. -- http://mail.python.org/mailman/listinfo/python-list
Re: locale settings and date parsing under windows
On 02/03/11 10:59, AlienBaby wrote: On Feb 3, 10:22 am, AlienBaby wrote: Hi, I'm attempting to convert some date-time strings from a text file under windows into a datetime object as returned by strptime() However, the strings can represent dates in various formats based on the country of origin, for example shortened month names etc.. are different between countries. I am trying to set the correct locale for strptime to work, but I'm having a lot of trouble doing this under windows. IE, wher the date is in the Danish Language, import locale locale.setlocale('LC_ALL',locale.normalize('da_DK')) gives locale.Error: unsupported locale string. I have tried various ways but always hit the same error. I understand setting LC_ALL may not be what I require, I was first looking to simply get the locale setting correctly before I started changing only the date-time specific elements. Any help or pointers much appreciated. Current searching around is revealing a fair amount of confusion..! Thanks, Matt. As often happens, writing that out and the working through a bit more, I resolved my own question. It ended up being a simple matter of translating from posix codes to windows codes, so 'fr_FR' becomes 'French_France'... thanks, MAtt. You might also want to have a look at the contents of: locale.locale_alias -- mph -- http://mail.python.org/mailman/listinfo/python-list
Re: locale settings and date parsing under windows
On Feb 3, 10:22 am, AlienBaby wrote: > Hi, > > I'm attempting to convert some date-time strings from a text file > under windows into a datetime object as returned by strptime() > > However, the strings can represent dates in various formats based on > the country of origin, for example shortened month names etc.. are > different between countries. > > I am trying to set the correct locale for strptime to work, but I'm > having a lot of trouble doing this under windows. > > IE, wher the date is in the Danish Language, > > import locale > locale.setlocale('LC_ALL',locale.normalize('da_DK')) > > gives > > locale.Error: unsupported locale string. > > I have tried various ways but always hit the same error. > > I understand setting LC_ALL may not be what I require, I was first > looking to simply get the locale setting correctly before I started > changing only the date-time specific elements. > > Any help or pointers much appreciated. Current searching around is > revealing a fair amount of confusion..! > > Thanks, > > Matt. As often happens, writing that out and the working through a bit more, I resolved my own question. It ended up being a simple matter of translating from posix codes to windows codes, so 'fr_FR' becomes 'French_France'... thanks, MAtt. -- http://mail.python.org/mailman/listinfo/python-list
Re: Style question: Nicknames for deeply nested objects
Gerald Britton wrote: however, considering what "import a.module.that.is.quite.nested as myModule" Won't work since I get the objects at run time myModule = __import__('whatever.module.imported.at.run.time', globals(), locals(), [], -1) See http://docs.python.org/library/functions.html#__import__ JM -- http://mail.python.org/mailman/listinfo/python-list
Re: IDLE: A cornicopia of mediocrity and obfuscation.
On Feb 1, 11:38 pm, rantingrick wrote: > On Feb 1, 4:20 am, flebber wrote: > > > Sorry Rick too boringtrying to get bored people to bite at your > > ultra lame post yawn... > > Well reality and truth both has a tendency to be boring. Why? Well > because we bathe in them daily. We have come accustomed, acclimated, > and sadly complacent of the ill state of our stdlib. Yes, boring. > However we must be aware of these things. Yes but fixing idle just gives us another editor, there isn't a shortage of editors. There is a shortage of a common community code base for an ide framework, logical, reusable and extensible. For an example of a brilliant beginners "ide" racket has it covered with DrRacket http://racket-lang.org/ , it has selectable language levels beginner, intermediate, advanced that allows the learner to adjust the level of language features available as they learn, teachpacks are installable to add extra features or options when completing the tutorials(could easily be adapted to the python tutorials). If idle is for teaching people to learn python shouldn't it have the facility to do that? -- http://mail.python.org/mailman/listinfo/python-list
locale settings and date parsing under windows
Hi, I'm attempting to convert some date-time strings from a text file under windows into a datetime object as returned by strptime() However, the strings can represent dates in various formats based on the country of origin, for example shortened month names etc.. are different between countries. I am trying to set the correct locale for strptime to work, but I'm having a lot of trouble doing this under windows. IE, wher the date is in the Danish Language, import locale locale.setlocale('LC_ALL',locale.normalize('da_DK')) gives locale.Error: unsupported locale string. I have tried various ways but always hit the same error. I understand setting LC_ALL may not be what I require, I was first looking to simply get the locale setting correctly before I started changing only the date-time specific elements. Any help or pointers much appreciated. Current searching around is revealing a fair amount of confusion..! Thanks, Matt. -- http://mail.python.org/mailman/listinfo/python-list
Re: DRY and static attribute for multiple classes.
On Feb 3, 10:24 am, Peter Otten <__pete...@web.de> wrote: > Marc Aymerich wrote: > > On Feb 2, 12:11 am, Peter Otten <__pete...@web.de> wrote: > >> Marc Aymerich wrote: > > Hi!, > > Unfortunately per_class attribute losses the "independence" when I try > > to mix it with django models.Model . > > > from django.db import models > > class Plugin(models.base.ModelBase): > > class __metaclass__(type): > > def __init__(self, *args): > > type.__init__(self, *args) > > self.per_class = [] > > > class BaseService(models.Model): > > class Meta: > > abstract = True > > > __metaclass__ = Plugin > > > class VirtualHost(BaseService): > > name = models.CharField(max_length=10) > > > class SystemUser(BaseService): > > name = models.CharField(max_length=10) > > VirtualHost.per_class is SystemUser.per_class > > True > > > What am I doing wrong? > > I'm surprised that you are seeing the per_class-attribute at all as you are > defining it in the metaclass of the metaclass, as far as I can tell. > I think the following should work: > > from django.db import models > > class Plugin(models.base.ModelBase): > def __init__(self, *args): > super(Plugin, self).__init__(*args) > self.per_class = [] > > class BaseService(models.Model): > class Meta: > abstract = True > > __metaclass__ = Plugin > > class VirtualHost(BaseService): > name = models.CharField(max_length=10) > > class SystemUser(BaseService): > name = models.CharField(max_length=10) > > assert VirtualHost.per_class is not SystemUser.per_class > > But I have never worked with Django, and the approach based on dictionary > lookup is less likely to interfere with the dark corners of the framework. > > Peter Wow Peter, thanks for the correction, I've never used a metaclass before :) With your correction seems that it works perfectly on djando >>> VirtualHost._plugin_registry.append('000') >>> VirtualHost._plugin_registry ['000'] >>> SystemUser._plugin_registry [] >>> -- http://mail.python.org/mailman/listinfo/python-list
Re: os.path.join doubt
On Thu, 03 Feb 2011 06:31:49 +, Steven D'Aprano wrote: > On Wed, 02 Feb 2011 20:46:12 -0800, harryos wrote: > >> In windows ,I tried this >> >> p1 = "C:\Users\me\Documents" >> p2 = "..\Pictures\images\my.jpg" Don't do this; backslash is significant within Python string literals. If want to use literal backslashes in a string literal, either double them: p1 = "C:\\Users\\me\\Documents" or use a raw literal: p1 = r"C:\Users\me\Documents" You got away with it because backslash is only significant when followed by specific characters, none of which occurred in this case. > BTW, Windows accepts / as well as \ as a path separator. You will have > far fewer headaches if you use that. Unless you need to pass strings to the command interpreter, which has its own interpretation of forward slashes. Apart from that, while forward slashes are supported by Windows itself, they aren't the "standard" separator, and may not be supported by other programs running on Windows. In general, directory separators shouldn't occur within string literals. Base directories should be taken from command-line parameters, registry entries, configuration files, environment variables etc, not embedded into the program. Paths relative to those directories should be constructed with os.path.join(). -- http://mail.python.org/mailman/listinfo/python-list
Re: Reassign or discard Popen().stdout from a server process
On Tue, 01 Feb 2011 08:30:19 +, John O'Hagan wrote: > I can't keep reading because that will block - there won't be any more > output until I send some input, and I don't want it in any case. > > To try to fix this I added: > > proc.stdout = os.path.devnull > > which has the effect of stopping the server from failing, but I'm not > convinced it's doing what I think it is. It isn't. os.path.devnull is a string, not a file. But even if you did: proc.stdout = open(os.path.devnull, 'w') that still wouldn't work. > If I replace devnull in the above line with a real file, it stays empty > although I know there is more output, which makes me think it hasn't > really worked. It hasn't. > Simply closing stdout also seems to stop the crashes, but doesn't that mean > it's still being written to, but the writes are just silently failing? In > either case I'm wary of more elusive bugs arising from misdirected stdout. If you close proc.stdout, the next time the server writes to its stdout, it will receive SIGPIPE or, if it catches that, the write will fail with EPIPE (write on pipe with no readers). It's up to the server how it deals with that. > Is it possible to re-assign the stdout of a subprocess after it has started? No. > Or just close it? What's the right way to read stdout up to a given > line, then discard the rest? If the server can handle the pipe being closed, go with that. Otherwise, options include redirecting stdout to a file and running "tail -f" on the file from within Python, or starting a thread or process whose sole function is to read and discard the server's output. -- http://mail.python.org/mailman/listinfo/python-list
Re: DRY and static attribute for multiple classes.
Marc Aymerich wrote: > On Feb 2, 12:11 am, Peter Otten <__pete...@web.de> wrote: >> Marc Aymerich wrote: > Hi!, > Unfortunately per_class attribute losses the "independence" when I try > to mix it with django models.Model . > > from django.db import models > class Plugin(models.base.ModelBase): > class __metaclass__(type): > def __init__(self, *args): > type.__init__(self, *args) > self.per_class = [] > > class BaseService(models.Model): > class Meta: > abstract = True > > __metaclass__ = Plugin > > class VirtualHost(BaseService): > name = models.CharField(max_length=10) > > class SystemUser(BaseService): > name = models.CharField(max_length=10) > > VirtualHost.per_class is SystemUser.per_class > True > > What am I doing wrong? I'm surprised that you are seeing the per_class-attribute at all as you are defining it in the metaclass of the metaclass, as far as I can tell. I think the following should work: from django.db import models class Plugin(models.base.ModelBase): def __init__(self, *args): super(Plugin, self).__init__(*args) self.per_class = [] class BaseService(models.Model): class Meta: abstract = True __metaclass__ = Plugin class VirtualHost(BaseService): name = models.CharField(max_length=10) class SystemUser(BaseService): name = models.CharField(max_length=10) assert VirtualHost.per_class is not SystemUser.per_class But I have never worked with Django, and the approach based on dictionary lookup is less likely to interfere with the dark corners of the framework. Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: IDLE: A cornicopia of mediocrity and obfuscation.
On Feb 2, 9:03 pm, alex23 wrote: > rantingrick wrote: > > Hmm, that coming from someone who has two posts in this group. And the > > last he posted was a year ago! > > Wait, I thought you had the approval of the silent majority? > > So once anyone actually posts, they lost the right to be counted, > because only when they shut up can you consider them allies? Lulz, +1 internetz for you -- http://mail.python.org/mailman/listinfo/python-list
Re: parse GET/POST data on simple http server
On Feb 3, 9:35 am, Chris Rebert wrote: > On Thu, Feb 3, 2011 at 12:15 AM, Markus wrote: > > Hi, > > > As a beginner in python, I am looking for example code that would help > > me understand how to > > code following idea: > > 1. Start minimal http server > > http://docs.python.org/library/basehttpserver.htmlhttp://docs.python.org/library/simplehttpserver.htmlhttp://docs.python.org/library/cgihttpserver.html > > > 2. Send GET or POST data (url encoded, or from form) - example > > Name="Foo" > > http://docs.python.org/library/urllib.html#urllib.urlencode > > > 3. Analyze the GET/POST variable value on server and match to > > different value > > example 'if Name = "Foo" then retval = "Bar" ' > > http://docs.python.org/library/cgi.html > > > 4. serve the content of retval back to user as plain html > > > If some code snipped that does implement all or part of the algorithm > > is known to you, please point me to it. I would be thankful for any > > push to the right direction. > > You'll be reinventing quite a few wheels if you work at such a low > level of abstraction. Have you considered using a web framework? > Django (http://www.djangoproject.com/) is one of the popular ones, > though there are a myriad of options > (http://wiki.python.org/moin/WebFrameworks). I would recommend > learning Python first and then a web framework, rather than trying to > learn both in tandem. > > Cheers, > Chris > --http://blog.rebertia.com Thank you for all that input, I will definitely check Django - it looks very interesting. I just found an example code that fits perfectly and is simple enough for me to play with it. http://stackoverflow.com/questions/336866/how-to-implement-a-minimal-server-for-ajax-in-python And one older post handling the same case with HTTPS: http://groups.google.com/group/comp.lang.python/browse_thread/thread/a1e761a02a852821/2ff6f704b3a6749a?lnk=gst&q=server+parse+post#2ff6f704b3a6749a :o) -- http://mail.python.org/mailman/listinfo/python-list
Re: parse GET/POST data on simple http server
On Thu, Feb 3, 2011 at 12:15 AM, Markus wrote: > Hi, > > As a beginner in python, I am looking for example code that would help > me understand how to > code following idea: > 1. Start minimal http server http://docs.python.org/library/basehttpserver.html http://docs.python.org/library/simplehttpserver.html http://docs.python.org/library/cgihttpserver.html > 2. Send GET or POST data (url encoded, or from form) - example > Name="Foo" http://docs.python.org/library/urllib.html#urllib.urlencode > 3. Analyze the GET/POST variable value on server and match to > different value > example 'if Name = "Foo" then retval = "Bar" ' http://docs.python.org/library/cgi.html > 4. serve the content of retval back to user as plain html > > If some code snipped that does implement all or part of the algorithm > is known to you, please point me to it. I would be thankful for any > push to the right direction. You'll be reinventing quite a few wheels if you work at such a low level of abstraction. Have you considered using a web framework? Django (http://www.djangoproject.com/ ) is one of the popular ones, though there are a myriad of options (http://wiki.python.org/moin/WebFrameworks ). I would recommend learning Python first and then a web framework, rather than trying to learn both in tandem. Cheers, Chris -- http://blog.rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
Re: parse GET/POST data on simple http server
On 02/03/2011 03:15 AM, Markus wrote: > Hi, > > As a beginner in python, I am looking for example code that would help > me understand how to > code following idea: > 1. Start minimal http server > 2. Send GET or POST data (url encoded, or from form) - example > Name="Foo" > 3. Analyze the GET/POST variable value on server and match to > different value > example 'if Name = "Foo" then retval = "Bar" ' > 4. serve the content of retval back to user as plain html > > If some code snipped that does implement all or part of the algorithm > is known to you, please point me to it. I would be thankful for any > push to the right direction. > > Thank you! [1] http://docs.python.org/library/cgihttpserver.html#module-CGIHTTPServer ...Sorry about that. I shouldn't post late at night! -- http://mail.python.org/mailman/listinfo/python-list
Re: parse GET/POST data on simple http server
On 02/03/2011 03:15 AM, Markus wrote: > Hi, > > As a beginner in python, I am looking for example code that would help > me understand how to > code following idea: > 1. Start minimal http server > 2. Send GET or POST data (url encoded, or from form) - example > Name="Foo" > 3. Analyze the GET/POST variable value on server and match to > different value > example 'if Name = "Foo" then retval = "Bar" ' > 4. serve the content of retval back to user as plain html > > If some code snipped that does implement all or part of the algorithm > is known to you, please point me to it. I would be thankful for any > push to the right direction. > > Thank you! If you really can't use a 'real' webserver like Apache, I found [1]. Not sure how to use it, never had the need to. The documentation will show you the way, however. Using that and the cgi module, your requirements should be fulfilled. -- http://mail.python.org/mailman/listinfo/python-list
parse GET/POST data on simple http server
Hi, As a beginner in python, I am looking for example code that would help me understand how to code following idea: 1. Start minimal http server 2. Send GET or POST data (url encoded, or from form) - example Name="Foo" 3. Analyze the GET/POST variable value on server and match to different value example 'if Name = "Foo" then retval = "Bar" ' 4. serve the content of retval back to user as plain html If some code snipped that does implement all or part of the algorithm is known to you, please point me to it. I would be thankful for any push to the right direction. Thank you! -- http://mail.python.org/mailman/listinfo/python-list