Re: python+ncurses: I can't display accents
On 27 Jan 2007 07:43:59 GMT, Fabrice DELENTE wrote
> Incidentally, I noticed something about the environment: in my
> script, I use the LINES and COLUMNS environment vars that are set in
> my shell:
>
> columns=int(os.environ.get("COLUMNS"))
> lines=int(os.environ.get("LINES"))
>
> In the shell, I get
>
> $ echo $LINES $COLUMNS
> 89 199
>
> but python doesn't get these values. I have to start the script with
>
> $ LINES=$LINES COLUMNS=$COLUMNS ./sort_entries.py
>
> How come?
There is a distinction between shell variables and environment variables. In
all likelihood, LINES and COLUMNS are shell variables, not environment
variables. Try "export LINES COLUMNS" to set them as environment variables.
HTH,
Carsten.
--
http://mail.python.org/mailman/listinfo/python-list
Re: Yank Bastards KILLED THEIR OWN PEOPLE to stage 911 DRAMA
See, if the python list mail server was written in Lisp Paul Graham would already have been able to write up a spam filter to ban this guy. Seriously though, shouldn't Thermate be banned by now. Cheers, Bryan Rasmussen On 26 Jan 2007 10:56:44 -0800, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote: > There is a million dollar reward for ANY fascist bastard to disprove > this assertion by giving a consistent theory of ALL the major observed > effects on that day about the related events. > > Dick faced Cheney sprayed his own lawyer with BB's. > > See the video by Alex Jones on the Forensics, why the claims of > distance and mistake were such a big lie ... > > 911 TRUTH BACK WITH VIGOR AND NEW SITE > Now it has two sites under > www.st911.org > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: python+ncurses: I can't display accents
> Try "export LINES COLUMNS" to set them as environment variables. Thanks, it works. Didn't know that. -- Fabrice DELENTE -- http://mail.python.org/mailman/listinfo/python-list
Re: Convert String to list of chars
On Jan 27, 9:18 am, Neil Cerutti <[EMAIL PROTECTED]> wrote:
> On 2007-01-27, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
>
> > How can I convert a string to a char list?
> > for example
>
> > "hello" --> ['h','e','l','l','o']
>
> > I have been searching but I can't find my answers
> list("hello")
Wow, I've been using [c for c in 'hello'] for as long as I can remember
needing it. Thanks!
Vlad
--
http://mail.python.org/mailman/listinfo/python-list
Re: python+ncurses: I can't display accents
In <[EMAIL PROTECTED]>, Fabrice DELENTE wrote: > As support for 8-bit (and even unicode) is important for my script, is there > any hope? Should I switch to slang instead of curses? Take a look at urwid: http://excess.org/urwid/ Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: wx Python event question
use wx.Timer - you bind a method to a timer event and define the timer's interval when you start it timer = wx.Timer(self, -1) self.Bind(wx.EVT_TIMER, self.timerMethod, timer) timer.Start(500) On Jan 27, 5:56 pm, "dudds" <[EMAIL PROTECTED]> wrote: > Hi I really haven't used wxPython before and I was just wondering if > there was some sort of timer event that can be used. For example if I > have a database that I want to query at regular intervals and display > the results in a window is that possibly to do under a wx Python > program? > > So far I have come across certain event handlers, but they all seem to > wait for something to happen, like moving the mouse, clicking on a > button etc. I just want to display the results of a query every so > often automatically without having to press a button to do so. > > I'm not looking for a complete solution as I'm doing this so I can > teach myself Python, but a bit of a hint or a nudge in the right > direction would be great. -- http://mail.python.org/mailman/listinfo/python-list
Re: The reliability of python threads
"Carl J. Van Arsdall" <[EMAIL PROTECTED]> wrote: > Hendrik van Rooyen wrote: > > "Carl J. Van Arsdall" <[EMAIL PROTECTED]> wrote: 8< --- > > > Yea, I do some of that too. I use that with conditional print > statements to stderr when i'm doing my validation against my test > cases. But I could definitely do more of them. The thing will be When I read this - I thought - probably your stuff is working perfectly - on your test cases - you could try to send it some random data and to see what happens - seeing as you have a test server, throw the kitchen sink at it. Possibly "random" here means something that "looks like" data but that is malformed in some way. Kind of try to "trick" the system to get it to break reliably. I'm sorry I can't be more specific - it sounds so weak, and you probably already have test cases that "must fail" but I don't know how to put it any better... - Hendrik -- http://mail.python.org/mailman/listinfo/python-list
New vs Old Style Python Classes in C Extensions?
While I have a reasonable understanding of the differences in new-style versus old-style classes, tonight while working a C extension module I realized I don't know how to indicate which style my C extension module should appear as. I'm following the Python docs for extended modules, but it doesn't say in there anyplace I can find which style I'm creating. My clue that something was wrong is when this: from cextension import Context class MyContext(Context): def __init__(self): super(Context, self).__init__() repeatedly and reliably failed with a corrupted C data structure, while this: class MyContext(Context): def __init__(self): Context.__init__() worked without any problems. As I understand it, the former uses new-style semantics while the latter uses old-style, and -thats- when I realized I have no idea which my C extension implemented. Any enlightenment? -Jeff -- http://mail.python.org/mailman/listinfo/python-list
extracting from web pages but got disordered words sometimes
There are ten web pages I want to deal with.
from http://www.af.shejis.com/new_lw/html/125926.shtml
to http://www.af.shejis.com/new_lw/html/125936.shtml
Each of them uses the charset of Chinese "gb2312", and firefox
displays all of them in the right form, that's readable Chinese.
My job is, I get every page and extract the html title of it and
dispaly the title on linux shell Termial.
And, my problem is, to some page, I get human readable title(that's in
Chinese), but to other pages, I got disordered word. Since each page
has the same charset, I don't know why I can't get every title in the
same way.
Here's my python code, get_title.py :
[CODE]
#!/usr/bin/python
import urllib2
from BeautifulSoup import BeautifulSoup
min_page=125926
max_page=125936
def make_page_url(page_index):
return ur"".join([ur"http://www.af.shejis.com/new_lw/
html/",str(page_index),ur".shtml"])
def get_page_title(page_index):
url=make_page_url(page_index)
print "now getting: ", url
user_agent='Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
headers={'User-Agent':user_agent}
req=urllib2.Request(url,None,headers)
response=urllib2.urlopen(req)
#print response.info()
page=response.read()
#extract tile by beautiful soup
soup=BeautifulSoup(page)
full_title=str(soup.html.head.title.string)
#title is in the format of "title --title"
#use this code to delete the "--" and the duplicate title
title=full_title[full_title.rfind('-')+1::]
return title
for i in xrange(min_page,max_page):
print get_page_title(i)
[/CODE]
Will somebody please help me out? Thanks in advance.
--
http://mail.python.org/mailman/listinfo/python-list
Re: Fixed length lists from .split()?
Duncan Booth:
> def nsplit(s, sep, n):
> return (s.split(sep) + [""]*n)[:n]
Another version, longer:
from itertools import repeat
def nsplit(text, sep, n):
"""
>>> nsplit("bcsn; 101; 1456", ";", 3)
['bcsn', ' 101', ' 1456']
>>> nsplit("bcsn; 101", ";", 3)
['bcsn', ' 101', '']
>>> nsplit("bcsn", ";", 3)
['bcsn', '', '']
>>> nsplit("", ".", 4)
['', '', '', '']
>>> nsplit("ab.ac.ad.ae", ".", 2)
['ab', 'ac', 'ad', 'ae']
"""
result = text.split(sep)
nparts = len(result)
result.extend(repeat("", n-nparts))
return result
if __name__ == "__main__":
import doctest
doctest.testmod()
Bye,
bearophile
--
http://mail.python.org/mailman/listinfo/python-list
Re: New vs Old Style Python Classes in C Extensions?
Jeff Rush schrieb: > from cextension import Context > > class MyContext(Context): > > def __init__(self): > super(Context, self).__init__() > > repeatedly and reliably failed with a corrupted C data structure, while > this: > > class MyContext(Context): > > def __init__(self): > Context.__init__() > > worked without any problems. As I understand it, the former uses > new-style semantics while the latter uses old-style, This understanding is incorrect: Context is either a new-style or an old-style class (if type(Context) is type, it's a new-style class, if type(context) is named 'classobj', it's an old-style class). As you have implemented Context in an extension module, it likely is a new-style class (i.e. a type). Most likely, something is wrong with your tp_init slot. You shouldn't be able to call Context.__init__(): that should raise a type error, indicating that an object is needed for the method __init__. That should hold whether Context is a new-style or an old-style class. HTH, Martin -- http://mail.python.org/mailman/listinfo/python-list
Re: python+ncurses: I can't display accents
It's solved, it was a locale problem: I put import locale locale.setlocale(locale.LC_ALL,"fr_FR.iso8859-1") at the beginning of the script, and now the 8-bit-chars show up correctly. Thanks all for your help. -- Fabrice DELENTE -- http://mail.python.org/mailman/listinfo/python-list
Re: New vs Old Style Python Classes in C Extensions?
On Jan 27, 6:11 am, Jeff Rush <[EMAIL PROTECTED]> wrote: > While I have a reasonable understanding of the differences in new-style versus > old-style classes, tonight while working a C extension module I realized I > don't know how to indicate which style my C extension module should appear as. > > I'm following the Python docs for extended modules, but it doesn't say in > there anyplace I can find which style I'm creating. My clue that something > was wrong is when this: > > from cextension import Context > > class MyContext(Context): > > def __init__(self): > super(Context, self).__init__() > > repeatedly and reliably failed with a corrupted C data structure, while this: > > class MyContext(Context): > > def __init__(self): > Context.__init__() > > worked without any problems. As I understand it, the former uses new-style > semantics while the latter uses old-style, and -thats- when I realized I have > no idea which my C extension implemented. > > Any enlightenment? Short answer: It has nothing to do with old-style classes, and is probably just due to a mistake in your extension. Longer answer: C extention types have never implemented old-style classes. Before Python 2.2, classes and types were different things. All class instances were of the same type. However, C extension objects were a different type, and weren't class instances at all. Nowadays, new-style classes are types, but the converse isn't necessary true. In particular, the typical way of defining old extension types didn't work as a new-style type. So, as part of type- class unification, they added some new fields (tp_members, tp_new, and so on) and new idioms to replace some of the old idioms, effectively creating "new-style types". Unless you've adopted the new ways, your type isn't going to work as a class. If you have adopted the new ways, then it's probably just a mistake in your code. I suspect you have adopted the new ways, because I'd expect Python to raise TypeError when trying to subclass a function. So you probably just have a bug. Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
Re: assertions to validate function parameters
Matthew Woodcraft <[EMAIL PROTECTED]> wrote:
> I have a question for you. Consider this function:
>
> def f(n):
> """Return the largest natural power of 2 which does not exceed n."""
> if n < 1:
> raise ValueError
> i = 1
> while i <= n:
> j = i
> i *= 2
> return j
>
> If I pass it an instance of MyNumericClass, it will return an int or a
> long, not an instance of MyNumericClass.
>
> In your view, is this a weakness of the implementation? Should the
> author of the function make an effort to have it return a value of the
> same type that it was passed?
Possibly... It is relatively easy to do anyway and reasonably cheap so
why not? In this case a number about the same size as the original
number (possibly very large) will be returned so the argument that it
should return the same type is reasonably strong.
>>> def f(n):
... """Return the largest natural power of 2 which does not exceed n."""
... if n < 1:
... raise ValueError
... i = n - n + 1
... while i <= n:
... j = i
... i *= 2
... return j
...
>>> f(1023)
512
>>> from decimal import Decimal
>>> f(Decimal("1023"))
Decimal("512")
>>>
There are other ways of writing that
i = n - n + 1
eg
i = n.__class__(1)
It it basically saying "make me a numeric type with this value" so
maybe the __class__ is the clearest. It assumes that the constructor
can co-erce an int into the type, wheras the first assumes that the
type can add an int.
Here is my function to calculate arctan() from any type. The only
subtle bit for a general numeric type is detecting when we've
calculated enough, without using any specific knowledge about which
numeric type.
def arctan(x):
"""
Calculate arctan(x)
arctan(x) = x - x**3/3 + x**5/5 - ... (-1 < x < 1)
"""
total = x
power = x
divisor = 1
old_delta = None
while 1:
power *= x
power *= x
power = -power
divisor += 2
old_total = total
total += power / divisor
delta = abs(total - old_total)
if old_delta is not None and delta >= old_delta:
break
old_delta = delta
return total
>>> arctan(0.5)
0.46364760900080587
>>> arctan(Decimal("0.5"))
Decimal("0.4636476090008061162142562314")
--
Nick Craig-Wood <[EMAIL PROTECTED]> -- http://www.craig-wood.com/nick
--
http://mail.python.org/mailman/listinfo/python-list
Re: python+ncurses: I can't display accents
Fabrice DELENTE <[EMAIL PROTECTED]> wrote: > My system is Linux, and the distribution is Slackware 10.1. > I have > /lib/libncurses.so.5.4 > /lib/libncursesw.so.5.4 > so I even have the wide-chars version available. Any hint on the python > configuration? I didn't find any function that would allow the unrestricted > display of 8-bit chars. It's more complicated than that: python's loading "ncurses" dynamically. It doesn't matter much (to python) which one it loads, but it's specifying the library name explicitly. At the same time, some other packages (such as readline) are _separately_ loading the ncurses library - and they also specify a library name. Rather than abstracting that stuff out to another (more easily changed) level, it's embedded in the code. If the initialization script is changed to load "ncursesw" then python can use ncursesw without further change. There are a few patches to the configuration that I've seen mentioned in the bug reports to enable python to do this. Those are patches to python of course... (this was a topic of discussion on this newsgroup about a year ago). -- Thomas E. Dickey http://invisible-island.net ftp://invisible-island.net -- http://mail.python.org/mailman/listinfo/python-list
Hi, I'm new to python
Hey Everyone Let me tell you all a little bit about my programming background so you can get an idea of my capability, or lack of, dealing with p.l; so far i've learned some visual basic when i was doing my a-levels and thats about it lol. Basically i like the sound of python and its ease of use and would like to know in depth more about it and its range of useage. Please do tell me all you know, keeping in mind i am a n00b, so do be gentle. :) Thanks Millball54 -- http://mail.python.org/mailman/listinfo/python-list
Re: wx Python event question
Thanks Steve. On Jan 27, 8:01 pm, "Steve" <[EMAIL PROTECTED]> wrote: > use wx.Timer - you bind a method to a timer event and define the > timer's interval when you start it > > timer = wx.Timer(self, -1) > self.Bind(wx.EVT_TIMER, self.timerMethod, timer) > timer.Start(500) > > On Jan 27, 5:56 pm, "dudds" <[EMAIL PROTECTED]> wrote: > > > Hi I really haven't used wxPython before and I was just wondering if > > there was some sort of timer event that can be used. For example if I > > have a database that I want to query at regular intervals and display > > the results in a window is that possibly to do under a wx Python > > program? > > > So far I have come across certain event handlers, but they all seem to > > wait for something to happen, like moving the mouse, clicking on a > > button etc. I just want to display the results of a query every so > > often automatically without having to press a button to do so. > > > I'm not looking for a complete solution as I'm doing this so I can > > teach myself Python, but a bit of a hint or a nudge in the right > > direction would be great. -- http://mail.python.org/mailman/listinfo/python-list
Re: assertions to validate function parameters
On Jan 25, 11:26 pm, Steven D'Aprano
<[EMAIL PROTECTED]> wrote:
> Note also that for real code, a bare assert like that is uselessly
> uninformative:
>
> >>> x = 1
> >>> assert x == 3Traceback (most recent call last):
> File "", line 1, in ?
> AssertionError
In real code, a traceback usually prints the line of code containing
the failed assertion.
> This is better:
>
> >>> assert x == 3, "x must be equal to three but is %s instead" % xTraceback
> >>> (most recent call last):
> File "", line 1, in ?
> AssertionError: x must be equal to three but is 1 instead
>
> This is even better still:
>
> >>> if x != 3:... raise ValueError("x must be equal to three but is %s
> >>> instead" % x)
> ...
> Traceback (most recent call last):
> File "", line 1, in ?
> ValueError: x must be equal to three but is 1 instead
These are are verbose to the point of silliness, and usually not worth
the effort since assertions are only supposed to check for ostensibly
impossible conditions. Thus it shouldn't pop up often enough to
justify writing a verbose error message in advance, and when it does
trigger you're going to have to print the failed result in a debuging
run anyways.
Carl Banks
--
http://mail.python.org/mailman/listinfo/python-list
Re: assertions to validate function parameters
On Jan 25, 11:54 am, Matthew Wilson <[EMAIL PROTECTED]> wrote: > Lately, I've been writing functions like this: > > def f(a, b): > > assert a in [1, 2, 3] > assert b in [4, 5, 6] > > The point is that I'm checking the type and the values of the > parameters. > > I'm curious how this does or doesn't fit into python's duck-typing > philosophy. The duck-typing thing fits into a wider philosophy of being liberal in what you accept. As you're constraining what a function accepts, it definitely goes against the philosophy. I suggest you not blindly slap assertions on every single function. Assertions should only be used to check for ostensibly impossible conditions. Therefore, guarding arguments like this is probably only a good idea for internal or private functions that you can personally guarantee will only be called with the right values. Personally, I find assertions are more helpful in complex situtations where I find myself having to maintain some sort of invariant. Some condition is supposed to always be true at this point, and my code relies on this. I've taken steps to maintain the invariant, but I could have made a mistake. So I throw an assertion in. If there's a leak somewhere, it will catch it. > I find that when I detect invalid parameters overtly, I spend less time > debugging. If it helps go ahead an use them. The world won't end if you use an assertion in a less than ideal situation. And, after all, if someone doesn't like it they can shut them off. > Are other people doing things like this? Any related commentary is > welcome. Well, there are examples of this usage of assert the standard library. Some public functions (off hand I can think of the threading module) use assertions to check for invalid arguments, a use I highly disagree with. The library shouldn't be making assertions on behalf of the users. If an AssertionError is raised from the threading module, it should be because there is a bug in the threading module, not because the user passed it a bad value. But, yes, it has been done. Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
Re: problems with pyzeroconf and linux
> I am trying to get pyzeroconf (http://sourceforge.net/projects/pyzeroconf)
> running on my machine but having trouble... Running the Zeroconf.py file
> seems to register the service, but is unable to find it.
You should be running avahi.. it also comes python support.
Here's an example that registers a CNAME that points to your hostname (that
avahi itself publishes)
#! /usr/bin/env python
import avahi, dbus
from encodings.idna import ToASCII
# Got these from /usr/include/avahi-common/defs.h
CLASS_IN = 0x01
TYPE_CNAME = 0x05
TTL = 60
def publish_cname(cname):
bus = dbus.SystemBus()
server = dbus.Interface(bus.get_object(avahi.DBUS_NAME,
avahi.DBUS_PATH_SERVER),
avahi.DBUS_INTERFACE_SERVER)
group = dbus.Interface(bus.get_object(avahi.DBUS_NAME,
server.EntryGroupNew()),
avahi.DBUS_INTERFACE_ENTRY_GROUP)
rdata = createRR(server.GetHostNameFqdn())
cname = encode_dns(cname)
group.AddRecord(avahi.IF_UNSPEC, avahi.PROTO_UNSPEC, dbus.UInt32(0),
cname, CLASS_IN, TYPE_CNAME, TTL, rdata)
group.Commit()
def encode_dns(name):
out = []
for part in name.split('.'):
if len(part) == 0: continue
out.append(ToASCII(part))
return '.'.join(out)
def createRR(name):
out = []
for part in name.split('.'):
if len(part) == 0: continue
out.append(chr(len(part)))
out.append(ToASCII(part))
out.append('\0')
return ''.join(out)
if __name__ == '__main__':
import time, sys, locale
for each in sys.argv[1:]:
name = unicode(each, locale.getpreferredencoding())
publish_cname(name)
try:
while 1: time.sleep(60)
except KeyboardInterrupt:
print "Exiting"
--
damjan
--
http://mail.python.org/mailman/listinfo/python-list
Commandline wrapper: help needed
I'm trying to write a simple commandline wrapper: a script that runs another program as a child and relays unbuffered stdin and stdout to/from the child process, possibly filtering it. The usefulness of such a program lies in the filtering stage, in a possible integration with readline, or in other interface enhancements. Still, I'd like to discuss with you the unfiltered, unembellished version, because I'm not satisfied with it and because I'm having some minor problems. Here's the script: #!/usr/bin/python import sys, os, thread def stdin_handler(child_stdin): while True: d = sys.stdin.read(1) if not d: break child_stdin.write(d) child_stdin.flush() child_stdin.close() def stdout_handler(child_stdout): while True: try: d = child_stdout.read(1) if not d: break sys.stdout.write(d) sys.stdout.flush() except KeyboardInterrupt: pass def wrap(cmd): child_stdin, child_stdout = os.popen2(cmd) thread.start_new_thread(stdin_handler, (child_stdin,)) stdout_handler(child_stdout) if __name__ == '__main__': wrap(sys.argv[1]) You invoke it passing a program name as the first argument (such as bash, python itself, sbcl, whatever) and then you interact with the child process as if this wrapper wasn't there. Ctrl-C and Ctrl-D work as expected, sending SIGINT (that the child program can catch) and closing stdin respectively. Problems: 1. I don't like the read(1) loops. I'd like to be able to read bigger chunks at a time, but I haven't found a way to do that while keeping the functionality intact. I have tried fidgeting with select() but I didn't get far. What I (think I) need is a non-blocking read(), but I'm not sure how to achieve that, at least with Python 2.4 on Linux. 2. Even this version sometimes has problems. For example, if you launch the wrapper around sbcl (a free Lisp interpreter/compiler) it mostly works (entering 1 gives 1, entering (+ 2 3) gives 5...) until you get to the debugger, for example by entering an undefined name. Now, when the debugger says "0: [ABORT] Exit debugger...", entering 0 should get you back to the "*" prompt--and indeed does, unless you are using my wrapper, in which case everything hangs, and the only solution is to terminate everything with Ctrl-\ or such. Any idea how to improve the script and solve this problem? Toby -- http://mail.python.org/mailman/listinfo/python-list
Re: Hi, I'm new to python
On Jan 27, 5:37 am, [EMAIL PROTECTED] wrote: > Hey Everyone > > Let me tell you all a little bit about my programming background so > you can get an idea of my capability, or lack of, dealing with p.l; > so far i've learned some visual basic when i was doing my a-levels > and thats about it lol. > > Basically i like the sound of python and its ease of use and would > like to know in depth more about it and its range of useage. Please > do tell me all you know, keeping in mind i am a n00b, so do be > gentle. :) > > Thanks > Millball54 Start Here http://www.python.org/doc/ There is a ton of documentation tailored to learners with differing skills. You might also want to pick up a book on Python. Be sure to read the docs, use Google, search this group for similar questions in the past before you post questions. They are great resources. If you have very basic questions, IRC (freenode has a Python channel), is a better option. When you post, make the question as specific as possible. Sometimes typing a good question itself gives you an answer. Ravi Teja. -- http://mail.python.org/mailman/listinfo/python-list
Dictionary inserts and threads
Hi all,
I'm thinking to speed up a process, I like to use multiple threads to
get data fractions from multiple servers and place those data fragments
into a local dictionary for further processing, the dictionary will look
like this:
self.dic = {'thread_a':dict(),
'thread_b':dict()}
The fragments will not overlap each other, since they will be
subdictionaries within the dictionary, though it would be possible that
multiple threads do something like this at the same time:
self.dic['thread_a'] = data_from_a()
and
self.dic['thread_b'] = data_from_b()
I assume that this is not a problem, but since assuming something gives
a lot of room for screw-ups I rather ask beforehand if I should except
all kinds of troubles when multiple threads update 'at the same time' a
dictionary or that I should lock the dictionary, for each update?
Thanks for your insights.
--
mph
--
http://mail.python.org/mailman/listinfo/python-list
Re: how to remove c++ comments from a cpp file?
Frank Potter wrote:
> r=re.compile(ur"//[^\r\n]+$", re.UNICODE|re.VERBOSE)
> f_new=r.sub(ur"",f)
>From the documentation:
re.MULTILINE
When specified [...] the pattern character "$" matches at the
end of the string and at the end of each line (immediately
preceding each newline). By default [...] "$" matches only at
the end of the string.
re.DOTALL
[...] without this flag, "." will match anything except a newline.
So a simple solution to your problem would be:
r = re.compile("//.*")
f_new = r.sub("", f)
Toby
--
http://mail.python.org/mailman/listinfo/python-list
Re: Dictionary inserts and threads
"Martin P. Hellwig" <[EMAIL PROTECTED]> writes: > I assume that this is not a problem, but since assuming something > gives a lot of room for screw-ups I rather ask beforehand if I should > except all kinds of troubles when multiple threads update 'at the same > time' a dictionary or that I should lock the dictionary, for each > update? Use a lock, or serialize the updates through a queue. -- http://mail.python.org/mailman/listinfo/python-list
[ANN] ftputil 2.2.1
ftputil 2.2.1 is now available from http://ftputil.sschwarzer.net/download . Changes since version 2.2 - This bugfix release checks and ignores status code 451 when FTPFiles are closed (thanks go to Alexander Holyapin). Upgrading is recommended. What is ftputil? ftputil is a high-level FTP client library for the Python programming language. ftputil implements a virtual file system for accessing FTP servers, that is, it can generate file-like objects for remote files. The library supports many functions similar to those in the os, os.path and shutil modules. ftputil has convenience functions for conditional uploads and downloads, and handles FTP clients and servers in different timezones. Read the documentation at http://ftputil.sschwarzer.net/trac/wiki/Documentation . License --- ftputil is Open Source software, released under the revised BSD license (see http://www.opensource.org/licenses/bsd-license.php ). Stefan -- Dr.-Ing. Stefan Schwarzer SSchwarzer.com - Softwareentwicklung für Technik und Wissenschaft http://sschwarzer.com http://ftputil.sschwarzer.net -- http://mail.python.org/mailman/listinfo/python-list
ANN: Plex 1.1.5
I have released a small update to Plex to fix the problem of assignment to None causing syntax warnings or errors in Python 2.3 and later. What is Plex? Plex is a Python module for lexical analysis that provides similar functionality to Lex and Flex. -- Greg -- http://mail.python.org/mailman/listinfo/python-list
ANN: Pyrex 0.9.5
Pyrex 0.9.5 is now available: http://www.cosc.canterbury.ac.nz/~greg/python/Pyrex/ Warning Elimination Extensive changes have been made in this version in an effort to eliminate most of the C compiler warnings that used to occur when compiling with distutils. There are also numerous other enhancements and bug fixes. See the CHANGES file in the distribution or on the web site for a full list. What is Pyrex? -- Pyrex is a language for writing Python extension modules. It lets you freely mix operations on Python and C data, with all Python reference counting and error checking handled automatically. -- http://mail.python.org/mailman/listinfo/python-list
IP address of webserver
How can I find server's IP address? >From console I can use ping, for example: C:\RobotP\cgi-bin>ping www.google.com Pinging www.google.com [209.85.129.147] with 32 bytes of data: Reply from 209.85.129.147: bytes=32 time=30ms TTL=244 Reply from 209.85.129.147: bytes=32 time=30ms TTL=244 .. .. So I know that www.google.com has 209.85.129.147 IP address. But how can I find it directly from Python script? Thanks for help J. -- http://mail.python.org/mailman/listinfo/python-list
distutils, sdist and tests
How do I get distutils to include my testing module in just the "sdist" distribution? My current call to setup() looks like:: distutils.core.setup( ... py_modules=['argparse'], ) If change this to:: distutils.core.setup( ... py_modules=['argparse', 'test_argparse'], ) then test_argparse.py gets included in the source distribution, but it also gets installed to site-packages like a normal module. I don't think I want that. If I change it to:: distutils.core.setup( ... py_modules=['argparse'], scripts=['test_argparse.py'], ) then test_argparse.py gets included in the source distribution, but it also gets installed in the Python scripts directory. I don't think I want that either. I want test_argparse.py to be available in the source distribution, but I don't think it should be included in the binary distributions. Or am I just being to picky? Do folks normally include their tests in the binary distributions? STeVe -- http://mail.python.org/mailman/listinfo/python-list
Re: IP address of webserver
"Johny" <[EMAIL PROTECTED]> writes:
> So I know that www.google.com has 209.85.129.147 IP address.
> But how can I find it directly from Python script?
>>> import socket
>>> print socket.gethostbyname('www.google.com')
66.102.7.147
>>>
--
http://mail.python.org/mailman/listinfo/python-list
Re: IP address of webserver
"Johny" <[EMAIL PROTECTED]> escribió en el mensaje
news:[EMAIL PROTECTED]
> How can I find server's IP address?
>>From console I can use ping, for example:
>
> C:\RobotP\cgi-bin>ping www.google.com
> Pinging www.google.com [209.85.129.147] with 32 bytes of data:
> [...]
> But how can I find it directly from Python script?
py> import socket
py> help(socket.gethostbyname)
Help on built-in function gethostbyname in module _socket:
gethostbyname(...)
gethostbyname(host) -> address
Return the IP address (a string of the form '255.255.255.255') for a
host.
py> socket.gethostbyname("www.google.com")
'209.85.165.147'
--
Gabriel Genellina
--
http://mail.python.org/mailman/listinfo/python-list
Re: extracting from web pages but got disordered words sometimes
On Jan 27, 5:18 am, "Frank Potter" <[EMAIL PROTECTED]> wrote:
> There are ten web pages I want to deal with.
> fromhttp://www.af.shejis.com/new_lw/html/125926.shtml
> to http://www.af.shejis.com/new_lw/html/125936.shtml
>
> Each of them uses the charset of Chinese "gb2312", and firefox
> displays all of them in the right form, that's readable Chinese.
>
> My job is, I get every page and extract the html title of it and
> dispaly the title on linux shell Termial.
>
> And, my problem is, to some page, I get human readable title(that's in
> Chinese), but to other pages, I got disordered word. Since each page
> has the same charset, I don't know why I can't get every title in the
> same way.
>
> Here's my python code, get_title.py :
>
> [CODE]
> #!/usr/bin/python
> import urllib2
> from BeautifulSoup import BeautifulSoup
>
> min_page=125926
> max_page=125936
>
> def make_page_url(page_index):
> return ur"".join([ur"http://www.af.shejis.com/new_lw/
> html/",str(page_index),ur".shtml"])
>
> def get_page_title(page_index):
> url=make_page_url(page_index)
> print "now getting: ", url
> user_agent='Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
> headers={'User-Agent':user_agent}
> req=urllib2.Request(url,None,headers)
> response=urllib2.urlopen(req)
> #print response.info()
> page=response.read()
>
> #extract tile by beautiful soup
> soup=BeautifulSoup(page)
> full_title=str(soup.html.head.title.string)
>
> #title is in the format of "title --title"
> #use this code to delete the "--" and the duplicate title
> title=full_title[full_title.rfind('-')+1::]
>
> return title
>
> for i in xrange(min_page,max_page):
> print get_page_title(i)
> [/CODE]
>
> Will somebody please help me out? Thanks in advance.
This pyparsing solution seems to extract what you were looking for,
but I don't know if this will render to Chinese or not.
-- Paul
from pyparsing import makeHTMLTags,SkipTo
import urllib
titleStart,titleEnd = makeHTMLTags("title")
scanExpr = titleStart + SkipTo("- -",include=True) +
SkipTo(titleEnd).setResultsName("titleChars") + titleEnd
def extractTitle(htmlSource):
titleSource = scanExpr.searchString(htmlSource, maxMatches=1)[0]
return titleSource.titleChars
for urlIndex in range(125926,125936+1):
url = "http://www.af.shejis.com/new_lw/html/%d.shtml"; % urlIndex
pg = urllib.urlopen(url)
html = pg.read()
pg.close()
print url,':',extractTitle(html)
Gives:
http://www.af.shejis.com/new_lw/html/125926.shtml : GSM±¾µØÍø×éÍø·½Ê½
http://www.af.shejis.com/new_lw/html/125927.shtml : GSM
±¾µØÍø×éÍø·½Ê½³õ̽
http://www.af.shejis.com/new_lw/html/125928.shtml : GSMµÄÊý¾ÝÒµÎñ
http://www.af.shejis.com/new_lw/html/125929.shtml :
GSMµÄÊý¾ÝÒµÎñºÍ³ÐÔØÄÜÁ¦
http://www.af.shejis.com/new_lw/html/125930.shtml : GSMµÄÍøÂçÑݽø-
´ÓGSMµ½GPRSµ½3G £¨¸½Í¼£©
http://www.af.shejis.com/new_lw/html/125931.shtml : GSM¶ÌÏûÏ
¢ÒµÎñÔÚË®Çé×Ô¶¯²â±¨ÏµÍ³ÖеÄÓ¦ÓìØ
http://www.af.shejis.com/new_lw/html/125932.shtml : £Ç£Ó
£Í½»»»ÏµÍ³µÄÍøÂçÓÅ»¯
http://www.af.shejis.com/new_lw/html/125933.shtml : GSMÇл»µô»°µÄ·ÖÎö¼
°½â¾ö°ì·¨
http://www.af.shejis.com/new_lw/html/125934.shtml : GSMÊÖ»ú²¦½ÐÊл°Ä
£¿é¾ÖÓû§¹ÊÕÏµÄÆÊÎö
http://www.af.shejis.com/new_lw/html/125935.shtml :
GSMÊÖ»úµ½WCDMAÖն˵ÄÑݱä
http://www.af.shejis.com/new_lw/html/125936.shtml : GSMÊÖ»úµÄάÐÞ·½·¨
--
http://mail.python.org/mailman/listinfo/python-list
Re: extracting from web pages but got disordered words sometimes
After looking at the pyparsing results, I think I see the problem with
your original code. You are selecting only the characters after the
rightmost "-" character, but you really want to select everything to
the right of "- -". In some of the titles, the encoded Chinese
includes a "-" character, so you are chopping off everything before
that.
Try changing your code to:
title=full_title.split("- -")[1]
I think then your original program will work.
-- Paul
--
http://mail.python.org/mailman/listinfo/python-list
Crunchy 0.8 release
Version 0.8 of Crunchy has been released. It is available on http://code.google.com/p/crunchy/ Crunchy, the Interactive Python Tutorial Maker, is an application that transforms an ordinary html-based Python tutorial into an interactive session within a web browser. Currently, only Firefox is supported. Crunchy is developed and tested on Windows XP and Ubuntu Dapper Drake, but should work on any suitable windows or UNIX system. Three major improvements have been made since version 0.7 had been released. 1. New editor Instead of a simple html textarea, Crunchy now gives the option of using a "real" editor, namely EditArea (http://www.cdolivet.net/editarea/). EditArea support syntax coloring and allows loading and saving local Python files among other features. Within Crunchy, it is set up so that the tab key is translated into 4 spaces. 2. Language support Crunchy now supports English and French, through the use of ".po" files. When running Python code, some error messages have been adapted/translated. EditArea itself support more languages (currently: Danish, Dutch, English, French, German, Italian, Japanese, Polish, Portuguese). 3. Graphical tutorial converter. Crunchy uses some supplementary markup to transform html files into interactive tutorials. Whereas previous versions required a tutorial maker to edit an html file "by hand", version 0.8 includes a tutorial editor: with a few clicks, you can easily add to an html file the chosen interactive elements and options for Crunchy. In addition to the above major improvements, the code has been refactored significantly and a number of small bug fixes have been made. Crunchy will be demonstrated at the upcoming Pycon 2007. André Roberge and Johannes Woolard. -- http://mail.python.org/mailman/listinfo/python-list
Re: distutils, sdist and tests
Steven Bethard wrote: > How do I get distutils to include my testing module in just the "sdist" > distribution? Use a MANIFEST. http://docs.python.org/dist/source-dist.html > I want test_argparse.py to be available in the source distribution, but > I don't think it should be included in the binary distributions. > > Or am I just being to picky? Do folks normally include their tests in > the binary distributions? Some do, but only when they are packages and can thus hide.the.tests . -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco -- http://mail.python.org/mailman/listinfo/python-list
looking for ppp dialing tutorial / resources
Hi, I need to implement ppp client connection in my program ... found chestnut dialer so far ... any other resource in mind ? Thanks hg -- http://mail.python.org/mailman/listinfo/python-list
Re: Hi, I'm new to python
I would definitely suggest checking out the documentation at http:// www.python.org/doc/. Also, you can check out the free book Dive into Python at http://www.diveintopython.org. It provides a great overview starting at the very beginning. I found it great and hope to buy it soon to support the author. Python is considered a general-purpose language (so is Perl by the way.) It can handle anything from processing text, to running as an application server (check out http://www.zope.com.) You can also use pieces of it for web programming. In fact, if you've heard of Ruby on Rails, then you can see a similar Python project called TurboGears at http://www.turbogears.com. If you only need a web framework, then you can also check out Django (http://www.djangoproject.com) and many other projects designed for getting a web-based application up and running quickly. Not to leave you with the impression that it's really only suited for web stuff, there is also Pygame (http://www.pygame.com), a library and bindings to SDL so you can write your own games. I am currently learning Pygame with OpenGL and writing a simple clone of SpaceWars. I've also written a Jabber bot in Python for use where I used to work. You can use Python for systems automation as well. I wrote a small applet that opened SSH connections to every server in a list and then sent all the text you typed into a single box to all servers at the same time. I'm currently learning how to use Python with osascript to control applications in Mac OS X and have dabbled a little with the win32com stuff to have Python control some aspects of Windows. As you can see, it's an extremely versatile language and is really only limited by your imagination. There are some things that it doesn't do so well, but for the most part, those things have solutions. For example, Python is typically slower than other languages when you must iterate over something many times. For example, in game programming, to iterate over the entire list of objects in the world to update their positions or draw them. Many times things like this can be moved into C libraries to make then run faster. I myself haven't had many problems with this at all. In fact, none of my iteration code is in C for my game. Well, that's enough rambling for me. I've turned this post into a commercial for Python. I hope that I've left you with enough ideas to get started in the language. -- Jerry H -- http://mail.python.org/mailman/listinfo/python-list
Re: stop script w/o exiting interpreter
Please note that this post has subject "stop script w/o exiting interpreter". The object is to work at the *interactive* interpreter, without leaving it. Here is an example goal: start a Python shell, execfile a script, exit the script at line 25, and return to the Python shell. E.g., some languages include a ``stop`` statement that you can put on line 25. Ideally, I would like the equivalent of this. Solutions suggested in this thread included: - raise SystemExit but this will exit the interpreter - sys.exit() but this will exit the interpreter - use pdb's set_trace() but I think that answers a different question. (However it does work to raise BdbQuit, but I'd like something less messy.) - wrap all code in functions and test the functions but this does not apply to my current use case - use PyScripter but this is overkill for my very simple goal Note that I can just put the undefined name ``stop`` on any line I want, and the script will stop execucting at that line and will return to the interactive interpreter, as I wish. It is just that it returns with an error message, and I'd like to avoid that. Thanks, Alan Isaac -- http://mail.python.org/mailman/listinfo/python-list
Re: assertions to validate function parameters
On Sat, 27 Jan 2007 06:58:04 -0800, Carl Banks wrote: >> I find that when I detect invalid parameters overtly, I spend less time >> debugging. > > If it helps go ahead an use them. The world won't end if you use an > assertion in a less than ideal situation. And, after all, if someone > doesn't like it they can shut them off. Is there any way to have finer control of assertions than just passing -O to the Python interpreter? Suppose I want to switch them off for certain modules but not others, am I out of luck? -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
Re: stop script w/o exiting interpreter
"Alan Isaac" <[EMAIL PROTECTED]> escribió en el mensaje news:[EMAIL PROTECTED] > Please note that this post has subject > "stop script w/o exiting interpreter". > Note that I can just put the undefined name ``stop`` on any line > I want, and the script will stop execucting at that line and will > return to the interactive interpreter, as I wish. It is just that it > returns with an error message, and I'd like to avoid that. If this is just for playing inside the interpreter, just ignore the exception. Or comment out all lines from 25 to end of script, some editors (including IDLE) have support for that. Or use a giant """ string """ if you can. If you invoke your script with `python -i your_script.py` Python will show the interpreter prompt when your script finishes (either normally or raising an exception). -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: Do I need Python to run Blender correctly?
"John Nagle" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > AKA gray asphalt wrote: >> I downloaded Blender but there was no link for python. Am I on the right >> track? > >Blender doesn't require Python, but if you have Python, you can > write plug-ins for Blender. Get "The Blender Book"; otherwise > you'll never figure Blender out. > > John Nagle Will do. Thanks. -- http://mail.python.org/mailman/listinfo/python-list
Re: Do I need Python to run Blender correctly?
"John Nagle" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > AKA gray asphalt wrote: >> I downloaded Blender but there was no link for python. Am I on the right >> track? > >Blender doesn't require Python, but if you have Python, you can > write plug-ins for Blender. Get "The Blender Book"; otherwise > you'll never figure Blender out. > > John Nagle I'm thinking about not upgrading "Strata 3D" because it still doesn't export textures with obj files and it just created an undo of more than one action, believe it or not... Am I expectiong too much of a $400+ program, to export textures with obj files? Does Blender do this? I see the BBook on Amazon for $30. That's probably my best bet, no? -- http://mail.python.org/mailman/listinfo/python-list
Re: Do I need Python to run Blender correctly?
AKA gray asphalt wrote: > "John Nagle" <[EMAIL PROTECTED]> wrote in message > news:[EMAIL PROTECTED] > >>AKA gray asphalt wrote: >> >>>I downloaded Blender but there was no link for python. Am I on the right >>>track? >> >> Blender doesn't require Python, but if you have Python, you can >>write plug-ins for Blender. Get "The Blender Book"; otherwise >>you'll never figure Blender out. >> >>John Nagle > > > I'm thinking about not upgrading "Strata 3D" because it still doesn't export > textures with obj files and it just created an undo of more than one action, > believe it or not... Am I expectiong too much of a $400+ program, to export > textures with obj files? Does Blender do this? I see the BBook on Amazon for > $30. That's probably my best bet, no? Blender has considerable power, but ease of use is a problem. The hotkey listing in the manual is 29 pages. -- http://mail.python.org/mailman/listinfo/python-list
set update in 2.5
Hello, In moving from 2.4 to 2.5 I find that some of my unit tests are now failing. I've worked out that the problem relates to the set update method. In 2.4 I could update a set with an iterable type derived from dict as the argument. I now find that the set is updated with the hash values of the items in my iterable, rather than the items themselves. Converting to a list first gets round the problem. My iterable type has the same API as 'set' but requires items to have hashable 'uid' attributes, so they can also be looked up by uid. I hope this, and the fact that this worked fine in 2.4 will be enough to track down the issue without me having to paste reams of code (other than the following, pasted from IDLE). Any ideas? Cheers. Duncan >>> from graphItems import Node >>> from keyed_sets import KeyedSet >>> n = Node(1) >>> n.uid 1 >>> k = KeyedSet([n]) >>> k KeyedSet([1]) >>> type(iter(k).next()) >>> type(k[1]) >>> s = set() >>> s.update(list(k)) >>> type(iter(s).next()) >>> s = set() >>> s.update(k) >>> type(iter(s).next()) >>> s = set() >>> s.add(n) >>> type(iter(s).next()) >>> hash(n) 1 >>> -- http://mail.python.org/mailman/listinfo/python-list
Re: extracting from web pages but got disordered words sometimes
Thank you, I tried again and I figured it out.
That's something with beautiful soup, I worked with it a year ago also
dealing with Chinese html pages and nothing error happened. I read the
old code and I find the difference. Change the page to unicode before
feeding to beautiful soup, then everything will be OK.
On Jan 28, 3:26 am, "Paul McGuire" <[EMAIL PROTECTED]> wrote:
> After looking at the pyparsing results, I think I see the problem with
> your original code. You are selecting only the characters after the
> rightmost "-" character, but you really want to select everything to
> the right of "- -". In some of the titles, the encoded Chinese
> includes a "-" character, so you are chopping off everything before
> that.
>
> Try changing your code to:
> title=full_title.split("- -")[1]
>
> I think then your original program will work.
>
> -- Paul
--
http://mail.python.org/mailman/listinfo/python-list
Re: distutils, sdist and tests
Robert Kern wrote: > Steven Bethard wrote: >> How do I get distutils to include my testing module in just the "sdist" >> distribution? > > Use a MANIFEST. > > http://docs.python.org/dist/source-dist.html > >> I want test_argparse.py to be available in the source distribution, but >> I don't think it should be included in the binary distributions. Using a MANIFEST appears to do the same thing as putting "test_argparse" into py_modules -- that is, it puts "test_argparse.py" into both "sdist" and "bdist" distributions. In "bdist" distributions it gets installed to the site-packages directory like any other module. STeVe -- http://mail.python.org/mailman/listinfo/python-list
Re: distutils, sdist and tests
Steven Bethard wrote: > Robert Kern wrote: >> Steven Bethard wrote: >>> How do I get distutils to include my testing module in just the "sdist" >>> distribution? >> Use a MANIFEST. >> >> http://docs.python.org/dist/source-dist.html Also, I just noted this tidbit: """If you don't supply an explicit list of files (or instructions on how to generate one), the sdist command puts a minimal default set into the source distribution: ... * anything that looks like a test script: test/test*.py (currently, the Distutils don't do anything with test scripts except include them in source distributions, but in the future there will be a standard for testing Python module distributions) ... """ So you can just stick test_argparse.py into a test/ directory. Having tested this, it appears to work (see below). >>> I want test_argparse.py to be available in the source distribution, but >>> I don't think it should be included in the binary distributions. > > Using a MANIFEST appears to do the same thing as putting "test_argparse" > into py_modules -- that is, it puts "test_argparse.py" into both "sdist" > and "bdist" distributions. In "bdist" distributions it gets installed to > the site-packages directory like any other module. Are you sure that you don't have changes left over in your setup.py when you tested that? Also check that you clear out your build/ directory every time. I think the bdist_* commands tend to just copy whatever is in the appropriate build/lib.*/ directory even though you've changed how those files should be generated. This is what I get with setup.py unmodified. The only thing I added was MANIFEST.in and an empty test_argparse.py file. [argparse]$ ls MANIFEST.in PKG-INFO README.txt argparse.py setup.py test_argparse.py [argparse]$ cat MANIFEST.in include PKG-INFO include *.txt include *.py [argparse]$ python setup.py bdist_dumb running bdist_dumb running build running build_py creating build creating build/lib copying argparse.py -> build/lib installing to build/bdist.macosx-10.3-fat/dumb running install running install_lib creating build/bdist.macosx-10.3-fat creating build/bdist.macosx-10.3-fat/dumb creating build/bdist.macosx-10.3-fat/dumb/Library creating build/bdist.macosx-10.3-fat/dumb/Library/Frameworks creating build/bdist.macosx-10.3-fat/dumb/Library/Frameworks/Python.framework creating build/bdist.macosx-10.3-fat/dumb/Library/Frameworks/Python.framework/Versions creating build/bdist.macosx-10.3-fat/dumb/Library/Frameworks/Python.framework/Versions/2.5 creating build/bdist.macosx-10.3-fat/dumb/Library/Frameworks/Python.framework/Versions/2.5/lib creating build/bdist.macosx-10.3-fat/dumb/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5 creating build/bdist.macosx-10.3-fat/dumb/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages copying build/lib/argparse.py -> build/bdist.macosx-10.3-fat/dumb/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages byte-compiling build/bdist.macosx-10.3-fat/dumb/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/argparse.py to argparse.pyc running install_egg_info Writing build/bdist.macosx-10.3-fat/dumb/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/argparse-0.5.0-py2.5.egg-info creating /Users/rkern/src/argparse/dist tar -cf /Users/rkern/src/argparse/dist/argparse-0.5.0.macosx-10.3-fat.tar . gzip -f9 /Users/rkern/src/argparse/dist/argparse-0.5.0.macosx-10.3-fat.tar removing 'build/bdist.macosx-10.3-fat/dumb' (and everything under it) [argparse]$ tar ztf dist/argparse-0.5.0.macosx-10.3-fat.tar.gz ./ ./Library/ ./Library/Frameworks/ ./Library/Frameworks/Python.framework/ ./Library/Frameworks/Python.framework/Versions/ ./Library/Frameworks/Python.framework/Versions/2.5/ ./Library/Frameworks/Python.framework/Versions/2.5/lib/ ./Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/ ./Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/ ./Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/argparse-0.5.0-py2.5.egg-info ./Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/argparse.py ./Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/argparse.pyc [argparse]$ python setup.py sdist running sdist reading manifest template 'MANIFEST.in' writing manifest file 'MANIFEST' creating argparse-0.5.0 making hard links in argparse-0.5.0... hard linking PKG-INFO -> argparse-0.5.0 hard linking README.txt -> argparse-0.5.0 hard linking argparse.py -> argparse-0.5.0 hard linking setup.py -> argparse-0.5.0 hard linking test_argparse.py -> argparse-0.5.0 tar -cf dist/argparse-0.5.0.tar argparse-0.5.0 gzip -f9 dist/argparse-0.5.0.tar removing 'argparse-0.5.0' (and everything under it) [argparse]$ tar ztf dist/argparse-0.5.0.tar.gz argparse-0.5.0/ argparse-0.5.0/argparse.py argparse-0.5.0/PKG-INFO argparse-0.5.0/
Re: assertions to validate function parameters
On Jan 27, 6:51 pm, Steven D'Aprano <[EMAIL PROTECTED]> wrote: > On Sat, 27 Jan 2007 06:58:04 -0800, Carl Banks wrote: > >> I find that when I detect invalid parameters overtly, I spend less time > >> debugging. > > > If it helps go ahead an use them. The world won't end if you use an > > assertion in a less than ideal situation. And, after all, if someone > > doesn't like it they can shut them off. > > Is there any way to have finer control of assertions than just passing -O > to the Python interpreter? Suppose I want to switch them off for certain > modules but not others, am I out of luck? Please relax. The suggestion that one could shut them off was tongue in cheek. Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
Re: assertions to validate function parameters
On Sat, 27 Jan 2007 19:29:06 -0800, Carl Banks wrote: > On Jan 27, 6:51 pm, Steven D'Aprano > <[EMAIL PROTECTED]> wrote: >> On Sat, 27 Jan 2007 06:58:04 -0800, Carl Banks wrote: >> >> I find that when I detect invalid parameters overtly, I spend less time >> >> debugging. >> >> > If it helps go ahead an use them. The world won't end if you use an >> > assertion in a less than ideal situation. And, after all, if someone >> > doesn't like it they can shut them off. >> >> Is there any way to have finer control of assertions than just passing -O >> to the Python interpreter? Suppose I want to switch them off for certain >> modules but not others, am I out of luck? > > Please relax. The suggestion that one could shut them off was tongue > in cheek. (a) I am relaxed; (b) One can shut down assertions, and it isn't a joke, it is a feature; (c) I meant my question seriously, I think it would be a good thing. -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
More Python screencasts (Google videos)
Here're three sample 3-6 min videos showing off Python to math teachers thinking about using a computer language instead of just calculators: http://controlroom.blogspot.com/2007/01/python-for-math-teachers.html Higher resolution versions are available to teachers enrolling in our program. Kirby -- http://mail.python.org/mailman/listinfo/python-list
log parser design question
I need to parse a log file using python and I need some advice/wisdom
on the best way to go about it:
The log file entries will consist of something like this:
ID=8688 IID=98889998 execute begin - 01.21.2007 status enabled
locked working.lock
status running
status complete
ID=9009 IID=87234785 execute wait - 01.21.2007 status wait
waiting to lock
status wait
waiting on ID=8688
and so on...
I need to be able to group these entries together, index them by ID
and IID, and search the context of each entry and if a certain status
if found (such as wait), then be able to return the ID or IID
(depending...) of that entry.
So I was considering parsing them to this effect:
in a dictionary, where the key is a tuple, and the value is a list:
{('ID=8688', 'IID=98889998'): ['ID=8688 IID=98889998 execute begin -
01.21.2007 status enabled', 'locked working.lock', 'status running',
'status complete']}
I am keeping the full text of each entry in the list so that I can
recreate them for display if need be.
I am fairly new to python, so could anyone offer any advice here
before I get too far and discover a fatal flaw that you might see
coming a mile away?
would I, with this design, be able to, for example, search each list
for "waiting on ID=8688", and when found, be able to associate that
value with one of the elements of it's key "ID=9009" ? or is this
approached flawed? I'm assuming there is a better way, but I need
some advice...
I appreciate any thoughts.
Thanks.
--
http://mail.python.org/mailman/listinfo/python-list
ANN: Plex 1.1.5 (Repost)
(Reposting to supply the URL that I forgot to include.:-() I have released a small update to Plex to fix the problem of assignment to None causing syntax warnings or errors in Python 2.3 and later. http://www.cosc.canterbury.ac.nz/greg.ewing/python/Plex What is Plex? Plex is a Python module for lexical analysis that provides similar functionality to Lex and Flex. -- Greg -- http://mail.python.org/mailman/listinfo/python-list
Re: distutils, sdist and tests
Robert Kern wrote: > Steven Bethard wrote: >> Robert Kern wrote: >>> Steven Bethard wrote: How do I get distutils to include my testing module in just the "sdist" distribution? >>> Use a MANIFEST. >>> >>> http://docs.python.org/dist/source-dist.html > > Also, I just noted this tidbit: > > """If you don't supply an explicit list of files (or instructions on how to > generate one), the sdist command puts a minimal default set into the source > distribution: > ... > * anything that looks like a test script: test/test*.py (currently, the > Distutils don't do anything with test scripts except include them in source > distributions, but in the future there will be a standard for testing Python > module distributions) > ... > """ > > So you can just stick test_argparse.py into a test/ directory. Having tested > this, it appears to work (see below). Yeah, I was trying to avoid having to put it in a test/ directory. When they're in the same directory, I can just run test_argparse.py and it tests the local one instead of the one I have installed in site-packages. When it's in a test/ directory, running test/test_argparse.py tests the one in site-packages. I did try putting test_argparse.py in a test/ directory though, and it doesn't seem to solve the problem -- test_argparse.py gets put into site-packages with the "bdist" command: > python setup.py sdist running sdist warning: sdist: manifest template 'MANIFEST.in' does not exist (using default file list) writing manifest file 'MANIFEST' creating argparse-0.6.0 creating argparse-0.6.0\test copying files to argparse-0.6.0... copying README.txt -> argparse-0.6.0 copying argparse.py -> argparse-0.6.0 copying setup.py -> argparse-0.6.0 copying test\test_argparse.py -> argparse-0.6.0\test creating 'dist\argparse-0.6.0.zip' and adding 'argparse-0.6.0' to it adding 'argparse-0.6.0\argparse.py' adding 'argparse-0.6.0\PKG-INFO' adding 'argparse-0.6.0\README.txt' adding 'argparse-0.6.0\setup.py' adding 'argparse-0.6.0\test\test_argparse.py' removing 'argparse-0.6.0' (and everything under it) > python setup.py bdist_dumb running bdist_dumb running build running build_py installing to build\bdist.win32\dumb running install running install_lib creating build\bdist.win32\dumb creating build\bdist.win32\dumb\Program Files creating build\bdist.win32\dumb\Program Files\Python creating build\bdist.win32\dumb\Program Files\Python\Lib creating build\bdist.win32\dumb\Program Files\Python\Lib\site-packages copying build\lib\argparse.py -> build\bdist.win32\dumb\Program Files\Python\Lib\site-packages copying build\lib\test_argparse.py -> build\bdist.win32\dumb\Program Files\Python\Lib\site-packages byte-compiling build\bdist.win32\dumb\Program Files\Python\Lib\site-packages\argparse.py to argparse.pyc byte-compiling build\bdist.win32\dumb\Program Files\Python\Lib\site-packages\test_argparse.py to test_argparse.pyc running install_egg_info Writing build\bdist.win32\dumb\Program Files\Python\Lib\site-packages\argparse-0.6.0-py2.5.egg-info creating 'dist\argparse-0.6.0.win32.zip' and adding '.' to it adding 'Program Files\Python\Lib\site-packages\argparse-0.6.0-py2.5.egg-info' adding 'Program Files\Python\Lib\site-packages\argparse.py' adding 'Program Files\Python\Lib\site-packages\argparse.pyc' adding 'Program Files\Python\Lib\site-packages\test_argparse.py' adding 'Program Files\Python\Lib\site-packages\test_argparse.pyc' removing 'build\bdist.win32\dumb' (and everything under it) >> Using a MANIFEST appears to do the same thing as putting "test_argparse" >> into py_modules -- that is, it puts "test_argparse.py" into both "sdist" >> and "bdist" distributions. In "bdist" distributions it gets installed to >> the site-packages directory like any other module. > > Are you sure that you don't have changes left over in your setup.py when you > tested that? Yep. (Though I still cleared everything out and tried it again.) Here's what I got using an unmodified setup.py and the MANIFEST.in you suggested. Note that the "bdist" version is putting test_argparse.py into site-packages. > type MANIFEST.in include PKG-INFO include *.txt include *.py > python setup.py sdist running sdist reading manifest template 'MANIFEST.in' warning: no files found matching 'PKG-INFO' writing manifest file 'MANIFEST' creating argparse-0.6.0 copying files to argparse-0.6.0... copying LICENSE.txt -> argparse-0.6.0 copying README.txt -> argparse-0.6.0 copying argparse.py -> argparse-0.6.0 copying setup.py -> argparse-0.6.0 copying test_argparse.py -> argparse-0.6.0 creating 'dist\argparse-0.6.0.zip' and adding 'argparse-0.6.0' to it adding 'argparse-0.6.0\argparse.py' adding 'argparse-0.6.0\LICENSE.txt' adding 'argparse-0.6.0\PKG-INFO' adding 'argparse-0.6.0\README.txt' adding 'argparse-0.6.0\setup.py' adding 'argparse-0.6.0\test_argparse.py' removing 'argparse-0.6.0' (and everything under it) > python setup.py bdist_dumb running bdist_dumb running build running bui
Re: distutils, sdist and tests
Steven Bethard wrote: > Robert Kern wrote: >> Are you sure that you don't have changes left over in your setup.py when you >> tested that? > > Yep. (Though I still cleared everything out and tried it again.) > Here's what I got using an unmodified setup.py and the MANIFEST.in you > suggested. Note that the "bdist" version is putting test_argparse.py > into site-packages. > > python setup.py bdist_dumb > running bdist_dumb > running build > running build_py > installing to build\bdist.win32\dumb > running install > running install_lib Are you sure that you removed the build/ directory? Because if it wasn't there, distutils would say that it was creating one: [argparse]$ python setup.py bdist_dumb running bdist_dumb running build running build_py creating build creating build/lib copying argparse.py -> build/lib installing to build/bdist.macosx-10.3-fat/dumb running install running install_lib -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco -- http://mail.python.org/mailman/listinfo/python-list
Re: distutils, sdist and tests
Robert Kern wrote: > Steven Bethard wrote: >> Robert Kern wrote: > >>> Are you sure that you don't have changes left over in your setup.py when you >>> tested that? >> Yep. (Though I still cleared everything out and tried it again.) >> Here's what I got using an unmodified setup.py and the MANIFEST.in you >> suggested. Note that the "bdist" version is putting test_argparse.py >> into site-packages. > >> > python setup.py bdist_dumb >> running bdist_dumb >> running build >> running build_py >> installing to build\bdist.win32\dumb >> running install >> running install_lib > > Are you sure that you removed the build/ directory? Ahh thanks. Sorry I thought I was supposed to remove the old stuff from dist/ not from build/. Yes, I get the same behavior as you do when I remove build/. Sorry for the confusion! Steve -- http://mail.python.org/mailman/listinfo/python-list
Re: distutils, sdist and tests
Robert Kern wrote: > Steven Bethard wrote: >> How do I get distutils to include my testing module in just the "sdist" >> distribution? > > Use a MANIFEST. Thanks again to Robert Kern for all the help. For the record, in the end all I did was add a MANIFEST.in file with the single line: include test_argparse.py and "test_argparse.py" got included in the source distribution and left out of the binary distributions. It's a pity there's no way to specify something this simple in the setup.py file, but since I'm not offering to maintain distutils, I guess I don't really have a right to complain. ;-) STeVe -- http://mail.python.org/mailman/listinfo/python-list
Re: subclassing pyrex extension types in python
Nitin wrote: > I am trying to subclass an extension type in Python and add attributes > to the new class but I keep getting errors. > > cdef class Spam: > > cdef int amount > > def __new__(self): > self.amount = 0 > > I get an error "TypeError: 'name2' is an > invalid keyword argument for this function" Arguments to the constructor of a class are passed to its __new__ method as well as its __init__ method, so if you want to subclass it in Python, you need to allow for that by defining it as def __new__(self, *args, **kwds): ... Without that, your Python subclass would have to define its own __new__ method which accepts the extra args and strips them out, e.g. class MySpam(Spam): def __new__(cls, name1=None, name2=None): return Spam.__new__(cls) -- Greg -- http://mail.python.org/mailman/listinfo/python-list
import from future
what are the things that we can do with import from future usage.i heard its very interesting..thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: import from future
In <[EMAIL PROTECTED]>, lee wrote: > what are the things that we can do with import from future usage.i > heard its very interesting..thanks Here's how to find out yourself (done with a 2.4 release): In [2]: import __future__ In [3]: dir(__future__) Out[3]: ['CO_FUTURE_DIVISION', 'CO_GENERATOR_ALLOWED', 'CO_NESTED', '_Feature', '__all__', '__builtins__', '__doc__', '__file__', '__name__', 'all_feature_names', 'division', 'generators', 'nested_scopes'] In [4]: __future__.all_feature_names Out[4]: ['nested_scopes', 'generators', 'division'] In [5]: __future__.division Out[5]: _Feature((2, 2, 0, 'alpha', 2), (3, 0, 0, 'alpha', 0), 8192) In [6]: help(__future__) Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
