Re: Installation of python on my workspace.
[EMAIL PROTECTED] wrote: Hi, I had two questions. I am new to Unix and Python. I wanted to get python installed on my unix terminal without too much interference from the administrator. How can I do this? It seems python is already installed at some location. But when i type Idle I am not able to get the Integrated Environment(IDLE). There is already the Tkinter.py installed . Do i have to modify my profile and add any environment variables to my .profile to get it going. I would greatly appreciate it, if anyone could help me with this. Thanks. As far as I know, my linux instalation of python doesn't have an IDE, but it could be different for your situation. If it is, the command is probably not called idle (that does something else normaly). You can always use an existing text editor. If python itself is installed, you should be able to type python to bring up the interperiter, or python filename.py to run filename.py. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to trap the event of a new process starting with wmi
gel wrote: Below is how it is down with vbscript. What is the best way to convert this to python? strComputer = . Set objWMIService = GetObject(winmgmts: _ {impersonationLevel=impersonate}!\\ strComputer \root\cimv2) Set colMonitoredProcesses = objWMIService. _ ExecNotificationQuery(select * from __instancecreationevent _ within 1 where TargetInstance isa 'Win32_Process') i = 0 Do While i = 0 Set objLatestProcess = colMonitoredProcesses.NextEvent Wscript.Echo objLatestProcess.TargetInstance.Name Loop A better question might be is there a method or guide for converting from vbs wmi to python wmi? -- http://mail.python.org/mailman/listinfo/python-list
Re: How can get button's name when cursor move over the button on a web page?
尹祥龙 wrote: How can get button's name when cursor move over the button on a web page? that sounds like a JavaScript question, doesn't it? so what is it doing on comp.lang.python ? /F -- http://mail.python.org/mailman/listinfo/python-list
Re: mirroring object attributes using xml-rpc
[EMAIL PROTECTED] wrote: Then the client code can get the value of i like this: c = xmlrpclib.ServerProxy(address) c.geti() but why can't I get the value of i like this? c.i you can't. the XML-RPC protocol only supports method calls, not attribute accesses. How can I implement such behaviour? you could use reflection to automatically wrap attributes on the server side; e.g. class foo: x = 10 # generic getter def __getattr__(self, key): if not key.startswith(get_): raise AttributeError value = getattr(self, key[4:]) return lambda: value f = foo() print f.x print f.get_x() /F -- http://mail.python.org/mailman/listinfo/python-list
Re: Very practical question
madpython [EMAIL PROTECTED] wrote: I've been doing an application with Tkinter widgets. Nothing really fancy just routine stuff. Though I have no problems with it by now I guess it would be reasonable to ask about a thing that's been bothering me a bit. Look at this piece of code: class A(object): def a(self): return a from A class B(object): def interClassCall(self): print globals()['c'].__dict__['a'].a() The others have given you good advice about better ways to do this, but I'd like to point out that this one line is equivalent to: print c.a.a() -- - Tim Roberts, [EMAIL PROTECTED] Providenza Boekelheide, Inc. -- http://mail.python.org/mailman/listinfo/python-list
Re: Error type for shelve.open()
I tried what you said and it looked like maybe AttributeError, but that didn't work either. This code snippet: import shelve from traceback import format_exc try: db = shelve.open(meh, r) except: print format_exc() Gave me this output: Traceback (most recent call last): File test.py, line 5, in ? db = shelve.open(meh, r) File /usr/lib/python2.4/shelve.py, line 231, in open return DbfilenameShelf(filename, flag, protocol, writeback, binary) File /usr/lib/python2.4/shelve.py, line 212, in __init__ Shelf.__init__(self, anydbm.open(filename, flag), protocol, writeback, binary) File /usr/lib/python2.4/anydbm.py, line 77, in open raise error, need 'c' or 'n' flag to open new db error: need 'c' or 'n' flag to open new db Exception exceptions.AttributeError: DbfilenameShelf instance has no attribute 'writeback' in ignored Do you know what the error is? Thanks, Martin Simon Forman wrote: [EMAIL PROTECTED] wrote: I wanted to write the following code: import shelve try: db = shelve.open(file, r) except SomeError: print Oh no, db not found Only, I'm not sure what SomeError should be. I tried error, anydbm.error, shelve.open.anydb.error, etc. but can't find it. Things worked fine with simply except:, but that's not optimal. Does anyone know either the what the error is or where I can find it for certain? Thanks, Martin What error did you get with just the bare except? you can find out by saying (for instance): try: 1/0 except Exception, err: E = err E exceptions.ZeroDivisionError instance at 0xb6efd8cc or to get really fancy, use the traceback module from traceback import format_exc try: 1/0 except: print format_exc() Traceback (most recent call last): File pyshell#10, line 2, in ? ZeroDivisionError: integer division or modulo by zero Peace, ~Simon -- http://mail.python.org/mailman/listinfo/python-list
Re: mirroring object attributes using xml-rpc
[EMAIL PROTECTED] wrote: but why can't I get the value of i like this? c.i How can I implement such behaviour? Not supported by XMLRpc. Switch to Pyro: http://pyro.sourceforge.net --Irmen -- http://mail.python.org/mailman/listinfo/python-list
Re: Very practical question
madpython wrote: Here is a short illustration: ... self.b=Tkinter.Button(root,txt=Button,command=self.doSmth).pack() self.l=Tkinter.Label(root,txt=default).pack() def doSmth(self): var=globals()[m].__dict__[progLogic].func(some input) self.l.config(txt=var) self.l.update_idletasks() ... I guess it's all correct or at least it close to what I work on. What do you think? what makes you think that var=globals()[m].__dict__[progLogic].func(some input) is, in any way, different from (and superior to) var = m.progLogic.func(some input) ? If I may I'd say it again that GUI is built according by the data that's passed by the thinking part of the program so I don't necessary know what it is (can only guess) and that's why passing references as an argument doesn't seem possible. sorry, but you make no sense at all. solving this is not a hard pro- blem, and the solution doesn't need to involve global variables. and even if you prefer globals, there's no need to write ludicrous code. /F -- http://mail.python.org/mailman/listinfo/python-list
Re: How to trap the event of a new process starting with wmi
gel wrote: gel wrote: Below is how it is down with vbscript. What is the best way to convert this to python? strComputer = . Set objWMIService = GetObject(winmgmts: _ {impersonationLevel=impersonate}!\\ strComputer \root\cimv2) Set colMonitoredProcesses = objWMIService. _ ExecNotificationQuery(select * from __instancecreationevent _ within 1 where TargetInstance isa 'Win32_Process') i = 0 Do While i = 0 Set objLatestProcess = colMonitoredProcesses.NextEvent Wscript.Echo objLatestProcess.TargetInstance.Name Loop A better question might be is there a method or guide for converting from vbs wmi to python wmi? Dont know about converting vbs to python but using Tim Golden's wmi module to trap the event of a new process starting is easy. wmi module can be found at http://timgolden.me.uk/python/wmi.html import wmi c = wmi.WMI() watcher = c.watch_for ( notification_type=Creation wmi_class=Win32_Process delay_secs=2, Name='calc.exe' ) calc_created = watcher () print calc_created and if you want to trap closing down of processes then change notification_type to Deletion -Cheers -- http://mail.python.org/mailman/listinfo/python-list
Re: Nested scopes, and augmented assignment
On 2006-07-05, Fredrik Lundh [EMAIL PROTECTED] wrote: Antoon Pardon wrote: Python could have chosen an approach with a nested keyword sure, and Python could also have been invented by aliens, powered by space potatoes, and been illegal to inhale in Belgium. At one time one could have reacted the same when people suggested python could use a ternary operator. In the mean time a ternary operator is in the pipeline. If you don't want to discuss how python could be different with me, that is fine, but I do no harm discussing such things with others. have any of your my mental model of how Python works is more important than how it actually works ever had a point ? Be free to correct me. But just suggesting that I'm wrong doesn't help me in changing my mental model. -- Antoon Pardon -- http://mail.python.org/mailman/listinfo/python-list
Re: Installation of python on my workspace.
[EMAIL PROTECTED] wrote: I had two questions. I am new to Unix and Python. I wanted to get python installed on my unix terminal without too much interference from the administrator. How can I do this? If you have the Python sources, you can configure it to install where you tell it using the --prefix option. E.g. ./configure --prefix=$(HOME) will install it in your login dir, so you'd run python using $(HOME)/bin/python. No sysadmin required. Glenn -- 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: RegEx conditional search and replace
Juho Schultz [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Martin Evans wrote: Sorry, yet another REGEX question. I've been struggling with trying to get a regular expression to do the following example in Python: Search and replace all instances of sleeping with dead. This parrot is sleeping. Really, it is sleeping. to This parrot is dead. Really, it is dead. But not if part of a link or inside a link: This parrot a href=sleeping.htm target=newis sleeping/a. Really, it is sleeping. to This parrot a href=sleeping.htm target=newis sleeping/a. Really, it is dead. This is the full extent of the html that would be seen in the text, the rest of the page has already been processed. Luckily I can rely on the formating always being consistent with the above example (the url will normally by much longer in reality though). There may though be more than one link present. I'm hoping to use this to implement the automatic addition of links to other areas of a website based on keywords found in the text. I'm guessing this is a bit too much to ask for regex. If this is the case, I'll add some more manual Python parsing to the string, but was hoping to use it to learn more about regex. Any pointers would be appreciated. Martin What you want is: re.sub(regex, replacement, instring) The replacement can be a function. So use a function. def sleeping_to_dead(inmatch): instr = inmatch.group(0) if needsfixing(instr): return instr.replace('sleeping','dead') else: return instr as for the regex, something like (a)?[^]*(/a)? could be a start. It is probaly better to use the regex to recognize the links as you might have something like sleeping.sleeping/sleeping/sleeping.html in your urls. Also you probably want to do many fixes, so you can put them all within the same replacer function. Many thanks for that, the function method looks very useful. My first working attempt had been to use the regex to locate all links. I then looped through replacing each with a numbered dummy entry. Then safely do the find/replaces and then replace the dummy entries with the original links. It just seems overly inefficient. -- http://mail.python.org/mailman/listinfo/python-list
Tkinter and dialogs
I'm trying unsuccessfully to do something in Tk that I though would be easy. After Googling this all day, I think I need some help. I am admittedly very novice with Tk (I started with it yesterday), so I am sure I am overlooking something simple. The basic idea is that my application will consist of a series of modal dialogs, that are chained together in wizard fashion. There will be some processing in between dialogs, but for the most part, the user will do some interaction with each dialog and then click Next or Previous. My thinking was that the main (root) Tk window would be hidden and that each dialog would be modal and child to that hidden window. Is this a reasonable way to do this in Tkinter? I grabbed the Dialog class from effbot's site figuring that was good starting point. I did modify it somewhat to convert to the grid layout manager, based on advice in the New Mexico Tech Tkinter Reference (by John Shipman). When I run this (Ubuntu 6.06), I get no windows, not even the root Tk one. Any ideas??? Thanks, Don #!/usr/bin/env python from Tkinter import * root = None class Dialog(Toplevel): def __init__(self, parent, title = None): Toplevel.__init__(self, parent) self.transient(parent) if title: self.title(title) print repr(parent) self.parent = parent self.result = None #body = Frame(self) #self.initial_focus = self.body(body) #body.pack(padx=5, pady=5) self.initial_focus = self.body(self) self.buttonbox() self.bind(Return, self.ok) self.bind(Escape, self.cancel) self.grab_set() if not self.initial_focus: self.initial_focus = self self.protocol(WM_DELETE_WINDOW, self.cancel) self.geometry(+%d+%d % (parent.winfo_rootx()+50, parent.winfo_rooty()+50)) self.initial_focus.focus_set() self.wait_window(self) # # construction hooks def body(self, master): # create dialog body. return widget that should have # initial focus. this method should be overridden pass def buttonbox(self): # add standard button box. override if you don't want the # standard buttons box = Frame(self) w = Button(box, text=OK, width=10, command=self.ok, default=ACTIVE) w.pack(side=LEFT, padx=5, pady=5) w = Button(box, text=Cancel, width=10, command=self.cancel) w.pack(side=LEFT, padx=5, pady=5) self.bind(Return, self.ok) self.bind(Escape, self.cancel) box.pack() # # standard button semantics def ok(self, event=None): if not self.validate(): self.initial_focus.focus_set() # put focus back return self.withdraw() self.update_idletasks() self.apply() self.cancel() def cancel(self, event=None): # put focus back to the parent window self.parent.focus_set() self.destroy() # # command hooks def validate(self): print validate return True # override def apply(self): print apply pass # override class WelcomeDialog(Dialog): def body(self, master): Label(master, text=First:).grid(row=0, sticky=W) Label(master, text=Second:).grid(row=1, sticky=W) self.e1 = Entry(master) self.e2 = Entry(master) self.e1.grid(row=0, column=1) self.e2.grid(row=1, column=1) self.cb = Checkbutton(master, text=Hardcopy) self.cb.grid(row=2, columnspan=2, sticky=W) self.w1 = Button(master, text=OK, width=10, command=self.ok, default=ACTIVE) #w.pack(side=LEFT, padx=5, pady=5) self.w1.grid(row=3, column=0) self.w2 = Button(master, text=Cancel, width=10, command=self.cancel) #w.pack(side=LEFT, padx=5, pady=5) self.w2.grid(row=3, column=1) def apply(self): print apply first = int(self.e1.get()) second = int(self.e2.get()) self.result = first, second def buttonbox(self): pass def show_ui(): welcome = WelcomeDialog(root, test1) global root root = Tk() root.after_idle(show_ui) root.mainloop() -- http://mail.python.org/mailman/listinfo/python-list
Re: XML-RPC server-client communication
server = SimpleXMLRPCServer.SimpleXMLRPCServer((xxx.xxx.xxx.xxx, 22999)) Could it be that xxx.xxx.xxx.xxx stands for '127.0.0.1'? If so... rename it to 'localhost'. If you bind a port to 127.0.0.1 it will be found only on the same machine. Greetings, Marco -- http://mail.python.org/mailman/listinfo/python-list
Re: Generating multiple lists from one list
Girish Sahani wrote: 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?? I don't understand what you mean by 'a','b','c' are objects and 1,3,4,2 are their instance ids, but I think the solution to whatever your problem is, will involve the Cartesian Product of sets (lists) - (also called the cross product). If your data is just the strings that you give in your example, then the following should work. If your 'object strings' are longer than one character, you will have to adapt it. print import itertools as it data1 = ['a.1','b.3','b.4','c.2'] data2 = ['a.1','b.3','b.4','c.2','c.6','d.3'] want1 = [['a.1', 'b.3', 'c.2'], ['a.1', 'b.4', 'c.2']] want2 = [['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'] ] def split_data(data): ret = [] for k, g in it.groupby(sorted(data), lambda x: x[0]): ret.append( list(g) ) return ret #following function from ASPN Cookbook by David Klaffenbach #http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/302478 def combine(*seqin): '''returns a list of all combinations of argument sequences. for example: combine((1,2),(3,4)) returns [[1, 3], [1, 4], [2, 3], [2, 4]]''' def rloop(seqin,listout,comb): '''recursive looping function''' if seqin: # any more sequences to process? for item in seqin[0]: newcomb=comb+[item] # add next item to current comb # call rloop w/ rem seqs, newcomb rloop(seqin[1:],listout,newcomb) else: # processing last sequence listout.append(comb)# comb finished, add to list listout=[] # listout initialization rloop(seqin,listout,[]) # start recursive process return listout assert combine(*split_data(data1)) == want1 assert combine(*split_data(data2)) == want2 Gerard -- http://mail.python.org/mailman/listinfo/python-list
About a month until PSF call for test trackers closes!
Back at the beginning of June, the Python Software Foundation's Infrastructure committee sent out an email requesting people to help us find a replacement tracker for SourceForge (the original announcement can be found at http://wiki.python.org/moin/CallForTrackers ). We asked that people put test trackers loaded with a data dump of Python's SourceForge tracker data online for us to play with. We said that we would close acceptance of test trackers as of August 7. That close date is a little over a month away! If you want to help get your favorite tracker up and going for the Infrastructure committee to evaluate, please visit http://wiki.python.org/moin/CallForTrackers and see if you can help out! We already have a tracker for JIRA up and loaded with the SF data to poke around with. There are also Trac and Roundup trackers in the planning stages that could use some help in getting the SF data imported and getting the servers up. In order for a tracker to be considered it *must* have the SF data loaded up. This will be a necessary step if the tracker is accepted, plus it lets us see how well the tracker lets us manage a large number of bugs. If you have questions or concerns, please email infrastructure at python.org (it is subscription-protected, but your email will be accepted; the subscription page is at http://mail.python.org/mailman/listinfo/infrastructure ). Thank you to those that have helped so far and those that do in the future.-Brett CannonChairman, PSF Infrastructure Committee -- http://mail.python.org/mailman/listinfo/python-list
Re: Tkinter and dialogs
dwelch91 wrote: I get no windows, not even the root Tk one. no time to dig deeper into this right now, but the culprit is probably a combination of this line self.transient(parent) and the after_idle approach to create the Dialog (Toplevel) window. the transient call tells Tkinter to make the new dialogue window dependent on the parent (which is the root Tk window in this case), but that window hasn't been created yet when you get to transient, so Tk ends up waiting for something that obviously never happens... as a workaround, you can either remove the transient call, or insert an explicit root.update() before the root.after_idle() call. root = None global root root = Tk() unrelated to your question: global is used in a local scope (a function or method) to indicate that a variable that you assign to is a global variable. for the full story, see http://pyref.infogami.com/naming-and-binding /F -- http://mail.python.org/mailman/listinfo/python-list
Need Billy the Kid modul for windows
Hey, There is a nice modul called BtK at http://home.student.utwente.nl/g.v.berg/btk/ Has someone a link for btk-python on windows? Thx, Spooky -- http://mail.python.org/mailman/listinfo/python-list
Re: Tkinter and dialogs
In [EMAIL PROTECTED], dwelch91 wrote: When I run this (Ubuntu 6.06), I get no windows, not even the root Tk one. Any ideas??? […] global root root = Tk() root.after_idle(show_ui) root.mainloop() What is this `after_idle()` call supposed to do? The main loop isn't running yet. If you just call `show_ui()` you should get some windows. The ``global`` is unnecessary by the way. It even generates a warning: test.py:0: SyntaxWarning: name 'root' is assigned to before global declaration Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: How to trap the event of a new process starting with wmi
placid wrote: gel wrote: gel wrote: Below is how it is down with vbscript. What is the best way to convert this to python? strComputer = . Set objWMIService = GetObject(winmgmts: _ {impersonationLevel=impersonate}!\\ strComputer \root\cimv2) Set colMonitoredProcesses = objWMIService. _ ExecNotificationQuery(select * from __instancecreationevent _ within 1 where TargetInstance isa 'Win32_Process') i = 0 Do While i = 0 Set objLatestProcess = colMonitoredProcesses.NextEvent Wscript.Echo objLatestProcess.TargetInstance.Name Loop A better question might be is there a method or guide for converting from vbs wmi to python wmi? Dont know about converting vbs to python but using Tim Golden's wmi module to trap the event of a new process starting is easy. wmi module can be found at http://timgolden.me.uk/python/wmi.html import wmi c = wmi.WMI() watcher = c.watch_for ( notification_type=Creation wmi_class=Win32_Process delay_secs=2, Name='calc.exe' ) calc_created = watcher () print calc_created and if you want to trap closing down of processes then change notification_type to Deletion -Cheers Great, thanks for that, where did you find details on using it. I am already using it for another part, but could not find information on watching processes start and stop. -- 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
Re: Perl Dictionary Convert
In [EMAIL PROTECTED], Tom Grove wrote: I have a server program that I am writing an interface to and it returns data in a perl dictionary. Is there a nice way to convert this to something useful in Python? You could write a little parser with pyparsing: source = \ { Calendar = { Access = { anyone = lr;}; Class = IPF.Appointment; Messages = 0; Size = 0; UIDNext = 1; UIDValidity = 287898056; Unseen = 0; }; Contacts = { Class = IPF.Contact; Messages = 0; Size = 0; UIDNext = 1; UIDValidity = 287898056; Unseen = 0; }; } from pyparsing import alphas, alphanums, nums, Dict, Forward, Group, \ Literal, OneOrMore, Suppress, Word OPEN_BRACE = Suppress('{') CLOSE_BRACE = Suppress('}') ASSIGN = Suppress('=') STATEMENT_END = Suppress(';') identifier = Word(alphas, alphanums + '.') number = Word(nums).setParseAction(lambda s, loc, toks: int(toks[0])) dictionary = Forward() value = identifier | number | dictionary item = Group(identifier + ASSIGN + value + STATEMENT_END) dictionary Dict(OPEN_BRACE + OneOrMore(item) + CLOSE_BRACE) result = dictionary.parseString(source) print result['Contacts']['Class'] Output is: IPF.Contact Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Is there a Python __LINE__ ?
Hi, is there a Python aquivalent to the C __LINE__? Thank you in advance Regards Rolf -- http://mail.python.org/mailman/listinfo/python-list
Re: use var to form name of object
In [EMAIL PROTECTED], gel wrote: Yeah I am still getting my head around things... not exactly sure what you where saying about the globals, but this works global k k = 5 class foo: def wow(self, n): global k k += n return k f=foo() f.wow(55) The first ``global`` does nothing. ``global`` at module level makes no sense. And the snippet could be easily written without assigning to global names from within a function/method: k = 5 class Foo: def wow(self, n): return k + n f = Foo() k = f.wow(55) Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Nested scopes, and augmented assignment
On 2006-07-05, Piet van Oostrum [EMAIL PROTECTED] wrote: Antoon Pardon [EMAIL PROTECTED] (AP) wrote: AP On 2006-07-05, Bruno Desthuilliers [EMAIL PROTECTED] wrote: Antoon Pardon wrote: (snip) Well no matter what explanation you give to it, and I understand how it works, I'm not sure of this. AP Should I care about that? Yes, because as long as you don't understand it, you are in for unpleasant surprises. Well if someone explains what is wrong about my understanding, I certainly care about that (although I confess to sometimes being impatient) but someone just stating he is not sure I understand? It's not about finding a name/identifier, it's about the difference between (re)binding a name and mutating an object. AP The two don't contradict each other. Python has chosen that it won't AP rebind variables that are out of the local scope. So if the lefthand AP side of an assignment is a simple name it will only search in the AP local scope for that name. But if the lefthand side is more complicated AP if will also search the outerscopes for the name. No. It will always use the same search order. So if I understand you correctly in code like: c.d = a b = a All three names are searched for in all scopes between the local en global one. That is what I understand with your statement that [python] always uses the same search order. My impression was that python will search for c and a in the total current namespace but will not for b. But a variable that is bound inside the function (with an asignment) and is not declared global, is in the local namespace. Aren't we now talking about implementation details? Sure the compilor can set things up so that local names are bound to the local scope and so the same code can be used. But it seems somewhere was made the decision that b was in the local scope without looking for that b in the scopes higher up. Let me explain a bit more. Suppose I'm writing a python interpreter in python. One implemantation detail is that I have a list of active scopes which are directories which map names to objects. At the start of a new function the scope list is adapted and all local variables are inserted to the new activated scope and mapped to some Illegal Value object. Now I also have a SearchName function that will start at the begin of a scope list and return the first scope in which that name exists. The [0] element is the local scope. Now we come to the line b = a This could be then executed internally as follows: LeftScope = SearchName(b, ScopeList) RightScope = SearchName(a, ScopeList) LeftScope[b] = RightScope[a] But I don't have to do it this way. I already know in which scope b is, the local one, which has index 0. So I could just as well have that line exucuted as follows: LeftScope = ScopeList[0] RightScope = SearchName(a, ScopeList) LeftScope[b] = RightScope[a] As far as I understand both implementations would make for a correct execution of the line b = a and because of the second possibility, b is IMO not conceptually searched for in the same way as a is searched for, although one could organise things that the same code is used for both. Of course it is possible I completely misunderstood how python is supposed to work and the above is nonesense in which case I would appreciate it if you correct me. AP Python could have chosen an approach with a nested keyword, to allow AP rebinding a name in an intermediate scope. It is not that big a deal AP that it hasn't, but I keep finding the result strange and somewhat AP counterintuitive. Maybe it would have been nice if variables could have been declared as nested, but I think it shows that nested variables have to be used with care, similar to globals. Especially not allowing rebinding in intermediate scopes is a sound principle (`Nested variables considered harmful'). If you need to modify the objects which are bound to names in intermediate scopes, use methods and give these objects as parameters. But shouldn't we just do programming in general with care? And if Nested variables are harmfull, what is then the big difference between rebinding them and mutating them that we should forbid the first and allow the second? I understand that python evolved and that this sometimes results in things that in hindsight could have been done better. But I sometimes have the impression that the defenders try to defend those results as a design decision. With your remark above I have to wonder if someone really thought this through at design time and came to the conclusion that nested variables are harmfull and thus may not be rebound but not that harmfull so mutation is allowed and if so how he came to that conclusion. AP Let me explain why: AP Suppose someone is rather new of python and writes the following AP code, manipulating vectors: AP A = 10 * [0] AP def f(B): AP ... AP for i in xrange(10): AP A[i] += B[i] AP ... AP Then he hears about the
Re: Is there a Python __LINE__ ?
Hi, is there a Python aquivalent to the C __LINE__? Thank you in advance Google says: http://www.nedbatchelder.com/blog/200410.html#e20041003T074926 -- http://mail.python.org/mailman/listinfo/python-list
Re: Is there a Python __LINE__ ?
Rolf Wester [EMAIL PROTECTED] wrote: is there a Python aquivalent to the C __LINE__? I found this in the archives: http://groups.google.it/group/comp.lang.python/browse_thread/thread/315e f9451067a320/87785edf569c1e96?q=current+linernum=2#87785edf569c1e96 -- Lawrence - http://www.oluyede.org/blog Nothing is more dangerous than an idea if it's the only one you have - E. A. Chartier -- http://mail.python.org/mailman/listinfo/python-list
numpy : argmin in multidimensional arrays
Hi there. I am working with multi-dimensional arrays and I need to get coordinates of the min value in it. using myarray.argmin() returns the index in the flatten array, which is a first step, but I wonder if it is possible to get the coordinates directly as an array, rather than calculating them myself by using this flat index and the shape of the array. well, in fact i'm not sure to understand how argmin(myarray) works, when myarray is multidimensional. Thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: converting file formats to txt
On 4 Jul 2006 08:38:47 -0700, Gaurav Agarwal [EMAIL PROTECTED] wrote: Thanks Steven, Actually i wanted a do text processing for my office where I can view all files in the system and use the first three to give a summary of the document. Instead of having somebody actually entering the summary. Seems there is no one code that can act as convertor across formats, i'll have to check out convertors for individual formats. I have some old code that does just that. It uses pdftotext, catdoc and links to convert .doc, .pdf and .html to text. ## import mimetypes from subprocess import call, Popen, PIPE import sys class ConversionError(Exception): pass class UnknownMimeType(ConversionError): pass class NotAMimeType(ConversionError): pass class ParseError(ConversionError): pass def has_program(progname): return call([which, progname], stdout = PIPE) == 0 def check_requirements(): missing = [] for prog in catdoc, pdftotext, links: if not has_program(prog): missing.append(prog) if missing: print You need to have the programs:, .join(missing) return False return True if not check_requirements(): print Needed external programs not found, quitting sys.exit(1) def get_catdoc_args(infile): return [catdoc, -s, 8859-1, infile] def get_pdftotext_args(infile): return [pdftotext, infile, -] def get_links_args(infile): return [links, infile, -dump] def totext(document): filetype_to_args_map = {application/msword : get_catdoc_args, application/pdf : get_pdftotext_args, text/html : get_links_args} ftype, ign = mimetypes.guess_type(document) if not ftype: raise NotAMimeType, Couldn't detect mimetype for %s % document try: argfunc = filetype_to_args_map[ftype] except KeyError: s = Don't know how to handle %s documents % ftype raise UnknownMimeType, s p = Popen(argfunc(document), stdout = PIPE, stderr = PIPE) text = p.stdout.read() if p.wait(): # Force a better exception to be thrown if the file doesn't exist. open(document) raise ParseError, Failed to parse %s % document return text if __name__ == __main__: print totext(testpdf.pdf) -- mvh Björn -- http://mail.python.org/mailman/listinfo/python-list
Re: Finding Return Code From GPG
* Dennis Benzinger [EMAIL PROTECTED]: Nomen Nescio wrote: I'm running gpg in python to verify a signature. But I need a way to let the python script know this. I have written a script to verify signatures using gpg some time ago, maybe this helps you: http://old.homeip.net/martin/sigcheck/ bye Martin -- http://mail.python.org/mailman/listinfo/python-list
eval to dict problems NEWB going crazy !
Hi, I have a text file called a.txt: # comments [('recId', 3), ('parse', {'pos': u'np', 'gen': u'm'})] [('recId', 5), ('parse', {'pos': u'np', 'gen': u'm'})] [('recId', 7 ), ('parse', {'pos': u'np', 'gen': u'm'})] I read it using this: filAnsMorph = codecs.open('a.txt', 'r', 'utf-8') # Initialise input file dicAnsMorph = {} for line in filAnsMorph: if line[0] != '#': # Get rid of comment lines x = eval(line) dicAnsMorph[x[0][1]] = x[1][1] # recid is key, parse dict is value But it crashes every time on x = eval(line). Why is this? If I change a.txt to: # comments [('recId', 3), ('parse', {'pos': u'np', 'gen': u'm'})] it works fine. Why doesn't it work with multiple lines? it's driving me crazy! Thanks, Matthew -- http://mail.python.org/mailman/listinfo/python-list
Re: How to trap the event of a new process starting with wmi
gel wrote: placid wrote: gel wrote: gel wrote: Below is how it is down with vbscript. What is the best way to convert this to python? strComputer = . Set objWMIService = GetObject(winmgmts: _ {impersonationLevel=impersonate}!\\ strComputer \root\cimv2) Set colMonitoredProcesses = objWMIService. _ ExecNotificationQuery(select * from __instancecreationevent _ within 1 where TargetInstance isa 'Win32_Process') i = 0 Do While i = 0 Set objLatestProcess = colMonitoredProcesses.NextEvent Wscript.Echo objLatestProcess.TargetInstance.Name Loop A better question might be is there a method or guide for converting from vbs wmi to python wmi? Dont know about converting vbs to python but using Tim Golden's wmi module to trap the event of a new process starting is easy. wmi module can be found at http://timgolden.me.uk/python/wmi.html import wmi c = wmi.WMI() watcher = c.watch_for ( notification_type=Creation wmi_class=Win32_Process delay_secs=2, Name='calc.exe' ) calc_created = watcher () print calc_created and if you want to trap closing down of processes then change notification_type to Deletion -Cheers Great, thanks for that, where did you find details on using it. I am already using it for another part, but could not find information on watching processes start and stop. c=wmi.WMI() help(c) ive been using the wmi module for 1.5 months and i had some help from the author of the module (Tim Golden). -- http://mail.python.org/mailman/listinfo/python-list
looping question 4 NEWB
Hi, I often have code like this: data='asdfbasdf' find = (('a','f')('s','g'),('x','y')) for i in find: if i[0] in data: data = data.replace(i[0],i[1]) is there a faster way of implementing this? Also, does the if clause increase the speed? Thanks, Matthew -- http://mail.python.org/mailman/listinfo/python-list
Re: Nested scopes, and augmented assignment
Antoon Pardon wrote: On 2006-07-05, Piet van Oostrum [EMAIL PROTECTED] wrote: Antoon Pardon [EMAIL PROTECTED] (AP) wrote: AP On 2006-07-05, Bruno Desthuilliers [EMAIL PROTECTED] wrote: Antoon Pardon wrote: (snip) Well no matter what explanation you give to it, and I understand how it works, I'm not sure of this. AP Should I care about that? Yes, because as long as you don't understand it, you are in for unpleasant surprises. Well if someone explains what is wrong about my understanding, I certainly care about that (although I confess to sometimes being impatient) but someone just stating he is not sure I understand? From what you wrote, I cannot decide if you really understand Python's lookup rules and poorly express some disagreement on it, or if you just don't understand Python lookup rules at all. It's not about finding a name/identifier, it's about the difference between (re)binding a name and mutating an object. AP The two don't contradict each other. Python has chosen that it won't AP rebind variables that are out of the local scope. So if the lefthand AP side of an assignment is a simple name it will only search in the AP local scope for that name. But if the lefthand side is more complicated AP if will also search the outerscopes for the name. Now it's pretty clear you *don't* understand. In the second case, ie: k = [0] def f(i): k[0] += i 'k[0]' is *not* a name. The name is 'k'. If we rewrite this snippet without all the syntactic sugar, we get something like: k = [0] def f(i): k.__setitem_(0, k.__getitem__(0) + i) Now where do you see any rebinding here ? No. It will always use the same search order. So if I understand you correctly in code like: c.d = a b = a All three names which ones ? are searched for in all scopes between the local en global one. In this example, we're at the top level, so the local scope is the global scope. I assert what you meant was: c = something a = something_else def somefunc(): c.d = a b = a (NB : following observations will refer to this code) That is what I understand with your statement that [python] always uses the same search order. yes. My impression was that python will search for c and a in the total current namespace what is the total current namespace ? but will not for b. b is bound in the local namespace, so there's no need to look for it in enclosing namespaces. But a variable that is bound inside the function (with an asignment) and is not declared global, is in the local namespace. Aren't we now talking about implementation details? Certainly not. Namespaces and names lookup rules are fundamental parts of the Python language. Sure the compilor can set things up so that local names are bound to the local scope and so the same code can be used. But it seems somewhere was made the decision that b was in the local scope without looking for that b in the scopes higher up. binding creates a name in the current namespace. b is bound in the local namespace, so b is local. period. (snip) -- bruno desthuilliers python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')]) -- http://mail.python.org/mailman/listinfo/python-list
I thought I'd 'got' globals but...
I thought I had 'got' globals but this one seems strange. I want my example function 'doIt' to use and optionally modify a module variable 'gname', so I declare 'global gname' in the function, but when modified it doesn't stay modified. gname = 'Sue' def doIt(name = gname): global gname gname = name print 'doIt name', name, 'gname', gname print 'start gname', gname doIt() doIt(name='Lisa') doIt() print 'finish gname', gname gives... start gname Sue doIt name Sue gname Sue doIt name Lisa gname Lisa doIt name Sue gname Sue finish gname Sue The variable gname has reverted back to value 'Sue' Curiously though, without the third doIt() call, it works... print 'start gname', gname doIt() doIt(name='Lisa') #doIt() print 'finish gname', gname gives... start gname Sue doIt name Sue gname Sue doIt name Lisa gname Lisa finish gname Lisa The variable gname has been modified to 'Lisa' Any ideas how I can make the 'Lisa' assignment permanent forever in 2nd doIt? Thanks (Note. Contrived example substitutes for a web-type app, where, if the page is called without arguments then it displays the global defaults. If the page is called with form arguments then it should be able to change the global defaults) -- http://mail.python.org/mailman/listinfo/python-list
rare error with python at execution
I was trying the win32api to gather some system information. But now I get this error everytime I run a script and I have no idea. It can be a simple print hello that it wont work This is the error I get 'import site' failed; use -v for traceback Traceback (most recent call last): File D:\Archivos de programa\ActiveState Komodo 3.5\lib\support\dbgp\bin\pydbgp.py, line 61, in ? if os.environ.has_key(PYDBGP_PATH): AttributeError: 'module' object has no attribute 'environ' -- http://mail.python.org/mailman/listinfo/python-list
Re: I thought I'd 'got' globals but...
meridian wrote: I thought I had 'got' globals but this one seems strange. I want my example function 'doIt' to use and optionally modify a module variable 'gname', so I declare 'global gname' in the function, but when modified it doesn't stay modified. gname = 'Sue' def doIt(name = gname): This is a FAQ, cf: http://www.python.org/doc/faq/general/#why-are-default-values-shared-between-objects Briefly : default args are eval'd only once at load/import time. Any ideas how I can make the 'Lisa' assignment permanent forever in 2nd doIt? Thanks def doIt(name=None): global gname if name is None: name = gname else: gname = name (Note. Contrived example substitutes for a web-type app, where, if the page is called without arguments then it displays the global defaults. If the page is called with form arguments then it should be able to change the global defaults) Modifying globals from within a function is usually a very bad idea. -- bruno desthuilliers python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')]) -- http://mail.python.org/mailman/listinfo/python-list
Re: numpy : argmin in multidimensional arrays
TG wrote: Hi there. I am working with multi-dimensional arrays and I need to get coordinates of the min value in it. using myarray.argmin() returns the index in the flatten array, which is a first step, but I wonder if it is possible to get the coordinates directly as an array, rather than calculating them myself by using this flat index and the shape of the array. well, in fact i'm not sure to understand how argmin(myarray) works, when myarray is multidimensional. By default, the argmin method flattens the array and returns the flat index. You can get the corresponding element using myarray.flat[index] Alternatively, you can use the function unravel_index unravel_index(flat_index, myarray.shape) to return an N-dimensional index. If you give an axis argument, then the minimum is found along the specified dimension and you get an N-1 dimensional array of indices that will all be between 1 and myarray.shape[axis] -Travis -- http://mail.python.org/mailman/listinfo/python-list
Re: eval to dict problems NEWB going crazy !
manstey wrote: Hi, I have a text file called a.txt: # comments [('recId', 3), ('parse', {'pos': u'np', 'gen': u'm'})] [('recId', 5), ('parse', {'pos': u'np', 'gen': u'm'})] [('recId', 7 ), ('parse', {'pos': u'np', 'gen': u'm'})] I read it using this: filAnsMorph = codecs.open('a.txt', 'r', 'utf-8') # Initialise input file dicAnsMorph = {} for line in filAnsMorph: if line[0] != '#': # Get rid of comment lines x = eval(line) dicAnsMorph[x[0][1]] = x[1][1] # recid is key, parse dict is value But it crashes every time on x = eval(line). Why is this? If I change a.txt to: # comments [('recId', 3), ('parse', {'pos': u'np', 'gen': u'm'})] it works fine. Why doesn't it work with multiple lines? it's driving me crazy! try with: x = eval(line.strip('\n')) -- bruno desthuilliers python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')]) -- http://mail.python.org/mailman/listinfo/python-list
Re: looping question 4 NEWB
manstey schreef: Hi, I often have code like this: data='asdfbasdf' find = (('a','f')('s','g'),('x','y')) for i in find: if i[0] in data: data = data.replace(i[0],i[1]) is there a faster way of implementing this? Also, does the if clause increase the speed? I think this is best done with translate() and string.maketrans() (see http://docs.python.org/lib/node110.html#l2h-835 and http://docs.python.org/lib/string-methods.html#l2h-208). An example: import string data = 'asdfbasdf' translatetable = string.maketrans('asx', 'fgy') data = data.translate(translatetable) print data This results in: fgdfbfgdf -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven -- http://mail.python.org/mailman/listinfo/python-list
Re: looping question 4 NEWB
On 06.07.2006 12:43, manstey wrote: Hi, I often have code like this: data='asdfbasdf' find = (('a','f')('s','g'),('x','y')) for i in find: if i[0] in data: data = data.replace(i[0],i[1]) is there a faster way of implementing this? Also, does the if clause increase the speed? Thanks, Matthew import string data='asdfbasdf' data.translate(string.maketrans('asx', 'fgy')) 'fgdfbfgdf' HTH, Wolfram -- http://mail.python.org/mailman/listinfo/python-list
Re: looping question 4 NEWB
But what about substitutions like: 'ab' 'cd', 'ced' 'de', etc what is the fastest way then? Roel Schroeven wrote: manstey schreef: Hi, I often have code like this: data='asdfbasdf' find = (('a','f')('s','g'),('x','y')) for i in find: if i[0] in data: data = data.replace(i[0],i[1]) is there a faster way of implementing this? Also, does the if clause increase the speed? I think this is best done with translate() and string.maketrans() (see http://docs.python.org/lib/node110.html#l2h-835 and http://docs.python.org/lib/string-methods.html#l2h-208). An example: import string data = 'asdfbasdf' translatetable = string.maketrans('asx', 'fgy') data = data.translate(translatetable) print data This results in: fgdfbfgdf -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven -- http://mail.python.org/mailman/listinfo/python-list
Re: looping question 4 NEWB
manstey: is there a faster way of implementing this? Also, does the if clause increase the speed? I doubt the if increases the speed. The following is a bit improved version: # Original data: data = 'asdfbasdf' find = (('a', 'f'), ('s', 'g'), ('x', 'y')) # The code: data2 = data for pat,rep in find: data2 = data.replace(pat, rep) print data2 # If find contains only chars, and the string is long # enough, then this is more or less the faster solution: from string import maketrans table = map(chr, xrange(256)) for c1,c2 in find: table[ord(c1)] = c2 table_str = .join(table) print data.translate(table_str) Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list
setting variables from a tuple NEWB
Hi, If I have a tuple like this: tupGlob = (('VOWELS','aeiou'),('CONS','bcdfgh')) is it possible to write code using tupGlob that is equivalent to: VOWELS = 'aeiou' CONS = ''bcdfgh' Thanks, Matthew -- http://mail.python.org/mailman/listinfo/python-list
Re: I thought I'd 'got' globals but...
Bruno Desthuilliers wrote: def doIt(name=None): global gname if name is None: name = gname else: gname = name Thanks Bruno, works a treat... -- http://mail.python.org/mailman/listinfo/python-list
Re: eval to dict problems NEWB going crazy !
That doesn't work. I just get an error: x = eval(line.strip('\n')) File string, line 1 [('recId', 3), ('parse', {'pos': u'np', 'gen': u'm'})] SyntaxError: unexpected EOF while parsing any other ideas? Bruno Desthuilliers wrote: manstey wrote: Hi, I have a text file called a.txt: # comments [('recId', 3), ('parse', {'pos': u'np', 'gen': u'm'})] [('recId', 5), ('parse', {'pos': u'np', 'gen': u'm'})] [('recId', 7 ), ('parse', {'pos': u'np', 'gen': u'm'})] I read it using this: filAnsMorph = codecs.open('a.txt', 'r', 'utf-8') # Initialise input file dicAnsMorph = {} for line in filAnsMorph: if line[0] != '#': # Get rid of comment lines x = eval(line) dicAnsMorph[x[0][1]] = x[1][1] # recid is key, parse dict is value But it crashes every time on x = eval(line). Why is this? If I change a.txt to: # comments [('recId', 3), ('parse', {'pos': u'np', 'gen': u'm'})] it works fine. Why doesn't it work with multiple lines? it's driving me crazy! try with: x = eval(line.strip('\n')) -- bruno desthuilliers python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')]) -- http://mail.python.org/mailman/listinfo/python-list
Re: rare error with python at execution
Luis Morales wrote: But now I get this error everytime I run a script and I have no idea. It can be a simple print 'hello' that it wont work This is the error I get 'import site' failed; use -v for traceback Traceback (most recent call last): File D:\Archivos de programa\ActiveState Komodo 3.5\lib\support\dbgp\bin\pydbgp.py, line 61, in ? if os.environ.has_key(PYDBGP_PATH): AttributeError: 'module' object has no attribute 'environ' have you perhaps added a file named os.py to your project ? /F -- http://mail.python.org/mailman/listinfo/python-list
Re: eval to dict problems NEWB going crazy !
manstey wrote: That doesn't work. I just get an error: x = eval(line.strip('\n')) File string, line 1 [('recId', 3), ('parse', {'pos': u'np', 'gen': u'm'})] SyntaxError: unexpected EOF while parsing is the last line of your file empty ?? what with for line in filAnsMorph: # remove any trailing and leading whitespace includes removing \n line = line.strip() # Get rid of comment lines if line.startswith('#'): continue # Get rid of blank line if line == '': continue #do the job x = eval(line) NB by default strip() removes leading and trailing characters from the target string. with whitspace defined as whitespace = '\t\n\x0b\x0c\r ' Eric -- http://mail.python.org/mailman/listinfo/python-list
Re: I thought I'd 'got' globals but...
meridian wrote: Bruno Desthuilliers wrote: def doIt(name=None): global gname if name is None: name = gname else: gname = name Thanks Bruno, works a treat... But still very probably a bad idea. -- bruno desthuilliers python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')]) -- http://mail.python.org/mailman/listinfo/python-list
searching for strings (in a tuple) in a string
Hi, I often use: a='yy' tup=('x','yy','asd') if a in tup: ... but I can't find an equivalent code for: a='xfsdfyysd asd x' tup=('x','yy','asd') if tup in a: ... I can only do: if 'x' in a or 'yy' in a or 'asd' in a: ... but then I can't make the if clause dependent on changing value of tup. Is there a way around this? -- http://mail.python.org/mailman/listinfo/python-list
Re: eval to dict problems NEWB going crazy !
manstey [EMAIL PROTECTED] wrote: That doesn't work. I just get an error: x = eval(line.strip('\n')) File string, line 1 [('recId', 3), ('parse', {'pos': u'np', 'gen': u'm'})] SyntaxError: unexpected EOF while parsing any other ideas? hint 1: eval([('recId', 3), ('parse', {'pos': u'np', 'gen': u'm'})]\n) [('recId', 3), ('parse', {'pos': u'np', 'gen': u'm'})] eval([('recId', 3), ('parse', {'pos': u'np', 'gen': u'm'})]) [('recId', 3), ('parse', {'pos': u'np', 'gen': u'm'})] hint 2: eval() Traceback (most recent call last): File stdin, line 1, in ? File string, line 0 ^ SyntaxError: unexpected EOF while parsing eval(\n) Traceback (most recent call last): File stdin, line 1, in ? File string, line 1 ^ SyntaxError: unexpected EOF while parsing hint 3: adding a print statement *before* the offending line is often a good way to figure out why something's not working. repr() is also a useful thing: if line[0] != '#': # Get rid of comment lines print repr(line) # DEBUG: let's see what we're trying to evaluate x = eval(line) dicAnsMorph[x[0][1]] = x[1][1] # recid is key, parse dict is /F -- http://mail.python.org/mailman/listinfo/python-list
Re: numpy : argmin in multidimensional arrays
thanks. unravel_index do the trick. Travis E. Oliphant wrote: TG wrote: Hi there. I am working with multi-dimensional arrays and I need to get coordinates of the min value in it. using myarray.argmin() returns the index in the flatten array, which is a first step, but I wonder if it is possible to get the coordinates directly as an array, rather than calculating them myself by using this flat index and the shape of the array. well, in fact i'm not sure to understand how argmin(myarray) works, when myarray is multidimensional. By default, the argmin method flattens the array and returns the flat index. You can get the corresponding element using myarray.flat[index] Alternatively, you can use the function unravel_index unravel_index(flat_index, myarray.shape) to return an N-dimensional index. If you give an axis argument, then the minimum is found along the specified dimension and you get an N-1 dimensional array of indices that will all be between 1 and myarray.shape[axis] -Travis -- http://mail.python.org/mailman/listinfo/python-list
Re: searching for strings (in a tuple) in a string
You can get the matching elements with a list comprehension with something like py a='xfsdfyysd asd x' py tup=('x','yy','asd') py [x for x in tup if x in a.split()] ['x', 'asd'] Hope this helps manstey wrote: Hi, I often use: a='yy' tup=('x','yy','asd') if a in tup: ... but I can't find an equivalent code for: a='xfsdfyysd asd x' tup=('x','yy','asd') if tup in a: ... I can only do: if 'x' in a or 'yy' in a or 'asd' in a: ... but then I can't make the if clause dependent on changing value of tup. Is there a way around this? -- http://mail.python.org/mailman/listinfo/python-list
Re: searching for strings (in a tuple) in a string
manstey [EMAIL PROTECTED] wrote: but I can't find an equivalent code for: a='xfsdfyysd asd x' tup=('x','yy','asd') if tup in a: ... I can only do: if 'x' in a or 'yy' in a or 'asd' in a: ... but then I can't make the if clause dependent on changing value of tup. Is there a way around this? is the def statement broken in your Python version ? def findany(text, words): for w in words: if w in text: return True return False if findany(a, tup): ... /F -- http://mail.python.org/mailman/listinfo/python-list
Re: eval to dict problems NEWB going crazy !
manstey schreef: Hi, I have a text file called a.txt: # comments [('recId', 3), ('parse', {'pos': u'np', 'gen': u'm'})] [('recId', 5), ('parse', {'pos': u'np', 'gen': u'm'})] [('recId', 7 ), ('parse', {'pos': u'np', 'gen': u'm'})] I read it using this: filAnsMorph = codecs.open('a.txt', 'r', 'utf-8') # Initialise input file dicAnsMorph = {} for line in filAnsMorph: if line[0] != '#': # Get rid of comment lines x = eval(line) dicAnsMorph[x[0][1]] = x[1][1] # recid is key, parse dict is value But it crashes every time on x = eval(line). Why is this? If I change a.txt to: # comments [('recId', 3), ('parse', {'pos': u'np', 'gen': u'm'})] it works fine. Why doesn't it work with multiple lines? it's driving me crazy! It looks like it's because of the trailing newline. When you read a file like that, the newline at the end of each line is still in line. You can strip it e.g. with rstrip, like so: x = eval(line.rstrip('\n')) -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven -- http://mail.python.org/mailman/listinfo/python-list
Re: Is there a Python __LINE__ ?
Thank you very much for your help. Regards Rolf -- http://mail.python.org/mailman/listinfo/python-list
Re: searching for strings (in a tuple) in a string
I know I can do it this way. I wanted to know if there was another way. Fredrik Lundh wrote: manstey [EMAIL PROTECTED] wrote: but I can't find an equivalent code for: a='xfsdfyysd asd x' tup=('x','yy','asd') if tup in a: ... I can only do: if 'x' in a or 'yy' in a or 'asd' in a: ... but then I can't make the if clause dependent on changing value of tup. Is there a way around this? is the def statement broken in your Python version ? def findany(text, words): for w in words: if w in text: return True return False if findany(a, tup): ... /F -- http://mail.python.org/mailman/listinfo/python-list
Re: looping question 4 NEWB
manstey schreef: Roel Schroeven wrote: manstey schreef: I often have code like this: data='asdfbasdf' find = (('a','f')('s','g'),('x','y')) for i in find: if i[0] in data: data = data.replace(i[0],i[1]) is there a faster way of implementing this? Also, does the if clause increase the speed? I think this is best done with translate() and string.maketrans() (see http://docs.python.org/lib/node110.html#l2h-835 and http://docs.python.org/lib/string-methods.html#l2h-208). An example: But what about substitutions like: 'ab' 'cd', 'ced' 'de', etc what is the fastest way then? Ah, in that case I don't think you can do much better than you already did. But I think the if clause doesn't increase the speed; it might even decrease it. If you want to know for sure, use timeit to see what's fastest. -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven -- http://mail.python.org/mailman/listinfo/python-list
Re: eval to dict problems NEWB going crazy !
hint 1: hint 1b: eval([('recId', 3), ('parse', {'pos': u'np', 'gen': u'm'})]) [('recId', 3), ('parse', {'pos': u'np', 'gen': u'm'})] eval([('recId', 3), ('parse', {'pos': u'np', 'gen': u'm'})]\n) [('recId', 3), ('parse', {'pos': u'np', 'gen': u'm'})] eval([('recId', 3), ('parse', {'pos': u'np', 'gen': u'm'})]\r\n) Traceback (most recent call last): File stdin, line 1, in ? File string, line 1 [('recId', 3), ('parse', {'pos': u'np', 'gen': u'm'})] ^ SyntaxError: invalid syntax /F -- http://mail.python.org/mailman/listinfo/python-list
Re: RegEx conditional search and replace
import SE Editor = SE.SE ('sleeping=dead sleeping.htm== sleeping==') Editor ('This parrot a href=sleeping.htm target=newis sleeping/a. Really, it is sleeping.' 'This parrot a href=sleeping.htm target=newis sleeping/a. Really, it is dead.' Or: Editor ( (name of htm file), (name of output file) ) Usage: You make an explicit list of what you want and don't want after identifying the distinctions. I am currently trying to upload SE to the Cheese Shop which seems to be quite a procedure. So far I have only been successful uploading the description, but not the program. Gudidance welcome. In the interim I can send SE out individually by request. Regards Frederic - Original Message - From: Martin Evans [EMAIL PROTECTED] Newsgroups: comp.lang.python To: python-list@python.org Sent: Wednesday, July 05, 2006 1:34 PM Subject: RegEx conditional search and replace Sorry, yet another REGEX question. I've been struggling with trying to get a regular expression to do the following example in Python: Search and replace all instances of sleeping with dead. This parrot is sleeping. Really, it is sleeping. to This parrot is dead. Really, it is dead. But not if part of a link or inside a link: This parrot a href=sleeping.htm target=newis sleeping/a. Really, it is sleeping. to This parrot a href=sleeping.htm target=newis sleeping/a. Really, it is dead. This is the full extent of the html that would be seen in the text, the rest of the page has already been processed. Luckily I can rely on the formating always being consistent with the above example (the url will normally by much longer in reality though). There may though be more than one link present. I'm hoping to use this to implement the automatic addition of links to other areas of a website based on keywords found in the text. I'm guessing this is a bit too much to ask for regex. If this is the case, I'll add some more manual Python parsing to the string, but was hoping to use it to learn more about regex. Any pointers would be appreciated. Martin -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: searching for strings (in a tuple) in a string
manstey [EMAIL PROTECTED] wrote: I know I can do it this way. I wanted to know if there was another way. if you don't want to write Python programs, why are you using Python ? /F -- http://mail.python.org/mailman/listinfo/python-list
Re: ANN: Intro to Python course, Aug 16-18, San Francisco
w chun wrote: What: (Intense) Intro to Python When: August 16-18, 2006 Where: San Francisco (SFO/San Bruno), CA, USA Interesting! Now that you mention it, I remember wanting to organise an extensive Python course in Bornhövede, Germany. However, there's only some 16 people living in the closer area and I don't think anyone of them uses Python. Anyway, I wanted to announce it to the world so that people who expect to come close to Bornhövede any time soon can contact me on this. The cost will be somewhere near a bottle of wine per attendee to get my tongue moving. Stefan -- http://mail.python.org/mailman/listinfo/python-list
Re: RegEx conditional search and replace
On Thu, 06 Jul 2006 08:32:46 +0100, Martin Evans wrote: Juho Schultz [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Martin Evans wrote: Sorry, yet another REGEX question. I've been struggling with trying to get a regular expression to do the following example in Python: Search and replace all instances of sleeping with dead. This parrot is sleeping. Really, it is sleeping. to This parrot is dead. Really, it is dead. But not if part of a link or inside a link: This parrot a href=sleeping.htm target=newis sleeping/a. Really, it is sleeping. to This parrot a href=sleeping.htm target=newis sleeping/a. Really, it is dead. This is the full extent of the html that would be seen in the text, the rest of the page has already been processed. Luckily I can rely on the formating always being consistent with the above example (the url will normally by much longer in reality though). There may though be more than one link present. I'm hoping to use this to implement the automatic addition of links to other areas of a website based on keywords found in the text. I'm guessing this is a bit too much to ask for regex. If this is the case, I'll add some more manual Python parsing to the string, but was hoping to use it to learn more about regex. Any pointers would be appreciated. Martin What you want is: re.sub(regex, replacement, instring) The replacement can be a function. So use a function. def sleeping_to_dead(inmatch): instr = inmatch.group(0) if needsfixing(instr): return instr.replace('sleeping','dead') else: return instr as for the regex, something like (a)?[^]*(/a)? could be a start. It is probaly better to use the regex to recognize the links as you might have something like sleeping.sleeping/sleeping/sleeping.html in your urls. Also you probably want to do many fixes, so you can put them all within the same replacer function. ... My first working attempt had been to use the regex to locate all links. I then looped through replacing each with a numbered dummy entry. Then safely do the find/replaces and then replace the dummy entries with the original links. It just seems overly inefficient. Someone may have made use of multiline links: _ This parrot a href=sleeping.htm target=new is sleeping /a. Really, it is sleeping. _ In such a case you may need to make the page into one string to search if you don't want to use some complex method of tracking state with variables as you move from string to string. You'll also have to make it possible for non-printing characters to have been inserted in all sorts of ways around the '' and '' and 'a' or 'A' characters using ' *' here and there in he regex. -- http://mail.python.org/mailman/listinfo/python-list
Re: I thought I'd 'got' globals but...
Bruno Desthuilliers wrote: meridian wrote: Bruno Desthuilliers wrote: def doIt(name=None): global gname if name is None: name = gname else: gname = name Thanks Bruno, works a treat... But still very probably a bad idea. Ok, my curiosity is pique'd - is there a better way to hold my app/module globals? I must say I'd prefer not to write global var in every function, for every global var I need. Maybe there's a simpler way to structure?... by a global class or something? Cheers Steve -- http://mail.python.org/mailman/listinfo/python-list
Help Needed !!! Browsing and Selecting More Than One File
Dear All, I am trying to create a GUI, using Tkinter on Windows 2000/XP using Python 2.2. Through buttons this GUI interacts with another program and assigns argument to that program. I managed to browse a .c file and assign this file as an argument to the other program written in C/C++ Programming Language. On DOS, to run this program the following can be written: 1) program file1.c 2) program file1.c file2.c file3.c . So briefly I managed to execute this program for one file(program file1.c), but I failed to run for more than one file(program file1.c file2.c file3.c ..). After browsing for files, is there a way to select more than one file and assign those as arguments to the program that I want to execute? If my explanations are not clear enough I can send you the code I have written, or try to explain further. Best Regards, Fatih K. __ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com -- http://mail.python.org/mailman/listinfo/python-list
Re: I thought I'd 'got' globals but...
You mentioned earlier that Modifying globals from within a function is usually a very bad idea. Most of my app consists of functions or class/object functions, that's all I do in OOP. Did you mean that modifying globals from anywhere is bad? or globals are bad? or don't code using methods/functions? not sure... -- http://mail.python.org/mailman/listinfo/python-list
Re: Help Needed !!! Browsing and Selecting More Than One File
Kilicaslan Fatih schrieb: Dear All, I am trying to create a GUI, using Tkinter on Windows 2000/XP using Python 2.2. Through buttons this GUI interacts with another program and assigns argument to that program. I managed to browse a .c file and assign this file as an argument to the other program written in C/C++ Programming Language. On DOS, to run this program the following can be written: 1) program file1.c 2) program file1.c file2.c file3.c . So briefly I managed to execute this program for one file(program file1.c), but I failed to run for more than one file(program file1.c file2.c file3.c ..). What does failure mean? Didn't it work at all, did it only take the first file as argument, did you machine explode? Without a proper explanation of what and especially how this fails there is no chance answering your question. Diez -- http://mail.python.org/mailman/listinfo/python-list
Python password display
Hello, I am currently writing some python code which requires the use of a password. Currently I am using the raw_input function to take the users input in and use it. One problem with that is the password is displayed in clear text on the console of the server. I would like to work on a way around that. Is there any built in method to do that or any how-to's around the Internet / Advice that I could research? Regards, Johhny. -- http://mail.python.org/mailman/listinfo/python-list
Help Needed !!! Browsing and Selecting More Than One File
Dear Diez B. Roggisch, After clicking a button on the GUI the user can browse and than select a .c file to assign to the other program I have mentioned. But in this way I can only select one file. I don't know how to implement this application for all of the *.c files in a folder. Do I need to write a for loop for this? Or maybe I can create a list after sequentially browsing files and than assign this list as a parameter to the function I am executing. Here is a part of the code, I am new to Python and OOP. Sorry for the ambiguity in my question. class App: #Browsing the file, this is triggered #through a menu def browseFile(self): global file file = askopenfilename(filetypes = [(C source code, *.c), (All Files, *.*)]) #Running the CC program #This is triggered by a button push def runCC(self, event): if type(file)==str: dosya = file cmd = 'cc ' + dosya return os.system(cmd) else: message = tkMessageBox.showinfo(Window Text, Please Browse a File Firstly) print message Regards, Fatih K. __ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Python password display
Johhny wrote: Hello, I am currently writing some python code which requires the use of a password. Currently I am using the raw_input function to take the users input in and use it. One problem with that is the password is displayed in clear text on the console of the server. I would like to work on a way around that. Is there any built in method yes: http://docs.python.org/lib/module-getpass.html to do that or any how-to's around the Internet / Advice that I could research? Regards, Johhny. -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: XML-RPC + SimpleHTTPServer question
I have recently implemented a system where clients connect to an RPC server (RPyC in my case), run a webserver on the RPC server, and close the webserver when they're done with it. To do this I wrote a ServerThread class which wraps a SimpleHTTPServer, runs as a thread, and can be signalled to stop. The ServerThread class doesn't use the server_forever() method (which is just while 1: self.handle_request()), instead it has a while loop which checks a flag which is signalled from outside. We need to set a timeout for the handle_request() call. The first thing I tried was to use Python's socket object's new 'set_timeout' method, but I found it caused mysterious errors to occur on my WindowsXP machine :( Instead I call select() on the server's listening socket to check for incoming requests, and only then call handle_request(). select()'s timeout works :) # This is the heart of the code - the request handling loop: while not self.close_flag.isSet(): # Use select() to check if there is an incoming request r,w,e = select.select([self.server.socket], [], [], self.timeout) if r: self.server.handle_request() # The stop method should be called to stop the request handling loop def stop(self, wait=False): self.close_flag.set() if wait: while self.isAlive(): # isAlive() is inherited from threading.Thread time.sleep(self.timeout/10.0) (in my case, self.stop_flag is a threading.Event object) Good luck! jbrewer wrote: I'm currently implementing an XML-RPC service in Python where binary data is sent to the server via URLs. However, some clients that need to access the server may not have access to a web server, and I need to find a solution. I came up with the idea of embedding a simple HTTP server in the XML-RPC clients so that files can be sent in the following way: 1. Start an HTTP server on the client using e.g SImpleHTTPServer on a user allowed port 2. Call XML-RPC server with the URL to the file on the client to upload 3. Get XML-RPC server response, then shut down HTTP server on client Does this sound reasonable? I know that XML-RPC can send binary data, but I presume that the URL method would be faster because the XML parser could skip reading the binary file (is it base64 encoded as a string like in SOAP?). Anyway, I'm unsure of how to implement this in Python. In particular, how do I shut down a web server once I've started it with server_forever()? Should I run the server in a separate thread or run it asynchronously? Since I'm only uploading one file I don't really need to handle multiple clients; I just need to be able to shut the server down once remote call has finished. Any help would be appreciated since I'm new to network programming. Jeremy -- http://mail.python.org/mailman/listinfo/python-list
Re: python list/array question...
Another way to do it is using a dict with keys that are tuples: arr = {} arr[0,0] = 'a1' arr[0,1] = 'a2' arr[1,0] = 'b1' arr[1,1] = 'b2' arr[2,0] = 'c1' arr[2,1] = 'c2' for j in range(3): ... for i in range(2): ... print arr[j,i], ' ', ... print ... a1 a2 b1 b2 c1 c2 You can derive a class from dict that implements desired behaviors (e.g. bounds checking, nrows and ncols attributes). Using this approach over lists of lists is nice: old fogey scientific programmers like me prefer the explicit [j,i] syntax over the [j][i] way, and it's easily extensible over more than two dimensions ([k][j][i]??? Yikes!). This is perhaps not preferred for a full matrix (I'd tend to use a NumPy array of Objects), but it can be useful. I've used it in two cases: -- A sparse matrix (overload dict.__getitem__ to return 0 if the tuple (j,i) is not a valid key), -- A multidimensional array in which all the indices are strings, like a table with column labels and row labels (in my case, it was a 3-dimensional table with a concatenated key of three text strings but there were reasons not to use a relational database). It was very convenient to implement the code in this way, and extremely readable. This trick is also useful with dbm files, e.g. using shelve. --vic -- http://mail.python.org/mailman/listinfo/python-list
Re: Very practical question
Thank you all for your comments. They are priceless beyond any doubt. As for the matter of the discussion it took me only a minute looking at the code to realize that with Tkinter I pass master reference to every widget and therefore I can access every method in the class hierarchy. I'm a fool that I haven't noticed it earlier. -- http://mail.python.org/mailman/listinfo/python-list
Re: RegEx conditional search and replace
mbstevens [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] On Thu, 06 Jul 2006 08:32:46 +0100, Martin Evans wrote: Juho Schultz [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Martin Evans wrote: Sorry, yet another REGEX question. I've been struggling with trying to get a regular expression to do the following example in Python: Search and replace all instances of sleeping with dead. This parrot is sleeping. Really, it is sleeping. to This parrot is dead. Really, it is dead. But not if part of a link or inside a link: This parrot a href=sleeping.htm target=newis sleeping/a. Really, it is sleeping. to This parrot a href=sleeping.htm target=newis sleeping/a. Really, it is dead. This is the full extent of the html that would be seen in the text, the rest of the page has already been processed. Luckily I can rely on the formating always being consistent with the above example (the url will normally by much longer in reality though). There may though be more than one link present. I'm hoping to use this to implement the automatic addition of links to other areas of a website based on keywords found in the text. I'm guessing this is a bit too much to ask for regex. If this is the case, I'll add some more manual Python parsing to the string, but was hoping to use it to learn more about regex. Any pointers would be appreciated. Martin What you want is: re.sub(regex, replacement, instring) The replacement can be a function. So use a function. def sleeping_to_dead(inmatch): instr = inmatch.group(0) if needsfixing(instr): return instr.replace('sleeping','dead') else: return instr as for the regex, something like (a)?[^]*(/a)? could be a start. It is probaly better to use the regex to recognize the links as you might have something like sleeping.sleeping/sleeping/sleeping.html in your urls. Also you probably want to do many fixes, so you can put them all within the same replacer function. ... My first working attempt had been to use the regex to locate all links. I then looped through replacing each with a numbered dummy entry. Then safely do the find/replaces and then replace the dummy entries with the original links. It just seems overly inefficient. Someone may have made use of multiline links: _ This parrot a href=sleeping.htm target=new is sleeping /a. Really, it is sleeping. _ In such a case you may need to make the page into one string to search if you don't want to use some complex method of tracking state with variables as you move from string to string. You'll also have to make it possible for non-printing characters to have been inserted in all sorts of ways around the '' and '' and 'a' or 'A' characters using ' *' here and there in he regex. I agree, but luckily in this case the HREF will always be formated the same as it happens to be inserted by another automated system, not a user. Ok it be changed by the server but AFAIK it hasn't for the last 6 years. The text in question apart from the links should be plain (not even b is allowed I think). I'd read about back and forward regex matching and thought it might somehow be of use here ie back search for the A and forward search for the /A but of course this would easily match in between two links. -- http://mail.python.org/mailman/listinfo/python-list
getting current UNIX uid
Hello, I am trying to get the user that is running the scripts uid, I have had a look at the pwd module and it does not appear to offer that functionality. Is there any way within python to get that information ? Regards, Johhny -- http://mail.python.org/mailman/listinfo/python-list
Re: Help Needed !!! Browsing and Selecting More Than One File
(Please quote at least a significant part of the message you're replying to, or people will have trouble understanding what you're talking about...) On Thu, 06 Jul 2006 15:42:28 +0200, Kilicaslan Fatih [EMAIL PROTECTED] wrote: Dear Diez B. Roggisch, After clicking a button on the GUI the user can browse and than select a .c file to assign to the other program I have mentioned. But in this way I can only select one file. I don't know how to implement this application for all of the *.c files in a folder. Do I need to write a for loop for this? Or maybe I can create a list after sequentially browsing files and than assign this list as a parameter to the function I am executing. What has it to do with running your program with several file names as arguments? Is it two different ways to select several files in your application? Or do you want one or the other? Here is a part of the code, I am new to Python and OOP. Sorry for the ambiguity in my question. class App: #Browsing the file, this is triggered #through a menu def browseFile(self): global file This is unrelated to your question, but why do you use a global variable in a class? Can't you use an instance attribute, or a class attribute? And BTW, file is the name of a built-in, so using it to name a variable is a bad idea. file = askopenfilename(filetypes = [(C source code, *.c), (All Files, *.*)]) So is it a third way of selecting multiple files? Anyway, if you want to be able to select multiple files via askopenfilename, use askopenfilename(..., multiple=1). The value returned by the function will then be a sequence of file names. #Running the CC program #This is triggered by a button push def runCC(self, event): if type(file)==str: Unrelated to your question again, but explicitely testing the type of a variable is usually a bad idea. What can be stored in file? I'd set it to None in the beginning, then test if file is not None: instead of testing its type. dosya = file cmd = 'cc ' + dosya return os.system(cmd) else: message = tkMessageBox.showinfo(Window Text, Please Browse a File Firstly) print message This line will always print None (or an empty string maybe), as tkMessageBox.showinfo doesn't return anything. No print is needed here, as showinfo already displays the message in a dialog. You also have a branch of the 'if' explicitely returning something (the result of the os.system call) and the other one not returning anything, i.e implicitely returning None. Is there a reason for that? This is - again - usually a bad idea as it makes your code difficult to understand. HTH -- python -c print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-']) -- http://mail.python.org/mailman/listinfo/python-list
Re: getting current UNIX uid
Johhny wrote: Hello, I am trying to get the user that is running the scripts uid, I have had a look at the pwd module and it does not appear to offer that functionality. Is there any way within python to get that information ? eg: username = pwd.getpwuid(os.getuid())[4] Eric -- http://mail.python.org/mailman/listinfo/python-list
Re: getting current UNIX uid
[Johhny] I am trying to get the user that is running the scripts uid, I have had a look at the pwd module and it does not appear to offer that functionality. Is there any way within python to get that information ? It's in the 'os' module: import os os.getuid() 553 -- Richie Hindle [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Countdown timer for different timezones
Hi! I'd like to implement a countdown timer on a webite. It should show the months, days, hours, minutes and seconds until a given date and time. So far it's not really difficult, but this website will be used from different time zones, what will make a difference of 10 hours, if I use the time-information from the client. The event will take place at one fixed moment which is worldwide the same. Does anyone know a way to solve this time-zone-problem? Regards and thanks for your ideas Dirk -- http://mail.python.org/mailman/listinfo/python-list
Re: numarray
bruce wrote: robert i did an python import numpy a = array([['q','a'],['w','e']]) not tested, but you usually need to mention where to find array: a = numpy.array([['q','a'],['w','e']]) and it didn't work... i used from import numpy * and it seems to accept the 'array' word.. .looks like it will work... from numpy import * makes numpy.array available as array in your code. I would be kind of you to post what you have exactly done as the phrase from import ... can't be it. Claudio Grondi what's the difference between 'import numpy', and from import numpy * comments... thanks -bruce -Original Message- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] Behalf Of Robert Kern Sent: Tuesday, July 04, 2006 9:42 PM To: python-list@python.org Subject: Re: numarray bruce wrote: hi... i'm trying to find numarray.. i found the numpy on sourceforge and downloaded/installed.. i did a python import numarray and got an error... Never just say I got an error. It tells us nothing. Copy-and-paste the exact error message. I presume, however, that you installed numpy, not numarray. They are not the same thing. the docs that i've seen point to the sourceforge area.. but i only see numpy.. which appears to incorporate numarray.. No, it replaces numarray. http://www.scipy.org/NumPy my goal is to somehow define multi-dimensional arrays of strengs... from numpy import * a = array([['some', 'strings'],['in an', 'array']], dtype=object) a array([[some, strings], [in an, array]], dtype=object) -- Robert Kern I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth. -- Umberto Eco -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: setting variables from a tuple NEWB
manstey [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Hi, If I have a tuple like this: tupGlob = (('VOWELS','aeiou'),('CONS','bcdfgh')) is it possible to write code using tupGlob that is equivalent to: VOWELS = 'aeiou' CONS = ''bcdfgh' Thanks, Matthew Try this. -- Paul tupGlob = (('VOWELS','aeiou'),('CONS','bcdfgh')) for nam,val in tupGlob: locals()[nam]=val ... VOWELS 'aeiou' CONS 'bcdfgh' -- http://mail.python.org/mailman/listinfo/python-list
Re: ElementTree : parse string input
[EMAIL PROTECTED] wrote: Hi, recently having discovered ElementTree I'm stumped by a very simple problem, which I can't find the answer to. I have some XML in a string object. Now the parse() method of ElementTree takes a filename or file-like object. So I tried creating a StringIO object from the original string and then giving that to parse(). But that does not seem to work. that should work, but the fromstring function (and it's XML alias) is a lot easier to use. data = some xml in a string elem = ElementTree.XML(data) also see the end of this section: http://www.effbot.org/zone/element.htm#reading-and-writing-xml-files /F -- http://mail.python.org/mailman/listinfo/python-list
Re: searching for strings (in a tuple) in a string
manstey wrote: Hi, I often use: a='yy' tup=('x','yy','asd') if a in tup: ... but I can't find an equivalent code for: a='xfsdfyysd asd x' tup=('x','yy','asd') if tup in a: ... I can only do: if 'x' in a or 'yy' in a or 'asd' in a: ... but then I can't make the if clause dependent on changing value of tup. Is there a way around this? One thing I do sometimes is to check for True in a generator comprehension if True in (t in a for t in tup): # do whatever here Because you're using a generator you get the same short-circut behavior that you would with a series of 'or's, the if statement won't bother checking the rest of the terms in tup after the first True value. def f(n, m): print n return n m m = 2 if True in (f(n, m) for n in range(5)): print 'done' 0 1 2 3 done # See? No 4! :-) I usually use this with assert statements when I need to check a sequence. Rather than: for something in something_else: assert expression I say assert False not in (expression for something in something_else) This way the whole assert statement will be removed if you use the '-O' switch to the python interpreter. (It just occurred to me that that's just an assumption on my part. I don't know for sure that the interpreter isn't smart enough to remove the first form as well. I should check that. ;P ) Note, in python 2.5 you could just say if any(t in a for t in tup): # do whatever here In your case though, if I were doing this kind of thing a lot, I would use a little helper function like the findany() function Fredrik Lundh posted. IMHO if findany(a, tup): ... is much clearer and readily understandable than mucking about with generator comprehensions... Peace, ~Simon -- http://mail.python.org/mailman/listinfo/python-list
Re: Countdown timer for different timezones
In [EMAIL PROTECTED], Dirk Hagemann wrote: I'd like to implement a countdown timer on a webite. It should show the months, days, hours, minutes and seconds until a given date and time. So far it's not really difficult, but this website will be used from different time zones, what will make a difference of 10 hours, if I use the time-information from the client. The event will take place at one fixed moment which is worldwide the same. Does anyone know a way to solve this time-zone-problem? I don't think there's a reliable way to get the time zone information from the viewer of the website with just HTTP. So you need a JavaScript solution I guess. Send the end time as UTC time to the browser an use JavaScript's `Date` object to display the countdown in local time. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: setting variables from a tuple NEWB
In [EMAIL PROTECTED], Paul McGuire wrote: tupGlob = (('VOWELS','aeiou'),('CONS','bcdfgh')) for nam,val in tupGlob: locals()[nam]=val ... VOWELS 'aeiou' CONS 'bcdfgh' Little warning: It works only on module level as assigning to `locals()` return value in functions and methods has no effect on the real locals. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: looping question 4 NEWB
In [EMAIL PROTECTED], manstey wrote: I often have code like this: data='asdfbasdf' find = (('a','f')('s','g'),('x','y')) for i in find: if i[0] in data: data = data.replace(i[0],i[1]) is there a faster way of implementing this? Also, does the if clause increase the speed? It decreases it. You search through `data` in the ``if`` clause. If it's `False` then you have searched the whole data and skip the replace. If it's `True` you searched into data until there's a match and the the `replace()` starts again from the start and searches/replaces through the whole data. You can get rid of the indexes and make the code a bit clearer by the way: for old, new in find: data = data.replace(old, new) Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: mirroring object attributes using xml-rpc
sashang Then the client code can get the value of i like this: sashang c = xmlrpclib.ServerProxy(address) sashang c.geti() sashang but why can't I get the value of i like this? sashang c.i RPC stands for Remote Procedure Call. You're looking for a remote object access protocol. As Irmen pointed out, Pyro is one such beast, though it is limited to use with Python. If you need something that's more language-independent, you might look at SOAP. Personally, XMLRPC has been sufficient for me for several years. Skip -- http://mail.python.org/mailman/listinfo/python-list
Re: looping question 4 NEWB
[EMAIL PROTECTED] wrote: manstey: is there a faster way of implementing this? Also, does the if clause increase the speed? I doubt the if increases the speed. The following is a bit improved version: # Original data: data = 'asdfbasdf' find = (('a', 'f'), ('s', 'g'), ('x', 'y')) # The code: data2 = data for pat,rep in find: data2 = data.replace(pat, rep) print data2 Small bug in that code, you'll wind up with data2 only being the result of replacing the last (pat, rep) in find. It should be: data2 = data for pat, rep in find: data2 = data2.replace(pat, rep) Be careful with multi-char terms in find. You could wind up replacing patterns that only occur in data2 as a result of earlier replacements. I.e. if find = ('bc', 'ab'), ('aa', 'bb') data = 'abc' then data2 = 'aab' # First iteration, data2 = 'bbb' # Second iteration replaces 'aa' even though 'aa' isn't in original data. Have fun, ~Simon # If find contains only chars, and the string is long # enough, then this is more or less the faster solution: from string import maketrans table = map(chr, xrange(256)) for c1,c2 in find: table[ord(c1)] = c2 table_str = .join(table) print data.translate(table_str) Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list
Re: handling unicode data
Hi Martin, One would have to ask the authors of pymssql, or Microsoft, why that happens; alternatively, you have to run pymssql in a debugger to find out yourself. Tried running pymssql in a debugger, but I felt a bit lost. There are too many things I would need to understand about pymssql first. Meanwhile, I got to some very interesting conclusions. Remember the ANSI-to-OEM conversion option you mentioned before? I began reading some docs about it and this description turned up: The ANSI to OEM conversion translates data coming back from SQL Server into the local code page used by your client. which seemed exactly what I don't want.. so I turned it to OFF (by using the registry key HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSSQLServer\Client\DB-Lib\AutoAnsiToOem) and everything started working the way I was originally expecting! I think that the best way to actually solve this will be to override AutoAnsiToOem (instead of using the registry setting) from within pymssql, or find a way to specify what the local code page should be. If not, I will have to have the pain of verifying this setting in every system where the code I'm developing will be deployed. Which reminds me... that this setting doesn't exist on non-windows environments (ie, no registry on Linux) so I'm not sure how will it all work there. Anyone with experience in using DB-Library that can confirm how it works (namely, on linux)? (but perhaps this is outside the scope of this newsgroup.. ) I got in touch with Andrzej Kukula, the current developer of pymssql, who has also been very helpful, and knows what we've been discussing over here. thanks for all the help, Filipe -- http://mail.python.org/mailman/listinfo/python-list
Re: Nested scopes, and augmented assignment
Antoon Pardon [EMAIL PROTECTED] (AP) wrote: AP Well if someone explains what is wrong about my understanding, I AP certainly care about that (although I confess to sometimes being AP impatient) but someone just stating he is not sure I understand? That is just a euphemistic way of stating `I think you do not understand it'. AP So if I understand you correctly in code like: AP c.d = a AP b = a AP All three names are searched for in all scopes between the local en global AP one. That is what I understand with your statement that [python] always AP uses the same search order. The d is different because it is an attribute. So it is looked up in the context of the object that is bound to c. For a, b, and c it is correct. AP My impression was that python will search for c and a in the total current AP namespace but will not for b. The assignment to b inside the function (supposing the code above is part of the function body) tells the compiler that b is a local variable. So the search stops in the local scope. The search order is always from local to global. First the current function, then nested function, then the module namespace, and finally the builtins. The first match will stop the search. Now for local variables inside a function, including the parameters, the compiler will usually optimize the search because it knows already that it is a local variable. But that is an implementation detail. But a variable that is bound inside the function (with an asignment) and is not declared global, is in the local namespace. AP Aren't we now talking about implementation details? Sure the compilor AP can set things up so that local names are bound to the local scope and AP so the same code can be used. But it seems somewhere was made the AP decision that b was in the local scope without looking for that b in AP the scopes higher up. Yes, as I (and others) have already said several times: an assignment to a variable inside a function body (but not an assignment to an attribute or part of an object) without a global declaration makes that variable a local variable. That is not an implementation detail; it is part of the language definition. AP Let me explain a bit more. Suppose I'm writing a python interpreter AP in python. One implemantation detail is that I have a list of active AP scopes which are directories which map names to objects. At the AP start of a new function the scope list is adapted and all local AP variables are inserted to the new activated scope and mapped to AP some Illegal Value object. Now I also have a SearchName function AP that will start at the begin of a scope list and return the AP first scope in which that name exists. The [0] element is the AP local scope. Now we come to the line b = a AP This could be then executed internally as follows: AP LeftScope = SearchName(b, ScopeList) AP RightScope = SearchName(a, ScopeList) AP LeftScope[b] = RightScope[a] AP But I don't have to do it this way. I already know in which scope AP b is, the local one, which has index 0. So I could just as well AP have that line exucuted as follows: AP LeftScope = ScopeList[0] AP RightScope = SearchName(a, ScopeList) AP LeftScope[b] = RightScope[a] AP As far as I understand both implementations would make for AP a correct execution of the line b = a and because of the AP second possibility, b is IMO not conceptually searched for in AP the same way as a is searched for, although one could organise AP things that the same code is used for both. That is the optimization I spoke of above. But it is not the problem we were discussing. Conceptually it is the same. It is similar to constant folding (replacing x = 2+3 by x = 5). AP Of course it is possible I completely misunderstood how python AP is supposed to work and the above is nonesense in which case AP I would appreciate it if you correct me. AP Python could have chosen an approach with a nested keyword, to allow AP rebinding a name in an intermediate scope. It is not that big a deal AP that it hasn't, but I keep finding the result strange and somewhat AP counterintuitive. Maybe it would have been nice if variables could have been declared as nested, but I think it shows that nested variables have to be used with care, similar to globals. Especially not allowing rebinding in intermediate scopes is a sound principle (`Nested variables considered harmful'). If you need to modify the objects which are bound to names in intermediate scopes, use methods and give these objects as parameters. AP But shouldn't we just do programming in general with care? And if AP Nested variables are harmfull, what is then the big difference AP between rebinding them and mutating them that we should forbid AP the first and allow the second? There is no big difference I think. Only Python doesn't have syntax for the former. Older versions of Python didn't even have nested scopes. maybe it was a mistake to add them. I think an important
fastcgi: how to accept HTTP requests, and return a result
Greetings, I'm now merrily on my way developing a FastCGI Server in python. Thanks to help of others on this list I've got a proof of concept up and running. Herein lies my question: My goal is to make this module as flexible as possible, so that it can receive requests from SimpleHTTP, or Cherrpy, or Webpy, or any other py web server. What is the best way to accept HTTP requests and return the result? Should I subclass SimpleHTTPRequestHandler (as CGIHTTPRequestHandler does) or is there another/better way? I dug around the net and the python source and didn't see much (next to nothing) on implementing your own request handlers, so I'm interested to hear what ya'll have to say. Thanks -- matthew -- http://mail.python.org/mailman/listinfo/python-list
Re: setting variables from a tuple NEWB
manstey wrote: Hi, If I have a tuple like this: tupGlob = (('VOWELS','aeiou'),('CONS','bcdfgh')) is it possible to write code using tupGlob that is equivalent to: VOWELS = 'aeiou' CONS = ''bcdfgh' could you use a dictionary instead? i.e. tupGlob = {'VOWELS':'aeiou', 'CONS':'bcdfgh'} tupGlob['VOWELS'] 'aeiou' tupGlob['VOWELS'] = 'aeiou AndSometimesY' tupGlob['VOWELS'] 'aeiou AndSometimesY' nate -- 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: Activate a daemon several times a day
Yves Glodt 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 If you're on a unix-ish system, you might consider making your daemon sensitive to a signal and then use cron and kill to send it that signal when you want it to activate. This is just an idea. It might not be the kind of solution you're looking for, especially if you're not already familiar with cron crontab. It might be more helpful to you to tell you that you can get the current hour as an int using the gmtime() (for UTC) or localtime() (for, uh, local time :-) ) from the time module: from time import gmtime, localtime gmtime() (2006, 7, 6, 16, 6, 32, 3, 187, 0) gmtime()[3] 16 help(gmtime) Help on built-in function gmtime in module time: gmtime(...) gmtime([seconds]) - (tm_year, tm_mon, tm_day, tm_hour, tm_min, tm_sec, tm_wday, tm_yday, tm_isdst) Convert seconds since the Epoch to a time tuple expressing UTC (a.k.a. GMT). When 'seconds' is not passed in, convert the current time instead. help(localtime) Help on built-in function localtime in module time: localtime(...) localtime([seconds]) - (tm_year,tm_mon,tm_day,tm_hour,tm_min,tm_sec,tm_wday,tm_yday,tm_isdst) Convert seconds since the Epoch to a time tuple expressing local time. When 'seconds' is not passed in, convert the current time instead. That takes care of the now(hours) part of your pseudocode. HTH, ~Simon -- http://mail.python.org/mailman/listinfo/python-list
Re: Activate a daemon several times a day
Yves Glodt wrote: while True: if now(hours) in runat: act() sleep(60) sleep(10) Note that, if now(hours) *is* in runat, this loop will sleep 70 seconds, not 60. It probably doesn't matter. -- http://mail.python.org/mailman/listinfo/python-list
python/xpath question...
for guys with python/xpath expertise.. i'm playing with xpath.. and i'm trying to solve an issue... i have the following kind of situation where i'm trying to get certain data. i have a bunch of tr/td... i can create an xpath, that gets me all of the tr.. i only want to get the sibling tr up until i hit a 'tr' that has a 'th' anybody have an idea as to how this query might be created?.. the idea would be to start at the Summer B, to skip the 1st tr, to get the next trs until you get to the next Summer section... sample data. tr Th colspan=14 class=soc_comment Summer B /th /tr !-- START RA.CTLIB(SOCPHDR1) -- tr td nowrap valign=bottom class=colhelp a href=#Coursespan bCourse/b brCourse number and suffix, if applicable. brC = combined lecture and lab course brL = laboratory course /span/a/td /tr !-- END RA.CTLIB(SOCPHDR1) -- tr td valign=top nowrapa href=javascript:crsdescunderpop('AST1002');AST 1002/a/td /tr tr td valign=top nowrapa href=javascript:crsdescunderpop('AST1022L');AST 1022L/a/td /tr tr td valign=top nowrapa href=javascript:crsdescunderpop('AST1022L');AST 1022L/a/td /tr tr td valign=top nowrapa href=javascript:crsdescunderpop('AST1022L');AST 1022L/a/td /tr tr Th colspan=14 class=soc_comment Summer C /th /tr !-- START RA.CTLIB(SOCPHDR1) -- tr td nowrap valign=bottom class=colhelp a href=#Coursespan . . . thanks... -bruce -- http://mail.python.org/mailman/listinfo/python-list
web app breakage with utf-8
Hello, after two days of failed efforts and googling, I thought I had better seek advice or observations from the experts. I would be grateful for any input. We have various small internal web applications that use utf-8 pages for storing, searching and retrieving user input. They have worked fine for years with non ASCII values, including Russian, Greek and lots of accented characters. They still do on an old version of python (2.2.1), and there's nothing in the code to decode/encode the input, it's *just worked*. Recently however, while testing on a dev machine, I notice that any characters outside ASCII are causing SQL statement usage to break with UnicodeDecodeError exceptions with newer versions of python (2.3 and 2.4). There are a number of threads online, suggesting converting to unicode types, and similar themes, but I'm having no success. I am probably completely misunderstaning something fundamental. :-( My first question is did something change for normal byte stream usage making it more strict? I'm surprised there aren't more problems like this online. Is there a correct way to handle text input from a FORM when the page is utf-8 and that input is going to be used in SQL statements? I've tried things like (with no success): sql = uselect * from blah where col='%s' % input Doing sql = sql.decode('latin1') prior to execution prevents the some UnicodeDecodeError exceptions, but the data retrieved from the tables is no longer usable, causing breakage when being used to create the output for the browser. I really am at a loss for what is going wrong, when everything works fine on crusty old 2.2.1. What are others doing for caputre, store, and output for web utf-8? Rgds, Jason -- http://mail.python.org/mailman/listinfo/python-list
Python SOAP and XML-RPC performance extremely low?
When I try TooFPy with the SOAP and XML-RPC sample client code provided in TooFPy tutorials, a log entry shows up quickly on web server log window, but it takes a long time (5 seconds or longer) for the client to output a Hello you. It seems like the web server is fast because the log entry shows immieidately on web server console. But it takes Python XML/SOAP parser a long time to parse the extremely simple result. If so, wouldn't this render Python SOAP and XMP-RPC implementation useless in real life? -- http://mail.python.org/mailman/listinfo/python-list