matching a string to extract substrings for which some function returns true
Hello All, say you have some string: "['a', 'b', 1], foobar ['d', 4, ('a', 'e')]" Now i want to extract all substrings for which "isinstance(eval(substr), list)" is "True" . now one way is to walk through the whole sample string and check the condition, I was wondering if there is any smarter way of doing the same, may be using regular-expressions. Thanks, amit. Endless the world's turn, endless the sun's spinning Endless the quest; I turn again, back to my own beginning, And here, find rest. -- http://mail.python.org/mailman/listinfo/python-list
Re: matching a string to extract substrings for which some function returns true
Well actually the problem is I have a list of tuples which i cast as string and then put in a html page as the value of a hidden variable. And when i get the string again, i want to cast it back as list of tuples: ex: input: "('foo', 1, 'foobar', (3, 0)), ('foo1', 2, 'foobar1', (3, 1)), ('foo2', 2, 'foobar2', (3, 2))" output: [('foo', 1, 'foobar', (3, 0)), ('foo1', 2, 'foobar1', (3, 1)), ('foo2', 2, 'foobar2', (3, 2))] I hope that explains it better... cheers, On 11/22/05, Steven D'Aprano <[EMAIL PROTECTED]> wrote: > On Tue, 22 Nov 2005 16:57:41 +0530, Amit Khemka wrote: > > > Hello All, > > > > say you have some string: "['a', 'b', 1], foobar ['d', 4, ('a', 'e')]" > > Now i want to extract all substrings for which > > "isinstance(eval(substr), list)" is "True" . > > That's an awfully open-ended question. Is there some sort of structure to > the string? What defines a substring? What should you get if you extract > from this string? > > "[]" > > Is that one list or five? > > > > now one way is to walk through the whole sample string and check the > > condition, > > Yes. Where does the string come from? Can a hostile user pass bad strings > to you and crash your code? > > > -- > Steven. > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Endless the world's turn, endless the sun's spinning Endless the quest; I turn again, back to my own beginning, And here, find rest. -- http://mail.python.org/mailman/listinfo/python-list
Re: matching a string to extract substrings for which some functionreturns true
Fredrik, thanks for your suggestion. Though the html page that are generated are for internal uses and input is verified before processing. And more than just a solution in current context, actually I was a more curious about how can one do so in Python. cheers, amit. On 11/22/05, Fredrik Lundh <[EMAIL PROTECTED]> wrote: > Amit Khemka wrote: > > > Well actually the problem is I have a list of tuples which i cast as > > string and then put in a html page as the value of a hidden variable. > > And when i get the string again, i want to cast it back as list of tuples: > > ex: > > input: "('foo', 1, 'foobar', (3, 0)), ('foo1', 2, 'foobar1', (3, 1)), > > ('foo2', 2, 'foobar2', (3, 2))" > > output: [('foo', 1, 'foobar', (3, 0)), ('foo1', 2, 'foobar1', (3, 1)), > > ('foo2', 2, 'foobar2', (3, 2))] > > > > I hope that explains it better... > > what do you think happens if the user manipulates the field values > so they contain, say > > os.system('rm -rf /') > > or > > "'*'*100*2*2*2*2*2*2*2*2*2" > > or something similar? > > if you cannot cache session data on the server side, I'd > recommend inventing a custom record format, and doing your > own parsing. turning your data into e.g. > > "foo:1:foobar:3:0+foo1:2:foobar1:3:1+foo2:2:foobar2:3:2" > > is trivial, and the resulting string can be trivially parsed by a couple > of string splits and int() calls. > > to make things a little less obvious, and make it less likely that some > character in your data causes problems for the HTML parser, you can > use base64.encodestring on the result (this won't stop a hacker, of > course, so you cannot put sensitive data in this field). > > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Endless the world's turn, endless the sun's spinning Endless the quest; I turn again, back to my own beginning, And here, find rest. -- http://mail.python.org/mailman/listinfo/python-list
Re: matching a string to extract substrings for which somefunctionreturns true
thanks for you suggestions :-) .. cheers, On 11/23/05, Fredrik Lundh <[EMAIL PROTECTED]> wrote: > I wrote: > > > if you cannot cache session data on the server side, I'd > > recommend inventing a custom record format, and doing your > > own parsing. turning your data into e.g. > > > >"foo:1:foobar:3:0+foo1:2:foobar1:3:1+foo2:2:foobar2:3:2" > > > > is trivial, and the resulting string can be trivially parsed by a couple > > of string splits and int() calls. > > on the other hand, the "myeval" function I posted here > > http://article.gmane.org/gmane.comp.python.general/433160 > > should be able to deal with your data, as well as handle data from > malevolent sources without bringing down your computer. > > just add > > if token[1] == "(": > out = [] > token = src.next() > while token[1] != ")": > out.append(_parse(src, token)) > token = src.next() > if token[1] == ",": > token = src.next() > return tuple(out) > > after the corresponding "[" part, and call it like: > > data = myeval("[" + input + "]") > > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Endless the world's turn, endless the sun's spinning Endless the quest; I turn again, back to my own beginning, And here, find rest. -- http://mail.python.org/mailman/listinfo/python-list
writing IM bots
Hello, I am trying to write an IM Bot, which automatically replies to a message, in Python. I was wondering If there are python modules for connecting to Yahoo!, msn networks ... ideally I would like to have a multithreaded module. This is one I found for msn, if anyone has used it please comment, - http://users.auriga.wearlab.de/~alb/msnlib/ cheers, amit. -- Endless the world's turn, endless the sun's spinning Endless the quest; I turn again, back to my own beginning, And here, find rest. -- http://mail.python.org/mailman/listinfo/python-list
Re: writing IM bots
thank you all for ur suggestions .. I got msnp and curfoo(for yahoo) customized and working :-) .. though they are pretty slow in responding to messages ... will try jabber based protocols, cheers, amit. On 12/14/05, Linsong <[EMAIL PROTECTED]> wrote: >Why not twisted.words, for me, twisted can solved almost all(if not > all, you can implement it under twisted framework easily) internet > protocol related tasks and it is really *cool*! >Twisted Words includes: > > * Low-level protocol implementations of OSCAR (AIM and ICQ), IRC, > MSN, TOC (AIM). > * Jabber libraries. > * Prototypes of chat server and client frameworks built on top of > the protocols. > >I have used twisted.words for IRC and MSN, it works very well. Never > forget to investigate the other projects of twisted, it will give you a > lot back. > http://twistedmatrix.com/projects/words/ > > Good Luck! > Linsong > > > Amit Khemka wrote: > > >Hello, > >I am trying to write an IM Bot, which automatically replies to a > >message, in Python. > >I was wondering If there are python modules for connecting to Yahoo!, > >msn networks ... > >ideally I would like to have a multithreaded module. > > > >This is one I found for msn, if anyone has used it please comment, > >- http://users.auriga.wearlab.de/~alb/msnlib/ > > > >cheers, > >amit. > > > > > >-- > > > >Endless the world's turn, endless the sun's spinning > >Endless the quest; > >I turn again, back to my own beginning, > >And here, find rest. > > > > > > -- Endless the world's turn, endless the sun's spinning Endless the quest; I turn again, back to my own beginning, And here, find rest. -- http://mail.python.org/mailman/listinfo/python-list
Re: Timeout at command prompt
One way would be to use 'signal' s ... something like this should work import signal TIMEOUT = 5 # number of seconds your want for timeout signal.signal(signal.SIGALRM, input) signal.alarm(TIMEOUT) def input(): try: foo = raw_input() return foo except: # timeout return cheers, amit. On 11 Jan 2006 13:24:34 -0800, Thierry Lam <[EMAIL PROTECTED]> wrote: > I can use the python function raw_input() to read any input from the > user but how can I add a timeout so that my program exits after x > period of time when no input has been entered. > > Thierry > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Endless the world's turn, endless the sun's spinning Endless the quest; I turn again, back to my own beginning, And here, find rest. -- http://mail.python.org/mailman/listinfo/python-list
Re: How can I create a dict that sets a flag if it's been modified
Ideally, I would have made a wrapper to add/delete/modify/read from the dictionay. But other than this, one way i can think straight off is to "pickle" the dict, and to see if the picked object is same as current object. cheers, amit. On 12 Jan 2006 01:15:38 -0800, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote: > I can think of several messy ways of making a dict that sets a flag if > it's been altered, but I have a hunch that experienced python > programmers would probably have an easier (well maybe more Pythonic) > way of doing this. > > It's important that I can read the contents of the dict without > flagging it as modified, but I want it to set the flag the moment I add > a new element or alter an existing one (the values in the dict are > mutable), this is what makes it difficult. Because the values are > mutable I don't think you can tell the difference between a read and a > write without making some sort of wrapper around them. > > Still, I'd love to hear how you guys would do it. > > Thanks, > -Sandra > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Endless the world's turn, endless the sun's spinning Endless the quest; I turn again, back to my own beginning, And here, find rest. -- http://mail.python.org/mailman/listinfo/python-list
Re: Timeout at command prompt
its "Python 2.4.1" .. on linux On 12 Jan 2006 06:34:08 -0800, Thierry Lam <[EMAIL PROTECTED]> wrote: > Is there a windows equivalent for that solution? > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Endless the world's turn, endless the sun's spinning Endless the quest; I turn again, back to my own beginning, And here, find rest. -- http://mail.python.org/mailman/listinfo/python-list
Re: Timeout at command prompt
I tried it on "Python 2.4.1" on '2.6.11-1.1369_FC4smp with gcc version 4.0.0' .. which works fine .. may be it could be an issue with some other combinations .. cheers, amit On 12 Jan 2006 07:35:57 -0800, Paul Rubin <"http://phr.cx"@nospam.invalid> wrote: > Amit Khemka <[EMAIL PROTECTED]> writes: > > import signal > > TIMEOUT = 5 # number of seconds your want for timeout > > signal.signal(signal.SIGALRM, input) > > signal.alarm(TIMEOUT) > > > > def input(): > > try: > >foo = raw_input() > >return foo > > except: > > # timeout > > return > > This doesn't work with raw_input under linux, maybe because the > readline lib is snagging the timer interrupt or something. Use > sys.stdin.readline instead. SF bug: > > http://sourceforge.net/tracker/index.php?func=detail&aid=685846&group_id=5470&atid=105470 > -- > http://mail.python.org/mailman/listinfo/python-list > -- Endless the world's turn, endless the sun's spinning Endless the quest; I turn again, back to my own beginning, And here, find rest. -- http://mail.python.org/mailman/listinfo/python-list
Re: Timeout at command prompt
Another thing that can be tried is: import threading a="" def input(): global a a = raw_input() T = threading.Thread(target=input) T.start() T.join(2) ## does the trick ... I have not tested it but i guess should work. cheers, amit. On 1/12/06, Amit Khemka <[EMAIL PROTECTED]> wrote: > I tried it on "Python 2.4.1" on '2.6.11-1.1369_FC4smp with gcc version > 4.0.0' .. which works fine .. may be it could be an issue with some > other combinations .. > > cheers, > amit > > On 12 Jan 2006 07:35:57 -0800, Paul Rubin > <"http://phr.cx"@nospam.invalid> wrote: > > Amit Khemka <[EMAIL PROTECTED]> writes: > > > import signal > > > TIMEOUT = 5 # number of seconds your want for timeout > > > signal.signal(signal.SIGALRM, input) > > > signal.alarm(TIMEOUT) > > > > > > def input(): > > > try: > > >foo = raw_input() > > >return foo > > > except: > > > # timeout > > > return > > > > This doesn't work with raw_input under linux, maybe because the > > readline lib is snagging the timer interrupt or something. Use > > sys.stdin.readline instead. SF bug: > > > > http://sourceforge.net/tracker/index.php?func=detail&aid=685846&group_id=5470&atid=105470 > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > > > -- > > Endless the world's turn, endless the sun's spinning > Endless the quest; > I turn again, back to my own beginning, > And here, find rest. > -- Endless the world's turn, endless the sun's spinning Endless the quest; I turn again, back to my own beginning, And here, find rest. -- http://mail.python.org/mailman/listinfo/python-list
Re: Encode filenames to safe format
On 7/20/06, Dara Durum <[EMAIL PROTECTED]> wrote: > Hi ! > > I want to encode filenames to safe format, like in browser url (space -> > %20, etc.). > What the module and function name that helps me in this project ? > import urllib urllib.quote('file name') cheers, amit -- Amit Khemka -- onyomo.com Home Page: www.cse.iitd.ernet.in/~csd00377 Endless the world's turn, endless the sun's Spinning, Endless the quest; I turn again, back to my own beginning, And here, find rest. -- http://mail.python.org/mailman/listinfo/python-list
Re: import a user created python file as module
On 30 Jul 2006 23:07:07 -0700, Phoe6 <[EMAIL PROTECTED]> wrote: > Hi, > I have the following directory structure in my project. > Base: > file1.py > file2.py > Directory1: >file1-dir1.py > > I am able to import file1 into file2.py > What I need to do is, import file1 in the file file1-dir1.py. > I did not create the entire dir structure as package. Adding > __init__.py file in both Base: as well as Directory1: is not helpful. I > am unable to import file1 in the file1-dir1.py. It is not able to find > the path of the file1.py. > > 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. Modify the path where python searches for modules, for example in file1-dir1.py add: import sys sys.path.append("/path/to/Base") import file1 cheers, amit. -- Amit Khemka -- onyomo.com Home Page: www.cse.iitd.ernet.in/~csd00377 Endless the world's turn, endless the sun's Spinning, Endless the quest; I turn again, back to my own beginning, And here, find rest. -- http://mail.python.org/mailman/listinfo/python-list
Re: how to safely extract dict values
On 7/31/06, David Zaret <[EMAIL PROTECTED]> wrote: > i have a dict with a particular key - the values for this key will be > None, one valid scalar, or a list: > > {mykey, None} > {mykey, "foo"} > {mykey, ["bar", "baz"]} > > let's ignore the None case - in the case of the one or many values, i > want to suck the values into a list. here's one way to do this: > > if mydict.has_key(mykey): > vals=[] > _v = mydict[mykey] > if isinstance(_v, types.ListType): > vals.extend(_v) > else: > vals.append(_v) > # now we can safely iterate through acts > for val in vals: > . how about: vals = [] for val in mydict.values(): try: vals.extend(val) except: vals.append(val) cheers, amit. -- Amit Khemka -- onyomo.com Home Page: www.cse.iitd.ernet.in/~csd00377 Endless the world's turn, endless the sun's Spinning, Endless the quest; I turn again, back to my own beginning, And here, find rest. -- http://mail.python.org/mailman/listinfo/python-list
Re: how to safely extract dict values
oops ! my mistake :-D On 7/31/06, Bruno Desthuilliers <[EMAIL PROTECTED]> wrote: > Amit Khemka wrote: > > how about: > > > > vals = [] > > for val in mydict.values(): > > try: vals.extend(val) > > except: vals.append(val) > > >>> l = [] > >>> l.extend((1, 2)) > >>> l > [1, 2] > >>> l.extend('ab') > >>> l > [1, 2, 'a', 'b'] Oops, my mistake ... jumped in too quickly ! cheers, -- Amit Khemka -- onyomo.com Home Page: www.cse.iitd.ernet.in/~csd00377 Endless the world's turn, endless the sun's Spinning, Endless the quest; I turn again, back to my own beginning, And here, find rest. -- http://mail.python.org/mailman/listinfo/python-list
Re: PIL issues
On 8/1/06, David Bear <[EMAIL PROTECTED]> wrote: > I am trying to use PIL and when building it, PIL fails to find my jpeg > library. I am using a python 2.4.3 that I build myself on Suse linux 9.3. I > do have the following jpeg libraries: > > rpm -qa | grep jpeg > jpeg-6b-738 > libjpeg-32bit-9.3-7 > libjpeg-6.2.0-738 > > > yet, when building PIL I get: > > python setup.py build_ext -i > running build_ext > > PIL 1.1.5 BUILD SUMMARY > > version 1.1.5 > platform linux2 2.4.2 (#4, Jul 27 2006, 14:34:30) > [GCC 3.3.5 20050117 (prerelease) (SUSE Linux)] > > *** TKINTER support not available > *** JPEG support not available > --- ZLIB (PNG/ZIP) support ok > *** FREETYPE2 support not available > > To add a missing option, make sure you have the required > library, and set the corresponding ROOT variable in the > setup.py script. > > I don't know what ROOT variable the message is referring too. Any advice > would be appreciated. This is because PIL, is not able to find the jpeg/other libraries . 1. Install jpeg-libs from sources: (http://www.ijg.org/files/jpegsrc.v6b.tar.gz) 2.0: "clean" the PIL build 2.1 In setup.py that comes with PIL, set the JPEG_ROOT to the jpeg-lib path 3.0 run setup.py I hope that should help .. cheers, amit -- Amit Khemka -- onyomo.com Home Page: www.cse.iitd.ernet.in/~csd00377 Endless the world's turn, endless the sun's Spinning, Endless the quest; I turn again, back to my own beginning, And here, find rest. -- http://mail.python.org/mailman/listinfo/python-list
Re: using globals
On 8/3/06, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote: > Hi, > > I have got a problem with importing global variables. For instance I have > got two files: > > # t1.py #t2.py > > counter = 1 > > def counter_adder(filenr): def show_adder(): >global counter import t1 >counter+= 1 print("adder > is %d" % t1.counter) >if filenr == 1: > show_adder() >else: > import t2 > t2.show_adder() > > def show_adder(): >print("adder is %d" % counter) > > >>counter_adder(1) > adder is 2 > >>counter_adder(2) > adder is 1 > > When I look at the outcome of two function calls I expected no differences > but much to my surprise it goes wrong when the global variable is imported. > It doesn't give the updated value but the value it get when instantiated. > Who come? What should I do to get the updated value call: counter_adder(2) In "t2.py", you are importing a python module "t1.py". And its very logical that all the (global) variables in "t1.py" have the value which one would expect after execution of the "t1.py" otherwise. And hence you see value of counter as 1. (or in other words you are accessing two different instances of variable "counter") I would rather advice that you pass counter as a variable to the function-calls, or use a class. cheers, amit. -- Amit Khemka -- onyomo.com Home Page: www.cse.iitd.ernet.in/~csd00377 Endless the world's turn, endless the sun's Spinning, Endless the quest; I turn again, back to my own beginning, And here, find rest. -- http://mail.python.org/mailman/listinfo/python-list
Re: Running queries on large data structure
On 8/3/06, Christoph Haas <[EMAIL PROTECTED]> wrote: > On Wednesday 02 August 2006 22:24, Christoph Haas wrote: > > I have written an application in Perl some time ago (I was young and > > needed the money) that parses multiple large text files containing > > nested data structures and allows the user to run quick queries on the > > data. [...] > > I suppose my former posting was too long and concrete. So allow me to try > it in a different way. :) > > The situation is that I have input data that take ~1 minute to parse while > the users need to run queries on that within seconds. I can think of two > ways: > > (1) Database > (very quick, but the input data is deeply nested and it would be > ugly to convert it into some relational shape for the database) > (2) cPickle > (Read the data every now and then, parse it, write the nested Python > data structure into a pickled file. The let the other application > that does the queries unpickle the variable and use it time and > again.) Though some sugggested maintaining data in some XML structures, I was wondering that if you considered using some native XML database like BDB XML. 1. It allows you to retain hierarchical structure of data. 2. It also has support for precompiled queries. 3. You can open a persistent connection. cheers, amit. -- Amit Khemka -- onyomo.com Home Page: www.cse.iitd.ernet.in/~csd00377 Endless the world's turn, endless the sun's Spinning, Endless the quest; I turn again, back to my own beginning, And here, find rest. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to change the path for python binary?
On 8/10/06, Nico Grubert <[EMAIL PROTECTED]> wrote: > Hi there, > > I have installed Python 2.3.5 on Suse Linux 10. > If I enter "python" in the shell, the Python 2.3.5 interpreter is called. > > After I installed Python 2.4.3. the Python 2.4.3 interpreter is called > which is the default behaviour I guess. > > "which python" brings me "/usr/local/bin/python" which calls the Python > 2.4.3 interpreter. > > My question now is: > What do I have to do in order to get the Python 2.3.5 interpreter each > time I enter "python" in the shell? There could be various ways of doing so, like: Option 1: open your shell preference file ( ex. for bash ~/.bashrc) and add an alias: alias python="/path/to/python/version/of/your/choise" Option 2: make /usr/local/bin/python a symlink to python2.3.5 cheers, amit. -- Amit Khemka -- onyomo.com Home Page: www.cse.iitd.ernet.in/~csd00377 Endless the world's turn, endless the sun's Spinning, Endless the quest; I turn again, back to my own beginning, And here, find rest. -- http://mail.python.org/mailman/listinfo/python-list
Re: Help with async xmlrpc design
On 8/17/06, David Hirschfield <[EMAIL PROTECTED]> wrote: > I have an xmlrpc client/server system that works fine, but I want to > improve performance on the client side. > > Right now the system operates like this: > > client makes request from server (by calling server.request() via xml-rpc) > server places "request" on queue and returns a unique ID to the calling > client > client repeatedly asks server if the request with the given ID is > complete via server.isComplete() > server eventually completes processing request > client eventually gets an affirmative from server.isComplete() and then > client pulls results from server via server.fetchResults() > > originally the client only made one request at a time, and each one was > processed and results fetched in order. > > I want to change this so that the client can send multiple requests to > the server and have them processed in the background. > There are a lot of different approaches to that process, and I'd like > advice on the best way to go about it. > > I could simply place the request checking and results fetching into a > thread or thread-pool so that the client can submit requests to some > kind of queue and the thread will handle submitting the requests from > that queue, checking for completion and fetching results. > > Unfortunately, that would mean lots of calls to the server asking if > each of the requests is complete yet (if I submit 100 requests, I'll be > repeatedly making 100 "are you done yet?" calls). I want to avoid that, > so I thought there would be some way to submit the request and then hold > open the connection to the server and wait on the completion, but still > allow the server to do work. > > Any advice on how to avoid polling the server over and over for request > completion, but also allowing the client to submit multiple requests > without waiting for each one to finish before submitting the next? One obvious improvement over your current scheme would be that instead of polling server for each request submitted, have a unified polling mechanism wherein server returns a list of "ids" of all processed request. But as you too mentioned polling is "often" not the best way, You may try say: 1. Upon submitting a request, client-server agree upon a port on which client will listen for the results. 2. Registering a callback function. (Googling would point to more elaborate discussions on pros and cons ) cheers, amit. Amit Khemka -- onyomo.com Home Page: www.cse.iitd.ernet.in/~csd00377 Endless the world's turn, endless the sun's Spinning, Endless the quest; I turn again, back to my own beginning, And here, find rest. -- http://mail.python.org/mailman/listinfo/python-list
Re: find, replace and save string in ascii file
On 23 Aug 2006 05:48:37 -0700, peter <[EMAIL PROTECTED]> wrote: > Hello all, > > I'm looking for an advice. > > Example (one block in ascii file): > $ > NAME='ALFA' > CODE='x' > $ > > There are many similar blocks in the file with different NAMEs and > different CODEs. What I'm looking for is a script that searchs through > whole file and finds all strings with name ALFA and based on what CODE > is after each ALFA (can be x, y or z) the ALFA name is replaced by > BETAx,BETAy or BETAz and so changed file saves. > > What I did is that I can find all strings which I need, next I change > these strings based on CODE, but what I can't is to replace old string > with new one, on the same position in the file. It always writes new > string at the end of the file. Here is my code A simpler way can be: 1. Read a 'block' from the input file, ( you can simply read a line starting with 'NAME' and keep on reading till you find a line with starting 'CODE') 2. Once you have read a 'block', make whatever you want changes to the NAME and then write the 'block' to a temperory file. If you want the output to be written to same file just 'move' this temperory file to the input file once you are done. Note: if there is other stuff in the input file, apart from such 'blocks' that you want to preserve, a small modification in step 1 would take care of it. hth, amit. -- Amit Khemka -- onyomo.com Home Page: www.cse.iitd.ernet.in/~csd00377 Endless the world's turn, endless the sun's Spinning, Endless the quest; I turn again, back to my own beginning, And here, find rest. -- http://mail.python.org/mailman/listinfo/python-list
Re: Logging to a file and closing it again properly (logging module)
On 6/13/06, Christoph Haas <[EMAIL PROTECTED]> wrote: > Evening, > > I have an application that is running in an endless loop processing an > incoming queue. Every run is supposed to write a log file about the run > and then close it again. While the 'logging' module is generally working > well (even though the documentation makes me miss some proper examples > how everything works together) I can't seem to close the log file again > to open a new one. > > This is basically what I'm doing: > > log = logging.getLogger("myapplication") > log.addHandler(logging.FileHandler("/tmp/testfile")) > log.setLevel(logging.INFO) > log.info("foo") > > Now I'm missing a way to tell this handler to go away. Through 'ipython' > I found out there is a log.handlers array that contains all the > handlers. Perhaps I could delete all of them but I'm sure there is a > more proper way to close files again. > > Googling found me: > > .>>> logging._handlers.clear() > .>>> logging.root.handlers = [] > .>>> for l in logging.Logger.manager.loggerDict.values(): > .>>> l.handlers = [] You can "close" the logger by just removing the handler from the logging object # first creater a logger and file handler fooLogger = logging.getLogger('FOO') fooLogger.setLevel(logging.INFO) fl = logging.FileHandler('foo.txt) fl.setLevel(logging.INFO) fooLogger.addHandler(fl) # remove the handler once you are done fooLogger.removeHandler(fl) cheers, amit. -- Amit Khemka -- onyomo.com Home Page: www.cse.iitd.ernet.in/~csd00377 Endless the world's turn, endless the sun's Spinning, Endless the quest; I turn again, back to my own beginning, And here, find rest. -- http://mail.python.org/mailman/listinfo/python-list
Import: Multiple modules with same name
Hello All, I have multiple modules with same name in different directories (well I guess thats may not be a good practise, but i needed it for debugging and working with various versions). Now how do I import a module with specifying a path. Few minutes of googling suggested: import ihooks import os def my_import(filename): loader = ihooks.BasicModuleLoader() path, file = os.path.split(filename) name, ext = os.path.splitext(file) module = loader.find_module_in_dir(name, path) if not module: raise ImportError, name module = loader.load_module(name, module) return module But It looked like an overkill, Is there a more elegant and better way of doing it ? Thanks in advance, cheers, amit. -- Amit Khemka -- onyomo.com Home Page: www.cse.iitd.ernet.in/~csd00377 Endless the world's turn, endless the sun's Spinning, Endless the quest; I turn again, back to my own beginning, And here, find rest. -- http://mail.python.org/mailman/listinfo/python-list
Re: starting and stopping a program from inside a python script
You can store the pid of the process when started and later use it to kill it. cheers, On 3 Jul 2006 15:28:19 -0700, dfaber <[EMAIL PROTECTED]> wrote: > Aloha! > I want to terminate a process/program from within a python script. > > For example, > if I have a program say foo.sh that starts running, then I can run it > from within a python script using > os.popen('foo.sh') which starts a program/process say 'bar' > > At some point later, I want to kill 'bar'. Currently, I start off the > process and then when the python script exits, the process 'bar' is > still running and I have to issue ps -ef | grep 'bar' and then kill > it. > > Is there any better way of doing this? > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Amit Khemka -- onyomo.com Home Page: www.cse.iitd.ernet.in/~csd00377 Endless the world's turn, endless the sun's Spinning, Endless the quest; I turn again, back to my own beginning, And here, find rest. -- http://mail.python.org/mailman/listinfo/python-list
Re: Generating multiple lists from one list
> On 7/6/06, Girish Sahani <[EMAIL PROTECTED]> wrote: > Thus, for the above list, my output should be: > [['a.1','b.3','c.2'],['a.1','b.4','c.2']] > Another example: Let l = ['a.1','b.3','b.4','c.2','c.6','d.3']. Then > output should be [['a.1','b.3','c.2','d.3'],['a.1','b.3','c.6','d.3'], > ['a.1','b.4','c.2','d.3'],[['a.1','b.4','c.6','d.3'] > > Can anyone suggest me a time-efficient method for doing this?? - x = ['a.1','b.3','b.4','c.2','c.6','d.3'] d = {} for y in x: l = d.get(y.split('.')[0], []) l.append(y) d[y.split('.')[0]] = l output = [[]] for l in d.values(): dfdf = output[:] ## ugly hack to work around references + for i in range(len(l)-1): for j in dfdf: k = j[:] output.append(k) # hack - for i in range(0, len(l)): for l1 in output[i*len(output)/len(l):((i+1)*len(output)/len(l))]: l1.append(l[i]) print output hope that helps ! cheers, amit. > hello ppl, > > Consider a list like ['a.1','b.3','b.4','c.2']. Here 'a','b','c' are > objects and 1,3,4,2 are their instance ids and they are unique e.g. a.1 > and b.1 cannot exist together. From this list i want to generate > multiple lists such that each list must have one and only one instance of > every object. > Thus, for the above list, my output should be: > [['a.1','b.3','c.2'],['a.1','b.4','c.2']] > Another example: Let l = ['a.1','b.3','b.4','c.2','c.6','d.3']. Then > output should be [['a.1','b.3','c.2','d.3'],['a.1','b.3','c.6','d.3'], > ['a.1','b.4','c.2','d.3'],[['a.1','b.4','c.6','d.3'] > > Can anyone suggest me a time-efficient method for doing this?? > > TIA, > girish > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Amit Khemka -- onyomo.com Home Page: www.cse.iitd.ernet.in/~csd00377 Endless the world's turn, endless the sun's Spinning, Endless the quest; I turn again, back to my own beginning, And here, find rest. -- http://mail.python.org/mailman/listinfo/python-list
Re: ElementTree : parse string input
> On 6 Jul 2006 07:38:10 -0700, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote: > Any pointers to getting ElementTree to parse from a string would be > appreciated (of course I could dump it to a temp file, but that doesn't > seem elegent) You can use the "fromstring" method. Btw, did you looked at cElementTree module ? It claims to be much 'faster' and has very similar api as ElementTree Module. link: http://effbot.org/zone/celementtree.htm cheers, amit. -- Amit Khemka -- onyomo.com Home Page: www.cse.iitd.ernet.in/~csd00377 Endless the world's turn, endless the sun's Spinning, Endless the quest; I turn again, back to my own beginning, And here, find rest. -- http://mail.python.org/mailman/listinfo/python-list
Re: Activate a daemon several times a day
did you considered using signals ?! I guess that could well serve the purpose .. more of signals: http://docs.python.org/lib/module-signal.html cheers, amit. On 7/6/06, Yves Glodt <[EMAIL PROTECTED]> wrote: > Hi, > > I have a daemon which runs permanently, and I want it to do a special > operation at some specifiy times every day, consider this configfile > extract: > > [general] > runat=10:00,12:00 > > > What would be the easiest and most pythonic way to do this? > Something like this pseudocode: > > while True: > if now(hours) in runat: > act() > sleep(60) > sleep(10) > > > Please enlighten me! > > Best regards, > Yves > -- > http://mail.python.org/mailman/listinfo/python-list > -- Amit Khemka -- onyomo.com Home Page: www.cse.iitd.ernet.in/~csd00377 Endless the world's turn, endless the sun's Spinning, Endless the quest; I turn again, back to my own beginning, And here, find rest. -- http://mail.python.org/mailman/listinfo/python-list
Re: all ip addresses of machines in the local network
On 23 Aug 2006 21:46:21 -0700, damacy <[EMAIL PROTECTED]> wrote: > hi, sandra. > > no, it's not as complicated as that. all i want to do is to load a > database onto different machines residing in the same network. i hope > there is a way doing it. or perhaps i have a poor understanding of how > networks work. > I expect that you would know the IP range for your network. Then you can simply 'ping' each IP in the range to find wether its alive. Moreover by your description I guess you would actually want to find all machines in your network that run a particular network service, to allow you to "distribute the database". In such case you can use "nmap" with -p option, to find all the machines which are listening on the particular port. hth, amit. Amit Khemka -- onyomo.com Home Page: www.cse.iitd.ernet.in/~csd00377 Endless the world's turn, endless the sun's Spinning, Endless the quest; I turn again, back to my own beginning, And here, find rest. -- http://mail.python.org/mailman/listinfo/python-list
Re: all ip addresses of machines in the local network
On 8/24/06, Amit Khemka <[EMAIL PROTECTED]> wrote: > On 23 Aug 2006 21:46:21 -0700, damacy <[EMAIL PROTECTED]> wrote: > > hi, sandra. > > > > no, it's not as complicated as that. all i want to do is to load a > > database onto different machines residing in the same network. i hope > > there is a way doing it. or perhaps i have a poor understanding of how > > networks work. > > > > I expect that you would know the IP range for your network. Then you > can simply 'ping' each IP in the range to find wether its alive. > Moreover by your description I guess you would actually want to find > all machines in your network that run a particular network service, to > allow you to "distribute the database". In such case you can use > "nmap" with -p option, to find all the machines which are listening on > the particular port. > > hth, > amit. It seems that I am not too busy, so here is a code which may work with a few tweaks here and there: _ import os # base and range of the ip addresses baseIP = "10.0.0." r = 6 interestingPort = 22 # port that you want to scan myIPs = [] for i in range(r): ip = baseIP+str(i) # It may need some customization for your case print "scanning: %s" %(ip) for output in os.popen("nmap %s -p %s" %(ip, interestingPort)).readlines(): if output.__contains__('%s/tcp open' %interestingPort): # i guess it would be tcp myIPs.append(ip) __ print myIPs hth, amit. -- Amit Khemka -- onyomo.com Home Page: www.cse.iitd.ernet.in/~csd00377 Endless the world's turn, endless the sun's Spinning, Endless the quest; I turn again, back to my own beginning, And here, find rest. -- http://mail.python.org/mailman/listinfo/python-list
Re: how can i change the text delimiter
sonald <[EMAIL PROTECTED]> wrote: > Hi, > Can anybody tell me how to change the text delimiter in FastCSV Parser > ? > By default the text delimiter is double quotes(") > I want to change it to anything else... say a pipe (|).. > can anyone please tell me how do i go about it? You can use the parser constructor to specify the field seperator: Python >>> parser(ms_double_quote = 1, field_sep = ',', auto_clear = 1) cheers, amit. -- Amit Khemka -- onyomo.com Home Page: www.cse.iitd.ernet.in/~csd00377 Endless the world's turn, endless the sun's Spinning, Endless the quest; I turn again, back to my own beginning, And here, find rest. -- http://mail.python.org/mailman/listinfo/python-list
Re: how can i change the text delimiter
On 8/30/06, Amit Khemka <[EMAIL PROTECTED]> wrote: > sonald <[EMAIL PROTECTED]> wrote: > > Hi, > > Can anybody tell me how to change the text delimiter in FastCSV Parser > > ? > > By default the text delimiter is double quotes(") > > I want to change it to anything else... say a pipe (|).. Btw, I forgot to mention that AFAIK, in CSV '"' (double quotes) are *not* field seperator delimiters character ! ',' (comma) is the default field seperator, and my earlier suggestion was considering that you want to change the default value for the field seperator. http://en.wikipedia.org/wiki/Comma-separated_values cheers, amit. -- Amit Khemka -- onyomo.com Home Page: www.cse.iitd.ernet.in/~csd00377 Endless the world's turn, endless the sun's Spinning, Endless the quest; I turn again, back to my own beginning, And here, find rest. -- http://mail.python.org/mailman/listinfo/python-list
Re: all ip addresses of machines in the local network
> in my program so far, multiple threads (255 threads in total) spawned > at once with each one of them trying to call socket.gethostbyaddr(ip) > function. i.e. if exception thrown, no machine found. i used .join() to > wait for the threads to terminate. it's fully working however the > problem is that it's too slow. it takes approx. 14 seconds to process > (i tried using 'ping' but it's even slower.). > > my question is.. is there a way to improve performance of the program > if i know what the port number would be? in my case, the port number > will always be constant although i have no clue on what ip addresses > would be (that's the reason all of 255 different addresses must be > tested). > > i tried the same function with the port number specified, > gethostbyaddr(ip:portno), but it is even 10-second slower than using > the same function without a port number specified (i.e. approx. 25 > seconds to complete). You can save some (DNS) overheads by escaping the call "gethostbyaddr", assuming you are not interested in knowing the 'Names' of the machines in your Network. And directly attempt to find the machines which are listenting on the specified port. A simple way of doing this would be to use socket.connect((ip, port)), if the connections succeds you have your machine ! ( There are various other ways of scanning ports, have a look at: http://insecure.org/nmap/nmap_doc.html#connect ) Though I am not sure how 'fast' it would be. Also remember that the time in scanning is affected by network-type, response-time-of-remote-machine, number-of-machines scanned etc. I would still be interested, in seeing how nmap(with some smart options) compares with the python code. ( In my network "nmap -osscan_limit -p 22 -T5 Class_D_Network" completes in 1.5 seconds !) cheers, amit. -- Amit Khemka -- onyomo.com Home Page: www.cse.iitd.ernet.in/~csd00377 Endless the world's turn, endless the sun's Spinning, Endless the quest; I turn again, back to my own beginning, And here, find rest. -- http://mail.python.org/mailman/listinfo/python-list
Re: how can i change the text delimiter
On 31 Aug 2006 00:25:38 -0700, sonald <[EMAIL PROTECTED]> wrote: > Hi, > I am using > Python version python-2.4.1 and along with this there are other > installables > like: > 1. fastcsv-1.0.1.win32-py2.4.exe > 2. psyco-1.4.win32-py2.4.exe > 3. scite-1.63-setup.exe > > We are freshers here, joined new... and are now into handling this > module which validates the data files, which are provided in some > predefined format from the third party. > The data files are provided in the comma separated format. > > The fastcsv package is imported in the code... > import fastcsv > and > csv = fastcsv.parser(strict = 1,field_sep = ',') > > can u plz tell me where to find the parser function definition, (used > above) > so that if possible i can provide a parameter for > text qualifier or text separator or text delimiter.. > just as {field_sep = ','} (as given above) > > I want to handle string containing double quotes (") > but the problem is that the default text qualifier is double quote > > Now if I can change the default text qualifier... to say pipe (|) > the double quote inside the string may be ignored... > plz refer to the example given in my previous query... > > Thanks.. As Fredrik and Skip mentioned earlier, The csv(from www.object-craft.com.au/projects/csv/) module you are using is obsolete. And an improved version is a part of standard python distribution. You should the standard module, in the way as suggested. You may like to do the following. 1. Convert all your data-file with say '|' as the quotechar (text delimiter) 2. Use (Import) the *standard* python cvs module () A sample code would look like: import csv # standard csv module distributed with python inputFile = "csv_file_with_pipe_as_quotchar.txt" reader = csv.reader(open(inputFile), quotechar='|') for row in reader: # do what ever you would like to do cheers, amit. Amit Khemka -- onyomo.com Home Page: www.cse.iitd.ernet.in/~csd00377 Endless the world's turn, endless the sun's Spinning, Endless the quest; I turn again, back to my own beginning, And here, find rest. -- http://mail.python.org/mailman/listinfo/python-list
Re: convert from date string to epoch
On 12/16/06, Stefan Antonelli <[EMAIL PROTECTED]> wrote: > Hi, > > i have to convert several timestamps. The given format, eg "-mm-dd > hh:mm:ss" > has to be converted to an epoch string. Is there any proper way to do this? > > If not, i have to split the given string and resolve this by a calculation? > > Thanks for help. > > Stefan. Check out timegm function in calendar module. The following function converts "mm/dd/" formats into epoch value, you can hack it for your date formats. def convertToEpoch(date): tup = map(int,date.split('/')) l = (tup[2], tup[0], tup[1], 0, 0, 0) epochs = calendar.timegm(l) return (int(epochs)) HTH, amit. -- Amit Khemka -- onyomo.com Home Page: www.cse.iitd.ernet.in/~csd00377 Endless the world's turn, endless the sun's Spinning, Endless the quest; I turn again, back to my own beginning, And here, find rest. -- http://mail.python.org/mailman/listinfo/python-list
Re: catching exceptions
On 16 Dec 2006 03:54:52 -0800, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote: > Hi, In the following program, I have a class Test which has a property > x. Its setx function gets a string value and converts it into a float > and stores into it. > > class Test(object): > def _getx(self): > return self._x > def _setx(self,strvalue): > try: > self._x = float(strvalue) > except ValueError: > print 'Warning : could not set x attribute to %s' % > strvalue > x = property(_getx,_setx) > > > def func1(value): > a = Test() > try: > a.x = value > except ValueError: > #Pop up a error window. > print 'This is second catch' > > > func1('12') > func1('12e1') > func1('a') > > > > func1('12') > func1('12e1') > func1('a') > >>> func1('a') > Warning : could not set x attribute to a > > I am looking for a way to call func1's exception handler also. > Basically I want to have the class's error handler as the basic text > based one, and in the calling side, If I have gui, I will pop-up a > window and say the error message. > One solution is to remove the exception handling inside the class and > leave the entire thing to the caller (software people call this > client?) side -- if the caller has access to gui it will use gui or > else will print the message. Any other way? If I gather correctly, i guess in case of errors/exceptions in a class function, you want to get the error string. One thing that comes straight to my mind is, in such a case use a return statement in functions with two arguments. for example: def foo(self, value): try: a.x = value return True, '' except ValueError: return False, 'Float conversion error: %s' %(value) and when ever u call the function, check the first return value, It is false then alert/print the error message. HTH, amit. -- Amit Khemka -- onyomo.com Home Page: www.cse.iitd.ernet.in/~csd00377 Endless the world's turn, endless the sun's Spinning, Endless the quest; I turn again, back to my own beginning, And here, find rest. -- http://mail.python.org/mailman/listinfo/python-list
Re: trouble getting google through urllib
On 19 Dec 2006 16:12:59 -0800, Dr. Locke Z2A <[EMAIL PROTECTED]> wrote: > I looked at those APIs and it would appear that SOAP isn't around > anymore and there are no APIs for google translate :( Can anyone tell > me how to set the user-agent string in the HTTP header? import urllib2 req = urllib2.Request('http://www.google.com') # add 'some' user agent header req.add_header('User-Agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.7.8) Gecko/20050524 Fedora/1.5 Firefox/1.5') up = urllib2.urlopen(req) cheers, amit -- Amit Khemka -- onyomo.com Home Page: www.cse.iitd.ernet.in/~csd00377 Endless the world's turn, endless the sun's Spinning, Endless the quest; I turn again, back to my own beginning, And here, find rest. -- http://mail.python.org/mailman/listinfo/python-list
Re: Unable to get PIL to load jpeg images
This is because PIL, is not able to find the jpeg library . 1. Install jpeg-libs from sources: (http://www.ijg.org/files/jpegsrc.v6b.tar.gz) 2.0: "clean" the PIL build 2.1 In setup.py that comes with PIL, set the JPEG_ROOT to the jpeg-lib path 3.0 run setup.py I hope that should help .. cheers, amit On 2/9/06, Andrew Gwozdziewycz <[EMAIL PROTECTED]> wrote: > On 2/7/06, Steve Holden <[EMAIL PROTECTED]> wrote: > > [EMAIL PROTECTED] wrote: > > > Someone out there must surely know - please! > > > > > > Peter > > > > > Try building the PIL from scratch. It might give you some insight as > to which library it exactly is looking for. I can remember when > compiling the PIL on my mac having to create a symbolic link to > libjpeg.so.6 or something. It was bizarre but worked fine afterwards. > > -- > Andrew Gwozdziewycz <[EMAIL PROTECTED]> > http://ihadagreatview.org > http://plasticandroid.org > -- > http://mail.python.org/mailman/listinfo/python-list > -- Amit Khemka -- onyomo.com Endless the world's turn, endless the sun's Spinning, Endless the quest; I turn again, back to my own beginning, And here, find rest. -- http://mail.python.org/mailman/listinfo/python-list
ordered sets operations on lists..
Hello, Is there a *direct* way of doing set operations on lists which preserve the order of the input lists ? For Ex. l1 = [1, 5, 3, 2, 4, 7] l2 = [3, 5, 10] and (l1 intersect l2) returns [5, 3] (and (l2 intersect l1) returns [3, 5]) thanks in advance, amit. -- Amit Khemka -- onyomo.com Endless the world's turn, endless the sun's Spinning, Endless the quest; I turn again, back to my own beginning, And here, find rest. -- http://mail.python.org/mailman/listinfo/python-list
Re: Split file into several and reformat
On 6/21/07, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote: > Hi, > > I want to take read an input file (sels.txt) that looks like: > > Begin sels >sel1 = {1001, 1002, 1003, ... >... >1099} > >sel2 = {1001, 1008, 1009 ... >... >1299} > End sels > > And turn it into an output file for each of the "sels" in the input file, i.e > sel1.txt: Once you have read Bruno's pointers ! Have a look at http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/521877 cheers, Amit Khemka -- Co-founder: OnYoMo website: www.onyomo.com wap-site: www.owap.in Home Page: www.cse.iitd.ernet.in/~csd00377 Endless the world's turn, endless the sun's Spinning, Endless the quest; I turn again, back to my own beginning, And here, find rest. -- http://mail.python.org/mailman/listinfo/python-list
Re: import
On 7/6/07, jolly <[EMAIL PROTECTED]> wrote: > Hey guys, > > I'm rather new to python and i'm have trouble(as usual) Hope it becomes un-usual with Python ! > > I want to know if it is possible to change where 'import' looks > this will save me clogging up my python directory Yes. You can tell python where all to look for importing modules. import sys sys.path.append("/this/is/my/modules/path") > Thanks Welcome ! cheers, -- Amit Khemka website: www.onyomo.com wap-site: www.owap.in Home Page: www.cse.iitd.ernet.in/~csd00377 Endless the world's turn, endless the sun's Spinning, Endless the quest; I turn again, back to my own beginning, And here, find rest. -- http://mail.python.org/mailman/listinfo/python-list
Re: Fetching a clean copy of a changing web page
On 7/16/07, John Nagle <[EMAIL PROTECTED]> wrote: > I'm reading the PhishTank XML file of active phishing sites, > at "http://data.phishtank.com/data/online-valid/"; This changes > frequently, and it's big (about 10MB right now) and on a busy server. > So once in a while I get a bogus copy of the file because the file > was rewritten while being sent by the server. > > Any good way to deal with this, short of reading it twice > and comparing? > If you have: 1. Ball park estimate of the size of XML 2. Some footers or "last tags" in the XML May be you can use the above to check the xml and catch the "bogus" ones ! cheers, -- Amit Khemka website: www.onyomo.com wap-site: www.owap.in Home Page: www.cse.iitd.ernet.in/~csd00377 Endless the world's turn, endless the sun's Spinning, Endless the quest; I turn again, back to my own beginning, And here, find rest. -- http://mail.python.org/mailman/listinfo/python-list
Re: how to use imaageop.scale
On 23 May 2007 00:02:34 -0700, Bruce <[EMAIL PROTECTED]> wrote: > Hi, I want to compress a jpg file. e.g. a jpg file which has RGB band > (24bit per pixel), 100 * 100 size to 50 * 50 size. I > tried to use scale function in imageop module but failed. Any > suggestions about this? Thanks! Were there any exceptions/error-messasges ? Do you jpeg libraries installed for hadling jpeg format ? Cheers, -- Amit Khemka -- onyomo.com Home Page: www.cse.iitd.ernet.in/~csd00377 Endless the world's turn, endless the sun's Spinning, Endless the quest; I turn again, back to my own beginning, And here, find rest. -- http://mail.python.org/mailman/listinfo/python-list
Re: how to use imaageop.scale
On 23 May 2007 18:58:28 -0700, Bruce <[EMAIL PROTECTED]> wrote: > On May 23, 5:31 pm, "Amit Khemka" <[EMAIL PROTECTED]> wrote: > > On 23 May 2007 00:02:34 -0700, Bruce <[EMAIL PROTECTED]> wrote: > > > > > Hi, I want to compress a jpg file. e.g. a jpg file which has RGB band > > > (24bit per pixel), 100 * 100 size to 50 * 50 size. I > > > tried to use scale function in imageop module but failed. Any > > > suggestions about this? Thanks! > > > > Were there any exceptions/error-messasges ? > > Do you jpeg libraries installed for hadling jpeg format ? > Amit & Marc, thank you very much. Now I used PIL instead and it works > fine. > But I still don't know how to complete this simple task with imageop > module. I think imageop moudle can handle raw images only, so if you want to use imageop you will need to convert jpeg images to raw format. Cheers, -- Amit Khemka -- onyomo.com Home Page: www.cse.iitd.ernet.in/~csd00377 Endless the world's turn, endless the sun's Spinning, Endless the quest; I turn again, back to my own beginning, And here, find rest. -- http://mail.python.org/mailman/listinfo/python-list
Re: function nested
On 5/24/07, Gigs_ <[EMAIL PROTECTED]> wrote: > def f(start): > stack = [] > def f1(start): > for fname in os.listdir(start): > path = os.path.join(start, fname) > if os.path.isfile(path): > stack.append(path) > else: > f1(path) > f1(start) > return stack > > > i feel s stupid right now > forgot to call f1 > > any comments how to make this better? os.walk is just the way for you ! Cheers, Amit Khemka -- onyomo.com Home Page: www.cse.iitd.ernet.in/~csd00377 Endless the world's turn, endless the sun's Spinning, Endless the quest; I turn again, back to my own beginning, And here, find rest. -- http://mail.python.org/mailman/listinfo/python-list
Re: Changing Unicode object to Tuple Type
On 24 May 2007 04:45:32 -0700, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote: > Can we have change a unicode string Type object to a Tuple type > object.. If so how *Loosely* speaking a tuple is a collection of multiple objects. So what are the objects that you want to put in that tuple ?! Or do you want to store the unicode string as one of the member in a tuple ? In which case you can just do it the obvious way (though i guess thats not the question you asked)! Cheers, Amit Khemka -- onyomo.com Home Page: www.cse.iitd.ernet.in/~csd00377 Endless the world's turn, endless the sun's Spinning, Endless the quest; I turn again, back to my own beginning, And here, find rest. -- http://mail.python.org/mailman/listinfo/python-list
Re: Web Archtecture using tow layers in Phyton
On 5/23/07, Wagner Garcia Campagner <[EMAIL PROTECTED]> wrote: > Hello, > > I need to develop an web applications that meet the following requirements: > > - 2 layers: the first one is the user interface (browser) and the second one > is the interaction with the operacional system of the server. > - the second layer must be developed using Python. > > I'd like to know if it is possible to implement this system... making the > second layer using python and the first layer using another web technologies > like AJAX for example. Yes, It is very much possible and you will find the quite a few of such impementations . > Does anybody have any experience in developing python web applications? > Maybe send me some links or documentation about it... Search this news-group or web for "python web framework" and you can choose one based on your specific needs. ( some names that often pop up are: django, cherrypy, webware, pylons etc) > The final goal is to make diferent user interfaces (layer 1) that can > integrate with the second layer... for example, one web interface and one > local interface using python+qt (example)... i don't know if this is > possible and how can this be implemented... any help is aprreciated... Read the documentation of the framework ( if any) you choose to work with you may find templating system useful. For standalone app you can look at wxPython, which can communicate to your server at some port. Cheers, -- Amit Khemka -- onyomo.com Home Page: www.cse.iitd.ernet.in/~csd00377 Endless the world's turn, endless the sun's Spinning, Endless the quest; I turn again, back to my own beginning, And here, find rest. -- http://mail.python.org/mailman/listinfo/python-list
Re: Xml parser
On 5/24/07, ashish <[EMAIL PROTECTED]> wrote: > Hi All, > > I want to know weather is there any api available in python for parsing > xml(XML parser) Checkout cElementTree . Cheers, -- Amit Khemka -- onyomo.com Home Page: www.cse.iitd.ernet.in/~csd00377 Endless the world's turn, endless the sun's Spinning, Endless the quest; I turn again, back to my own beginning, And here, find rest. -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie help understanding...
On 26 May 2007 00:23:32 -0700, mark <[EMAIL PROTECTED]> wrote: > Hi I am trying to get a piece of code to work based on an exercise in > a book. Any help appreciated. Can someone please explain what is going > on here. > > I am trying to read from a text file a list of cards with the > following format and sort firstly by suit and then by rank > > h 1 > d 2 > c 5 > s 9 > h2 > d3 > > etc... > > I get the following error; > Traceback (most recent call last): > File "F:/###UNI###/ITC106/ass2/cardread.py", line 25, in > t.append( t[0] + 400 ) > AttributeError: 'str' object has no attribute 'append' > def read_cards(filename): > cards = [] > for card in open(filename, 'r'): > cards.append(card.strip()) > return cards > > # read the deck of cards from a file > filename = 'cards.txt' > cards = read_cards(filename) > > > for t in read_cards(filename): > if t[1] == 'h': > t.append( t[0] + 100 ) > elif t[1] == 'd': > t.append( t[0] + 200 ) > elif t[1] == 'c': > t.append( t[0] + 300 ) > else: > t.append( t[0] + 400 ) In read_cards function you are appending a string in the list 'cards' , where i guess you wanted to append a list of suit and rank in list cards. def read_cards(filename): cards = [] for card in file(filename): cards.append(cards.split()) # i assume that suit and rank is separated by white space return cards or better still cards = [card.split() for card in file(filename)] Cheers, Amit Khemka -- onyomo.com Home Page: www.cse.iitd.ernet.in/~csd00377 Endless the world's turn, endless the sun's Spinning, Endless the quest; I turn again, back to my own beginning, And here, find rest. -- http://mail.python.org/mailman/listinfo/python-list
Re: Filtering content of a text file
On 7/27/07, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote: > Hello All, > > I'd greatly appreciate if you can take a look at the task I need help > with. > > It'd be outstanding if someone can provide some sample Python code. > > Thanks a lot, > > Ira > > --- > Problem > --- > > I am working with 30K+ record datasets in flat file format (.txt) that > look like this: > > //-+alibaba sinage > //-+amra damian//_9 > //-+anix anire//_ > //-+borom > //-+bokima sun drane > //-+ciren > //-+cop calestieon eded > //-+ciciban > //-+drago kimano sole > > > The records start with the same string (in the example //-+) wich is > followed by another string of characters taht's changing from record > to record. > > I am working on one file at the time and for each file I need to be > able to do the following: > > a) By looping thru the file the program should isolate all records > that have letter a following the //-+ > b) The isolated dataset will contain only records that start with //- > +a > c) Save the isolated dataset as flat flat text file named a.txt > d) Repeat a), b) and c) for all letters of english alphabet (a thru z) > and numerical values (0 thru 9) Well that should be easy if you take a look at methods in "string" module: A rough sketch would be : import string # import string module alnums = list(string.lowercase+string.digits) # create a list of alphabets and digits for alnum in alnums: outfile = open(alnum+'.txt', 'w') for line in file("myrecords.txt"): # iterate over the records if line.startswith("//-+"+alnum): # check your condition # write the matches to a file outfile.write(line) outfile.close() However rather than looping over the file for each alnum you may just iterate over the file, and check the starting characters (if len(line) > 4:ch=line[4]) , and if it is alnum then process it. Cheers, -- Amit Khemka website: www.onyomo.com wap-site: www.owap.in Home Page: www.cse.iitd.ernet.in/~csd00377 Endless the world's turn, endless the sun's Spinning, Endless the quest; I turn again, back to my own beginning, And here, find rest. -- http://mail.python.org/mailman/listinfo/python-list
Re: Logging module gives duplicate log entries
On 8/21/07, Shiao <[EMAIL PROTECTED]> wrote: > Hi, > I am getting duplicate log entries with the logging module. > > The following behaves as expected, leading to one log entry for each > logged event: > > logging.basicConfig(level=logging.DEBUG, filename='/tmp/foo.log') > > But this results in two entries for each logged event: > > applog = logging.getLogger() > applog.setLevel(logging.DEBUG) > hdl = logging.FileHandler('/tmp/foo.log') > applog.addHandler(hdl) > You need to remove the handler from the logging object # remove the handler once you are done applog.removeHandler(hdl) Cheers, amit. Amit Khemka website: www.onyomo.com wap-site: www.owap.in Home Page: www.cse.iitd.ernet.in/~csd00377 Endless the world's turn, endless the sun's Spinning, Endless the quest; I turn again, back to my own beginning, And here, find rest. -- http://mail.python.org/mailman/listinfo/python-list
Re: for statement on empty iterable
On 8/22/07, james_027 <[EMAIL PROTECTED]> wrote: > hi Paul, > > > > > That doesn't crash or anything like that, but it also doesn't > > set the index variable, which can cause confusion in some situations. > > Thanks for your quick answer ... Actually I was thinking how do I > access the index inside a for statement? Can you help Have a look at "enumerate", You can iterate over a list like: for i,x in enumerate(['a', 'b', 'c']): print i, x It prints: 0 a 1 b 2 c cheers, amit Amit Khemka website: www.onyomo.com wap-site: www.owap.in Home Page: www.cse.iitd.ernet.in/~csd00377 Endless the world's turn, endless the sun's Spinning, Endless the quest; I turn again, back to my own beginning, And here, find rest. -- http://mail.python.org/mailman/listinfo/python-list
Re: TypeError: 'module object is not callable'
On 9/3/07, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote: > Hi > > I am new to Python and have recieved this error message when trying to > instantiate an object from a class from another file within the same > directory and wondered what I have done wrong. > > I have a Step.py class: > class Step(object) > def __init__(self, sName): > "Initialise a new Step instance" > self.sName = sName > self.depSteps = [] > self.remDepSteps = [] > self.isCompleted = 0 > > > Then I have created a new file within the same directory called > main.py: > > import Step > a = Step("magn") > > The following however generates the error > Traceback (most recent call last): > File "main.py", line 3, in ? > a = Step("magn") > TypeError: 'module' object is not callable > > If anyone could help point me in the right direction, how to fix this > problem it would be much appreciated. > Chris The exception is being raised as you are being confused about the names ie: you have a class named "Step" in a module named "Step.py" . And by importing the module the only "Step" python sees is the module not the names declared within the module. To access a name defined in the module you can do : example1: import Step a = Step.Step("magn") # It refers the name "Step" defined IN the module "Step" example 2: from Step import Step # You directly import the class ( and make the name visible in your name space) a = Step("magn") Also have a look at: http://effbot.org/zone/import-confusion.htm http://docs.python.org/ref/import.html Cheers, -- Amit Khemka website: www.onyomo.com wap-site: www.owap.in -- http://mail.python.org/mailman/listinfo/python-list
Re: TypeError: 'module object is not callable'
On 9/3/07, Bruno Desthuilliers <[EMAIL PROTECTED]> wrote: > Amit Khemka a écrit : > (snip) > > The exception is being raised as you are being confused about the > > names ie: you have a class named "Step" in a module named "Step.py" . > > > Actually, the module is named 'Step', not 'Setp.py' !-) > > Yup, My Bad ! Thanks. -- Amit Khemka website: www.onyomo.com wap-site: www.owap.in -- http://mail.python.org/mailman/listinfo/python-list
Re: TypeError: 'module object is not callable'
On 9/4/07, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote: > Thanks guys. Changing to how Python does things has a lot of geting > used to! > Do any of you have any ideas on the best way to do the following > problem: > > Each loop I perform, I get a new list of Strings. > I then want to print these lists as columns adjacent to each other > starting with the first > created list in the first column and last created list in the final > column. > > If you need any more information, just let me know! > Cheers If I understand correctly what you may want is: >>> l = ['1', '2', '3', '4'] you can do: >>> print "\t".join(l) # lookup join method in string module, assuming "\t" as the delimiter or, >>> for i in l: print i, '\t' , # note the trailing "," If this is not what you want, post an example. Btw, Please post new issues in a separate thread. Cheers, -- Amit Khemka website: www.onyomo.com wap-site: www.owap.in -- http://mail.python.org/mailman/listinfo/python-list
Re: TypeError: 'module object is not callable'
On 9/4/07, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote: > On Sep 4, 11:24 am, "Amit Khemka" <[EMAIL PROTECTED]> wrote: > > On 9/4/07, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote: > > > > > Thanks guys. Changing to how Python does things has a lot of geting > > > used to! > > > Do any of you have any ideas on the best way to do the following > > > problem: > > > > > Each loop I perform, I get a new list of Strings. > > > I then want to print these lists as columns adjacent to each other > > > starting with the first > > > created list in the first column and last created list in the final > > > column. > > > > > If you need any more information, just let me know! > > > Cheers > > > > If I understand correctly what you may want is: > > > > >>> l = ['1', '2', '3', '4'] > > > > you can do: > > > > >>> print "\t".join(l) # lookup join method in stringmodule, > > > > assuming "\t" as the delimiter > > > > or, > > > > >>> for i in l: > > > > print i, '\t' , # note the trailing "," > > > > If this isnotwhat you want, post an example. > > > > Btw, Please post new issues in a separate thread. > > > > Cheers, > > -- > > > > Amit Khemka > > website:www.onyomo.com > > wap-site:www.owap.in > > I think that is very similar to what I want to do. > Say I had lists a = ["1" , "2", "3"] b = ["4", "5", "6"] c = ["7", > "8", "9"] > Stored in another list d = [a,b,c] > I want the printed output from d to be of the form: > 1 4 7 > 2 5 8 > 3 6 9 > > >From what I am aware, there is no table module to do this. The '\t' > operator looks like it can allow this, > I am playing with it at the moment, although going for my lunch break > now! Have a look at function 'zip' or function 'izip' in module "itertools" . -- Amit Khemka website: www.onyomo.com wap-site: www.owap.in -- http://mail.python.org/mailman/listinfo/python-list
Re: Printing lists in columns
On 9/5/07, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote: > Thanks guys, I really appreciate it. I have never used google groups > before and am so impressed with how helpful you all are. It is also lovely > that none of you mock my little knowledge of Python but just want to > improve it. And we are proud of it ! > I have another question in relation to the izip_longest function (I > persume > this should be within the same topic). > Using this funciton, is there a way to manipulate it so that the > columns can be formated > tabular i.e. perhaps using something such as str(list).rjust(15) > because currently the columns > overlap depending on the strings lengths within each column/list of > lists. i.e. my output is > currently like: > > bo, daf, da > pres, ppar, xppc > magnjklep, *, dsa > *, *, nbi > > But I want it justified, i.e: > > bo , daf, da > pres , ppar, xppc > magnjklep,*, dsa > *,*, nbi You can format the output while "print"ing the table. Have a look at: http://www.python.org/doc/current/lib/typesseq-strings.html example: for tup in izip_longest(*d, **dict(fillvalue='*')): print "%15s, %15s, %15s" %tup # for a tuple of length 3, you can generalize it > I am struggling to understand how the izip_longest function works > and thus don't really know how it could be manipulated to do the > above. > It would be much apprecited if somoene could also explain how > izip_function > works as I don't like adding code into my programs which I struggle to > understand. > Or perhaps I have to pad out the lists when storing the Strings? > > Any help would be much appreciated. This is an example of "generator" functions, to understand what they are and how they work you can: 1. web-search for "python generators" 2. have a look at "itertools" module, for more generators -- Amit Khemka website: www.onyomo.com wap-site: www.owap.in -- http://mail.python.org/mailman/listinfo/python-list
Re: Looping through File Question
On 9/5/07, Francesco Guerrieri <[EMAIL PROTECTED]> wrote: > On 9/5/07, planetmatt <[EMAIL PROTECTED]> wrote: > > I am a Python beginner. I am trying to loop through a CSV file which > > I can do. What I want to change though is for the loop to start at > > row 2 in the file thus excluding column headers. > > > > At present I am using this statement to initiate a loop though the > > records: > > > > for line in f.readlines(): > > > > How do I start this at row 2? > > > > you can simply call (and maybe throw away) f.readline() a single time before > looping. > If the lenght of the first line is fixed, you can also use f.seek to start > reading from the second row. > > francesco Btw, if you are trying to read a csv file and parse it, you can save some work .. have a look at "csv" module ! -- Amit Khemka website: www.onyomo.com wap-site: www.owap.in -- http://mail.python.org/mailman/listinfo/python-list
Re: Using wild character
On 9/6/07, Sreeraj <[EMAIL PROTECTED]> wrote: > hi, > > I am a beginner in Python. I wish to know how can i filter a list of > strings using wild characters.ie > Lets say i have list countries = > ["india","africa","atlanta","artica","nigeria"]. I need only the list > of string starting with 'a'. There are a few ways of doing so. For some simple operations there are functions on the strings, If you want some more complex "filtering" then have a look at Python's regular expression module "re". example: >>> l = ["india","africa","atlanta","artica","nigeria"] >>> al = [c for c in l if c.startswith('a')] # this is a list comprehension >>> al ['africa', 'atlanta', 'artica'] To know more about list comprehensions, have a look at: http://docs.python.org/tut/node7.html#SECTION00714 Methods on strings: http://docs.python.org/lib/string-methods.html#string-methods Btw, not all of names in your list are countries ! Cheers, -- Amit Khemka website: www.onyomo.com wap-site: www.owap.in -- http://mail.python.org/mailman/listinfo/python-list
Re: Python and Cron
On 9/8/07, Greg Lindstrom <[EMAIL PROTECTED]> wrote: > # run client pricing at 0215 (p) Monday-Friday > 15 2 * * 1-5 cd /m01/edith/src && /usr/bin/python /m01/edith/src/driver.py > --paid-date yesterday --jobname professional >> > /m01/edith/stdout/ecomppo.stdout 2&>1 "2&>1", Is that a typo ? It should be "2>&1" . Are you *sure* that the cron job is running ? cheers, -- Amit Khemka website: www.onyomo.com wap-site: www.owap.in -- http://mail.python.org/mailman/listinfo/python-list
Re: Dictionary of Dictionaries
On 5 Mar 2007 02:22:24 -0800, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote: > Hi, > > I have the following - > > messagesReceived = dict.fromkeys(("one","two"), {}) This will create a dictionary "messagesReceived", with all the keys referring to *same instance* of the (empty) dictionary. ( try: messagesReceived = dict( [(k,{}) for k in ('one', 'two') ] ) ) > > messagesReceived['one']['123'] = 1 > messagesReceived['two']['121'] = 2 > messagesReceived['two']['124'] = 4 > > This gives: > > {'two': {'121': 2, '123': 1, '124': 4}, 'one': {'121': > 2, '123': 1, '124': 4}} And hence the results ! HTH, -- Amit Khemka -- onyomo.com Home Page: www.cse.iitd.ernet.in/~csd00377 Endless the world's turn, endless the sun's Spinning, Endless the quest; I turn again, back to my own beginning, And here, find rest. -- http://mail.python.org/mailman/listinfo/python-list
Re: converting epoch time to string (and vice versa)
On 3/13/07, Astan Chee <[EMAIL PROTECTED]> wrote: > Hi, > I have a string in this format "DD/MM/YYY" for example: > tdate = "18/01/1990" > and Im trying to convert this to epoch time, can anyone help? import calendar t = map(int,tdate.split('/')) epochs = calendar.timegm((t[2], t[1], t[0], 0, 0, 0)) > Im also trying to convert that epoch time to the string format > previously. Can anyone help this one too? import time time.ctime(epochs) cheers, amit. -- Amit Khemka -- onyomo.com Home Page: www.cse.iitd.ernet.in/~csd00377 Endless the world's turn, endless the sun's Spinning, Endless the quest; I turn again, back to my own beginning, And here, find rest. -- http://mail.python.org/mailman/listinfo/python-list
Re: XML Parsing
On 28 Mar 2007 00:38:38 -0700, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote: > I want to parse this XML file: > > > > > > > filename > > Hello > > > > > filename2 > > Hello2 > > > > > > This XML will be in a file called filecreate.xml > > As you might have guessed, I want to create files from this XML file > contents, so how can I do this? > What modules should I use? What options do I have? Where can I find > tutorials? Will I be able to put > this on the internet (on a googlepages server)? http://effbot.org/zone/celementtree.htm HTH, -- Amit Khemka -- onyomo.com Home Page: www.cse.iitd.ernet.in/~csd00377 Endless the world's turn, endless the sun's Spinning, Endless the quest; I turn again, back to my own beginning, And here, find rest. -- http://mail.python.org/mailman/listinfo/python-list
Re: Weird behavior in search in a list
On 29 Mar 2007 04:51:00 -0700, Su Y <[EMAIL PROTECTED]> wrote: > hi all, > I can't understand how this code work, its behavior is really weird > for me... > > I want find the first number in extend[] which is larger than num, so > I wrote: > def find(num): > count=0 > for elem in extend: > if elem count+=1 > return count > > I found that if extend[] is monotonous, like [1.1, 2.3, 3.2, 4.5, > 5.6], > it works fine: find(4) returns 3, extend[3] is 4.5. > But, if extend[] is not monotonous, like [1.1, 2.3, 3.2, 4.5, 5.6, > 4.6, 3.4, 2.1, 0.3], > find(4) returns 6, extend[6] is 3.4! > > what's going on here? I really can't understand Actually your function "find" returns the number of elements in list extend, which are smaller than the argument. Perhaps you wanted to 'break' when once the condition is met. def find(num): count=0 for elem in extend: if elem>num: break else: count+=1 return count Btw a concise way could be: def getfirstbigger(num): for i,x in enumerate(extend): if x>num:return i return len(extend) HTH, -- Amit Khemka -- onyomo.com Home Page: www.cse.iitd.ernet.in/~csd00377 Endless the world's turn, endless the sun's Spinning, Endless the quest; I turn again, back to my own beginning, And here, find rest. -- http://mail.python.org/mailman/listinfo/python-list
Re: Weird behavior in search in a list
> On 29 Mar 2007 04:51:00 -0700, Su Y <[EMAIL PROTECTED]> wrote: > > I want find the first number in extend[] which is larger than num, so > On 3/29/07, Amit Khemka <[EMAIL PROTECTED]> wrote: > Btw a concise way could be: > def getfirstbigger(num): > for i,x in enumerate(extend): > if x>num:return i > return len(extend) I forgot to add that you can as well 'return' the the item (along with the index), but in case all the items in the list are smaller than the argument, what return value do you require? -- Amit Khemka -- onyomo.com Home Page: www.cse.iitd.ernet.in/~csd00377 Endless the world's turn, endless the sun's Spinning, Endless the quest; I turn again, back to my own beginning, And here, find rest. -- http://mail.python.org/mailman/listinfo/python-list
Re: Weird behavior in search in a list
On 3/29/07, Michael Bentley <[EMAIL PROTECTED]> wrote: > > On Mar 29, 2007, at 6:51 AM, Su Y wrote: > > > > I want find the first number in extend[] which is larger than num, so > def find(num): > # check to make sure there *is* a value greater than num > if max(extend) > num: > # then return the smallest value that is greater than num > return min([x for x in extend if x > num]) > else: > return None I think OP wants the first value in the list greater than 'num' not the smallest greater value in the list. cheers, -- Amit Khemka -- onyomo.com Home Page: www.cse.iitd.ernet.in/~csd00377 Endless the world's turn, endless the sun's Spinning, Endless the quest; I turn again, back to my own beginning, And here, find rest. -- http://mail.python.org/mailman/listinfo/python-list
Re: os.system questions
On 3/31/07, Eric Price <[EMAIL PROTECTED]> wrote: > Hi; > I have a couple bugs to work out in the below script; namely, I don't know > how to capture the result of an os.system command, nor am I convinced that > the call to os.system actually results in the execution of the command. Here > is the script: > > #!/usr/local/bin/python > import re, os > > def freshReboot(): > up = os.system("uptime") > if re.search('day|hour', up): > pass > else: > first = up > tup = re.split('min', up) > first = tup[0] > n = len(first) > char = first[n-3:n-2] > if re.match(' ', char): > > os.system("/usr/local/etc/rc.d/zz_mysql_starter_script.sh") > > > Here are my problems: > > up = os.system("uptime") > How do I assign the output of "uptime" to the variable "up"? > > os.system("/usr/local/etc/rc.d/zz_mysql_starter_script.sh") > When I substitute a test variable for "up", I don't get this script to > actually run. Everything else is tested and works. Why won't this script > run? os.system doesn't allow you to get the output of the program, use os.popen instead. example: import os up = os.popen('uptime').readlines() Cheers, -- Amit Khemka -- onyomo.com Home Page: www.cse.iitd.ernet.in/~csd00377 Endless the world's turn, endless the sun's Spinning, Endless the quest; I turn again, back to my own beginning, And here, find rest. -- http://mail.python.org/mailman/listinfo/python-list
Re: Question about text in Python
On 4/2/07, Steve <[EMAIL PROTECTED]> wrote: > Hi, > > I've created a Python program that a user enteres one line of text which > will then create an acronym from that text. > > What I want to add to the program is the abilty to rerun this process (where > the user enteres another line of text) until the user has had enough and > enters a blank line which would then end the program. > > Can anyone help with this? > > thanks > > -- > http://mail.python.org/mailman/listinfo/python-list > Untested: if __name__ == "__main__": userinp=raw_input("Query>") while userinp: callmyabbrvfunction(userinp) userinp=raw_input("Another Query>") print "Exit: You have entered empty string !" cheers, -- Amit Khemka -- onyomo.com Home Page: www.cse.iitd.ernet.in/~csd00377 Endless the world's turn, endless the sun's Spinning, Endless the quest; I turn again, back to my own beginning, And here, find rest. -- http://mail.python.org/mailman/listinfo/python-list
Re: how to remove multiple occurrences of a string within a list?
On 3 Apr 2007 11:20:33 -0700, bahoo <[EMAIL PROTECTED]> wrote: > Hi, > > I have a list like ['0024', 'haha', '0024'] > and as output I want ['haha'] > > If I > myList.remove('0024') > > then only the first instance of '0024' is removed. To remove all items with multiple occurances in myList: list(set(myList) - set([x for x in myList if myList.count(x)>1])) cheers, -- Amit Khemka -- onyomo.com Home Page: www.cse.iitd.ernet.in/~csd00377 Endless the world's turn, endless the sun's Spinning, Endless the quest; I turn again, back to my own beginning, And here, find rest. -- http://mail.python.org/mailman/listinfo/python-list
Re: Storing of folder structure in SQL DB
On 5 Apr 2007 04:58:22 -0700, Sergei Minayev <[EMAIL PROTECTED]> wrote: > Hi All! > Can you please help me with the following problem: > I need to store a copy of local folders structure in MySQL database. > I have chosen the following table structure for that: > > | id | id_uplink | folder_name | > > id - unique property of each folder. > id_uplink - id of upper level folder is stored here (for example: if > id of c:\test is 1, than id_uplink of c:\test\python equals 1). > folder_name - name of folder. > You see, i dont want to store the path list, but the structure. > > The question is how to implement that in Python. I easily made it in C+ > + using recursion. But, unfortunately, I can't figure it out how to > make it in python using os.walk function (or can you recommend smth. > else???). :( Though it looks quite simple, but anyway. > > Best Regards, os.walk should be more than sufficient in your case. You can navigate the directory structure and at each 'new' directory find its parents id and assign a new-id to this 'new' directory. An Example: import os root='/my/root/directory' id =0 tree={root:(-1, id)} id+=1 for path, dirs, files in os.walk(root): for dir in dirs: if not tree.has_key(path+'/'+dir): tree[path+'/'+dir]=(tree[path][1], id) id+=1 It stores ids as a tuple (parent_id, id) in a dictionary(tree). Should be straight forward to modify to your requirements. Also you can make the following code more efficient by saving/caching some lookups ! Cheers, -- Amit Khemka -- onyomo.com Home Page: www.cse.iitd.ernet.in/~csd00377 Endless the world's turn, endless the sun's Spinning, Endless the quest; I turn again, back to my own beginning, And here, find rest. -- http://mail.python.org/mailman/listinfo/python-list
Re: Storing of folder structure in SQL DB
On 4/5/07, Amit Khemka <[EMAIL PROTECTED]> wrote: > On 5 Apr 2007 04:58:22 -0700, Sergei Minayev <[EMAIL PROTECTED]> wrote: > An Example: > > import os > root='/my/root/directory' > id =0 > tree={root:(-1, id)} > id+=1 > for path, dirs, files in os.walk(root): > for dir in dirs: > if not tree.has_key(path+'/'+dir): > tree[path+'/'+dir]=(tree[path][1], id) > id+=1 > > It stores ids as a tuple (parent_id, id) in a dictionary(tree). Should > be straight forward to modify to your requirements. Also you can make > the following code more efficient by saving/caching some lookups ! use os.sep instead of '/' ! Cheers, -- Amit Khemka -- onyomo.com Home Page: www.cse.iitd.ernet.in/~csd00377 Endless the world's turn, endless the sun's Spinning, Endless the quest; I turn again, back to my own beginning, And here, find rest. -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie question: how to read back the dictionary from a file?
On 16 Apr 2007 03:03:40 -0700, lancered <[EMAIL PROTECTED]> wrote: > Hi Dear all, > > I have some data here in the form of a dictionary, called "vdic". Then > I write them to a data file "f" using the write function as > f.write(str(vdic)). The keys of this dictionary are integers and > values are float numbers. Something like this: > > { 1: 0.00951486513347, 2: 0.0388123556019, ... ...} > > Now, I want to read these data back in another function. Of course, I > could parse the string little by little, e.g, first read a "{", then > loop read a int, then read a ":", then a float etc etc... Since it is > written out with standard python builtin functions, I guess there may > be some more direct method than this, say a function in some modules? > Could someone give me a hint? > Check out cPickle or shelve modules. Cheers, -- Amit Khemka -- onyomo.com Home Page: www.cse.iitd.ernet.in/~csd00377 Endless the world's turn, endless the sun's Spinning, Endless the quest; I turn again, back to my own beginning, And here, find rest. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to generate a continuous string
On 16 Apr 2007 03:03:26 -0700, 人言落日是天涯,望极天涯不见家 <[EMAIL PROTECTED]> wrote: How to generate a continuous string, like this "aaa" the number of characters is dynamic. Is there a module or function implement this string ? such as: duplicate_string(char, num) mystr = mychar*n n: Integer (number of times you want to duplicate) Cheers, -- Amit Khemka -- onyomo.com Home Page: www.cse.iitd.ernet.in/~csd00377 Endless the world's turn, endless the sun's Spinning, Endless the quest; I turn again, back to my own beginning, And here, find rest. -- http://mail.python.org/mailman/listinfo/python-list
Re: mass editing for keys in a dictionary
On 9/14/07, james_027 <[EMAIL PROTECTED]> wrote: > hi, > > How could I transform something like this > > dict_1 = {'customer_id':1, 'item_id':3, amount:100} > > into > > dict_2 = {'customer':1, 'item':3, amount:100} A one liner would be : >>> dict_2 = dict([(k.split('_')[0], v) for (k,v) in dict_1.iteritems()]) It would split the keys by '_' and use first part of split as the new key ! You must be aware be careful in cases where there are keys like 'customer_1' , 'customer_2', ... Cheers, -- Amit Khemka website: www.onyomo.com wap-site: www.owap.in -- http://mail.python.org/mailman/listinfo/python-list
Re: global name is not defined - but this is actually a function's name
On 9/21/07, Mridula Ramesh <[EMAIL PROTECTED]> wrote: > hi. > > i'm a beginner and i'm trying to get the hang of classes and functions. my > code looks like this: > > > > class showRecord(main): > def __init__(self): > global gmax > #now to create the screen by placing all the widgets > rt = Tk() > showbuttons() > #call the scroller to DoSomething > scroll() > > def showbuttons(self): > # NAVIGATION BAR-- > NavBut1 = Button(rt, text="|<", width=6, height=2, > bg="DarkSeaGreen", fg="Black") > NavBut1.grid(row=10, column=20, padx=6, pady=6, columnspan=3) > NavBut2 = Button(rt, text="<<", width=6, height=2, > bg="DarkSeaGreen", fg="Black") > NavBut2.grid (row=10, column=25, padx=6, pady=6, columnspan=3) > #widget bindings > NavBut2.bind('', lambda e:GoPrev(ctr)) > > > > my problem is at the 6th line: showbuttons() > the error says "global name "showbuttons" is not defined but it's not a > global variable. what am i doing wrong? use self.showbuttons() > also, should i say ... > > def showbuttons(self): This should work ! Cheers, -- Amit Khemka website: www.onyomo.com wap-site: www.owap.in -- http://mail.python.org/mailman/listinfo/python-list
Re: sorting a list numbers stored as strings
On 9/24/07, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote: > hi, > > I have the following list - > > ["1", "11", "2", "22"] > > how do I sort it like this - > > ["1", "2", "11", "22"] > Hi, >>> l = ["1", "11", "2", "22"] >>> sorted(l, cmp = lambda x, y: cmp(int(x), int(y))) # provide your own compare function ! >>> l ['1', '2', '11', '22'] Cheers, -- Amit Khemka website: www.onyomo.com wap-site: www.owap.in -- http://mail.python.org/mailman/listinfo/python-list
Re: sorting a list numbers stored as strings
On 9/24/07, Carsten Haese <[EMAIL PROTECTED]> wrote: > On Mon, 2007-09-24 at 16:53 +0530, Amit Khemka wrote: > > On 9/24/07, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote: > > > > >>> l = ["1", "11", "2", "22"] > > >>> sorted(l, cmp = lambda x, y: cmp(int(x), int(y))) # provide your > > own compare function ! > > >>> l > > ['1', '2', '11', '22'] > > That interpreter session is a work of fiction, since sorted returns the > sorted list instead of sorting the list in place. I am sorry, thanks for pointing out ! What I intended to write was: >>> l = sorted(l, cmp = lambda x, y: cmp(int(x), int(y))) Btw, It was more of a goofed up Reality show ! cheers, -- Amit Khemka website: www.onyomo.com wap-site: www.owap.in -- http://mail.python.org/mailman/listinfo/python-list
Re: generating range of numbers
On 10/3/07, vimal <[EMAIL PROTECTED]> wrote: > hi all, > > i am new to python. > i just want to generate numbers in the form like: > > 1,2,4,8,16,32.to a maximum of 1024 > > using a range function [2**i for i in range(11)] This is a list comprehension, for more have a look at http://docs.python.org/tut/node7.html#SECTION007140000 Cheers, -- Amit Khemka website: www.onyomo.com wap-site: www.owap.in -- http://mail.python.org/mailman/listinfo/python-list
Re: HELP me Am very new one To python
On 10/4/07, Damodhar <[EMAIL PROTECTED]> wrote: > hi, > > Am working in PHP MYSQL. I am very very interest to learn Python but i > don't Know Little Bit, > am using windows Xp, Ialready download from > http://www.python.org/ftp/python/2.5.1/python-2.5.1.ia64.msi > > and install into C:\Python25 > > whats the next step . i UsedApache 2.0 run as a local server.. > > whats the next step . please say one by one i already read the > documentation but i cant get clearer. > > how to configure apache where i want to configure . > if any files want to copy in to apache folder, wahts the procedure to > start the coding pls help me am very very beginner pls spend some time > to teach how to do that.please plaes I presume that you want to do web programming using python. Have a look at following: Using mod_python: http://webpython.codepoint.net/mod_python CGI: http://docs.python.org/lib/module-cgi.html FastCGI: http://www.fastcgi.com/ You can also explore some of existing web frameworks. Search web for "python web frameworks", some popular ones are django, pylons etc. Try to play with one of the above that you like and suits your needs. If you still get struck , please post specific issues. I wish and hope learning python would be a pleasing experience ! Cheers, amit. -- Amit Khemka website: www.onyomo.com wap-site: www.owap.in -- http://mail.python.org/mailman/listinfo/python-list
Re: Last value of yield statement
On 10/10/07, Shriphani <[EMAIL PROTECTED]> wrote: > On Oct 10, 3:34 pm, Dustan <[EMAIL PROTECTED]> wrote: > > On Oct 10, 5:19 am, Shriphani <[EMAIL PROTECTED]> wrote: > > > > > Hello all, > > > > > Let us say I have a function like this: > > > > > def efficientFiller(file): > > > > Note that you are shadowing the built-in variable 'file' here. Better > > use 'filename', or something to that effect. > > > > > > > > > worthless_list = [] > > > pot_file = open(file,'r') > > > pot_file_text = pot_file.readlines() > > > for line in pot_file_text: > > > if line.find("msgid") != -1: > > > message_id = shlex.split(line)[1] > > > if message_id in dictionary: > > > number = pot_file_text.index(line) > > > corresponding_crap = > > > dictionary.get(message_id) > > > final_string = 'msgstr' + " " + '"' + > > > corresponding_crap + '"' + '\n' > > > pot_file_text[number+1] = final_string > > > yield pot_file_text > > > > > efficient_filler = efficientFiller("libexo-0.3.pot") > > > new_list = list(efficient_filler) > > > print new_list > > > > > I want to plainly get the last value the yield statement generates. > > > How can I go about doing this please? > Well the basic trouble is that the yield statement you see there > causes it to print the list over and over again when a string > containing "msgid" is found and the subsequent conditions are > satisfied. I just want the last list the yield statement generates. I > don't want the last element of the list generated. just the last > statement. I may be being stupid but i really fail to understand that why would you want to use 'yield' in such a scenario ? Btw, the following line in your code may cause some unexpected behavior (in case of duplicates): number = pot_file_text.index(line) You should rather use 'enumerate' . Cheers, -- -- Amit Khemka -- http://mail.python.org/mailman/listinfo/python-list
Re: use lines as argument to a command
On 10/15/07, Shoryuken <[EMAIL PROTECTED]> wrote: > I'm new to Python, so my question may sounds naive. Here is it. > > I have a text file like this: > > www.a.com > www.b.com > www.c.com > ... > > I want to read one line from this file at a time, which I know how to > do. And use it as an argument to a command, for example, telnet www.a.com > and so on. However I have no idea how to do this task. I guess that you want to loop over a file and for each line in the file you want to call some external program with the line as the argument. Have a look at subprocess module http://docs.python.org/lib/module-subprocess.html If there is some else that you meant, please specify . Cheers, -- -- Amit Khemka -- http://mail.python.org/mailman/listinfo/python-list
Re: use lines as argument to a command
On 10/16/07, Shoryuken <[EMAIL PROTECTED]> wrote: > > I guess that you want to loop over a file and for each line in the > > file you want to call some > > external program with the line as the argument. > > > > Have a look at subprocess module > > http://docs.python.org/lib/module-subprocess.html > > > > If there is some else that you meant, please specify . > > > Thanks alot, its working now. But I have another question (sorry I'm > so noob), how can I redirect a command's output to a file (just like > executing a linux command "dmesg>>stat.txt")? Since subprocess module allow you to call programs through (linux) shell , you can use the same syntax in your command. example: >>> from subprocess import call >>> call("echo foo >> bar.txt", shell=True) Cheers, -- -- Amit Khemka -- http://mail.python.org/mailman/listinfo/python-list
Re: easy but difficult
On 10/16/07, Beema shafreen <[EMAIL PROTECTED]> wrote: > hi everybody, > I have a file separated by hash: > as shown below, > file: > A#1 > B#2 > A#2 > A#3 > B#3 > > I need the result like this: > A 1#2#3 > B 2#3 > > how will generate the result like this from the above file > can somebody tell me what i have to do.. > My code: > fh =open('abc_file','r') > for line in fh.readlines(): >data = line.strip().split('#') > for data[0] in line > print line > > I tried but i donot know how to create 1#2#3 in a single line > regards > shafreen While looping over the file you may store alphabets as key in a dictionary and numbers as values. for example: d = {} for line in open('abc_file'): data = line.strip().split('#') # add the numbers to the 'alphabet' key as a list d[data[0]] = d.get(data[0], []) + [data[1]] Now you can just iterate over the dictionary and write it into a file Cheers, -- -- Amit Khemka -- http://mail.python.org/mailman/listinfo/python-list
Re: importing modules question
On 10/18/07, warhero <[EMAIL PROTECTED]> wrote: > Hey all, sorry for the totally newb question. I recently switched over > to python from ruby. I'm having problems figuring out how module > importing works.. as a simple example I've got these files: > > /example/loader.py > /example/loadee.py > > loadee.py > class loadee(object): > def __init__(self): > print "loadee" > > loader.py > import loadee > if __name__ == "__main__": > l = loadee() > > > When I run the loader file I get a TypeError: TypeError: 'module' > object is not callable 'import module' statement imports the 'module' object and binds the name to the local namespace. Any names defined in the module will have to referenced by module.module_object so you need to do something like this: import loadee if __name__ == "__main__": l = loadee.loadee() Alternatively you can directly import the objects defined in a module by : from loadee import loadee if __name__ == "__main__": l = loadee() cheers, -- -- Amit Khemka -- http://mail.python.org/mailman/listinfo/python-list
Re: Best way to generate alternate toggling values in a loop?
On 10/18/07, Carsten Haese <[EMAIL PROTECTED]> wrote: > On Wed, 2007-10-17 at 23:55 +, Debajit Adhikary wrote: > > I'm writing this little Python program which will pull values from a > > database and generate some XHTML. > > > > I'm generating a where I would like the alternate 's to be > > > > > > and > > > > > > What is the best way to do this? > > > > I wrote a little generator (code snippet follows). Is there a better > > (more "Pythonic") way to do this? > > > > > > # Start of Code > > > > def evenOdd(): > > values = ["Even", "Odd"] > > state = 0 > > while True: > > yield values[state] > > state = (state + 1) % 2 > > > > > > # Snippet > > > > trClass = evenOdd() > > stringBuffer = cStringIO.StringIO() > > > > for id, name in result: > > stringBuffer.write(''' > > > > %d > > %s > > > > ''' > > % > > (trClass.next(), id, name)) > > This is a respectable first attempt, but I recommend you familiarize > yourself with the itertools module. It has lots of useful tools for > making your code more elegant and concise. > > Rather than spelling out the final result, I'll give you hints: Look at > itertools.cycle and itertools.izip. > Why not just use enumerate ? clvalues = ["Even", "Odd"] for i, (id, name) in enumerate(result): stringBuffer.write(''' %d %s ''' % (clvalues[i % 2], id, name)) Cheers, -- -- Amit Khemka -- http://mail.python.org/mailman/listinfo/python-list
Re: Order by value in dictionary
On 10/17/07, Abandoned <[EMAIL PROTECTED]> wrote: > Very very thanks everbody.. > > These are some method.. > Now the fastest method is second.. > > 1 === > def sortt(d): > items=d.items() > backitems=[ [v[1],v[0]] for v in items] > backitems.sort() > #boyut=len(backitems) > #backitems=backitems[boyut-500:] > a=[ backitems[i][1] for i in range(0,len(backitems))] > a.reverse() > return a > > 2 = > import operator > def sortt(d): > backitems=d.items() > boyut=len(backitems) > backitems=backitems[boyut-500:] > backitems=sorted(backitems, key=operator.itemgetter(1)) > a=[ backitems[i][0] for i in range(0,len(backitems))] > a.reverse() > return a > > 3 = > def sortt(d): > backitems=d.items() > backitems.sort(lambda x,y:cmp(x[1],y[1])) > backitems=sorted(backitems, key=operator.itemgetter(1)) > a=[ backitems[i][0] for i in range(0,len(backitems))] > a.reverse() > return a > > == 4 === > import heapq > > def sortt(d): > backitems=d.items() > backitems=heapq.nlargest(1000, backitems, operator.itemgetter(1)) > a=[ backitems[i][0] for i in range(0,len(backitems))] > a.reverse() > return a > Btw, there are specialized algorithms called "Selection Algorithms" for finding k largest items in a collection. http://en.wikipedia.org/wiki/Selection_algorithm Cheers, -- -- Amit Khemka -- http://mail.python.org/mailman/listinfo/python-list
Re: vote for Python - PLEASE
On 10/19/07, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote: > On Oct 18, 6:12 pm, Monty Taylor <[EMAIL PROTECTED]> wrote: > > Hey everybody, > > > > MySQL has put up a poll onhttp://dev.mysql.comasking what your primary > > programming language is. > > But it doesn't ask that, it asks what your > primary programming language is FOR DEVELOPING > MYSQL APPLICATIONS. > > In my case, there is no such language (even though > I primarily use Python) BECAUSE I DON'T USE MYSQL. > > > > Even if you don't use MySQL - please go stick > > in a vote for Python. I'm constantly telling folks that Python needs > > more love, but PHP and Java are kicking our butts... > > > > (I know the world would be a better place if the poll were honest, > > There is dishonestly and there's outright lying > > > but > > I'd rather that people got the message that they should do more python > > development work!) > > Maybe the Python community doesn't need your help. I do use mysql with python bindings, but it was a pleasant surprise to see python was ahead of other languages. Though i too doubt the meaning and genuineness of such internet polls. But may be there are similar people in every community who would try to spread the word and get more votes for 'their' language, hence actually helping to normalize the results ! However even if the poll results do not accurately reflect the intended purpose, they may be, just may be, give an idea of size of community and just how much that 'one' lie they will live with to see 'their' language ahead ;-) ! cheers, -- -- Amit Khemka -- http://mail.python.org/mailman/listinfo/python-list
Re: Hi to every one
On 10/22/07, niket mhatre <[EMAIL PROTECTED]> wrote: > Hello to every member of this list. > Can any one tell me where to find various python development in to linux > clustering? Just give me some startup info for searching such material. I m > starting to writing some patches in my existed cluster at my college. Just > look for python development held in this area. > Hey i was active member of this from last 2 year, i had just changed my > email address. Have a look at : http://cheeseshop.python.org/pypi?%3Aaction=browse Cheers, -- Amit Khemka -- http://mail.python.org/mailman/listinfo/python-list
Re: Iteration for Factorials
On 10/22/07, Py-Fun <[EMAIL PROTECTED]> wrote: > On 22 Oct, 13:28, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote: > > Py-Fun wrote: > > > I'm stuck trying to write a function that generates a factorial of a > > > number using iteration and not recursion. Any simple ideas would be > > > appreciated. > > > > Show us your attempts, and we might suggest a fix. Because otherwise this > > sounds suspiciously like homework. > > > > Diez > > Here is my futile attempt. Be careful with this though, I just ran > something similar and it was never ending... > > def itforfact(n): > while n<100: > print n > n+1 > n = input("Please enter a number below 100") > > itforfact(n) Let me give you a pseudo code (which though can be found in most of the textbooks and some 'simple' googling). Try to understand the code and then write an equivalent python function. function iFactorial(n: integer): integer; var i, temp: integer; begin temp = 1; for i = 1 to n do temp = temp * i end return temp About your code. 1. why doesn't it surprise you if the code that you posted goes in infinite loop ?! 2. why do you use condition: n < 100 3. How do you think that your function will calculate the factorial ? 4. Instead of "input" use "raw_input", and then "cast" the input as integer . Cheers, amit. -- -- Amit Khemka -- http://mail.python.org/mailman/listinfo/python-list
Re: How can i protect text format ?
On 10/23/07, Abandoned <[EMAIL PROTECTED]> wrote: > Hi.. > I want to do a forum with python but i have a problem.. > > I have a and i write: > line 1 hi > line 2 how r u > > And then i save to this database ( colomn data type is text) > And than it looks "line 1 hi line 2 how r u".. > How can i protect \n characters ? I don't think the issue has anything to do with python. I guess while you are displaying the text into an HTML page the "\n" characters should be replaced by "" to appear as newlines. Cheers, -- Amit Khemka -- http://mail.python.org/mailman/listinfo/python-list
Re: Lists and Sublists
On 10/24/07, Bruno Desthuilliers <[EMAIL PROTECTED]> wrote: > dineshv a écrit : > > We have a list of N (>2,000) keywords (of datatype string). Each of > > the N keywords has associated with it a list of names of varying > > numbers. For example, keyword(1) will have a list of L1 names > > associated with it, keyword(2) will have a list of L2 names associated > > with it and so on with L1 not equal to L2 etc. All keywords and names > > are immutable. > > > > Given a keyword(n) , we want to get hold of the associated list of Ln > > names. > > > > At anytime, we also want to add keywords to the list of N keywords, > > and to any of the associated Ln lists - both of which will grow to > > very large sizes. > > > > The data will be read into the Python data structure(s) from disk > > storage. > > > > I am struggling to work out what is the ideal Python data structure > > for the above. Any help would be greatly appreciated. > > keywords = {} > keywords['python'] = ['fun', 'simple'] > keywords['another_p_language'] = ['line noise', 'cryptic'] > keywords['python'].append('readable') > To add you may want to have a look at "shelve" module , in case you want to store this object to a file. It can be useful if the data set is large and does not change frequently and you would want to save on some startup time . cheers, -- -- Amit Khemka -- http://mail.python.org/mailman/listinfo/python-list
Re: Which persistence is for me?
On 11/1/07, Neal Becker <[EMAIL PROTECTED]> wrote: > I need to organize the results of some experiments. Seems some sort of > database is in order. > > I just took a look at DBAPI and the new sqlite interface in python2.5. I > have no experience with sql. I am repulsed by e.g.: > c.execute("""insert into stocks > values ('2006-01-05','BUY','RHAT',100,35.14)""") > > ewww. How unpythonic. I don't want to use a string to specify what > function to execute. I want to call a function (c.insert?). > > Is there some other interface/database that I might like better? Why you can always look at some "pure" database solutions. If persistence is all you require, have a look at "anydbm" and or "shelve" modules . Cheers, -- -- Amit Khemka -- http://mail.python.org/mailman/listinfo/python-list
Re: Explanation about for loop
On 11 Jan 2007 20:48:19 -0800, raghu <[EMAIL PROTECTED]> wrote: > can any one help me explaining for loop and its execution and its > syntax with a simple example. Well Guido did that: http://docs.python.org/tut/node6.html#SECTION00620 -- Amit Khemka -- onyomo.com Home Page: www.cse.iitd.ernet.in/~csd00377 Endless the world's turn, endless the sun's Spinning, Endless the quest; I turn again, back to my own beginning, And here, find rest. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to find out if another process is using a file
> > Yes, that would work very neatly but I don't have any control over the > writing process. I think the modification time route might be the best > option, but thanks to all for their replies. Its not pythonic, but may be "lsof" on POSIX can be helpful: see: http://www.physiol.ox.ac.uk/Computing/Online_Documentation/lsof-quickstart.txt cheers, -- Amit Khemka -- onyomo.com Home Page: www.cse.iitd.ernet.in/~csd00377 Endless the world's turn, endless the sun's Spinning, Endless the quest; I turn again, back to my own beginning, And here, find rest. -- http://mail.python.org/mailman/listinfo/python-list
Re: Trouble with for loop
On 11/6/07, Shriphani <[EMAIL PROTECTED]> wrote: > Hello, > I want to try something like: > > for (a, b, c, d, e, f) in [1, 2, 3, 4, 5, 6, 7, 8, 9]: > > > When I do that I get an error: > TypeError: unpack non-sequence > > My main intention is to state that each of the variables namely a, b, > c, ## can take value from 1 to 9. > How do I go about this ? An ugly code for it would be ;-) : for (a, b, c, d, e, f) in zip(*[range(1, 10)]*6): print a, b, c, d, e, f Cheers, -- -- Amit Khemka -- http://mail.python.org/mailman/listinfo/python-list
Re: manually cutting a picture
On 11/6/07, Joseph king <[EMAIL PROTECTED]> wrote: > I have a kinda hard question i am trying to build a jigsaw game with > python, i would like to give the option for people to create there own > puzzle piece does anyone know how to accomplish this it is becoming > increasingly difficult for me Disclaimer: I don't know how helpful I am being here. I have no experience with jigsaw puzzles programming, but the problem seemed interesting enough to give it a thought. I think given an image (may be user provided) you want to cut it in N (user input) pieces. Here is an idea: Cut image by "m X m" grid (bigger the m, the more varied shapes you would be able to generate), this will give you m*m square pieces. With each piece store a vector which represents the polygon (say by storing co-ordinates of the corners). Now visualize this set of pieces as a graph with an edge between adjacent pieces. Now depending on the final number of pieces that you want to generate (N), you traverse the graph and for each node: 1. "Merge" a node with a randomly selected neighbor Repeat step 1 until you have N pieces left Notes: 1. ''merge" operations can be optimized calculating a factor "m*m/N" and doing all merges together. 2. You can also maintain a 'size' attribute with each piece, so that all the pieces generated are of approximately same size. Please let me know if you have other ideas. Cheers, -- -- Amit Khemka -- http://mail.python.org/mailman/listinfo/python-list
Re: manually cutting a picture
On 11/7/07, Cameron Walsh <[EMAIL PROTECTED]> wrote: > Amit Khemka wrote: > > > Cut image by "m X m" grid (bigger the m, the more varied shapes you > > would be able to generate), this will give you m*m square pieces. With > > each piece store a vector which represents the polygon (say by storing > > co-ordinates of the corners). > > Now visualize this set of pieces as a graph with an edge between > > adjacent pieces. Now depending on the final number of pieces that you > > want to generate (N), you traverse the graph and for each node: > > > > 1. "Merge" a node with a randomly selected neighbor > > > > Repeat step 1 until you have N pieces left > > > Doesn't that have the fairly likely possibility of ending up with 1 very > large piece and n-1 very small pieces? If you iterate over the graph > merging with a neighbour at random, then each node has a 50% chance of > being merged with a node that has already been merged. > > *-*-* *-* > | | | > * *-*-* * > > * * * * * etc. could be the result of the first 8 steps. Already every > node touched is part of the same group. Or have I misunderstood your > algorithm? Yes, It potentially can result into that. That is the reason I suggested to calculate (m*m/N) and while merging nodes keep track of the "size" (number of nodes are merged in a node), so that while growing/merging the node does not grow 'much large' than (m*m/M) > > A random region growing approach might work, with seeds scattered evenly > throughout the image. That would be prone to orphaning squares inside > larger objects, but that may be what you want. It would not be easy to > program. > > What I would do is break the graph in to m*m squares, then for each > edge, randomly select a means of joining them - blob sticking out of > piece A, or hole for blob in piece A; move hole/blob along the edge by a > random amount, move edge in or out to get different sized pieces. For > each square this was applied to, it would apply the reverse sizing to > the square touching on that edge. > > I'd restrict in/out movement of edges and movement of blob/hole along > the edge to a specific range, to avoid problems where the blob of one > square is stuck on the furthest corner, but the piece touching that > corner has had its edge moved in too far so the blob would overlap two > squares. Interesting idea, though the implementation may become a bit complex ! To OP : 1. Have you checked out research papers on Digital Image Processing and Graphics ? I would guess that there should exist some good solutions. I hadn't had much time but a quick search showed quite a few "free softwares" to create Jigsaw puzzles and Algorithms to solve one. 2. Can you please post anything relevant to this topic on this thread only instead of doing a new post. Helps to track the postings easily. Cheeers, -- -- Amit Khemka -- http://mail.python.org/mailman/listinfo/python-list
Re: What is python?????
On 11/17/07, Cope <[EMAIL PROTECTED]> wrote: > > In our place we eat pythons for curry. Its delicious. > And how about your python? > > Cope Not much of the difference here, it is just a bit more flexible. My python goes and brings me whatever I wish to eat. Cheers, -- -- Amit Khemka -- http://mail.python.org/mailman/listinfo/python-list
Re: How do I not make a list?
On 11/29/07, Just Another Victim of the Ambient Morality <[EMAIL PROTECTED]> wrote: > It may sound like a strange question but that's probably only because I > don't know the proper terminology. I have an iterable object, like a list, > and I want to perform a transform on it (do an operation on each of the > elements) and then pass it onto something else that expects and iterable. > I'm pretty sure this something else doesn't need a list, either, and just > wants to iterate over elements. > Now, I could just make a list, using a list comprehension, performing my > operation on each element, and then pass that list on, knowing that it is > iterable. However, I was wondering if there was a way I can do virtually > this without having to actually allocate the memory for a list. Creating a > stock iterator or generator or whatever it's called, with a passed in > operation? Well I think what you want is to use "()" instead of "[]" >>> l = (i for i in range(1,20)) >>> l Cheers, -- Amit Khemka -- http://mail.python.org/mailman/listinfo/python-list
Re: Does anyone know where is the Berkeley XML Database documentation for its Python API?
There are no official/un-official documentation for bdbxml python api AFAIK !!! If you want some examples look in "dbxml/examples/python/", directory in your dbxml installation. Though for most part the python api closely follows the C++/Java api (look: http://www.dbxml.com/docs/programmer.html ) for details. You may also find http://blog.gmane.org/gmane.comp.db.dbxml.general useful. cheers, amit. On 4 Apr 2006 01:34:25 -0700, Sullivan WxPyQtKinter <[EMAIL PROTECTED]> wrote: > I have been looking for python API documentation of BDBXML for quite a > few days but I could not find it. Anyone has any idea where it is? Or > if there is not such a thing at all, how could I get started? > > In addition, in the previous posts I have seen some grumble about > python API's lack of XMLexception and some basic programming and > debugging elements for project engineering. Are they added or fixed in > the lastest version of BSBXML? > > > Thank you for help. > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Amit Khemka -- onyomo.com Home Page: www.cse.iitd.ernet.in/~csd00377 Endless the world's turn, endless the sun's Spinning, Endless the quest; I turn again, back to my own beginning, And here, find rest. -- http://mail.python.org/mailman/listinfo/python-list
Re: Splitting a string with extra parameters
I guess you should use "re" module ... In this case re.split("\D,\D", YOUR_STRING) should work. (splits only when "," is between two non-digits). for details and more options see python-docs. cheers, amit. On 4/6/06, Fulvio <[EMAIL PROTECTED]> wrote: > Alle 11:23, giovedì 06 aprile 2006, Chris P ha scritto: > > when splitting based on a delimiter of "," the above string gets broken up > > in 5 "columns" instead of 4 due to the "," in the money amount. > > There should be cvs package in the python directory. Why don't you try that > way? > Reading some help gives more details of its use. > > F > -- > http://mail.python.org/mailman/listinfo/python-list > -- Amit Khemka -- onyomo.com Home Page: www.cse.iitd.ernet.in/~csd00377 Endless the world's turn, endless the sun's Spinning, Endless the quest; I turn again, back to my own beginning, And here, find rest. -- http://mail.python.org/mailman/listinfo/python-list