problems with tkinter updates
I'm missing something about tkinter updates. How can I give tkinter a chance to run? Here's some code: import time import tkinter import tkinter.scrolledtext tk = tkinter.Tk() f = tkinter.Toplevel(tk) st = tkinter.scrolledtext.ScrolledText(f) st.pack() def update(): print('updating') st.see(tkinter.END) tk.after(1000, update) input('hit enter to start') update() f = open('/etc/services') for line in f: st.insert(tkinter.END, line + '\n') print('got it') #time.sleep(5) input('more?') input('finished?') When I do this (input('more?'), it works as expected. If I comment that line out, then the program reads the entire file, then update the window right at the end, even if I put a sleep in there. What can I do inside the loop to give tk a chance? Thanks. -- Yves. http://www.SollerS.ca/ http://ipv6.SollerS.ca http://blog.zioup.org/ -- http://mail.python.org/mailman/listinfo/python-list
Re: problems with tkinter updates
On 2012-01-23 20:57, Dave Angel wrote: You have it backward. The question is not what you do inside your loop to give tk a chance, but rather what do you do to make tk give you a chance. tk doesn't "start" till you make the mainloop() method call, and once you call that method, it won't return till the program is exiting. So, forget about input statements inside some loop. Input isn't a gui concept, it's for console apps. Gui apps use dialog boxes and such. Similarly sleep(). mainloop() will sleep, when there are no events in its queue. If you want to do work, break it into manageable chunks, and attach each chunk to some event that tk will fire. The input statements were there for debugging purpose... I now have got it running without any sleep or input, I simply added a tk.update() in the loop. It works for updating the window, but when I add buttons to that frame, they are quite unresponsive. I'm starting to think I need to split off the reading part into a different thread. -- Yves. http://www.SollerS.ca/ http://ipv6.SollerS.ca http://blog.zioup.org/ -- http://mail.python.org/mailman/listinfo/python-list
Re: problems with tkinter updates
On 2012-01-24 02:52, Peter Otten wrote: Have update() (renamed to read_more() in my code) do the reading: import sys import tkinter import tkinter.scrolledtext root = tkinter.Tk() text_window = tkinter.Toplevel() text = tkinter.scrolledtext.ScrolledText(text_window) text.pack() infile = open(sys.argv[1]) def read_more(): line = next(infile, None) if line is not None: text.insert(tkinter.END, line) root.after(100, read_more) else: text.insert(tkinter.END, "\nThat's all folks", "looney") text.tag_configure("looney", foreground="RED") text.see(tkinter.END) read_more() root.mainloop() Thank you, this was very useful! -- Yves. http://www.SollerS.ca/ http://ipv6.SollerS.ca http://blog.zioup.org/ -- http://mail.python.org/mailman/listinfo/python-list
Re: problems with tkinter updates
In case somebody else is trying to do the same thing, this is what I ended up with to get the concept, that I can now integrate in other scripts: http://projects.zioup.org/scratchpad/python/tkrun.py -- Yves. http://www.SollerS.ca/ http://ipv6.SollerS.ca http://blog.zioup.org/ -- http://mail.python.org/mailman/listinfo/python-list
tkinter.Toplevel
With a tkinter.Toplevel, how can I "disable" the parent windown and all its widget, in the same fashion as tkinter.messagebox? -- Yves. http://www.SollerS.ca/ http://ipv6.SollerS.ca http://blog.zioup.org/ -- http://mail.python.org/mailman/listinfo/python-list
Re: tkinter.Toplevel
On 2012-02-17 16:48, Rick Johnson wrote: On Feb 16, 8:39 pm, y...@zioup.com wrote: With a tkinter.Toplevel, how can I "disable" the parent windown and all its widget, in the same fashion as tkinter.messagebox? The answer lies within the tkSimpleDialog source code; which is pure python. Look in the __init__ method of Dialog class. My advice is to study the code until you understand every line. Look at the following references when you need more info: http://infohost.nmt.edu/tcc/help/pubs/tkinter/ http://effbot.org/tkinterbook/ ...grab_set() Thanks. -- Yves. http://www.SollerS.ca/ http://ipv6.SollerS.ca http://blog.zioup.org/ -- http://mail.python.org/mailman/listinfo/python-list
Re: py3k: datetime resolution / isoformat
On 11-02-25 07:49 PM, Ned Deily wrote: datetime.datetime.now().replace(microsecond=0).isoformat() '2011-02-25T18:48:24' Ah, Thanks! -- Yves. http://www.SollerS.ca/ http://blog.zioup.org/ -- http://mail.python.org/mailman/listinfo/python-list
suggestions for functional style (singleton pattern?)
Hi, For some scripts, I write in a a more functional way, using a lot of small functions outside of any class. Although it makes the code clearer for specific cases, I have found that it makes debugging and using the repl in general difficult, as as I have to re-initialise every single objects every time. I have now started to use some kind of state pattern to alleviate this, here's a simplistic example: https://github.com/dorfsmay/state_pattern_for_debugging_python/blob/master/dirstats.py Are there better ways to address this? Any suggestion on this style? Thanks. -- http://yves.zioup.com gpg: 4096R/32B0F416 -- https://mail.python.org/mailman/listinfo/python-list
Re: suggestions for functional style (singleton pattern?)
On 2015-02-28 19:19, Michael Torrie wrote: > You say you are trying to use a singleton pattern, but your code does > not appear to implement a singleton. From what I can read of your code, I call it a singletone because I only every create one object. I am not trying to use a singleton, I'm trying to avoid issues created by the alternative ways of doing this (not having access to the variables in the repl etc...). > you really should just put all your functions as methods to the DirStat > class and call it good. Especially if your module is going to be used > in several places potentially at the same time. There are type of problems where I don't want to bind functions to data. By the way, I have just added some more explanation in the code, trying to clarify the problem. -- http://yves.zioup.com gpg: 4096R/32B0F416 -- https://mail.python.org/mailman/listinfo/python-list
Re: suggestions for functional style (singleton pattern?)
On 2015-02-28 20:45, Mario Figueiredo wrote: > Problem 1: > With the exception of get_all_files(), all your functions do is to > call another standard function. This decreases performance > unnecessarily and may mislead the users of your API into thinking > these functions perform some different type of average or min/max > operations. I tried to create a simple example to make a point, I wouldn't create function wrappers like this. I'll to think of a better example, this was to get the discussion going. > Problem 3: > At the very least they should be moved inside the class so it becomes > clear to anyone caring that these functions really only matter in the > context of the DirStats object. Trying to write in a more functional way, not OO here, the functions could be used by more than one class. I understand OO, use it a lot, but sometimes try to move beyond that. > Problem 4: > You speak of a singleton. But you haven't implemented one. It is not > clear from your code if this class should be a singleton. I'm guessing > not. Singletons are in fact rare. Well, let me put it another way: > Good reasons to code a singleton are rare. Thanks. I hadn't realise "singleton" meant a class built such that it could not be instanciated more than once, I thought it corresponded to a pattern where only one object is ever created from a given class. > But, if you ever wish to implement a singleton, the following pattern > mostly works and is short and to the point: > > class Map(): > _instance = None > > def __new__(cls, *args, **kwargs): > if Map._instance is None: > Map._instance = super(Map, cls).__new__(cls) > return Map._instance > > >>> a = Map() > >>> b = Map() > >>> a is b > True Thanks. > Problem 5: > A pet peeve of mine. If you aren't going to use a variable, make that > explicit in your code by taking advatange of Python wonderful language > features. Good point - thanks. -- http://yves.zioup.com gpg: 4096R/32B0F416 -- https://mail.python.org/mailman/listinfo/python-list
with statements does not delete the object
Is this the expected behaviour: with mylib.token() as t: do_something dir() In the last dir(), after the with "loop" is finished, t still shows up... I expected it to be unreferenced by then. -- Yves. http://www.SollerS.ca/ http://ipv6.SollerS.ca http://blog.zioup.org/ -- http://mail.python.org/mailman/listinfo/python-list
bufsize in subprocess
Is this the expected behaviour? When I run this script, it reads only once, but I expected once per line with bufsize=1. What I am trying to do is display the output of a slow process in a tkinter window as it runs. Right now, the process runs to completion, then display the result. import subprocess com = ['/bin/ls', '-l', '/usr/bin'] with subprocess.Popen(com, bufsize=1, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) as proc: print('out: ' + str(proc.stdout.read(), 'utf8')) Thanks. -- Yves. http://www.SollerS.ca/ http://ipv6.SollerS.ca http://blog.zioup.org/ -- http://mail.python.org/mailman/listinfo/python-list
Re: bufsize in subprocess
On 2012-01-22 00:27, Chris Rebert wrote: On Sat, Jan 21, 2012 at 9:45 PM, wrote: Is this the expected behavior? Yes. `.read()` [with no argument] on a file-like object reads until EOF. See http://docs.python.org/library/stdtypes.html#file.read Right, got it now. You want proc.stdout.readline(). Yes, or a for loop, this works for me now: import subprocess com = ['/bin/ls', '-l', '/usr/bin'] with subprocess.Popen(com, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) as proc: for line in proc: print('out: ' + str(line, 'utf8')) -- Yves. http://www.SollerS.ca/ http://ipv6.SollerS.ca http://blog.zioup.org/ -- http://mail.python.org/mailman/listinfo/python-list
Re: bufsize in subprocess
import subprocess com = ['/bin/ls', '-l', '/usr/bin'] with subprocess.Popen(com, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) as proc: for line in proc.stdout: print('out: ' + str(line, 'utf8')) -- Yves. http://www.SollerS.ca/ http://ipv6.SollerS.ca http://blog.zioup.org/ -- http://mail.python.org/mailman/listinfo/python-list
executing a function/method from a variable
What is the best way to execute a function which name is stored in a variable ? Right now I use an eval, but I'm wondering if there isn't a better way: Here is a simplified example, but what I use this for is to parse a formated text file, and execute a different method depending on the pattern: import sys class dummy(object): def __init__(self, arg): self.todo = 'self.print' + arg; def printa(self): print 'a' def printb(self): print 'b' def doit(self): #k = eval(self.todo) #k() eval(self.todo)() o = dummy(sys.argv[1]) o.doit() Thanks. -- Yves. http://www.sollers.ca/ -- http://mail.python.org/mailman/listinfo/python-list
Re: executing a function/method from a variable
Carsten Haese wrote: Right now I use an eval, but I'm wondering if there isn't a better way: There's (almost) always a better way than using eval. Yes I agree, every time I use eval, I feel like the language is missing something, fair enough to shell type languages, but usually not the case in python. That's why I asked, In this case, you should use getattr(). Right ! I always forget about get/set attr. Thanks ! Here's your simplified example modified to use getattr: Tried it, and it works if we remove the self from the name of course: import sys class dummy(object): def __init__(self, arg): self.todo = 'print' + arg; def printa(self): print 'a' def printb(self): print 'b' def doit(self): #func = getattr(self, self.todo) #func() getattr(self, self.todo)() o = dummy(sys.argv[1]) o.doit() Thanks again, -- Yves. http://www.SollerS.ca -- http://mail.python.org/mailman/listinfo/python-list
append to non-existing list
Hello, if I do this: for row in sqlsth: pkcolumns.append(row[0].strip()) etc without a prior: pkcolumns = []; I get this error on first iteration: UnboundLocalError: local variable 'pkcolums' referenced before assignment I guess that's normal as it's the way python works...?!? My question is: Is there no way to append to a non existing list? I am lazy for declaring it first, IMHO it bloats the code, and (don't know if it's good to say that here) where I come from (php) I was used to not-needing it... regards, Yves -- http://mail.python.org/mailman/listinfo/python-list
Re: append to non-existing list
[EMAIL PROTECTED] wrote: > Yves> My question is: Is there no way to append to a non existing list? > > My question in return is: How is Python supposed to know that pkcolumns is > supposed to be a list instead of some other type of object that happens to > define an append() method? I am fairly new to python (and I like it more and more), but I can not answer this question... As I said, where I come from it is possible, and how they do it is explained a little here: http://lu.php.net/manual/en/language.types.type-juggling.php As I want to learn, I will work with python the pythonic way, but sometimes I just fall back to what I know from php... :-) Thanks for your answer and the example code, Yves p.s. thanks for the "import this" hint > For example, my code might contain this class > definition before the suspect pkcolumns.append() call: > > class MaxLengthList: > def __init__(self, maxsize=0): > self.data = [] > self.maxsize = maxsize > > def append(self, item): > if self.maxsize and len(self.data) == self.maxsize: > del self.data[0] > self.data.append(item) > > def __getattr__(self, attr): > return getattr(self.data, attr) > > I think it would be perfectly reasonable for Python to choose to instantiate > my MaxLengthList instead of a plain old list. > > Yves> I am lazy for declaring it first, IMHO it bloats the code, and > Yves> (don't know if it's good to say that here) where I come from (php) > Yves> I was used to not-needing it... > > I don't know php, but would also have to wonder how it knows to create a > list instead of an integer (for example). > > Finally, from the Zen of Python (try "import this" at an interpreter > prompt): > > In the face of ambiguity, refuse the temptation to guess. > > Skip > > . > -- http://mail.python.org/mailman/listinfo/python-list
Re: append to non-existing list
[EMAIL PROTECTED] wrote: > I am afraid you have to either go back to php or whatever programming > language that fits your style or change your style to fit python. sorry for offending... I just asked a question, and now I know one more thing about python... And btw I really am surprised by the amount of answers that my question rose, in so little time! thanks all! > There is a lot I don't like about python but if you have to use it, you > have to cope with it. > > Yves Glodt wrote: >> My question is: Is there no way to append to a non existing list? >> >> I am lazy for declaring it first, IMHO it bloats the code, and (don't >> know if it's good to say that here) where I come from (php) I was used >> to not-needing it... >> >> >> regards, >> Yves > -- http://mail.python.org/mailman/listinfo/python-list
Re: append to non-existing list
Juho Schultz wrote: > Yves Glodt wrote: >> Hello, >> >> if I do this: >> >> for row in sqlsth: >> pkcolumns.append(row[0].strip()) >> etc >> >> >> without a prior: >> >> pkcolumns = []; >> >> >> I get this error on first iteration: >> UnboundLocalError: local variable 'pkcolums' referenced before assignment >> >> I guess that's normal as it's the way python works...?!? >> >> My question is: Is there no way to append to a non existing list? >> >> I am lazy for declaring it first, IMHO it bloats the code, and (don't >> know if it's good to say that here) where I come from (php) I was used >> to not-needing it... >> >> >> regards, >> Yves > > You mean you want to type "pkcolumns" only once to keep your code short? > Would something like this be useful? > > pkcolumns = [row.strip() for row in sqlsth] I will look into this, maybe it's what I need, thanks! -- http://mail.python.org/mailman/listinfo/python-list
Re: append to non-existing list
bruno at modulix wrote: > Yves Glodt wrote: >> Hello, >> >> if I do this: >> >> for row in sqlsth: >> pkcolumns.append(row[0].strip()) >> etc >> >> >> without a prior: >> >> pkcolumns = []; >> >> >> I get this error on first iteration: >> UnboundLocalError: local variable 'pkcolums' referenced before assignment >> >> >> I guess that's normal as it's the way python works...?!? > > yes sir. > >> My question is: Is there no way to append to a non existing list? > > No. Definitively. And that's a Good Thing(tm). > > How would you use something that doesn't exist ??? > >> I am lazy for declaring it first, > > s/declaring/instantiating/ > > If you were to use your own class Toto, would you ever hope that the > following code would work : > > for v in some_seq: > toto.dothis(v) > > without instantiating Toto and binding it to the name 'toto' before ? > Well, in Python, a list is an instance of class list. There are > syntactic sugar to instanciate a list (or a tuple or a string or a dict > etc), but this: > > my_list = [] > > is strictly equivalent to this: > > my_list = list() > > Now let's try something else: > > class Machin(object): > def append(self, value): pass > > class Bidule(object): > def append(self, value): pass > > for i in range(10): > m.append(i) > > > How should Python interpret this ? Should it create a list, or a Machin, > or a Bidule, or an instance of whatever imported class having a > append() method ? ok I see your point, and python's... (just FYI, and not to start a flamewar ;-): In php, the [] means "append to an array object". If the array does not exist yet, it's created. [] *is* explicit for arrays, thus for php it's clear what you want.) >> IMHO it bloats the code, > > run your python interpreter and type: > import this > > Then read carefully. > > Now if being explicit still hurts your personal convictions, there's > this other language with a name starting with p... !-) no thanks, this is the 21st century ;-) >> and (don't >> know if it's good to say that here) where I come from (php) I was used >> to not-needing it... > > Not creating an Array before using it is Bad Style in PHP (and generate > a Warning BTW). an "undefined" notice, yes, not a warning... ;-) > There are warts in Python (as in any other languages), and there are > things that sometimes bore me but are not really warts. But having to > explicitely instanciate objects can't be seen as a wart in any language > IMHO !-) Ok... I thank you for all the explanations. It helps me to see more far. I (and will continue to) use php for web, and wanna standardize on python for all non-web stuff we are doing, so I might be a frequent guest on this list... have a nice day, Yves -- http://mail.python.org/mailman/listinfo/python-list
Re: append to non-existing list
[EMAIL PROTECTED] wrote: > Thomas Bellman wrote: >> The next time you go shopping at your local super-market, do >> *not* get a shopping-cart (or shopping-basket, or any similar >> container). As you pick up the things you want to buy, try >> to put them into the non-existing cart. Perhaps you will then >> become enlightened. > > But in PHP(and I believe Perl), it is more like : > > "oops, I need a cart. Hello, I need a cart here, please" and > magically, someone wheel you a cart which you can put your stuff in. > The "@" is the magic calls for service. So as a customer, this sounds > like better service but that will create problems to the super market > as it need extra staff for this service and the environment is noiser, > that is another story. > :-) I will never mention any p-language except python in this list anymore... -- http://mail.python.org/mailman/listinfo/python-list
Re: append to non-existing list
Max M wrote: > Yves Glodt wrote: >> bruno at modulix wrote: >> >>> Yves Glodt wrote: >>> >>>> Hello, >>>> >>>> if I do this: >>>> >>>> for row in sqlsth: >>>> pkcolumns.append(row[0].strip()) >>>> etc >>>> >>>> >>>> without a prior: >>>> >>>> pkcolumns = []; >>>> >>>> >>>> I get this error on first iteration: >>>> UnboundLocalError: local variable 'pkcolums' referenced before >>>> assignment >>>> >>>> >>>> I guess that's normal as it's the way python works...?!? > > > Well you could do something like this. (Untested and unrecommended) > > self.__dict__.setdefault('pkcolumns', []).append(row[0].strip()) > > Personally I find > > pkcolumns = [] > pkcolumns .append(row[0].strip()) > > to be nicer ;-) Yes me too, I'm gonna stick to that... :-) -- http://mail.python.org/mailman/listinfo/python-list
Re: append to non-existing list
bruno at modulix wrote: > Yves Glodt wrote: > (snip) >> ok I see your point, and python's... >> >> (just FYI, and not to start a flamewar ;-): >> In php, the [] means "append to an array object". > > yes, I know this. > >> If the array does not exist yet, it's created. > > Which is what I don't like. It should crash. > >> [] *is* explicit for >> arrays, > > IIRC, you can also use it to sbscript strings, but I wouldn't bet my > life on this. > >> thus for php it's clear what you want.) > > Nope. You may be in the case where you think the array already exists, > and then you (well, I at least...) would prefer that PHP don't try to > second-guess you... If and when I want to create an object, I tell it. > If I dont tell "create me an array", I don't want one to come in existence. > (snip) >> an "undefined" notice, yes, not a warning... ;-) >> > (snip) >> Ok... I thank you for all the explanations. >> >> It helps me to see more far. I (and will continue to) use php for web, >> and wanna standardize on python for all non-web stuff we are doing, > > You might discover that Python is just great for web programming too !-) Which raises another question... :-) Is there a possibility to bring together apache and python in a way that I can embed python into html? Or even, write a smallish webserver in python (using twisted maybe) whose only purpose is to serve pages and execute the embedded code...? >> so I >> might be a frequent guest on this list... > > You're welcome !-) > And if you're a french speaker, there's also french-speaking mailing > list and newsgroups. Merci pour l'info, I am, but for now the volume of this list is enough for me ... :-) -- http://mail.python.org/mailman/listinfo/python-list
Re: append to non-existing list
[EMAIL PROTECTED] wrote: > Yves Glodt wrote: >> Which raises another question... :-) >> >> Is there a possibility to bring together apache and python in a way that >> I can embed python into html? > What do you mean ? I need this (invalid example-html follows): title of page Hello, today is: %s" % (time.ctime()) ?> Should that not be fairly easy to to, even from scratch, with the httplib module...? The advantage would be that I could write a webinterface for my database and reuse the classes I wrote for the command line app. >> Or even, write a smallish webserver in python (using twisted maybe) >> whose only purpose is to serve pages and execute the embedded code...? > My favorite is TurboGears, a collection of modules and glue that brings > together HTTP server(cherrypy), template(Kid) and SQL object > store(SQLObject) that can do serious web developement yet don't need to > read a book before starting. > > If you just need the server, cherrypy is pretty good and simple to > start. Ok gonna look into that, regards, Yves -- http://mail.python.org/mailman/listinfo/python-list
iterate over class variables
Hello list, I need to iterate over a class and get all her variable names and values, e.g. considering this example: class testclass: var1 = 'ab' var2 = 'cd' var3 = 'ef' test = testclass() Then I wanna do sonmething like this: for name,value in test: print name print value fails with of course with: "TypeError: iteration over non-sequence" How can I do that? regards, Yves -- http://mail.python.org/mailman/listinfo/python-list
Re: iterate over class variables
Yves Glodt wrote: > Hello list, > > I need to iterate over a class and get all her variable names and > values, e.g. considering this example: > > > class testclass: > var1 = 'ab' > var2 = 'cd' > var3 = 'ef' > > test = testclass() > > > > Then I wanna do sonmething like this: > > for name,value in test: > print name > print value > > fails with of course with: > "TypeError: iteration over non-sequence" > > > How can I do that? sorry for selfreplying, but I found a solution: for key in dir(test): if '__' not in key: value = getattr(test,key) print key, value Does anything speak about this? Is there a better-performing way to do this? > regards, > Yves -- http://mail.python.org/mailman/listinfo/python-list
Re: iterate over class variables
Yves Glodt wrote: > Yves Glodt wrote: >> Hello list, >> >> I need to iterate over a class and get all her variable names and >> values, e.g. considering this example: >> >> >> class testclass: >> var1 = 'ab' >> var2 = 'cd' >> var3 = 'ef' >> >> test = testclass() >> >> >> >> Then I wanna do sonmething like this: >> >> for name,value in test: >> print name >> print value >> >> fails with of course with: >> "TypeError: iteration over non-sequence" >> >> >> How can I do that? > > sorry for selfreplying, but I found a solution: > > for key in dir(test): > if '__' not in key: > value = getattr(test,key) > print key, value > > Does anything speak about this? s/about/against /me: s/more sleep/less party > Is there a better-performing way to do this? > > >> regards, >> Yves -- http://mail.python.org/mailman/listinfo/python-list
Re: iterate over class variables
bruno at modulix wrote: > Yves Glodt wrote: >> Yves Glodt wrote: >> >>> Hello list, >>> >>> I need to iterate over a class and get all her variable names and >>> values, e.g. considering this example: >>> >>> >>> class testclass: >>> var1 = 'ab' >>> var2 = 'cd' >>> var3 = 'ef' > > Take care, these are *class* variables, not instance variables. > >>> test = testclass() >>> >>> Then I wanna do sonmething like this: >>> >>> for name,value in test: >>> print name >>> print value >>> > (snip) >> sorry for selfreplying, but I found a solution: >> >> for key in dir(test): >> if '__' not in key: >> value = getattr(test,key) >> print key, value >> >> Does anything speak about this? > > 1/ dir() doesn't necessary returns all the attributes of an object: > """ > dir(...) > dir([object]) -> list of strings > > Return an alphabetized list of names comprising (some of) the attributes > of the given object, and of attributes reachable from it: > """ > > But I don't think this is a problem here. > > 2/ everything being an object, dir() also returns methods (a method > being a - callable - attribute of the object's class). > > If you're only interested in data attributes, you may want to try this: > > for key in dir(test): > if not key.startswith('__'): > value = getattr(test,key) > if not callable(value): > print key, value This serves me well so far, thanks to you, Peter and Daniel for the suggestions! Yves (still amazed of the responsiveness of this list :-) > You can also check inspect.getmember() -- http://mail.python.org/mailman/listinfo/python-list
how to start a process and get it's pid?
Hello, another question rose for me today... Is there a way to start an external process, in it's own context (not as the exec-() functions do), and get it's pid...? e.g.: pid = wonderfulstartprocfunction('/usr/bin/wine bla.exe') #... later if (...): os.kill(pid,9) best regards, Yves -- http://mail.python.org/mailman/listinfo/python-list
Re: how to start a process and get it's pid?
Gerhard Häring wrote: > Yves Glodt wrote: >> Hello, >> >> another question rose for me today... >> >> Is there a way to start an external process, in it's own context (not as >> the exec-() functions do), and get it's pid...? [...] > > Check out the subprocess module if you're using Python 2.4. > > Otherwise, you can always use os.spawn*, for example: > > >>> os.spawnl(os.P_NOWAIT, "c:/windows/notepad.exe") > 1944 Thanks, in Linux it seems to work. > HTH, > > -- Gerhard > -- http://mail.python.org/mailman/listinfo/python-list
Clone an object
Hello, how can I clone a class instance? I have trouble finding that in the documentation... thanks and best regards, Yves -- http://mail.python.org/mailman/listinfo/python-list
Re: Pregunta sobre python
Andres de la Cuadra wrote: > Hola, me llamo Andres de la cuadra, soy un usuario de python en chile y me > gustaría saber como puedo cerrer un programa a través de python. Yo se que > con la librería os puedo ejecutar programas, pero no e encontrado una > librería para poder cerrarlos Hola Andres, puedes cerrer un programa con os.kill, pero depende de tu plataforma, por ejemplo en linux (no se para windows): os.kill(pid_del_proceso, 9) p.s. Vas a tener mas excito si escribes en ingles, esta es une lista en ingles ;-) > Gracias > > -- http://mail.python.org/mailman/listinfo/python-list
[Twisted-Python] ssh tunnel
(I asked about this several times in the twisted list but never got an answer, maybe here I'll more happy...) Hi, I'm new to conch and I wonder if somebody could point me to an example of how to create an ssh tunnel with conch to forward a connection (e.g. database or vnc) through that tunnel (if that's possible at all...) Thanks in advance and best regards, Yves -- http://mail.python.org/mailman/listinfo/python-list
Re: Python, Linux, Desktop Environment
> [EMAIL PROTECTED] wrote: > >> So, I've written my first GUI app in python. I've turned it into a >> binary .exe and .app that runs on Windows and Mac respectively, but on >> my Linux box, where I wrote the thing, I still have to drop to the >> command line and ./myscript.py. What can I do to make it a "click and >> run" sort of application in KDE or Gnome on Linux? >> I don't really understand what you mean... Have you tried simply creating a "shortcut" that points to your script.py? That should make it run with a click... HTH, Yves -- http://mail.python.org/mailman/listinfo/python-list
spawnle & umask
Hi, I tried something like this but the umask part does not work clearly...: newpid = os.spawnle(os.P_NOWAIT,'/usr/bin/touch','/usr/bin/touch','xyz','umask 0113') What would be the correct syntax for setting the umask for the created process...? Best regards, Yves -- http://mail.python.org/mailman/listinfo/python-list
Re: spawnle & umask
Fredrik Lundh wrote: > Yves Glodt wrote: > >> I tried something like this but the umask part does not work clearly...: >> >> newpid = >> os.spawnle(os.P_NOWAIT,'/usr/bin/touch','/usr/bin/touch','xyz','umask 0113') >> >> What would be the correct syntax for setting the umask for the created >> process...? > > not sure, but something like > > try: > old_mask = os.umask(0113) > newpid = os.spawnle(...) > finally: > os.umask(old_mask) # restore > > might work. It does, I did like this: os.umask(0113) newpid = os.spawnl(os.P_NOWAIT,'/usr/local/bin/wine','/usr/local/bin/wine',executable) But I wanted to use spawnle and it's env argument, to avoid setting umask manually... regards, Yves > > > > -- http://mail.python.org/mailman/listinfo/python-list
Re: spawnle & umask
David Wahler wrote: > Yves Glodt wrote: >> It does, I did like this: >> >> os.umask(0113) >> newpid = >> os.spawnl(os.P_NOWAIT,'/usr/local/bin/wine','/usr/local/bin/wine',executable) >> >> But I wanted to use spawnle and it's env argument, to avoid setting >> umask manually... > > The umask is not part of the environment, so there's no way to set it > directly through spawnle. ok > Why don't you want to use os.umask? Only because I thought spawnle could set it through env... But as it can't I will now go with os.umask. thanks, Yves > -- David > -- http://mail.python.org/mailman/listinfo/python-list
heartbeats
Hi, I need to write a heartbeat solution to monitor some external clients, and what is different as in the examples that I have seen so far is that I want my central server to poll the clients, and not the clients "pinging" the central server. In detail I need a daemon on my central server which e.g. which in a loop pings (not really ping but you know what I mean) each 20 seconds one of the clients. The only thing the client has to do is to accept the connection. (optionally sending back some bytes). If it refuses it is assumed to be offline. My central server, and this is important, should have a short timeout. If one client does not respond because it's offline, after max. 10 seconds the central server should continue with the next client. Which python functions would be the most convenient for this application? Best regards, Yves -- http://mail.python.org/mailman/listinfo/python-list
python-soappy
Hi list, can anybody point me to a tutorial, howto or example code of python-soappy...? google did not have really useful results about... Best regards, Yves -- http://mail.python.org/mailman/listinfo/python-list
Snapshot+Clipboard
Hello, i'm searching a method to take a snapshot and save it in a jpg, bmp or gif file. I tried with win32api and win32con but it save the snapshot to the clipboard, so i tried to redirect this in a file but i have some problems while getting the IMAGE stocked in the clipboard and save it to a file. Can somebody help me ? Questions: -How can i read the snapshot in the clipboard ? -How can i take a snapshot in a different way (less difficult) ? Thks. -- http://mail.python.org/mailman/listinfo/python-list
Re: Snapshot+Clipboard
Claudio Grondi a écrit : > Yves Lange wrote: >> Hello, >> i'm searching a method to take a snapshot and save it in a jpg, bmp or >> gif file. I tried with win32api and win32con but it save the snapshot >> to the clipboard, so i tried to redirect this in a file but i have >> some problems while getting the IMAGE stocked in the clipboard and >> save it to a file. Can somebody help me ? >> >> Questions: >> -How can i read the snapshot in the clipboard ? >> -How can i take a snapshot in a different way (less difficult) ? >> >> Thks. > > Use PIL which on Windows supports taking snapshots of the screen. > > import ImageGrab > GrabbedImage = ImageGrab.grab() # store screenshot as "RGB" Image > GrabbedImage.save("TheScreenshot.jpg") # PIL evaluates extension > > For more details see: > http://effbot.org/imagingbook/imagegrab.htm > (works on Windows only) > > Claudio Grondi Thks this module works well ! -- http://mail.python.org/mailman/listinfo/python-list
Re: Zipping files/zipfile module
Simon Forman a écrit : > Brian Beck wrote: >> OriginalBrownster wrote: >>> I want to zip all the files within a directory called "temp" >>> and have the zip archive saved in a directory with temp called ziptemp >>> >>> I was trying to read up on how to use the zipfile module python >>> provides, but I cannot seem to find adequate documentation on function >>> itself. >>> >>> Perhaps someone could help me in this task? >> Hello, >> >> This isn't completely tested, but perhaps it will help you get started: >> >> from os import listdir, mkdir >> from os.path import join, basename, isfile >> from zipfile import ZipFile >> >> def zip_dir(path, output_path, include_hidden=True): >> files = [join(path, f) for f in listdir(path) if isfile(join(path, f))] >> try: >> mkdir(output_path) >> except OSError, e: >> if e.errno == 17: # Path exists >> pass >> zip_file = ZipFile(join(output_path, 'temp.zip'), 'w') >> for f in files: >> if basename(f).startswith('.') and not include_hidden: >> continue >> print "Adding %s to archive..." % (f,) >> zip_file.write(f) >> zip_file.close() >> >> Use like: >> zip_dir('temp', 'temp/ziptemp') >> >> Note that if you want to add the entire contents of a directory >> (subdirectories, recursively), you should consider using os.walk or >> something similar. This will only add the file contents of the directory. >> I'm not sure if the zipfile module provides any nice ways to write >> directories to the archive, but I'm assuming it just involves writing an >> arcname with a '/' in it (see help(zipfile.ZipFile)). >> >> -- >> Brian Beck >> Adventurer of the First Order > > To avoid calling os.path.join() twice for each filename when you build > the list of files you could write the list comprehension like so: > > [n for n in (join(path, f) for f in listdir(path)) if isfile(n)] > > Also, you should use the "symbolic" errors from the errno module rather > than hard-coding a constant: > > from errno import EEXIST > ... > if e.errno == EEXIST: # Path exists > > Finally, if your using a single arg with a string interpolation and you > know it'll never be a tuple you needn't wrap it in a tuple: > > print "Adding %s to archive..." % f > Other solutions: you can try the rar command line from WinRar but it's not recommended. This is a very slow manner to compress file. Or you can try the Bz module of python. -- http://mail.python.org/mailman/listinfo/python-list
schedule at specific hours
Hi there, I have a daemon running 24/7, and I want that it executes a certain function several times a day, as specified in an configfile (e.g. actiontimes=10:00,12:00,19:00) Do I have to fiddle with sched.scheduler and calc. time differences to schedule my events, or is there another (nicer...) way? Regards, Yves -- http://mail.python.org/mailman/listinfo/python-list
pyqt show wizard
Hi, I have a mainwindow in my pyqt application, and on click of a button I want to start an assistant (wizard). I have create the wizard with the Qt Designer, generated the python code with pyuic, imported it "from assistant import *", and subclassed it as usual. To show it, the onclick method of the button does: w = Wizard() w.show() bot nothing happens... How must I do to start the wizard...? Best regards, Yves -- http://mail.python.org/mailman/listinfo/python-list
Activate a daemon several times a day
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
append to the end of a dictionary
Hi there, I seem to be unable to find a way to appends more keys/values to the end of a dictionary... how can I do that? E.g: mydict = {'a':'1'} I need to append 'b':'2' to it to have: mydict = {'a':'1','b':'2'} How to do? Best regards, Yves -- http://mail.python.org/mailman/listinfo/python-list
Re: append to the end of a dictionary
Rene Pijlman wrote: > Yves Glodt: >> I seem to be unable to find a way to appends more keys/values to the end >> of a dictionary > > A dictionary has no order, and therefore no end. that means I can neither have a dictionary with 2 identical keys but different values...? I would need e.g. this: (a list of ports and protocols, to be treated later in a loop) ports = {'5631': 'udp', '5632': 'tcp', '3389': 'tcp', '5900': 'tcp'} #then: for port,protocol in ports.iteritems(): print port,protocol #do more stuff What would be the appropriate pythonic way of doing this? >> mydict = {'a':'1'} >> >> I need to append 'b':'2' to it to have: >> >> mydict = {'a':'1','b':'2'} >> >> How to do? > > Like this: > >>>> mydict = {'a':'1'} >>>> mydict['b'] = '2' >>>> print mydict > {'a': '1', 'b': '2'} >>>> {'a': '1', 'b': '2'} == {'b': '2', 'a': '1'} > True > -- http://mail.python.org/mailman/listinfo/python-list
Re: append to the end of a dictionary
Yves Glodt wrote: > Hi there, > > I seem to be unable to find a way to appends more keys/values to the end > of a dictionary... how can I do that? > > E.g: > > mydict = {'a':'1'} > > I need to append 'b':'2' to it to have: > > mydict = {'a':'1','b':'2'} > > > > How to do? Sorry for the noise... mydict['b'] = '2' > Best regards, > Yves -- http://mail.python.org/mailman/listinfo/python-list
Re: append to the end of a dictionary
Paul Rubin wrote: > Yves Glodt <[EMAIL PROTECTED]> writes: >> that means I can neither have a dictionary with 2 identical keys but >> different values...? > > No. > >> I would need e.g. this: >> (a list of ports and protocols, to be treated later in a loop) >> >> ports = {'5631': 'udp', '5632': 'tcp', '3389': 'tcp', '5900': 'tcp'} >> #then: >> for port,protocol in ports.iteritems(): >> print port,protocol >> #do more stuff >> >> What would be the appropriate pythonic way of doing this? > > ports = [('5631', 'udp'), > ('5632': 'tcp'), > ('3389': 'tcp'), > ('5900': 'tcp')] > > for port,protocol in ports: > print port, protocol # ... > > You'd append with > >ports.append(('2345', 'tcp')) > > note the double set of parentheses since you're appending a tuple. Tim, Paul, I love you guys ! Thanks a lot -- http://mail.python.org/mailman/listinfo/python-list
test whether 2 objects are equal
Hello, I need to compare 2 instances of objects to see whether they are equal or not, but with the code down it does not work (it outputs "not equal") #!/usr/bin/python class Test: var1 = '' var2 = '' test1 = Test() test1.var1 = 'a' test1.var2 = 'b' test2 = Test() test2.var1 = 'a' test2.var2 = 'b' if test1 == test2: print "equal" else: print "not equal" What am I doing wrong...? best regards, Yves -- http://mail.python.org/mailman/listinfo/python-list
Re: test whether 2 objects are equal
Rene Pijlman wrote: > Yves Glodt: >> I need to compare 2 instances of objects to see whether they are equal >> or not, > > This prints "equal": thank you! Have a nice day, Yves > class Test(object): > def __init__(self): > self.var1 = '' > self.var2 = '' > def __eq__(self,other): > return self.var1 == other.var1 and self.var2 == other.var2 > > test1 = Test() > test1.var1 = 'a' > test1.var2 = 'b' > > test2 = Test() > test2.var1 = 'a' > test2.var2 = 'b' > > if test1 == test2: > print "equal" > else: > print "not equal" > -- http://mail.python.org/mailman/listinfo/python-list
Re: test whether 2 objects are equal
bruno at modulix wrote: > Yves Glodt wrote: >> Hello, >> >> >> I need to compare 2 instances of objects to see whether they are equal >> or not, but with the code down it does not work (it outputs "not equal") >> >> >> #!/usr/bin/python >> >> class Test: >> var1 = '' >> var2 = '' > > Take care, this creates two *class* variables var1 and var2. For > *instance* variables, you want: Thanks for making me aware. I'll have to read more about classes in python... ( As you can see I'm still new to it ;-) btw, this is the best list I've ever joined, very helpful and nice ppl. Have a nice day! Yves > class Test: > def __init__(self, var1='', var2=''): > self.var1 = var1 > self.var2 = var2 > > >> test1 = Test() >> test1.var1 = 'a' >> test1.var2 = 'b' > > This creates instances variables var1 and var2 for test1 (shadowing > class variables). > > (snip the rest, see other posts in this thread) > -- http://mail.python.org/mailman/listinfo/python-list
Re: Python threading, and processes
Robin Haswell wrote: > Hey there > > I'm doing some threading in python with Python 2.3 and 2.4 on Ubuntu and > Debian machines, and I've noticed that if I open a lot of threads (say, > 50), I get lots of python processes with individual PIDs, which consume a > disproportionate amount of CPU. Does this mean that Python is using the > dummy_thread module by accident? And is there a realistic limitation to > the number of threads I can do? Though I can not answer your question, I have however a similar situation here, on debian sarge. I have a simple daemon that runs one thread, and I noticed that on our sarges with kernel 2.4 my daemon creates 4 processes, on the ones with kernel 2.6, only one process. btw, I use the thread module. best regards, Yves > Cheers > > -Rob -- http://mail.python.org/mailman/listinfo/python-list
encoding problem
Hi list, Playing with the great pysvn I get this problem: Traceback (most recent call last): File "D:\avn\mail.py", line 80, in ? mailbody += diff UnicodeDecodeError: 'ascii' codec can't decode byte 0xe9 in position 10710: ordinal not in range(128) It seems the pysvn.client.diff function returns "bytes" (as I read in the changelog of pysvn: http://svn.haxx.se/dev/archive-2005-10/0466.shtml) How can I convert this string so that I can contatenate it to my "regular" string? Best regards, Yves -- http://mail.python.org/mailman/listinfo/python-list
generating a liste of characters
Is there any built in way to generate a list of characters, something along the line of range('a'-'z') ? Right now I am using: chars = [ chr(l) for l in range(0x30, 0x3a) ] # 0 - 9 chars += [ chr(l) for l in range(0x41, 0x5b) ] # A - Z chars += [ chr(l) for l in range(0x61, 0x7b) ] # a - z Is there a better, more straight forward way of doing that ? Thanks. Yves. http://www.sollers.ca/blog/2008/swappiness http://www.sollers.ca/blog/2008/swappiness/.fr -- http://mail.python.org/mailman/listinfo/python-list
Unicode (UTF8) in dbhas on 2.5
Can you put UTF-8 characters in a dbhash in python 2.5 ? It fails when I try: #!/bin/env python # -*- coding: utf-8 -*- import dbhash db = dbhash.open('dbfile.db', 'w') db[u'smiley'] = u'☺' db.close() Do I need to change the bsd db library, or there is no way to make it work with python 2.5 ? What about python 2.6 ? Thanks. -- Yves. http://www.sollers.ca/blog/2008/no_sound_PulseAudio http://www.sollers.ca/blog/2008/PulseAudio_pas_de_son/.fr -- http://mail.python.org/mailman/listinfo/python-list
Re: Unicode (UTF8) in dbhas on 2.5
Diez B. Roggisch <[EMAIL PROTECTED]> wrote: > Please write the following program and meditate at least 30min in front of > it: > while True: >print "utf-8 is not unicode" I hope you will have a better day today than yesterday ! Now, I did this: while True: print "¡ Python knows about encoding, but only sometimes !" My terminal is setup in UTF-8, and... It did print correctly. I expected that by setting coding: utf-8, all the I/O functions would do the encoding for me, because if they don't then I, and everybody who writes a script, will need to subclass every single I/O class (ok, except for print !). > Bytestrings are just that - a sequence of 8-bit-values. It used to be that int were 8 bits, we did not stay stuck in time and int are now typically longer. I expect a high level language to let me set the encoding once, and do simple I/O operation... without having encode/decode. > Now the real world of databases, network-connections and harddrives doesn't > know about unicode. They only know bytes. So before you can write to them, > you need to "encode" the unicode data to a byte-stream-representation. > There are quite a few of these, e.g. latin1, or the aforementioned UTF-8, > which has the property that it can render *all* unicode characters, > potentially needing more than one byte per character. Sure if I write assembly, I'll make sure I get my bits, bytes, multi-bytes chars right, but that's why I use a high level language. Here's an example of an implementation that let you write Unicode directly to a dbhash, I hoped there would be something similar in python: http://www.oracle.com/technology/documentation/berkeley-db/db/gsg/JAVA/DBEntry.html > db = dbhash.open('dbfile.db') > smiley = db[u'smiley'.encode('utf-8')].decode('utf-8') > print smiley.encode('utf-8') > The last encode is there to print out the smiley on a terminal - one of > those pesky bytestream-eaters that don't know about unicode. What are you talking about ? I just copied this right from my terminal (LANG=en_CA.utf8): >>> print unichr(0x020ac) € >>> Now, I have read that python 2.6 has better support for Unicode. Does it allow to write to file, bsddb etc... without having to encode/decode every time ? This is a big enough issue for me right now that I will manually install 2.6 if it does. Thanks. -- Yves. http://www.sollers.ca/blog/2008/no_sound_PulseAudio http://www.sollers.ca/blog/2008/PulseAudio_pas_de_son/.fr -- http://mail.python.org/mailman/listinfo/python-list
Re: How to call a file
Gary Herron wrote: First of all, some terminology: You are not *calling* a file, you are *opening* it or reading. Wouldn't it be more correct to say that, in python, you either create a file object, or call a method for that object, once the object has been created ? Yves. -- http://mail.python.org/mailman/listinfo/python-list
Re: Is using range() in for loops really Pythonic?
John Salerno wrote: To me, the first example is a pure use of the for loop. You are iterating through an object and *using* the items you are stepping through. The second example, however, is simply doing something 10 times, and what it's doing has nothing to do with 'x' or xrange. So it seems like an abuse of the for loop. Well, I would say this: myl = ['a', 'b', 'c', 'd'] for i in xrange(len(myl)): print myl[i] As you would see in other languages, is an abuse in python. But in you need to iterate 5 times over something. Do you have a cleaner / python'er alternative ? Do you find the following cleaner: x = 0 while x <= 4: print x x += 1 Yves. http://www.SollerS.ca -- http://mail.python.org/mailman/listinfo/python-list
anonymous assignment
Is there anyway to tell python I don't care about a value ? Say I want today's year and day, I'd like to do something like: import time y, None, d, None, None, None, None = time.localtime() I know you can't assign anything to None, but I'm sure you get what I mean, a special keyword that means I don't care about this value. In this particular case, there's got to be a better way than: d = time.local() y = d[0] d = d[1] Thanks. Yves. http://www.SollerS.ca -- http://mail.python.org/mailman/listinfo/python-list
Re: anonymous assignment
Paul Rubin wrote: Yves Dorfsman <[EMAIL PROTECTED]> writes: import time y, None, d, None, None, None, None = time.localtime() I know you can't assign anything to None, but I'm sure you get what I mean, a special keyword that means I don't care about this value. You can just use a variable name than you ignore. It's traditional to use _ but it's not a special keyword, it's just a another variable name: y, _, d, _, _, _, _, _, _ = time.localtime() But you still have have a variable that's using memory for nothing. I find this unsatisfactory... I don't want to compare languages, but I find the perl "undef" elegant. Yves. http://www.SollerS.ca -- http://mail.python.org/mailman/listinfo/python-list
Re: anonymous assignment
D'Arcy J.M. Cain wrote: On Mon, 12 May 2008 02:28:13 GMT Yves Dorfsman <[EMAIL PROTECTED]> wrote: particular case, there's got to be a better way than: d = time.local() y = d[0] d = d[1] Like this? y, d = time.local()[:2] Sorry this was a typo (again :-), I meant: d = time.local() y = d[0] d = d[2] Yves. http://www.SollerS.ca -- http://mail.python.org/mailman/listinfo/python-list
Re: anonymous assignment
Gabriel Genellina wrote: Uses Python 2.6! ;) No need of 2.6 - the above code works since Python 2.2 at least: Python 2.2.3 (#42, May 30 2003, 18:12:08) [MSC 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. import time t=time.localtime() type(t) t.tm_year 2008 (but struct_time objects were printed as regular tuples) And not well documented ! Nice one ! Thanks. -- http://mail.python.org/mailman/listinfo/python-list
Re: anonymous assignment
Ben Finney wrote: y, _, d, _, _, _, _, _, _ = time.localtime() But you still have have a variable that's using memory for nothing. No, you have one extra unused name binding. The values that you don't want to use have *already* been allocated by the time the above statement is executed. Name binding doesn't copy the values, it merely binds a name to them. There's no "variable" in the above statement. But if this happens in the main part of your script, it could take a long time before this binding disapear, therefore, the gc won't be able to clean that one up. In this particular case, it doesn't really matter (small size), but imagine in a case where we are talking of a list of list, with potentially large element in the list. Yves. -- http://mail.python.org/mailman/listinfo/python-list
Re: anonymous assignment
Scott David Daniels wrote: Yves Dorfsman wrote: ... Sorry this was a typo (again :-), I meant: d = time.local() y = d[0] d = d[2] Then: y, d = list(time.localtime())[:4:2] What is this ? Could you point me to a document on this syntax ? I've tried it, it works, but I don't understand how. Thanks. Yves. -- http://mail.python.org/mailman/listinfo/python-list
Re: anonymous assignment
Marc 'BlackJack' Rintsch wrote: y, _, d, _, _, _, _, _, _ = time.localtime() But you still have have a variable that's using memory for nothing. I find this unsatisfactory... Get over it… Than what's the point of wanting a better language if every time we run in something that looks wrong, or something that could be done better we should just "get over it" ? Yves. -- http://mail.python.org/mailman/listinfo/python-list
How to subclass file
I want to create a subclass of 'file' but need to open the file with os.open (because I want to open it in exclusive mode), and need an additional method. Because I need an additional method, I truly need a object of my sublass. If I do something like class myFile(file): def __new__(cls, filename): import os fd = os.open(filename, os.O_WRONLY | os.O_CREAT | os.O_EXCL) return os.fdoen(fd, 'w') def myMethod(self): do_something then x = myFile('somefilename') is of type file, not myFile, and therefore does not have myMethod as a valid method. Now if I try: class myFile(file): def __new__(cls, filename): import os fd = os.open(filename, os.O_WRONLY | os.O_CREAT | os.O_EXCL) obj = file.__new__(cls) return obj def myMethod(self): do_something Then it fails, because the 'file' constructor needs a filename. I can provide the filename, but it will then try to re-open that file, and even if I did manage to create an object file, how do I connect the file descriptor created by os.open to my object ? Thanks. Yves. http://www.SollerS.ca -- http://mail.python.org/mailman/listinfo/python-list
Re: Producing multiple items in a list comprehension
Peter Otten <[EMAIL PROTECTED]> wrote: > > A slightly similar problem: If I want to "merge," say, list1=[1,2,3] with > > list2=[4,5,6] to obtain [1,4,2,5,3,6], is there some clever way with "zip" > > to do so? > >>> items = [None] * 6 > >>> items[::2] = 1,2,3 > >>> items[1::2] = 4,5,6 > >>> items > [1, 4, 2, 5, 3, 6] My problem with this solution is that you depend on knowing how many elements you have in each list ahead of time. Assuming that both list are of the same length, then, I find the following more elegant: list1=[1,2,3] list2=[4,5,6] reduce(lambda x, y: x+y, zip(list1, list2)) of course, zip creates tuples, so you end up with a tuple, therefore if you need for your solution to be a list: list(reduce(lambda x, y: x+y, zip(list1, list2))) of reduce(lambda x, y: x+y, list(zip(list1, list2)) ) Yves. http://www.SollerS.ca -- http://mail.python.org/mailman/listinfo/python-list
Re: serach file for regexp, return if found?
[EMAIL PROTECTED] wrote: > i want to search a document for a particular regexp and then store > that regexp to a file. > but search and match only returns matchobjects(what are those anyway? > i dont get what to do with them, do they contain true/false, > stringposition etc?) > how do i do: > for rows in file: > print regexp.find ## or something equiavlent Is this what you are trying to do: for row in file('/etc/services'): if re.match('^ssh', row): print row Yves. http://www.SollerS.ca -- http://mail.python.org/mailman/listinfo/python-list
Re: Producing multiple items in a list comprehension
Peter Otten <[EMAIL PROTECTED]> wrote: > The speed gain is significant. Why should I throw away useful information if > I have it? My thinking was that it wasn't generic enough, and I was looking for a solution that would work for more generic problem. I agree, I shouldn't have used the world "elegant" here, more generic would have been better. > I'd even be willing to convert one arbitrary iterable to a list > to get the length information. > $ python -m timeit -s"a = [1,2,3]*100; b = [4,5,6]*100" "aa = list(a); > items=[None]*(2*len(aa)); items[::2] = aa; items[1::2] = b" > 1 loops, best of 3: 29.5 usec per loop Yes, I like that, it is as generic as the reduce one. > are more complicated than elegant. Not recommended. You proved your point. Every book and webpage out there says that functional solutions are faster than loops, that's why I tried hard not to use a loop, and "reduce" is considered functional - I should have timed it. Yves. http://www.SollerS.ca -- http://mail.python.org/mailman/listinfo/python-list
Re: how to remove \n in the list
Gabriel Genellina wrote: > En Mon, 14 Apr 2008 01:41:55 -0300, reetesh nigam >> l=['5\n', '2\n', '7\n', '3\n', '6\n'] >> >> how to remove \n from the given list > > l is is very poor name... I'll use lines instead: > > lines[:] = [line.rstrip('\n') for line in lines] When I saw the original message, I immediately thought: k = [x.strip() for x in l] What is the point of the [:] after lines ? How different is it with or without it ? Yves. http://www.SollerS.ca -- http://mail.python.org/mailman/listinfo/python-list
Re: how to remove \n in the list
Dan Bishop wrote: >>> lines[:] = [line.rstrip('\n') for line in lines] >> What is the point of the [:] after lines ? How different is it with or >> without it ? > > It causes the result to be stored in the existing list. > If we do: lines = [line.rstrip('\n') for line in lines] lines is now a new list, the old list as no reference to it, and will be discarded by the gc, right ? So we're not really saving any space here ? If we do: lines[:] = [line.rstrip('\n') for line in lines] We reuse an existing list, therefore we are saving the time it takes to create a new list ? So this is a performance issue ? Thanks. Yves. http://www.SollerS.ca -- http://mail.python.org/mailman/listinfo/python-list
#!/usr/bin/env python vs. #!/usr/bin/python
On UNIX, some people use #!/usr/bin/env python While other use #!/usr/bin/python Why is one preferred over the other one ? Thanks. -- Yves. http://www.SollerS.ca -- http://mail.python.org/mailman/listinfo/python-list
help with list comprehension
In the following script, m1() and m2() work fine. I am assuming m2() is faster although I haven't checked that (loops through the list twice instead of once). Now what I am trying to do is something like m3(). As currently written it does not work, and I have tried different ways, but I haven't managed to make it work. Is there a possibility ? Or is m2() the optimum ? Thanks. #!/usr/bin/python l = [ { 'colour': 'black', 'num': 0}, { 'colour': 'brown', 'num': 1}, { 'colour': 'red', 'num': 2}, { 'colour': 'orange', 'num': 3}, { 'colour': 'yellow', 'num': 4}, { 'colour': 'green', 'num': 5}, { 'colour': 'blue','num': 6}, { 'colour': 'violet', 'num': 7}, { 'colour': 'grey','num': 8}, { 'colour': 'white', 'num': 9} ] def m1(): colours = [ e['colour'] for e in l ] nums= [ e['num']for e in l ] def m2(): colours = [] nums= [] for e in l: colours.append(e['colour']) nums.append(e['num']) #def m3(): # colours, nums = [ e['colour'], e['num'] for e in l ] -- Yves. http://www.SollerS.ca -- http://mail.python.org/mailman/listinfo/python-list
no cleanup on TERM signal
I did a few tests with this script: class byebye: def __del__(self): print 'Bye, bye...' x = byebye() x.del() gets executed if: -I del x, then run gc.collect() -simply exit the script -get the script to abort on an exception But if I kill it with the default signal TERM, the script dies, but I don't get the message, so I am assuming that python isn't taking the time to cleanup, even though that is (was) what TERM was intended for. Has this been discussed before ? Is worth a suggestion (PEP) ? -- Yves. http://www.SollerS.ca -- http://mail.python.org/mailman/listinfo/python-list
Re: help with list comprehension
George Sakkis wrote: Another alternative is: from operator import itemgetter def m3(): colours, nums = zip(*map(itemgetter('colour','num'), l)) It's slower than m1() but faster than m2(); it's also the most concise, especially if you extract more than two keys. Good you guys gave me some ideas, I've made m3() work: def m3() total = [ [e['colour'], e['num'], e['couleur']] for e in l ] c,d,e = zip(*total) return map(list, [c,d,e]) (I have to transform to lists, I need to transform them later on, so tuples won't work). Unfortunately the timing is inconsistant, the first time I run python -m timeit 'import listcomp ; listcomp.m1()' m1 is the fastest. But then if I run the test several times, they all seem to be about the same time ; I'll have to try with a large list. Now here is a question: Is there any way to change my first line there for the list comp. to return a list of lists rather than a list of tuples ? -- http://mail.python.org/mailman/listinfo/python-list
Re: #!/usr/bin/env python vs. #!/usr/bin/python
Thanks everybody, I didn't mean to start a flamewar... I do get it now, it's whatever python is in the path, vs. the specific one you're pointing to. Ben Finney wrote: No, because it's quite common for the PATH variable to have '/usr/local/bin' appear *before* both of '/bin' and '/usr/bin'. If the system has a sysadmin-installed '/usr/local/bin/python' installed as well as the OS-installed '/usr/bin/python', then the two shebang options the OP raised will behave differently on such a system. This seems to be quite the point of the discussion. And I have to admit, I prefer specifying the version (full path) because I have run into too many problem when users have different PATHs and end up running different version of an interpreter. Yves. -- http://www.SollerS.ca -- http://mail.python.org/mailman/listinfo/python-list
slicing lists
Is there a way to do: x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] x[0,2:6] That would return: [0, 3, 4, 5, 6] I am surprised this notation is not supported, it seems intuitive. A concrete example of the sort of thing I want to do: p = file('/etc/passwd').readlines() q = [ e.strip().split(':')[0,2:] for e in p ] (getting rid of the password / x field) Thanks. Yves. http://www.SollerS.ca -- http://mail.python.org/mailman/listinfo/python-list
class definition
Does it make a difference if you put subclass object or not ? What is the difference between c1 and c2 here: class c1: pass class c2(object): pass Thanks, Yves. http://www.SollerS.ca -- http://mail.python.org/mailman/listinfo/python-list
Re: class definition
Miles wrote: In Python 2.2, classes and types were unified. If a class inherits from object (or any other built-in), it is considered a "new-style" class; otherwise, it is an old-style (or classic) class. There are some differences in their behavior; most notably, descriptors (computer properties) will not work with old-style classes. Old-style classes will go away in Python 3 (I think), and all classes will have object as a base. An introduction to new-style classes: http://www.cafepy.com/article/python_types_and_objects/python_types_and_objects.html A guide to descriptors: http://users.rcn.com/python/download/Descriptor.htm The reference manual on the distinction: http://docs.python.org/ref/node33.html The technical explanation: http://www.python.org/download/releases/2.2.3/descrintro/ Thanks Miles, I've started to go though those links, that should keep me busy for a while ! Yves. http://www.SollerS.ca -- http://mail.python.org/mailman/listinfo/python-list
Re: slicing lists
Miles wrote: On Wed, May 7, 2008 at 7:46 PM, Ivan Illarionov > > Is there a way to do: > > x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] > > x[0,2:6] > > > > That would return: > > [0, 3, 4, 5, 6] Arg... Yes, this is a typo, I meant: [1, 3, 4, 5, 6] I think Yves meant to return [1, 3, 4, 5, 6], as in Perl's list slicing: my @x = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10); return @x[0, 2..6]; // returns (1, 3, 4, 5, 6) Yes, exactly. This isn't incredibly efficient, but it does what you want (I think): from itertools import chain class multisliceable(list): def __getitem__(self, slices): if isinstance(slices, (slice, int, long)): return list.__getitem__(self, slices) else: return list(chain(*[list.__getitem__(self, s) if isinstance(s, slice) else [list.__getitem__(self, s)] for s in slices])) p = open('/etc/passwd') q = [multisliceable(e.strip().split(':'))[0,2:] for e in p] So would it be a worthy addition to python, to add it right in the core of the language, and hopefully in an efficient manner ? That would certainly help some type of list comprehensions, making them more readable, and hopefully more readable (running split once instead of twice, or how many number of time you need it). The passwd example is just one example I ran into, but I can see running in this problem a lot with more complex cases. Right now I solve the passwd pb with: p = file('/etc/passwd').readlines() r = [ e.strip().split(':') for e in p ] s = [ e[0:1] + e[2:] for e in r ] Or: p = file('/etc/passwd').readlines() s = [ e.strip().split(':')[0:1] + e.strip().split(':')[2:] for e in p ] In the first case we're looping twice (two list comprehension), in the second case we're running the split twice on every element of p. Yves. http://www.SollerS.ca -- http://mail.python.org/mailman/listinfo/python-list
Re: python newbie: some surprises
Mensanator wrote: 2. python requires to pass "self" to all instance methods Who uses methods? Is this a joke ? What are the alternatives ? and I missed ":" often. :) Try using something like Seed7, where you have to use "then" with "if" and "do" with "while" and "end" in every block. Maybe you'll come to appreciate significant whitespace and ":". I see the point of the OP. Couldn't the new-line be used as an equivalent of ':', for example, do you find this difficult to read: if a == 3 do_something() if a == 3: do_something() And surely, it should be easy to parse by the compiler. Yves. http://www.SollerS.ca -- http://mail.python.org/mailman/listinfo/python-list
Re: slicing lists
MRAB wrote: You should've read the thread entitled "Why don't generators execute until first yield?"! :-) Michael Torrie gave the URL http://www.dabeaz.com/generators/Generators.pdf. Your example can be rewritten as follows: p = file('/etc/passwd') # No need for readlines() because file's iterator yields the lines. r = ( e.strip().split(':') for e in p ) # A generator expression instead of a list comprehension. s = [ e[0:1] + e[2:] for e in r ] Thanks, this is very elegant indeed, but because there are two list comprehension expressions (the one defining r and the one defining s), it means that the we're looping twice over the same list instead of once with the e[0,2:] hypotetical notation ; or am I missing something ? Yves. http://www.SollerS.ca -- http://mail.python.org/mailman/listinfo/python-list
Re: Grabbing previous iteration in a dict
[EMAIL PROTECTED] wrote: You cannot rely on the elements of a dictionary being in any particular order (dicts are internally hash tables), so the above is almost certainly ont what you want. Hi - thanks for your reply. How about if I made the dict into a list (of which I have done). How would I then reference the previous item? Can they be indexed? Yes, I ran in a situation similar to yours, I read the content of a file, and had to both keep the order of the lines in the original file, and create a dictionary from the lines. So I created a class that contained both a dictionary and a tuple containing the keys of the dictionary in the original order. Something like this: class mydict(object): def __init__(self, filename): x = [ e.strip().split() for e in file(filename) ] self.ordered_lines = tuple([ e[0] for e in x ]) self.dictionary = dict( zip(self.ordered_lines, [ e[1:] for e in x]) ) a = mydict('/some/file') a.ordered_lines a.dictionary Yves. http://www.SollerS.ca -- http://mail.python.org/mailman/listinfo/python-list
Re: python newbie: some surprises
Gabriel Genellina wrote: I see the point of the OP. Couldn't the new-line be used as an equivalent of ':', for example, do you find this difficult to read: if a == 3 do_something() if a == 3: do_something() Yes, it could be done, there are no technical reasons to always force to use ":". But AFAIK the main reasons to keep ":" are internal consistency (an inner block always starts with ":"; incidentally, that's easier to handle for editors) and legibility (the ":" stands for itself and has a meaning) Legibility ? But one could make the same argument for curly brackets, and we seem to be doing fine without them ! I have become so used to the power of indenting in python that I keep forgetting the colon, and this is getting worse as I do more python, not better. Maybe I'll write myself a "pre-compiler" that add the colons where the compiler needs them :-) Yves. http://www.SollerS.ca -- http://mail.python.org/mailman/listinfo/python-list
Re: slicing lists
[EMAIL PROTECTED] wrote: The only thing is, is there is another natural meaning to [a,b:c]. Counting grids on the diagonals, the rational set is well defined: 0: 0, 0 1: 1, 0 2: 0, 1 3: 2, 0 4: 1, 1 5: 0, 2 6: 3, 0 7: 2, 1 ... Thencefore ( 2, 0 ) : ( 3, 0 ) is well defined. Thencefore, a,b:c,d is not; x[a,b:c,d]= x[a]+ x[b:c]+ x[d]. I'm not sure what you mean here. Could you give me a simple piece of code to show an example ? Yves. http://www.SollerS.ca -- http://mail.python.org/mailman/listinfo/python-list
Re: encoding problem
Sebastjan Trepca wrote: > I think you are trying to concatenate a unicode string with regular > one so when it tries to convert the regular string to unicode with > ASCII(default one) encoding it fails. First find out which of these > strings is regular and how it was encoded, then you can decode it like > this(if regular string is diff): > > mailbody +=diff.decode('') Thanks I'll look into that... It seems in general I have trouble with special characters... What is the python way to deal with éàè öäü etc... print 'é' fails here, print u'é' as well :-( How am I supposed to print non-ascii characters the correct way? best regards, Yves > Sebastjan > > On 3/3/06, Yves Glodt <[EMAIL PROTECTED]> wrote: >> Hi list, >> >> >> Playing with the great pysvn I get this problem: >> >> >> Traceback (most recent call last): >>File "D:\avn\mail.py", line 80, in ? >> mailbody += diff >> UnicodeDecodeError: 'ascii' codec can't decode byte 0xe9 in position >> 10710: ordinal not in range(128) >> >> >> >> It seems the pysvn.client.diff function returns "bytes" (as I read in >> the changelog of pysvn: http://svn.haxx.se/dev/archive-2005-10/0466.shtml) >> >> How can I convert this string so that I can contatenate it to my >> "regular" string? >> >> >> Best regards, >> Yves -- http://mail.python.org/mailman/listinfo/python-list
Why won't Python 2/3 compile when I have valgrind installed?
This isn't a huge issue, but I'm wondering. I'm running Mac OS X, I tried to configure with --with-valgrind and this is the error that I got: configure: error: Valgrind support requested but headers not available Now, I have valgrind installed, so it should work, yes? If someone has any extra info on this, I'd appreciate it. -- http://mail.python.org/mailman/listinfo/python-list
Having a hard time to 'get' bing api search results
Hello all, This is my dilemma, I'm trying to get the generated JSON file using the bing api search. This is the code that I'm executing from inside the shell: http://bin.cakephp.org/view/460660617 The port doesn't matter to me. Thoughts? -- http://mail.python.org/mailman/listinfo/python-list
Re: Having a hard time to 'get' bing api search results
This is the format that I've been following: http://gavinmhackeling.com/blog/2012/05/using-the-bing-search-api-in-python/ If I execute the specified query from a browser, the JSON file shows up without a problem. Now, I'd like to do that programmatically. On Thu, Jun 13, 2013 at 4:57 PM, Yves S. Garret wrote: > Hello all, > > This is my dilemma, I'm trying to get the generated JSON file using the > bing api > search. > > This is the code that I'm executing from inside the shell: > http://bin.cakephp.org/view/460660617 > > The port doesn't matter to me. Thoughts? > -- http://mail.python.org/mailman/listinfo/python-list
Re: Having a hard time to 'get' bing api search results
That works beautifully! Thank you! I do have one question, what are urllib and urllib2 then? I figured that urllib2 is a newer version of the previous library (and one that I should be using). Am I missing something? On Thu, Jun 13, 2013 at 6:45 PM, Kevin LaTona wrote: > > I did a quick test with url lib instead of urllib2 and got closer. > > Problem right now is without ID code I can't check any further. > > But it does look promising at this point. > > > If all else fails http://docs.python.org/2/library/urllib.html#examples > > > import urllib > > f = urllib.urlopen(' > https://user:...@api.datamarket.azure.com/Bing/SearchWeb/Web?Query=%27xbox%20one%27&$top=50&$format=JSON' > ) > > print f.read() > > > > IOError: ('http error', 401, 'The authorization type you provided is not > supported. Only Basic and OAuth are supported', > > > > > > On Jun 13, 2013, at 2:31 PM, Yves S. Garret > wrote: > > This is the format that I've been following: > > http://gavinmhackeling.com/blog/2012/05/using-the-bing-search-api-in-python/ > > If I execute the specified query from a browser, the JSON file > shows up without a problem. Now, I'd like to do that programmatically. > > > On Thu, Jun 13, 2013 at 4:57 PM, Yves S. Garret < > yoursurrogate...@gmail.com> wrote: > >> Hello all, >> >> This is my dilemma, I'm trying to get the generated JSON file using the >> bing api >> search. >> >> This is the code that I'm executing from inside the shell: >> http://bin.cakephp.org/view/460660617 >> >> The port doesn't matter to me. Thoughts? >> > > -- > http://mail.python.org/mailman/listinfo/python-list > > > -- http://mail.python.org/mailman/listinfo/python-list
Re: Having a hard time to 'get' bing api search results
Thanks again Kevin. I'm deviating from the original thread, but I've got another issue. When I try to load the json file and then parse it, this is the error that I get: http://bin.cakephp.org/view/1329549559 On Thu, Jun 13, 2013 at 6:57 PM, Kevin LaTona wrote: > > > Your welcome. > > > To be honest I am not 100% on the differences between. > > I could be off, but I recall urllib2 was a more refined version of urllib. > > Yet it seems like urllib works better for me, when I need to do a simple > call like this. > > > -Kevin > > > > On Jun 13, 2013, at 3:50 PM, "Yves S. Garret" > wrote: > > That works beautifully! Thank you! > > I do have one question, what are urllib and urllib2 then? I figured that > urllib2 is a newer version of the previous library (and one that I should > be using). Am I missing something? > > > On Thu, Jun 13, 2013 at 6:45 PM, Kevin LaTona wrote: > >> >> I did a quick test with url lib instead of urllib2 and got closer. >> >> Problem right now is without ID code I can't check any further. >> >> But it does look promising at this point. >> >> >> If all else fails http://docs.python.org/2/library/urllib.html#examples >> >> >> import urllib >> >> f = urllib.urlopen(' >> https://user:...@api.datamarket.azure.com/Bing/SearchWeb/Web?Query=%27xbox%20one%27&$top=50&$format=JSON' >> ) >> >> print f.read() >> >> >> >> IOError: ('http error', 401, 'The authorization type you provided is not >> supported. Only Basic and OAuth are supported', >> >> >> >> >> >> On Jun 13, 2013, at 2:31 PM, Yves S. Garret >> wrote: >> >> This is the format that I've been following: >> >> http://gavinmhackeling.com/blog/2012/05/using-the-bing-search-api-in-python/ >> >> If I execute the specified query from a browser, the JSON file >> shows up without a problem. Now, I'd like to do that programmatically. >> >> >> On Thu, Jun 13, 2013 at 4:57 PM, Yves S. Garret < >> yoursurrogate...@gmail.com> wrote: >> >>> Hello all, >>> >>> This is my dilemma, I'm trying to get the generated JSON file using the >>> bing api >>> search. >>> >>> This is the code that I'm executing from inside the shell: >>> http://bin.cakephp.org/view/460660617 >>> >>> The port doesn't matter to me. Thoughts? >>> >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> >> >> > > -- http://mail.python.org/mailman/listinfo/python-list
Re: Having a hard time to 'get' bing api search results
On Fri, Jun 14, 2013 at 2:04 PM, Kevin LaTona wrote: > > > Sounds like you are missing a closing } json bracket > > > Try a different json validator site to prove your json doc is working. > > > If it's the same doc you sent me last night it worked for me > > so maybe it got messed up moving it around? > > > > > > On Jun 14, 2013, at 10:53 AM, "Yves S. Garret" > wrote: > > Hi Kevin, still more of the same: > http://bin.cakephp.org/view/1358843680 > > The file _is_ there. I did check the JSON file, in this site: > - http://paulisageek.com/json_validator/ > > I got an error stating this: > expected property name or '}' > > And I don't know what it means, especially if my JSON looks like this: > http://bin.cakephp.org/view/33141714 > > > On Fri, Jun 14, 2013 at 12:40 PM, Kevin LaTona wrote: > >> >> import json >> >>> from pprint import pprint >> >>> path = '/home/azureuser/temp.json' >> >>> with open(data) as data_file: >> ... data = json.load(data_file) >> >> >> >> change this to >> >> >> with open(path) as data_file: >> >> >> >> you need to tell the open command what file path to read. >> >> >> >> >> >> On Jun 14, 2013, at 9:28 AM, "Yves S. Garret" >> wrote: >> >> > Hi Kevin, >> > >> > This is the file. >> > http://bin.cakephp.org/view/1893672423 >> > >> > >> > On Fri, Jun 14, 2013 at 12:20 PM, Kevin LaTona >> wrote: >> > >> > >> > >> >> >> >> Traceback >> >> (most recent call last): >> >> >> >> File >> >> "", line 1, in >> >> >> >> NameError: name 'data' is not defined >> > >> > >> > >> > It looks like it saying it did not open and read your json document. >> > >> > Are you 100% sure that is sitting in your home directory? >> > >> > Trying opening it with nano or some other text editor at that path >> > >> > or try >> > >> > cat /home/azureuser/temp.json >> > >> > and see what you get >> > >> > >> > >> > Your are close…… so close. >> > >> > >> > On Jun 14, 2013, at 9:03 AM, Yves S. Garret >> wrote: >> > >> >> Hi Kevin, >> >> >> >> I'm not sure what I'm doing wrong... this is what I did in the shell >> and the error that I got: >> >> http://bin.cakephp.org/view/49070824 >> >> >> >> I'll keep hacking away at this problem... >> >> >> >> >> >> On Thu, Jun 13, 2013 at 11:26 PM, Kevin LaTona >> wrote: >> >> >> >> both are working for me. >> >> >> >> >> >> >> >> >> >> import json >> >> from pprint import pprint >> >> >> >> path = '/Users/yves/ms.json' >> >> >> >> >> >> with open(path) as data_file: >> >> data = json.load(data_file) >> >> >> >> >> >> >> >> this will allow you to walk through >> >> >> >> [ list ] requires a number else should be mostly just names pulled >> out of the jSon doc >> >> >> >> Xbox One is a state-of-the art gaming console, a new generation TV and >> movie system and a whole lot more. Gone are the days of switching inputs on >> your TV to play a game or watch a movie. >> >> >> >> >> >> * >> >> >> >> >> >> >> >> >> >> print data['d']['results'][0]['Description'] >> >> >> >> >> >> >> >> >> >> pretty print >> >> >> >> >> >> >> >> pprint(data) >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> >> {u'd': {u'__next': u" >> https://api.datamarket.azure.com/Data.ashx/Bing/SearchWeb/Web?Query='xbox%20one'&$skip=2&$top=2 >> ", >> >> u'results': [{u'Description': u'Xbox One is a state-of-the art
n00b question on spacing
Hi, I have a question about breaking up really long lines of code in Python. I have the following line of code: log.msg("Item wrote to MongoDB database %s/%s" %(settings['MONGODB_DB'], settings['MONGODB_COLLECTION']), level=log.DEBUG, spider=spider) Given the fact that it goes off very far to the right on my screen is not terribly pleasing to my eyes (and can be rude for other developers). I was thinking of splitting it up like so: log.msg("Item wrote to MongoDB database %s/%s" %(settings['MONGODB_DB'], settings['MONGODB_COLLECTION']), level=log.DEBUG, spider=spider) Is this ok? Are there any rules in Python when it comes to breaking up long lines of code? -- http://mail.python.org/mailman/listinfo/python-list
Re: n00b question on spacing
On Fri, Jun 21, 2013 at 5:48 PM, Ray Cote wrote: > > -- > > *From: *"Yves S. Garret" > *To: *python-list@python.org > *Sent: *Friday, June 21, 2013 5:17:28 PM > *Subject: *n00b question on spacing > > > Hi, I have a question about breaking up really long lines of code in > Python. > > I have the following line of code: > log.msg("Item wrote to MongoDB database %s/%s" %(settings['MONGODB_DB'], > settings['MONGODB_COLLECTION']), level=log.DEBUG, spider=spider) > > Given the fact that it goes off very far to the right on my screen is not > terribly > pleasing to my eyes (and can be rude for other developers). > > I was thinking of splitting it up like so: > log.msg("Item wrote to MongoDB database %s/%s" > %(settings['MONGODB_DB'], settings['MONGODB_COLLECTION']), > level=log.DEBUG, spider=spider) > > Is this ok? Are there any rules in Python when it comes to breaking up > long lines of > code? > > -- > http://mail.python.org/mailman/listinfo/python-list > > > Hi Yves: > PEP8 is your definitive guide for style questions: > <http://www.python.org/dev/peps/pep-0008/> > > and this is an interesting set of notes: > < > http://stackoverflow.com/questions/5931297/how-would-you-properly-break-this-line-to-match-pep8-rules > > > > > Basic rule is to break within parenthesis -- after that it becomes a > matter of personal taste/style. > > In your specific example, I would do something like: > log.msg( > "Item wrote to MongoDB database %s %s" % ( > > settings['MONGODB_DB'], > settings['MONGODB_COLLECTION]), > level=log.DEBUG, > spider=spider) > > Though you might want to: > a) start your string right after the log.msg( > b) put more than one settings on the same line > c) put the last two parameters on the same line. > > I find that once I start breaking up lines for length, that I prefer to > break up everything. > > Also remember when entering long lines of text that strings concatenate > within parenthesis. > So, > ("a, b, c" > "d, e, f" > "g, h, i") > > Is the same as ("a, b, cd, e, fg, h, i") > > --Ray > > -- > Ray Cote, President > Appropriate Solutions, Inc. > We Build Software > 603.924.6079 > Thanks for your reply Ray. My concern was that if I were to break with something like this: log.msg("Item written to MongoDB database %s/%s" %(settings['MONGODB_DB'], settings['MONGODB_COLLECTION']), level = log.DEBUG, spider = spider) I would get some undefined behaviour (the % is a little before the log.msg). I'll read the links that you provided in order to learn more. -- http://mail.python.org/mailman/listinfo/python-list
Unable to compile Python 2.7.3 in Cygwin
Hi, I'm trying to compile Python in Cygwin, with little luck. I've posted the ugliness in this link. Thoughts? http://bin.cakephp.org/view/176472400 -- http://mail.python.org/mailman/listinfo/python-list
Good web-development Python book
Hello, I'm trying to brush up on my Python and would like to -- http://mail.python.org/mailman/listinfo/python-list
Good web-development Python book
Oooops! Sent my previous e-mail too soon! Didn't mean to. Another try. Hello, I'm trying to brush up on my Python and would like to learn how to make web-apps. I was hoping to get a good book on learning how to make web-applications using Python (as opposed to something like PHP) without any framework at the moment. Do you guys have any suggestions? I looked around on Amazon, but didn't really find anything too promising. It was either very old or had no more than 3 stars in a rating. I'd appreciate your help on this. -- http://mail.python.org/mailman/listinfo/python-list
Re: [TIP] Anyone still using Python 2.5?
On Wed, Dec 21, 2011 at 07:15:46AM +, Chris Withers wrote: > Hi All, > > What's the general consensus on supporting Python 2.5 nowadays? > > Do people still have to use this in commercial environments or is > everyone on 2.6+ nowadays? > > I'm finally getting some continuous integration set up for my > packages and it's highlighting some 2.5 compatibility issues. I'm > wondering whether to fix those (lots of ugly "from __future__ import > with_statement" everywhere) or just to drop Python 2.5 support. > > What do people feel? Most linux distribution went directly from 2.4 to 2.5 Debian: old stable (lenny) 2.4 stable (squeeze)2.5 Red Hat REHL5 2.4 REHL6 2.6 The most notable exception is Ubuntu Hardy and LTS release from april 2008 with 2.5. But this LTS is out of support for almost 1 year now and current LTS (Lucid) ship 2.6. If you don't plan to support 2.4, supporting 2.5 does not seems a priority. -- Pierre-Yves David http://www.logilab.fr/ signature.asc Description: Digital signature -- http://mail.python.org/mailman/listinfo/python-list