sub typing built in type with common attributes. Am I right?
I am new to python and getting into classes. Here I am trying to create subtype of built in types with some additional attributes and function. 'Attributes' is the main class and holds all the common attributes that requires by these subtypes. This is what I came out with. I need to know whether everything is right here ? or there are some better ways to do it. class Attribute(object): """ Common attributes and methods for custom types """ def __init__(self, name=None, type=None, range=None, label=None): #read only attributes self._name = name self._type = type self._range = range #read/write attribute self.label = label #make read only attributes name = property(lambda self: self._name) type = property(lambda self: self._type) range = property(lambda self: self._range) class Float(float, Attribute): '''Custom Float class with some additional attributes.''' __slots__ = ['_Attribute__name', '_Attribute__type', '_Attribute__range', 'label'] def __new__(cls, value=0.0, *args, **kwargs): return float.__new__(cls, value) def __init__(self, value=0.0, name=None, label=None, type=None, range=(0.0, 1.0)): super(Float, self).__init__(name=name, label=label, type=type, range=range) def __str__(self): return '{ %s }' % (float.__str__(self)) class Int(int, Attribute): '''Custom Int class with some additional attributes.''' __slots__ = ['_Attribute__name', '_Attribute__type', '_Attribute__range', 'label'] def __new__(cls, value=0.0, *args, **kwargs): return int.__new__(cls, value) def __init__(self, value=0.0, name=None, label=None, type=None, range=(0.0, 1.0)): super(Int, self).__init__(name=name, label=label, type=type, range=range) def __str__(self): return '{ %s }' % (int.__str__(self)) -- http://mail.python.org/mailman/listinfo/python-list
Re: sub typing built in type with common attributes. Am I right?
My mistake... The correct __slots__ is like: __slots__ = ['_Attribute_name', '_Attribute_type', '_Attribute_range', 'label'] Could you please suggest an alternative or code improvement for the matter. Prashant -- http://mail.python.org/mailman/listinfo/python-list
Re: sub typing built in type with common attributes. Am I right?
Thanks Michaud, You have actually solved an another problem by 'make_subtype_with_attr' function. What actually I am trying to do here is to create custom types using built in types to use in my application. For example , float2, float3, color, vector, point, normal, matrix etc. The reason being creating as individual subtypes is because each subtypes has it's own set of functions as well as common functions and attributes defined in 'Attribute' class. Although I won't be doing any math using subtypes like multiply a color by another color or add a float and a color. One of the important function that every subtype has is to print itself in a special format. For 'color' it would be : 'type' + 'name' + ' = color('+color[0]+', '+color[2]+', '+color[2]+');' Result: color myColor = color(0.5, 0.1, 1.0); I hope this will make things more clearer. If you do have any suggestions then please send it across. Prashant -- http://mail.python.org/mailman/listinfo/python-list
Safe guard .pyc files
After google a lot I didn't find any way to safe guard .pyc files from decompilation. One way I can think of is to wrap important functions/classes as a libraby using SWIG/PyRex, but again is going to be a lot more of work and doesn't sound good. any body out there has done something for this? -- http://mail.python.org/mailman/listinfo/python-list
instance comparison
I am facing a problem where I am really confused about it. I am trying to compare to instances using: if inst1 == inst2 These instances have a overridden method __str__ which returns same string. The condition result is true although they are different instances. If I use: if id(inst1) == id(inst2) The results is false. What's happening here? If I am trying to store this pair in a set where other instances are already stored, but it's not storing it. Although I am sure that there is no pair already stored of same but even if Set is comparing by using string return by __str__ method then it won't. How do I solve this? Is this mean when you have overridden __str__ method then it comapre with results of __str__ or else it will comapre whether they are the same instances? -- http://mail.python.org/mailman/listinfo/python-list
Re: instance comparison
The only methods I do have in class is __init__ and __str__. How ever inst1 and inst2 is coming from a dictionary where I stored them with a unique id. inst1 = stored[id] inst2 = stored[id] Is this makes a difference? I will rip down the piece of code giving me problem and post. -- http://mail.python.org/mailman/listinfo/python-list
Re: instance comparison
No, The the class is not subclass of another one. Problem still persist. The code is pretty huge and I am trying to post the information as clear as possible. -- http://mail.python.org/mailman/listinfo/python-list
object persistency, store instances relationship externally
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 -- http://mail.python.org/mailman/listinfo/python-list
Re: 2d graphics - what module to use?
Use python's default GUI tkinter's drawing functions or you can use wxPython GUI kit or you can use pyopengl. If you are only interested to draw sin waves or math functions that you should give try to matlab at www.mathworks.com -- http://mail.python.org/mailman/listinfo/python-list
Re: object persistency, store instances relationship externally
Thanks Fredrik, It helped a lot and this is really an amazing this I have discovered today. :-)) -- http://mail.python.org/mailman/listinfo/python-list
Read .txt file like .py file
I have a text file and contents are: Help=""" Code is written by xteam. """ value = 0.0 How do I read this file like python syntax. What I mean is first readline operation should return complete declaration of 'Help' variable. If I evaluate this string then it should create a 'Help' variable with it's value. May be something related to 'parsing' would help but I don't know much. -- http://mail.python.org/mailman/listinfo/python-list
Re: Read .txt file like .py file
Well, I have a look to into compiler module and gave it a try using compiler.parseFile and compiler.walk but I haven't got what I need here. -- http://mail.python.org/mailman/listinfo/python-list
Multiline text in XML file
Is there any other way to define multiline text in a XML file: -- http://mail.python.org/mailman/listinfo/python-list
python subprocess know how
Hi, I am using subprocess module to execute a command and print results back. startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW my_process = subprocess.Popen(cmnd, startupinfo=startupinfo) print repr(my_process.communicate()[0]) This code executes on pressing a button (wxPython). The problem is until command is not done and it's results are not printed, program halts and button keep the state of pushed. Is there any way to avoid this? Thanks -- http://mail.python.org/mailman/listinfo/python-list
what is next for you, a great opportunity waiting for
www.hrconsultant.tk -- http://mail.python.org/mailman/listinfo/python-list
conditional __init__
class A(object): def __init__(self): pass def printme(self): print "I am A" class B(object): def __init__(self): pass def printme(self): print "I am B" class K(A, B): def __init__(self, value=0): if value == 0: A.__init__(self) print "__init__ A" elif value == 1: B.__init__(self) print "__init__ B" self.printme() o = K(value=1) Output >>__init__ B >>I am A In above code "B" is correctly getting initialized as per condition. How ever method "printme" is printing "I am A". Instead it has to print "I am B" because "B" is the one that has been initialized. What's wrong here? Is there a better/another way to do conditional initialization as needed above? Cheers Prashant Python 2.6.2 Win XP 32 -- http://mail.python.org/mailman/listinfo/python-list
object indexing and item assignment
class MyFloat(object): def __init__(self, value=0.): self.value = value def set(self, value): self.value = value def get(self): return self.value class MyColor(object): def __init__(self, value=(0,0,0)): self.value = (MyFloat(value[0]), MyFloat(value[1]), MyFloat(value[2])) def set(self, value): self.value[0].set(value[0]) self.value[1].set(value[1]) self.value[2].set(value[2]) def get(self): return (self.value[0].get(), self.value[1].get(), self.value[2].get()) col = MyColor() col[0].set(0.5) # 'MyColor' object does not support indexing col[0] = 0.5 # 'MyColor' object does not support item assignment The last two lines of the script produce errors. (written as comments). I know it won't work as I am expecting. One solution I can think of is to rewrite MyFloat and MyColor by sub classing default python types "float and "tuple". Is this the only solution? Prashant Python 2.6.2 Win XP 32 -- http://mail.python.org/mailman/listinfo/python-list
object serialization as python scripts
I have looked upon various object serialization de-serialization techniques. (shelve, pickle, anydbm, custom xml format etc.) What I personally feel that instead of all these methods for saving the objects it would be easier to save the data as python scripts itself. In this case, loading the data is merely to run the script in the context itself. Need some expert advice and pointers here. Is there any thing (module, script, doc, article) helpful out there for the concern? Prashant Python 2.6.2 Win XP 32 -- http://mail.python.org/mailman/listinfo/python-list
Re: object serialization as python scripts
> Why is it easier than the above mentioned - they are *there* (except the > custom xml), and just can be used. What don't they do you want to do? > > Other than that, and even security issues put aside, I don't see much > difference between pickle and python code, except the latter being more > verbose. Which suits humans, but other than that has no advantage. > > Diez My application is PyQt based and objects that I am trying to save are couple of QGraphicsItem instances. You can't save instances of QGraphicsItem using pickle or shelve. Custom xml format would be a real pain as you have to write code for writing/reading both. I am aware of security issue but over all there are only 5 statements I have to use to get the entire information back. I can do syntax checking and other stuff before I should execute the script. Another reason is that data should be in human readable form. Prashant Python 2.6.2 Win XP 32 -- http://mail.python.org/mailman/listinfo/python-list
Get attribute this way
Python's getattr, setattr and __getattribute__ commands works fine with python types. For example: print o.__getattribute__("name") print getattr(o, "name") This is the easiest way to get an attribute using a string. In my case the "Node" class load/creates all the attributes from a xml file. Example There are certain atrributes of compound type. Example: # Array of colors, Here we are referring first color and second element (green) self.gradient.colors[0][1] = 0.5 # Array of floats, referring first element self.gradient.positions[0] = 1.0 Color, color array and floats are all custom classes. Now question is how to get these compound attributes using string as we do with default singular attributes. Example: getattr(o, "gradient.colors[0][1] ") I need this to save the data of nodes->attributes into a custom xml format, when loading this data back, I create the node first and then setup values from the saved xml file. Prashant Python 2.6.2 Win XP 32 -- http://mail.python.org/mailman/listinfo/python-list
Re: Get attribute this way
Writing/Reading data to xml is not a problem. The problem is when I have to write to attributes in xml, where a connections has been established. XML: While reading back I have to convert both source and destination strings into object so that I can call connections function using source and target attributes. Prashant Python 2.6.2 Win XP 32 -- http://mail.python.org/mailman/listinfo/python-list
Re: Get attribute this way
"eval" can solve this problem right away but I am concerned about security issues. If not "eval" could you suggest something more efficient way. It won't be a big deal to change the format as application is still at development stage? Thanks Prashant Python 2.6.2 Win XP 32 -- http://mail.python.org/mailman/listinfo/python-list
No duplicate variable
class A(object): def __init__(self, value=0.): self.value = value class B(A): def __init__(self, value=None): A.__init__(self) self.value = value obj = B() When "B" initializes, it overwrite "value" variable of "A". How do I make sure that no variable should not be defined with names of "A" in "B"? Prashant -- http://mail.python.org/mailman/listinfo/python-list
Python compiled modules are too big in size (even after strip)
Hi, I have just compiled python 2.6.5 from sources on ubuntu "hardy" 8.04. I have used a simple script to do everything in one go: ./configure --enable-shared make make install Python is compiled and installed successfully. However the modules(_socket.so, _random.so etc) are two big in terms of file size. They are around 4.5-5.0 mb each. I have used "strip strip-all *.so", but still size is around 1.5 mb each. This is still too big compare to size of modules on ubuntu karmic's pre installed python 2.6.5. Am I missing something here? Do I have to re-configure or re-compile the python again from sources? Regards Prashant -- http://mail.python.org/mailman/listinfo/python-list
Re: Python compiled modules are too big in size (even after strip)
Hi Jon, I do have a limited skill sets in c/c++ and also new on linux. I think I am missing some flags or anything when I am compiling python from sources. Still hoping that some one point me out the missing link. Cheers Prashant -- http://mail.python.org/mailman/listinfo/python-list
executable builder
Hi, I am trying to build python a cross platform python executable builder to deploy python app. I tried various tools such as py2exe, pyinstaller, cx_freeze but some how they are not upto the mark except py2exe. Unfortunately py2exe is working only on windows based systems. The task is divide into 3 steps: 1. Collect all the modules(.pyo, .pyd, .dll, etc) required for your project. 2. set up temporary environment for python 3. run main.py using :python.exe main.py Initially I won't be creating an executable using main.py. I would be using shell scripting to execute the main.py. Q1. Which is most efficient way to fine all the modules required by your "main.py". Q2. For example, I have copied all the modules in "d:\project\lib\*.*" python.exe, python.dll, ms*.dll, main.py are copied to "d: \project". Before executing "python.exe main.py", I have to set up an environment var and point it to "d:\project\lib", so that python.exe can find the path for searching/loading modules. How do I do that? Q3. How do you convert your "main.py" into an executable? Prashant -- http://mail.python.org/mailman/listinfo/python-list
simple python deployment tool
Hi, I am writing a python package deployment tool for linux based platforms. I have tried various existing tool sets but none of them is up to the mark and they have their own issues. Initially I'll start with simple approach. 1. Find all the modules/packages and copy to "lib" directory. 2. Find python's *.so dependencies(system libs) and copy them to "syslib" 3. Copy python(executable) and libpython2.6.so.1.0 into "dist" directory. 4. Set up temp environment 5. Run main script using "python .py" The idea is to produce a cleaner directory structure. Neither I am creating a boot loader nor I am converting main script file into executable. It's plain vanilla stuff. Using above steps I have pulled down a package using wxPython's demo example "pySketch.py". You can download the archive from here: http://rapidshare.com/files/405255400/dist.zip (Note : It's for linux users.) After extracting the contents, run the executable file using "./run". This file sets temporary environment variables and execute "pySketch.py". I apologize for the archive size as all the systems libs are also included. This is eventually not working. I think I am not able to set up temporary environment properly or may be missing some other stuff. I would appreciate if some one can point out mistakes. Here is the practical approach: /lib (all python libs, files and third party modules.) /syslib (all the system libs. libX*.*, cairo, etc.) python (executable) pySketch.py run.sh Contents of "run.sh". -- set LD_LIBRARY_PATH="syslib/" set PYTHONPATH="/lib" python pySketch.py Cheers Prashant -- http://mail.python.org/mailman/listinfo/python-list
Re: simple python deployment tool
On Jul 8, 2:21 pm, Alexander Kapps wrote: > King wrote: > > Hi, > > > I am writing a python package deployment tool for linux based > > platforms. I have tried various existing > > tool sets but none of them is up to the mark and they have their own > > issues. Initially I'll start with simple approach. > > I'm sorry, but your approach is not going to work. The Right Way(tm) > is to not ship any external libraries, but let the user install the > dependencies with the distro's package manager. And to not try to > build custom packages, but to let the package maintainers of the > different distros package your application for you. Yes, you an do this by creating a .deb package that will take care of installing the required libraries. It may possible that either required version is not available in the distro's repository or the one available is older one then required. So best deal would be to ship at least all the python's libs along with your package. > > 1. Find all the modules/packages and copy to "lib" directory. > > 2. Find python's *.so dependencies(system libs) and copy them to > > "syslib" > > That would include all the way down to libc, your archive is going > to be huge, but the actual problem is, what if the libc isn't > compatible with the kernel, what if the WX, GTK, X11, etc libraries > aren't compatible with the running Xserver? You are right here. It seems there is no standard definition of system libraries on linux. To over come the problem of binary compatibility, I am using ubuntu (hardy) which is on glibc 2.7. Every other external python library including python is compiled on hardy. This is would give you maximum chances that libs would be compatible in case if you run on any other distro which is using glibc >=2.7 > End of the story is, you would need to package a minimal (but almost > complete) Linux system into your package, which of course is not > want you want. > > > 3. Copy python(executable) and libpython2.6.so.1.0 into "dist" > > directory. > > 4. Set up temp environment > > 5. Run main script using "python .py" > > > The idea is to produce a cleaner directory structure. Neither I am > > creating a boot loader nor I am converting main script > > file into executable. It's plain vanilla stuff. > > It's not vanilla stuff, but a very hard problem. In fact you are > fighting against the whole system structure. Ok, forget about system libs(libX*.* etc.), I don't know why it sounds too complicated. I am hoping it should work and eventually it's easier then tools that create an executable using bootloader. The problem is in setting the correct python environment. Prashant -- http://mail.python.org/mailman/listinfo/python-list
zipimport (.pyd & .so) files.
Hi, The 'zipimport' modules can only import (.py & .pyc) files from a zip file and doesn't support importing .pyd & .so files. Recently I was examining the code of Py2Exe (python package deployment tool) and I have found that it is using a module 'zipextimporter' that can import dlls(.pyd) modules from a zip file. It is based on the concept of loading library form memory. You can find out more about here: http://www.joachim-bauch.de/tutorials/loading-a-dll-from-memory/ It's strictly for windows platform. I would like to know from expert python users and linux programmers, how we can achieve similar functionality on linux platform? I do have limited c/c++ skill sets but I would love to give a try. Cheers Prashant -- http://mail.python.org/mailman/listinfo/python-list
Re: zipimport (.pyd & .so) files.
I think I am trying to open a can of worms. It's better to leave the idea for now. Prashant -- http://mail.python.org/mailman/listinfo/python-list
Node based architecture
Hi, I am planning to build a generic node based framework using python. I would start with a simple image editing application. I hope that experienced users understands what am I trying to say here. In simple words: LoaderNode : Load Image from disk OperatorNode : Performs a specific task on data and spit output(data) OutputNode : Get the data from OperatorNode(output) and writes image to disk. Graph : A collection Nodes that are inter connected. The question is how to process graph? Here is a simple representation: class Integer(object): """ A simple integer node. """ def __init__(self, value=0): self.value = value def output(self): return self.value class OperatorAdd(object): """ A simple operator node """ def __init__(self, integerInst1=None, integerInst2=None): self.a = integerInst1.output() self.b = integerInst2.output() def compute(self): return Integer(self.a + self.b) def output(self): return self.compute() "Integer" is data node and "OperatorAdd" is a compute node. Imagine I have created two integer nodes and their output is going to "OperatorNode". One way to solve is to represent every node using a string and then you can write these series of string which actually is a python code that you can execute and get the result. Example: compute = """ i1 = Integer(2) i2 = Integer(3) i3 = OperatorAdd(i1, i2).output() """ Now you can execute "compute" variable using exec(compute) or something like that. This would do the job but I would like to know the opinion of more experienced users. One advantage of above mentioned string method is that it can be saved to disk and later you can load/compute it again. Cheers Prashant -- http://mail.python.org/mailman/listinfo/python-list
Compile python executable only for package deployment on Linux
Hi, I have created a simple tool(python script) that creates a self sufficient package ready for deployment. Current implementation is based on shell scripting to set environment for the app and finally execute "python main.py". I am planning to convert "main.py" into an executable. The plan is to rip the unnecessary code from source code that produce python executable such as command line arguments etc, use "main.py" as python string (hardcoded inside executable source) and execute it using "exec" or similar methods and finally creates executable. Am I right here? Is this is the correct approach? For example a simple script: import os import math print math.sin(23.0) print os.getenv("PATH") Once I'll convert above script as i have mentioned above in an executable say: "myapp", executing "myapp" will print messages on console. Cheers Prashant -- http://mail.python.org/mailman/listinfo/python-list
Re: Compile python executable only for package deployment on Linux
Hi Stefan, Well, the idea is similar to package tools like pyinstaller or cx_freeze. There approach is slightly different then what I intend to do here. You have to pass the name of the script to python executable("python main.py") in order to execute it. What I mean here is to create python executable using python executable source code only(not compilation of entire python using source code) and insert "main.py" contents in source code(hardcoded) and produce a new executable. When you run that executable, it should run the "main.py", which was hard coded while building using fixed string or any other method. The executable is actually a modified version of python executable. It won't take any argument because we'll rip that piece of code out. Hope this will clear out. Cheers prashant -- http://mail.python.org/mailman/listinfo/python-list
Undo-Redo, copy instance, custom events and a problem
Hi, I am developing an app using wxPython. The Undo-Redo implementation is based on storing pre & post state of an attribute. You store the instance before changing the value and store the instance after changing the values. While undoing or redoing, you copy/replace the current state with stored once. For color attribute as soon as you choose a color, here is the code: # Custom Event evt = ValueChangeEvent(EVT_COLOR_CHANGED.typeId, self.GetId()) # Store Pre State evt.SetPreState(copy.copy(self.attribute)) # Change the newly selected color self.attribute.setValue(R,G,B) # Store Post State evt.SetPostState(copy.copy(self.attribute)) # Throw Custom Event self.GetEventHandler().ProcessEvent(evt) Both states are copied as new instance with correct values. The problem is when this event is getting fired. evt.GetPreState().GetValue() is showing the post color value. Although GetPreState() & GetPostState() are showing two different instances but I have no idea why values are not coming/stored correctly. Some where in between is messed up and post-state values are copied in pre-state. On a side note, self.attribute.setValue takes three floating values for R,G & B colors but stored them as a text. Similarly self.attribute.getValue() converts text into float and returns. Is there anything related to scope or something? Cheers Prashant -- http://mail.python.org/mailman/listinfo/python-list
relative imports and sub-module execution
Hi, After reading couple of docs and articles, I have implemented a simple test package with nested modules. When running "main.py", everything is working fine. Some of my sub- modules has some small test routines for debug purpose. It's because I am using relative package imports at the top, I am not able to run these sub modules individually. For example, this works when running from main.py Here is example structure main.py __init__.py core/ __init__.py folder1 __init__.py f1a.py f1b.py folder2 __init__.py f2a.py f2b.py in folder2/f2b.py, I am importing from core.folder1 import f1a print f1a.myvar Now I can't execute 'f2b.py' individually. It's giving an error: ImportError: No module named core.folder2 Is this mean when you have created a package where modules are using relative imports, they can't execute individually? Another solution that I have discovered is using sys.path. Check this: import sys import os sys.path.append(os.path.abspath("../../")) from core.folder1 import f1a print f1a.myvar This works fine and easier too. I can execute modules individually as well as package is also working. Are there any disadvantages when using above technique? Couple of articles suggests that this is a bad practice and should not be used. Need some clarifications. Thanks Prashant -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Gotcha's?
A common one used to be expecting .sort() to return, rather than mutate (as it does). Same with .reverse() - sorted and reversed have this covered, not sure how common a gotcha it is any more. Iain On Wednesday, 4 April 2012 23:34:20 UTC+1, Miki Tebeka wrote: > Greetings, > > I'm going to give a "Python Gotcha's" talk at work. > If you have an interesting/common "Gotcha" (warts/dark corners ...) please > share. > > (Note that I want over http://wiki.python.org/moin/PythonWarts already). > > Thanks, > -- > Miki -- http://mail.python.org/mailman/listinfo/python-list
Re: tiny script has memory leak
On Friday, 11 May 2012 22:29:39 UTC+1, gry wrote: > sys.version --> '2.6 (r26:66714, Feb 21 2009, 02:16:04) \n[GCC 4.3.2 > [gcc-4_3-branch revision 141291]] > I thought this script would be very lean and fast, but with a large > value for n (like 15), it uses 26G of virtural memory, and things > start to crumble. > > #!/usr/bin/env python > '''write a file of random integers. args are: file-name how-many''' > import sys, random > > f = open(sys.argv[1], 'w') > n = int(sys.argv[2]) > for i in xrange(n): > print >>f, random.randint(0, sys.maxint) > f.close() > > What's using so much memory? > What would be a better way to do this? (aside from checking arg > values and types, I know...) Ran OK for me, python 2.4.1 on Windows 7 Iain -- http://mail.python.org/mailman/listinfo/python-list
problem python
hi im new in python and i have a problem about when i type python in my command line console i get an error message 'import site' failed; use -v for traceback Python 2.4.3 (#1, May 5 2011, 18:44:23) [GCC 4.1.2 20080704 (Red Hat 4.1.2-50)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> what is going on and how i can fix it thanks in andvance-- http://mail.python.org/mailman/listinfo/python-list
Re: use of index (beginner's question)
On Apr 28, 2:45 am, Chris Angelico wrote: > Incidentally, you're allowed to put the comma on the last item too: > > lists = [ > ['pig', 'horse', 'moose'], > ['62327', '49123', '79115'], > ] > > Often makes for easier maintenance, especially when you append > array/list elements. > > Chris Angelico I did not know this. Very useful! Iain -- http://mail.python.org/mailman/listinfo/python-list
Re: Code Review
On May 25, 2:44 pm, ad wrote: > On May 25, 4:06 am, Ulrich Eckhardt > wrote: > > > > > ad wrote: > > > Please review the code pasted below. I am wondering what other ways > > > there are of performing the same tasks. > > > On a unix system, you would call "find" with according arguments and then > > handle the found files with "-exec rm ..." or something like that, but I see > > you are on MS Windows. > > > > args = parser.parse_args() > > > > dictKeys = (vars(args)) > > > The first of these looks okay, while I don't get the additional brackets in > > the second one. Another habit I observe here is the Hungarian notation of > > prefixing the type to the name and using camelCaps. PEP 8 (IIRC) has > > something to say on the preferred naming. I'm not 100% against encoding the > > type in the variable name in Python, since it lacks static type checking, I > > would have chosen "key_dict" here though, or, due to the small size of the > > overall program just "keys". > > > > print (HowManyDays) > > > This puzzled me at first, again the useless additional brackets I thought. > > However, in Python 3, "print" is a function, so that is correct. Still, it > > should be "print(foo)" not "print (foo)". > > > > for files in DirListing: > > > > # Get the absolute path of the file name > > > abspath = (os.path.join(WhatDirectory, files)) > > > "files" is just the name of a single file, right? In that case the name is a > > bit confusing. > > > > # Get the date from seven days ago > > > WeekOldFileDate = CurrentTime - DaysToDelete > > > You are repeating this calculation for every file in the loop. > > > > if FileCreationTime < WeekOldFileDate: > > > #check if the object is a file > > > if os.path.isfile(abspath): os.remove(abspath) > > > # It is not a file it is a directory > > > elif os.path.isdir(abspath): shutil.rmtree(abspath) > > > I'm not sure, but I believe you could use shutil.rmtree() for both files and > > directories. In any case, be prepared for the file still being open or > > otherwise read-only, i.e. for having to handle errors. > > > Also, what if a directory is old but the content is new? Would this cause > > the non-old content to be deleted? > > > Cheers! > > > Uli > > > -- > > Domino Laser GmbH > > Geschäftsführer: Thorsten Föcking, Amtsgericht Hamburg HR B62 932 > > Thank you guys very much for the excellent points. I will use this > information as a reference as I write more code and fix up the > existing script. > > Chris, thank you for putting so much time into your post! > > Until we type again... Wrote something to do the same basic thing a little while ago. Less verbose than yours, and it only does files, not folders. If I was going to do folders though, I'd do them by recursing into them and pruning files, and not go by the folder modify date, which I don't think changes the way you think it changes (for example, if a file inside a folder got updated such that it shouln't be deleted it still will be with your code if the folder modify date is old [this is on Windows]) import os, glob, time, sys if len(sys.argv) < 3: print "USAGE: %s " % sys.argv[0] sys.exit(1) pattern = sys.argv[1] days = int(sys.argv[2]) threshold = days * 24 * 60 * 60 t = time.time() for f in glob.glob(pattern): if t - os.stat(f)[9] > threshold: print f os.remove(f) -- http://mail.python.org/mailman/listinfo/python-list
Re: How can I set the size of a window with tkinter?
Tor Erik Sønvisen wrote: > Hi > > I create a canvas that is to big for the default window-size, so it gets cut > to fit... > How can I increase the window-size to make sure the canvas fits? > > regards tores root=Tk() root.minsize(300,300) root.geometry("500x500") will limit the window to be at least 300x300, and set it straight away to 500x500. Iain -- http://mail.python.org/mailman/listinfo/python-list
Re: backreferences
Amy Dillavou wrote: > Can someone help me with understanding how python uses backreferences? > I need to remember the item that was last matched by the re engine but i > cant seem to understand anything that I find on backreferences. if I > want to access the last match do i use \number or is there something > else i have to do? > > heres part of my code: > renDate = re.compile("$((\d){4}-(\d){2}-(\d){2}))") > renDate.search(l) > if(exist.search(l) and str(lastmodDate) < \1): #i need help here with \1 > > Thanks in advance > A.D I haven't had to use backreferences yet, so I don't know offhand how to go about it. What I do know is that this online book is very useful: http://gnosis.cx/TPiP/ Chapter 3 covers REs: http://gnosis.cx/TPiP/chap3.txt >From what I remember, in python you can use numbered backreferences (up to 99), or named ones. Iain -- http://mail.python.org/mailman/listinfo/python-list
Re: [PIL]: Question On Changing Colour
Andrea Gavana wrote: > I have tried your solution, Terry: > > > new_hue # your 'basic color', just the hue part > > rgb_base # color from the basic button image > > rgb_new # the new color you want to replace rgb_base with > > > > rgb_new = hsv_to_rgb( (new_hue,) + rgb_to_hsv(rgb_base)[1:]) > > > thanks a lot for your suggestion! However, either I did not understand it > correctly or I am doing something stupid in my code. Here is a small > example: > > from colorsys import * > > # that is the old colour --> GREY > rgb_old = (0.7, 0.7, 0.7) > > # Transform the new colour in HSV > hsv_old = rgb_to_hsv(rgb_old[0], rgb_old[1], rgb_old[2]) > > # this is the new colour --> BLUE > rgb_new = (0.0, 0.0, 1.0) > > # Transform the new colour in HSV > hsv_new = rgb_to_hsv(rgb_new[0], rgb_new[1], rgb_new[2]) > > # I take only the Hue part of the new colour > new_hue = hsv_new[0] > > # Get the new colour > rgb_new = hsv_to_rgb(new_hue, hsv_old[1], hsv_old[2]) > > print rgb_old > print rgb_new > print rgb_old == rgb_new > > > This prints: > > (0.69996, 0.69996, 0.69996) > (0.69996, 0.69996, 0.69996) > True > > So, no matter what colour I choose as a "new" colour, the Hue part of the > new colour doesn't change in RGB. In other words, leaving the old value for > "Saturation" and "Value" makes the presence of the "Hue" part useless. But > why in the world does this happen? If a colour is defined by 3 values, > changes in every single value should change the colour too... Not with HSV. The hue determines which 'color' it will be - red, blue, indigo, whatever. That Saturation determined how vibrant this 'color' will be. V is brightness (I can't remember what the V actually stands for). Each of these values scales from 0 to 1, or 0% to 100%, however you want to thiink about it. If you try and picture the gradient you'd get by plotting this range as a line, then: The H line would be a spectrum of colours, like a rainbow. Say we pick H to be RGB #FF - Red The S line would be a gradient ranging from grey (absense of color) to red. The V line would be a gradient ranging from black (completely dark) to red. So on the HSV scale, grey is represented by a saturation of 0 - meaning none of H is present in the color; the color in question being determined purely by it's brightness (V). So when you pick your HSV triplet for a grey color, you have to set S to 0. You can set H to anything at all - because S is 0, no tint of H will appear in the color at all. Iain http://www.snakebomb.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Python vs Ruby
Tom Anderson wrote: > On Fri, 21 Oct 2005, vdrab wrote: > > > You can tell everything is well in the world of dynamic languages when > > someone posts a question with nuclear flame war potential like "python > > vs. ruby" and after a while people go off singing hymns about the beauty > > of Scheme... > > +1 QOTW > > > I love this place. > > Someone should really try posting a similar question on c.l.perl and > seeing how they react ... > > tom SSsh! Xah Lee might be listening! Iain -- http://mail.python.org/mailman/listinfo/python-list
Re: more than 100 capturing groups in a regex
Fredrik Lundh wrote: > Joerg Schuster wrote: > > > I just want to use more than 100 capturing groups. > > define "more" (101, 200, 1000, 10, ... ?) > > The Zero-One-Infinity Rule: http://www.catb.org/~esr/jargon/html/Z/Zero-One-Infinity-Rule.html Iain -- http://mail.python.org/mailman/listinfo/python-list
Re: more than 100 capturing groups in a regex
Steven D'Aprano wrote: > On Tue, 25 Oct 2005 05:17:52 -0700, Iain King wrote: > > > > > Fredrik Lundh wrote: > >> Joerg Schuster wrote: > >> > >> > I just want to use more than 100 capturing groups. > >> > >> define "more" (101, 200, 1000, 10, ... ?) > >> > >> > > > > The Zero-One-Infinity Rule: > > > > http://www.catb.org/~esr/jargon/html/Z/Zero-One-Infinity-Rule.html > > > Nice in principle, not always practical. Sometimes the choice is, "do you > want it today with arbitrary limits, or six months from now with bugs > but no limits?" > > If assigning arbitrary limits prevents worse problems, well, then go for > the limit. For instance, anyone who has fought browser pops ups ("close > one window, and ten more open") may have wished that the browser > implemented an arbitrary limit of, say, ten pop ups. Or even zero :-) > Well, exactly. Why limit to ten? The user is either going to want to see pop-ups, or not. So either limit to 0, or to infinity (and indeed, this is what most browsers do). Note the jargon entry defines infinity in this case to me the largest possible amount given whatever ram/disk space/processing power you have available. Also: These arbitrary limits tend to stem from languages which predominantly use fixed size arrays - DIM in basic, or malloc in C. The native python component is the list, which doesn't have a max size, so these problems should be encountered less in python code; by it's nature, python steers you away from this mistake. Iain -- http://mail.python.org/mailman/listinfo/python-list
Re: more than 100 capturing groups in a regex
Steven D'Aprano wrote: > On Tue, 25 Oct 2005 06:30:35 -0700, Iain King wrote: > > > > > Steven D'Aprano wrote: > >> On Tue, 25 Oct 2005 05:17:52 -0700, Iain King wrote: > >> > >> > > >> > Fredrik Lundh wrote: > >> >> Joerg Schuster wrote: > >> >> > >> >> > I just want to use more than 100 capturing groups. > >> >> > >> >> define "more" (101, 200, 1000, 10, ... ?) > >> >> > >> >> > >> > > >> > The Zero-One-Infinity Rule: > >> > > >> > http://www.catb.org/~esr/jargon/html/Z/Zero-One-Infinity-Rule.html > >> > >> > >> Nice in principle, not always practical. Sometimes the choice is, "do you > >> want it today with arbitrary limits, or six months from now with bugs > >> but no limits?" > >> > >> If assigning arbitrary limits prevents worse problems, well, then go for > >> the limit. For instance, anyone who has fought browser pops ups ("close > >> one window, and ten more open") may have wished that the browser > >> implemented an arbitrary limit of, say, ten pop ups. Or even zero :-) > >> > > > > Well, exactly. Why limit to ten? The user is either going to want to > > see pop-ups, or not. So either limit to 0, or to infinity (and indeed, > > this is what most browsers do). > > I haven't been troubled by exponentially increasing numbers of pop up > windows for a long, long time. But consider your question "why limit to > ten?" in a wider context. > > Elevators always have a weight limit: the lift will operate up to N > kilograms, and stop at N+1. This limit is, in a sense, quite arbitrary, > since that value of N is well below the breaking point of the elevator > cables. Lift engineers, I'm told, use a safety factor of 10 (if the > cable will carry X kg without breaking, set N = X/10). This safety > factor is obviously arbitrary: a more cautious engineer might use a > factor of 100, or even 1000, while another might choose a factor of 5 or > 2 or even 1.1. If engineers followed your advice, they would build lifts > that either carried nothing at all, or accepted as much weight until the > cable stretched and snapped. > > Perhaps computer programmers would have fewer buffer overflow security > exploits if they took a leaf out of engineers' book and built in a few > more arbitrary safety factors into their data-handling routines. We can > argue whether 256 bytes is long enough for a URL or not, but I think we > can all agree that 3 MB for a URL is more than any person needs. > > When you are creating an iterative solution to a problem, the ending > condition is not always well-specified. Trig functions such as sine and > cosine are an easy case: although they theoretically require an infinite > number of terms to generate an exact answer, the terms will eventually > underflow to zero allowing us to stop the calculation. > > But unfortunately that isn't the case for all mathematical calculations. > Often, the terms of our sequence do not converge to zero, due to round-off > error. Our answer cycles backwards and forwards between two or more > floating point approximations, e.g. 1.276805 <-> 1.276804. The developer > must make an arbitrary choice to stop after N iterations, if the answer > has not converged. Zero iterations is clearly pointless. One is useless. > And infinite iterations will simply never return an answer. So an > arbitrary choice for N is the only sensible way out. > > In a database, we might like to associate (say) multiple phone numbers > with a single account. Most good databases will allow you to do that, but > there is still the question of how to collect that information: you have > to provide some sort of user interface. Now, perhaps you are willing to > build some sort of web-based front-end that allows the user to add new > fields, put their phone number in the new field, with no limit. But > perhaps you are also collecting data using paper forms. So you make an > arbitrary choice: leave two (or three, or ten) boxes for phone numbers. > > There are many other reasons why you might decide rationally to impose an > arbitrary limit on some process -- arbitrary does not necessarily mean > "for no good reason". Just make sure that the reason is a good one. > > > -- > Steven. I think we are arguing at cross-purposes, mainly because the term' arbitrary' has snuck in. The actual rule: "Allow none of foo, one of foo, or any number of foo." A rule of thumb for software design, which instructs
Re: more than 100 capturing groups in a regex
Fredrik Lundh wrote: > Iain King wrote: > > > Anyway, back to the OP: in this specific case, the cap of 100 groups in > > a RE seems random to me, so I think the rule applies. > > perhaps in the "indistinguishable from magic" sense. > > if you want to know why 100 is a reasonable and non-random choice, I > suggest checking the RE documentation for "99 groups" and the special > meaning of group 0. > > Ah, doh! Of course. Oh well then... still, doesn't python's RE engine support named groups? That would be cumbersome, but would allow you to go above 100... -- http://mail.python.org/mailman/listinfo/python-list
Re: Looping Problem (Generating files - only the last record generates a file)
[EMAIL PROTECTED] wrote: > Hello All, > > I have a problem with the program that should generate x number of txt > files (x is the number of records in the file datafile.txt). > > Once I execute the program (see below) only one file (instead of x > files) is created. The file created is based on the last record in > datafile.txt. > > The program is as follows: > > #! python > > HEADER = "This page displays longitude-latitude information" > SUBHEADER = "City" > > for line in open("datafile.txt"): > > > town, latlong = line.split('\t') > > f = open(town + ".txt", "w+") > > f.write(HEADER + "\n") > f.write(SUBHEADER + ": " + town + "\n") > f.write("LAT/LONG" + ": " + latlong + "\n") > f.close() > > > # end > > > > > > The datafile.txt is as follows (tab separated columns): > > > NYC - > Lima - > Rome - > > > > Once executed, the program will create a single file (named Rome.txt) > and it would not create files NYC.txt and Lima.txt as I would expect it > to do. > > I'd appreciate if you can pinpoint my error. > > Best, > > Vasa Did you try indenting the last five lines? Iain -- http://mail.python.org/mailman/listinfo/python-list
Re: Microsoft Hatred FAQ
David Blomstrom wrote: > A bit off topic, but it amazes me that people in the > web design/Internet industry don't take a more active > stance against Microsoft. > > Think about it: The health care industry has been > privatized in the U.S. I spent sixteen years in > education, another institution that has been > privatized. (It has largely become another Microsoft > subsidiary.) > > So here we have web designers, who are among the > freest people in the world, able to choose their > specialties, hours, fees and even where they work. Yet > they surrender to Microsoft's "standards" without a > fight. > > Frankly, I think every self-respecting webmaster ought > to be campaigning against Microsoft on their websites. > Tiny, simple messages like "Microsoft-Free" or "If you > like George AWOL Bush, you'll love Bill Gates," could > go a long ways in educating the public. > Or, you know, just code your website to be W3C compliant, which IE will invariably choke on. Iain -- http://mail.python.org/mailman/listinfo/python-list
Double replace or single re.sub?
I have some code that converts html into xhtml. For example, convert all tags into . Right now I need to do to string.replace calls for every tag: html = html.replace('','') html = html.replace('','') I can change this to a single call to re.sub: html = re.sub('<([/]*)i>', r'<\1em>', html) Would this be a quicker/better way of doing it? Iain -- http://mail.python.org/mailman/listinfo/python-list
Re: Top-quoting defined [was: namespace dictionaries ok?]
Duncan Booth wrote: > James Stroud wrote: > > > On Tuesday 25 October 2005 00:31, Duncan Booth wrote: > >> P.S. James, *please* could you avoid top-quoting > > > > Were it not for Steve Holden's providing me with a link off the list, > > I would have never known to what it is you are referring. I have read > > some relevant literature to find that this is more widely known as > > "top-posting". I'll go with majority rules here, but I would like to > > say that my lack of "netiquette" in this matter comes from > > practicality and not malice. > > No, I didn't think it was malice which is why I just added what I > considered to be a polite request at the end of my message. I assumed that > most people either knew the phrase or could find out in a few seconds using > Google so there wasn't much point in rehashing the arguments. Probably I > should have equally lambasted Ron for the heinous crime of bottom-quoting. > > In general, there are three ways to quote a message: top-quoting, which > forces people to read the message out of order; bottom-quoting which is > nearly as bad because it hides the new comments; and proper quoting in > context where you trim the message and put specific points under brief bits > of context. > Just to continue this off-topic argument :) - I've never heard the terms top-quoting, bottom-quoting. I've heard top-posting and bottom-posting before (lots). But regardless of however many people use top-quoting and bottom-quoting, surely you're using them the wrong way around? If I top-post, then that means that the quote is at the bottom, no? To quote someone's sig block: "To top-post is human, to bottom-post and snip is sublime." Iain -- http://mail.python.org/mailman/listinfo/python-list
Re: Double replace or single re.sub?
Mike Meyer wrote: > "Iain King" <[EMAIL PROTECTED]> writes: > > > I have some code that converts html into xhtml. For example, convert > > all tags into . Right now I need to do to string.replace calls > > for every tag: > > > > html = html.replace('','') > > html = html.replace('','') > > > > I can change this to a single call to re.sub: > > > > html = re.sub('<([/]*)i>', r'<\1em>', html) > > > > Would this be a quicker/better way of doing it? > > Maybe. You could measure it and see. But neither will work in the face > of attributes or whitespace in the tag. > > If you're going to parse [X]HTML, you really should use tools that are > designed for the job. If you have well-formed HTML, you can use the > htmllib parser in the standard library. If you have the usual crap one > finds on the web, I recommend BeautifulSoup. > Thanks. My initial post overstates the program a bit - what I actually have is a cgi script which outputs my LIveJournal, which I then server-side include in my home page (so my home page also displays the latest X entries in my livejournal). The only html I need to convert is the stuff that LJ spews out, which, while bad, isn't terrible, and is fairly consistent. The stuff I need to convert is mostly stuff I write myself in journal entries, so it doesn't have to be so comprehensive that I'd need something like BeautifulSoup. I'm not trying to parse it, just clean it up a little. Iain -- http://mail.python.org/mailman/listinfo/python-list
Re: Microsoft Hatred FAQ
David Schwartz wrote: > Roedy Green wrote: > > > On Sun, 16 Oct 2005 16:31:41 GMT, Roedy Green > > <[EMAIL PROTECTED]> wrote, quoted or > > indirectly quoted someone who said : > > >> I used to be a retailer of custom computers. MS used a dirty trick > >> to compete with IBM's OS/2. They said to me as a retailer. You must > >> buy a copy of our OS for EVERY machine you sell. The alternative is > >> to pay full retail for the OSes. > > > Through intimidation, MS managed to control the entire retail computer > > market in Vancouver BC to the extent you could not buy even the most > > stripped down computer without having to buy a copy of Windows with > > it, whether you wanted it or not. > > > > You might not want it because you bought OS/2. > > > > You might not want it because you already owned Windows from your > > older machine you were upgrading. > > > > You might not want it because somebody stole your machine and they did > > not steal all your software masters. > > Tell me, can you buy a new car without seats? Guess what, you have to > buy those seats whether you want them or not. > > Try to start a business selling competing seats for a new car. Your > seats may be cheaper, better, but how can you possibly compete when people > have to pay for factory car seats whether they want them or not? > > The real reason PCs were not available without Windows was because not > enough people wanted them that way to justify setting up a business to > provide them that way, and Microsoft was not going to let a business > parasitically use Windows to build a business that touted the advantages of > competing products. (Just as Burger King corporate will not you sell Big > Macs in the same store in which you sell Whoppers.) > > DS Don't you see how your metaphor doesn't work? It would only be fitting if Microsoft OWNED the outlet. Places which sell Whoppers are Burger King franchises, so of course they aren't going to sell Big Mac's. PC hardware stores do not belong to microsoft. There just isn't any correlation. Iain -- http://mail.python.org/mailman/listinfo/python-list
Re: Microsoft Hatred FAQ
David Schwartz wrote: > Roedy Green wrote: > > > The particular way MS threatened to put me out of business was by > > threatening to arm twist all wholesalers to refuse to sell MS product > > to me, which any retailer needed to survive in those days. > > Right, I get that. You owed your entire business to Microsoft. Without > their products, you would have had nothing, by your own admission. The way > you repay them is by trying to screw them -- attract people who come in only > because you offer Windows and then say "here's an OS that's better and > cheaper". Oh right. You're actually just a troll. Oh well. *plonk* Iain -- http://mail.python.org/mailman/listinfo/python-list
Re: need help extracting data from a text file
[EMAIL PROTECTED] wrote: > Hey there, > i have a text file with a bunch of values scattered throughout it. > i am needing to pull out a value that is in parenthesis right after a > certain word, > like the first time the word 'foo' is found, retrieve the values in the > next set of parenthesis (bar) and it would return 'bar' > > i think i can use re to do this, but is there some easier way? > thanks well, you can use string.find with offsets, but an re is probably a cleaner way to go. I'm not sure which way is faster - it'll depend on how many times you're searching compared to the overhead of setting up an re. start = textfile.find("foo(") + 4 # 4 being how long 'foo(' is end = textfile.find(")", start) value = textfile[start:end] Iain -- http://mail.python.org/mailman/listinfo/python-list
Re: need help extracting data from a text file
[EMAIL PROTECTED] wrote: > this is cool, it is only going to run about 10 times a day, > > the text is not written out like foo(bar) its more like > foo blah blah blah (bar) > then I guess you worked this out, but just for completeness: keywordPos = textfile.find("foo") start = textfile.find("(", keywordPos) end = textfile.find(")", start) value = textfile[start:end] Iain -- http://mail.python.org/mailman/listinfo/python-list
PNG processing with only base python install
My web server supports python CGI scripts, but I can't install anything else there - I can just use what they've provided. I want to process some PNG images - any ideas how I can do this with just the basic modules? Is there an image processing module written purely in Python? Iain -- http://mail.python.org/mailman/listinfo/python-list
Re: How to paste python code on wordpress?
Dan Lowe wrote: > On Nov 22, 2005, at 12:30 AM, could ildg wrote: > > > Thank you~ > > It works! > > but how can paste "<" and ">", please? > > these 2 symbols will also confuse wordpress and I can't publish > > what I want. > > Replace < with < > > Replace > with > > > (where those abbreviations stand for "less than" and "greater than") > > Before: if x < 5: > > After: if x < 5: > > Another common character in code that you "should" do similarly is > the double quote ("). For that, use " > > Before: if x == "foo": > > After: if x == "foo": > > -dan > > -- > Any society that needs disclaimers has too many lawyers. -Erik Pepke You don't *need* to replace with " However, you will need to replace any ampersands with & ( <, >, and & are characters with intrinsic qualities in html). You need to replace & before you replace anything else: if you do it after repalcing < and > you'll catch your < and >, ending up with < and > which is not what you want. Iain -- http://mail.python.org/mailman/listinfo/python-list
Re: Documentation suggestions
> The library reference has so many modules that the table of contents > is very large. Again, not really a problem that we can fix; splitting > it up into separate manuals doesn't seem like it would help. I like the Global Module Index in general - it allows quick access to exactly what I want. I would like a minor change to it though - stop words starting with a given letter rolling over to another column (for example, os.path is at the foot of one column, while ossaudiodev is at the head of the next), and provide links to each initial letter at the top of the page. Iain -- http://mail.python.org/mailman/listinfo/python-list
Re: Documentation suggestions
[EMAIL PROTECTED] wrote: > >> The library reference has so many modules that the table of contents > >> is very large. Again, not really a problem that we can fix; > >> splitting it up into separate manuals doesn't seem like it would > >> help. > > Iain> I like the Global Module Index in general - it allows quick access > Iain> to exactly what I want. I would like a minor change to it though > Iain> - stop words starting with a given letter rolling over to another > Iain> column (for example, os.path is at the foot of one column, while > Iain> ossaudiodev is at the head of the next), and provide links to each > Iain> initial letter at the top of the page. > > I know it's not what you asked for, but give > > http://staging.musi-cal.com/modindex/ > > a try. See if by dynamically migrating the most frequently requested > modules to the front of the section it becomes more manageable. > > Skip Well, the point of the GMI is to lookup whatever module you are currently having to use for the first time (at least it is for me). Giving easy access to the modules I've already had to look up (because they are common) doesn't really help - I've already accessed those. It'll be nice when I have to find some obscure feature I haven't used in them before, but really, all I'd like is an easy to use index :) Iain -- http://mail.python.org/mailman/listinfo/python-list
Re: Documentation suggestions
[EMAIL PROTECTED] wrote: > Iain> Well, the point of the GMI is to lookup whatever module you are > Iain> currently having to use for the first time (at least it is for > Iain> me). Giving easy access to the modules I've already had to look > Iain> up (because they are common) doesn't really help - I've already > Iain> accessed those. It'll be nice when I have to find some obscure > Iain> feature I haven't used in them before, but really, all I'd like is > Iain> an easy to use index :) > > Reorganizing the global module index isn't all that straightforward. It is > generated by latex2html. To change its layout would probaly require some > additional markup and mods to latex2html (not a pretty piece of code as I > understand it). > > OTOH, I find myself returning to the same module docs over and over again to > look up function arguments, regular expression syntax, that sort of thing. > Having to page down past dozens and dozens of modules I don't care about to > click on "sys" or "datetime" motivated me to write my little hack. > > Skip Argh, you made me look at the html again - at least now I know *why* it is so disgusting. I understand there's a new version coming out soon, hopefully in html 4 strict or xhtml. I'm sure at that point it'll be easier to use. I can wait. :) Iain -- http://mail.python.org/mailman/listinfo/python-list
socket setdefaulttimeout
I'm doing DNS lookups on common spam blacklists (such as SpamCop..and others) in an email filtering script. Sometimes, because the DNS server that is resolving the looksup can go down, it is important to make sure that the socket doesn't just hang there waiting for a response. After a recent system upgrade to Python 2.4.1 (from 2.2.2) I thought I could take advantage of the setdefaulttimeout in the socket module, to limit the amount of time the sockets take for a lookup. As a test, I set the default timout ridiculously low. But it doesn't seem to be having any effect. The sockets will take several seconds to make the connection and complete the lookups, even though I've set the timeout to millionths of a second, which I thought would ensure a timeout (sample script below). Am I doing something wrong? Do I misunderstand something? Is what I want to do simply not possible? Thanks for any tips. Example code follows signature... -- Sheila King http://www.thinkspot.net/sheila/ #!/usr/local/bin/python2.4 import socket import sys from time import time, asctime, localtime socket.setdefaulttimeout(.1) debugfile = "socketdebug.txt" def debug(data): timestamp = str(asctime(localtime(time( try: f = open(debugfile, 'a') f.write('\n*** %s ***\n' % timestamp) f.write('%s\n' % data) # 24-Dec-2003 -ctm- removed one linefeed f.close() except IOError: pass # do nothing if the file cannot be opened IPaddy = '220.108.204.114' if IPaddy: IPquads = IPaddy.split('.') IPquads.reverse() reverseIP = '.'.join(IPquads) bl_list = { 'bl.spamcop.net' : 'IP Address %s Rejected - see: http://spamcop.net/bl.shtml' % IPaddy, \ 'relays.ordb.org' : 'IP Address %s Rejected - see: http://ordb.org/' % IPaddy, \ 'list.dsbl.org' : 'IP Address %s Rejected - see: http://dsbl.org' % IPaddy} timing_done = 0 start_time = time() for host in bl_list.keys(): if host in bl_list.keys(): IPlookup = "%s.%s" % (reverseIP, host) try: debug(" IPlookup=%s=" % IPlookup) resolvesIP = socket.gethostbyname(IPlookup) debug(" resolvesIP=%s=" % resolvesIP) if resolvesIP.startswith('127.'): end_time = time() elapsed_time = end_time - start_time timing_done = 1 debug("Time elapsed for rDNS on bl_list: %f secs" % elapsed_time) debug("exiting--SPAM! id'd by %s" % host) print bl_list[host] sys.exit(0) except socket.gaierror: pass if not timing_done: end_time = time() elapsed_time = end_time - start_time debug("2nd try:Time elapsed for rDNS on bl_list: %f secs" % elapsed_time) -- http://mail.python.org/mailman/listinfo/python-list
Re: socket setdefaulttimeout
I do note that the setdefaulttimeout is accomplishing something in my full program. I am testing some error handling in the code at the moment, and am raising an exception to make the code go into the "except" blocks... The part that sends an error email notice bombed due to socket timeout. (well, until I raised the timeout to 3 seconds...) The last time I asked about this topic in the newsgroups...was a while back (like 2 or so years) and someone said that because the socket function that I'm trying to use is coded in C, rather than Python, that I could not use the timeoutsocket module (which was the only way prior to Python 2.3 to set timeouts on sockets). I wonder...is it possible this applies to the particular timeouts I'm trying to enforce on the "gethostbyname" DNS lookups? Insights appreciated -- http://mail.python.org/mailman/listinfo/python-list
Re: socket setdefaulttimeout
On 08/12/2005 22:37:22 Bryan Olson <[EMAIL PROTECTED]> wrote: > Sheila King wrote: >> I'm doing DNS lookups [...] it is important to make sure that the socket >> doesn't just hang there waiting for a response. >> After a recent system upgrade to Python 2.4.1 (from 2.2.2) I thought I >> could take advantage of the setdefaulttimeout in the socket module, to >> limit the amount of time the sockets take for a lookup. >> As a test, I set the default timout ridiculously low. But it doesn't >> seem to be having any effect. > The timeout applies to network communication on that socket, but not to > calls such as socket.gethostbyname. The gethostbyname function actually > goes to the operating system, which can look up the name in a cache, or a > hosts file, or query DNS servers on sockets of its own. > Modern OS's generally have reasonably TCP/IP implementations, and the OS > will handle applying a reasonable timeout. Still gethostbyname and its > brethren can be a pain for single- threaded event-driven programs, because > they can block for significant time. > Under some older threading systems, any system call would block every > thread in the process, and gethostbyname was notorious for holding things > up. Some systems offer an asynchronous gethostbyname, but that doesn't > help users of Python's library. Some programmers would keep around a few > extra processes to handle their hosts lookups. Fortunately, threading > systems are now much better, and should only block the thread waiting for > gethostbyname. Thanks, Bryan. I'm not doing any threading. But we are running this script on incoming email as it arrives at the SMTP server, and scripts have a 16 second max time of execution. Generally they run in much less time. However, we have seen incidents where, due to issues with the DNS servers for the blacklists, that the script exceed it's max time to run and the process was killed by the OS. This results in the email being placed back into the mail queue for attempted re-delivery later. Of course, if this issue goes undetected, the mail can eventually be "returned to sender". There's no effective way to check from within the running filter script that the time is not exceeded if the gethostbyname blocks and doesn't return. :( As I said, normally this isn't a problem. But there have been a handful of incidents where it did cause issues briefly over a few days. I was hoping to address it. :/ Sounds like I'm out of luck. -- Sheila King http://www.thinkspot.net/sheila/ -- http://mail.python.org/mailman/listinfo/python-list
Re: socket setdefaulttimeout
Bryan: Thanks for the tips/suggestion. I will definitely look into that. (It will be my first foray into coding with threads...I do appreciate that you've laid a great deal of it out. I will certainly refer to my references and do substantial testing on this...) Thanks! -- Sheila King http://www.thinkspot.net/sheila/ -- http://mail.python.org/mailman/listinfo/python-list
Re: overload builtin operator
Robert Kern wrote: > Shaun wrote: > > Thanks for your replies, obviously this isn't a simple thing to do so > > I'll take a different tack. > > > > The exact problem I am trying to solve here is to avoid the > > ZeroDivisionError in division. > > I have c++ code which delegates to python to calculate expressions on > > table cells. The values of the table cell are arbitary numbers and the > > expressions to be calculated are fairly simple python arithmetic and > > math functions. > > > > The problem being that some users want an expression like '(100/x)+ 3' > > where x=0 to return 3. So that dividing a number by zero results in 0. > > You have silly users. You mean you don't? Damn. Can I have some of yours? Iain -- http://mail.python.org/mailman/listinfo/python-list
Re: how to join two Dictionary together?
DENG wrote: > dict1={...something...} > > dict2={...somethind else ..} > > dict1 + dict2 > > > that's does works ..:(, it's not like List... > > > anyone can tell me how to get it? > Uh, I'm just learning python too, so there may be a much simpler way to do this, but you could: dict3 = {} for k,i in dict1.iteritems(): dict3[k] = i for k,i in dict2.iteritems(): dict3[k] = i Think this should work. Obviously, if the same key appears in both dict1 and dict2 then dict2's value will overwrite dict1's. Iain -- http://mail.python.org/mailman/listinfo/python-list
Re: how to join two Dictionary together?
Iain King wrote: > DENG wrote: > > dict1={...something...} > > > > dict2={...somethind else ..} > > > > dict1 + dict2 > > > > > > that's does works ..:(, it's not like List... > > > > > > anyone can tell me how to get it? > > > > Uh, I'm just learning python too, so there may be a much simpler way to > do this, but you could: > > dict3 = {} > for k,i in dict1.iteritems(): > dict3[k] = i > for k,i in dict2.iteritems(): > dict3[k] = i > > Think this should work. Obviously, if the same key appears in both > dict1 and dict2 then dict2's value will overwrite dict1's. > > Iain Or, on reading the tutorial a bit more thoroughly, you can do: dict1.update(dict2) which will add all of dict2's key:value pairs to dict1 Iain -- http://mail.python.org/mailman/listinfo/python-list
Re: how to join two Dictionary together?
[EMAIL PROTECTED] wrote: > update works like append for lists > > a = {} > a['a']='a' > a['c']='c' > b={} > b['b'] = 'b' > c={} > c.update(a) > c.update(b) > So what do you think is the better way to do it, based on speed or aesthetics? (1) c=a.copy() c.update(b) or (2) c={} c.update(a) c.update(b) Iain -- http://mail.python.org/mailman/listinfo/python-list
wxPython, using sizers.
I'm making a program to view log files. The main display is a multi column listbox. I want to add combobox filters above the listbox headers. The filters contain each unique instance in the list column below it, and if any filter has text selected in it then the listbox will only display rows in which the relevant column contains that text (MS Excel's Autofilter, basically). I need to get the comboboxes to be positioned directly above the column headers, and be the same width, and I've had no luck. I tried with a horizontal boxsizer, but it resets the widths automatically (as I imagine it is supposed to). Any tips? Iain -- http://mail.python.org/mailman/listinfo/python-list
time.strftime in 2.4.1 claims data out of range when not
I have a web app that has been running just fine for several months under Python 2.2.2. We are preparing to upgrade the server to run Python 2.4.1. However, part of my web app is throwing an error on this code (that has previously worked without exception): >>> time.strftime("%Y-%m-%d", (Y, M, D, 0,0,0,0,0,0)) Traceback (most recent call last): File "", line 1, in ? ValueError: day of year out of range >>> Y 2005 >>> M 5 >>> D 15L I don't see what parts of the date that I have submitted to strftime are out of range? Also, the phrasing of the error message is a bit odd? "day of year out of range" I'm not sure what the day of a year would be??? Sheila King http://www.thinkspot.net/sheila/ -- http://mail.python.org/mailman/listinfo/python-list
Async/Concurrent HTTP Requests
Hi, I'd like to query two (or more) RESTful APIs concurrently. What is the pythonic way of doing so? Is it better to use built in functions or are third-party packages? Thanks. Best, Ari -- https://mail.python.org/mailman/listinfo/python-list
Validating Data Extracted from Files
Hi, I'm sourcing data from multiple excel files (workbooks) each with multiple worksheets. Prior to persisting the aggregated data, I want to validate it. I was thinking of creating classes to hold the data and validate type and content via methods. I'd appreciate feedback on this approach, suggestions on possibly better alternatives, and if there are existing libraries that provide this functionality. Thanks. Best, Ari -- https://mail.python.org/mailman/listinfo/python-list
How to Nest Structs?
Hi, I'm trying to nest the "info_header", "info_body", and "info_trailer" structs (see below) into a "data_packet" struct. Does anyone know how I can/should accomplish this? Thanks. batch_header_format = struct.Struct('!c2h') info_header_format = struct.Struct('!2hl') mkt_status_format = struct.Struct('!c') info_trailer_format = struct.Struct('!hc') mkt_session_codes = [b'PO',b'PC',b'CO',b'CC',b'CK',b'CL'] mkt_type = [b'N',b'S',b'O',b'A',b'C',b'G'] batch_header = batch_header_format.pack(b'1',1,1024) total_size = info_header_format.size + mkt_status_format.size + info_trailer_format.size # Combine following into data struct. info_header = info_header_format.pack(int(binascii.hexlify(mkt_session_codes[random.randint(0,5)])), total_size, 124) info_body = mkt_status_format.pack(mkt_type[random.randint(0,5)]) info_trailer = info_trailer_format.pack(0, b'\r') -Ari -- http://mail.python.org/mailman/listinfo/python-list
Re: question about what lamda does
Steve Holden wrote: > tac-tics wrote: > > [EMAIL PROTECTED] wrote: > > > >>Hey there, > >>i have been learning python for the past few months, but i can seem to > >>get what exactly a lamda is for. What would i use a lamda for that i > >>could not or would not use a def for ? Is there a notable difference ? > >>I only ask because i see it in code samples on the internet and in > >>books. > > > > > > Lambda is just as powerful as a function, but totally useless =-P > > > > Lambda used to be handy before the introduction of list comprehensions. > > Now, though, there primary use is obfuscating your code. > > > I do wish you could hold yourself back and stop muddying the waters. > Lambdas and list comprehensions have little or nothing to do with each > other. Unless you know something I don't ... > I think he meant that lambda's main use before was inside map and filter; as stated earlier in the thread, lambda's main use was for passing simple functions as arguments, and of these map and filter must have made up a majority (and then I'd guess TKinter would be next). List comprehensions replace map and filter, so... I wouldn't put it as explosively as he has, but I find a lambda less clear than a def too. Iain > regards > Steve > -- > Steve Holden +44 150 684 7255 +1 800 494 3119 > Holden Web LLC/Ltd http://www.holdenweb.com > Skype: holdenweb http://holdenweb.blogspot.com > Recent Ramblings http://del.icio.us/steve.holden -- http://mail.python.org/mailman/listinfo/python-list
Re: using names before they're defined
[EMAIL PROTECTED] wrote: > I have a problem. I'm writing a simulation program with a number of > mechanical components represented as objects. When I create instances > of objects, I need to reference (link) each object to the objects > upstream and downstream of it, i.e. > > supply = supply() > compressor = compressor(downstream=combustor, upstream=supply) > combuster = combuster(downstream=turbine, upstream=compressor) > etc. > > the problem with this is that I reference 'combustor' before is it > created. If I swap the 2nd and 3rd lines I get the same problem > (compressor is referenced before creation). > > > aargh!!! any ideas on getting around this? > > Dave At the top of your code you could put: supply = None compressor = None combuster = None turbine = None It might be better, though, to arrange your code like: supply = Supply() compressor = Compressor() combuster = Combuster() turbine = Turbine() compressor.setStreams(down=combuster, up=supply) combuster.setStreams(down=turbine, up=compressor) Do the streams reflect each other? That is, if supply.down is compressor, is compressor.up supply? In that case you probably want to do something like: class Component(): upstream = None downstream = None def setUpstream(self, c): self.upstream = c if c.downstream != self: c.setDownstream(self) def setDownstream(self, c): self.downstream = c if c.upstream != self: c.setUpstream(self) class Supply(Component): pass etc. Iain -- http://mail.python.org/mailman/listinfo/python-list
Re: using names before they're defined
[EMAIL PROTECTED] wrote: > Iain, thanks - very helpful. > > Really I'm trying to write a simulation program that goes through a > number of objects that are linked to one another and does calculations > at each object. The calculations might be backwards or fowards (i.e. > starting at the supply or demand ends of the system and then working > through the objects). And also, I might have multiple objects linked to > a single object (upstream or downstream) - e.g. compressor -- multiple > combusters - turbine > > I like your idea of using something like a setStreams method to > establish the linking. The streams do reflect each other, although > having many-to-one and vice versa will complicate that. I have not > quite got my head around having multiple links. In C++ I would be > thinking about something like a linked-list but I'm not sure that's the > right approach here. > > Dave You don't need linked-lists : python has a list type built in. Example: class Component(): upstream = [] downstream = [] def addUpstream(self, c): self.upstream.append(c) if not self in c.downstream: c.addDownstream(self) def addDownstream(self, c): self.downstream.append(c) if not self in c.upstream: c.addUpstream(self) def remUpstream(self, c): c.downstream.remove(self) self.upstream.remove(c) def remDownstream(self, c): c.upstream.remove(self) self.downstream.remove(c) def cascadeDownTest(self): print self # this could run forever if you connect components in a circle: for c in self.downstream: c.cascadeDownTest() Iain -- http://mail.python.org/mailman/listinfo/python-list
Re: random shuffles
Dustan wrote: > Boris Borcic wrote: > > does > > > > x.sort(cmp = lambda x,y : cmp(random.random(),0.5)) > > > > pick a random shuffle of x with uniform distribution ? > > > > Intuitively, assuming list.sort() does a minimal number of comparisons to > > achieve the sort, I'd say the answer is yes. But I don't feel quite > > confortable > > with the intuition... can anyone think of a more solid argumentation ? > > Why not use the supplied shuffle method? > > random.shuffle(x) or check out this thread: http://groups.google.com/group/comp.lang.python/browse_thread/thread/766f4dcc92ff6545?tvc=2&q=shuffle Iain -- http://mail.python.org/mailman/listinfo/python-list
Re: FOR LOOPS
OriginalBrownster wrote: > I am using a class called UploadedFile. > I want to create a for loop to itterate through the objects within file > name > > class UploadedFile(SQLObject): > filename = StringCol(alternateID=True) > abspath = StringCol() > uniqueid = IntCol() > > I'll show you a snippit of the code I am trying to use it in:: > > > zip= ["zip.txt"] > file_path = [myfile.filename for myfile in > UploadedFile.select(orderBy=UploadedFile.q.filename)] > > if kw: > for filename in file_path: > zip.append(filename) > flash('Options selected'+ str(kw) + str(zip)) > else: > pass > > When i run this the flash displays all the values for kw...however zip > only shows up as "zip.txt" using the str function. Meaning that the FOR > LOOP is not working correctly. After your 'file_path =' line, try adding a 'print file_path', and see if it's creating it correctly. Your for loop looks fine, assuming that file_path is a list of filenames. Iain -- http://mail.python.org/mailman/listinfo/python-list
Re: help - iter & dict
here goes... > > thanks simon for this, it seems a little easier to understand for me but i still get the error when i run the script: #here is a sample dictionary from the 1000 key:values normally in it. they are all non zero and values to 15 decimal places CDSitdict = {32.030822391220937: "'1.36799874'", 29.150765445901769: "'2.20799727'", 27.930109636681877: "'2.7449993'", 28.590095427450688: "'2.43599813'", 27.595161357952588: "'2.9217'", 29.961761413410386: "'1.92299674'", 36.311798000222424: "'0.66348'", 34.358611987430052: "'0.93372'", 41.199188199569292: "'0.20413'", 29.560651138651014: "'2.0579967'"} #i have tried to format the numerical key into the dictionary to give a string using %s but it didnt work so eventually i used # #itera = "\'" + `DSit` + "\'" #CDSitdict[Cpcmax] = itera # #i am now wondering if i have been trying to iterate through the key value pairs, does the numerical part im trying to iterate over have to be the value #side or can it be any side? #here is a sample exvalue Cpcb = 33.94 ** def pcloop(dictionary, exvalue): ''' Return the key in dictionary whose value is closest to exvalue. If dictionary is empty, return None. ''' # Get a iterator over *both* keys and values. diter = dictionary.iteritems() # Get the first (key, value) pair. try: u, z = diter.next() except StopIteration: # The dictionary was empty! # You might want to do something else here return # Compute the closeness of the first value. closest = abs(z - exvalue) # Create a var to store the closest key result = u # Iterate through the rest of the dict. for u, z in diter: # Compute the closeness. v = abs(z - exvalue) # Check if it's closer than the closest. if v < closest: # If so, store the new closest. closest = v # And store the new closest key. result = u return result Cpcb = input("\n\nPlease enter the carbon percentage value obtained from the microanalysis. If none, enter 0: ") print"\n\nCellulose Carbon Percentage is " + `Cpca` + "\n\nMaximum potential monomer carbon weight is " + `Cwmax` + "\n\nMaximum potential carbon percentage is " + `Cpcmax` + "\n\nPercentage difference between Cellulose and Maximum is " + `Cdiff` + "\n\n" exvalue = Cpcb dictionary = CDSitdict CDS = pcloop(dictionary, exvalue) error is: Traceback (most recent call last): File "elementalDS.py", line 184, in ? CDS = pcloop(dictionary, exvalue) File "elementalDS.py", line 158, in pcloop closest = abs(z - exvalue) TypeError: unsupported operand type(s) for -: 'str' and 'float' :( ali -- Dr. Alistair King Research Chemist, Laboratory of Organic Chemistry, Department of Chemistry, Faculty of Science P.O. Box 55 (A.I. Virtasen aukio 1) FIN-00014 University of Helsinki Tel. +358 9 191 50429, Mobile +358 (0)50 5279446 Fax +358 9 191 50366 -- http://mail.python.org/mailman/listinfo/python-list
Re: help - iter & dict
taleinat wrote: > mappi.helsinki.fi> writes: > > >> CDSitdict = {28.473823598317392: "'2.48699832'", 40.06163037274758: >> "'0.2912'", 27.756248559438422: "'2.83499964'", >> 33.2299196586726: "'1.12499962'", 29.989685187220061: >> "'1.91399677'", 31.502319473614037: "'1.4909983'", >> 28.487341570327612: "'2.4809983'", 30.017763818271245: >> "'1.90499681'", 32.94343842266: "'1.17899943'", >> 30.520103712886584: "'1.75199736'", 31.453205956498341: >> "'1.50299826'", 29.484222697359598: "'2.0849968'", >> 28.413513489228706: "'2.51399842'", 28.314852455260802: >> "'2.5589986'", 28.652931545003508: "'2.40899803'"} >> >> heres the error i get after entering Cpcb >> >> Traceback (most recent call last): >> File "elementalDS.py", line 156, in ? >> CDS = findClosest(CDSitdict, Cpcb) >> File "elementalDS.py", line 142, in findClosest >> distance = (target - v) ** 2 >> TypeError: unsupported operand type(s) for -: 'float' and 'str' >> alicat linux:~/Desktop> >> > > The Python interpreter is being friendly and explaining exactly what the > problem > is and where it occured. It's telling you that it can't subtract a string > from a > float, in line 142 of your code (in the findClosest function). So the problem > is > that 'target' is a float while 'v' is a string. > > 'v' should be a float as well, but it's a string since the values in your > dictionary are strings instead of numbers. Try removing the quotes around the > values in your dict (both the double-quotes and the single-quotes). > > > yes i now the key and values are swapped and the solutions work fine, i cant let the numerical key be involved in the iteration as in some cases there may be an exvalue below 3. the only solution i could come up with is to put single quotes round it but unfortunately i couldnt even to that thanks a -- Dr. Alistair King Research Chemist, Laboratory of Organic Chemistry, Department of Chemistry, Faculty of Science P.O. Box 55 (A.I. Virtasen aukio 1) FIN-00014 University of Helsinki Tel. +358 9 191 50429, Mobile +358 (0)50 5279446 Fax +358 9 191 50366 -- http://mail.python.org/mailman/listinfo/python-list
Re: help - iter & dict
thanks to Simon Forman, his solution worked, the key value pairs were entered the wrong way round in the dictionary...Doh! -- Dr. Alistair King Research Chemist, Laboratory of Organic Chemistry, Department of Chemistry, Faculty of Science P.O. Box 55 (A.I. Virtasen aukio 1) FIN-00014 University of Helsinki Tel. +358 9 191 50429, Mobile +358 (0)50 5279446 Fax +358 9 191 50366 -- http://mail.python.org/mailman/listinfo/python-list
variable creation
Hei all, im trying to create a list of variables for further use: Els = raw_input("Are there any further elements you would like to include? if so type the element, eg, Pd. If not type No: ") if Els != 'No': el = Els in pt while el == 1 and Els != 'Next': elements = [] elements.insert(-1, Els) Els = raw_input("Which further element would you like to include, eg, Pd, if not type Next: ") el = Els in pt while el == 0 and Els != 'Next': Els = raw_input("This is not an element in the periodic table, please try again, eg Pd, If you dont wish to include any more, type Next: ") if el == 1: elements.insert(-1, Els) while el == 0: Els = raw_input("This is not an element in the periodic table, please try again, eg Pd. If you dont wish to include any more, type Next: ") print elements this works to a certain extent but gets stuck on some loop. Im a beginner and am not sure where im going wrong. here is a portion of the dictionary containing typical elements: pt = {'H': 1.00794, 'He': 4.002602, 'Li': 6.941, 'Be': 9.012182, 'B': 10.811} Ali -- Dr. Alistair King Research Chemist, Laboratory of Organic Chemistry, Department of Chemistry, Faculty of Science P.O. Box 55 (A.I. Virtasen aukio 1) FIN-00014 University of Helsinki Tel. +358 9 191 50429, Mobile +358 (0)50 5279446 Fax +358 9 191 50366 -- http://mail.python.org/mailman/listinfo/python-list
Re: The Semicolon Wars as a software industry and human condition
Xah Lee wrote: > Of interest: > > • The Semicolon Wars, by Brian Hayes. 2006. > http://www.americanscientist.org/template/AssetDetail/assetid/51982 > > in conjunction to this article, i recommend: > > • Software Needs Philosophers, by Steve Yegge, 2006 > http://xahlee.org/Periodic_dosage_dir/_p/software_phil.html > > • What Languages to Hate, Xah Lee, 2002 > http://xahlee.org/UnixResource_dir/writ/language_to_hate.html > > Xah > [EMAIL PROTECTED] > ∑ http://xahlee.org/ I'm confused - I thought Xah Lee loved Perl? Now he's bashing it? Huh? Iain -- http://mail.python.org/mailman/listinfo/python-list
Re: Looking For mp3 ID Tag Module
Tim Daneliuk wrote: > Iñigo Serna wrote: > > On 8/18/06, Tim Daneliuk <[EMAIL PROTECTED]> wrote: > >> > try mutagen. > >> http://www.sacredchao.net/quodlibet/wiki/Development/Mutagen > >> > >> This module is more-or-less exactly what I needed. However, I am running > >> into problems when the filenames or ID tags have unicode characters in > >> them. > >> > >> Typically, I do something like: > >> > >> from mutagen.easyid3 import EasyID3 > >> > >> audio["title'] = Something based on the filename that has unicode > >> chars in it > >> > >> I then get this: > >> > >> UnicodeDecodeError: 'ascii' codec can't decode byte 0xfc in position > >> 56: ordinal not in range(128) > > > >> From the docs: > > """Mutagen has full Unicode support for all formats. When you assign > > text strings, we strongly recommend using Python unicode objects > > rather than str objects. If you use str objects, Mutagen will assume > > they are in UTF-8.""" > > > > So I suppose the value you try to assign as title is not unicode, > > check the encoding used in the file system. > > > > Iñigo > > I am trying to set the title based on the filename. The file is in a Win32 > NTFS filesystem, so it could have non-ASCII chars in it. What I am stumbling > on it how to coerce it into unicode. I have tried: > > name = filename.split() blah blah blah > audio["title"] = unicode(name) > > But I still get this error. I am not real up to speed on the whole unicode > end of things, so any kind suggestions would be most welcome. > > By the way, I believe the offending string contains a German umlaut, at least > in one > of the cases. > > To get the MP3's name, use os.path.basename (I'm guessing that's what your split() is for?) Looking at the mutagen tutorial, most of the tags are lists of unicode strings, so you might want to try audio["title"] = [unicode(name)], instead of audio["title"] = unicode(name). This might be your problem when reading the tags, too. Iain -- http://mail.python.org/mailman/listinfo/python-list
Re: edit a torrent file with python
di0rz` wrote: > hi, > I am looking for a python script to edit .torrent files > if anybody know one thx Not sure exactly what you are looking for, but the original bittorrent client is written in Python, so you could grab a copy of it and check the code. Iain -- http://mail.python.org/mailman/listinfo/python-list
dict problem
Hi, ive been trying to update a dictionary containing a molecular formula, but seem to be getting this error: Traceback (most recent call last): File "DS1excessH2O.py", line 242, in ? updateDS1v(FCas, C, XDS) NameError: name 'C' is not defined dictionary is: DS1v = {'C': 6, 'H': 10, 'O': 5} #'Fxas' in each case will be integers but 'atoms' should be a float def updateDS1v(Fxas, x, XDS): while Fxas != 0: atoms = DS1v.get('x') + Fxas*XDS DS1v[x] = atoms updateDS1v(FCas, C, XDS) updateDS1v(FHas, H, XDS) updateDS1v(FOas, O, XDS) updateDS1v(FNas, N, XDS) updateDS1v(FSas, S, XDS) updateDS1v(FClas, Cl, XDS) updateDS1v(FBras, Br, XDS) updateDS1v(FZnas, Zn, XDS) print DS1v I know there is probably a simple solution but im quite new to python and am lost? Ali -- Dr. Alistair King Research Chemist, Laboratory of Organic Chemistry, Department of Chemistry, Faculty of Science P.O. Box 55 (A.I. Virtasen aukio 1) FIN-00014 University of Helsinki Tel. +358 9 191 50392, Mobile +358 (0)50 5279446 Fax +358 9 191 50366 -- http://mail.python.org/mailman/listinfo/python-list
dict problem
Jon Clements wrote: > > Alistair King wrote: > > > > > >> >> Hi, >> >> >> >> ive been trying to update a dictionary containing a molecular formula, >> >> but seem to be getting this error: >> >> >> >> >> >> Traceback (most recent call last): >> >> File "DS1excessH2O.py", line 242, in ? >> >> updateDS1v(FCas, C, XDS) >> >> NameError: name 'C' is not defined >> >> >> >> dictionary is: >> >> >> >> DS1v = {'C': 6, 'H': 10, 'O': 5} >> >> >> >> >> >> >> >> #'Fxas' in each case will be integers but 'atoms' should be a float >> >> >> >> def updateDS1v(Fxas, x, XDS): >> >> while Fxas != 0: >> >> atoms = DS1v.get('x') + Fxas*XDS >> >> DS1v[x] = atoms >> >> >> >> updateDS1v(FCas, C, XDS) >> >> updateDS1v(FHas, H, XDS) >> >> updateDS1v(FOas, O, XDS) >> >> updateDS1v(FNas, N, XDS) >> >> updateDS1v(FSas, S, XDS) >> >> updateDS1v(FClas, Cl, XDS) >> >> updateDS1v(FBras, Br, XDS) >> >> updateDS1v(FZnas, Zn, XDS) >> >> print DS1v >> >> >> >> I know there is probably a simple solution but im quite new to python and >> >> am lost? >> >> >> >> >> > > > > I strongly suggest reading through the tutorial. > > > > I don't think there's enough code here for anyone to check it properly. > > For instance, it looks like FCas exists somewhere as it's barfing on > > trying to find C. Where is XDS defined etc...? > > > > I can't see updateDS1v() ever completing: any Fxas passed in not equal > > to 0 will repeat indefinately. > > > > I'm guessing unless C is meant to be a variable, you mean to pass in > > the string 'C'. > > > > A dictionary already has it's own update method > > > > Perhaps if you explain what you're trying to do in plain English, we > > could give you some pointers. > > > > Jon. > > > > > sorry, this has been a little rushed XDS is defined before the function and is a float. the Fxas values are also and they are integers now ive tried def updateDS1v(Fxas, x, XDS): while Fxas != 0: atoms = DS1v.get(x) + Fxas*XDS DS1v['x'] = atoms updateDS1v(FCas, 'C', XDS) updateDS1v(FHas, H, XDS) updateDS1v(FOas, O, XDS) updateDS1v(FNas, N, XDS) updateDS1v(FSas, S, XDS) updateDS1v(FClas, Cl, XDS) updateDS1v(FBras, Br, XDS) updateDS1v(FZnas, Zn, XDS) print DS1v from this i get the error: Traceback (most recent call last): File "DS1excessH2O.py", line 242, in ? updateDS1v(FCas, 'C', XDS) File "DS1excessH2O.py", line 239, in updateDS1v atoms = DS1v.get(x) + Fxas*XDS TypeError: unsupported operand type(s) for +: 'int' and 'str' with single quotes (FCas, 'C', XDS) to retrieve the value for that key from the dictionary and then create the new value and replace the old value. a -- Dr. Alistair King Research Chemist, Laboratory of Organic Chemistry, Department of Chemistry, Faculty of Science P.O. Box 55 (A.I. Virtasen aukio 1) FIN-00014 University of Helsinki Tel. +358 9 191 50392, Mobile +358 (0)50 5279446 Fax +358 9 191 50366 -- http://mail.python.org/mailman/listinfo/python-list
Re: dict problem
Ben Finney wrote: > "Jon Clements" <[EMAIL PROTECTED]> writes: > > >> We're still in the dark as to what you're trying to do, try >> describing something like: "for each element there is an associated >> 'F' value. For each element in an existing molecule I wish to change >> the number of 'whatever' to be 'whatever' + my 'F' value * value >> XDS..." >> > > Even better, work on a minimal program to do nothing but reproduce the > unexpected behaviour. If you get to such a program and still don't > understand, then post it here so others can run it themselves and > explain. > > ive checked the values and XDS is actually returning a string where i want a float ie '123.45' not 123.45. -- Dr. Alistair King Research Chemist, Laboratory of Organic Chemistry, Department of Chemistry, Faculty of Science P.O. Box 55 (A.I. Virtasen aukio 1) FIN-00014 University of Helsinki Tel. +358 9 191 50392, Mobile +358 (0)50 5279446 Fax +358 9 191 50366 -- http://mail.python.org/mailman/listinfo/python-list
dict problem
Ben Finney wrote: > Alistair King <[EMAIL PROTECTED]> writes: > > >> Ben Finney wrote: >> >>> Even better, work on a minimal program to do nothing but reproduce >>> the unexpected behaviour. If you get to such a program and still >>> don't understand, then post it here so others can run it >>> themselves and explain. >>> >> ive checked the values and XDS is actually returning a string where i >> want a float ie '123.45' not 123.45. >> > > Can you please post a small, complete program that shows the behaviour > you want explained? > > You get this program by writing it -- either by cutting away > irrelevant parts of the existing program, or (better) writing a new > program from scratch that does nothing except demonstrate the > behaviour. > > Note that in the process of getting such a program behaving this way, > you may end up understanding the problem better. > > i have seemed to work out most of the problems from the previous code, now i have: ... heavy = raw_input("\n\n@@\n\nPlease enter the heaviest atom for which you obtained percentage values for, but not Oxygen, eg, 'C', 'N', 'S', 'Br'...: ") print DSvalues def updateDS1v(Fxas, x): if Fxas != 0: value = DSvalues.get(heavy) floatvalue = float(value) atoms = DS1v.get(x) + Fxas*floatvalue DS1v[x] = atoms updateDS1v(FCas, 'C') print DS1v ... the problem now is converting badly formatted dictionary values into floats ive been trying something like this, where 'value' is a typical entry into the dictionary: ... IDLE 1.1 >>> value = "'0.0642501084'" >>> print float(value) and get the error, in IDLE and the code as: Traceback (most recent call last): File "", line 1, in -toplevel- print float(value) ValueError: invalid literal for float(): '0.0642501084' ... Is there any other way of removing double and single quotes from a number, as a string, to give the float value again? I know it would be easier to create a properly formatted dictionary again and i will do that but it would be good to know as i want to get this program running properly to get some results i need for work. Everything else seems to be working fine but this. thanks a -- Dr. Alistair King Research Chemist, Laboratory of Organic Chemistry, Department of Chemistry, Faculty of Science P.O. Box 55 (A.I. Virtasen aukio 1) FIN-00014 University of Helsinki Tel. +358 9 191 50392, Mobile +358 (0)50 5279446 Fax +358 9 191 50366 -- http://mail.python.org/mailman/listinfo/python-list
Re: dict problem
Fredrik Lundh wrote: > Alistair King wrote: > > >> Is there any other way of removing double and single quotes from a >> number, as a string, to give the float value again? >> > > help(str) describes what you can do with a string (an object of type > 'str', that is). among the methods listed, you'll find: > > >> | strip(...) >> | S.strip([chars]) -> string or unicode >> | >> | Return a copy of the string S with leading and 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 >> > > which looks like it should be pretty useful for this specific case: > > >>> value = "'0.0642501084'" > >>> value > "'0.0642501084'" > >>> value.strip("'") > '0.0642501084' > >>> value.strip("'\"") > '0.0642501084' > >>> float(value.strip("'\"")) > 0.0642501084 > > > > Thanks.. the code works great now. I know these things are quite simple to learn from books etc.. but i would be lost without this mailinglist, from lack of time. Hopefully soon i can give something more complicated. I ended up doing the dictionary formatting properly and the new code is: .. heavy = raw_input("\n\n@@\n\nPlease enter the heaviest atom for which you obtained percentage values for, but not Oxygen or Hydrogen, ie, 'C', 'N', 'S', 'Br'...: ") def updateDS1v(Fxas, x): if Fxas !=0 and DS1v.get(x)!=None: value = DSvalues.get(heavy) floatvalue = float(value) atoms = DS1v.get(x) + Fxas*floatvalue else: value = DSvalues.get(heavy) floatvalue = float(value) DS1v[x] = Fxas*floatvalue updateDS1v(FCas, 'C') updateDS1v(FHas, 'H') updateDS1v(FOas, 'O') updateDS1v(FNas, 'N') updateDS1v(FSas, 'S') updateDS1v(FClas, 'Cl') updateDS1v(FBras, 'Br') updateDS1v(FZnas, 'Zn') .. it works perfectly now thanks for the help a -- Dr. Alistair King Research Chemist, Laboratory of Organic Chemistry, Department of Chemistry, Faculty of Science P.O. Box 55 (A.I. Virtasen aukio 1) FIN-00014 University of Helsinki Tel. +358 9 191 50392, Mobile +358 (0)50 5279446 Fax +358 9 191 50366 -- http://mail.python.org/mailman/listinfo/python-list
Re: dict problem
Peter Otten wrote: > Alistair King wrote: > > >> the code works great now. I know these things are quite simple to learn >> from books etc.. but i would be lost without this mailinglist, from lack >> of time. Hopefully soon i can give something more complicated. >> I ended up doing the dictionary formatting properly and the new code is: >> > > >> heavy = raw_input("\n\n@@\n\nPlease enter the heaviest >> atom for which you obtained percentage values for, but not Oxygen or >> Hydrogen, ie, 'C', 'N', 'S', 'Br'...: ") >> >> def updateDS1v(Fxas, x): >> if Fxas !=0 and DS1v.get(x)!=None: >> value = DSvalues.get(heavy) >> floatvalue = float(value) >> atoms = DS1v.get(x) + Fxas*floatvalue >> else: >> value = DSvalues.get(heavy) >> floatvalue = float(value) >> DS1v[x] = Fxas*floatvalue >> >> updateDS1v(FCas, 'C') >> updateDS1v(FHas, 'H') >> updateDS1v(FOas, 'O') >> updateDS1v(FNas, 'N') >> updateDS1v(FSas, 'S') >> updateDS1v(FClas, 'Cl') >> updateDS1v(FBras, 'Br') >> updateDS1v(FZnas, 'Zn') >> > > >> it works perfectly now >> > > Probably not. Have you manually verified the result with more than one > example? Where does 'heavy' come from? Is that black hole 'atoms' > intentional? > > # I'm just guessing here > for k, v in DSvalues.iteritems(): > DSvalues[k] = float(v) > > def updateDS1v(Fxas, x): > DS1v[x] = DS1v.get(x, 0) + Fxas*DSvalues[x] > > Peter > yea...sorry i snipped one line by accident for the email should be: def updateDS1v(Fxas, x): if Fxas !=0 and DS1v.get(x)!=None: value = DSvalues.get(heavy) floatvalue = float(value) atoms = DS1v.get(x) + Fxas*floatvalue DS1v[x] = atoms else: value = DSvalues.get(heavy) floatvalue = float(value) DS1v[x] = Fxas*floatvalue thanks a -- Dr. Alistair King Research Chemist, Laboratory of Organic Chemistry, Department of Chemistry, Faculty of Science P.O. Box 55 (A.I. Virtasen aukio 1) FIN-00014 University of Helsinki Tel. +358 9 191 50392, Mobile +358 (0)50 5279446 Fax +358 9 191 50366 -- http://mail.python.org/mailman/listinfo/python-list
create global variables?
Hi, is there a simple way of creating global variables within a function? ive tried simply adding the variables in: def function(atom, Xaa, Xab): Xaa = onefunction(atom) Xab = anotherfunction(atom) if i can give something like: function('C')#where atom = 'C' but not necessarly include Xaa or Xab i would like to recieve: Caa = a float Cab = another float ive tried predefining Xaa and Xab before the function but they are global values and wont change within my function. Is there a simple way round this, even if i call the function with the variables ('C', Caa, Cab)? .. some actual code: # sample dictionaries DS1v = {'C': 6} pt = {'C': 12.0107} def monoVarcalc(atom): a = atom + 'aa' Xaa = a.strip('\'') m = atom + 'ma' Xma = m.strip('\'') Xaa = DS1v.get(atom) Xma = pt.get(atom) print Xma print Xaa monoVarcalc('C') print Caa print Cma .. it seems to work but again i can only print the values of Xma and Xaa ? Alistair -- Dr. Alistair King Research Chemist, Laboratory of Organic Chemistry, Department of Chemistry, Faculty of Science P.O. Box 55 (A.I. Virtasen aukio 1) FIN-00014 University of Helsinki Tel. +358 9 191 50392, Mobile +358 (0)50 5279446 Fax +358 9 191 50366 -- http://mail.python.org/mailman/listinfo/python-list
Re: IE7 skulduggery?
BartlebyScrivener wrote: > Found fix for this at Mozilla: > > http://kb.mozillazine.org/Default_browser > > Apparently, even though it LOOKS and ACTS like Firefox is still your > default browser after an IE7 upgrade, it's not. > > To fix, you must run: > > firefox.exe -silent -nosplash -setDefaultBrowser > > Which also fixes the webbrowser. py problem. > > At least so far. > > rd > > yes, annoying i know that this may not be related to python but occasionally when im using firefox under windows and /i think/ when i open IE7, firefox hangs and wont reopen until i restart. Is this likely to be anything related to IE7? -- Dr. Alistair King Research Chemist, Laboratory of Organic Chemistry, Department of Chemistry, Faculty of Science P.O. Box 55 (A.I. Virtasen aukio 1) FIN-00014 University of Helsinki Tel. +358 9 191 50392, Mobile +358 (0)50 5279446 Fax +358 9 191 50366 -- http://mail.python.org/mailman/listinfo/python-list
Re: create global variables?
Gary Herron wrote: > Alistair King wrote: > >> Hi, >> >> is there a simple way of creating global variables within a function? >> >> >> > Use the "global" statement within a function to bind a variable to a > global. > > See http://docs.python.org/ref/global.html for details. > > > >>>> def x(): >>>> > ... global g > ... g = 123 > ... > >>>> x() >>>> g >>>> > 123 > > > Gary Herron > > > > > >> ive tried simply adding the variables in: >> >> def function(atom, Xaa, Xab): >> Xaa = onefunction(atom) >> Xab = anotherfunction(atom) >> >> if i can give something like: >> >> function('C')#where atom = 'C' but not necessarly include Xaa or Xab >> >> i would like to recieve: >> >> Caa = a float >> Cab = another float >> >> ive tried predefining Xaa and Xab before the function but they are >> global values and wont change within my function. Is there a simple way >> round this, even if i call the function with the variables ('C', Caa, Cab)? >> .. >> >> some actual code: >> >> # sample dictionaries >> DS1v = {'C': 6} >> pt = {'C': 12.0107} >> >> def monoVarcalc(atom): >> a = atom + 'aa' >> Xaa = a.strip('\'') >> m = atom + 'ma' >> Xma = m.strip('\'') >> Xaa = DS1v.get(atom) >> Xma = pt.get(atom) >> print Xma >> print Xaa >> >> monoVarcalc('C') >> >> print Caa >> print Cma >> .. >> it seems to work but again i can only print the values of Xma and Xaa >> >> ? >> >> Alistair >> >> >> > > have tried: def monoVarcalc(atom): a = atom + 'aa' Xaa = a.strip('\'') m = atom + 'ma' Xma = m.strip('\'') global Xma global Xaa Xaa = DS1v.get(atom) Xma = pt.get(atom) print Xma print Xaa monoVarcalc('C') print Caa print Cma ... where global Xma & Xaa are before and after any further functions i get still get the error Traceback (most recent call last): File "DS1excessH2O.py", line 54, in ? print Caa NameError: name 'Caa' is not defined -- Dr. Alistair King Research Chemist, Laboratory of Organic Chemistry, Department of Chemistry, Faculty of Science P.O. Box 55 (A.I. Virtasen aukio 1) FIN-00014 University of Helsinki Tel. +358 9 191 50392, Mobile +358 (0)50 5279446 Fax +358 9 191 50366 -- http://mail.python.org/mailman/listinfo/python-list
Re: create global variables?
Steve Holden wrote: > [EMAIL PROTECTED] wrote: > >> J. Clifford Dyer wrote: >> >> >>> Alistair King wrote: >>> > > [... advice and help ...] > > >> this worked a treat: >> >> def monoVarcalc(atom): >> >>a = atom + 'aa' >>Xaa = a.strip('\'') >>m = atom + 'ma' >>Xma = m.strip('\'') >>Xaa = DS1v.get(atom) >>Xma = pt.get(atom) >>return Xaa, Xma >> >> >> Caa, Cma = monoVarcalc('C') >> >> > In which case I suspect you will find that this works just as well: > > def monoVarcalc(atom): > > Xaa = DS1v.get(atom) > Xma = pt.get(atom) > return Xaa, Xma > > > Unless there is something decidedly odd about the side-effects of the > statements I've removed, since you never appear to use the values of a, > m, Xaa and Xma there seems little point in calculation them. > > regards > Steve > Yup...it works..but now i have to create a dictionary of 'a' and 'm', ie... "Xaa" and "Xma" string, key:value pairs so i can use other functions on the Xaa, Xma variables by iterating over them and retrieving the values from the variables. I think if i just input Xaa and Xma, only the values associated with those variables will go into the dictionary and ill just be iterating over nonsence. atomsmasses = {} def monoVarcalc(atom): a = atom + 'aa' m = atom + 'ma' atomsmasses[a]=m Xaa = a.strip('\'') Xma = m.strip('\'') Xma = pt.get(atom) if DS1v.get(atom) != None: Xaa = DS1v.get(atom) else: Xaa = 0 return Xaa, Xma Caa, Cma = monoVarcalc('C') Oaa, Oma = monoVarcalc('O') Haa, Hma = monoVarcalc('H') Naa, Nma = monoVarcalc('N') Saa, Sma = monoVarcalc('S') Claa, Clma = monoVarcalc('Cl') Braa, Brma = monoVarcalc('Br') Znaa, Znma = monoVarcalc('Zn') i think? :) thanks a -- Dr. Alistair King Research Chemist, Laboratory of Organic Chemistry, Department of Chemistry, Faculty of Science P.O. Box 55 (A.I. Virtasen aukio 1) FIN-00014 University of Helsinki Tel. +358 9 191 50392, Mobile +358 (0)50 5279446 Fax +358 9 191 50366 -- http://mail.python.org/mailman/listinfo/python-list
Re: create global variables?-the full story
Steve Holden wrote: > Alistair King wrote: > >> Steve Holden wrote: >> >> >>> [EMAIL PROTECTED] wrote: >>> >>> >>> >>>> J. Clifford Dyer wrote: >>>> >>>> >>>> >>>> >>>>> Alistair King wrote: >>>>> >>>>> >>> [... advice and help ...] >>> >>> >>> >>> >>>> this worked a treat: >>>> >>>> def monoVarcalc(atom): >>>> >>>> a = atom + 'aa' >>>> Xaa = a.strip('\'') >>>> m = atom + 'ma' >>>> Xma = m.strip('\'') >>>> Xaa = DS1v.get(atom) >>>> Xma = pt.get(atom) >>>> return Xaa, Xma >>>> >>>> >>>> Caa, Cma = monoVarcalc('C') >>>> >>>> >>>> >>> In which case I suspect you will find that this works just as well: >>> >>> def monoVarcalc(atom): >>> >>>Xaa = DS1v.get(atom) >>>Xma = pt.get(atom) >>>return Xaa, Xma >>> >>> >>> Unless there is something decidedly odd about the side-effects of the >>> statements I've removed, since you never appear to use the values of a, >>> m, Xaa and Xma there seems little point in calculation them. >>> >>> regards >>> Steve >>> >>> >> Yup...it works..but now i have to create a dictionary of 'a' and 'm', >> ie... "Xaa" and "Xma" string, key:value pairs so i can use other >> functions on the Xaa, Xma variables by iterating over them and >> retrieving the values from the variables. I think if i just input Xaa >> and Xma, only the values associated with those variables will go into >> the dictionary and ill just be iterating over nonsence. >> >> atomsmasses = {} >> >> def monoVarcalc(atom): >> a = atom + 'aa' >> m = atom + 'ma' >> atomsmasses[a]=m >> Xaa = a.strip('\'') >> Xma = m.strip('\'') >> Xma = pt.get(atom) >> if DS1v.get(atom) != None: >> Xaa = DS1v.get(atom) >> else: >> Xaa = 0 >> return Xaa, Xma >> >> Caa, Cma = monoVarcalc('C') >> Oaa, Oma = monoVarcalc('O') >> Haa, Hma = monoVarcalc('H') >> Naa, Nma = monoVarcalc('N') >> Saa, Sma = monoVarcalc('S') >> Claa, Clma = monoVarcalc('Cl') >> Braa, Brma = monoVarcalc('Br') >> Znaa, Znma = monoVarcalc('Zn') >> >> >> >> i think? :) >> thanks >> >> a >> >> > No fair: you only just added atomsmasses! ;-) > > However, it seems to me that your atomsmasses dictionary is going to be > entirely predictable, and you are still focusing on storing the *names* > of things rather than building up a usable data structure. Indeed I > suspect that your problem can be solved using only the names of the > elements, and not the names of the variables that hold various > attributes of the elements. > > Perhaps if you explain in plain English what you *really* want to do we > can help you find a more Pythonic solution. It'll probably end up > something like this: > > mass = {} > for element in ['C', 'O', ..., 'Zn'] > mass[element] = monoVarcalc(element) > > But I could, of course, be completely wrong ... it wouldn't be the first > time. Do you understand what I'm saying? > > regards > Steve > OK... from the start. im trying to develop a simple command line application for determining the degree of substitution (DS) on a polymer backbone from elemental analysis, i.e., the % weights of different elements in the monomer-substituent compound ( i want each element to give a result and heaviest atoms give the most accurate results). most basic comp chem programs use input files but i dont know anything about file iteration yet and want the program to be as user friendly as possible..i.e. command line prompt. GUI would be great but too much for me at this stage at the start of the script i have 2 dictionaries 1) containing every atom in the periodic table with associated isotopic average masses 2) containing the molecular forumla of the monomer unit...eg for cellulose AGU {'C': 6, 'H': 10, 'O': 5}.
Re: create global variables?-the full story
J. Clifford Dyer wrote: >> OK... >> >> from the start. >> >> im trying to develop a simple command line application for determining >> the degree of substitution (DS) on a polymer backbone from elemental >> analysis, i.e., the % weights of different elements in the >> monomer-substituent compound ( i want each element to give a result and >> heaviest atoms give the most accurate results). >> >> most basic comp chem programs use input files but i dont know anything >> about file iteration yet and want the program to be as user friendly as >> possible..i.e. command line prompt. GUI would be great but too much for >> me at this stage >> >> at the start of the script i have 2 dictionaries 1) containing every >> atom in the periodic table with associated isotopic average masses 2) >> containing the molecular forumla of the monomer unit...eg for cellulose >> AGU {'C': 6, 'H': 10, 'O': 5}. >> >> the basic steps are >> >> 1. calculate the weight percentage values for each atom in the monomer >> 2. iterate into dictionaries from DS=0 - DS=15 (0.5 step) the >> projected % values for the monomer plus substituent, for EACH atom in >> the compound. >> 3. find the (local) minimum from each dictionary/atom to give the >> appropriate DS value. >> >> *Note* I have to iterate ALL the values as there is a non-linear >> relationship between % values and DS due to the different atomic weights >> The computer seems to cope with this in about 10 seconds with the above >> parameters and about 8 elements for the iteration step >> >> > > Since you have a parallel structure for each element, consider using a > dictionary with the element names as keys: > > >>> atomicdata = {} > >>> for element in 'C','H','U': > ... atomicdata[element] = getAtomVars(element) > ... > >>> print atomicdata > { 'C': (1, 2), 'H': (4, 5), 'U': (78, 20) } > > The first value of each tuple will be your Xaa, and the second value > will be Xma. Do you really need to keep the names Caa, Cma, Haa, Hma > around? Instead of Caa, you have atomicdata['C'][0] and Cma becomes > atomicdata['C'][1]. Completely unambiguous. A bit more verbose, > perhaps, but you don't have to try to sneak around the back side of the > language to find the data you are looking for. That's very much against > the tao. If you really want the names, nest dicts, but don't try to get > the element name into the keys, because you already have that: > > >>> atomicdata = { 'C': { 'aa': 1, > ... 'ma': 2}, > ...'H': { 'aa': 4 > ... 'ma': 5}, > ...'U': { 'aa': 78 > ... 'ma': 20} } > > and to get from there to storing all your data for all however many > steps, change the value of each entry in atomic data from a tuple (or > dict) to a list of tuples (or dicts). > > > >>> atomicdata = { 'C': [ (1,2), (4,6), (7,8), (20,19) ], > ...'H': [ (5,7), (2,986), (3,4) ] } > >>> atomicdata['H'].append((5,9)) > >>> atomicdata > { 'C': [ (1, 2), (4, 6), (7, 8), (20, 19) ], 'H': [ (5, 7), (2, 986), > (3, 4), (5, 9) ] } > > You can build up those lists with nested for loops. (one tells you which > element you're working on, the other which iteration). > > The indexes of your lists, of course, will not correspond to the DS > values, but to the step number. To get back to the DS number, of > course, let the index number be i, and calculate DS = i * 0.5 > > That should get you off and running now. Happy pythoning! > > Cheers, > Cliff > Thanks Cliff, this is what i need, it seems to make much more sense to do this way. I think once i learn to include datastructures within each other im gonna try to make up this 3D 'array' (i think this is a word from C, is there a python equivalent?) of further iterations within each iteration to take into account the excess water. For this i think ill have to add another 100 values onto the values i already have, i.e. 1.8x10**8 entries in total and god knows how many calculations in potentially one datastructure. Could my computer cope with this or should i try a series of refinement iterations? Does anyone knows of a simple way of determining how much processer time it takes to do these calculations? thanks a -- Dr. Alistair King Research Chemist, Laboratory of Organic Chemistry, Department of Chemistry, Faculty of Science P.O. Box 55 (A.I. Virtasen aukio 1) FIN-00014 University of Helsinki Tel. +358 9 191 50392, Mobile +358 (0)50 5279446 Fax +358 9 191 50366 -- http://mail.python.org/mailman/listinfo/python-list
Python deployment options.
Hi to all folks here, i just bought a book and started reading about this language. I want to ask what options do we have to deploy a python program to users that do not have the labguage installed ?? I mean, can i make an executable file, or something that contains the runtime and the modules that the program only use or am i forced to download the language to the user machine so the .py files can be run ?? Thanks in advance, king kikapu -- http://mail.python.org/mailman/listinfo/python-list