Re: Dispatch('Excel.Application') on Vista from Task Scheduler
Cupric wrote: I have a python script that runs fine from the command line or from within IDLE, but doesn't work through the Vista Task Scheduler. The script downloads some csv files and then uses pywin32 to combine the csv files into a single document. When I run it through the task scheduler, it downloads the csv files, but then doesn't seem to launch excel. I can't figure out what is wrong or how to add enough logging to tell. I'm using Python 2.6 and pywin32-212.win32-py2.6 on Vista. Code snippet below. Any ideas? Does it have something to do with permissioning on Vista? I'm running the task as my regular user (that has administrative privileges). Thanks, Theo --- from win32com.client import Dispatch excel = Dispatch('Excel.Application') excel.visible =0 print 'launched excel' workbook =excel.Workbooks.Add() Sheets = workbook.sheets defaultWorksheets = workbook.Worksheets(1) excel.application.displayalerts = 0 for port in portList: print 'about to open' + basePath + port.filename port_book = excel.Workbooks.Open( basePath + port.filename) port_sheets = port_book.Sheets datasheet = port_sheets(1) datasheet.Activate() datasheet.Cells.Select() excel.Selection.Copy() Sheets.Add().Name = port.name newsheet=workbook.Worksheets(port.name) newsheet.Activate() newsheet.Paste() port_book.Close(SaveChanges=0) Normally this has more to do with the context that the app runs in under Task Scheduler not having the same environment as the logged in user. Try telling the Task Scheduler to run the application using the same credentials as the foreground user to see if that makes a difference. -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: Python COM: Automatic wrap/unwrap?
Greg Ewing wrote: I'm creating a COM server in Python that will have one main class, with methods that create and return instances of other classes. I've found that I need to use win32com.server.util.wrap and unwrap on these objects when they pass over a COM connection. This doesn't seem very convenient, especially for methods that can be called either via COM or internally from other Python code. It seems that the basic Python types are wrapped and unwrapped automatically when needed. Is there some way of extending this mechanism? Is there a class I can inherit from, or a magic attribute I can set, or some registration process I can use, to get instances of my class automatically wrapped and unwrapped? You should post this on comp.python.windows as Mark and the other Windows/COM gurus hang around there a lot. -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: Does Python have Multiple Inheritance ?
Lawrence D'Oliveiro wrote: In message <[EMAIL PROTECTED]>, Steve Holden wrote: Lawrence D'Oliveiro wrote: In message <[EMAIL PROTECTED]>, Michele Simionato wrote: On Nov 7, 4:38 pm, Tim Golden <[EMAIL PROTECTED]> wrote: Seriously, though, although Python does indeed support multiple inheritance, I have the impression from comments over the years that it's used a lot less than in other languages where it is more of a common idiom. The reason is that in Python using composition is very easy, so there is little need for MI (which is a Good Thing). Not to mention duck typing, which does away with the need for inheritance altogether. That seems a somewhat extreme point of view. Hey, I didn't design the language, I just use it. :) I'm with Steve. Multiple inheritance is still a "good" thing, especially for mixin-classes. wxPython, for instance, wouldn't be nearly so flexible without it. -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: Looking for a nitty-gritty Python Ajax middleware script to fire off a number of processors
Shao wrote: Dear All, I am looking for a nitty-gritty Python Ajax script to fire off a number of processing programmes, periodically checking their operations, sending messages back to an HTML div form by sending back the links of generated data files, to be downloaded by end users. I am using .NET IIS 6.0 and Windows Server. Regards. Shao What you are asking requires so much more information than you have provided to actually give you an answer I doubt you will get one. This is NOT a simple task but rather quite complicated. Sounds like you need something written in Twisted that dispatches background processes and handles the callbacks from those processes. Twisted Web could then update the HTML pages that users are watching by refreshing them periodically. -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: More __init__ methods
Mr.SpOOn wrote: On Thu, Nov 6, 2008 at 7:44 PM, Tim Golden <[EMAIL PROTECTED]> wrote: While that's no bad thing, you don't really need to do that simply to understand these examples: they're just saying "do whatever you need to to make these method class methods, not instance methods". Yes. I think this changes the design of my class. I mean, till now I had something like: class foo: def __init__(self, string=None, integer=None, someinstance=None): self.a = 0 self.b = 0 if string: # do something to calculate "a and b" elif integer: # do something else to calculate "a and b" ... ... So I used different methods to calculate the same variables. Now I must pass a and b to the main constructor and calculate them in the classmethods. class foo: def __init__(self, a, b): self.a = a self.b = b @classmethod def from_string(self, ..): ... ... What I mean is: I can't use anymore __init__ as the default constructor, but I always have to specify the way I'm creating my object. Am I right? I'm asking just to be sure I have understood. Is there some reason not to use something like the following? class foo: def __init__(self, val): self.a = 0 self.b = 0 if isinstance(val, basestring): # # do something to calculate "a and b" # elif isintance(val, int): # # do something else to calculate "a and b" # elif isinstance(val, someinstance) # # do something else to calculate "a and b" # else: # # Don't know what to do with unknown type # raise ValueError() -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: Is there a better/simpler way to filter blank lines?
[EMAIL PROTECTED] wrote: tmallen: I'm parsing some text files, and I want to strip blank lines in the process. Is there a simpler way to do this than what I have here? lines = filter(lambda line: len(line.strip()) > 0, lines) xlines = (line for line in open(filename) if line.strip()) Bye, bearophile Of if you want to filter/loop at the same time, or if you don't want all the lines in memory at the same time: fp = open(filename, 'r') for line in fp: if not line.strip(): continue # # Do something with the non-blank like: # fp.close() -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: How to get an object's name as a string?
Shannon Mayne wrote: I would like to create objects with algorithmically determined names based on other object names and use object names for general algorithm input. How would one extract the name of an object from an object instance as a string. I would think that it is stored as an attribute of the object but successive 'dir()' calles haven't found me the attribute with the namestring. My thanks! Once again (there have been many posts on this subject). Objects can have more than one name in Python. Therefore there is not a one-to-one correspondence between an object instance and name(s) that point to it. Example: a = myObject() b = a c = a now a, b, c all point to the same object. How would you define it's "name". You are certainly free to store a name as an attribute to the object, but the linkage would then be purely logical. Example: objects = [] objects.append(myObject('a')) # # Find object with name == 'a' # obj = None for object in objects: if object.name == 'a': obj = object -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: Need some advice
alex23 wrote: On Oct 23, 3:15 pm, Larry Bates <[EMAIL PROTECTED]> wrote: Bruno is correct, the protocol IS https, you don't type shttp into your browser get secure http connection. https[1] and shttp[2] are two entirely different protocols. [1] http://en.wikipedia.org/wiki/Https [2] http://en.wikipedia.org/wiki/Secure_hypertext_transfer_protocol Ok, I stand corrected on "shttp". I've been a programmer for over 30 years and have been using python and web development for about 7 years and I've never seen any reference to it until now. IMHO it wouldn't be a good idea to implement any production code utilizing such an obscure protocol when https is available. You asked for "advice" in the Subject of OP, that's my advice. -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: which program I need for sftp using pramiko??
sa6113 wrote: which program I have to install for using paramiko for sftp between a two windows machine in local network?? I have installed freeSSHd for server machine but I got an Authentication failed erro when try to connect to server using this code : sock.connect((hostname, port)) t = paramiko.Transport(sock) event = threading.Event() t.start_client(event) event.wait() if not t.is_active(): print 'SSH negotiation failed.' sys.exit(1) else: print "SSH negotiation sucessful" event.clear() t.auth_password(username=username, password=password,event=event) if not t.is_authenticated(): print "Authentication failed" output: SSH negotiation successful Authentication failed May I install any program on client computer such as openssh ? please help me. Thanks Is security really that important between two machines on the same LAN? If it really is that important, just use scp between the two machines. You don't really have to reinvent the wheel to copy files between to machines. -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: socket programming (client-server)
ryan wrote: i have implemented a small client server model to do file transfer over a LAN network. It work with some machines on the network and on others it doesnt. when i run the server.py file in some machine then it pops up a windows security alert. The message is as follows: Do you want to keep blocking this program? there are three options below it. 1. Keep Blocking 2. Unblock 3. Ask Me later. I selected the option unblock.Even then the client and server are not able to communicate. I get a error saying that:- socket.error: (10060, 'Operation timed out') I guess its a firewall problem... How do i go abt it? any help? Yes it is a firewall problem. To make sure, turn off the firewall on a machine that doesn't work and try the application again. If that works, put an exception in the firewall for your application's port. -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: Need some advice
azrael wrote: I mean shttp. (secure hyper text transfer protocol) On Oct 22, 9:48 am, Bruno Desthuilliers wrote: azrael a écrit : There have been some discutions with my partner about which protocol to use. We agreed to use also http. But we are looking for a possibility to use something to trasfer python objects like Json objects. 'like' ??? there are a couple json implementation for Python, and for PHP too IIRC. If my memory is me well http transfers data in plaintext. Because of the risk of datacapturing, is there a better soulutioon to suggest to be more secure like shttp I suppose you mean https... if it is implemented in python http://www.python.org/doc/2.5.2/lib/https-handler-objects.html Bruno is correct, the protocol IS https, you don't type shttp into your browser get secure http connection. You don't transfer python objects with JSON, you can transfer data that was stored in Python objects via converting them to JSON (e.g. most JSON resembles a Python dictionary, but it is a text representation). PHP couldn't do anything with a Python object. You may want to pick up a copy of "RESTful Web Services", from O'Reilly. It is an excellent starting place for you. -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: quick newbie syntax question
Robocop wrote: oops! Sorry about that, i should have just copied my code directly. I actually did specify an int in range: year = '2008' month = '09' limit = '31' for i in range(1,int(limit)): The code is currently failing due to the syntax in the filter, particularly the section "date = year'-'month'-'i" I believe you want something more like date = "%s-%s-%s" % (year, month, i) but then again I can't quite figure out what is is that you are wanting to do (Note: September doesn't have 31 days). Where did Table object come from and what does the table.objects.filter method do and what are the appropriate arguments to that method? If it was "my" method, and I wanted to use it this way, I would think about changing it so that it accepted a filtering function and returned only those objects that passed the filtering function: def myFilter(obj): return (obj.date >= '2008-09-01' and obj.date <= '2008-09-30') class objects(object): def __init__(self): self.objects = [] def filter(filterFunc): return [x for x in self.objects if filterFunc(x)] Then temp = Table.objects.filter(myFilter) temp is a list of objects you can act on. -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: Creating single .exe file without py2exe and pyinstaller
Tino Wildenhain wrote: Hi, Abah Joseph wrote: I have written a small application of about 40-45 lines which is about 4KB, so I want to create a single .exe file from it, using py2exe it created unnecessary files, that just increase the size of the program and also less portable to me. What else can I use? the "unneccessary files" you say, are what your 40-45 lines bring to life. 1) just distribute the 40-45 lines - but this requires python installation on users end 2) use a python to C(++) compiler and compile the result to .exe, works pretty well for simple applications: http://shed-skin.blogspot.com/ Regards Tino 3) Stop worrying about the size of the distribution. In today's world 4Mb is trivial to download. -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: windows / unix path
Marcin201 wrote: Is there an built-in functionality in python to convert Windows paths to Unix paths? I am running into problems when creating data files on Windows and the running them on a Unix platform. I create paths using os.path.join. os.path.join('Pictures', '01.jpg') returns 'Pictures\\01..jpg' on Win. When I read files created on Win under Unix this is a problem, python cannot open 'Pictures\\01.jpg' Thanks, Marcin I use posixpath when I want to "force" forward slashes that I know will work on Linux. Actually the forward slashes work fine on Windows also (undocumented feature of Windows). -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: Finding the instance reference of an object
Joe Strout wrote: On Oct 16, 2008, at 10:59 AM, Larry Bates wrote: how do i find that the name is 'bob' Short answer is that you can't. This because Python's names (bob) are bound to objects (modulename.objectname()). They are NOT variables as they are in "other" programming languages. Which other programming languages? I've never seen an OOP language that didn't work the same way as Python. However, 'bob' here really is a variable. It's a variable whose value (at the moment) is a reference to some object. It is perfectly legal in Python to bind multiple names to a single object: a=b=c=modulename.objectname() Right -- three variables (a, b, and c) that all have the same value, i.e. all refer to the same object. There's nothing more mysterious here than i=j=k=42 where i, j, and k all have the same value. (The OP's question would be like asking "what is the name of the variable referring to 42? And while you might, in theory, be able to produce a list of all such variables by trolling through the Python's internals, it's a bit of a silly thing to do.) a, b, and c all point to the same object. An object can have an unlimited number of names bound to it. This is one of the most difficult concepts for many beginning Python programmers to understand (I know I had a difficult time at first). It is just not how we taught ourselves to think about "variables" and you can write quite a lot of Python treating the names you bind to objects like they were "variables". Well, they are variables. I'm not quite grasping the difficulty here... unless perhaps you were (at first) thinking of the variables as holding the object values, rather than the object references. That is indeed something important to grasp, since it explains why if you do a = b # where b was some object with an attribute 'foo'... a.foo = 42 ...you now find that b.foo is 42 too. Nothing mysterious once you realize that the value of a and b is a reference to some object that has a "foo" attribute. Not sure if all this was helpful to anyone, but I hope so! Best, - Joe Sorry Joe, but I respectfully disagree about "not being mysterious". I've been on this list for about 8 years and this question/issue comes up EVERY week with newbies. Python names are just not variables in the traditional sense. If they were then: a=b=c=[42] would create three independent variables that each contained a list with a single element of 42. That is not what Python does and just about every newbie gets bitten by that fact at least once. ow many posts have a read here where people do things like: a = [1,2,3,4,5] b = a b.append(6) and can't figure out why a now contains [1,2,3,4,5,6]? Without fail they thought that b = a copied the contents of a into b. That is, they thought of a and b as variables that "hold" values. Now the term "variables" may mean something different to you than most of the other newbies that frequent this list, but they all (including me when I first started) miss the subtilety of the name/value bindings at first (but boy are they beautiful when you finally see the light). Perhaps you were lucky and were able to grasp this quite powerful concept more easily than most of us. I think this is one of the most difficult concepts about Python to grasp for people coming from VB, C, Fortran, Cobol (oops showed my age there), etc. We trained our minds to treat "variables" like named buckets (or memory locations). Even the OP here wants to interrogate the object in the bucket and coerce it into giving him the bucket (variable) name. The problem, as Steven so eloquently shows in a separate post, is that is is hard to talk about names that are bound to objects. So we fall back into familiar language and use "variable" which confuses a lot of newbies because they have preconceived notion about what a "variable" is and what it does. Regards, Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: Finding the instance reference of an object
Astley Le Jasper wrote: Sorry for the numpty question ... How do you find the reference name of an object? So if i have this bob = modulename.objectname() how do i find that the name is 'bob' Short answer is that you can't. This because Python's names (bob) are bound to objects (modulename.objectname()). They are NOT variables as they are in "other" programming languages. It is perfectly legal in Python to bind multiple names to a single object: a=b=c=modulename.objectname() a, b, and c all point to the same object. An object can have an unlimited number of names bound to it. This is one of the most difficult concepts for many beginning Python programmers to understand (I know I had a difficult time at first). It is just not how we taught ourselves to think about "variables" and you can write quite a lot of Python treating the names you bind to objects like they were "variables". To accomplish what you want, put your instances in a dictionary. instances = {} instances['bob'] = modulename.objectname() instances['joe'] = modulename.objectname() . . . Then you can reference them as: instances[name] and/or you can pass the name in as an argument to the __init__ method of objectname so that it can "hold" the name of the dictionary key that references it (good for debugging/logging). -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: using SSh problem!
sa6113 wrote: I want to connect form a windows machine to a Linux one using SSH (I use Paramiko) and simply copy a file to Linux machine. Would you please help me how should I start? Is there any useful code? I find that one of the easiest ways of doing this is to install Cygwin on the windows machine, then you have all the Linux capabilities under Windows. Open Cygwin console and you can use ssh, scp, etc. to connect to Linux box, copy a file, etc. All with ssh security. -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: questions from a lost sheep
johannes raggam wrote: On Thu, 2008-10-02 at 15:18 -0500, [EMAIL PROTECTED] wrote: Joe> I've started to think fondly of the rock-solid stability of Python, Joe> and have been wondering if perhaps aggressive unit testing could Joe> mitigate most of the problems of weak typing. Note: Python is not weakly typed. It is dynamically typed. But, yes, there is no substitute for unit tests in a language like Python. just to make it maybe clearer - here an excerpt from the excellent book dive into python, which is also free available: """ statically typed language: A language in which types are fixed at compile time. Most statically typed languages enforce this by requiring you to declare all variables with their datatypes before using them. Java and C are statically typed languages. dynamically typed language: A language in which types are discovered at execution time; the opposite of statically typed. VBScript and Python are dynamically typed, because they figure out what type a variable is when you first assign it a value. strongly typed language: A language in which types are always enforced. Java and Python are strongly typed. If you have an integer, you can't treat it like a string without explicitly converting it. weakly typed language: A language in which types may be ignored; the opposite of strongly typed. VBScript is weakly typed. In VBScript, you can concatenate the string '12' and the integer 3 to get the string '123', then treat that as the integer 123, all without any explicit conversion. So Python is both dynamically typed (because it doesn't use explicit datatype declarations) and strongly typed (because once a variable has a datatype, it actually matters). """ http://diveintopython.org/getting_to_know_python/declaring_functions.html#d0e4188 cheers, hannes That is a GREAT explanation of statically, dynamically, strongly and weakly typed languages. So many programmers are confused about these differences. Many believe that statically typed is the only way to have strongly typed and they are incorrect. Thanks for this. -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: How to send Data Transfer Objects across the network?
Daniel wrote: Hello, I've been building a system that has need to send object data across the network. The approach I've taken has been to build Data Transfer Objects, which just contain the attributes of the objects, and to pickle them and send them over a socket connection. As I get deeper this is a bit problematic, and so I was wondering if there is a package or framework that is already designed to do this? Again, all I need to do is serialize an object, send it somewhere where it is deserialized and processed after which a response object is serialized and sent back to the client to complete the transaction. Thanks in advance... Daniel You might also want to take a look at Twisted's Perspective Broker: http://twistedmatrix.com/projects/core/documentation/howto/pb-intro.html -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: del and sets proposal
Chris Hebert wrote: On Thu, Oct 2, 2008 at 3:20 PM, Larry Bates <[EMAIL PROTECTED]> wrote: You can do the following: a = [1,2,3,4,5] del a[0] and a = {1:'1', 2: '2', 3: '3', 4:'4', 5:'5'} del a[1] why doesn't it work the same for sets (particularly since sets are based on a dictionary)? a = set([1,2,3,4,5]) del a[1] Sets don't support subscripting, so if you can't go 'a_set[something]', why would you expect to be able to be able to 'del' such an expression? What would the subscription even mean without the 'del'? It doesn't make sense and would just be inconsistent. Yes I know that sets have a remove method (like lists), but since dictionaries don't have a remove method, shouldn't sets behave like more like dictionaries and less like lists? IMHO del for sets is quite No, sets are a datatype unto themselves. They are based on dictionaries internally (at least in CPython), but that's an implemention detail to be hidden, not emphasized. intuitive. I guess it is too late to change now. Most likely. Cheers, Chris I believe that the fact that Sets don't support indexing is an implementation artifact that is due to the FACT that their underlying implementation is based on dictionaries (a good choice in my opinion). One could just as easily have implemented (but then they would not have performed so well) Sets as an ordered list of unique values and have provided indexing capabilities (but I can't quite think of a use case for such an animal right now). I didn't mean to imply that del a[1] would delete the first thing in the set, but rather the item with a value of 1. Just as when we use it on a dictionary: del a[1] doesn't mean delete the first dictionary entry but rather delete the entry in the object with a value of 1, which IMHO would be perfectly logical for a set (which is why I started this discussion). There is no ambiguity because sets, like dictionaries, require uniqueness. Maybe dictionaries should have had a .remove method then things would be more consistent? -Larry -- http://mail.python.org/mailman/listinfo/python-list
del and sets proposal
You can do the following: a = [1,2,3,4,5] del a[0] and a = {1:'1', 2: '2', 3: '3', 4:'4', 5:'5'} del a[1] why doesn't it work the same for sets (particularly since sets are based on a dictionary)? a = set([1,2,3,4,5]) del a[1] Yes I know that sets have a remove method (like lists), but since dictionaries don't have a remove method, shouldn't sets behave like more like dictionaries and less like lists? IMHO del for sets is quite intuitive. I guess it is too late to change now. -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: writing dll in python?
nishalrs wrote: Hello All, My main motivation is to build a collection of useful mathematical models (that I have developed over the years) to design ultrasonic sensors. This should be some sort of a library that should be able to be used for desktop/web application development, to run in variety of operating systems. I am more than convinced after looking at python.org website, it is the right tool for the job. I intend to learn python, but I am not really sure, where to begin. Should I write all the functions as simple python scripts? Or is there some facility for creating a .dll like library, that could be more suitable for what in intend to develop? Any help is much appreciated. Regards, Nishal DLLs are so 1990s . You can more easily write COM objects in Python that can easily be utilized by essentially virtually every programming language that exists on Windows. -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: Making small executive file for distribution
Marin Brkic wrote: Not commercial distribution, but an academic kind of sorts - giving the exe file to coleagues, so they can use it in their work. Giving .py file is not an option, since due to centralized computer maintenance, they don't (and cannot) have installed python (except the ones that bring their own computer at work, but those are an exception). As far as I know py2exe is the only option which can do such a thing (make exe files from scripts). Is there a way to make those exe files a little smaller (for a small script they easily go up to 5-10 mb). Has anyone had a situation like this ? All your inputs and suggestions are more then welcomed. -- Marin Times have changed, 5-10Mb is REALLY small. Flash drives hold 4000-8000Mb for less than $20 and standard hard drives are now 500Gb. IMHO you are concerned about a problem that doesn't actually exist. -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: Python style: exceptions vs. sys.exit()
Drake wrote: I have a general question of Python style, or perhaps just good programming practice. My group is developing a medium-sized library of general-purpose Python functions, some of which do I/O. Therefore it is possible for many of the library functions to raise IOError Exceptions. The question is: should the library function be able to just dump to sys.exit() with a message about the error (like "couldn't open this file"), or should the exception propagate to the calling program which handles the issue? Thanks in advance for anyone who can either answer my question or point me to where this question has already been answered. IMHO libraries should always just let the exception propagate up to the caller. That allows the caller the option of taking the appropriate action. -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: new style classes, __new__, __init__
Torsten Mohr wrote: Hi, i have some questions related to new style classes, they look quite useful but i wonder if somebody can give me an example on constructors using __new__ and on using __init__ ? I just see that when using it i can't give parameters to __new__ and when i additionally define __init__ then __new__ is not called. So i can use __new__ only for classes whose constructors don't have parameters? class C2: def __new__(self): print "new called" self.a = 8 def __init__(self, a): print "init called" self.a = a def fct(self): print self.a a = C2(7) a.fct() This way __new__ is not called, if i remove __init__ then there are too many parameters to __new__, if i add a parameter to __new__ then it says that __new__ does not take arguments. Thanks for any hints, Torsten. New style classes should be based on object: class C2(object): -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: code style and readability [was: Re: Checking the boolean value of a collection]
Bruno Desthuilliers wrote: Bruno Desthuilliers a écrit : Larry Bates a écrit : (snip) IMHO it reads better if you use the __call__ method of the class to return the value IMHO, it makes no sense at all to abuse the __call__ magic method here. Sorry - after a more careful re-read of other posts in the thread, it might make sense, given the use case : condition = FolderInUse(core) if condition.true_for(folder): # code here but then, a plain function (or a partial) might be even better - that is, if the FolderInUse class doesn't have other responsabilities. Sorry but I respectfully disagree that this is "abuse" of the __call__ method. I do agree that a plain function probably makes more sense but it appears that the class does "other"things because of references to other class instances, etc. I also have a personal dislike for early returns because I've found it makes it harder insert execution trace logging into the code. Just my experience. -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: code style and readability [was: Re: Checking the boolean value of a collection]
Marco Bizzarri wrote: On Sat, Sep 13, 2008 at 4:11 PM, Fredrik Lundh <[EMAIL PROTECTED]> wrote: Marco Bizzarri wrote: class FolderInUse: def true_for(self, archivefolder): return any([instance.forbid_to_close(archivefolder) for instance in self.core.active_outgoing_registration_instances()]) Is this any better? The true_for name does not satisfy me a lot... well, "true_for" is indeed pretty inscrutable, but I'm not sure that would be the first thing I'd complain about in that verbose mess... "verbose mess". It is always frustrating when you do what you think is your best and you read that. Anyway: I'm here to learn, and, of course, part of it is to listen those who've been there much longer than you. So, thanks for your sincere evaluation, Fredrik :-). (when you pick method names, keep in mind that the reader will see the context, the instance, and the arguments at the same time as they see the name. there's no need to use complete sentences; pick short short descriptive names instead.) Maybe I'm looking at the wrong direction, right now. From the point of view of the FolderInUse clients, they will do: condition = FolderInUse(core) condition.true_for(folder) Is this too verbose? This is not a polemic statement, I'm really asking your opionion. The expression inside the true_for is indeed complex, and maybe I can simplify it; however, I'm deeply convinced that instance.forbid_to_close(folder) has some good points on it; I mean, once I read this kind of code, I can hope to understand it without looking at what forbid_to_close does. >>> class FolderInUse: >>> >>>def true_for(self, archivefolder): >>>return any([instance.forbid_to_close(archivefolder) for instance in >>>self.core.active_outgoing_registration_instances()]) IMHO it reads better if you use the __call__ method of the class to return the value and rewrite it as a regular loop for clarity. Sometimes the simplest way is the easiest to read. class FolderInUse: def __call__(self, archivefolder): result = False for instance in self.core.active_outgoing_registration_instances(): if instance.forbid_to_close(archivefolder): result = True break return result Then it can be called with: if FolderInUse(archivefolder): ... -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: testing if another instance of a script is already running
Strato wrote: Hi folks, I want to write some kind of test to check at startup if another instance of my script is already running. I don't want to handle writing of a PID file because it is too Unix/Linux specific way to do this, and I need to keep the code to be cross-platform. I think the better way to achieve this is to use some process control, but I'm a neebie and I don't see how to do this in a safe and clean way. Any idea ? Best regards, Strato Here is a recipe for Windows version of singleinstance class: http://code.activestate.com/recipes/474070/ and I wrote and contributed the equivalent Linux version: http://code.activestate.com/recipes/546512/ Hope this helps. -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: testing if another instance of a script is already running
Strato wrote: Hi folks, I want to write some kind of test to check at startup if another instance of my script is already running. I don't want to handle writing of a PID file because it is too Unix/Linux specific way to do this, and I need to keep the code to be cross-platform. I think the better way to achieve this is to use some process control, but I'm a neebie and I don't see how to do this in a safe and clean way. Any idea ? Best regards, Strato Here is a recipe for Linux version of singleinstance class: http://code.activestate.com/recipes/546512/ and I wrote and contributed the equivalent Windows version: http://code.activestate.com/recipes/474070/ Hope this helps. -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: wxpython ms-dos black window popping up in background
icarus wrote: Oh ok. Thanks. In windows xp I just renamed the file extension to .pyw That did it. one more question... how do I create a pythonw standalone executable that works on w32, linux, mac, etc..? My intent is to have the process transparent to the user. He wouldn't even know the app was written in python. All he knows that when he double-clicks on it, the application pops up without the DOS black screen in the background (for w32 users.) On Sep 9, 10:49 am, "Chris Rebert" <[EMAIL PROTECTED]> wrote: You need to have the script be run by pythonw.exe as opposed to python.exe pythonw.exe suppresses the DOS box from coming up and should be used for running GUI applications such as yours. Regards, Chris On Tue, Sep 9, 2008 at 1:33 PM, icarus <[EMAIL PROTECTED]> wrote: platform: windows xp professional, python 2.5, wxpython When I double-check on my program file test.py (for simplicity I'll be using this code below), I see the window just fine. But the ms-dos black window pops up in the background. On Linux, no issues at all. How can I get rid of that ms-dos black window in the background? something I need to add to my code? a setting to adjust in windows? thanks in advance. #!/usr/bin/python import wx appwx = wx.App() frame = wx.Frame(None, -1, 'test.py') frame.Show() appwx.MainLoop() -- http://mail.python.org/mailman/listinfo/python-list -- Follow the path of the Iguana...http://rebertia.com On Windows use py2exe and Inno Setup to create "frozen" application that is easy to distribute. On Mac/Linux there are other solutions. -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: dynamic allocation file buffer
castironpi wrote: I will try my idea again. I want to talk to people about a module I want to write and I will take the time to explain it. I think it's a "cool idea" that a lot of people, forgiving the slang, could benefit from. What are its flaws? A user has a file he is using either 1/ to persist binary data after the run of a single program (persistence) or 2/ share binary data between concurrently running programs (IPC / shared memory). The data are records of variable types and lengths that can change over time. He wants to change a record that's already present in the file. Here are two examples. Use Case 1: Hierarchical ElementTree-style data A user has an XML file like the one shown here. Foo ... He wants to change "Foo" to "Foobar". Foobar ... The change he wants to make is at the beginning of a 4GB file, and recopying the remainder is an unacceptable resource drain. Use Case 2: Web session logger A tutor application has written a plugin to a webbrowser that records the order of a user's mouse and keyboard activity during a browsing session, and makes them concurrently available to other applications in a suite, which are written in varying lanugages. The user takes some action, such as surfing to a site or clicking on a link. The browser plugin records that sequence into shared memory, where it is marked as acknowledged by the listener programs, and recycled back into an unused block. URLs, user inputs, and link text can be of any length, so truncating them to fit a fixed length is not an option. Existing Solutions - Shelve - A Python Standard Library shelf object can store a random access dictionary mapping strings to pickled objects. It does not provide for hierarchical data stores, and objects must be unpickled before they can be examined. - Relational Database - Separate tables of nodes, attributes, and text, and the relations between them are slow and unwieldy to reproduce the contents of a dynamic structure. The VARCHAR data type still carries a maximum size, no more flexible than fixed-length records. - POSH - Python Object Sharing - A module currently in its alpha stage promises to make it possible to store Python objects directly in shared memory. In its current form, its only entry point is 'fork' and does not offer persistence, only sharing. See: http://poshmodule.sourceforge.net/ Dynamic Allocation The traditional solution, dynamic memory allocation, is to maintain a metadata list of "free blocks" that are available to write to. See: http://en.wikipedia.org/wiki/Dynamic_memory_allocation http://en.wikipedia.org/wiki/Malloc http://en.wikipedia.org/wiki/Mmap http://en.wikipedia.org/wiki/Memory_leak The catch, and the crux of the proposal, is that the metadata must be stored in shared memory along with the data themselves. Assuming they are, a program can acquire the offset of an unused block of a sufficient size for its data, then write it to the file at that offset. The metadata can maintain the offset of one root member, to serve as a 'table of contents' or header for the remainder of the file. It can be grown and reassigned as needed. An acquaintence writes: It could be quite useful for highly concurrent systems: the overhead involved with interprocess communication can be overwhelming, and something more flexible than normal object persistence to disk might be worth having. Python Applicability The usual problems with data persistence and sharing apply. The format of the external data is only established conventionally, and conversions between Python objects and raw memory bytes take the usual overhead. 'struct.Struct', 'ctypes.Structure', and 'pickle.Pickler' currently offer this functionality, and the buffer offset obtained from 'alloc' can be used with all three. Ex 1. s= struct.Struct( 'III' ) x= alloc( s.size ) s.pack_into( mem, x, 2, 4, 6 ) Struct in its current form does not permit random access into structure contents; a user must read or write the entire converted strucutre in order to update one field. Alternative: s= struct.Struct( 'I' ) x1, x2, x3= alloc( s.size ), alloc( s.size ), alloc( s.size ) s.pack_into( mem, x1, 2 ) s.pack_into( mem, x2, 4 ) s.pack_into( mem, x3, 6 ) Ex 2. class Items( ctypes.Structure ): _fields_= [ ( 'x1', ctypes.c_float ), ( 'y1', ctypes.c_float ) ] x= alloc( ctypes.sizeof( Items ) ) c= ctypes.cast( mem+ x, ctypes.POINTER( Items ) ).contents c.x1, c.y1= 2, 4 The 'mem' variable is obtained from a call to PyObject_AsWriteBuffer. Ex 3. s= pickle.dumps( ( 2, 4, 6 ) ) x= alloc( len( s ) ) mem[ x: x+ len( s ) ]= s 'dumps' is still slow and nor does permit random access into contents. Use Cases Revisited Use Case 1: Hierarchical ElementTree-style data Solution: Dynamically allocate the tree and its elements. Node: tag: a Node: tag: b Node: tag: c Node: text: Foo The user
Re: creating an (inefficent) alternating regular expression from a list of options
metaperl.com wrote: Pyparsing has a really nice feature that I want in PLY. I want to specify a list of strings and have them converted to a regular expression. A Perl module which does an aggressively optimizing job of this is Regexp::List - http://search.cpan.org/~dankogai/Regexp-Optimizer-0.15/lib/Regexp/List.pm I really dont care if the expression is optimal. So the goal is something like: vowel_regexp = oneOf("a aa i ii u uu".split()) # yielding r'(aa|a|uu| u|ii|i)' Is there a public module available for this purpose? Perhaps I'm missing something but your function call oneOf(...) is longer than than actually specifying the result. You can certainly write quite easily: def oneOf(s): return "|".join(s.split()) -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: Submitting forms over HTTPS with mechanize
Rex wrote: Hello, I am working on an academic research project where I need to log in to a website (www.lexis.com) over HTTPS and execute a bunch of queries to gather a data set. I just discovered the mechanize module, which seems great because it's a high-level tool. However, I can't find any decent documentation for mechanize apart from the docstrings, which are pretty thin. So I just followed some other examples I found online, to produce the following: baseurl = 'http://www.lexis.com/' br = mechanize.Browser() br.set_handle_robots(False) br.addheaders = [('User-Agent', 'Firefox')] br.open(baseurl) br.select_form(name="formauth") br["USER_ID"]="my_user_id" br["PASSWORD"]="my_password" result = br.submit() This code hangs at br.submit(), and I can't tell what I'm doing wrong. Typically I would inspect the HTTP data with an HTTP debugging proxy (Fiddler), but I guess since this is HTTPS I can't do that. Any glaring errors in my code? By the way, does anyone have suggestions for Python modules that I should use instead of mechanize (and that are sufficiently easy)? If mechanize fails, I might try modifying some similar Perl code a friend sent me that logs into lexis.com. Thanks so much, Rex I've used mechanize quite successfully but others have suggested Twill http://twill.idyll.org/. It seems to be at least documented. -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: Access to Windows "Add/Remove Programs"?
Sean DiZazzo wrote: Hi all, I'm trying to find a way to get a list of all the installed programs on a Windows box via Python. I thought of a few hacks that might partially work, and then thought about "Add/Remove Programs" Seems like the right way to go. I looked over the pywin32 docs a bit, but nothing slapped me in the face. Is there any reliable way to get at that info? Thanks in advance, ~Sean I would guess that that program gets the information from the registry. Maybe looking at HKEY_LOCAL_MACHINE\SOFTWARE or HKEY_CURRENT_USER\Software branches? -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: Fastest way to write huge files
Mohamed Yousef wrote: If connection is over Internet via HTTP the connection speed is so slow in relation to the speed of your CPU that it doesn't really matter. this is not always true , espicially when using a localhost or a local netwtork server the problem is the increase in cpu and memory usage make it a painful bug such that downloading a big file (say 1 GB ) would introduce a big cpu usage (already tested) Thanks , Regards, Mohamed Yousef I disagree. There is very little overhead in file writing if you stream your writes to disk in small blocks as they arrive via HTTP. Don't wait for the entire 1Gb to arrive and then write it. Python can write small to a file blazingly fast with normal file writing I/O. Any extra CPU overhead you may see is probably due to reading the entire 1Gb into memory and seeing swapping to disk as you exhaust main memory. Interleaving your HTTP reading with file writing should be very fast. -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: Ensure only single application instance.
Cameron Laird wrote: In article <[EMAIL PROTECTED]>, Uberman <[EMAIL PROTECTED]> wrote: On Fri, Aug 29, 2008 at 6:51 AM, Heston James <[EMAIL PROTECTED]> wrote: Good afternoon all. I have an application/script which is launched by crontab on a regular basis. I need an effective and accurate way to ensure that only one instance of the script is running at any one time. You could create a named pipe in /tmp with a unique (static) name and permissions that disallow any kind of read/write access. Then simply have your script check for its existence when it starts. If it exists, then another instance of your script is running, and just terminate. Make sure your original instance removes the pipe when it exits. I'll write an article on this subject this fall. The essentials are: A. There's no canonical answer; every apparent solution has problems; B. The suggestions offered you are certainly among the popular ones; C. My personal favorite is to open a (network) socket server. For reasons I'll eventually explain, this has particularly apt semantics under Unix. Cameron, I found this recipe (http://code.activestate.com/recipes/474070/) on ActiveState's site that had a working version of a single instance class for Windows that I've used quite successfully. Since I also work a lot Linux, I wrote and donated this version (http://code.activestate.com/recipes/546512/) for Linux that also seems to work well for me. -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: How to check is something is a list or a dictionary or a string?
[EMAIL PROTECTED] wrote: Hi, How to check if something is a list or a dictionary or just a string? Eg: for item in self.__libVerDict.itervalues(): self.cbAnalysisLibVersion(END, item) where __libVerDict is a dictionary that holds values as strings or lists. So now, when I iterate this dictionary I want to check whether the item is a list or just a string? Thanks, Rajat Are you sure that is what you want to do or do you want to make sure that "something" is an iterable. What if someone passed in a generator or a class instance that is iterable, do you really want to fail? -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: microsoft terminal server
Tim Golden wrote: [EMAIL PROTECTED] wrote: HI, i would like to know if there is a way to create a python script for automate mstsc.exe username and pwd credential, i mean i would create a script that first open mstsc.exe and in the same time is able to fill [computer+username+pwd]. Haven't tried it, but in principle you should be able to use the win32cred package from pywin32 to store your username / password and use an .rdp file to automate the rest of the settings, including the server. TJG Use Remote Desktop Connection to create/save an .rdp file that can connect to your remote computer. Then use os.startfile(''.rdp). It will call mstsc for you. -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: Fastest way to write huge files
Mohamed Yousef wrote: Thanks all , but there is still something i forget to state -sorry - all communication will be via Http with a server so data is received via Http so local network solutions won't work the problem really starts after receiving data in storing them without much of a CPU/Memory usage and with a good speed @James Mills : didn't understand fully what you mean and how it will improve writting effciency Thanks, Regards, Mohamed Yousef 2008/8/29 Tim Golden <[EMAIL PROTECTED]>: Terry Reedy wrote: Mohamed Yousef wrote: let's say , I'm moving large files through network between devices what is the fastest way to do this ? what i came up with :- Use your OS's network copy command. On unix, that was once uucp. On Windows, I drag-and-drop to/from a Network Neighborhood location, including to a printer, so I don't know whether you can use copy and if so how. For completeness' sake, on Windows you could use any of the following techniques with a UNC as the destination (and/or source): http://timgolden.me.uk/python/win32_how_do_i/copy-a-file.html TJG -- http://mail.python.org/mailman/listinfo/python-list If connection is over Internet via HTTP the connection speed is so slow in relation to the speed of your CPU that it doesn't really matter. You are prematurely optimizing your application. Get it working first and then see if the file writing is the bottleneck (it probably won't be). -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: JSON from Python mysqldb
jpuopolo wrote: All: I am using Python to read some records from the MySQL database. I am using the mysqldb library, and things are working well. Now, I would like to pass back the results of the query to a Web-based front end, and I would like to use JSON. Is there a library/example of creating a JSON array from a mysqldb row or row set? Thanks, jpuopolo Google turns up several high quality links, just look for 'python json'. -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: 'While' question
Ben Keshet wrote: Thanks for the reference. I tried it with a general example and got it to work - I used an index that counts up to a threshold that is set to break. It does not work though with my real code. I suspect this is because I cannot really read any lines from an empty file, so the code gets stuck even before I get to j=j+1: line = f.readline()[:-1] j=0 while 'PRIMARY' not in line: line = f.readline()[:-1] j=j+1 if j==30: break Any suggestions? BK Wojtek Walczak wrote: On Thu, 21 Aug 2008 18:01:25 -0400, Ben Keshet wrote: somehow. I use 'while 'word' not in line' to recognize words in the texts. Sometimes, the files are empty, so while doesn't find 'word' and runs forever. I have two questions: 1) how do I overcome this, and make the script skip the empty files? (should I use another command?) 2) how do I interrupt the code without closing Python? (I have ActivePython) Try the docs first. You need to read about 'continue' and 'break' statements: http://docs.python.org/tut/node6.html HTH. You might consider turning this around into something like: for j, line in enumerate(f): if 'PRIMARY' in line: continue if j == 30: break IMHO this is MUCH easier to understand. -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: how to add property "dynamically"?
akonsu wrote: hello, i need to add properties to instances dynamically during run time. this is because their names are determined by the database contents. so far i found a way to add methods on demand: class A(object) : def __getattr__(self, name) : if name == 'test' : def f() : return 'test' setattr(self, name, f) return f else : raise AttributeError("'%s' object has no attribute '%s'" % (self.__class__.__name__, name)) this seems to work and i can invoke method test() on an object. it would be nice to have it as property though. so i tried: class A(object) : def __getattr__(self, name) : if name == 'test' : def f() : return 'test' setattr(self, name, property(f)) return f else : raise AttributeError("'%s' object has no attribute '%s'" % (self.__class__.__name__, name)) but this does not work, instance.test returns a callable but does not call it. i am not an expert in python, would someone please tell me what i am doing wrong? thanks konstantin Are you sure you can't get by by adding attributes to the instance that hold the values that the property would return? class A(object): def __init__(self, dbvaluedict): self.__dict__.update(dbvaluedict) >>> dbvaluedict = dict('test': 'test') >>> a = A(dbvaluedict) >>> print a.test test If this doesn't help. You might want to start at the beginning and explain what it is you are trying to accomplish. What you are trying to do is very unusual. -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: Fixed-length text file to database script
Michael Ströder wrote: Larry Bates wrote: [EMAIL PROTECTED] wrote: I have a machine (PLC) that is dumping its test results into a fixed- length text file. I need to pull this data into a database (MySQL most likely) so that I can access it with Crystal Reports to create daily reports for my engineers. [..] I need to know how to write a script that will DAILY pull this text file into a MySQL database. Just use the built in import SQL statement to import the information. You don't really need a Python script. import can handle fixed field records (as well as CSV, etc.). If the input data has to be pre-processed before storing it into the database a Python script would be needed. Just in case somebody needs a module for reading fixed-length files in the spirit of module csv: http://www.stroeder.com/pylib/fixedlenfields.py For the MySQL part: http://mysql-python.sourceforge.net/ Ciao, Michael. While you are correct, that is not what the OP asked. There is no reference to processing data prior to insertion into MySQL database. Also the OP said they had a 1 day deadline. -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: Getting stdout using ctypes.
Mathias Lorente wrote: Hello all. I have a simple application (C++) that relies on shared libraries. It works fine in console mode. Lot of job is done into the shared library, so there is some calls to 'std::cout' to inform the user in it. Now, I would like to wrap everything into a GUI, remove the application and call directly everything from Python using ctypes. (I still need the console application to launch it manually if needed). I've made a simple library to test ctypes and everything works fine except that I don't know how to get stout in order to redirect it somewhere (dialog box or so). I've looked for some help into the mailing list history and found nothing useful (until now). Do someone has any suggestion? Mathias If I'm understanding your question correctly, you can replace sys.stdout with any class that provides a write method. class myStdout(object): def __init__(self): self.lines = list() def write(self, data): self.lines.append(data) Then in program do something like import sys sys.stdout = myStdout() Now everything that would have gone to stdout will be buffered into the list in sys.stdout.lines. -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: ActiveState Python v2.5 doesn't come with Tkinter or Tk installed.
Dudeja, Rajat wrote: Hi, So, now I've finally started using Eclipse and PyDev as an IDE for my GUI Application. I just wrote some sample programs as an hands on. Now I would like to take up Tkinter. I'm using Active State Python version 2.5 and found that there is not Tkinter and Tk module in it. To use Tkinter do I actually require Tk installed on my machine? Please suggest and where can I find both these modules? Also, please direct me to a good and short document on using Tkinter or Tk in Python. Cheers, Rajat Notice: This e-mail is intended solely for use of the individual or entity to which it is addressed and may contain information that is proprietary, privileged, company confidential and/or exempt from disclosure under applicable law. If the reader is not the intended recipient or agent responsible for delivering the message to the intended recipient, you are hereby notified that any dissemination, distribution or copying of this communication is strictly prohibited. If this communication has been transmitted from a U.S. location it may also contain data subject to the International Traffic in Arms Regulations or U.S. Export Administration Regulations and cannot be disseminated, distributed or copied to foreign nationals, residing in the U.S. or abroad, without the prior approval of the U.S. Department of State or appropriate export licensing authority. If you have received this communication in error, please notify the sender by reply e-mail or collect telephone call and delete or destroy all copies of this e-mail message, any physical copies made of this e-mail message and/or any file attachment(s). NOTE: Please begin your posts with what platform (Linux/Mac/Windows) you are running on so we can answer your questions better. From ActiveState's webpage: All platforms * Tcl/Tk 8.4.14 and Tix 8.4.2 upgrades. It is certainly on my machine which is Windows ActiveState install. You better check again. If you are on Windows, you can use py2exe to package up your program and you won't have to have Python/Tk installation. First hit on Google is: http://wiki.python.org/moin/TkInter -Larry -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: Factory for Struct-like classes
eliben wrote: Hello, I want to be able to do something like this: Employee = Struct(name, salary) And then: john = Employee('john doe', 34000) print john.salary Basically, Employee = Struct(name, salary) should be equivalent to: class Employee(object): def __init__(self, name, salary): self.name = name self.salary = salary Ruby's 'Scruct' class (http://ruby-doc.org/core/classes/Struct.html) does this. I suppose it can be done with 'exec', but is there a more Pythonic way ? Thanks in advance P.S. I'm aware of this common "pattern": class Struct: def __init__(self, **entries): self.__dict__.update(entries) Which allows: john = Struct(name='john doe', salary=34000) print john.salary But what I'm asking for is somewhat more general. That's about as "general" as it gets ;-). It works for any number/type of attribute. I would probably make it a new-style class by subclassing object, but for simulating a generic row container, this is quite good. You might extend it with a __str__ method, __len__ method, make it an iterator, etc. but that is quite easy. -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: i want to control python using keyboard
[EMAIL PROTECTED] wrote: hi i want to play alarm sound when i press a particular key in keyboard.so someone help me in doing it. Thanks and Regards Sasil.G When you post to this list you need to give us more to go on than you have. 1) What have you tried that doesn't work? 2) What type of sound file is "alarm sound" or do you just want a beep? 3) What key should be monitored on the keyboard? 4) What platform (operating system) are you running on? 5) Will this be a console or GUI application? All these things need to be known to answer your question? People are more than willing to help, but you have to be willing to try something on your own and to provide enough information so we can help. When something does not work, post your code (and any tracebacks) with your question. -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: for y in range (0,iNumItems)--> not in order?
korean_dave wrote: for y in range(0,iNumItems): print(str(y)) How do i make the output go IN ORDER 0 1 2 3 4 5 6 etc. instead of 0 1 10 11 12 13 14 2 3 4 5 6 7 8 9 That's not what it does on my system (Python 2.5.2 on Windows). Please post the code that you are "actually" running. >>> for y in range(15): ... print str(y) ... 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 You must have put them in a list and sorted them prior to printing them to get the output you show. If you sort the list, the output is correct. To make it different, you will need to pass sort a custom cmp function. -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: Fixed-length text file to database script
[EMAIL PROTECTED] wrote: Hi Guys, I'm new to Python (mostly) and I'm wanting to use it for a new project I'm faced with. I have a machine (PLC) that is dumping its test results into a fixed- length text file. I need to pull this data into a database (MySQL most likely) so that I can access it with Crystal Reports to create daily reports for my engineers. I've been reading the Python manual for about a week now and I'm learning a lot. Unfortunately, I was given a deadline today that I cannot meet without a little help. I need to know how to write a script that will DAILY pull this text file into a MySQL database. Can anyone show me how to do this? Thanks Stacey Just use the built in import SQL statement to import the information. You don't really need a Python script. import can handle fixed field records (as well as CSV, etc.). -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: callbacks in python
Alexandru Mosoi wrote: On Aug 14, 12:02 am, Fredrik Lundh <[EMAIL PROTECTED]> wrote: your use of the word "callback" is a bit unusual, and your example isn't valid Python code, but it looks as if functools.partial might be what you need: http://docs.python.org/lib/module-functools.html my current implementation is very similar to partial() :) (10x, i'll use partial from now on). however it seems that I don't understand very well positional and keyword arguments in python because I got the error described here: http://docs.python.org/ref/calls.html#calls (TypeError: f() got multiple values for keyword argument 'a') which confused me even more. so if you pass positional and keyword arguments to both partial() and function returned the order of passed arguments might be different than expected. i was looking for an implementation that somehow avoids this confusion. Positional arguments come first, keyword arguments come second. You can pick up positional keywords as a list and keyword arguments as a dictionary if you want: def foo(*args, **kwargs): for a in args: # # process positional arguments as a list # for k,v in kwargs.iteritems(): # # Process keyword arguments by iterating over the dictionary # It is a little hard to understand exactly what you are wanting to do, but it sounds like you should probably ONLY use keyword arguments and then there isn't any problem with order or missing arguments (if you set appropriate defaults). -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: callbacks in python
Alexandru Mosoi wrote: does anyone know a nice implementation of callbacks in python? i have issues mixing named & unamed parameters. i want build a callback over a function such that some parameters are passed when callback is created and the rest are passed when the function is called. example: callback = Callback(function, x=1, y) callback(z, t=4, u) First problem is that all unnamed arguments must come BEFORE named ones (Python limitation). To do what you want define you callback as a class instead. class Callback(object): def __init__(x, y): self.x = x self.y = y def __call__(z, t, u): # # Do what you want done at every callback # callback = Callback(x, y) callback(z, t, u) -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: win32service and Python
David wrote: I am collecting informations about win32 services for Python but, except for few basic examples about Mark Hammond's win32serviceutil, I found nothing useful. Any link is welcome. Thank you. David Actually those examples in Python for Win32 book are quite good and basically all services are built using the same framework shown there. If you run into a problem post something here or better yet on comp.python.windows group (I know Mark hangs out over there more than here ;-). -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: newb loop problem
Dave wrote: arrrggg, now I feel really dumb.. hitNum = 0 stopCnt = 6 + hitNum offSet = 5 for i in range(0,10,1): for x in range(hitNum,len(inLst), 1): print hitNum, stopCnt if x == stopCnt: break hitLst.append(inLst[x]) hitNum +=offSet stopCnt+=offSet print hitLst Beers, Dave On Aug 13, 12:58 am, Dave <[EMAIL PROTECTED]> wrote: On Aug 13, 12:35 am, Larry Bates <[EMAIL PROTECTED]> wrote: Dave wrote: Hey there, having a bit of problem iterating through lists before i go on any further, here is a snip of the script. -- d = "a1 b1 c1 d1 e1 a2 b2 c2 d2 e2 a3 b3 c3 d3 e3 a4 b4 c4 d4 e4 a5 b5 c5 d5 e5" inLst = d.split() hitLst = [] hitNum = 0 stopCnt = 6 + hitNum for i in range(hitNum,len(inLst), 1): if i == stopCnt: break hitLst.append(inLst[i]) print hitLst -- $ python helper.py ['a1', 'b1', 'c1', 'd1', 'e1', 'a2'] This works fine for my purposes, what I need is an outer loop that goes through the original list again and appends my next request. ie. hitNum = 5 which will return: ['a2', 'b2', 'c2', 'd2', 'e2', 'a3'] and append it to the previous one. ie: ['a1', 'b1', 'c1', 'd1', 'e1', 'a2'] ['a2', 'b2', 'c2', 'd2', 'e2', 'a3'] not really sure how to do this right now though, been trying several methods with no good results. btw, just creating lagged values (sort of shift registers) on the incoming signal Many thanks, Dave Dave, You are going to need to supply us with more info to help. 1) Are you always going to want to get 6 elements from the list 2) Are you always going to want to step by 5 elements as your offset each time through the outer loop? 3) Is your requirement just to split inLst into equal length lists and append them together into a list? Depending on your answers this might be quite easy. -Larry Hi Larry, well to answer your questions. 1) Are you always going to want to get 6 elements from the list yes for this example, but this will change depending on the length of the sig. hitNum will be changing depending on what element I need to lag ie: if hitNum = 1 ['b1', 'c1', 'd1', 'e1', 'a2', 'b2'] so I will be lagging the b elements. 2) Are you always going to want to step by 5 elements as your offset each time through the outer loop? I think I just answered this 3) Is your requirement just to split inLst into equal length lists and append them together into a list? yes Thanks for all your help, Dave This can also be written as: d = "a1 b1 c1 d1 e1 a2 b2 c2 d2 e2 a3 b3 c3 d3 e3 " \ "a4 b4 c4 d4 e4 a5 b5 c5 d5 e5" inLst = d.split() sliceLen = 6 step = 5 offset = 1 hitLst = list() for n in xrange(len(inLst)/step): start = offset + n * step hitLst.append(inLst[offset:offset + sliceLen]) print hitLst -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: Random Problems
Lanny wrote: Well the othe day I was making a program to make a list of all the songs in certian directorys but I got a problem, only one of the directorys was added to the list. Heres my code: import random import os import glob songs = glob.glob('C:\Documents and Settings\Admin\My Documents\LimeWire\Saved\*.mp3') asongs = glob.glob('C:\Documents and Settings\Admin\My Documents\Downloads\*\*.mp3') songs.append(asongs) asongs = glob.glob('C:\Documents and Settings\Admin\My Documents\Downloads\*\*\*.mp3') songs.append(asongs) asongs = glob.glob('C:\Documents and Settings\Admin\My Documents\Downloads\*\*\*\*.mp3') songs.append(asongs) pick = random.choice(songs) all goes well but pick awalys is from the first directory but songs awalys includes all the files I want it to. Im baffaled. -- Posted on news://freenews.netfront.net - Complaints to [EMAIL PROTECTED] -- 1) You need to either use raw string for your pathnames or use forward slashes. This is because backslash is an escape character to Python and if you get any legal escaped sequence (like \n, \t, etc) it won't work as expected. songs = glob.glob(r'C:\Documents and Settings\Admin\My Documents\LimeWire\Saved\*.mp3') or songs = glob.glob('C:/Documents and Settings/Admin/My Documents/LimeWire/Saved/*.mp3') Yes, forward slashes work just fine on windows. 2) When you have a list (songs) and append another list (asongs) you don't get a combined list, you get a list with the last element being the second list. example: >>> songs = [1,2,3] >>> asongs = [4,5,6] >>> songs.append(asongs) >>> songs [1, 2, 3, [4, 5, 6]] >>> What you wanted was songs.extend(asongs). BTW-Inserting a couple of print statements would have shown you this problem pretty quickly. -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: newb loop problem
Dave wrote: Hey there, having a bit of problem iterating through lists before i go on any further, here is a snip of the script. -- d = "a1 b1 c1 d1 e1 a2 b2 c2 d2 e2 a3 b3 c3 d3 e3 a4 b4 c4 d4 e4 a5 b5 c5 d5 e5" inLst = d.split() hitLst = [] hitNum = 0 stopCnt = 6 + hitNum for i in range(hitNum,len(inLst), 1): if i == stopCnt: break hitLst.append(inLst[i]) print hitLst -- $ python helper.py ['a1', 'b1', 'c1', 'd1', 'e1', 'a2'] This works fine for my purposes, what I need is an outer loop that goes through the original list again and appends my next request. ie. hitNum = 5 which will return: ['a2', 'b2', 'c2', 'd2', 'e2', 'a3'] and append it to the previous one. ie: ['a1', 'b1', 'c1', 'd1', 'e1', 'a2'] ['a2', 'b2', 'c2', 'd2', 'e2', 'a3'] not really sure how to do this right now though, been trying several methods with no good results. btw, just creating lagged values (sort of shift registers) on the incoming signal Many thanks, Dave Dave, You are going to need to supply us with more info to help. 1) Are you always going to want to get 6 elements from the list 2) Are you always going to want to step by 5 elements as your offset each time through the outer loop? 3) Is your requirement just to split inLst into equal length lists and append them together into a list? Depending on your answers this might be quite easy. -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: Checking a file's time stamp.
Christian Heimes wrote: William Purcell wrote: Hi all, I am wanting to check to see the last time a file was edited. For example, I have a directory containing two text files, file1.txt and file2.txt. I want to be able to process these files but only if they have been edited since the last time they were processed. I think that I want to be able to check the time stamp of each file. Can anyone tell me how to do that or point me in a better direction of checking the last time a file was edited? >>> import os >>> stat = os.stat("/etc/passwd") >>> print stat (33188, 362259, 2053L, 1, 0, 0, 1690, 1218550501, 1218118498, 1218118498) >>> dir(stat) ['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__str__', 'n_fields', 'n_sequence_fields', 'n_unnamed_fields', 'st_atime', 'st_blksize', 'st_blocks', 'st_ctime', 'st_dev', 'st_gid', 'st_ino', 'st_mode', 'st_mtime', 'st_nlink', 'st_rdev', 'st_size', 'st_uid'] >>> stat.st_mtime 1218118498.0 use these shortcuts, IMHO they are easier than os.stat. os.path.getmtime() - get modified time os.path.atime()- get last accessed time (careful some admins turn this off on their servers for performance reasons) os.path.ctime()- get creation time -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: Extract string from log file
[EMAIL PROTECTED] wrote: 203.114.10.66 - - [01/Aug/2008:05:41:21 +0300] "GET /stat.gif? stat=v&c=F-Secure&v=1.1%20Build%2014231&s=av%7BNorton %20360%20%28Symantec%20Corporation%29+69%3B%7Dsw%7BNorton %20360%20%28Symantec%20Corporation%29+69%3B%7Dfw%7BNorton %20360%20%28Symantec%20Corporation%29+5%3B%7Dv%7BMicrosoft%20Windows %20XP+insecure%3BMicrosoft%20Windows%20XP%20Professional+f %3B26027%3B26447%3B26003%3B22452%3B%7D&r=0.9496 HTTP/1.1" 200 43 "http://dfstage1.f-secure.com/fshc/1.1/release/devbw/1.1.14231/ card.html" "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727)" does anyone know how can i extract certain string from this log file using regular expression in python or using XML. can teach me. Joseph, You will get much more help on this list if you show us what you have actually tried so far to solve the problem on your own. Then post what is not working (with full tracebacks if there are any) and you will find that people will try to assist you. If you require help reading lines from a file or learning regular expressions, you really need to use Google to look for tutorials first. -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: Ascii to binary conversion
azrael wrote: looks nice. is there an oposite function of ord() so I could also bring a binary number also back to ascii. the speed matters if you plan to exchange about 10 M ascii chars and don't wont to wait a year for the results. :) On 9 kol, 15:39, John Machin <[EMAIL PROTECTED]> wrote: On Aug 9, 11:18 pm, azrael <[EMAIL PROTECTED]> wrote: Hy folks, I googled, and searched, and can not bealive that I have not found a built in way to convert the easy and elegant python way a function to easily convert simple ascii data to binary and back. I've written some my own but they were pretty slow using binascii linbrary with hexifly and unhexifly functions conbined with a lookuptable of binary and hex values. Any idea how to easily write a function that recieves a character or string and returns a binary number like: ascii("1") is converted to bin("00110001") Here's one way: def a2b(a): ...ai = ord(a) ...return ''.join('01'[(ai >> x) & 1] for x in xrange(7, -1, -1)) ... a2b('1') '00110001' a2b('2') '00110010' a2b(chr(0)) '' a2b(chr(255)) '' BUT ... why are you doing this so much that the speed matters??? Opposite of ord() is chr(). These functions have been available in every language I've used for the last 30 years. I would suggest that you might want to spend a little time reading a good Python book and to work through the tutorial. It will be worth your investment of time. -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: Large production environments using ZODB/ZOE?
Phillip B Oldham wrote: I've been reading a lot recently on ZODB/ZOE, but I've not seen any reference to its use in large-scale production envrironments. Are there any real-world examples of ZODB/ZOE in use for a large system? By large, I'm thinking in terms of both horizontally-scaled systems and in terms of data storage size. I have been told (by one of the developers) that Viacom uses it for their video streaming website which is quite large. There is also a list of organizations on Zope's webside that is pretty impressive. -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: Trying to fix Invalid CSV File
Ryan Rosario wrote: On Aug 4, 8:30 am, Emile van Sebille <[EMAIL PROTECTED]> wrote: John Machin wrote: On Aug 4, 6:15 pm, Ryan Rosario <[EMAIL PROTECTED]> wrote: On Aug 4, 1:01 am, John Machin <[EMAIL PROTECTED]> wrote: On Aug 4, 5:49 pm, Ryan Rosario <[EMAIL PROTECTED]> wrote: Thanks Emile! Works almost perfectly, but is there some way I can adapt this to quote fields that contain a comma in them? Emile's snippet is pushing it through the csv reading process, to demonstrate that his series of replaces works (on your *sole* example, at least). Exactly -- just print out the results of the passed argument: >>> rec.replace(',"',",'''").replace('",',"''',").replace('"','""').replace("'''",'"') '123,"Here is some, text ""and some quoted text"" where the quotes should have been doubled",321' Where it won't work is if any of the field embedded quotes are next to commas. I'd run it against the file. Presumably, you've got a consistent field count expectation per record. Any resulting record not matching is suspect and will identify records this approach won't address. There's probably better ways, but sometimes it's fun to create executable line noise. :) Emile Thanks for your responses. I think John may be right that I am reading it a second time. I will take a look at the CSV reader documentation and see if that helps. Then once I run it I can see if I need to worry about the comma-next-to-quote issue. This is a perfect demonstration of why tab delimited files are so much better than comma and quote delimited. Virtually all software can handle table delimited as well as comma and quote delimited, but you would have none of these problems if you had used tab delimited. The chances of tabs being embedded in most data is virtually nil. -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: What Python looks like
iu2 wrote: Hi, This is a little bit strange post, but I'm curious... I learned Python from its tutorial step by step, and practicing writing small scripts. I haven't seen a Python program before knowing Python. I'm curious, what did Python code look like to those of you who have seen a bunch of Python code for the first time before knowing Python? (I can tell, for example, that seeing perl for the first time looked like C with many $$$, I could see "if" and "for" and "while" but they were meaningless. Or Lisp for the first time looked like many words, no operators, how could that make a program???) Thanks Python looked like pseudo-code that people would write before actually coding. I've always thought that Python was "Pseudo-code that runs". -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: import * and py2exe
Paul Sijben wrote: I am trying to turn my application into a WinXP exe. Py2exe has packaged all my files up into one humongous executable. When trying to run the app, it complains that it can not find modules I just saw it include. These invariably are modules that have been imported using from import * Apparently this confuses py2exe. Well I tried unconfusing it by giving those modules as imports in the first place! How can I convince the py2exe-generated app to look for those modules in its own .exe file??? Paul Don't try to bundle everything into a single .EXE (this is fraught with "issues"). Drop back to bundle=1 or bundle=2 and it should work for you. -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: Using two pythons in an application
Allen wrote: Larry Bates wrote: Allen wrote: I'm in the process of developing an application that will use Python for a scripting support. In light of the upcoming changes to Python, I was wondering if it is possible to link to and use two different versions of Python so that in the future, scripts could be migrated to the new version, and older scripts would still work as well. If so are there any code examples of this. Brian Vanderburg II Unlike languages you pay for, Python has on real motivation to "obsolete" old versions of Python (e.g. to force you to pay of an upgrade). You can still get version 1.5.2 of Python and it is MANY years old and most could consider quite obsolete. I just would not worry about it and stick with 2.5/2.6 for development and begin looking at Python 3.0 so I can learn what's new and exciting. -Larry I agree. I had wanted for scripts of the program to be able to use the new string format method that is only in py3k, but I'm currently looking into other template solutions. Brian Vanderburg II There are many good ones around that you can look at: http://www.webwareforpython.org/Papers/Templates/ -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: from Tkinter import *,win = Tk() "from Tkinter import *"
Pierre Dagenais wrote: from Tkinter import * win = Tk() If I type those two lines at the command prompt (in WindowsXP) I get a new window on my screen. Yet if I copy those lines in a file called test.py and then run "python test.py" at the command prompt I am returned to the command prompt and nothing shows up on the screen. Is this normal behavior or is it a bug? Thanks to all who responded to my previous post, it was quite helpfull. The window opens and closes so fast you can't see it. You will need to put something in the window and start a message loop for it to stay up there. -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: Using two pythons in an application
Allen wrote: I'm in the process of developing an application that will use Python for a scripting support. In light of the upcoming changes to Python, I was wondering if it is possible to link to and use two different versions of Python so that in the future, scripts could be migrated to the new version, and older scripts would still work as well. If so are there any code examples of this. Brian Vanderburg II Unlike languages you pay for, Python has on real motivation to "obsolete" old versions of Python (e.g. to force you to pay of an upgrade). You can still get version 1.5.2 of Python and it is MANY years old and most could consider quite obsolete. I just would not worry about it and stick with 2.5/2.6 for development and begin looking at Python 3.0 so I can learn what's new and exciting. -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: Decimals not equalling themselves (e.g. 0.2 = 0.2000000001)
CNiall wrote: I am very new to Python (I started learning it just yesterday), but I have encountered a problem. I want to make a simple script that calculates the n-th root of a given number (e.g. 4th root of 625--obviously five, but it's just an example :P), and because there is no nth-root function in Python I will do this with something like x**(1/n). However, with some, but not all, decimals, they do not seem to 'equal themselves'. This is probably a bad way of expressing what I mean, so I'll give an example: >>> 0.5 0.5 >>> 0.25 0.25 >>> 0.125 0.125 >>> 0.2 0.20001 >>> 0.33 0.33002 As you can see, the last two decimals are very slightly inaccurate. However, it appears that when n in 1/n is a power of two, the decimal does not get 'thrown off'. How might I make Python recognise 0.2 as 0.2 and not 0.20001? This discrepancy is very minor, but it makes the whole n-th root calculator inaccurate. :\ What are they teaching in computer science classes these days? -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: raw_input on several lines
TP wrote: Hi everybody, When using raw_input(), the input of the user ends when he types Return on his keyboard. How can I change this behavior, so that another action is needed to stop the input? For example, CTRL-G. It would allow the user to input several lines. Thanks Julien Just put raw_input() in a loop and check for something. Actually a blank line would probably work best in that case. Not tested, but you will get the idea: lines = list() print 'Enter your text (empty line to quit)' while 1: line = raw_input('') if line.strip() == '': break lines.append(line) -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: I donä't get while-loops
ssecorp wrote: in read2 it never quits when I write quit, why? def read(): expr = raw_input("Lisp> ") if expr != "quit": print parse(expr) read() else: print "Good session!" def read2(): expr = "" while expr != "quit": expr = raw_input("Lisp> ") print parse(expr) read2() print "Good session!" That's because read2() is being called recursively making expr be always a blank string the first time you go through the loop. Delete the call to read2() that is inside your while loop and try. -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: Searching for some kind of data type
Giampaolo Rodola' wrote: Hi, for an FTP server I wrote I'd need to group the FTP commands in one table that defines the command itself, the syntax string, required permission, whether it requires authorization, whether it takes argument and whether there's a need to validate the path from the argument. The more obvious way I found to do that is something like this: class CommandProperty: def __init__(self, perm, auth_needed, arg_needed, check_path, syntax): self.perm = perm self.auth_needed = auth_needed self.arg_needed = arg_needed self.check_path = check_path self.syntax = syntax ftp_cmds = { "ABOR" : CommandProperty(perm=None, auth_needed=True, arg_needed=False, check_path=False, syntax="ABOR (abort transfer)."), "APPE" : CommandProperty(perm='a', auth_needed=True, arg_needed=True, check_path=True, syntax="APPE file-name (append data to an existent file)."), "CDUP" : CommandProperty(perm='e', auth_needed=True,arg_needed=False, check_path=False, syntax="CDUP (go to parentdirectory)."), ... ... ... } ...but I find it somewhat redundant and... "ugly". I was wondering if there was some kind of data type which could better fit such purpose or if someone could suggest me some other approach to do this same thing. Maybe using a dictionary is not the better choice here. Thanks in advance --- Giampaolo http://code.google.com/p/pyftpdlib/ Seems completely reasonable to me. You might just consider using keyword arguments in the __init__ method and eliminate the dictionary altogether. Not tested, but you will get the idea: class CommandProperty: def __init__(self, perm = perm, auth_needed = True, arg_needed = True, check_path = False, syntax = syntax): self.perm = perm self.auth_needed = auth_needed self.arg_needed = arg_needed self.check_path = check_path self.syntax = syntax ftpCommands = dict( ABOR = CommandProperty(perm = None, arg_needed = False, syntax="ABOR (abort transfer)."), APPE = CommandProperty(perm = 'a', check_path=True, syntax = "APPE file-name (append data to" \ "an existent file)."), CDUP = CommandProperty(perm= 'e', arg_needed = False, syntax="CDUP (go> to parentdirectory)."), ... ... ... ) IMHO this is a "little" easier to manage because you can take advantage of the default values for keyword arguments to eliminate some of the arguments. Hope this helps, Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: Python COM
[EMAIL PROTECTED] wrote: I have implemented a COM in C++,buy i don't know how to use this COM in python. For example: the COM's ProgID is "MyCOM1.AdvMethod".this COM have two interfaces,the default interface's name is IAdvMethod,the second interface's name is IBasicMethod. How do i use those interfaces in python.Thank you very much,please answer my question in code. Suggestion: Post this to comp.python.windows instead of here. I think you will find that a better place for this question. -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: static variables in Python?
kj wrote: Yet another noob question... Is there a way to mimic C's static variables in Python? Or something like it? The idea is to equip a given function with a set of constants that belong only to it, so as not to clutter the global namespace with variables that are not needed elsewhere. For example, in Perl one can define a function foo like this *foo = do { my $x = expensive_call(); sub { return do_stuff_with( $x, @_ ); } }; In this case, foo is defined by assigning to it a closure that has an associated variable, $x, in its scope. Is there an equivalent in Python? Thanks! kynn First names in Python are just that, names that point to objects. Those objects can contain any type of information including other objects. They are NOT buckets where things are stored. 1) Names (variables in Perl/C) defined within a Python function are placed in its local namespace. They are not visible in the global namespace. 2) Yes you can have a local name point to a global. This is often used in classes with attributes because looking up local is somewhat quicker than looking up the class attribute. def foo(): x = expensive_call return do_stuff_with(x()) In this particular case it doesn't really help. It would be more useful in something like: class foo(object): def __init__(self, initialvalue = 0) self.currentvalue = initialvalue def longloopingmethod(self, listtosum): currentvalue = self.currentvalue for v in listtosum: currentvalue += v BTW - There are BETTER ways to sum a list, so this is just an example. -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: Suggestions for creating a PDF table
Kirk Strauser wrote: Short question: Is there a good library for generating HTML-style tables with the equivalent of colspans, automatically sized columns, etc. that can render directly to PDF? Longer question: I'm re-doing a big chunk of locally-written code. I have a report-generating function that takes a list of lists of lists as input and returns either a PDF, an HTML table, or an Excel spreadsheet as requested. For example, input might look like: makereport('html', headers=['Invoice number', 'Customer', 'Price'], data=[ [['123', 'John Doe', '$50.00'], ['Ordered on 2008-01-01 via the website']], [['124', 'Peter Bilt', '$25.99'], ['Mail via African swallow']] ]) This would result in HTML like: Invoice number Customer Price 123 John Doe $50.00 Ordered on 2008-01-01 via the website 124 Peter Bilt $25.99 Mail via African swallow Note particularly how the explanatory notes for each invoice are similar in appearance to the "primary" report lines they're associated with. Now, I have a similar transformation to PDF via pdflatex. This works fairly well but requires a bunch of temp files and subprocesses, and I've never been 100% happy with the LaTeX output (you have to calculate your own column widths, for instance). Since I plan to re-write this anyway, I'd like to find a more widely used library if one was available. ReportLab seemed *almost* perfect, except that it doesn't support colspans. As I hope I demonstrated in the example, most of our reports depend on that ability. So, again, any thoughts on a PDF generator that can generate tables with the same kind of flexibility as HTML? It does support the equivalent of colspans. See page 75 of the userguide manual. -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: We programming
srinivasan srinivas wrote: Hi, Could someone suggest me better python modules for developing web programming related projects like web-pages download and uopload?? Thanks, Srini Explore your hobbies and interests. Go to http://in.promos.yahoo.com/groups/ urllib, urllib2, httplib All depends on what you want to do with them. -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: write unsigned integer 32 bits to socket
[EMAIL PROTECTED] wrote: On Sun, Jul 27, 2008 at 7:01 PM, Larry Bates <[EMAIL PROTECTED]> wrote: [EMAIL PROTECTED] wrote: i want to send unsigned 32 bit integer to socket, and looking for something equivalent to this method... http://livedocs.adobe.com/flex/2/langref/flash/net/Socket.html#writeUnsignedInt() is there such method / library available in python?! You will need to use struct module to build the 4 byte value and then send it. Something like (not tested): import struct us32bit = struct.pack("I", value) s.send(us32bit) thanks a lot!!! just to make sure if I want 32 bit or 4 bytes then should I use the short or integer or long? this is short struct.pack('!h',3) '\x00\x03' this is integer struct.pack('!i',3) '\x00\x00\x00\x03' this is long struct.pack('!l',3) '\x00\x00\x00\x03' Short is 16 bits, Integer is 32 bits, long is 64 bits (as I read and have found). -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: write unsigned integer 32 bits to socket
[EMAIL PROTECTED] wrote: hi i want to send unsigned 32 bit integer to socket, and looking for something equivalent to this method... http://livedocs.adobe.com/flex/2/langref/flash/net/Socket.html#writeUnsignedInt() is there such method / library available in python?! this is as far as i have gotten along s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(('127.0.0.1',3000)) You will need to use struct module to build the 4 byte value and then send it. Something like (not tested): import struct us32bit = struct.pack("I", value) s.send(us32bit) -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: Where is the correct round() method?
josh logan wrote: Hello, I need a round function that _always_ rounds to the higher integer if the argument is equidistant between two integers. In Python 3.0, this is not the advertised behavior of the built-in function round() as seen below: round(0.5) 0 round(1.5) 2 round(2.5) 2 I would think this is a common need, but I cannot find a function in the Python library to do it. I wrote my own, but did I miss such a method in my search of the Python library? Thanks I think what you want is something like: math.ceil(x-0.4) -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: Stripping parts of a path
Tim Cook wrote: Hi All, I just ran into an issue with the rstrip method when using it on path strings. When executing a function I have a need to strip off a portion of the current working directory and add on a path to a log file. Initially this worked great but then I added a branch in SVN which caused the path to contain 'LNCCWorkshop'. The rstrip() then began removing the characters 'shop' leaving an incorrect path to the log file. When I hard coded this path it worked okay but then did the same thing later in the file when I needed to point to a database. The code worked fine with a different path. Here are some code fragments. logfile=os.getcwd().rstrip('src/oship/atbldr')+'/oship/log/at_build_errors.log' this worked when the path was: /home/tim/ref_impl_python/TRUNK/oship/src/oship/atbldr the code above returns: /home/tim/ref_impl_python/TRUNK/oship/log/at_build_errors.log but when I tried a branches version that has the path: /home/tim/ref_impl_python/BRANCHES/LNCCWorkshop/oship/src/oship/atbldr it SHOULD return: /home/tim/ref_impl_python/BRANCHES/LNCCWorkshop/oship/log/at_build_errors.log but I get: /home/tim/ref_impl_python/BRANCHES/LNCCWork/oship/log/at_build_errors.log logfile=os.getcwd() print logfile is correct; but when I add the .rstrip('src/oship/atbldr') it also strips the 'shop' off of LNCCWorkshop and returns /home/tim/ref_impl_python/BRANCHES/LNCCWork/oship/log/at_build_errors.log I had two other people looking at this as we did troubleshooting and we could not determine the cause. It is repeatable with this path name. In resolution I renamed the branch to just LNCC and it works fine. Thoughts? Tim Always helps to consult documentation when things don't work. Help on built-in function rstrip: rstrip(...) S.rstrip([chars]) -> string or unicode Return a copy of the string S with trailing whitespace removed. If chars is given and not None, remove characters in chars instead. If chars is unicode, S will be converted to unicode before stripping If you give chars to rstrip() it removes all those characters from the string not that substring. -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: object persistency, store instances relationship externally
King wrote: This is a new test for object persistency. I am trying to store the relationship between instances externally. It's not working as expected. May be I am doing it in wrong way. Any suggestions? import shelve class attrib(object): pass class node(object): def __init__(self): self.a = attrib() self.b = attrib() self.c = attrib() self.d = attrib() a = node() #store pair relationship. This relationship is created at run time. lst = [[a.a, a.b], [a.c, a.d]] #Write objects into file shelf = shelve.open('shelve_test_01.txt', writeback=True) shelf['node'] = a shelf['lst'] = lst shelf.sync() shelf.close() #Read objects from file shelf = shelve.open('shelve_test_01.txt', 'r') a = shelf['node'] lst = shelf['lst'] print a.a, a.b, a.c, a.d #lst does not contains the relationship of object 'a''s attributes, instead it's creating new instances #of 'attrib' class print lst You may want to take a look at Zope's ZODB. -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: os.walk question
Fredrik Lundh wrote: Lanny wrote: How would one make a list of the files in the top directory using os.walk. I need to pick a random file from said list. if you want a list of files from a single directory, use listdir, not walk: >>> import os, random >>> random.choice(os.listdir("/")) 'python25' Or use glob. import glob random.choice([f for f in glob.glob(root, "*")]) -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Written in C?
Marc 'BlackJack' Rintsch wrote: On Mon, 21 Jul 2008 18:12:54 +0200, mk wrote: Seriously, though, would there be any advantage in re-implementing Python in e.g. C++? Not that current implementation is bad, anything but, but if you're not careful, the fact that lists are implemented as C arrays can bite your rear from time to time (it recently bit mine while using lxml). Suppose C++ re-implementation used some other data structure (like linked list, possibly with twists like having an array containing pointers to 1st linked list elements to speed lookups up), which would be a bit slower on average perhaps, but it would behave better re deletion? An operation that most people avoid because of the penalty of "shifting down" all elements after the deleted one. Pythonistas tend to build new lists without unwanted elements instead. I can't even remember when I deleted something from a list in the past. Ciao, Marc 'BlackJack' Rintsch When I use os.walk and need to remove directories or files. Seems to be the only way to do the in-place delete that is required. But you are right, it is very seldom. -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Written in C?
Grant Edwards wrote: On 2008-07-22, Larry Bates <[EMAIL PROTECTED]> wrote: Grant Edwards wrote: On 2008-07-22, Larry Bates <[EMAIL PROTECTED]> wrote: You talk about "writing it in assembly language for each MPU chip". Actually it is even better than that. We now have these modern inventions, called compilers that do that type of work for us. They translate high level instructions, not into assembler but into machine language. Actually, all of the compilers I'm familiar with (gcc and a handful of cross compilers for various microprocessors) translate from high-level languages (e.g. C, C++) into assembly, which is then assembled into relocatable object files, which are then linked/loaded to produce machine language. I just learned something I did not know. I was under the impression that they translated directly to machine code without ever actually generating Assembler text files. There may indeed be compilers that work that way. On Unix systems (which is what I work with) compilers have traditionally generated assembly language files. Seems like a waste to generate the text and turn around run that through the assembler, but what do I know. I guess that way the compiler can have pluggable assembler back-ends. Since you probably need an assembler anyway, generating assembly-language in the compiler prevents you from having to duplicate a bunch of object-code-generation code in two places. I'm not sure I understand what you mean here. The code generation phase of the top level compiler would have to generate assembler mnemonics instead of just generating machine coded directly. At that point it should be just as easy to generate machine code, unless you take advantage of macros, or other helpers provided in the assembly phase. My "compiler" work was way back on mainframes and the ones I worked with definitely didn't produce assembler then needed to be run through the assembler. They created likable objects directly. But that was over 30 years ago! All this may be a moot point, because assembler is just a mnemonic representations of machine language anyway. -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: How do I compare files?
Clay Hobbs wrote: I am making a program that (with urllib) that downloads two jpeg files and, if they are different, displays the new one. I need to find a way to compare two files in Python. How is this done? -- Ratfink Use md5 to calculate checksum: import md5 md5file1 = md5.md5(open(filename1).read()).hexdigest() md5file2 = md5.md5(open(filename2).read()).hexdigest() if md5file1 != mdfile2: # # Do whatever you want # -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: Iterating Through List or Tuple
Samir wrote: Is there a way to loop or iterate through a list/tuple in such a way that when you reach the end, you start over at the beginning? For example, suppose I define a list "daysOfWeek" such that: daysOfWeek = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'] If today is Sunday, I can set the variable "day" to today by: i = iter(daysOfWeek) day = i.next() print day sunday If I want to find out the day of the week 2 days from now, then this code works ok: for x in xrange(2): day = i.next() print day tuesday However, when extending my range beyond the number of items in the list, I receive an error. For example, if I want to find out the day of the week 11 days from today, I get this: for x in xrange(11): day = i.next() Traceback (most recent call last): File "", line 1, in for x in xrange(11): day = i.next() StopIteration Is there a way to easily loop through a list or tuple (and starting over at the beginning when reaching the end) without having to resort to an "if" or "while" statement? (My question concerns the more general use of lists and tuples, not necessarily determining days of the week. I know about using "import datetime" and "from calendar import weekday" but thought that using the days of the week would best illustrate my problem.) As always, thanks in advance. Samir >>> import itertools >>> i = itertools.cycle(daysOfWeek) >>> i.next() 'sunday' >>> i.next() 'monday' . . . >>> i.next() 'saturday' >>> i.next() 'sunday' -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: Authentication for XML-RPC Calls
whitemice wrote: The only documentation regarding doing authentication for XML-RPC I can find is - "Both the HTTP and HTTPS transports support the URL syntax extension for HTTP Basic Authentication: http://user:[EMAIL PROTECTED]:port/path. The user:pass portion will be base64-encoded as an HTTP `Authorization' header, and sent to the remote server as part of the connection process when invoking an XML-RPC method. You only need to use this if the remote server requires a Basic Authentication user and password." - from http://docs.python.org/lib/module-xmlrpclib.html Is this really the only way to do authentication for XML-RPC calls? Like this: server = xmlrpclib.Server('http://adam:[EMAIL PROTECTED]/zidestore/so/ adam/' This works, but is pretty ugly. Is there no way to setup the authentication through properties (like in most XML-RPC bindings), like: server = xmlrpclib.Server('http://localhost/zidestore/so/adam/' server.Username = 'adam' server.Password = 'fred123' Just write a little factory class that does it for you: import urlparse class myauth(object): def __init__(self, scheme = None, domain = None, path = None): self.scheme = scheme self.domain = domain self.path = path self.Username = None self.Password = None def __str__(self): for attr in ['scheme', 'domain', 'path', 'Username', 'Password']: if getattr(self, attr) is None: raise ValueError('No %s attribute value given' % attr) url=urlparse.urlunsplit((self.scheme, '%s:[EMAIL PROTECTED]' % (self.Username, self.Password, self.domain), self.path, '', '')) return url if __name__ == "__main__": auth = auth = myauth(scheme = 'http', domain = 'localhost', path='/zidestore/so/adam/') auth.Username = 'adam' auth.Password = 'fred123' print auth In program auth = myauth(scheme = 'http', domain = 'localhost', path = '/zidestore/so/adam') auth.Username = 'adam' auth.Password = 'fred123' print auth 'http://adam:[EMAIL PROTECTED]/params;/lib/module-xmlrpclib.html' >>> -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Written in C?
Grant Edwards wrote: On 2008-07-22, Larry Bates <[EMAIL PROTECTED]> wrote: You talk about "writing it in assembly language for each MPU chip". Actually it is even better than that. We now have these modern inventions, called compilers that do that type of work for us. They translate high level instructions, not into assembler but into machine language. Actually, all of the compilers I'm familiar with (gcc and a handful of cross compilers for various microprocessors) translate from high-level languages (e.g. C, C++) into assembly, which is then assembled into relocatable object files, which are then linked/loaded to produce machine language. I just learned something I did not know. I was under the impression that they translated directly to machine code without ever actually generating Assembler text files. Seems like a waste to generate the text and turn around run that through the assembler, but what do I know. I guess that way the compiler can have pluggable assembler back-ends. -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: Website Creation using Python
Amie wrote: Afternoon, I would like some help on how to create a website using the python programming language. I've tried using enamel, but had some problems because I could not create html tables and intergrating it with python, like you use it when coding in php. Any help would be appreciated. Thanks Python is not PHP. Page generation is done differently. You might take a look at Django's web framework: http://www.djangoproject.com/ or http://pylonshq.com/ WARNING - Python web frameworks are MUCH more powerful than just using PHP to place some dynamic content on a web page. For many people, PHP will still be an easy to implement solution if your project isn't very complex. As the complexity grows, the need for additional power and flexibility grows also. -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Written in C?
[EMAIL PROTECTED] wrote: I'm just learning about Python now and it sounds interesting. But I just read (on the Wiki page) that mainstream Python was written in C. That's what I was searching for: Python was written in what other language? See, my concern was something like: OK, if Python is so hot, then, hopefully someone is writing it in assembly language for each MPU chip out there. Otherwise, if, say, they've written it in C#, then it looks like the REAL, generally useful language to learn is C# and Python is akin to Visual Basic or something: a specialty languagewhereas REAL WORLD programmers who want to be generally useful go and learn C#. So I was suspecting the Python compiler or interpreter is written in a REAL language like C#. So, Wiki says it's written in C! It's almost as if it were an intentional trick...write your own, new language in an OLD, real world language that is passe. Compile it into executable modules of course, so it is a real, working compiler, alright. But the SOURCE is some old, high level language which no one wants to use anymore! So now you've got a hot new language package and no one can say "well, it is written in, the SOURCE code is written in, a REAL language." No, it's not! The source is some outdated language and compiler and no one is going to prefer learning THAT to learning your hot new language! I'm not dissing Python, here. Just noting that, if it is written in C, that throws a curve at me in trying to balance the value of learning Python vs. some other major language. SPSS (was and may still be) written in Fortran and the Fortran compiler was written in C. But NOBODY would suggest that you try to solve the problems that SPSS is used for in C. You talk about "writing it in assembly language for each MPU chip". Actually it is even better than that. We now have these modern inventions, called compilers that do that type of work for us. They translate high level instructions, not into assembler but into machine language. -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: Trying to solve a python/mechanize "error 500" http error
bruce wrote: i'm getting the following error: mechanize._response.httperror_seek_wrapper: HTTP Error 500: i'm running python 5.1 and mechanize 0.1.7b I have no idea as to what I have to change/modify/include to handle this issue. The link that I'm testing is at the bottom of the page. When I insert the link into the browser, I actually get an err page.. so, I suspect that there is a handler that I should be able to modify/use to handle this situation... Thoughts/Comments will be greatly appreciated... Thanks the output is: www = www.1800ink.com url2= http://www.quantcast.com/www.1800ink.com/traffic Traceback (most recent call last): File "./reseller_scrape_child.py", line 288, in q1 = shopfuncs.quant(rhref) File "/adkiller/shopfuncs.py", line 56, in quant br.open(url2) File "build/bdist.linux-x86_64/egg/mechanize/_mechanize.py", line 203, in open File "build/bdist.linux-x86_64/egg/mechanize/_mechanize.py", line 254, in _mech_open mechanize._response.httperror_seek_wrapper: HTTP Error 500: [EMAIL PROTECTED] adkiller]# ./reseller_scrape_child.py my code segment looks like: from mechanize import Browser import mechanize br = Browser() user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' values1 = {'name' : 'Michael Foord', 'location' : 'Northampton', 'language' : 'Python' } headers = { 'User-Agent' : user_agent } #br.set_cookiejar(cj) br.set_handle_redirect(True) br.set_handle_referer(True) br.set_handle_robots(False) br.addheaders = [('User-Agent', 'Firefox')] url2 ="http://www.quantcast.com//traffic"; #gets the page (url) from the quantcast app url2=url2.replace("",url) print "url2=",url2 br.open(url2) === this works ok for most of the sites.. but something weird is happening with the actual page: http://www.quantcast.com/www.1800ink.com/traffic thanks... Looking up 500 error (here http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html) gives me: 10.5.1 500 Internal Server Error The server encountered an unexpected condition which prevented it from fulfilling the request. On some servers (Amazon), when you get 500 errors you are instructed to try the request again. I don't know about this server. -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: persistent deque (continued)
castironpi wrote: Some time ago, I was asking about the feasibility of a persistent deque, a double-ended queue. It runs into the typical space allocation problems. If you're storing a pickle, you have to allocate and fragment the file you've opened, since pickles can be variable-length strings; i.e. if the new data is too long, blank out its entry, and grow the file. If you're storing a data-type, you lose Python's dynamic-type advantages, as well as its long integers, as they can be any length. If you change the object in the deque, such as when using any mutable type, you have to update the container too. Does anyone have any experience storing pickles (I am aware of the similarities to shelf) to a database? Can the file system facilitate the variable-length string problem? How feasible is a length-of-length - length - data solution to the unbounded integer problem? Is there any alternative to completely re-pickling a large (say 1k pickled) object you only change slightly? What other issues are there? Is a hybrid-storage type possible, that stores the contents of its Python-allocated memory block to disk, including reference count, even if it's a lot slower? The object could not contain any references to objects not allocated on disk. A first approach is for the file to look like this: 00 data 01 data 02 01 data 03 data 04 02 data 05 data 06 Append would add: 03 data 07 data 08 AppendLeft would add: -01 data 09 data 0a Pop would remove 03, PopLeft would remove -01. You would need a length-and-head index to make 'rotate' available. Remove would run a worst-case risk of renumbering half of the indices stored, plus a rotate. It is so much easier to implement this using a database table that IMHO most people would go that route. -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: how to create GUI dynamically
[EMAIL PROTECTED] wrote: Hi; i m working on a project where i need run time creation of GUI. i have some no. of entities for which i want checkboxes in front of them which can be checked/ unchecked by user. But the problem is that the number and name of entities is not fixed and it depends on the file which is used as input. So is there any way to tackle this problem. By the way ; i use Boa constructor (zope editor) for GUI now. regards pawan pundir All the GUI tookits (Tkinter, wxWindows, QT) allow you to build the GUI dynamically. -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: Please recommend a RPC system working with twisted.
??? wrote: Hi all, I'm looking for an RPC system working with twisted. 1. Binary. I want it run faster than any xml based RPC. 2. Bidirectional. Unlike HTTP, on which the client has to poll the sever for events, the server should "call" the client's method to notify events. 3. C/Python support. Part of the system shall be written in C. 4. Could easily integrated with twisted. Unfortunately, there seems no such resolution existed. So maybe I have to give up some requirements. --- It would be wonderful if ICE could integrate with twisted! Twisted Perspective Broker? -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: Run as Service
[EMAIL PROTECTED] wrote: I have, in the past, used SRVANY to run a Python app as a Windows service. However, now I am interested in distributing my scripts and want to make it as painless for the end user as possible (hands-off is best :). How can you go about running a Python app as a Windows service without SRVANY? Pick up a copy of Mark Hammond's book "Python on Win32". It has an excellent chapter on using Win32 extensions to write Windows Services. Also you might consider looking at gmane.comp.python.windows usergroup. -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: create instance attributes for every method argument
Berco Beute wrote: I remember reading somewhere how to create an instance attribute for every method argument, but although Google is my friend, I can't seem to find it. This could likely be done way more elegant: = class Test(object): def __init__(self, a, b, c, d, e, f): self.a = a self.b = b self.c = c self.d = d = 2B IMHO you can't do much better than that with positional arguments, but you can if they are keyword arguments. class foo(object): def __init__(self, **kwargs): self.__dict__.update(kwargs) -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: py2exe issues with pictures and icons
Alexnb wrote: Hello I am sure most of you are familiar with py2exe. I am having a bit of a problem. See the program has a few pictures involved and the .ico it uses for the windows. However, the pictures are stored in the same directory as the source, something like: C:\Docs and settings\me\My docs\python\program. When I run the program for the interpreter, just as a .py, everything works just as it should. However, when I compile the main source as an .exe, and say let a friend try the program. It fails because it is missing the .ico. The catch, is I don't want to have it have to installed, at least at this point, I want it to be able to just run. So how can I make it just run from any computer with the files not being in the immediate directory. If that is not possible, how can I put them in the immediate directory and still make it work. Because that directory may change a lot so the path will change. Just a few questions. I hope someone out there can help me out! Windows can't read minds. The icon's/pictures have to either be in the same directory as the .exe or the .exe has to have a way to find them in another folder (e.g. via .ini config file). Takw a few minutes and go to: http://jrsoftware.org/isinfo.php It is a free Windows installer that I use to take py2exe, icons, pictures, .ini files, documentation, etc and wrap it all up into a nice, neat package that can be distributed as a single .exe. It will take a couple of hours, but it will be hours well spent (especially if you think you will do this more than once). Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: Framework recommendations for web service?
Phillip B Oldham wrote: We're looking at the next phase of development for our webapp, and the main focus will be to move the core from the app to a web service so other systems can use the data we've gathered (we're thinking along the lines of the XML API of Highrise from 37Signals). Its possible that we'll extend the service to allow access via vanilla XML, JSON, and YAML at some point, however we've decided to use Facebook's Thrift for connectivity initially to support as many techs as possible and also because our web interface for the app is written in PHP. As we're extracting the core we'll be translating it to Python to make use of the wealth of well-structured libraries and hopefully make the project shorter. However, we've hit a snag in choosing a framework around which to rebuild the service. It seems the more popular frameworks (django, turbogears) are all focused on providing web content. Since our core will be using thrift to communicate, we don't need templating, feeds, admin pages (django), or ajax (turbogears). What we *do* need is a lightweight, simple framework that will allow us to create a RESTful interface and throw code together fast. We'll probably go with SQLObject (unless we can extract the ORM from django - lazy evaluation would be very useful), and we're just looking for something fast and light to sit between that and the thrift interfaces we'll create. So, can anyone suggest a lightweight python framework which just does the essentials? You want thin and fast with little cruft and a focus on interfaces, look at Twisted. -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: Best Python packages?
Ben Sizer wrote: Although the standard library in Python is great, there are undoubtedly some great packages available from 3rd parties, and I've encountered a few almost by accident. However, I don't know how a user would become aware of many of these. http://pypi.python.org/pypi/ presumably lists most of the decent ones, but there's a lot there and little indication as to quality or popularity - great if you know exactly what you need, but not so great for just browsing. I'd love to have some way of finding out what hidden gems are out there in the Python world which could make my development a lot easier. Any suggestions? -- Ben Sizer Hang around this list for a little while and these "hidden gems" will become more apparent. -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: graphing lifelines
E. J. Gold is the Hi-Tech Shaman wrote: On Jul 15, 3:38 pm, Larry Bates <[EMAIL PROTECTED]> wrote: Certainly a "Hi-Tech Shaman" can whip something up to do this, right? Yes, well E.J. Gold is the Hi-Tech Shaman. I'm Terrence Brannon, stating that fact :) So, maybe EJ could whip up such a thing :) I like the sci.math answer I got the best and will go with that approach - http://groups.google.com/group/sci.math/browse_thread/thread/09b254718d4cbfeb# Hey you're the one using his email address ;-). -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: How to figure out if the platform is 32bit or 64bit?
David Lees wrote: [EMAIL PROTECTED] wrote: I need to know if I'm running on 32bit or 64bit ... so far I haven't come up with how to get this info via python. sys.platform returns what python was built on ... but not what the current system is. I thought platform.uname() or just platform.processor() would have done it, but python returns an empty string on windows. Any ideas? Thanks, Ken On my windows box this works: >>> platform.architecture() ('32bit', 'WindowsPE') David On Fedora Core 5 64-bit here is what I see: >>> import platform >>> platform.architecture() ('64bit', 'ELF') -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: Modify a string's value
[EMAIL PROTECTED] wrote: Hi everyone, I've heard that a 'str' object is immutable. But is there *any* way to modify a string's internal value? Thanks, Sebastian Why would you care? Just create a new string (with the changed contents) and let garbage collection take care of the old one when all the references to it have gone away. Since these types of questions seem to appear almost every day on this list, this Python stuff is so much different than old languages people have hard time making the conceptual "jump". You can basically quite worrying about how/where things are stored, they just are. -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: Python internals
Ben Finney wrote: Larry Bates <[EMAIL PROTECTED]> writes: Names are pointers in Python that point to values in memory. The term "pointer" carries much extra baggage for a programmer thinking of C (as the original poster is). Python names give no access to the "address" of the value, and don't need to be "de-referenced". I've had better success explaining Python names to such people in terms of "references": there is no "address" and no "de-reference" needed. Access the name, and you get its value. On the other hand, I prefer to avoid using either of those concepts, and talk in terms of "name tags" or "sticky notes". Names (and other references, like list elements) attach to the object, and have no other value or purpose. They don't affect the object they're attached to; they are entirely independent of other bindings to the same object; they re-bind to another object with no history of what they were bound to previously. The analogy is quite robust, and carries none of the confusing baggage of "variable" or "pointer" or other overloaded language terms. You are, of course, correct. Since I'm not a C programmer, the term pointer doesn't carry the same "baggage" as it might to others. The "problem" I had when I first started is that people were using such "vague" terms like names, tags, etc. that it had no meaning to me. I like your idea of "references". -Larry -- http://mail.python.org/mailman/listinfo/python-list