Re: Python 3 dict question
dmitrey writes: > hi all, > suppose I have Python dict myDict and I know it's not empty. > I have to get any (key, value) pair from the dict (no matter which > one) and perform some operation. > In Python 2 I used mere > key, val = myDict.items()[0] > but in Python 3 myDict.items() return iterator. > Of course, I could use > for key, val in myDict.items(): >do_something >break > but maybe there is any better way? key, val = next(iter(myDict.items())) http://docs.python.org/py3k/library/stdtypes.html#dictionary-view-objects HTH, Rob -- http://mail.python.org/mailman/listinfo/python-list
Re: Running a command line program and reading the result as it runs
Ian Simcock writes:
> Greetings all.
>
> I'm using Python 2.7 under Windows and am trying to run a command line
> program and process the programs output as it is running. A number of
> web searches have indicated that the following code would work.
>
> import subprocess
>
> p = subprocess.Popen("D:\Python\Python27\Scripts\pip.exe list -o",
> stdout=subprocess.PIPE,
> stderr=subprocess.STDOUT,
> bufsize=1,
> universal_newlines=True,
> shell=False)
> for line in p.stdout:
> print line
>
> When I use this code I can see that the Popen works, any code between
> the Popen and the for will run straight away, but as soon as it gets
> to the for and tries to read p.stdout the code blocks until the
> command line program completes, then all of the lines are returned.
>
> Does anyone know how to get the results of the program without it blocking?
When file object is used in a for loop it works like an iterator
and then it uses a hidden read-ahead buffer.
It might cause this kind of blocking.
You can read more details here (description of method ``next``):
http://docs.python.org/lib/bltin-file-objects.html
So basically non-blocking loop might look like this:
while True:
line = p.stdout.readline()
if not line: break
print line
HTH,
Rob
--
http://mail.python.org/mailman/listinfo/python-list
Re: WSAStartup failed: error code 10107
[EMAIL PROTECTED] wrote: > Trying to get moinmoin wiki working on Windows 2000 using IIS and > python. I get the following error when trying to view the start page > after insalling moinmoin and python - key error seems to be at the end > related to socket.py (ImportError: WSAStartup failed: error code > 10107). 10107 is "A system call that should never fail has > failed"...which isn't very helpful. Any ideas what the problem may be? > > Thanks, > Ralph > > CGI Error > The specified CGI application misbehaved by not returning a complete > set of HTTP headers. The headers it did return are: > > > Traceback (most recent call last): > File "C:\Moin\wiki\moin.cgi", line 40, in ? > from MoinMoin.request import RequestCGI > File "C:\Moin\Lib\site-packages\MoinMoin\request.py", line 10, in ? > import os, re, time, sys, cgi, StringIO > File "C:\Python\lib\cgi.py", line 39, in ? > import urllib > File "C:\Python\lib\urllib.py", line 26, in ? > import socket > File "C:\Python\lib\socket.py", line 44, in ? > import _socket > ImportError: WSAStartup failed: error code 10107 I'm not sure if that helps but check if you have multiple winsock.dll files on the machine. Maybe in the system path you have some old winsock.dll. regards, Rob -- http://mail.python.org/mailman/listinfo/python-list
Re: WSAStartup failed: error code 10107
[EMAIL PROTECTED] wrote: > Thanks for the suggestion Rob. All I can find are 2 copies of > winsock.dll: > c:/WINNT/system32/winsock.dll > c:/WINNT/system32/dllcache/winsock.dll > They're both the same version 3.10.0.13 > > I assume it's ok to have a copy in the dllcach directory and that's not > a source of the problem? > > Does python require a specific version of winsock.dll? The OS is > windows 2000 5.00.2195 Service Pack 4. No, python doesn't require specific version of winsock.dll. On my XP I have: winsock.dll - 3.10.0.103 ws2_32.dll - 5.1.2600.2180 wsock32.dll - 5.1.2600.2180 and everything works fine. No other idea, but I'm almost sure that problem is on the OS side not on python side. Regards, Rob -- http://mail.python.org/mailman/listinfo/python-list
Re: problem with regex
abcd wrote:
> I have a regex: '[A-Za-z]:\\([^/:\*\?"<>\|])*'
>
> when I do, re.compile('[A-Za-z]:\\([^/:\*\?"<>\|])*') ...I get
>
> sre_constants.error: unbalanced parenthesis
>
> do i need to escape something else? i see that i have matching
> parenthesis.
You should use raw string:
re.compile(r'[A-Za-z]:\\([^/:\*\?"<>\|])*')
Regards,
Rob
--
http://mail.python.org/mailman/listinfo/python-list
Re: problem with regex
abcd wrote:
> not sure why this passes:
>
>
> >>> regex = r'[A-Za-z]:\\([^/:\*\?"<>\|])*'
> >>> p = re.compile(regex)
> >>> p.match('c:\\test')
> <_sre.SRE_Match object at 0x009D77E0>
> >>> p.match('c:\\test?:/')
> <_sre.SRE_Match object at 0x009D7720>
> >>>
>
> the last example shouldnt give a match
If you want to learn RE I suggest to use great tool redemo.py (tk app).
Then you can play with regular expressions to find the result
you are looking for.
It can be found in Python 2.4 in Tools\Scripts.
Regards,
Rob
--
http://mail.python.org/mailman/listinfo/python-list
Re: import a user created python file as module
> How and what should I do to import file1.py into file1-dir1.py ? Please > give me some references to the tutorial topic which I can study as > well. And some reference: http://docs.python.org/tut/node8.html Regards, Rob -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie help - test for data type
> This is my function:
> selecteddeptcodes = context.REQUEST.DEPTCODE
> currentstatus = context.REQUEST.STATUS
>
> if currentstatus == 'pending':
> for dptcd in selecteddeptcodes:
>context.changetolive(DEPTCODE=dptcd)
> if currentstatus == 'old':
> for dptcd in selecteddeptcodes:
>context.changetopending(DEPTCODE=dptcd)
> return context.pub_dept_form(context, context.REQUEST, message='Updated
> Status')
>
> The argument in question is selecteddeptcodes.
You can use isinstance or function like that:
>>> def list_from_string(s):
... try:
... s + ''
... return [s]
... except:
... return s
and then:
>>> def f(selecteddeptcodes):
... if selecteddeptcodes is None: return
... selecteddeptcodes = list_from_string(selecteddeptcodes)
... for dptcd in selecteddeptcodes: print dptcd
...
>>> f(['aaa', 'bbb'])
aaa
bbb
>>> f(['aaa'])
aaa
>>> f('aaa')
aaa
>>> f(None)
>>>
Regards,
Rob
--
http://mail.python.org/mailman/listinfo/python-list
Re: import help
placid wrote:
> Hi all,
>
> How do i import a module that has an hypen/dash (-) in its name ? I get
> a SytaxError exception
You can use function __import__.
>>> print open("-test.py").read()
def fun2():
return "Hello from -test !"
>>> import -test
File "", line 1
import -test
^
SyntaxError: invalid syntax
>>> __import__("-test", globals(), locals(), [])
But here is another problem:
>>> -test.fun2()
Traceback (most recent call last):
File "", line 1, in ?
NameError: name 'test' is not defined
>>> import sys
>>> sys.modules["-test"].fun2()
'Hello from -test !'
Regards,
Rob
--
http://mail.python.org/mailman/listinfo/python-list
Re: do people really complain about significant whitespace?
Slawomir Nowaczyk wrote: > Really, typing brace after function/if/etc should add newlines and > indent code as required -- automatically. Actually, for me, it is even > *less* typing in C and similar languages... I probably should teach my > Emacs to automatically add newline after colon in Python, just as it > does after a brace in C... As soon as I figure out how to deal with > dictionary literals. Hmmm. Are you sure? My Emacs already know how to do it with the help of python-mode and magic function py-newline-and-indent. emacs-version "21.3.1" py-version "$Revision: 4.63 $" Regards, Rob -- http://mail.python.org/mailman/listinfo/python-list
Re: Advice on a TCP passthru daemon for HTTP proxy rotation
Robin Haswell wrote:
> Hey there
>
> Soon we will have many squid proxies on many seperate connections for use
> by our services. I want to make them available to users via a single HTTP
> proxy - however, I want fine-grained control over how the squid proxies
> are selected for each connection. This is so I can collect statistics,
> control usage on each proxy, monitor what's going on - etc. However I
> don't want to implement the HTTP proxy protocol in Python, and would
> much rather let my daemon run as a man-in-the-middle for TCP, similar to
> this netcat command:
>
> [EMAIL PROTECTED]:~$ mknod backpipe p
> [EMAIL PROTECTED]:~$ nc -l -p 8080 < backpipe | nc ganesh 8080 > backpipe
>
> Basically when my daemon received a connection (call it "c1"), it makes a
> connection to one of my squid proxies ("c2"), then all data which gets
> read from c1 is written to c2 - all data read from c2 is written to c1.
> I'm pretty sure there's an elegant way to do this but I was wondering if
> anyone had any input? I've tried GIYF'ing this but it's difficult to
> search for :P
Maybe this is what you're looking for:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/483732
Regards,
Rob
--
http://mail.python.org/mailman/listinfo/python-list
Re: sys.platform documentation?
Michiel Sikma wrote: > So here's the question of the day: what does your sys.platform tell > you? :-) uname -srv HP-UX B.11.00 D python -c "import sys; print sys.platform" hp-ux11 Regards, Rob -- http://mail.python.org/mailman/listinfo/python-list
Re: do people really complain about significant whitespace?
Slawomir Nowaczyk wrote: > On Wed, 09 Aug 2006 07:33:41 -0700 > Rob Wolfe <[EMAIL PROTECTED]> wrote: > > #> Slawomir Nowaczyk wrote: > #> > #> > Really, typing brace after function/if/etc should add newlines and > #> > indent code as required -- automatically. Actually, for me, it is even > #> > *less* typing in C and similar languages... I probably should teach my > #> > Emacs to automatically add newline after colon in Python, just as it > #> > does after a brace in C... As soon as I figure out how to deal with > #> > dictionary literals. Hmmm. > #> > #> Are you sure? My Emacs already know how to do it with the help > #> of python-mode and magic function py-newline-and-indent. > #> > #> emacs-version "21.3.1" > #> py-version "$Revision: 4.63 $" > > OK, my python-mode.el was older, so I upgraded to 4.75, but it still > doesn't work. Did you mean that after you write > > if x==1: > > the newline is inserted automatically when you type ":"? That's a Exactly. > functionality I would like to see, but it doesn't seem to work this > way. Here is fragment of my python-mode.el: """ The \\[indent-for-tab-command] and \\[py-newline-and-indent] keys try to suggest plausible indentation, based on the indentation of preceding statements. E.g., assuming py-indent-offset is 4, after you enter \tif a > 0: \\[py-newline-and-indent] the cursor will be moved to the position of the `_' (_ is not a character in the file, it's just used here to indicate the location of the cursor): \tif a > 0: \t_ If you then enter `c = d' \\[py-newline-and-indent], the cursor will move to \tif a > 0: \tc = d \t_ Python-mode cannot know whether that's what you intended, or whether \tif a > 0: \tc = d \t_ was your intent. In general, Python-mode either reproduces the indentation of the (closest code or indenting-comment) preceding statement, or adds an extra py-indent-offset blanks if the preceding statement has `:' as its last significant (non-whitespace and non- comment) character. If the suggested indentation is too much, use \\[py-electric-backspace] to reduce it. """ Regards, Rob -- http://mail.python.org/mailman/listinfo/python-list
Re: using python to edit a word file?
John Salerno <[EMAIL PROTECTED]> writes: > I figured my first step is to install the win32 extension, which I > did, but I can't seem to find any documentation for it. A couple of > the links on Mark Hammond's site don't seem to work. > > Anyway, all I need to do is search in the Word document for certain > strings and either delete them or replace them. Easy enough, if only I > knew which function, etc. to use. > > Hope someone can push me in the right direction. Maybe this will be helpful: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/279003 -- Regards, Rob -- http://mail.python.org/mailman/listinfo/python-list
Re: hide python code !
John Machin wrote: > If you want to distribute obfuscated code, consider writing it in perl > :-) LOL That's really strong protection. Machine code is too easy to reverse engineer. :) Regards, Rob -- http://mail.python.org/mailman/listinfo/python-list
Re: sending values over classes
"Rafał Janas" <[EMAIL PROTECTED]> writes: > Hi, > > How to read/write value over different classes (in different files) > Something like global values? You need to be more specific about what exactly you're trying to accomplish. Some code whould be great. Maybe import statement is what you're looking for. You can import a class from another module (file) to current module (file) and use it. BTW on pl.comp.lang.python you can meet helpful people too :) -- HTH, Rob -- http://mail.python.org/mailman/listinfo/python-list
Re: Create a Multilanguage PDF in Python
"Perseo" <[EMAIL PROTECTED]> writes:
> Hi guys,
>
> I'm disprate with the Pdf Unicode. I try to create a class using ufpdf
> but some chars are not correct and now I would like try Python because
> a friend tolds me that it's very powerful.
> I need a simple script in Python that grab all Records from a MySql
> table and print in the pdf file.
>
> The languages stored in my db are about 25 and they are:
> Greek English French Hungarian Italian Lithuanian Dutch Portuguese
> Albanian
> Czech Danish German Spanish Estonian Finnish Irish Latvian Maltese
> Polish Romanian
> Russian Slovene Slovak Swedish
You can give reportlab [1] a try. It has support for TrueType fonts
and unicode translation using UTF-8. I used to use it for pdf files
with polish chars.
Some example code:
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.pdfgen import canvas
pdfmetrics.registerFont(TTFont('Verdana', 'Verdana.ttf'))
c = canvas.Canvas("pl.pdf")
c.setFont("Verdana", 12)
c.drawString(100, 600, "Witaj, świecie!".decode("iso-8859-2").encode("utf-8"))
c.showPage()
c.save()
[1] http://www.reportlab.org/
--
HTH,
Rob
--
http://mail.python.org/mailman/listinfo/python-list
Re: Create a Multilanguage PDF in Python
Perseo wrote: > Hi again, > > WORKS!!! I download all I need as python + reportlab. Only 2 questions: > > 1. I need all of this package? because it is 6Mb! I'm afraid you need all of it. BTW My reportlab package is only 3MB... hmm strange. > 2. How can I connect my software with MySql. In my Hosting is present > the Python support but I don't thing that the MySQLdb is present. How > can I solve this little problem? You can install MySQLdb wherever you want. You need only to make sure the module is in your PYTHONPATH. HTH, Rob -- http://mail.python.org/mailman/listinfo/python-list
Re: Regular Expression question
[EMAIL PROTECTED] wrote:
> Hi, I am having some difficulty trying to create a regular expression.
>
> Consider:
>
>
>
>
>
>
> Whenever a tag1 is followed by a tag 2, I want to retrieve the values
> of the tag1:name and tag2:value attributes. So my end result here
> should be
> john, tall
> jack, short
>
> My low quality regexp
> re.compile('tag1.+?name="(.+?)".*?(?!tag1).*?="adj__(.*?)__',
> re.DOTALL)
>
> cannot handle the case where there is a tag1 that is not followed by a
> tag2. findall returns
> john, tall
> joe, short
>
> Ideas?
Have you tried this:
'tag1.+?name="(.+?)".*?(?=tag2).*?="adj__(.*?)__'
?
HTH,
Rob
--
http://mail.python.org/mailman/listinfo/python-list
Re: Regular Expression question
[EMAIL PROTECTED] wrote: > Thanks, i just tried it but I got the same result. > > I've been thinking about it for a few hours now and the problem with > this approach is that the .*? before the (?=tag2) may have matched a > tag1 and i don't know how to detect it. Maybe like this: 'tag1.+?name="(.+?)".*?(?:<)(?=tag2).*?="adj__(.*?)__' HTH, Rob -- http://mail.python.org/mailman/listinfo/python-list
Re: Regular Expression question
[EMAIL PROTECTED] wrote:
> got zero results on this one :)
Really?
>>> s = '''
'''
>>> pat = re.compile('tag1.+?name="(.+?)".*?(?:<)(?=tag2).*?="adj__(.*?)__',
>>> re.DOTALL)
>>> m = re.findall(pat, s)
>>> m
[('john', 'tall'), ('joe', 'short')]
Regards,
Rob
--
http://mail.python.org/mailman/listinfo/python-list
Re: Create a Multilanguage PDF in Python
Perseo wrote: > Nothing to do! > I enable test2.py and the folder with 777 permission and I write at the > top of the file the PYTHONPATH "#!/usr/bin/python" as you told me but > it doesn't works as well. #!/usr/bin/python is not PYTHONPATH. I think you should read this: http://docs.python.org/tut/node4.html#SECTION00422 > The verdana font doesn't exist in the reportlab fonts folder. I try to > delete the rows where it is called like (registerFont, setFont) but > nothing to do. Fonts are not part of reportlab package. You should find it in your OS or in the net. You need to know what font do you want to use. > any suggestion?! Install reportlab package in your home directory, for example /home/perseo/python/lib and then in the shell write this: export PYTHONPATH=/home/perseo/python/lib and look here: http://docs.python.org/tut/node8.html#SECTION00811 HTH, Rob -- http://mail.python.org/mailman/listinfo/python-list
Re: How to ask sax for the file encoding
"Edward K. Ream" <[EMAIL PROTECTED]> writes: > Can anyone tell me how the content handler can determine the encoding of the > file? Can sax provide this info? Try this: from xml.parsers import expat s = """ Title Chapter 1 """ class MyParser(object): def XmlDecl(self, version, encoding, standalone): print "XmlDecl", version, encoding, standalone def Parse(self, data): Parser = expat.ParserCreate() Parser.XmlDeclHandler = self.XmlDecl Parser.Parse(data, 1) parser = MyParser() parser.Parse(s) -- HTH, Rob -- http://mail.python.org/mailman/listinfo/python-list
Re: A curses-game I need help with.
"Gasten" <[EMAIL PROTECTED]> writes:
> Can you help?
I'm not a guru on curses by any means, but I've moved one line
of your code and IMHO it works fine now.
Look below for the code I've changed.
> I'll just append all my code here (for anyone to test), so you who
> doesn't want to read this humble beginners code can skip to another
> message. Thank you for your time.
>
> (So far I've understood, is that iMsg() and updateMsg() is wrong. Line
> 71 and 92.)
>
>
> try:
> import curses
> except ImportError:
> print "Missing the Curses-library."
> print "Please install the curses-library correctly."
> SystemExit
>
> #---
>
> class Game:
> """The Game-object. Controls the windows, global settings and so
> on."""
> def __init__(self):
> self.mainwin = curses.initscr()
>
> ## Some basic settings
> curses.noecho()
> curses.cbreak()
> self.mainwin.keypad(1)
> curses.curs_set(0)
>
> self.msg = Msg()
> self.msg.msg(["Welcome to The Game! Lets watch another fearless
> samurai", "get beaten bloody in the arena!"])
>
> self.mainwin.addstr(3,15, '+' + '-' * 62 + '+')
> self.mainwin.addstr(22,15, '+' + '-' * 62 + '+')
> self.mainwin.vline(4,15, '|', 18)
> self.mainwin.vline(4,78, '|', 18)
>
>
> movedir = {
> 'up': {'x':0, 'y':-1},
> 'down': {'x':0, 'y':+1},
> 'right':{'x':+1, 'y':0},
> 'left': {'x':-1, 'y':0},
> 'downright':{'x':+1, 'y':+1},
> 'upright': {'x':+1, 'y':-1},
> 'downleft': {'x':-1, 'y':+1},
> 'upleft': {'x':-1, 'y':-1}
> }
>
> walls = (
> ord('|'),
> ord('+'),
> ord('-')
> )
>
> #---
>
> class Msg:
> """The messagehandeling and -bar system."""
> def __init__(self):
> self.msgs = []
>
> def printMore(self):
> # Print the little #More#-sign
> game.mainwin.addch(1, 71, curses.ACS_BLOCK, curses.A_REVERSE)
> game.mainwin.addstr(1, 72, "More", curses.A_REVERSE)
> game.mainwin.addch(1, 76, curses.ACS_BLOCK, curses.A_REVERSE)
>
> def msg(self, msg):
> if isinstance(msg, str):
> self.msgs.append(msg)
> else:
> self.msgs = self.msgs + msg
>
> def ereasMsg(self):
> for count in range(0,2):
> game.mainwin.move(count,0)
> game.mainwin.clrtoeol()
>
> def updateMsg(self):
> count = len(self.msgs)
> for msg in self.msgs: # Print one msg after
> another
> game.mainwin.addstr(0,0, msg) # Print the actual message
> if count > 1: # If there are two or more
> laft, print a #More#-sign.
> count -= 1
> self.printMore()
> game.mainwin.refresh()
> while 1:
> next = game.mainwin.getch()
> if next == ord(' '):
> self.ereasMsg()
> break
> else:
> continue
> else:
> game.mainwin.refresh()
>
> self.msgs = [] # When done, kill all messages
> return True
>
> def iMsg(self, msg):
> """Same as msg(), but the screen will refresh instantly.
> 'i' is standing for Interface or Instant message."""
> if isinstance(msg, str):
> msg = [msg] # List'it!
> count = len(msg)
> for item in msg:
> if count > 1:
> count -= 1
> self.printMore()
> game.mainwin.addstr(0,0, item)
> game.mainwin.refresh()
> while 1:
> next = game.mainwin.getch()
> if next == ord(' '):
> self.ereasMsg()
> break
> else:
> continue
> else:
> game.mainwin.addstr(0,0, item)
>
> return
>
>
> #---
>
> class Samurai:
> """This is the object of the mighty Samurai. Phe4r him. He can
> move.
> He can spawn. He will be able to kick som robo butt too,
> but not now."""
> def __init__(self):
> ## Configuring game values.
> self.loc = {
> "x": 20,
> "y": 8
> }
> self.samuraichar = ord("X")
>
> # spawn
> game.mainwin.addch(self.loc['y'], self.loc['x'],
> self.samuraichar)
>
> def move(self, dir, speed=1):
> # Move in dir speed number of times.
> for count in range(1, speed + 1):
> newX = self.loc['x'] + game.movedir[dir]['x']
> newY
Re: How to send E-mail without an external SMTP server ?
[EMAIL PROTECTED] wrote: > Hi, > > I just want to send a very simple email from within python. > > I think the standard module of smtpd in python can do this, but I > haven't found documents about how to use it after googleing. Are there > any examples of using smtpd ? I'm not an expert,so I need some examples > to learn how to use it. See standard documentation: http://docs.python.org/lib/SMTP-example.html HTH, Rob -- http://mail.python.org/mailman/listinfo/python-list
Re: How to send E-mail without an external SMTP server ?
[EMAIL PROTECTED] wrote: > Do I have to setup a smtp server on my localhost ? If I see correctly your smtp server is gmail.com. HTH, Rob -- http://mail.python.org/mailman/listinfo/python-list
Re: Looking for assignement operator
Alexander Eisenhuth wrote: > Hello, > > is there a assignement operator, that i can overwrite? You can't overwrite assignment operator, but you can overwrite methods of numeric objects: http://docs.python.org/ref/numeric-types.html HTH, Rob -- http://mail.python.org/mailman/listinfo/python-list
Re: a little about regex
Fulvio wrote: > I'm trying to get working an assertion which filter address from some domain > but if it's prefixed by '.com'. > Even trying to put the result in a negate test I can't get the wanted result. [...] > Seem that I miss some better regex implementation to avoid that both of the > filters taking action. I'm thinking of lookbehind (negative or positive) > option, but I think I couldn't realize it yet. > I think the compilation should either allow have no '.com' before '.my' or > deny should have _only_ '.com' before '.my'. Sorry I don't get the correct > sintax to do it. > > Suggestions are welcome. Try this: def filter(adr):# note that "filter" is a builtin function also import re allow = re.compile(r'.*(?|$)') # negative lookbehind deny = re.compile(r'.*\.com\.my(>|$)') cnt = 0 if deny.search(adr): cnt += 1 if allow.search(adr): cnt += 1 return cnt HTH, Rob -- http://mail.python.org/mailman/listinfo/python-list
Re: a little about regex
Fulvio wrote: > Great, it works perfectly. I found my errors. > I didn't use r ahead of the patterns and i was close to the 'allow' pattern > but didn't give positive result and KregexEditor reported wrong way. This > specially because of '<' inside the stream. I thing that is not a normal > regex input. It's only python valid. Am I right? The sequence inside "(?...)" is an extension notation specific to python. Regards, Rob -- http://mail.python.org/mailman/listinfo/python-list
Re: django's view.py as class not just methods
Skink <[EMAIL PROTECTED]> writes:
> Hi,
>
> I'm relatively new to django and maybe my question is stupid, but...
>
> Is it possible to map in urls.py some url not to function in views.py
> (which has first argument with HttpRequest) but to some class method?
> In that case each instance of such class would be created when session
> starts and for subsequent calls would be served as self ?
>
> I know, I know that HttpRequest has session member and I can use it.
> But maybe it would be good idea to have such url ==> class.method
> mapping.
I didn't try it with django but maybe closure is the solution.
Try this:
#!/usr/bin/env python
class MyView(object):
def __init__(self):
self.visited = []
def index(self, *args):
self.visited.append("index")
print "%s.index: %r" % (self.__class__.__name__, args)
return "response from index"
def detail(self, *args):
self.visited.append("detail")
print "%s.detail: %r" % (self.__class__.__name__, args)
return "response from detail"
def error(self, *args):
self.visited.append("error")
print "%s.error: %r" % (self.__class__.__name__, args)
return "response from error"
def make_view(obj, methodname):
def view(*args):
try:
return getattr(obj, methodname)(*args)
except AttributeError:
return obj.error(*args)
return view
view_obj = MyView()
index = make_view(view_obj, "index")
detail = make_view(view_obj, "detail")
download = make_view(view_obj, "download")
print index("request to index")
print detail("request to detail", 25)
print download("request to download", "abc", 99)
print
print "\n".join(view_obj.visited)
index, detail and download functions can be mapped
in urls.py now.
--
HTH,
Rob
--
http://mail.python.org/mailman/listinfo/python-list
Re: NEED HELP
[EMAIL PROTECTED] wrote:
> Below is my code, which is kind of virtual and with its help ill use it
> in my main project.
> Now what i am looking for is can anybody write all the code inside a
> class...so that I can reuse it. I am kind of novice...n kind of stuc
> with that.
>
> from Tkinter import *
>
> root = Tk()
>
> w = Label(root, text="Right-click to display menu", width=40,
> height=20)
> w.pack()
>
> # create a menu
> popup = Menu(root, tearoff=0)
> popup.add_radiobutton(label="SourceIP", command= hello) # ,
> command=next) etc...
> popup.add_radiobutton(label="DestIP", command= hello)
> popup.add_radiobutton(label="Reporter'sIP", command= hello)
> popup.add_radiobutton(label="Observer'sIP", command= hello)
> popup.add_separator()
> popup.add_radiobutton(label="Home")
>
> def do_popup(event):
> # display the popup menu
> try:
> popup.post(event.x_root, event.y_root)
> finally:
> # make sure to release the grab (Tk 8.0a1 only)
> popup.grab_release()
> def hello(event= None):
> print "hello"
>
> w.bind("", do_popup)
>
> b = Button(root, text="Quit", command=root.destroy)
> b.pack()
>
> mainloop()
Here's a great tutorial:
http://www.effbot.org/tkinterbook/tkinter-hello-again.htm
HTH,
Rob
--
http://mail.python.org/mailman/listinfo/python-list
Re: wxNotebook color change
mardif wrote: > Hi ! > > this is my problem: > > I've a wxNotebook object, which contains 2 Panels. > On up, there is TAB section, I have 2 tabs. > I want to color the TAB section with ( for example ) red color. > > I've tried with SetBackgroundColour() for wxNotebook object and for 2 > panel inside, but it doesn't works. > why?? Presumably you forgot to refresh window. Try this: import wx app = wx.PySimpleApp() frame = wx.Frame(None, -1, "Notebook") nb = wx.Notebook(frame, -1) form1 = wx.Panel(nb, -1) nb.AddPage(form1, "Form1") form2 = wx.Panel(nb, -1) form2.SetBackgroundColour(wx.RED) nb.AddPage(form2, "Form2") nb.SetSelection(1) frame.Refresh() frame.Show(True) app.MainLoop() HTH, Rob -- http://mail.python.org/mailman/listinfo/python-list
Re: wxNotebook color change
mardif wrote: > If you set: > > frame.SetBackgroundColour(wx.RED) > > On unix, you can see that label "form1" and "form2" are grey, and > others elements are red. > But on Windows, on the same line of "form1" and "form2", the color is > not red, but grey as labels. > > I want to color this space RED!!! Oh, I see now. I don't know if that is possible on windows. SetBackgroundColour works differently on windows than on unix, so probably native windows widget doesn't support this feature. (but I can be wrong of course.) Regards, Rob -- http://mail.python.org/mailman/listinfo/python-list
Re: Subclassing Tkinter Buttons
Bob Greschke wrote:
> I don't use classes much (mainly because I'm stupid), but I'd like to make a
> subclass of the regular Tkinter Button widget that simply adds spaces to the
> passed "text=" when the program is running on Windows (Linux, Solaris, Mac
> add a little space between the button text and the right and left edges of a
> button, Windows does not and it looks bad/can be hard to read). Below is
> some pseudo code. What should the guts of the BButton class be? I can't
> work out how all of the arguments that would be passed to a regular Button
> call get handled. *args and **kw confuse me and I can't seem to find simple
> enough examples in my mountain of books.
So watch this:
import Tkinter as Tk
import sys
class MyButton(Tk.Button):
system = sys.platform[:3]# 1
def __init__(self, master=None, **kw): # 2 3
if self.system == "win":
kw["padx"] = kw.get("padx", 0) + 5 # 4
# alternative solution
# if "text" in kw and self.system == "win":
# kw["text"] = " " + kw["text"] + " "
Tk.Button.__init__(self, master, **kw) # 5
1. system is a class attribute, so is shared by the class and all
instances of the class
2. __init__ is called immediately after an instance of the class
is created
3. kw is a dictionary of button options for example:
{"text": "Hello", "padx": 2}
4. change value of element "padx" or add this element to dictionary kw
5. call parent __init__ method to create button
HTH,
Rob
--
http://mail.python.org/mailman/listinfo/python-list
Re: Javadoc style python manual?
[EMAIL PROTECTED] wrote: > Hi there, > > I'm new to python and I'm from the java world. > Though I love to learn python, I'm not very comfortable with the python > documentation. > Because when i read jdk doc, i can see the class hierachy, class > member, class methods etc in html docs. It's very easy for me to > understand the Java language. > But in python, i find it kind of inconvient. > > Any advice? With AcitvePython is distributed the htmlhelp version of python reference (ActivePython24.chm). It's really convinient to use. HTH, Rob -- http://mail.python.org/mailman/listinfo/python-list
Re: best way of testing a program exists before using it?
Hari Sekhon wrote:
> I am writing a wrapper to a binary command to run it and then do
> something with the xml output from it.
>
> What is the best way of making sure that the command is installed on the
> system before I try to execute it, like the python equivalent of the
> unix command "which"?
>
> Otherwise I'd have to do something like:
>
> if os.system('which somecommand') != 0:
> print "you don't have %s installed" % somecommand
> sys.exit(1)
>
> I know that isn't portable which is why a python solution would be
> better (although this will run on unix anyway, but it'd be nice if it
> ran on windows too).
IMHO this is pretty portable:
>>> def is_on_path(fname):
... for p in os.environ['PATH'].split(os.pathsep):
... if os.path.isfile(os.path.join(p, fname)):
... return True
... return False
HTH,
Rob
--
http://mail.python.org/mailman/listinfo/python-list
Re: best way of testing a program exists before using it?
Steve Holden <[EMAIL PROTECTED]> writes:
> Rob Wolfe wrote:
>> Hari Sekhon wrote:
>>
>>>I am writing a wrapper to a binary command to run it and then do
>>>something with the xml output from it.
>>>
>>>What is the best way of making sure that the command is installed on the
>>>system before I try to execute it, like the python equivalent of the
>>>unix command "which"?
>>>
>>>Otherwise I'd have to do something like:
>>>
>>>if os.system('which somecommand') != 0:
>>>print "you don't have %s installed" % somecommand
>>>sys.exit(1)
>>>
>>>I know that isn't portable which is why a python solution would be
>>>better (although this will run on unix anyway, but it'd be nice if it
>>>ran on windows too).
>> IMHO this is pretty portable:
>>
>>>>>def is_on_path(fname):
>> for p in os.environ['PATH'].split(os.pathsep):
>> if os.path.isfile(os.path.join(p, fname)):
>> return True
>> return False
>>
> Except that the fname will then have to be a ".exe" on Windows and not
> on Unix.
My function doesn't check if the file is executable at all.
This function checks only if the file exists on the PATH.
I know it isn't a perfect solution but it is portable.
--
Regards,
Rob
--
http://mail.python.org/mailman/listinfo/python-list
Re: error
[EMAIL PROTECTED] wrote: > Hi, [...] > Step 3: Wrote the given script of multipication in a file named as > multiply (using vi editor) The name of module should be multiply.py HTH, Rob -- http://mail.python.org/mailman/listinfo/python-list
Re: error
John Machin wrote: > Rob Wolfe wrote: > > [EMAIL PROTECTED] wrote: > > > Hi, > > [...] > > > Step 3: Wrote the given script of multipication in a file named as > > > multiply (using vi editor) > > > > The name of module should be multiply.py > > > > module != source_file > module don't have no ferschlugginer dots in its name Ooops... sorry. I meant name of python source file, of course. Regards, Rob -- http://mail.python.org/mailman/listinfo/python-list
Re: How to compare to directories?
[EMAIL PROTECTED] wrote: > I want to compare 2 directories: dir1 and dir2. > What I want to do is to get these informations: > 1. does they have the same number of files and sub-directories? > 2. does each file with the same name have the same size and date > information? > > So, how can I do it in python? Here is a nice example: http://docs.python.org/lib/os-file-dir.html Look for description of function walk. HTH, Rob -- http://mail.python.org/mailman/listinfo/python-list
Re: Cross-process dictionary/hashtable
"Sandra-24" <[EMAIL PROTECTED]> writes: > A dictionary that can be shared across processes without being > marshaled? > > Is there such a thing already for python? Check this out: http://poshmodule.sourceforge.net/ -- HTH, Rob -- http://mail.python.org/mailman/listinfo/python-list
Re: jpype package, could be path problem
kelemen.viktor wrote:
> everything worked correctly but when i wrote a short script:
> "
> from jpype import *
>
> jpype.startJVM('/usr/lib/jvm/java-1.5.0-sun-1.5.0.06/jre/lib/i386/client/libjvm.so','-ea')
> java.lang.System.out.println("hello world")
> shutdownJVM()
> "
> and tried to run it this's got:
>
> "
> Traceback (most recent call last):
> File "/home/kelemen/workspace/JPype/src/helloAgent.py", line 3, in ?
>
> jpype.startJVM('/usr/lib/jvm/java-1.5.0-sun-1.5.0.06/jre/lib/i386/client/libjvm.so','-ea')
> NameError: name 'jpype' is not defined
> "
>
> What would be the reason?
Consider this:
# bad style (potential name clash)
from jpype import *
startJVM('/usr/lib/jvm/java-1.5.0-sun-1.5.0.06/jre/lib/i386/client/libjvm.so','-ea')
# that's better
import jpype
jpype.startJVM('/usr/lib/jvm/java-1.5.0-sun-1.5.0.06/jre/lib/i386/client/libjvm.so','-ea')
# for long names of modules
import jpype as jp
jp.startJVM('/usr/lib/jvm/java-1.5.0-sun-1.5.0.06/jre/lib/i386/client/libjvm.so','-ea')
And see this:
http://docs.python.org/tut/node8.html
HTH,
Rob
--
http://mail.python.org/mailman/listinfo/python-list
Re: jpype package, could be path problem
kelemen.viktor wrote:
> Hi
>
> thanks for your suggestions
>
> ive modified the sample code
You've modified it incorrect.
> "
> import jpype
> from jpype import *
You should use "import jpype" OR "from jpype import *" (not
recommended)
but NOT BOTH.
> jpype.startJVM('/usr/lib/jvm/java-1.5.0-sun-1.5.0.06/jre/lib/i386/client/libjvm.so','-ea')
> java.lang.System.out.println("hello world")
> shutdownJVM()
> "
>
> and its working. It seems to be quite strange.
> What would be the difference between the two import?
1. "import jpype"
This does not enter the name of the function startJVM defined in jpype
directly in the current symbol table; it only enters the module name
jpype there.
Using the module name you can access the function like that:
jpype.startJVM()
2. "from jpype import"
This enters the name of the function startJVM in the currrent symbol
table,
so you can access the function just like that:
startJVM()
And have you read this: http://docs.python.org/tut/node8.html ?
HTH,
Rob
--
http://mail.python.org/mailman/listinfo/python-list
Re: How to change menu text with Tkinter?
Phil Schmidt wrote: > I am making a little Tkinter GUI app that needs to be in several > languages (english, french, etc.), adjustable at runtime via a menu > pick to select the language. The only way I can see to change text in > the menus entries is to destroy them and recreate them usiing different > labels. This seems very clunky though, and there must be a better way. > Can anyone offer any pointers or a short example for how to do this? Try this: menu.entryconfig(index, label="new_name") HTH, Rob -- http://mail.python.org/mailman/listinfo/python-list
Re: combining the path and fileinput modules
wo_shi_big_stomach wrote:
> Newbie to python writing a script to recurse a directory tree and delete
> the first line of a file if it contains a given string. I get the same
> error on a Mac running OS X 10.4.8 and FreeBSD 6.1.
>
> Here's the script:
>
> # start of program
>
> # p.pl - fix broken SMTP headers in email files
> #
> # recurses from dir and searches all subdirs
> # for each file, evaluates whether 1st line starts with "From "
> # for each match, program deletes line
>
> import fileinput
> import os
> import re
> import string
> import sys
> from path import path
>
> # recurse dirs
> dir = path(/home/wsbs/Maildir)
> for f in dir.walkfiles('*'):
> #
> # test:
> # print f
Are you absolutely sure that f list doesn't contain
any path to directory, not file?
Add this:
f = filter(os.path.isfile, f)
and try one more time.
> #
> # open file, search, change if necessary, write backup
> for line in fileinput.input(f, inplace=1, backup='.bak'):
> # check first line only
> if fileinput.isfirstline():
> if not re.search('^From ',line):
> print line.rstrip('\n')
> # just print all other lines
> if not fileinput.isfirstline():
> print line.rstrip('\n')
> fileinput.close()
> # end of program
--
HTH,
Rob
--
http://mail.python.org/mailman/listinfo/python-list
Re: Question about import and sys.path
Frank Millman wrote:
> Hi all
>
> I am writing a business/accounting application. Once a user has logged
> in they are presented with a menu. Each menu option has a description
> and an associated file name and program name. The file name is the name
> of a .py file (impName) and the program name is the name of a class in
> that file which I instantiate to run the program (progName).
>
> When a menu option is selected, I execute the program like this -
> imp = __import__(impName)
> app = getattr(imp,progName)()
>
> All the .py files are stored in one directory, which I add to sys.path
> at the beginning of the session. It all seems to work fine.
>
> Now my program directory is getting cluttered, so I want to split it
> into sub-directories, one per company (it is a multi-company system). I
> can do that, and each of the subdirectories can be added to sys.path,
> so it should work as at present.
>
> However, I want the ability to have duplicate program names stored in
> different subdirectories. At the time of selecting the menu option I
> know which company is active, so I know which directory I want to run
> the program from, but there does not seem to be a way to tell 'import'
> to import from a particular directory.
I suggest to use module `imp`.
For example:
I assume paths like this:
app/
importer.py
company1/
prog1.py
the module in the company1 subdirectory:
# prog1
class SomeClass(object):
def test(self):
return "%s: %s" % (__file__, self.__class__.__name__)
and the module with your menu could look like this:
# importer.py
def get_class(classname, impname, company):
fp, pathname, description = imp.find_module(impname, [company])
m = imp.load_module(impname, fp, pathname, description)
return getattr(m, classname)
obj = get_class("SomeClass", "prog1", "company1")()
print obj.test()
--
HTH,
Rob
--
http://mail.python.org/mailman/listinfo/python-list
Re: Question about import and sys.path
Frank Millman wrote: > One small point. The docs have the following warning - > > "Important: the caller is responsible for closing the file argument, if > it was not None, even when an exception is raised. This is best done > using a try ... finally statement. " > > I have added this to my code. > > I wonder if you can avoid this in 2.5 by using the 'with' statement. I > am still using 2.4, so I cannot test. Anyway, your suggestion does > exactly what I want, and it works perfectly. Yes, of course. The `with` statement works exactly as previously try...finally. I've tried it in 2.5 and it works perfectly. You have to use `from __future__ import with_statement`, though. This statement will be always enabled in Python 2.6. -- HTH, Rob -- http://mail.python.org/mailman/listinfo/python-list
Re: Detecting recursion loops
robert wrote: > My code does recursion loops through a couple of functions. Due to > problematic I/O input this leads sometimes to "endless" recursions and after > expensive I/O to the Python recursion exception. > What would be a good method to detect recursion loops and stop it by > user-Exception (after N passes or some complex criteria) without passing a > recursion counter parameter through all the funcs? What about `sys.setrecursionlimit`? http://docs.python.org/lib/module-sys.html -- HTH, Rob -- http://mail.python.org/mailman/listinfo/python-list
Re: get script path
hg wrote:
> Hi,
>
> must I parse argv[0] to get it, or is there an easier way (that works under
> Windows and *nix)?
>
> Ex:
>
> python /home/hg/test/test.py ==> test.py #knows it is in /home/hg/test
IMHO it is easy enough:
>>> dname, fname = os.path.split("/home/hg/test/test.py")
>>> dname
'/home/hg/test'
--
HTH,
Rob
--
http://mail.python.org/mailman/listinfo/python-list
Re: SLUT distibution mangled?
Actually when you remember the ancient history of Windows and MS/DOS you will see why. That filename, and a lot of others (as noted by Fredrik) are legacies of that time. They were special filenames (think "/dev/null") that related to specific devices. Gives us a good example of one of the little "gotchas" involved in cross platform development. Rob -- http://mail.python.org/mailman/listinfo/python-list
Re: subprocess leaves child living
Thomas Dybdahl Ahle wrote: > Problem is - I can't do that when I get killed. > Isn't it possible to open processes in such a way like terminals? If I > kill the terminal, everything open in it will die too. On POSIX platform you can use signals and ``os.kill`` function. Fo example: import os, signal from subprocess import Popen from time import sleep def handler(signum, frame): print 'Signal handler called' raise KeyboardInterrupt signal.signal(signal.SIGTERM, handler) try: popen = Popen(["ping", "google.com"]) try: sleep(100) except KeyboardInterrupt: pass finally: if popen.poll() is None: print "killing process: %d" % popen.pid os.kill(popen.pid, signal.SIGTERM) -- HTH, Rob -- http://mail.python.org/mailman/listinfo/python-list
Re: subprocess leaves child living
Thomas Dybdahl Ahle <[EMAIL PROTECTED]> writes: > But you can't ever catch sigkill. There is no protection against sigkill. > Isn't there a way to make sure the os kills the childprocess when the > parrent dies? If the parent dies suddenly without any notification childprocesses become zombies and there is no way to avoid that. -- HTH, Rob -- http://mail.python.org/mailman/listinfo/python-list
Re: Encoding problem with web application (Paste+Mako)
[EMAIL PROTECTED] wrote: > Hi > > I have a problem with encoding non-ascii characters in a web > application. The application uses Paste and Mako. > > The code is here: http://www.webudkast.dk/demo.txt > > The main points are: > > After getting some user generated input using > paste.request.parse_formvars, how should this be correctly saved to > file? > > How should this afterward be read from the file, and fed correctly > into a Mako template? You have to know the encoding of user input and then you can use ``input_encoding`` and ``output_encoding`` parameters of ``Template``. Mako internally handles everything as Python unicode objects. For example: t = Template(filename="templ.mako", input_encoding="iso-8859-2", output_encoding="iso-8859-2") content = t.render(**context) -- HTH, Rob -- http://mail.python.org/mailman/listinfo/python-list
Re: subprocess call acts differently than command line call?
Jim <[EMAIL PROTECTED]> writes: > Hello, > > I need a program that will traverse a directory tree to ensure that > there > are unix-style line endings on every file in that tree that is a text > file. > To tell text files from others I want to use the unix "file" command > (Python's "mimetypes" is not so good for me). But I am stuck on > something about getting that output, and I'd greatly appreciate any > pointers. > > Both the command line "file" and the python libmagic binding give the > same behavior, but I'll illustrate with "file". It sometimes acts > differently when run from the command line than when run using > the subprocess module (with the same user). For example, it > sometimes > gives output when run from the command line but no output when run as > a subprocess. > > Below is a short program to demo. (I use this on a test file tree > that is at ftp://joshua.smcvt.edu/pub/hefferon/a.zip if anyone > is interested.) [...] > I've put a transcript of what happens at the bottom of this message. > One file (in the test tree it is "eqchange.txt") gives no output from > the above program, but does give an output when I use "file" at the > command line. [...] > -transcript (edited to shorten) > $ python test.py > result: acrotex/readme.txt: ASCII English text, with CRLF line > terminators > > result: acrotex/eq2db.ins: ASCII English text, with CRLF line > terminators > > result: acrotex/eqchange.txt: > > result: acrotex/exerquiz.dtx: ISO-8859 English text, with CRLF line > terminators > result: acrotex/doc: directory > > done > > $ file acrotex/eqchange.txt > acrotex/eqchange.txt: ISO-8859 English text, with CRLF line That's interesting. I've checked this eqchange.txt file from your a.zip on my machine and the result is: $ file acrotex/readme.txt acrotex/readme.txt: ASCII English text, with CRLF line terminators $ file acrotex/eqchange.txt acrotex/eqchange.txt: $ file acrotex/exerquiz.dtx acrotex/exerquiz.dtx: ISO-8859 English text, with CRLF line terminators $ file -v file-4.17 magic file from /etc/magic:/usr/share/file/magic $ uname -orvm 2.6.18-4-k7 #1 SMP Wed May 9 23:42:01 UTC 2007 i686 GNU/Linux That's really strange. Have you got only *one* version of ``file`` program on your machine? -- HTH, Rob -- http://mail.python.org/mailman/listinfo/python-list
Re: SimplePrograms challenge
Steve Howell wrote: > Hi, I'm offering a challenge to extend the following > page by one good example: > > http://wiki.python.org/moin/SimplePrograms What about simple HTML parsing? As a matter of fact this is not language concept, but shows the power of Python standard library. Besides, that's very popular problem among newbies. This program for example shows all the linked URLs in the HTML document: from HTMLParser import HTMLParser page = ''' URLs http://domain1/page1";>some page1 http://domain2/page2";>some page2 ''' class URLLister(HTMLParser): def reset(self): HTMLParser.reset(self) self.urls = [] def handle_starttag(self, tag, attrs): try: # get handler for tag and call it e.g. self.start_a getattr(self, "start_%s" % tag)(attrs) except AttributeError: pass def start_a(self, attrs): href = [v for k, v in attrs if k == "href"] if href: self.urls.extend(href) parser = URLLister() parser.feed(page) parser.close() for url in parser.urls: print url -- Regards, Rob -- http://mail.python.org/mailman/listinfo/python-list
Re: SimplePrograms challenge
Steven Bethard <[EMAIL PROTECTED]> writes:
> I'd hate to steer a potential new Python developer to a clumsier
"clumsier"???
Try to parse this with your program:
page2 = '''
URLs
http://domain1/page1";>some page1
http://domain2/page2";>some page2
'''
> library when Python 2.5 includes ElementTree::
>
> import xml.etree.ElementTree as etree
>
> page = '''
> URLs
>
>
> http://domain1/page1";>some page1
> http://domain2/page2";>some page2
>
>
> '''
>
> tree = etree.fromstring(page)
> for a_node in tree.getiterator('a'):
> url = a_node.get('href')
> if url is not None:
> print url
It might be even one-liner:
print "\n".join((url.get('href', '') for url in tree.findall(".//a")))
But as far as HTML (not XML) is concerned this is not very realistic solution.
>
> I know that the wiki page is supposed to be Python 2.4 only, but I'd
> rather have no example than an outdated one.
This example is by no means "outdated".
--
Regards,
Rob
--
http://mail.python.org/mailman/listinfo/python-list
Re: SimplePrograms challenge
Steve Howell wrote: > I suggested earlier that maybe we post multiple > solutions. That makes me a little nervous, to the > extent that it shows that the Python community has a > hard time coming to consensus on tools sometimes. We agree that BeautifulSoup is the best for parsing HTML. :) > This is not a completely unfair knock on Python, > although I think the reason multiple solutions tend to > emerge for this type of thing is precisely due to the > simplicity and power of the language itself. > > So I don't know. What about trying to agree on an XML > parsing example instead? > > Thoughts? I vote for example with ElementTree (without xpath) with a mention of using ElementSoup for invalid HTML. -- Regards, Rob -- http://mail.python.org/mailman/listinfo/python-list
Re: SimplePrograms challenge
Steven Bethard <[EMAIL PROTECTED]> writes:
>> I vote for example with ElementTree (without xpath)
>> with a mention of using ElementSoup for invalid HTML.
>
> Sounds good to me. Maybe something like::
>
> import xml.etree.ElementTree as etree
> dinner_recipe = '''
>
> 24slicesbaguette
> 2+tbspolive_oil
^
Is that a typo here?
> 1cuptomatoes
> 1-2tbspgarlic
> 1/2cupParmesan
> 1jarpesto
> '''
> pantry = set(['olive oil', 'pesto'])
> tree = etree.fromstring(dinner_recipe)
> for item_elem in tree.getiterator('item'):
> if item_elem.text not in pantry:
> print item_elem.text
That's nice example. :)
> Though I wouldn't know where to put the ElementSoup link in this one...
I had a regular HTML in mind, something like:
# HTML page
dinner_recipe = '''
Recipe
amtunititem
24slicesbaguette
2+tbspolive_oil
1cuptomatoes
1-2tbspgarlic
1/2cupParmesan
1jarpesto
'''
# program
import xml.etree.ElementTree as etree
tree = etree.fromstring(dinner_recipe)
#import ElementSoup as etree # for invalid HTML
#from cStringIO import StringIO # use this
#tree = etree.parse(StringIO(dinner_recipe)) # wrapper for BeautifulSoup
pantry = set(['olive oil', 'pesto'])
for ingredient in tree.getiterator('tr'):
amt, unit, item = ingredient.getchildren()
if item.tag == "td" and item.text not in pantry:
print "%s: %s %s" % (item.text, amt.text, unit.text)
But if that's too complicated I will not insist on this. :)
Your example is good enough.
--
Regards,
Rob
--
http://mail.python.org/mailman/listinfo/python-list
Re: Efficient way of generating original alphabetic strings like unix file "split"
py_genetic <[EMAIL PROTECTED]> writes: > Hi, > > I'm looking to generate x alphabetic strings in a list size x. This > is exactly the same output that the unix command "split" generates as > default file name output when splitting large files. > > Example: > > produce x original, but not random strings from english alphabet, all > lowercase. The length of each string and possible combinations is > dependent on x. You don't want any repeats. > > [aaa, aab, aac, aad, aax, .. bbc, bbd, bcd] > > I'm assumming there is a slick, pythonic way of doing this, besides > writing out a beast of a looping function. I've looked around on > activestate cookbook, but have come up empty handed. Any suggestions? You didn't try hard enough. :) http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/190465 -- HTH, Rob -- http://mail.python.org/mailman/listinfo/python-list
Re: Parsing HTML, extracting text and changing attributes.
[EMAIL PROTECTED] wrote: > So, I'm writing this to have your opinion on what tools I should use > to do this and what technique I should use. Take a look at parsing example on this page: http://wiki.python.org/moin/SimplePrograms -- HTH, Rob -- http://mail.python.org/mailman/listinfo/python-list
Re: HTMLParser.HTMLParseError: EOF in middle of construct
Sérgio Monteiro Basto wrote:
> Stefan Behnel wrote:
>
> > Sérgio Monteiro Basto wrote:
> >> but is one single error that blocks this.
> >> Finally I found it , it is :
> >> >> if I put :
> >> >>
> >> p = re.compile('"align')
> >> content = p.sub('" align', content)
> >>
> >> I can parse the html
> >> I don't know if it a bug of HTMLParser
> >
> > Sure, and next time your key doesn't open your neighbours house, please
> > report to the building company to have them fix the door.
> >
>
> The question, here, is if
> is valid HTML or not ?
> I think is valid , if so it's a bug on HTMLParser
According to the HTML 4.01 specification this is *not valid* HTML.
"""
Elements may have associated properties, called attributes, which may
have values
(by default, or set by authors or scripts). Attribute/value pairs
appear before the final
">" of an element's start tag. Any number of (legal) attribute value
pairs, separated
by spaces, may appear in an element's start tag.
"""
> if not, we still have a very bad message error (EOF in middle of
> construct !?)
HTMLParser can deal with some errors e.g. lack of ending tags,
but it can't handle many other problems.
> I have to use HTMLParser because I want use only python 2.4 standard , I
> have to install the scripts in many machines.
> And I have to parse many different sites, I just want extract the links, so
> with a clean up before parse solve very quickly my problem.
In Python 2.4 you have to use some third party module. There is no
other option for _invalid_ HTML. IMHO BeautifulSoup is the best among
them.
--
HTH,
Rob
--
http://mail.python.org/mailman/listinfo/python-list
Re: bool behavior in Python 3000?
Steven D'Aprano wrote:
> From a purely functional perspective, bools are unnecessary in Python. I
> think of True and False as syntactic sugar. But they shouldn't be
> syntactic sugar for 1 and 0 any more than they should be syntactic sugar
> for {"x": "foo"} and {}.
But `bools` are usefull in some contexts. Consider this:
>>> 1 == 1
True
>>> cmp(1, 1)
0
>>> 1 == 2
False
>>> cmp(1, 2)
-1
At first look you can see that `cmp` does not return boolean value
what not for all newbies is so obvious.
Rob
--
http://mail.python.org/mailman/listinfo/python-list
Re: bool behavior in Python 3000?
Marc 'BlackJack' Rintsch wrote:
> On Wed, 11 Jul 2007 00:37:38 -0700, Rob Wolfe wrote:
>
> > Steven D'Aprano wrote:
> >
> >> From a purely functional perspective, bools are unnecessary in Python. I
> >> think of True and False as syntactic sugar. But they shouldn't be
> >> syntactic sugar for 1 and 0 any more than they should be syntactic sugar
> >> for {"x": "foo"} and {}.
> >
> > But `bools` are usefull in some contexts. Consider this:
> >
> >>>> 1 == 1
> > True
> >>>> cmp(1, 1)
> > 0
> >>>> 1 == 2
> > False
> >>>> cmp(1, 2)
> > -1
> >
> > At first look you can see that `cmp` does not return boolean value
> > what not for all newbies is so obvious.
>
> Sorry I fail to see your point!? What has ``==`` to do with `cmp()` here?
> The return of `cmp()` is an integer that cannot and should not be seen as
> boolean value.
Before `bool` appeared it looked like this:
>>> 1 == 1
1
>>> cmp(2, 1)
1
Wich result is boolean value?
Rob
--
http://mail.python.org/mailman/listinfo/python-list
Re: Question about Tkinter MenuOption variable
Chad wrote:
> Is there anyway to set the individual options in Tkinter to a
> particular variable. For example, I have a menu option(code is below)
> which has January, February, March and so on, which I would like to
> have corresponding values of 01, 02, 03 and so on. Can someone please
> tell me how to do that within the context of the code I have below -
> or even totally modify it if you must.
>
> Label(self,
> text = "Month"
> ).grid(row = 5, column = 1, sticky = W)
>OPTIONS = [
>"Jan",
>"Feb",
>"Mar",
>"Apr",
>"May",
>"June",
>"July",
>"Aug",
>"Sep",
>"Oct",
>"Nov",
>"Dec"]
>default_option = StringVar(self)
>default_option.set(OPTIONS[0])
>self.month_option = OptionMenu(self, default_option, *OPTIONS)
>self.month_option.grid(row = 5, column = 2, sticky = W)
What about using dictionary? For example:
import Tkinter as Tk
def state():
print OPTIONS[default_option.get()]
root = Tk.Tk()
Tk.Label(root, text="Month").grid(row=1, column=1, sticky=Tk.W)
OPTIONS = dict(Jan=1, Feb=2, Mar=3, Apr=4, May=5, June=6, July=7,
Aug=8, Sep=9, Oct=10, Nov=11, Dec=12)
# or
#OPTIONS = dict(Jan="01", Feb="02", Mar="03", Apr="04", May="05",
June="06", July="07",
# Aug="08", Sep="09", Oct="10", Nov="11", Dec="12")
default_option = Tk.StringVar()
default_option.set("Jan")
month_option = Tk.OptionMenu(root, default_option, *OPTIONS.keys())
month_option.grid(row=1, column=2, sticky=Tk.W)
Tk.Button(root, command=state, text='state').grid(row=2, column=1)
root.mainloop()
--
HTH,
Rob
--
http://mail.python.org/mailman/listinfo/python-list
Re: using tkinter to display html
Stephen M. Gava wrote: > On Thu, 19 Apr 2007 06:09:33 -0700, kyosohma wrote: > > > On Apr 19, 6:29 am, "Stephen M. Gava" <[EMAIL PROTECTED]> > > wrote: > >> Hi all, > >> > >> I prefer using tkinter to wxpython (so sue me :) and i need to display > >> a lot of html in a particular app. does anyone know if one of the > >> existing add on tk html widgets have been wrapped for tkinter already? > >> > >> TIA for any reply, > >> Stephen > > > > The following thread has various ideas in it: > > http://mail.python.org/pipermail/python-list/2001-October/107989.html > > thanks mike, i found that thread before i posted here, it doesn'rt answer > my question though. Why not? Did you try to use tkhtml [1]_ with python wrapper [2]_. IMHO it works pretty nice. .. [1] http://www.hwaci.com/sw/tkhtml/ .. [2] http://tix.sourceforge.net/Tixapps/src/Python/TkHtml.py -- HTH, Rob -- http://mail.python.org/mailman/listinfo/python-list
Re: Tutorial creates confusion about slices
Antoon Pardon wrote: > The following is part of the explanation on slices in the > tutorial: > > The best way to remember how slices work is to think of the indices as > pointing between characters, with the left edge of the first character > numbered 0. Then the right edge of the last character of a string of n > characters has index n, for example: > > +---+---+---+---+---+ > | H | e | l | p | A | > +---+---+---+---+---+ > 0 1 2 3 4 5 > -5 -4 -3 -2 -1 > > This is all very well with a simple slice like: > > "HelpA"[2:4]=> "lp" > > > But it give the wrong idea when using the following extended slice: > > "HelpA"[4:2:-1] => "Ap" > > So this doesn't result in the reverse of the previous expression while > the explanation above suggest it does. Clearly I understand that differently: >>> "HelpA"[-2:-4:-1] 'pl' -- Regards, Rob -- http://mail.python.org/mailman/listinfo/python-list
Re: I wish that [].append(x) returned [x]
Tobiah <[EMAIL PROTECTED]> writes: > I wanted to do: > > query = "query text" % tuple(rec[1:-1].append(extra)) > > but the append() method returns none, so I did this: > > fields = rec[1:-1] > fields.append(extra) > query = "query text" % tuple(fields) What about this? query = "query text" % tuple(rec[1:-1] + [extra]) -- HTH, Rob -- http://mail.python.org/mailman/listinfo/python-list
Re: read list of dirnames and search for filenames
fscked <[EMAIL PROTECTED]> writes:
> I cannot seem to get this to work. I am hyst trying to read in a list
> of paths and see if the directory or any sub has a filename pattern.
> Here is the code:
>
> import os, sys
> from path import path
>
> myfile = open("boxids.txt", "r")
> for line in myfile.readlines():
Instead of this:
> d = path(line)
try this:
d = path(line.strip())
``readlines`` doesn't remove trailing newline characters from string
> for f in d.walkfiles('*Config*.xml'):
> print f
>
> And here is my error:
>
> Traceback (most recent call last):
> File "Untitled.py", line 21, in ?
> for f in d.walkfiles('*Config*.xml'):
> File "C:\Python24\Lib\site-packages\path.py", line 460, in walkfiles
> childList = self.listdir()
> File "C:\Python24\Lib\site-packages\path.py", line 328, in listdir
> names = os.listdir(self)
> WindowsError: [Errno 3] The system cannot find the path specified: u'X:
> \\Instructions\\97544546294\n/*.*'
>
--
HTH,
Rob
--
http://mail.python.org/mailman/listinfo/python-list
Re: read list of dirnames and search for filenames
Rob Wolfe <[EMAIL PROTECTED]> writes:
> fscked <[EMAIL PROTECTED]> writes:
>
>> I cannot seem to get this to work. I am hyst trying to read in a list
>> of paths and see if the directory or any sub has a filename pattern.
>> Here is the code:
>>
>> import os, sys
>> from path import path
>>
>> myfile = open("boxids.txt", "r")
>> for line in myfile.readlines():
And you don't need to use ``readlines`` at all.
This is enough:
for line in myfile:
--
HTH,
Rob
--
http://mail.python.org/mailman/listinfo/python-list
Re: tkinter - label widget text selection
[EMAIL PROTECTED] writes:
> Hi,
> I guess this is a very trivial question --
> I am using a label widget to display text (black font in a white
> background color). I am trying to use my mouse to scroll over the
> displayed text to select it, but tkinter does not allow me to do it.
> Is there a method/option to do this.
Try to use an entry widget in read-only state:
import Tkinter as Tk
root = Tk.Tk()
ent = Tk.Entry(root, state='readonly', readonlybackground='white', fg='black')
var = Tk.StringVar()
var.set('Some text')
ent.config(textvariable=var, relief='flat')
ent.pack()
root.mainloop()
--
HTH,
Rob
--
http://mail.python.org/mailman/listinfo/python-list
Re: Unzip then Zip help
[EMAIL PROTECTED] writes:
> I am a true n00b... and I just using Python to complete some very
> small uneventful task, but need help with one last thing.
>
> Basically, this I what I am trying to do.
>
> make a temp directory (this part I can do)
>
> Need help with:
> ***unzip a JAR file with the complete list of subdirectories w/
> files
>
> modify the a set of XML files (this part I can do)
>
> Need help with:
> ***then zip the entire contents of the temp directory with sub
> directories***
>
> The only thing I am having trouble with is the whole directory stuff,
> if this was just straight files, no problem.
>
> Any help would be appreciated
>
Try this:
import os
from os.path import dirname, exists, splitext, join
from zipfile import ZipFile, ZIP_DEFLATED
def unpack(archname):
arch = ZipFile(archname, 'r')
for path in arch.namelist():
print path
dname = dirname(path)
if not exists(dname): os.makedirs(dname)
if splitext(path)[1]:
f = open(path, 'wb')
f.write(arch.read(path))
f.close()
arch.close()
def pack(archname, paths):
arch = ZipFile(archname, 'w', ZIP_DEFLATED)
for path in paths:
for root, dirs, files in os.walk(path):
for fname in files:
fname = join(root, fname)
print fname
arch.write(fname)
arch.close()
unpack('test.jar')
pack('test2.jar', ['com', 'META-INF'])
--
HTH,
Rob
--
http://mail.python.org/mailman/listinfo/python-list
Re: Popen and wget, problems
"Jesse" <[EMAIL PROTECTED]> writes:
> Hi all, I have a problem using wget and Popen. I hope someone can help.
>
>
> -- Problem --
> I want to use the command:
> wget -nv -O "dir/cpan.txt" "http://search.cpan.org";
> and capture all it's stdout+stderr.
> (Note that option -O requires 'dir' to be existing before wget is executed)
>
> Popen doesn't work, while os.system and shell do. Popen will give the error:
> dir/cpan.txt: No such file or directory
>
> While os.system and shell will give the correct result:
> 06:52:40 URL:http://search.cpan.org/ [3657/3657] -> "dir1/cpan.txt" [1]
[...]
> -- Python Code using Popen with cmd arg list --
> # imports
> import os
> from subprocess import Popen, PIPE
>
> # vars and create dir
> cmd_set = ['wget', '-nv', '-O dir/cpan.txt', 'http://search.span.org']
> cmd = ' '.join(cmd_set)
> print "cmd: " + cmd
> try:
> os.makedirs('dir')
> except:
> print 'dir already exists'
>
>
> # execute using Popen (does NOT work)
> proc = Popen(cmd_set, stdout=PIPE, stderr=PIPE)
> return_code = proc.wait()
> if return_code == 0:
> print "Success:\n%s" % (proc.stdout.read() + proc.stderr.read())
> else:
> print "Failure %s:\n%s" % (return_code, proc.stderr.read() +
> proc.stdout.read())
>
>
> # execute using os.system (does work)
> os.system(cmd)
>
>
> -- Python code output of Popen --
> Failure 1:
> dir/cpan.txt: No such file or directory
>
>
> -- Question --
> Why is Popen unable to correctly execute the wget, while os.system can?
I don't know exactly why in this case Popen doesn't work,
but the counterpart of os.system is Popen with option shell=True
and the first parameter should be a string instead of list.
That seems to work:
proc = Popen("wget -nv -O dir/cpan.txt http://search.span.org";,
shell=True, stdout=PIPE, stderr=PIPE)
and this variant seems to work too:
cmd_set = ['wget', '-nv', '-O', 'dir/cpan.txt', 'http://search.span.org']
--
HTH,
Rob
--
http://mail.python.org/mailman/listinfo/python-list
Re: emacs python debugging: pydb or pdb fringe interaction
Paul Rudin <[EMAIL PROTECTED]> writes: > I can't get the gdb fringe interaction functionality to work with > either pdb or pydb. Any hints as to versions or incantations I should > try? It works for me on Debian Etch and GNU Emacs 21.4.1. I'm using this settings: (setq pdb-path '/usr/lib/python2.4/pdb.py gud-pdb-command-name (symbol-name pdb-path)) (defadvice pdb (before gud-query-cmdline activate) "Provide a better default command line when called interactively." (interactive (list (gud-query-cmdline pdb-path (file-name-nondirectory buffer-file-name) -- HTH, Rob -- http://mail.python.org/mailman/listinfo/python-list
Re: emacs python debugging: pydb or pdb fringe interaction
Paul Rudin <[EMAIL PROTECTED]> writes: > Unfortunately this doesn't make any difference for me, with either > emacs 22 or 21. I guess I'll just have to dig deeper into the code. So what happens after M-x pdb? -- http://mail.python.org/mailman/listinfo/python-list
Re: psycopg2 & large result set
Jon Clements wrote: > Hi All. > > I'm using psycopg2 to retrieve results from a rather large query (it > returns 22m records); unsurprisingly this doesn't fit in memory all at > once. What I'd like to achieve is something similar to a .NET data > provider I have which allows you to set a 'FetchSize' property; it > then retrieves 'n' many rows at a time, and fetches the next 'chunk' > after you read past the end of the current chunk. I suppose I could > use Python for .NET or IronPython but I'd rather stick with CPython > 2.5 if possible. psycopg2 is DB-API 2.0 [1]_ compliant, so you can use ``fetchmany`` method and set ``cursor.arraysize`` accordingly. [1] .. http://www.python.org/dev/peps/pep-0249/ -- HTH, Rob -- http://mail.python.org/mailman/listinfo/python-list
Re: Removing NS in ElementTree
"Sebastian Bassi" <[EMAIL PROTECTED]> writes:
> I would like to remove the namespace information from my elements and
> have just the tag without this information. This
> "{http://uniprot.org/uniprot}"; is preapended into all my output.
> I understand that the solution is related with "_namespace_map" but I
> don't know much more.
>
>
for x in eleroot[0]:
> print x.tag
> print x.text
Try this:
NS = "{http://uniprot.org/uniprot}";
for x in eleroot[0]:
x.tag = x.tag[len(NS):]
print x.tag
--
HTH,
Rob
--
http://mail.python.org/mailman/listinfo/python-list
Re: Create new processes over telnet in XP
Godzilla wrote:
> Hello,
>
> How do you create/spawn new processes in XP over telnet using python?
> I.e. I would like to create a new process and have it running in the
> background... when I terminate the telnet connection, I would what the
> spawned processes to keep running until I shut it off...
>
> I got the os.popen method to spawn a new process running in the
> backgroun, but not over telnet... tried os.popen[2, 3, 4] and also
> subprocesses.popen without any luck...
I don't know what kind of OS there is on that remote host you telnet
to.
The idea boils down to appropriate using of methods
`read_until` and `write` from class `telnetlib.Telnet`.
For more complicated stuff you can consider using pyexpect.
Here is a small example of connecting to HP-UX.
You can adjust that to your needs.
import telnetlib, time
def login(tn, login, passwd, prompt):
tn.read_until("login: ")
tn.write(login + "\n")
if passwd:
tn.read_until("Password: ")
tn.write(passwd + "\n")
tn.read_until(prompt)
time.sleep(2)
print "logged in"
def run_proc(tn, progname):
tn.write("nohup %s &\n" % progname)
tn.write("exit\n")
print "program <%s> running" % progname
def kill_proc(tn, login, prompt, progname):
tn.write("ps -u %s\n" % login)
buf = tn.read_until(prompt)
pid = get_pid(buf, progname)
if not pid:
print "program <%s> not killed" % progname
tn.write("exit\n")
return
tn.write("kill -TERM %s\n" % pid)
tn.write("exit\n")
print "program <%s> killed" % progname
def get_pid(buf, progname):
pid, comm = None, None
for line in buf.split("\n"):
try:
pid, _, _, comm = line.split()
except ValueError:
continue
if comm == progname:
return pid
tn = telnetlib.Telnet(HOST, PORT)
#tn.set_debuglevel(1)
login(tn, "login", "passwd", "/home/user")
run_proc(tn, "python ~/test.py")
#kill_proc(tn, "login", "/home/user", "python")
--
HTH,
Rob
--
http://mail.python.org/mailman/listinfo/python-list
Re: Create new processes over telnet in XP
"Godzilla" <[EMAIL PROTECTED]> writes: > Rob, I would be logging into another XP machine to do some software I was afraid of that. :) > installation... the code you provided, correct me if I'm wrong, seems > to work under Unix/Linux. This part of running and killing processes, yes. > Any idea how to do the equivalent in XP? You could use windows services, for example: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/115875 But I don't know details, because this is not my favourite OS. :) -- Regards, Rob -- http://mail.python.org/mailman/listinfo/python-list
Re: Tkinter <> and bindtags ordering
bytecolor wrote:
[...]
> changing = False
> root = tk.Tk()
> t = tk.Text(master=root)
> t.pack()
> t.focus_set()
> t.tk.call(t._w, 'edit', 'modified', 0)
What about instead of:
> t.bind('<>', text_changed)
this event:
t.bind('', text_changed)
> root.mainloop()
--
HTH,
Rob
--
http://mail.python.org/mailman/listinfo/python-list
Re: Tkinter <> and bindtags ordering
bytecolor wrote: > Hey Rob, > I actually started with that event, until I came across the modified > event. I'm working on syntax highlighting. So I need any text change. > Also, colorizing on a key release is annoyingly noticeable to the > user. I tried it :) > > I'm sure there are going to be other perils along the way as this is > my first attempt at syntax highlighing. I can load a file and the > highlighting works very well. I used an elaborate regex with named > groups and re.finditer(). I either use the names directly as edit > tags, or they help me look up other tags in a dict. It's quite fast. > > screenshot with random (ugly) colors: > http://bytecolor.homelinux.org/~bytecolor/vapt_colorizing.png > > That part wasn't bad at all. Now I need to code the text change > logistics but this bindtags ordering has got me perplexed. Have you looked at ColorDelegator.py from idlelib? There has been done such a syntax highlighting based on Tkinter.Text. -- HTH, Rob -- http://mail.python.org/mailman/listinfo/python-list
Re: real time updating of popen, bufsize=0 problems
"ianaré" <[EMAIL PROTECTED]> writes:
> hey all, I'm trying to get real time updates of batch file output.
[...]
> So I tried subprocess:
> proc = subprocess.Popen('"C:/path/to/test.bat"', bufsize=0,
> stdout=subprocess.PIPE)
Instead of that:
> for line in proc.stdout:
> self.display.WriteText(line)
try that:
while True:
line = proc.stdout.readline()
if not line: break
self.display.WriteText(line)
When a file is used in a for loop it works like an iterator.
You can read details here (description of method ``next``):
http://docs.python.org/lib/bltin-file-objects.html
--
HTH,
Rob
--
http://mail.python.org/mailman/listinfo/python-list
Re: About Eggs
Mark Elston <[EMAIL PROTECTED]> writes: > This is probably a *really* stupid question but... > I have looked at all the documentation I have for 2.4.3 > and all the docs I can download for 2.5 and I simply cannot > find anything, anywhere that documents what egg files are. > > I have read posts referring to them and have been able to > deduce that they are some form of zip file for the distribution > of modules but beyond that I cannot find *any* docs for them > anywhere. Start here: http://peak.telecommunity.com/DevCenter/setuptools -- HTH, Rob -- http://mail.python.org/mailman/listinfo/python-list
Re: sqlite3 question
Jorgen Bodde wrote:
> All I can think of is a 'crappy' construction where I use the iterator
> to see if there was something in there, but surely, there must be a
> better way to know?
>
> >>> r = c.execute('select * from song where id = 2')
> >>> notfound = True
> >>> for s in r:
> ... notfound = False
> ... print s
> >>> if notfound:
> ... print 'No rows'
>
> I am pretty new with Python, maybe there are some properties of an
> iterator / sqlite3 I am not aware of that can tell me how many rows
> are there?
What about this:
if not c.fetchone():
print "No rows"
or
print "rowcount=", len(cur.fetchall())
--
HTH,
Rob
--
http://mail.python.org/mailman/listinfo/python-list
Re: Boost Problem! Boost.Build not found
Soren wrote: > Unable to load Boost.Build: could not find "boost-build.jam" > --- > Attempted search from C:\boost\boost_1_33_1\libs\python\example > \tutorial up to t > he root and in these directories from BOOST_BUILD_PATH and BOOST_ROOT: > C:\boost\boost_1_ > 33_1. > Please consult the documentation at 'http://www.boost.org'. > > Can anyone please tell me what I am doing wrong?? Theres no tutorial > on how to make a boost-build.jam file.. and as I understand I don't > need one as long as I set BOOST_BUILD_PATH .. Try to create boost-build.jam file like this: # boost-build.jam boost-build C:\boost\boost_1_33_1\tools\build\v1 ; -- HTH, Rob -- http://mail.python.org/mailman/listinfo/python-list
Re: Boost Problem! Boost.Build not found
Soren wrote: > > Try to create boost-build.jam file like this: > > > > # boost-build.jam > > boost-build C:\boost\boost_1_33_1\tools\build\v1 ; > > > Hi Rob, Thanks for the answer! > > It did solve the error.. but produced a new one: > > C:\boost\boost_1_33_1\libs\python\example\tutorial>bjam -sTOOLS=vc-8_0 > Unable to load Boost.Build: could not find build system. > - > C:\boost\boost_1_33_1\libs\python\example\boost-build.jam attempted to > load the > build system by invoking > >'boost-build C:/boost/boost_1_33_1/tools/build/v1 ;' > > but we were unable to find "bootstrap.jam" in the specified directory > or in BOOST_BUILD_PATH (searching C:\boost\boost_1_33_1, C:/boost/ > boost_1_33_1/t > ools/build/v1). There is something wrong with your boost installation. Do you have subdirectory tools/build/v1 in your installation? > > What is bootstrap.jam? .. Haven't seen that one in the short > tutorial... It is essential for boost build system that the file bootstrap.jam could be found. -- HTH, Rob -- http://mail.python.org/mailman/listinfo/python-list
Re: why does Configparser change names to lowercase ?
stef mientki <[EMAIL PROTECTED]> writes:
> hello,
>
> Why does Configparser change names to lowercase ?
>
> As Python is case sensitive (which btw I don't like at all ;-)
> but now when really need the casesensitivity,
> because it handles about names which should be recognized by human,
> it changes everything to lowercase
I don't know why, but I know how to change it and I found the solution here:
http://docs.python.org/lib/RawConfigParser-objects.html
You need to change the implementation of method `optionxform`, e.g.:
# config
[section1]
option1=item1
Option2=item2
option2=item3
# cfg.py
from ConfigParser import ConfigParser
config = ConfigParser()
config.optionxform = str
config.read('config')
print config.get('section1', 'option1')
print config.get('section1', 'Option2')
print config.options('section1')
HTH,
Rob
--
http://mail.python.org/mailman/listinfo/python-list
Re: Normalize a polish L
Peter Bengtsson <[EMAIL PROTECTED]> writes:
> In UTF8, \u0141 is a capital L with a little dash through it as can be
> seen in this image:
> http://static.peterbe.com/lukasz.png
>
> I tried this:
import unicodedata
unicodedata.normalize('NFKD', u'\u0141').encode('ascii','ignore')
> ''
>
> I was hoping it would convert it it 'L' because that's what it
> visually looks like. And I've seen it becoming a normal ascii L before
> in other programs such as Thunderbird.
>
> I also tried the other forms: 'NFC', 'NFKC', 'NFD', and 'NFKD' but
> none of them helped.
>
> What am I doing wrong?
I had the same problem and my little research revealed that the problem
is caused by unicode standard itself. I don't know why
but characters with stroke don't have canonical equivalent.
I looked into this file:
http://unicode.org/Public/UNIDATA/UnicodeData.txt
and compared two positions:
1.
0142;LATIN SMALL LETTER L WITH STROKE;Ll;0;L;N;LATIN SMALL LETTER L SLASH \
;;0141;;0141
0141;LATIN CAPITAL LETTER L WITH STROKE;Lu;0;L;N;LATIN CAPITAL LETTER L
SLASH \
;;;0142;
2.
0105;LATIN SMALL LETTER A WITH OGONEK;Ll;0;L;0061 0328N;LATIN SMALL LETTER
A OGONEK \
;;0104;;0104
In the second position there is in the 6-th field canonical equivalent
but in the 1-st there is nothing. I don't know what justification
is behind that, but probably there is something. ;)
Regards,
Rob
--
http://mail.python.org/mailman/listinfo/python-list
Re: A Python 3000 Question
brad <[EMAIL PROTECTED]> writes: > Will len(a_string) become a_string.len()? I was just reading > > http://docs.python.org/dev/3.0/whatsnew/3.0.html > > One of the criticisms of Python compared to other OO languages is that > it isn't OO enough or as OO as others or that it is inconsistent. And > little things such as this seem to support those arguments. Not that > it matters really... just seems that classes with methods used in a > more consistent manner would be more appropriate in an OO > langauage. Is there a reason that len cannot be a method? > > a_string.lower() makes sense, as does a_string.split(), > a_string.strip()... why not a_string.len()? I wonder why people always complain about `len` function but never about `iter` or `pprint.pprint`? :) And to answer the question. In OO programming generic functions are no less important than classes and objects. Regards, Rob -- http://mail.python.org/mailman/listinfo/python-list
Re: Question about compiling.
Gabriel Genellina <[EMAIL PROTECTED]> writes: > At Tuesday 9/1/2007 14:56, Steven W. Orr wrote: > >>I *just* read the tutorial so please be gentle. I created a file called >>fib.py which works very nicely thank you. When I run it it does what it's >>supposed to do but I do not get a resulting .pyc file. The tutorial says I >>shouldn't do anything special to create it. I have machines that have both >>2.4.1 and 2.3.5. Does anyone have an idea what to do? > > Welcome to Python! > When you run a script directly, no .pyc file is generated. Only when a > module is imported (See section 6.1.2 on the tutorial). And don't > worry about it... That's not the whole truth. :) If you want to compile your script, you can do that, of course: $ ls fib* fib.py $ python2.4 -mpy_compile fib.py $ ls fib* fib.py fib.pyc -- HTH, Rob -- http://mail.python.org/mailman/listinfo/python-list
Re: module file
Imbaud Pierre <[EMAIL PROTECTED]> writes: > I am willing to retrieve the file an imported module came from; > module.__file__, or inspect.getfile(module) only gives me the > relative file name. How do I determine the path? >>> import os >>> os.path.abspath(module.__file__) -- HTH, Rob -- http://mail.python.org/mailman/listinfo/python-list
Re: How to respond to a confirmation prompt automatically
"Coby" <[EMAIL PROTECTED]> writes:
> Just to give you some background about my problem:
>
> I execute os.system(command), where command is a string.
>
> On the command line in windows, I get:
>
> "Continue, and unload these objects? [no]"
>
> I need to respond 'y' to continue, but I am uncertain on how to output
> the 'y' automatically.
You need to use pipe.
1.
p = os.popen(command, "w")
p.write("y\n")
http://docs.python.org/lib/os-newstreams.html#os-newstreams
2.
from subprocess import Popen, PIPE
p = Popen(command, shell=True, stdin=PIPE)
p.stdin.write("y\n")
http://docs.python.org/lib/module-subprocess.html
--
HTH,
Rob
--
http://mail.python.org/mailman/listinfo/python-list
Re: module email
"Sergey Dorofeev" <[EMAIL PROTECTED]> writes:
> Hello.
>
> Why does not work?
[...]
> m=email.message.Message()
[...]
> p2=email.message.Message()
> p2.set_type("message/rfc822")
> p2.set_payload(m)
Payload is a _list_ of Message objects (is_multipart() == True)
or a _string_ object (is_multipart() == False) but never just Message object.
http://docs.python.org/lib/module-email.message.html
--
HTH,
Rob
--
http://mail.python.org/mailman/listinfo/python-list
Re: module email
Sergey Dorofeev wrote:
> "Rob Wolfe" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED]
>
> >> p2=email.message.Message()
> >> p2.set_type("message/rfc822")
> >> p2.set_payload(m)
> >
> > Payload is a _list_ of Message objects (is_multipart() == True)
> > or a _string_ object (is_multipart() == False) but never just Message
> > object.
>
> 1. If I give m.as_string() into set_payload, result is the same.
The payload of a message/rfc822 is treated like a sequence
of length 1. So that works:
p2.set_payload([m])
> 2. I don't understand, how message/rfc822 section can accept a list of two
> or more messages. Can you explain?
That's another question.
I don't understand either, why the payload for message/rfc822 has to be
a list of length 1 and not a Message object itself.
This assumption looks strange to me, too, but I can live with that. :)
--
Regards,
Rob
--
http://mail.python.org/mailman/listinfo/python-list
Re: howto redirect and extend help content ?
Stef Mientki <[EMAIL PROTECTED]> writes: > I'm making special versions of existing functions, > and now I want the help-text of the newly created function to exists of > 1. an extra line from my new function > 2. all the help text from the old function > > # the old function > def triang(M,sym=1): > """The M-point triangular window.<== old help text > """ > > > # the new function > def chunked_triang(M): > """ Chunked version of "triang" <== the extra line > """ > > >>> help(chunked_triang) > # should give something like > > chunked_triang(M)<== the new definition > Chunked version of "triang" <== the extra line > The M-point triangular window. <== old help text > > Is that possible ? You can take advantage of the decorator syntax: >>> def triang(M,sym=1): ... """The M-point triangular window. ... """ ... return "triang" ... >>> help(triang) Help on function triang in module __main__: triang(M, sym=1) The M-point triangular window. >>> def add_doc(f): ... def wrap(g): ... g.__doc__="chunked version of %s\n%s" % (f.__name__,f.__doc__) ... return g ... return wrap ... >>> @add_doc(triang) ... def chunked_triang(M): ... return "chunked triang" ... >>> help(chunked_triang) Help on function chunked_triang in module __main__: chunked_triang(M) chunked version of triang The M-point triangular window. -- HTH, Rob -- http://mail.python.org/mailman/listinfo/python-list
Re: string byte dump
Jammer <[EMAIL PROTECTED]> writes:
> Does anyone that knows python want to write me a byte dump for strings? :-)
>
> I am trying to modify a plugin (that someone else wrote) that uses
> interprocess communication.
> It works on strings without special characters but it fails on other
> stings like "Björk".
>
> It calls decode('utf8') but I guess the strings are not utf8 so I need
> to find out what is being input.
Try this:
>>> "abc".encode("hex")
'616263'
--
HTH,
Rob
--
http://mail.python.org/mailman/listinfo/python-list
Re: Help needed on config files
jvdb wrote:
> Hi there,
>
> I am quite new on python programming and need some help on solving my
> problem..
>
> I have to make a (python) program which deletes files from
> directories. I don't think deleting, etc. is the problem. The problem
> is that the directories where i have to delete them are 'dynamic'/
> subject to change. So what i thought is to make a config file
> containing an identifier (useful for myself) and there the directory.
> something like:
> [PROJECTx]
>
> [PROJECTy]
>
What about this?
# proj.cfg
[PROJECTx]
path=/path/to/dir1
[PROJECTy]
path=/path/to/dir2
# cfg.py
from ConfigParser import ConfigParser
cfg = ConfigParser()
cfg.read("proj.cfg")
for proj in cfg.sections():
path = cfg.items(proj)[0][1]
print "proj: %s, path: %s" % (proj, path)
Is that not enough?
--
HTH,
Rob
--
http://mail.python.org/mailman/listinfo/python-list
Re: PYTHONPATH or any other way to set seachpath (winXP) ?
Stef Mientki <[EMAIL PROTECTED]> writes:
> Is it possible to change the searchpath for modules on the flight,
> under winXP ?
> Most preferred is some command to extend the searchpath.
> (the environment variable PYTHONPATH needs a reboot)
Do you mean something like that?
>>> import some_module
Traceback (most recent call last):
File "", line 1, in ?
ImportError: No module named some_module
>>> import sys
>>> sys.path.append("..")
>>> import some_module
http://docs.python.org/tut/node8.html#SECTION00811
--
HTH,
Rob
--
http://mail.python.org/mailman/listinfo/python-list
Re: python references
[EMAIL PROTECTED] wrote: > >>> from Numeric import zeros > >>> p=zeros(3) > >>> p > array([0,0,0]) > >>> p[0] > 0 > >>> x=p[0] `x' is now a reference to immutable integer object with value 0, not to first element of array `p' > >>> x=10 now `x' is a reference to immutable integer object with value 10, array doesn't change > >>> p > array([0,0,0]) #actual behavior > #array([10,0,0]) #desired behavior > > I want x to be a C++-esque reference to p[0] for convenience in a > vector3 class. i dont want accessor methods. i know python can do > this, but it's been a long time since I used it and am unsuccessful in > my googling and docreading. a little help please? You can have such a reference to mutable objects. Consider this: >>> p = [[0,0,0], [0,0,0]] >>> x = p[0]# reference to mutable list object >>> x[0] = 10 >>> p [[10, 0, 0], [0, 0, 0]] -- HTH, Rob -- http://mail.python.org/mailman/listinfo/python-list
Re: calling php function from python
mark wrote: > is it possible to call a php function from python and use a class from > php in python? i want to use mmslib which creates mms messages and the > only implementation is a php mmslib implementation. You can consider to use some kind of RPC (remote procedure call) for example XML-RPC. This is a platform and language independent solution. Here you have some information: http://www.faqs.org/docs/Linux-HOWTO/XML-RPC-HOWTO.html http://groups.google.pl/group/comp.lang.python/msg/5a6ae6290593fc97 -- HTH, Rob -- http://mail.python.org/mailman/listinfo/python-list
Re: rot13 in a more Pythonic style?
"Andy Dingley" <[EMAIL PROTECTED]> writes:
> I'm trying to write rot13, but to do it in a better and more Pythonic
> style than I'm currrently using. What would you reckon to the
> following pretty ugly thing? How would you improve it? In
> particular, I don't like the way a three-way selection is done by
> nesting two binary selections. Also I dislike stating the same
> algorithm twice, but can't see how to parameterise them neatly.
It looks to me like a good place to use closure and dictionaries.
I would write it this way:
def rot(step):
import string
rot_char = lambda a,c,step=step: chrord(c) - ord(a)) + step) % 26) +
ord(a))
make_dict = lambda a,s: dict([(x, rot_char(a, x)) for x in s])
d = make_dict('a', string.ascii_lowercase)
d.update(make_dict('A', string.ascii_uppercase))
def f(s):
return "".join([d.get(c) or c for c in s])
return f
>>> rot13 = rot(13)
>>> rot13('Sybevk Tenohaqnr, Fcyhaqvt ihe guevtt')
'Florix Grabundae, Splundig vur thrigg'
>>> rot_13 = rot(-13)
>>> rot_13('Florix Grabundae, Splundig vur thrigg')
'Sybevk Tenohaqnr, Fcyhaqvt ihe guevtt'
--
HTH,
Rob
--
http://mail.python.org/mailman/listinfo/python-list
