Re: Python serial data aquisition
Hello Flávio, > My problem is to how to recover my reading from these bytes, since > pyserial gives me a character (string) from each byte... I dont know > how to throw away the unneeded bits and concatenate the remaining > bits to form a number... See the array module. Also http://tebeka.bizhat.com/Software/bitter.py HTH. Miki -- http://mail.python.org/mailman/listinfo/python-list
Re: packaging python for install.
Hello J, >I have created an App that embedds the python interpreter and I am >now in the process of creating an installer. I am currently linking >python24.lib, but it is only 184k and I suspect that it imports other >dlls... I am also using numarray. Does anyone have any experiences in >packaging python with an application in a single installer ? Has that >been done before ? http://starship.python.net/crew/theller/moin.cgi/ShippingEmbedded HTH, Miki -- http://mail.python.org/mailman/listinfo/python-list
Re: Step by step: Compiling extensions with MS Visual C++ Toolkit 2003 - msvccompiler-patch.txt (0/1)
Hello Martin, Martin Bless wrote: [Something very long ...] Why don't just use MingW32? Download it from http://prdownloads.sf.net/mingw/MinGW-3.1.0-1.exe?download (14.8MB) and install. Write your extension module and setup.py and then run: python setup.py build --compiler=mingw32 That's all! You'll have a working .pyd ready to rock. Miki -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie question: what's with "self"?
Hello, > I'm new to both Python and OO programming. From looking at a number of > code examples, the word "self" is used a lot when referring to classes. > As such, what does "self" mean and/or do? I've read things that say > it's a naming convention, but no-one has really spelt it out (in idiot > form!) in a way I can understand. Note that apart from what all the other pepole said, "self" is not a reserved word. It's just the wide convention that we use the name "self". If you know C++/Java then "self" is like "this". HTH, Miki http://pythonwise.blogspot.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Looking for an intellisense with good help IDE for Python
Hello Terrence, > I would like an IDE that shows me all methods and functions I can call > on a particular data item. For instance, iter() can be called on any > sequence, but it is not a method. > > Nonetheless, I would like for something to show me every thing that I > can call on a particular data item. > > This includes % after a string. > > I would also like browseable help with good examples on whatever > methods and functions and operators it pops up. The IDLE that will come (soon) with Python 2.5 with have some intellisense. Not all that you requested but some of it. HTH, Miki http://pythonwise.blogspot.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Which Python API for PostgreSQL?
Hello Scott, > Which one do you use? psycopg2 (http://initd.org/tracker/psycopg/wiki/PsycopgTwo) > What do you like about it? Compiles and works. Has support for Postgres array types. Also thread safe. HTH, Miki http://pythonwise.blogspot.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Getting previous file name
Hello hj, > I have a small script here that goes to inside dir and sorts the file > by create date. I can return the create date but I don't know how to > find the name of that file... > I need file that is not latest but was created before the last file. > Any hints... I am newbiw python dude and still trying to figure out lot > of 'stuff'.. > > ... Remember that Python comes with "battaries included": #!/usr/bin/env python from os import walk from os.path import getctime, join def cmp_file_by_ctime(file1, file2): return cmp(getctime(file1), getctime(file2)) def walktree(path): file_list = [] for root, dirs, files in walk(path): file_list += [join(root, file) for file in files] file_list.sort(cmp_file_by_ctime) return file_list[-2] HTH, Miki http://pythonwise.blogspot.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Accessing Yahoo Mail withtout POP
Hello T, > Is there a way to access yahoo mail via its web interface? If so, can > someone give some pointers? http://www.crummy.com/software/BeautifulSoup/ http://wwwsearch.sourceforge.net/ClientForm/ HTH, Miki http://pythonwise.blogspot.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Import module with non-standard file name
Hello Ben, > Question: I have Python modules named without '.py' as the extension, > and I'd like to be able to import them. How can I do that? http://docs.python.org/lib/module-imp.html (hint: load_source :) HTH, Miki http://pythonwise.blogspot.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Projects Continuous Integration
Hello Dave, > I'm just starting a development project in Python having spent time in > the Java world. I was wondering what tool advice you could give me > about setting up a continuous integration environment for the python > code: get the latest source, run all the tests, package up, produce the > docs, tag the code repository. I'm used to things like Maven and > CruiseControl in the Java world. If you are familiar with CruiseControl and Maven then it shouldn't be too complicated to write a Maven file that run the tests, package up, produce the docs. CruiseControl can take care of all the rest. I also found that writing a simple Continuous integration system myself was a very simple task in Python, it might be a good choice as well. (I resorted to this solution after giving up on trying to install Java on OpenBSD.) HTH, Miki http://pythonwise.blogspot.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: How to get database metadata information (i.e. existing tables and columns in tables)
Hello Chris, > Is it possible to retrieve details about the database, specifically a > list of the tables in the database; and then to retrieve the columns > and their types for the tables? > > Is this dependant on the database? Yes and Yes. However some toolkits like SQLObject (http://www.sqlobject.org/) and SQLAlchemy (http://www.sqlalchemy.org/) can do this work for you (IIRC). HTH, Miki http://pythonwise.blogspot.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: IDLE with python 2.5
Hello Emmanuel, > I've just read in Python 2.5 description that IDLE 'executes code in a > separate process', using a TCP connection on port 127.0.0.1 to > communicate. This is older than 2.5 (for sure it's in 2.4, can't remember if it was in 2.3) > Does it mean that we can now debug embedded python with IDLE ? I don't think so, it just open a new "python.exe" process and communicates with it via TCP. HTH, Miki http://pythonwise.blogspot.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: HTMLParser chokes on bad end tag in comment
Hello Rene, You can also check out BeautifulSoup (http://www.crummy.com/software/BeautifulSoup/) which is less strict than the regular HTML parser. HTH, Miki http://pythonwise.blogspot.com/ -- http://mail.python.org/mailman/listinfo/python-list
Yet Another Python Blog
Hello All, Decided that there are not enough blogs out there so http://pythonwise.blogspot.com/ is up :) This blog will feature a weekly (or about) Python code examples. I'll be glad to hear your comments. Miki, http://pythonwise.blogspot.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: can't find win32api from embedded pyrun call
Hello Jim, > // Py_Initialize(); > Py_InitializeEx(0); > PyRun_SimpleString("from win32com.client import *"); > > Here's what it does on the last line: > > File "D:\Python\Lib\site-packages\win32com\__init__.py", line 5, in ? > import win32api, sys, ok > ImportError: No module named win32api > > The same line runs fine in IDLE or at the command prompt. It also runs > without complaint if I run a release version of the app. To build the > debug version I had to build python42_d.lib/dll myself. The reason I > can't call PyInitialize is that it crashes with an "invalid signal" > error. > > I don't think it's a path issue -- I've checked system path, sys.path, > pythonpath env var, and the pythonpath entry in the registry, all of > them loaded with directories including the one with win32api.pyd. > Besides, if it were an install or path problem, why would it work at > the command prompt? IIRC you need to set the path explicitly in an embedded interpreter. See the code in "site.py" (which again IMO is *not* imported when the interpreter starts). HTH, Miki http://pythonwise.blogspot.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: need all python dialog equivalent
Hello Eric, > Is there anything like an all Python dialog equivalent floating around? http://www.pythonware.com/library/tkinter/introduction/ HTH, -- Miki http://pythonwise.blogspot.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: sys.argv[0] doesn't always contain the full path of running script.
Hello Max, > How can I find where exactly the current python script is running? > ... > That means sys.argv[0] doesn't always contain the full path of > running script. sys.path[0] is the script directory, combined with sys.argv[0] you can find the full path to the script. (Note that in some rare cases sys.path[0] might not contain the script directory. For example in an executable created by py2exe). HTH. -- Miki http://pythonwise.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: How to get the package, file, and line of a method/function invocant?
> > I am looking for something like the caller() routine in Perl: > >http://perldoc.perl.org/functions/caller.html > > Look at the inspect module in Python's standard library. Or is you're feeling lazy, have a look at the "here" function found in http://www.unixreview.com/documents/s=9133/ur0404e/ur0404e_listing1.htm -- Miki http://pythonwise.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Forgetting an import
Hello, > I imported a set of functions from a file I wrote to interpreter > shell: > > from myFile import * > > Now if I change functions in this file how can I make python forget it > so I can force a fresh import? "import *" is evil for many reasons, this is one of them :) >>> import my_module >>> my_module.add(1, 1) 4 [Hack] >>> reload(my_module) >>> my_module.add(1, 1) 2 HTH, -- Miki <[EMAIL PROTECTED]> http://pythonwise.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Pattern Classification Frameworks?
Hello Evan, > What frameworks are there available for doing pattern classification? > ... Two Bayesian classifiers are SpamBayes (http://spambayes.sf.net) and Reverend Thomas (http://www.divmod.org/projects/reverend). IMO the latter will be easier to play with. > Also, as a sidenote, are there any texts that anyone can recommend to > me for learning more about this area? A good book about NLP is http://nlp.stanford.edu/fsnlp/ which have a chapter about text classification. http://www.cs.cmu.edu/~tom/mlbook.html has some good coverage on the subject as well. HTH. -- Miki Tebeka <[EMAIL PROTECTED]> http://pythonwise.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: web page text extractor
Hello jk, > For a project, I need to develop a corpus of online news stories. I'm > looking for an application that, given the url of a web page, "copies" > the rendered text of the web page (not the source HTNL text), opens a > text editor (Notepad), and displays the copied text for the user to > examine and save into a text file. Graphics and sidebars to be > ignored. The examples I have come across are much too complex for me > to customize for this simple job. Can anyone lead me to the right > direction? Going simple :) from os import system from sys import argv OUTFILE = "geturl.txt" system("lynx -dump %s > %s" % (argv[1], OUTFILE)) system("start notepad %s" % OUTFILE) (You can find lynx at http://lynx.browser.org/) Note the removing sidebars is a very difficult problem. Search for "wrapper induction" to see some work on the subject. HTH, -- Miki <[EMAIL PROTECTED]> http://pythonwise.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Break up list into groups
Hello Dan, Yet another option (using itertools.groupby): from itertools import groupby class GrouperToggler: def __init__(self): self.group = 1 def __call__(self, value): # New packet, toggle group if value & 0x80: self.group = 1 - self.group return self.group def group(items): for group, items in groupby(items, GrouperToggler()): # groupby return [key, group_iterator] yield [item for item in items] i = [ 0xF0, 1, 2, 3, 0xF0, 4, 5, 6, 0xF1, 7, 8, 0xF2, 9, 10, 11, 12, 13, 0xF0, 14, 0xF1, 15 ] for g in group(i): print g HTH, -- Miki <[EMAIL PROTECTED]> http://pythonwise.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Script to POST to web page with cookies?
Hello Gille, > I need to write a script to automate fetching data from a web site: > 1. using the POST method, log on, with login/password saved as cookies > 2. download page and extract relevent information using regexes > 3. log off > 4. wait for a random number of minutes, and GOTO 1 > ... http://wwwsearch.sourceforge.net/mechanize/ HTH, -- Miki <[EMAIL PROTECTED]> http://pythonwise.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Python C Embedded ! Attribute Error
Hello, > I am using the below C code so that i can embed a Python Code and > get input from a python function and use it in C code . > > Below is the C Code [snipped] > I am getting error > > AttributeError: 'module' object has no attribute 'print' > Cannot find function "print" How do you run your program (I suspect with 'pr pr print 1', should be 'pr pr pr 1'). FWIW, the following simplified program works: #include int main(int argc, char *argv[]) { PyObject *modname, *module, *args, *value, *func; Py_Initialize(); PyRun_SimpleString("import sys; sys.path.append(\".\")"); modname = PyString_FromString("pr"); module = PyImport_Import(modname); Py_DECREF(modname); if (NULL == module) { fprintf(stderr, "error: can't load\n"); Py_Finalize(); return 1; } func = PyObject_GetAttrString(module, "pr"); args = PyTuple_New(1); value = PyLong_FromLong(10); PyTuple_SetItem(args, 0, value); PyObject_CallObject(func, args); Py_Finalize(); return 0; } HTH, -- Miki <[EMAIL PROTECTED]> http://pythonwise.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: code packaging
Hello Paul, > I'm now wondering where this type of thing is best addressed in more > general terms. What I usually see happening, in projects I've worked > on and in others, is that developers get the code working on their own > computers, using source control tools and (if we're lucky) tests > developed in parallel with the code, but without much attention to > final packaging until the very end when the code is about to be > shipped. [snipped] IMO you should invest the time a build automated packaging and some smoke tests for the product. After this is done, start using some "continuous automation" tools (like http://cruisecontrol.sourceforge.net/, http://buildbot.net/trac and others). HTH, -- Miki <[EMAIL PROTECTED]> http://pythonwise.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: how to find a lable quickly?
Hello Frank, > I am a new user on Python and I really love it. The more you know, the deeper the love :) > I have a big text file with each line like: > > label 3 > teststart 5 > endtest 100 > newrun 2345 > > I opened the file by uu=open('test.txt','r') and then read the data as > xx=uu.readlines() This reads the whole file to memory, which might be a problem. > In xx, it contains the list of each line. I want to find a spcefic labels > and read the data. Currently, I > do this by > for ss in xx: >zz=ss.split( ) > if zz[0] = endtest: > index=zz[1] > > Since the file is big and I need find more lables, this code runs slowly. > Are there anyway to speed up the process? I thought to convert the data xx > from list to a dictionay, so I can get the index quickly based on the > label. Can I do that effeciently? IMO a better way is either to not load the whole file to memory: # Untested labels = {}.fromkeys(["endtest", "other_label"]) for line in open("test.txt"): label, value = line.split() if label in labels: labels[label] = value.strip() Another option is to use an external fast program (such as egrep): from os import popen labels = {} for line in popen("egrep 'endtest|other_label' test.txt"): label, value = line.strip().split() labels[label] = value HTH, -- Miki <[EMAIL PROTECTED]> http://pythonwise.blogspot.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie and Page Re-Loading
Hello Richard, > I do not want to run a framework yet. I would like to understand > python at script level, before adding more aspects to learn, like > frameworks. The way CGI works is that your script is called every time the corresponding HTML is loaded. You can access all the parameters sent to the script using cgi.FieldStorage. > I think I get your idea about hidden fields and how to alter them. Note that hidden fields are passed in plain text format from/to the server, don't send anything sensitive in them. > My single page script should work something like this > > DisplayHTMLHeaderandBodyHeader > Check if this is a Re-Load (HiddenField would not exist first time I > am assuming) It could be None: cgi.FieldStorage().getvalue("hidden_attribute") == None > Display SearchSection with previous SearchRequest > If SearchRequest is True: Get and Display Results > Display TrailerHTMLandTrailerBody > > . Wait for NewSearch or NextPage In CGI you don't wait, the script exists and called again when use hits a button/refresh ... > Does the above make sense or is there a better way ? There are many other ways (AJAX, Web frameworks, FastCGI ...). However I'd recommend you start with plain CGI which is *simple*. Here is a small example: #!/usr/local/bin/python import cgitb; cgitb.enable() # Show errors in HTML output from cgi import FieldStorage FUNNY = [ "mickey", "donald", "daisy", "minnie", "goofy" ] def main(): print "Content-Type: text/html" print form = FieldStorage() query = form.getvalue("query", "") print ''' Disney Search ''' % query if query: for someone in FUNNY: if query in someone: print "%s" % someone print "" if __name__ == "__main__": main() > How do I get the directory of my modules into the Python Path import sys sys.path.append("/path/to/my/modules") Note that your script directory is automatically added to the path. > Is there a lightweight Https Server I could run locally (WINXP), which > would run .py scripts, without lots of installation modifications ? http://lighttpd.net. Make sure "mod_cgi" is uncommented, set your document root and set right python interpreter in cgi.assign HTH, -- Miki <[EMAIL PROTECTED]> http://pythonwise.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Typed named groups in regular expression
Hello Hugo, > Is it possible to "automagically" coerce the named groups to python types? > e.g.: Not that I know of, however I use the following idiom: match = my_regexp.find(some_string) def t(name, convert=str): return convert(match.group(name)) myint = t("field1", int) HTH, -- Miki <[EMAIL PROTECTED]> http://pythonwise.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: how to use python to checking password on servlet
Hello sandeep, > my application design on java servlet i want to check password in > python & return result again servlet to forward to next page. > how to set session in python .get session It depends on the web platform you use, can you elaborate more? (To make the browser send a GET method, just specify it using the form METHOD="GET" attribute). HTH. -- Miki <[EMAIL PROTECTED]> http://pythonwise.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: OSError[Error 5]
Hello SamG, > I do this on PowerPC.. > > >>> import os > >>> os.listdir('/usr/bin') > > And endup getting this ... > > OSError: [Error 5] Input/output error:/usr/bin What happens when you run "ls /usr/bin" in the terminal? HTH, -- Miki <[EMAIL PROTECTED]> http://pythonwise.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Website data-mining.
Hello, > I'm using Python for the first time to make a plug-in for Firefox. > The goal of this plug-in is to take the source code from a website > and use the metadata and body text for different kinds of analysis. > My question is: How can I retrieve data from a website? I'm not even > sure if this is possible through Python. Any help? Have a look at http://www.myinterestingfiles.com/2007/03/playboy-germany-ads.html for getting the data and at http://www.crummy.com/software/BeautifulSoup/ for handling it. HTH. -- Miki Tebeka <[EMAIL PROTECTED]> http://pythonwise.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Website data-mining.
Hello, > >> I'm using Python for the first time to make a plug-in for Firefox. > >> The goal of this plug-in is to take the source code from a website > >> and use the metadata and body text for different kinds of analysis. > >> My question is: How can I retrieve data from a website? I'm not even > >> sure if this is possible through Python. Any help? > > Have a look > > athttp://www.myinterestingfiles.com/2007/03/playboy-germany-ads.html > > Well, it's certainly interesting, but I'm not sure how it might help the OP > get data from a website... Ouch, let there be a lesson to me to *read* my posts before sending them :) Should have been http://wwwsearch.sourceforge.net/mechanize/. -- Miki (who can't paste) Tebeka [EMAIL PROTECTED] http://pythonwise.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: import * is not allowed ??
Hello Stef, > can anyone explain a little bit more what this error message means: > > import * is not allowed in function 'JAL_MAIN_RUN' because it contains > a nested function with free variables (JAL_simulation_file.py, line 22) > > what are "free variables" ? http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-10.html#%_idx_590 HTH, -- Miki <[EMAIL PROTECTED]> http://pythonwise.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Fast kNN from python
Hello, > I am looking for a Python implementation or bindings to a library that > can quickly find k-Nearest Neighbors given an arbitrary distance > metric between objects. Specifically, I have an "edit distance" > between objects that is written in Python. First Google search for "k-Nearest Neighbors python", yielded http://people.revoledu.com/kardi/tutorial/KNN/resources.html which pointed to http://biopython.org/DIST/docs/api/public/Bio.kNN-module.html HTH, -- Miki <[EMAIL PROTECTED]> http://pythonwise.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Is there a simple way to exit a while loop on keystroke?
Hello, > I am new to python, and have written a simple program to read a port > via telnet. I would like it to run until any key is pressed. Of > course I wouldn't mind requiring a specific keystroke in the future, > but I would think this is simpler for now. > > I have used kbhit() and getch() many times in C, but I can't find > anything similar in Python. I am using Linux also, so the msvcrt > code isn't an option. I have tried sys.stdin.read(), but that hangs > UNTIL a key is pressed. You might want to look at http://docs.python.org/lib/module-curses.html Another solution is to ask the user to hit CTRL-C from time import sleep try: while 1: print "BEEP" sleep(1) except KeyboardInterrupt: print "BYE BYE" HTH, -- Miki <[EMAIL PROTECTED]> http://pythonwise.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Spell-checking Python source code
>> In an ideal world, my IDE would do this with a red wavy line. > > You didn't mention which IDE you use; however, if you use Emacs, there > is flyspell-prog-mode which does that for you (checks your spelling > "on the fly", but only within comments and strings). Same in Vim (:set spell) HTH, -- Miki <[EMAIL PROTECTED]> http://pythonwise.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: debugging program that uses ctypes
Hello Marco, > hi all, I have a python program that calls a dll through ctypes > (py2.5). In some (reproducible) > conditions the program crashes with an error in ctypes module. > How can I trace down the problem? I have created a debug build of > python but I also use pyodbc > and dateutil libraries in my program and I don't know how to make them > visible to python_d.exe > Am I using the right approach? If you are the one compiling the called module, you can add `__asm int 3` somewhere in the code. When this is reached, the windows debugger will pop up on the line. HTH, -- Miki <[EMAIL PROTECTED]> http://pythonwise.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Using s.sort([cmp[, key[, reverse]]]) to sort a list of objects based on a attribute
> steps.sort(key = lambda s: s.time) This is why attrgetter in the operator module was invented. from operator import attrgetter ... steps.sort(key=attrgettr("time")) HTH, -- Miki <[EMAIL PROTECTED]> http://pythonwise.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: catching exceptions from an except: block
Hello Arnaud, > Imagine I have three functions a(x), b(x), c(x) that each return > something or raise an exception. Imagine I want to define a function > that returns a(x) if possible, otherwise b(x), otherwise c(x), > otherwise raise CantDoIt. Exceptions are for error handling, not flow control. > Here are three ways I can think of doing it: > ... > # This one only works because a,b,c are functions > # Moreover it seems like an abuse of a loop construct to me > def rolled_first(x): > for f in a, b, c: > try: > return f(x) > except: > continue > raise CantDoIt My vote is for that one. > I don't feel happy with any of these. Is there a more satisfying way > of doing this in Python? What I would like is something like: > > -- > # This one isn't correct but looks the clearest to me > def wished_first(x): > try: > return a(x) > except: > return b(x) > except: > return c(x) > except: > raise CantDoIt Again, exception are for error handling, not for flow control. As a side note, try to avoid "catch:", always catch explicit exceptions. HTH, Miki <[EMAIL PROTECTED]> http://pythonwise.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Subclassing: what is wrong here?
Hello Paulo, > What's wrong with this way of subclassing? > ... See http://sourceforge.net/tracker/index.php?func=detail&aid=1448640&group_id=5470&atid=105470 HTH, -- Miki <[EMAIL PROTECTED]> http://pythonwise.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: why brackets & commas in func calls can't be ommited? (maybe it could be PEP?)
Hello Dmitrey, > I looked to the PEPs & didn't find a proposition to remove brackets & > commas for to make Python func call syntax caml- or tcl- like: instead > of > result = myfun(param1, myfun2(param5, param8), param3) > just make possible using > result = myfun param1 (myfun2 param5 param8) param3 If you have result = func1 func2 arg is it result = func1(func2, arg) or result = func1(func2(arg)) Miki <[EMAIL PROTECTED]> http://pythonwise.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Making GIF image twice the size - in memory
Hello All, I get an image from a web page (via urlopen), and like to make it twice the size. I'm trying (using PIL): code from ImageFile import Parser def double(image_data): image_parser = Parser() image_parser.feed(image_data) im = image_parser.close() new_size = tuple(map(lambda x: 2 * x, im.size)) new = im.resize(new_size) return new.tostring("gif", "P") # This is probably the problem, have no idea image_data = urlopen(url).read() image_data = double(image_data) code However I don't get a valid GIF image. Any ideas? Thanks, Miki <[EMAIL PROTECTED]> http://pythonwise.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: p2p chat framework
Hello Ghirai, > Are there any p2p chat/filetransfer frameworks/examples floating > around? http://divmod.org/projects/shtoom HTH, -- Miki <[EMAIL PROTECTED]> http://pythonwise.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Parallel ping problems python puzzler
Hello, >def run(self): > # -w 1 option to ping makes it timeout after 1 second > pingcmd="/bin/ping -c 2 -q -i 0.3 -w 1 %s >/dev/null" % ip Not sure, but "ip" should be "self.ip", this might cause the problem. HTH, -- Miki <[EMAIL PROTECTED]> http://pythonwise.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: stop script w/o exiting interpreter
Hello Alan, > I'm fairly new to Python and I've lately been running a script at > the interpreter while working on it. Sometimes I only want to > run the first quarter or half etc. What is the "good" way to do this? If you want to exit from the program then "raise SystemExit" is what you want. If you want to enter the debugger, you can do: from pdb import set_trace ... set_trace() # Stop and execute debugger here. ... HTH, -- Miki http://pythonwise.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Help extracting info from HTML source ..
Hello Shelton, > I am learning Python, and have never worked with HTML. However, I would > like to write a simple script to audit my 100+ Netware servers via their web > portal. Always use the right tool, BeautilfulSoup (http://www.crummy.com/software/BeautifulSoup/) is best for web scraping (IMO). from urllib import urlopen from BeautifulSoup import BeautifulSoup html = urlopen("http://www.python.org";).read() soup = BeautifulSoup(html) for link in soup("a"): print link["href"], "-->", link.contents HTH, -- Miki http://pythonwise.blogspot.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie/ merging lists of lists with items in common
Hello, > Here is my problem: > I have a list that looks like this - > [['a', '13'], ['a', '3'], ['b', '6'], ['c', '12'], ['c', '15'], ['c', > '4'], ['d', '2'], ['e', '11'], ['e', '5'], ['e', '16'], ['e', '7']] > > and I would like to end up with something like this, i.e. with the > only one list per letter: > > [['a', ['13' '3']], ['b', '6'], ['c', ['12', '15', '4']], ['d', '2'], > ['e', ['11', '5', '16', '7']]] I'd use a dictionary to store value for a given key: >>> def aggregate(lst): items = {} # key -> values for key, value in lst: values = items.get(key) if values: if type(values) == list: values.append(value) else: items[key] = [values, value] else: items[key] = value return [list(pair) for pair in items.items()] >>> aggregate(lst) [['a', ['13', '3']], ['c', ['12', '15', '4']], ['b', '6'], ['e', ['11', '5', '16', '7']], ['d', '2']] >>> HTH, -- Miki <[EMAIL PROTECTED]> http://pythonwise.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: How do I print out in the standard output coloured lines
Hello Carlos, > I'm interested in printing out coloured lines of my application and > I don't know what to use. Can anybody give me an idea?? I use the following script: #!/usr/bin/env python '''Print message using ANSI terminal codes''' __author__ = "Miki Tebeka <[EMAIL PROTECTED]>" # $Id: ansiprint 1229 2005-05-16 05:50:22Z mikit $ # = # Copyright (c) Miki Tebeka <[EMAIL PROTECTED]> # This file is under the GNU Public License (GPL), see # http://www.gnu.org/copyleft/gpl.html for more details # = from sys import stdout, stderr # Format bright = 1 dim = 2 underline = 4 blink = 5 reverse = 7 hidden = 8 # Forground black = 30 red = 31 green = 32 yellow = 33 blue = 34 magenta = 35 cyan = 36 white = 37 # Background on_black = 40 on_red = 41 on_green = 42 on_yellow = 43 on_blue = 44 on_magenta = 45 on_cyan = 46 on_white = 47 def ansiformat(msg, *args): '''Format msg according to args. See http://www.termsys.demon.co.uk/vtansi.htm for more details/ ''' return "\033[%sm%s\033[0m" % (";".join(["%s" % f for f in args]), msg) def ansiprint(msg, *args, **kw): '''Print formatted message. Should work on ANSI compatible terminal. ''' if kw.get("stderr", 0): outfo = stderr else: outfo = stdout outfo.write(ansiformat(msg, *args)) outfo.flush() if __name__ == "__main__": from sys import argv, exit from os.path import basename h = { "bright" : bright, "dim" : dim, "underline" : underline, "blink" : blink, "reverse" : reverse, "hidden" : hidden, "black" : black, "red" : red, "green" : green, "yellow" : yellow, "blue" : blue, "magenta" : magenta, "cyan" : cyan, "white" : white, "on_black" : on_black, "on_red" : on_red, "on_green" : on_green, "on_yellow" : on_yellow, "on_blue" : on_blue, "on_magenta" : on_magenta, "on_cyan" : on_cyan, "on_white" : on_white } eg = "e.g. ansiprint hello red on_green underline -> %s" % \ ansiformat("hello", red, on_green, underline) # Check command line if len(argv) < 2: print >> stderr, "usage: %s message [format ...]" % basename(argv[0]) print >> stderr, eg exit(1) for i in argv[2:]: if i not in h: ansiprint("%s: Unknown format\n" % i, red, bright, stderr=True) print >> stderr, "Formats can be:", msg = ", ".join([ansiformat(f, h[f]) for f in h.keys()]) print msg print >> stderr, eg exit(1) # Print ansiprint(argv[1], *[h[i] for i in argv[2:]]) print # vim: ft=python Hope you find it useful. -- Miki <[EMAIL PROTECTED]> http://pythonwise.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: question with inspect module
Hello, > I would like to retrieve all the classes, methods and functions of a > module. > I've used the inspect module for this, but inside a given class > (subclass of some other one), I wanted to retrieve only the methods > I've written, not the inherited one. How can I do ? class A: def a_method(self): pass def common_method(self): pass class B(A): def common_method(self): pass def b_method(self): pass import inspect from os.path import abspath lines, start_line = inspect.getsourcelines(B) end_line = start_line + len(lines) filename = abspath(inspect.getsourcefile(B)) for name in dir(B): method = getattr(B, name) if not callable(method): continue lnum = method.func_code.co_firstlineno fname = abspath(method.func_code.co_filename) if (lnum >= start_line) and (lnum <= end_line) and (fname == filename): print "%s is from B" % name HTH, -- Miki Tebeka <[EMAIL PROTECTED]> http://pythonwise.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Weird result returned from adding floats depending on order I add them
Hello Joanne, > ... [float problem] ... > I get True returned. Can anyone tell me whats going on and how I can > avoid the problem. Thanks If you want to be truly accurate, you can use gmpy.mpq (http:// gmpy.sourceforge.net/). >>> a = [0.2, 0.2, 0.2, 0.1, 0.2, 0.1] >>> b = [0.2, 0.2, 0.2, 0.2, 0.1, 0.1] >>> qa = [gmpy.mpq(int(i * 10), 10) for i in a] >>> qb = [gmpy.mpq(int(i * 10), 10) for i in b] >>> sum(qa) mpq(1) >>> sum(qb) mpq(1) >>> sum(qa) == sum(qb) True HTH, -- Miki <[EMAIL PROTECTED]> http://pythonwise.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: send an email with picture/rich text format in the body
Hello Anya, See http://docs.python.org/lib/node597.html IMO if you'll place the picture as 1'st MutliMime part the *some* email readers will show it like you want. HTH, Miki -- http://mail.python.org/mailman/listinfo/python-list
Re: Is there any pure python webserver that can use FCGI
Hello llothar, IIRC trac (http://www.edgewall.com/trac/) is pure python, have a web server and support FCGI HTH, Miki -- http://mail.python.org/mailman/listinfo/python-list
Re: distutils and binding a script to a file extension on windows
Hello Alex, Not really an answer but if you use InnoSetup (http://www.jrsoftware.org/) you can set file type association (see http://www.jrsoftware.org/isfaq.php) HTH, Miki -- http://mail.python.org/mailman/listinfo/python-list
Re: Compile Python
Hello Zoidberg, > How would one compile python with Visual Studio 2005? By reading the section "Building on non-UNIX systems" in the README file (hint: chceck out the "PC" directory) Miki http://pythonwise.blogspot.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Web framework to recommend
Hello Jacky, I found CherryPy + Cheeta a good solution. See (shameless plug) http://www.unixreview.com/documents/s=10075/ur0604h/ Miki http://pythonwise.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Job Offer (Herzelia, Israel)
Job Title: Python Application Expert Company: Logia (http://www.logiamobile.com) Contact: Lior Rudnik ([EMAIL PROTECTED]) Job Description: * Design & Development of our leading product's PC client application * Development in Python Job Requirements: * At least 4 years of experience developing client applications * Extensive knowledge and experience in Object Oriented and design methodologies * Fast learner, able to study the impact of new technologies and adapt accordingly * Excellent communication skills, ability to handle multiple interfaces * High problem analysis and solving skills * Ability to work in a very challenging & dynamic environment Advantage (nice to have) * Experience developing python * Experience with wxPython and/or wxWidgets * Experience with open source * Experience with content - Video, Audio * Experience with VoIP -- http://mail.python.org/mailman/listinfo/python-list
Re: getting the value of an attribute from pdb
Hello Gary, > (Pdb) p root.title > > > (Pdb) p root.title[Tk.wm_title] Looks like "title" is a function, try "p root.title()" HTH, Miki http://pythonwise.blogspot.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: how to make the program notify me explicitly
Hello hankssong, You can alert yourself in many methods: * Open a message dialog - Use Tkinter or other GUI toolkit (such as wxPython) * Write yourself an email - Use email + smtplib library modules * Provide an RSS feed and read it - Use HTTPServer library * Write yourself an instant message - see msnpy and other libraries HTH, Miki http://pythonwise.blogspot.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: How to couple pyunit with GUI?
Hello volcano, http://pyunit.sourceforge.net/ has unittestgui.py (bit old though) HTH, Miki http://pythonwise.blogspot.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: using wxPython events inside a loop
Hello BigSmoke, You can process one at a time in an "OnIdle" handler, this way you'll work only when the application is doing nothing. HTH, Miki, http://pythonwise.blogspot.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: pickling multiple dictionaries
Hello Matthew, You can try either http://docs.python.org/lib/module-shelve.html or any other database bindings with blobs. HTH, Miki http://pythonwise.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: ftputil.py
Hello Sheldon, > Here is the part of the program that I need explained: > > host.download(name, name, 'b') # remote, local, binary mode Download file called "name" from host to a local file in the same name, use binary mode. > source = host.file('index.html', 'r') # file-like object Open a file (like built-in "open") on remote site in read mode > target = host.file('newdir/index.html', 'w') # file-like object Open a file (like built-in "open") on remote site in write mode > host.copyfileobj(source, target) # similar to shutil.copyfileobj Copy 1'st file to the second. HTH, Miki http://pythonwise.blogspot.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Running External Commands + Seeing when they are Finished
Hello Tommy, Use the subprocess module (http://docs.python.org/lib/module-subprocess.html). for app in MY_APPLICATION_LIST: pipe = Popen(app) pipe.wait() HTH, http://pythonwise.blogspot.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Linking onClick event to other controls on the Frame
Hello Harles, Please define "link" - is it bind event, get information from control, ...? If I'm guessing the you want to the the value of each control then you need to store a reference to this control and call the method that gets the value of each control. (GetValue() for most, GetStringSelection() for others ...) Also I suggest you use sizers instead of hard coding the widgets location. My best suggestion however is that you download the wxPython demo and view the examples over there. See revised code below: import wx class Form1(wx.Panel): def __init__(self, parent, id): wx.Panel.__init__(self, parent, id) sizer = wx.GridSizer(wx.VERTICAL) gsizer = wx.FlexGridSizer(2, 2) # First Name: ___ gsizer.Add(wx.StaticText(self, -1, "First Name:")) self._first_name = wx.TextCtrl(self, -1, size=(100, -1)) gsizer.Add(self._first_name, 0, wx.EXPAND) # Last Name: ___ gsizer.Add(wx.StaticText(self, -1, "Last Name:")) self._last_name = wx.TextCtrl(self, -1, size=(100, -1)) gsizer.Add(self._last_name, 0, wx.EXPAND) gsizer.AddGrowableCol(1) sizer.Add(gsizer, 1, wx.EXPAND) self._work_status = wx.RadioBox(self, -1, "Work Status", choices=["Employed", "Unemployed"]) sizer.Add(self._work_status, 0, wx.EXPAND) self._martial_status = wx.RadioBox(self, -1, "Martial Status", choices=["Married", "Single"]) sizer.Add(self._martial_status, 0, wx.EXPAND) b = wx.Button(self, -1, "GO!") self.Bind(wx.EVT_BUTTON, self.OnClick, b) sizer.Add(b) self.SetSizer(sizer) self.SetAutoLayout(1) sizer.Fit(self) # Button event def OnClick(self,event): fo = open("job.cfg", "w") print >> fo, "First Name:", self._first_name.GetValue() print >> fo, "Last Name:", self._last_name.GetValue() print >> fo, "Work Status:", self._work_status.GetStringSelection() print >> fo, "Martial Status:", self._martial_status.GetStringSelection() fo.close() HTH, Miki http://pythonwise.blogspot.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Speed up this code?
Hello Martin, You can use gmpy (http://gmpy.sourceforge.net/) def primes(): n = 2 while 1: yield long(n) n = gmpy.next_prime(n) HTH, Miki http://pythonwise.blogspot.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: A question about event handlers with wxPython
Hello Eric, > I'd appreciate any pointer on a simple way to tell within an event handler > where the event came from. def HandleSomething(self, event): generating_control = event.GetEventObject() print generating_control HTH, -- Miki Tebeka <[EMAIL PROTECTED]> http://pythonwise.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Is there some Python function that searches "sys.path" for a module?
Hello John, > Python's own loader searches "sys.path" for module names, but is there > some function that makes that search functionality accessible to > Python programs? I need the absolute pathname of a module, with the > search being done exactly the same way "import" does it. The loader for > "egg" files has this functionality, but I'd like to find out if there's > a standard way to do this before looking into that source code. > > Also, it seems that the environment variable "PYTHONPATH" applies to > "import", but not to the starting module named on the Python command > line. Is that correct? Thanks. http://docs.python.org/lib/module-imp.html HTH, -- Miki Tebeka <[EMAIL PROTECTED]> http://pythonwise.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
[OT] "Code Friendly" Blog?
Hello, Posting code examples to blogger.com hosted blog is not fun (need to remember alway escape < and >). Is there any free blog hosting that is more "code friendly" (easy to post code snippets and such)? Thanks, -- Miki <[EMAIL PROTECTED]> http://pythonwise.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: "Code Friendly" Blog?
Hello Mel, [Hai] >> how about bracketing your code in the tags? [Mel] > That won't help the escape problem, though it will preserve vital > Python whitespace. HTML has to be interpreting '<' characters to > recognize the ''. They also manage to mess up the first indentation in the section :) Thanks, -- Miki <[EMAIL PROTECTED]> http://pythonwise.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: loading dictionary from a file
Hello Amit, > Need a python trick, if it exists: > > I have a file that stores key, value in following format > -- > "v1" : "k1", > "v2" : "k2" > -- > > Is there a way to directly load this file as dictionary in python. I > could do (foreach line in file, split by ":" and then do dictionary > insert). Wondering, if some python built-in function can just read a > valid dictionary-file and load it? def load_as_dict(filename): return eval("{" + open(filename).read() + "}") Note that this is a very big security hole. HTH, -- Miki <[EMAIL PROTECTED]> http://pythonwise.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Time conversion between UTC and local time
Hello, > I have the following problem: > There are strings describing a UTC time, e.g. " 2008-01-15 22:32:30" > and a string reflecting the time > zone e.g. "-05:00". > > What is an elegant way of getting the local time (considering DST - > daylight saving time) with that data? > The date is not important, just the local time. > The format is not important, the easiest would probably be a tuple > (h,m,s) . http://labix.org/python-dateutil HTH, -- Miki <[EMAIL PROTECTED]> http://pythonwise.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: using scons as a library
Hello Tim, > Hi, I've been reading up on the SCons build tool. It's intended to > work by the end-user calling 'scons' on a buildscript. However, I'd > like to use it from my own python project as an imported module, and > have my already-written classes use the Scons objects to take actions > without an external script. > > The reason for this somewhat odd question is that I don't want SCons > to build the project--the project itself builds documentation (pdf/ > html/xml) from LaTeX sources--my classes handle some complex > configuration issues, source parsing, actual rendering, etc. What I > would gain by using SCons is to let my code hand-off tasks to SCons > like making and cleaning directories, creating zip files, interacting > with CVS, etc. > > Has anyone tried this before? It seems doable, but if someone has an > example that would help to shorten my learning curve. Just have a look at the "scons" script: import SCons.Script SCons.Script.main() Looks simple enough. HTH, -- Miki <[EMAIL PROTECTED]> http://pythonwise.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: unitests don't run under pdb
Hello Amit, > python testname.py : the unitests runs as usual and I get the > following results: > -- > Ran 2 tests in 0.024s > > OK > > > However, if I do "python -m pdb testnames.py": I get > ython -m pdb testnames.py> /s/nd6/amit/pyiglu/testnames.py(1)() > > -> import unittest > (Pdb) c > > -- > Ran 0 tests in 0.000s > > OK > --- IIRC unittest checks the __main__ module for tests to run. Once you run python with "-m pdb" the __main__ module is pdb and not your script. HTH, -- Miki <[EMAIL PROTECTED]> http://pythonwise.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: smtplib & gnupg
Hello Bernd, > at the moment my program sends mail with smtplib. Is there a chance to > sign and/or encode/cipher this mails with GnuPG? > If yes, does anyone have some sample code? Not exactly Python, but maybe http://codesorcery.net/old/mutt/mutt-gnupg-howto might help. HTH, -- Miki <[EMAIL PROTECTED]> http://pythonwise.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Tkinter OSX and "lift"
Hello, Tk.lift doesn't seem to work on OSX (Python 2.5.1). The below starts OK, but the window is the behind all other windows. from Tkinter import * root = Tk() Button(root, text="OK", command=root.quit).pack() root.lift() root.mainloop() Any ideas how to tell the window to start as the topmost window? Thanks, -- Miki <[EMAIL PROTECTED]> http://pythonwise.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Tkinter OSX and "lift"
Hello Kevin, > Tk.lift doesn't seem to work on OSX (Python 2.5.1). >> If you click on the PythonLauncher application that runs in your dock >> when this script is executed, the window comes into focus fine. You're right, but I want to window to be initially in focus (without the user clicking on the python launcher icon). All the best, -- Miki <[EMAIL PROTECTED]> http://pythonwise.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Tkinter OSX and "lift"
Hello Kevin, > "Lift" (which calls the Tk command "raise") doesn't work this way, at > least not under Aqua. If your application has focus, "lift" will raise > the widget being called to the top of the stacking order. However, it > will not make the application frontmost. To do this you'd have to use > Carbon calls (look at Carbon.CarbonEvt) or use a Tk extension and call > it from Python. Of course, this is pretty much a non-issue if your > application is wrapped as a standard Mac application bundle via > py2app--most Mac users don't run Python apps from the Terminal but > instead double-click an application icon. In that event, "lift" should > work fine, because the application will already have focus. Thanks, -- Miki <[EMAIL PROTECTED]> http://pythonwise.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Tkinter OSX and "lift"
Hello Eric, > >>> Tk.lift doesn't seem to work on OSX (Python 2.5.1). > There is a trick that sometimes works even for interpreted application: > > import Tkinter as tk > root = tk.Tk() > root.withdraw() > # Code building the window... > root.lift() > root.deiconify() > root.mainloop() > > This sometimes forces the window to be top-most. If this doesn't work, you > can also try: > > import Tkinter as tk > root = tk.Tk() > root.withdraw() > # Code building the window... > root.lift() > root.after_idle(root.deiconify) > root.mainloop() > > This was a trick that had to be done on Windows a few years back to force > the main window to be created on top of this others. It deosn't seem to be > needed anymore now, but maybe the trick can be used on a Mac... Don't know > if this will work the same, though... Sadly, both of them didn't work. Thanks. -- Miki <[EMAIL PROTECTED]> http://pythonwise.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Getting stdout from other processes
Hello Matthias, > as I found out, it is possible to get the output of other programs > using os.popen() and read from it. However this method is blocking for > server processes and programs that don't stop immediately. Has anyone > an idea how to get the output of such programs? The current "official" module to use is subprocess (pipe = Popen([client], stdout=PIPE)) However if the client is sending data, reading from the pipe.stdout will block the server. If you *need* to wait, then you can use pipe.wait(), otherwise do as Diez suggested and have a thread read the client output and propagate it to the main loop (maybe using Queue.Queue) HTH, -- Miki <[EMAIL PROTECTED]> http://pythonwise.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: (Newbie) Help with sockets.
Hello, > Hi everyone. I'm fairly new to Python, and even more new to socket > programming. I think I've wrapped my head around sockets, and with > that I want to create a Telnet-based chat server, the idea being > people connect to the telnet servers with their clients and they all > communicate. IMO you should start with twisted (http://twistedmatrix.com/trac/), which simplifies socket programming very much. HTH, -- Miki <[EMAIL PROTECTED]> http://pythonwise.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: 'normal' shell with curses
Hello Michael, > I'm trying to print out text in color. As far as I know, curses is the > only way to do that (or not?). On unix, every XTerm compatible terminal will be able to display color using escape sequence. (Like the one you see in the output of 'grep --color') See the shameless plug in http://pythonwise.blogspot.com/2008/03/ansiprint.html HTH, -- Miki <[EMAIL PROTECTED]> http://pythonwise.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: tools to install not in python tree?
Hello Jim, > I have some materials for a project that I am working on that I keep > in a source code control system (svn now, but I'm experimenting with > mercurial). I want to install these things from the repository, but > not into site-packages/ as Distutils wants to do. > > For instance there are some administrative scripts I want to put in ~/ > admin/ and some programs that I want in ~/public_html/ . I also > want to run some post-install routines (for instance, reset the > database tables on my development machine). So I'm looking for a tool > to take things from a repository and install them into place. > Something like: > install_from_repository.py -version "1.2.7" > if there is a bug in 1.2.7 that I need to work on. > > Some of the things that I am looking for are like what setup.py does > (for instance, changing the #! line on scripts or having a > convenient .cfg file). But as I understand it setup only targets > installing below sys.prefix; is that right? > > I can write routines for myself but other people must need to do these > things also and a tested solution is obviously better. Is there such > a tool? Have a look at http://docs.python.org/lib/module-distutils.html, specially http://docs.python.org/dist/node13.html and http://docs.python.org/inst/alt-install-windows.html HTH, -- Miki <[EMAIL PROTECTED]> http://pythonwise.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Python CGI & Webpage with an Image
Hello Rod, > I have a set of CGI scripts set up and in one page (which is stored in > an HTML file then printed via a python CGI) there is an image. However > the image never displays, can anyone recommend a way round this > problem? We need more information, can you post a code snippet? error page? ... My *guess* is that the web server don't know how to server the image (wrong path configuration?) HTH, -- Miki <[EMAIL PROTECTED]> http://pythonwise.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Changing the size of a Button
Hello Konrad, > How do i change the size of a Button > (using Tkinter), other than to set it > during construction? In Tkinter, usually the geometry managers (such as pack) are the ones who size the widgets. If you run something like: import Tkinter as tk root = tk.Tk() def change_size(): b["text"] = "More text" b = tk.Button(root, text="Text", command=change_size) b.pack() root.mainloop() You'll see that the button changes size to accommodate the new text. HTH, -- Miki <[EMAIL PROTECTED]> http://pythonwise.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Parse specific text in email body to CSV file
Hello, > I have been searching all over for a solution to this. I am new to > Python, so I'm a little lost. Any pointers would be a great help. I > have a couple hundred emails that contain data I would like to > incorporate into a database or CSV file. I want to search the email > for specific text. > > The emails basically look like this: > > random text _important text:_15648 random text random text random text > random text > random text random text random text _important text:_15493 random text > random text > random text random text _important text:_11674 random text random text > random text > ===Date: Wednesday March 5, 2008 > name1: 15 name5: 14 > > name2: 18 name6: 105 > > name3: 64 name7: 2 > > name4: 24 name8: 13 > > I want information like "name1: 15" to be placed into the CSV with the > name "name1" and the value "15". The same goes for the date and > "_important text:_15493". > > I would like to use this CSV or database to plot a graph with the > data. import re for match in re.finditer("_([\w ]+):_(\d+)", text): print match.groups()[0], match.groups()[1] for match in re.finditer("Date: ([^=]+)=", text): print match.groups()[0] for match in re.finditer("(\w+): (\d+)", text): print match.groups()[0], match.groups()[1] Now you have two problems :) HTH, -- Miki <[EMAIL PROTECTED]> http://pythonwise.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
How to make a Tkinter widget always visible?
Hello, I have a simple Tkinter window with [GO] and [Quit] buttons at the bottom. When I resize the window to be shorter, the first thing to disappear are the buttons, however I want these button to be visible at all times. Is there a way to make sure that these buttons are always visible? Thanks, -- Miki <[EMAIL PROTECTED]> http://pythonwise.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Exctract GIF comment from image
Hello Wingi, > simple question: The PIL does not support reading the optional > description in GIF Images. > > http://www.pythonware.com/library/pil/handbook/format-gif.htm > > After some reasearch I could not find a python solution for this, any > suggestions? Use ImageMagick (www.imagemagick.org), "identify -verbose " should have the comments somewhere in the output. There also a python binding to ImageMagick but I have no experience with it. HTH, -- Miki <[EMAIL PROTECTED]> http://pythonwise.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: How to make a Tkinter widget always visible?
Hello Kevin, > > Is there a way to make sure that these buttons are always visible? > > There are various ways to do this: you can set the window to be > non-resizable, or set a minimum size to it, so that it can't be resized > below that level. However, if you allow arbitrary resizing of the > window, there's no real way to guarantee that the widgets will be > visible at all times. Thanks. I've set a minimal size to the window. However when I resize it to be shorter, the buttons are hidden while the top frame stays visible. Thanks, -- Miki <[EMAIL PROTECTED]> http://pythonwise.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: How to parse this timestamp?
Hello, > [19-Aug-2007 07:38:43+216ms NZST] > > How can I parse them? I don't see any way to build a strftime() > format string that can handle the +216ms part. The best I can see is > tearing it all apart with a regex, but I'm trying to avoid that pain > if I can. > > (PS: I have no clue why google groups thinks it should put > "gnu.gcc.help" on the from line) Just zap the end and use time.strptime: >>> s = '19-Aug-2007 07:38:43+216ms NZST' >>> strptime(re.sub("\+\d{3}ms [A-Z]{4}", "", s), "%d-%b-%Y %H:%M:%S") (2007, 8, 19, 7, 38, 43, 6, 231, -1) >>> HTH, -- Miki <[EMAIL PROTECTED]> http://pythonwise.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: How to make a Tkinter widget always visible?
Hello Kevin, > Please post the code you're using--it will be easier to help if we can > see exactly what you are trying. In a nutshell: --- import Tkinter as tk, tkFont from tkMessageBox import showinfo, showerror from os import popen def main(): root = tk.Tk() # Log window tk.Label(root, text="Log:", anchor=tk.W).pack(fill=tk.X) frame = tk.Frame(root) scrollbar = tk.Scrollbar(frame) scrollbar.pack(side=tk.RIGHT, fill=tk.Y) log = tk.Text(frame, width=80) log.config(state=tk.DISABLED) log.pack(side=tk.LEFT, fill=tk.BOTH, expand=1) scrollbar.config(command=log.yview) frame.pack(fill=tk.BOTH, expand=1) # Button frame frame = tk.Frame(root) update = tk.Button(frame, text="GO", command=lambda: showinfo("OUCH")) update.pack(side=tk.LEFT) tk.Button(frame, text="Quit", command=root.quit).pack(side=tk.LEFT) frame.pack(fill=tk.X) root.bind("", lambda e: root.quit()) update.focus() root.minsize(-1, 100) root.mainloop() if __name__ == "__main__": main() --- When I pack the buttons frame first (using side=BOTTOM), it stays visible at all times. Thanks, -- Miki <[EMAIL PROTECTED]> http://pythonwise.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: C extensions question
Hello, > Let's say I write a simple extension in c only for the windows version > of my script. Can I just put this compiled dll in the root directory > of my application along with the other py files and distribute it like > that without the need of an installation script? Yes (current directory is always looked first in when loading DLLs). HTH, -- Miki <[EMAIL PROTECTED]> http://pythonwise.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Fast 2D Raster Rendering with GUI
Hello Dave, > Hi All. I've been formulating in my head a simple image editor. I > actually started prototyping is some time ago in Java, but am liking > Python more and more. My editor will be nowhere near the level of Gimp/ > Photoshop, but I do need fast pixel level control and display. For > instance, that means no automatic anti-aliasing and that I will be > implementing my own line drawing algorithms. > > I've got the high level architectual aspects of my program down, but > am stuck on what graphics API to use. I want a canvas area of > adjustable size which users can draw on with as little lag as > possible. The canvas area will be composed of layers (i.e. I require > an alpha channel) and I need to be able to zoom in and out of it (zoom > levels will be at fixed intervals, so this can be simulated if need > be.) > > I started looking at PyGame but realize that I need to integrate a GUI > into the whole thing (or integrate the image into the GUI rather) and > I didn't see a straightforward way to do that. Of course, I don't even > know if PyGame is the right API for the job anyways :P > > Any thoughts or ideas that could help me get started? Thanks! Apart from PIL, some other options are: 1. Most GUI frameworks (wxPython, PyQT, ...) give you a canvas object you can draw on 2. A bit of an overkill, but you can use PyOpenGL 3. ImageMagick bindings? (http://www.imagemagick.org/script/api.php) HTH, -- Miki <[EMAIL PROTECTED]> http://pythonwise.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Distributing Python Apps on Linux\BSD
Hello, Disclaimer: I'm not an expert on the subject. > Setuptools and friends seem to be focused on distributing modules, I'm > at the other end of the scale where I want to distribute an entire > application so that an Administrator can run a single install and have > a fully operational product. A key requirement is that I want the > application to fit in with what and admin would expect an application > to look like at the system level i.e site-packages like structures > aren't suitable. You do that with distutils as well. > So far I've thought of using a configure script and make which would > call some custom python installer script to do the actual install. It > fits in nicely with what I want to achieve but are there any better > options out there, how are others doing the same thing? Every distro flavor has it's own installer: apt/deb, rpm, port, ... On Windows you can use one of the free installer (InnoSetup and friends). HTH, -- Miki <[EMAIL PROTECTED]> http://pythonwise.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: what are generators?
On Mar 24, 8:17 am, [EMAIL PROTECTED] wrote: > I'm looking for a cool trick using generators. Know any exercises I > can work? Simple one the comes to mind is flattening a list: >>> list(flatten([1, [[2], 3], [[[4)) [1, 2, 3, 4] >>> HTH, -- Miki <[EMAIL PROTECTED]> http://pythonwise.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: first interactive app
Hello Tim, > I want to write a tiny interactive app for the following situation: > I have books of many chapters that must be split into volumes before going > to the printer. > A volume can have up to 600 pages. We obviously break the book into volumes > only at chapter breaks. Since some chapters make a natural grouping, we want > some human interaction for where the volume breaks occur. > > Not having experience with interactive apps, I'm asking for advice about how > to go about it. The data I start with is just a dictionary with chapter name > = ending page number. I figured I would first show where the volumes would > break with no human interaction, with the begin and ending chapter > names/pagenumbers for each volume. > > From here I thought about having a slider for each volume, but the number of > volumes could change during the session. > Or maybe I should just ask 'enter the ending chapter for the first volume' > and recalculate, etc until all volumes are defined. > > Any ideas on a simple interface for this? How about something like: Chapter 1 (001-200 200) Chapter 2 (200-300 100) -- 001-300 300 Chapter 3 (300-450 150) Chapter 4 (450-500 50) -- 300-450 250 Chapter 5 (500-600 100) -- 500-600 100 Where the user can move the divider up and down to create new volume, they can also add and delete dividers. The program will not allow to drag the divider above the 600 page limit. HTH, -- Miki <[EMAIL PROTECTED]> http://pythonwise.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Pystemmer 1.0.1 installation problem in Linux
Hello Supheakmungkol, > I am a newbie to Python community. For my project, I tried to install > Pystemmer 1.0.1 (http://snowball.tartarus.org/wrappers/ > PyStemmer-1.0.1.tar.gz) on my linux ubuntu 7.10 machine but > unsuccessful. It produced the following error: > > running install > running build > running build_ext > building 'Stemmer' extension > gcc -pthread -fno-strict-aliasing -DNDEBUG -g -O2 -Wall -Wstrict- > prototypes -fPIC -Isrc -Ilibstemmer_c/include -I/usr/include/python2.5 > -c libstemmer_c/src_c/stem_ISO_8859_1_danish.c -o build/temp.linux- > i686-2.5/libstemmer_c/src_c/stem_ISO_8859_1_danish.o > In file included from /usr/lib/gcc/i486-linux-gnu/4.1.3/include/ > syslimits.h:7, > from /usr/lib/gcc/i486-linux-gnu/4.1.3/include/ > limits.h:11, > from libstemmer_c/src_c/../runtime/header.h:2, > from libstemmer_c/src_c/stem_ISO_8859_1_danish.c:4: > /usr/lib/gcc/i486-linux-gnu/4.1.3/include/limits.h:122:61: error: > limits.h: No such file or directory > error: command 'gcc' failed with exit status 1 > > Did anyone experience this before? Nope, compiles out of the box for me on 7.1 (IIRC easy_install worked for it as well). > Any comment/suggestion is highly appreciated. Do you have limits.h on your system? Did you install the python2.5-dev package? HTH, -- Miki <[EMAIL PROTECTED]> http://pythonwise.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
ctypes and gmp
Hello All, Playing around with ctypes, I'm try to use gmp (gmpy is excellent but I want to learn ctypes). I'm running: #!/usr/bin/env python from ctypes import * class mpz(Structure): _fields_ = [ ("_mp_alloc", c_int), ("_mp_size", c_int), ("_mp_d", POINTER(c_uint)), ] gmp = cdll.LoadLibrary("libgmp.so") m = mpz() gmp.__gmpz_init(byref(m)) gmp.__gmpz_set_ui(byref(m), 27) gmp.__gmp_printf("m is %d\n", byref(m)) However, the output is: m is -1210863888 Any ideas? (gmp.h can bee view at http://tinyurl.com/yrqen4) Thanks, -- Miki <[EMAIL PROTECTED]> http://pythonwise.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Instrumented web proxy
Hello Andrew, > Tiny HTTP Proxy in Python looks promising as it's nominally simple (not > many lines of code) > > http://www.okisoft.co.jp/esc/python/proxy/ > > It does what it's supposed to, but I'm a bit at a loss as where to > intercept the traffic. I suspect it should be quite straightforward, but > I'm finding the code a bit opaque. > > Any suggestions? >From a quick look at the code, you need to either hook to do_GET where you have the URL (see the urlunparse line). If you want the actual content of the page, you'll need to hook to _read_write (data = i.recv(8192)). HTH, -- Miki <[EMAIL PROTECTED]> http://pythonwise.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Tips Re Pattern Matching / REGEX
Hello, > I have a large text file (1GB or so) with structure similar to the > html example below. > > I have to extract content (text between div and tr tags) from this > file and put it into a spreadsheet or a database - given my limited > python knowledge I was going to try to do this with regex pattern > matching. > > Would someone be able to provide pointers regarding how do I approach > this? Any code samples would be greatly appreciated. The ultimate tool for handling HTML is http://www.crummy.com/software/BeautifulSoup/ where you can do stuff like: soup = BeautifulSoup(html) for div in soup("div", {"class" : "special"}): ... Not sure how fast it is though. There is also the htmllib module that comes with python, it might do the work as well and maybe a bit faster. If the file is valid HTML and you need some speed, have a look at xml.sax. HTH, -- Miki <[EMAIL PROTECTED]> http://pythonwise.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: first interactive app
Hello Tim, > that looks nice, simple, and intuitive. thanks for thinking about it. Thanks, glad I could help. > Now to dive into some gui coding! IMO you can pull it off as a web application and then you won't need to worry about cross-platform, upgrades and all that interesting stuff. HTH, -- Miki <[EMAIL PROTECTED]> http://pythonwise.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list