content
stringlengths
85
101k
title
stringlengths
0
150
question
stringlengths
15
48k
answers
sequence
answers_scores
sequence
non_answers
sequence
non_answers_scores
sequence
tags
sequence
name
stringlengths
35
137
Q: Python, Convert 9 tuple UTC date to MySQL datetime format I am parsing RSS feeds with the format as specified here: http://www.feedparser.org/docs/date-parsing.html date tuple (2009, 3, 23, 13, 6, 34, 0, 82, 0) I am a bit stumped at how to get this into the MySQL datetime format (Y-m-d H:M:S)? A: tup = (2009, 3, 23, 13, 6, 34, 0, 82, 0) import datetime d = datetime.datetime(*(tup[0:6])) #two equivalent ways to format it: dStr = d.isoformat(' ') #or dStr = d.strftime('%Y-%m-%d %H:%M:%S')
Python, Convert 9 tuple UTC date to MySQL datetime format
I am parsing RSS feeds with the format as specified here: http://www.feedparser.org/docs/date-parsing.html date tuple (2009, 3, 23, 13, 6, 34, 0, 82, 0) I am a bit stumped at how to get this into the MySQL datetime format (Y-m-d H:M:S)?
[ "tup = (2009, 3, 23, 13, 6, 34, 0, 82, 0)\nimport datetime \nd = datetime.datetime(*(tup[0:6]))\n#two equivalent ways to format it:\ndStr = d.isoformat(' ')\n#or\ndStr = d.strftime('%Y-%m-%d %H:%M:%S')\n\n" ]
[ 21 ]
[]
[]
[ "datetime", "mysql", "python", "sql", "tuples" ]
stackoverflow_0000686717_datetime_mysql_python_sql_tuples.txt
Q: Problem using Python comtypes library to add a querytable to Excel I'm trying to create a QueryTable in an excel spreadsheet using the Python comtypes library, but getting a rather uninformative error... In vba (in a module within the workbook), the following code works fine: Sub CreateQuery() Dim con As ADODB.Connection Dim rs As ADODB.Recordset Dim ws As Worksheet Dim qt As QueryTable Set ws = ActiveWorkbook.Sheets(1) Set con = New ADODB.Connection con.Open ("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Path\to\Db.mdb;") Set rs = New ADODB.Recordset rs.Open "Select * from [tbl Base Data];", con Set qt = ws.QueryTables.Add(rs, ws.Range("A1")) qt.Refresh End Sub But the following Python code: import sys import comtypes.client as client def create_querytable(): constring = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Path\\to\\Db.mdb" conn = client.CreateObject("ADODB.Connection", dynamic = True) rs = client.CreateObject("ADODB.Recordset", dynamic = True) SQL = "Select * from [tbl Base Data];" conn.Open(constring) rs.Open(SQL, conn) excel = client.CreateObject("Excel.Application", dynamic = True) excel.Visible = True ws = excel.Workbooks.Add().Sheets(1) qt = ws.QueryTables.Add(rs, ws.Range["A1"]) qt.Refresh() rs.Close() conn.Close() Throws the unhelpful error message: Traceback (most recent call last): File "<pyshell#34>", line 1, in <module> create_querytable() File "C:/Documents and Settings/cvmne250/Desktop/temp.py", line 17, in create_querytable qt = ws.QueryTables.Add(rs, ws.Range["A1"]) File "G:\ISA\SPSS\comtypes\lib\comtypes\client\lazybind.py", line 160, in caller File "G:\ISA\SPSS\comtypes\lib\comtypes\automation.py", line 628, in _invoke COMError: (-2147352567, 'Exception occurred.', (None, None, None, 0, None)) Any ideas on what's happening here? Thanks! A: I simplified your code and this should work fine (I'll explain the changes below): def create_querytable2(): constring = "OLEDB;Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\path\to\db.mdb;" SQL = "Select * from tblName;" excel = client.CreateObject("Excel.Application", dynamic=True) excel.Visible = True ws = excel.Workbooks.Add().Worksheets(1) ws.QueryTables.Add(constring, ws.Range["A1"], SQL).Refresh() The QueryTables.Add() function can create the Connection and Recordset objects for you, so that simplifies a lot of things... you just need to add what type of connection it is in the conneciton string (the "OLEDB" part). Letting Excel do most of the work seems to solve your problem :) A: It looks like your error is on this line: qt = ws.QueryTables.Add(rs, ws.Range["A1"]) I think your problem is that you are using python syntax to look up a value in a VBA Collection. Try changing your square brackets to parentheses. i.e. qt = ws.QueryTables.Add(rs, ws.Range("A1")) The reason being that in VBA when you invoke a Collection like this, Range("A1"), you are actually calling it's default method, Range.Item("A1"). Basically, VBA Collections do not translate to python dictionaries. I'm getting this from this forum thread, and my experience with VBA. Edit due to comment: Unfortunately, I've tried both: as noted in your link, they sometimes don't do the same thing, but my gut feeling here is that the '[' is more likely to be what I want. – mavnn Do you know if comtypes.client.CreateObject works the same as win32com.client.Dispatch? You might try creating your com object with the win32com package and see if that makes a difference.
Problem using Python comtypes library to add a querytable to Excel
I'm trying to create a QueryTable in an excel spreadsheet using the Python comtypes library, but getting a rather uninformative error... In vba (in a module within the workbook), the following code works fine: Sub CreateQuery() Dim con As ADODB.Connection Dim rs As ADODB.Recordset Dim ws As Worksheet Dim qt As QueryTable Set ws = ActiveWorkbook.Sheets(1) Set con = New ADODB.Connection con.Open ("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Path\to\Db.mdb;") Set rs = New ADODB.Recordset rs.Open "Select * from [tbl Base Data];", con Set qt = ws.QueryTables.Add(rs, ws.Range("A1")) qt.Refresh End Sub But the following Python code: import sys import comtypes.client as client def create_querytable(): constring = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Path\\to\\Db.mdb" conn = client.CreateObject("ADODB.Connection", dynamic = True) rs = client.CreateObject("ADODB.Recordset", dynamic = True) SQL = "Select * from [tbl Base Data];" conn.Open(constring) rs.Open(SQL, conn) excel = client.CreateObject("Excel.Application", dynamic = True) excel.Visible = True ws = excel.Workbooks.Add().Sheets(1) qt = ws.QueryTables.Add(rs, ws.Range["A1"]) qt.Refresh() rs.Close() conn.Close() Throws the unhelpful error message: Traceback (most recent call last): File "<pyshell#34>", line 1, in <module> create_querytable() File "C:/Documents and Settings/cvmne250/Desktop/temp.py", line 17, in create_querytable qt = ws.QueryTables.Add(rs, ws.Range["A1"]) File "G:\ISA\SPSS\comtypes\lib\comtypes\client\lazybind.py", line 160, in caller File "G:\ISA\SPSS\comtypes\lib\comtypes\automation.py", line 628, in _invoke COMError: (-2147352567, 'Exception occurred.', (None, None, None, 0, None)) Any ideas on what's happening here? Thanks!
[ "I simplified your code and this should work fine (I'll explain the changes below):\ndef create_querytable2():\n constring = \"OLEDB;Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\path\\to\\db.mdb;\"\n SQL = \"Select * from tblName;\"\n excel = client.CreateObject(\"Excel.Application\", dynamic=True)\n excel.Visible = True\n ws = excel.Workbooks.Add().Worksheets(1)\n ws.QueryTables.Add(constring, ws.Range[\"A1\"], SQL).Refresh()\n\nThe QueryTables.Add() function can create the Connection and Recordset objects for you, so that simplifies a lot of things... you just need to add what type of connection it is in the conneciton string (the \"OLEDB\" part).\nLetting Excel do most of the work seems to solve your problem :)\n", "It looks like your error is on this line:\nqt = ws.QueryTables.Add(rs, ws.Range[\"A1\"])\n\nI think your problem is that you are using python syntax to look up a value in a VBA Collection. Try changing your square brackets to parentheses.\ni.e.\nqt = ws.QueryTables.Add(rs, ws.Range(\"A1\"))\n\nThe reason being that in VBA when you invoke a Collection like this, Range(\"A1\"), you are actually calling it's default method, Range.Item(\"A1\"). Basically, VBA Collections do not translate to python dictionaries.\nI'm getting this from this forum thread, and my experience with VBA.\n\nEdit due to comment:\n\nUnfortunately, I've tried both: as\n noted in your link, they sometimes\n don't do the same thing, but my gut\n feeling here is that the '[' is more\n likely to be what I want. – mavnn\n\nDo you know if comtypes.client.CreateObject works the same as win32com.client.Dispatch? You might try creating your com object with the win32com package and see if that makes a difference.\n" ]
[ 2, 1 ]
[]
[]
[ "com", "comtypes", "excel", "python", "vba" ]
stackoverflow_0000685589_com_comtypes_excel_python_vba.txt
Q: Embed Python script I have some Python Scripts which I would like to use from my VB.NET class library however instead of increasing the amount of files that I distribute is it possible to embed the script into my project/dll in Visual Studio and then run the script from the dll during my program runtime? Thanks for any help. Rob A: Yes, it is possible. A: I believe you may be looking for this, but I am not sure. This is possible, however. The link above shows you how to add the file/script as an embedded resource. If that isn't what you are after, vartec's post describes how to embed the python runtime directly.
Embed Python script
I have some Python Scripts which I would like to use from my VB.NET class library however instead of increasing the amount of files that I distribute is it possible to embed the script into my project/dll in Visual Studio and then run the script from the dll during my program runtime? Thanks for any help. Rob
[ "Yes, it is possible.\n", "I believe you may be looking for this, but I am not sure. This is possible, however.\nThe link above shows you how to add the file/script as an embedded resource. If that isn't what you are after, vartec's post describes how to embed the python runtime directly.\n" ]
[ 2, 0 ]
[]
[]
[ ".net", "deployment", "python", "vb.net", "visual_studio" ]
stackoverflow_0000686690_.net_deployment_python_vb.net_visual_studio.txt
Q: Python: Why can't I modify the current scope within a function using locals()? Why does creating/modifying a member of locals() not work within a function? Python 2.5 (release25-maint, Jul 20 2008, 20:47:25) [GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> # Here's an example of what I expect to be possible in a function: >>> a = 1 >>> locals()["a"] = 2 >>> print a 2 >>> # ...and here's what actually happens: >>> def foo(): ... b = 3 ... locals()["b"] = 4 ... print b ... >>> foo() 3 A: Why would it? It's designed to return a representation, and was never intended for editing the locals. It's not ever guaranteed to work as a tool for such, as the documentation warns. A: locals() return a copy of the namespace (which is the opposite of what globals() does). This means that any change you perform on the dictionary returned by locals() will have no effect. Check in dive into python at example 4.12.
Python: Why can't I modify the current scope within a function using locals()?
Why does creating/modifying a member of locals() not work within a function? Python 2.5 (release25-maint, Jul 20 2008, 20:47:25) [GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> # Here's an example of what I expect to be possible in a function: >>> a = 1 >>> locals()["a"] = 2 >>> print a 2 >>> # ...and here's what actually happens: >>> def foo(): ... b = 3 ... locals()["b"] = 4 ... print b ... >>> foo() 3
[ "Why would it? It's designed to return a representation, and was never intended for editing the locals. It's not ever guaranteed to work as a tool for such, as the documentation warns.\n", "locals() return a copy of the namespace (which is the opposite of what globals() does). This means that any change you perform on the dictionary returned by locals() will have no effect. Check in dive into python at example 4.12.\n" ]
[ 7, 3 ]
[]
[]
[ "introspection", "python", "scope" ]
stackoverflow_0000686715_introspection_python_scope.txt
Q: Redirecting function definitions in python Pointing the class method at the instance method is clearly causing problems: class A(dict): def __getitem__(self, name): return dict.__getitem__(self, name) class B(object): def __init__(self): self.a = A() B.__getitem__ = self.a.__getitem__ b1 = B() b1.a['a'] = 5 b2 = B() b2.a['b'] = 10 c = b1['a'] d = b2['b'] Gives this error: File ... in __getitem__ return dict.__getitem__(self, name) KeyError: 'a' What should I be doing here instead? A: __getitem__ only works in the class. You can't override it in a instance basis. This works: class A(dict): def __getitem__(self, name): return dict.__getitem__(self, name) class B(object): def __init__(self): self.a = A() def __getitem__(self, item): return self.a[item] b1 = B() b1.a['a'] = 5 b2 = B() b2.a['b'] = 10 c = b1['a'] d = b2['b'] If you want to define it in __init__ for some strange reason, you must create a descriptor: def __init__(self): self.a = A() def mygetitem(self, item): return self.a[item] B.__getitem__ = types.MethodType(mygetitem, None, B)
Redirecting function definitions in python
Pointing the class method at the instance method is clearly causing problems: class A(dict): def __getitem__(self, name): return dict.__getitem__(self, name) class B(object): def __init__(self): self.a = A() B.__getitem__ = self.a.__getitem__ b1 = B() b1.a['a'] = 5 b2 = B() b2.a['b'] = 10 c = b1['a'] d = b2['b'] Gives this error: File ... in __getitem__ return dict.__getitem__(self, name) KeyError: 'a' What should I be doing here instead?
[ "__getitem__ only works in the class. You can't override it in a instance basis.\nThis works:\nclass A(dict): \n def __getitem__(self, name):\n return dict.__getitem__(self, name)\n\nclass B(object):\n def __init__(self):\n self.a = A()\n\n def __getitem__(self, item):\n return self.a[item]\n\nb1 = B()\nb1.a['a'] = 5\nb2 = B()\nb2.a['b'] = 10\n\nc = b1['a']\nd = b2['b']\n\nIf you want to define it in __init__ for some strange reason, you must create a descriptor:\ndef __init__(self):\n self.a = A()\n def mygetitem(self, item):\n return self.a[item]\n B.__getitem__ = types.MethodType(mygetitem, None, B)\n\n" ]
[ 7 ]
[]
[]
[ "class_attributes", "python" ]
stackoverflow_0000686899_class_attributes_python.txt
Q: Advice for C# programmer writing Python I've mainly been doing C# development for the past few years but recently started to do a bit of Python (not Iron Python). But I'm not sure if I've made the mental leap to Python...I kind of feel I'm trying to do things as I would in C#. Any advice on how I can fully take advantage of Python? Or any tips\tricks, things to learn more about, things to watch out for? A: First, check tgray's and Lundström's advice. Then, some things you may want to know: Python is dynamically typed, so unlike C#, you will not check type, but behavior. You may want to google about duck typing. It implies you do not have to deal with boxing and unboxing. Python is fully object oriented, but the syntax does not enforce this paradigm. You can write Python without using the word "class". The GUI library featured with Python can't compare with C#'s. Check PyQt, GTK or wxPython libraries. Python has a lot of concepts you may not be familiar with: list comprehensions, generators ("yield" does exist in C#, but it is not used much), decorators, metaclasses, etc. Don't be afraid; you can program in Python without them. They are just smart tools, not mandatory. Like in C#, the Python standard library is huge. Always look at it when you encounter any problem. It is most likely that someone solved it already. Python use LATE binding and variable labels. It's far too early for somebody starting with the language to worry about it, but remember that one day you will encounter a behavior with variables that SEEMS illogical, and you'll have to check that. For the moment: Just remember to never do the following: def myfunc(my_list=[]) : # bla Instead: def myfunc(my_list=()) : my_list = list(my_list) And you'll be good. There is a good reason for that, but that's not the point :-) Python is cross platform, enjoy writing on Mac, and run on Linux, if you wish. Python is not provided with a complex IDE (you got IDLE :-)). If you are a Visual Studio addict, check Glade. This is not as advanced as Visual Studio, but it's still a good RAD. If you want to develop some web application in Python, remember that Python is not .NET. You must add a web framework to it if you want to compare. I like Django. Python does not need a huge IDE to work with. SciTE, Notepad++, IDLE, Kate, gedit... Lightweight editors are really sufficient. Python enforces indentation using spaces and line break, you can't change that. You should avoid using tabs for indenting and choose spaces instead. The equivalent of empty bracelets {} is the keyword "pass". Python does not enforce private variables. You can define a private var using "__" (two underscores) at the beginning of the variable name, but it's still bypassable in some tricky ways. Python usually assume programmers are grown adults that know what they do and communicate. Python uses iteration. A lot. A lot of a lot. And so the itertools module is you best friend. Python has no built in delegates. The delegate module is not what you think. For event-driven programming, use a GUI lib (or code the pattern yourself, it's not that difficult). Python has an interpreter: you can test almost anything, live. It should always be running next to your text editor. Python basic interpreter is not much, try IPython for something tasty. Python is autodocumented: use docstrings in your own code and consult other's using "help()" in the python interpreter Module basics: sys: manipulate system features os: set credential, manipulate file paths, rename, recursive file walk, etc shutil: batch file processing (such as recursive delete) re: regexp urllib and urllib2: HTTP¨scripting like downloading, post / get resquests, etc. datetime: manipulate date, time AND DURATION thread: you guess it zlib: compression pickle: serialization xml: parsing / Writing XML with SAX or DOM There are hundreds of modules. Enjoy. Some typical ways to do things in Python: Loops: Python coders use massively the equivalent of the foreach C# loop, and prefer it to any others: Basic iterations: for item in collection: print str(item) "collection" can be a string, a list, a tuple... Any iterable: any object defining the .next() method. There are a lot of iterables in Python. E.g: a typical Python idiom to read files: for line in open("/path/to/file") : print line A shortcut to the for loop is called "list comprehension". It's a way to create an new iterable in one line: Creating a filtered list with list comprehension: my_list = [item for item in collection if condition] Creating a new list with a list comprehension: my_list = [int(item) * 3 for item in collection] Creating a new generator with a list comprehension: my_list = (int(item) * 3 for item in collection) Same as above, but the values will be generated on the fly at the first iteration then lost. More information about it here. Ordinary for loop If you want to express a usual for loop, you can use the xrange() function. for (int i = 0; i < 5; i++) becomes: for i in xrange(0,5) : do while equivalent There is no "Do While" in Python. I never missed it, but if you have to use this logic, do the following: while True : # Yes, this is an infinite loop. Crazy, hu? # Do your stuff if condition : break Unpacking Swapping variables: a, b = b, a Multiple assignations: The above is just a result of what we call "unpacking" (here applied to a tuple). A simple way to explain it is that you can assign each value of any sequence directly to an equal number a variables, in one row: animal1, animal2, animal3, animal4 = ["cow", "dog", "bird", "fish"] This has a lot of implications. While iterating on a multidimensional array, you normally get each sub sequence one by one then use it, for example: agenda = [("steve", "jobs"), ("linus", "torvald"), ("bill", "gates"),("jon", "skeet")] for person in agenda: print person[0], person[1] But with unpacking, you can assign the values directly to variables as well: agenda = [("steve", "jobs"), ("linus", "torvald"), ("bill", "gates"),("jon", "skeet")] for name, lastname in agenda: print name, lastname And that's why if you want to get an index while iterating, Python coders use the following idioms (enumerate() is a standard function): for index, value in enumerate(sequence) : print index, value Unpacking in functions calls This is advanced use, and you can skip it if it bothers you. You can unpack values using the sign "*" to use a sequence directly in a function call. E.g: >>> foo(var1, var1, var3) : print var1, var2 print var3 >>> seq = (3.14, 42, "yeah") >>> foo(*seq) 3.14 42 yeah There is even more than that. You can unpack a dictionary as named variables, and write function prototypes with *, ** to accept an arbitrary number of arguments. But it not used enough to deserve to make this post even longer :-). String formatting: print "This is a %s on %s about %s" % ("post", "stackoverflow", "python") print "This is a %(subject)s on %(place)s about %(about)s" % {"subject" : "post", "place" : "stackoverflow", "about" : "python"} Slicing an iterable: You can get any part of an iterable using a very concise syntax: print "blebla"[2:4] # Print "eb" last = string[:-1] # Getting last element even = (0,1,2,3,4,5,6,7,8,9)[::2] # Getting evens only (third argument is a step) reversed = string[::-1] # Reversing a string Logical checks: You can check the way you do in C#, but there are "Pythonic" ways (shorter, clearer :-)): if 1 in (1, 2, 3, 4) : # Check en element is in a sequence if var : # check is var is true. Var == false if it's False, 0, (), [], {} or None if not var : # Contrary of above if thing is var: # Check if "thing" and "var" label the same content. if thing is None : # We use that one because None means nothing in Python (almost null) Combo (print on one line all the words containing an "o" in uppercase ): sentence = "It's a good day to write some code" print " ".join([word.upper() for word in sentence.split() if "o" in word]) Output: "GOOD TO SOME CODE" Easier to ask for forgiveness than permission Python coders usually don't check if something is possible. They are a bit like Chuck Norris. They do it. Then catch the exception. Typically, you don't check if a file exists, you try to open it, and roll back if it fails: try : f = open(file) except IOerror : print "no file here !" Of course Chuck Norris never uses excepts since he never fails. The else clause "Else" is a world of many uses in Python. You will find "else" after "if", but after "except" and "for" as well. for stuff in bunch : # Do things else : # This always happens unless you hit "break" in the loop This works for "while" loop too, even if we do not use this loop as much. try : # A crazy stuff except ToCrazyError : # This happens if the crazy stuff raises a ToCrazyError Exception else : # This will happen if there is no error so you can put only one line after the "try" clause finally : # The same as in C# If you are curious, here is a bunch of advanced quick and dirty (but nice) Python snippets. A: Refrain from using classes. Use dictionaries, sets, list and tuples. Setters and getters are forbidden. Don't have exception handlers unless you really need to - let it crash in style. Pylint can be your friend for more pythonish coding style. When you're ready - check out list comprehensions, generators and lambda functions. A: If you are not new to programming, I would recommend the book "Dive into Python" by Mark Pilgrim. It explains Python in a way that makes it easy to understand how Python techniques and idioms can be applied to build practical applications. A: Start by reading The Zen of Python You can read it at the link above, or just type import this at the Python prompt. =) Take advantage of Python features not offered* by C# Such as duck-typing, metaclasses, list comprehension, etc.* Write simple programs just to test these features. You'll get used (if not addicted) to them in no time. Look at the Python Standard Library So you don't reinvent the wheel. Don't try to read the whole thing, even a quick look at the TOC could save you a lot of time. * I know C# already has some of these features, but from what I can see they're either pretty new or not commonly used by C# developers. Please correct me if I'm wrong. A: In case you haven't heard about it yet, Dive Into Python is a great place to start for anyone learning Python. It also has a bunch of Tips & Tricks. A: If you are someone who is better learning a new language by taking small incremental steps then I would recommend using IronPython. Otherwise use regular CPython and don't do any more C# coding until you feel like you have a grasp of Python. A: I would suggest getting a good editor so that you don't get bitten by whitespace. For simplicity, I just use ActivePython's packages Link, which include an editor and all of the win32api libraries. They are pretty fun to get into if you have been using C#. The win32api in Python can be a little bit simpler. You don't need to do the whole DDLImport thing. Download ActivePython (which comes with CPython), open it up, and start entering some stuff at the console. You will pick it up fairly easy after using C#. For some more interesting Python tidbits, try ActiveState code, which has all sorts of recipes, which can allow you to very simply see different things that you can do with Python. A: I'm pretty much in your shoes too, still using C# for most of my work, but using Python more and more for other projects. @e-satis probably knows Python inside-out and all his advice is top-notch. From my point of view what made the biggest difference to me was the following: Get back into functional. not necessarily spaghetti code, but learning that not everything has to be in an object, nor should it be. The interpreter. It's like the immediate window except 10^10 better. Because of how Python works you don't need all the baggage and crap C# makes you put in before you can run things; you can just whack in a few lines and see how things work. I've normally got an IDLE instance up where I just throw around snippets as I'm working out how the various bits in the language works while I'm editing my files... e.g. busy working out how to do a map call on a list, but I'm not 100% on the lambda I should use... whack in a few lines into IDLE, see how it works and what it does. And finally, loving into the verbosity of Python, and I don't mean that in the long winded meaning of verbosity, but as e-satis pointed out, using verbs like "in", "is", "for", etc. If you did a lot of reflection work in C# you'll feel like crying when you see how simple the same stuff is in Python. Good luck with it. A: If you have programming experience and don't feel like spending money I'd recommend How to Think Like a Computer Scientist in Python. A: And then something you can benefit from: IPython shell: Auto completion in the shell. It does batch operations, adds a ton of features, logging and such. >>> Play with the shell - always! easy_install / pip: So nice and an easy way to install a 3rd party Python application.
Advice for C# programmer writing Python
I've mainly been doing C# development for the past few years but recently started to do a bit of Python (not Iron Python). But I'm not sure if I've made the mental leap to Python...I kind of feel I'm trying to do things as I would in C#. Any advice on how I can fully take advantage of Python? Or any tips\tricks, things to learn more about, things to watch out for?
[ "First, check tgray's and Lundström's advice.\nThen, some things you may want to know:\n\nPython is dynamically typed, so unlike C#, you will not\ncheck type, but behavior. You may want to google about duck\ntyping. It implies you do not have to deal with boxing and\nunboxing.\nPython is fully object oriented, but the syntax does not\nenforce this paradigm. You can write Python without using\nthe word \"class\".\nThe GUI library featured with Python can't compare with\nC#'s. Check PyQt, GTK or wxPython libraries.\nPython has a lot of concepts you may not be familiar with:\nlist comprehensions, generators (\"yield\" does exist in C#,\nbut it is not used much), decorators, metaclasses, etc. Don't\nbe afraid; you can program in Python without them. They\nare just smart tools, not mandatory.\nLike in C#, the Python standard library is huge. Always\nlook at it when you encounter any problem. It is most\nlikely that someone solved it already.\nPython use LATE binding and variable labels. It's far too\nearly for somebody starting with the language to worry\nabout it, but remember that one day you will encounter a\nbehavior with variables that SEEMS illogical, and you'll\nhave to check that. For the moment:\n\nJust remember to never do the following:\ndef myfunc(my_list=[]) :\n # bla\n\nInstead:\ndef myfunc(my_list=()) :\n my_list = list(my_list)\n\nAnd you'll be good. There is a good reason for that, but\nthat's not the point :-)\n\nPython is cross platform, enjoy writing on Mac, and\nrun on Linux, if you wish.\nPython is not provided with a complex IDE (you got IDLE :-)).\nIf you are a Visual Studio addict, check Glade. This is\nnot as advanced as Visual Studio, but it's still a good RAD.\nIf you want to develop some web application in Python,\nremember that Python is not .NET. You must add a web\nframework to it if you want to compare. I like Django.\nPython does not need a huge IDE to work with. SciTE,\nNotepad++, IDLE, Kate, gedit...\nLightweight editors are really sufficient.\nPython enforces indentation using spaces and line break,\nyou can't change that. You should avoid using tabs for\nindenting and choose spaces instead. The equivalent of\nempty bracelets {} is the keyword \"pass\".\nPython does not enforce private variables. You can define a\nprivate var using \"__\" (two underscores) at the beginning of\nthe variable name, but it's still bypassable in some tricky\nways. Python usually assume programmers are grown adults\nthat know what they do and communicate.\nPython uses iteration. A lot. A lot of a lot. And so the\nitertools module is you best friend.\nPython has no built in delegates. The delegate module is\nnot what you think. For event-driven programming, use a\nGUI lib (or code the pattern yourself, it's not that\ndifficult).\nPython has an interpreter: you can test almost anything,\nlive. It should always be running next to your text\neditor. Python basic interpreter is not much, try IPython\nfor something tasty.\nPython is autodocumented: use docstrings in your own code\nand consult other's using \"help()\" in the python interpreter\n\nModule basics:\n\nsys: manipulate system features\nos: set credential, manipulate file paths, rename, recursive file walk, etc\nshutil: batch file processing (such as recursive delete)\nre: regexp\nurllib and urllib2: HTTP¨scripting like downloading, post / get resquests, etc.\ndatetime: manipulate date, time AND DURATION\nthread: you guess it\nzlib: compression\npickle: serialization\nxml: parsing / Writing XML with SAX or DOM\n\nThere are hundreds of modules. Enjoy.\nSome typical ways to do things in Python:\nLoops:\nPython coders use massively the equivalent of the foreach C#\nloop, and prefer it to any others:\nBasic iterations:\nfor item in collection:\n print str(item)\n\n\"collection\" can be a string, a list, a tuple... Any\niterable: any object defining the .next() method. There are\na lot of iterables in Python. E.g: a typical Python idiom\nto read files:\nfor line in open(\"/path/to/file\") :\n print line\n\nA shortcut to the for loop is called \"list comprehension\".\nIt's a way to create an new iterable in one line:\nCreating a filtered list with list comprehension:\nmy_list = [item for item in collection if condition]\n\nCreating a new list with a list comprehension:\nmy_list = [int(item) * 3 for item in collection]\n\nCreating a new generator with a list comprehension:\nmy_list = (int(item) * 3 for item in collection)\n\nSame as above, but the values will be generated on the fly\nat the first iteration then lost. More information about it here.\nOrdinary for loop\nIf you want to express a usual for loop, you can use the\nxrange() function. for (int i = 0; i < 5; i++) becomes:\nfor i in xrange(0,5) :\n\ndo while equivalent\nThere is no \"Do While\" in Python. I never missed it, but if\nyou have to use this logic, do the following:\nwhile True : # Yes, this is an infinite loop. Crazy, hu?\n\n # Do your stuff\n\n if condition :\n break\n\nUnpacking\nSwapping variables:\na, b = b, a\n\nMultiple assignations:\nThe above is just a result of what we call \"unpacking\" (here\napplied to a tuple). A simple way to explain it is that you\ncan assign each value of any sequence directly to an equal\nnumber a variables, in one row:\nanimal1, animal2, animal3, animal4 = [\"cow\", \"dog\", \"bird\", \"fish\"]\n\nThis has a lot of implications. While iterating on a\nmultidimensional array, you normally get each sub sequence\none by one then use it, for example:\nagenda = [(\"steve\", \"jobs\"), (\"linus\", \"torvald\"), (\"bill\", \"gates\"),(\"jon\", \"skeet\")]\nfor person in agenda:\n print person[0], person[1]\n\nBut with unpacking, you can assign the values directly to\nvariables as well:\nagenda = [(\"steve\", \"jobs\"), (\"linus\", \"torvald\"), (\"bill\", \"gates\"),(\"jon\", \"skeet\")]\nfor name, lastname in agenda:\n print name, lastname\n\nAnd that's why if you want to get an index while iterating,\nPython coders use the following idioms (enumerate() is a\nstandard function):\nfor index, value in enumerate(sequence) :\n print index, value\n\nUnpacking in functions calls\nThis is advanced use, and you can skip it if it bothers you.\nYou can unpack values using the sign \"*\" to use a sequence\ndirectly in a function call. E.g:\n>>> foo(var1, var1, var3) :\n print var1, var2\n print var3\n>>> seq = (3.14, 42, \"yeah\")\n>>> foo(*seq)\n3.14 42\nyeah\n\nThere is even more than that. You can unpack a dictionary as\nnamed variables, and write function prototypes with *,\n** to accept an arbitrary number of arguments. But it not\nused enough to deserve to make this post even longer :-).\nString formatting:\nprint \"This is a %s on %s about %s\" % (\"post\", \"stackoverflow\", \"python\")\nprint \"This is a %(subject)s on %(place)s about %(about)s\" % {\"subject\" : \"post\", \"place\" : \"stackoverflow\", \"about\" : \"python\"}\n\nSlicing an iterable:\nYou can get any part of an iterable using a very concise syntax:\nprint \"blebla\"[2:4] # Print \"eb\"\nlast = string[:-1] # Getting last element\neven = (0,1,2,3,4,5,6,7,8,9)[::2] # Getting evens only (third argument is a step)\nreversed = string[::-1] # Reversing a string\n\nLogical checks:\nYou can check the way you do in C#, but there are \"Pythonic\"\nways (shorter, clearer :-)):\nif 1 in (1, 2, 3, 4) : # Check en element is in a sequence\n\nif var : # check is var is true. Var == false if it's False, 0, (), [], {} or None\n\nif not var : # Contrary of above\n\nif thing is var: # Check if \"thing\" and \"var\" label the same content.\n\nif thing is None : # We use that one because None means nothing in Python (almost null)\n\nCombo (print on one line all the words containing an \"o\" in uppercase ):\nsentence = \"It's a good day to write some code\"\nprint \" \".join([word.upper() for word in sentence.split() if \"o\" in word])\n\nOutput: \"GOOD TO SOME CODE\"\nEasier to ask for forgiveness than permission\nPython coders usually don't check if something is possible. They are a bit like Chuck Norris. They do it. Then catch the exception. Typically, you don't check if a file exists, you try to open it, and roll back if it fails:\ntry :\n f = open(file)\nexcept IOerror :\n print \"no file here !\"\n\nOf course Chuck Norris never uses excepts since he never fails.\nThe else clause\n\"Else\" is a world of many uses in Python. You will find\n\"else\" after \"if\", but after \"except\" and \"for\" as well.\nfor stuff in bunch :\n # Do things\nelse :\n # This always happens unless you hit \"break\" in the loop\n\nThis works for \"while\" loop too, even if we do not use this\nloop as much.\n try :\n # A crazy stuff\n except ToCrazyError :\n # This happens if the crazy stuff raises a ToCrazyError Exception\n else :\n # This will happen if there is no error so you can put only one line after the \"try\" clause\n finally :\n # The same as in C#\n\n\nIf you are curious, here is a bunch of advanced quick and\ndirty (but nice) Python snippets.\n", "\nRefrain from using classes. Use dictionaries, sets, list and tuples.\nSetters and getters are forbidden.\nDon't have exception handlers unless you really need to - let it crash in style.\nPylint can be your friend for more pythonish coding style.\nWhen you're ready - check out list comprehensions, generators and lambda functions.\n\n", "If you are not new to programming, I would recommend the book \"Dive into Python\" by Mark Pilgrim. It explains Python in a way that makes it easy to understand how Python techniques and idioms can be applied to build practical applications.\n", "Start by reading The Zen of Python\nYou can read it at the link above, or just type import this at the Python prompt. =)\nTake advantage of Python features not offered* by C#\nSuch as duck-typing, metaclasses, list comprehension, etc.*\nWrite simple programs just to test these features. You'll get used (if not addicted) to them in no time.\nLook at the Python Standard Library\nSo you don't reinvent the wheel. Don't try to read the whole thing, even a quick look at the TOC could save you a lot of time.\n\n* I know C# already has some of these features, but from what I can see they're either pretty new or not commonly used by C# developers. Please correct me if I'm wrong.\n", "In case you haven't heard about it yet, Dive Into Python is a great place to start for anyone learning Python. It also has a bunch of Tips & Tricks.\n", "If you are someone who is better learning a new language by taking small incremental steps then I would recommend using IronPython. Otherwise use regular CPython and don't do any more C# coding until you feel like you have a grasp of Python.\n", "I would suggest getting a good editor so that you don't get bitten by whitespace. For simplicity, I just use ActivePython's packages Link, which include an editor and all of the win32api libraries. They are pretty fun to get into if you have been using C#. The win32api in Python can be a little bit simpler. You don't need to do the whole DDLImport thing. Download ActivePython (which comes with CPython), open it up, and start entering some stuff at the console. You will pick it up fairly easy after using C#. For some more interesting Python tidbits, try ActiveState code, which has all sorts of recipes, which can allow you to very simply see different things that you can do with Python.\n", "I'm pretty much in your shoes too, still using C# for most of my work, but using Python more and more for other projects.\n@e-satis probably knows Python inside-out and all his advice is top-notch. From my point of view what made the biggest difference to me was the following:\nGet back into functional. not necessarily spaghetti code, but learning that not everything has to be in an object, nor should it be.\nThe interpreter. It's like the immediate window except 10^10 better. Because of how Python works you don't need all the baggage and crap C# makes you put in before you can run things; you can just whack in a few lines and see how things work.\nI've normally got an IDLE instance up where I just throw around snippets as I'm working out how the various bits in the language works while I'm editing my files... e.g. busy working out how to do a map call on a list, but I'm not 100% on the lambda I should use... whack in a few lines into IDLE, see how it works and what it does.\nAnd finally, loving into the verbosity of Python, and I don't mean that in the long winded meaning of verbosity, but as e-satis pointed out, using verbs like \"in\", \"is\", \"for\", etc.\nIf you did a lot of reflection work in C# you'll feel like crying when you see how simple the same stuff is in Python.\nGood luck with it.\n", "If you have programming experience and don't feel like spending money I'd recommend How to Think Like a Computer Scientist in Python. \n", "And then something you can benefit from:\nIPython shell: Auto completion in the shell. It does batch operations, adds a ton of features, logging and such. >>> Play with the shell - always!\neasy_install / pip: So nice and an easy way to install a 3rd party Python application.\n" ]
[ 157, 16, 13, 6, 5, 3, 2, 2, 1, 0 ]
[]
[]
[ "c#", "python" ]
stackoverflow_0000683273_c#_python.txt
Q: How to get the root node of an xml file in Python? Basically I am using: from xml.etree import ElementTree as ET path = 'C:\cool.xml' et = ET.parse ( path ) But I am not sure how to get the root from et? A: You probably want: et.getroot() Have a look at the official docs for ElementTree from the effbot site. Note that Python 2.5 (the first version of Python to include ElementTree out of the box) uses ElementTree 1.2, not the more recent 1.3. There aren't many differences, but just FYI in case. A: root = et.getroot() I would recommend using lxml.etree instead of xml.etree.ElementTree, as lxml is faster and the interface is the same. A: root = et.getroot()
How to get the root node of an xml file in Python?
Basically I am using: from xml.etree import ElementTree as ET path = 'C:\cool.xml' et = ET.parse ( path ) But I am not sure how to get the root from et?
[ "You probably want:\net.getroot()\n\nHave a look at the official docs for ElementTree from the effbot site. Note that Python 2.5 (the first version of Python to include ElementTree out of the box) uses ElementTree 1.2, not the more recent 1.3. There aren't many differences, but just FYI in case.\n", "root = et.getroot()\n\nI would recommend using lxml.etree instead of xml.etree.ElementTree, as lxml is faster and the interface is the same.\n", "root = et.getroot()\n\n" ]
[ 10, 4, 2 ]
[]
[]
[ "python", "xml" ]
stackoverflow_0000687177_python_xml.txt
Q: How to set up Python for .NET with Python 2.6.1? The "final" release of Python for .NET (link) isn't pre-compiled for Python 2.6. I don't have a problem changing the compilation symbol to PYTHON26 as specified in the docs, the solution rebuilds just fine, but when attempting to import the CLR, I get an error indicating that python26.dll is missing. Anyone know how to build this file? It doesn't seem to be part of the solution, but I might be missing something obvious. A: I managed it by following these instructions by one Feihong Hsu. I notice now that the author has made a follow-up post that may be important too if you're using SP1.
How to set up Python for .NET with Python 2.6.1?
The "final" release of Python for .NET (link) isn't pre-compiled for Python 2.6. I don't have a problem changing the compilation symbol to PYTHON26 as specified in the docs, the solution rebuilds just fine, but when attempting to import the CLR, I get an error indicating that python26.dll is missing. Anyone know how to build this file? It doesn't seem to be part of the solution, but I might be missing something obvious.
[ "I managed it by following these instructions by one Feihong Hsu.\nI notice now that the author has made a follow-up post that may be important too if you're using SP1.\n" ]
[ 3 ]
[]
[]
[ "python" ]
stackoverflow_0000687487_python.txt
Q: Python game programming: is my IO object a legitimate candidate for being a global variable? I'm programming a game in Python, where all IO activities are done by an IO object (in the hope that it will be easy to swap that object out for another which implements a different user interface). Nearly all the other objects in the game need to access the IO system at some point (e.g. printing a message, updating the position of the player, showing a special effect caused by an in-game action), so my question is this: Does it make sense for a reference to the IO object to be available globally? The alternative is passing a reference to the IO object into the __init__() of every object that needs to use it. I understand that this is good from a testing point of view, but is this worth the resulting "function signature pollution"? Thanks. A: Yes, this is a legitimate use of a global variable. If you'd rather not, passing around a context object that is equivalent to this global is another option, as you mentioned. Since I assume you're using multiple files (modules), why not do something like: import io io.print('hello, world') io.clear() This is a common way programs that have more complex I/O needs than simple printing do things like logging. A: Yes, I think so. Another possibility would be to create a module loggerModule that has functions like print() and write(), but this would only marginally be better. A: Nope. Variables are too specific to be passed around in the global namespace. Hide them inside static functions/classes instead that can do magic things to them at run time (or call other ones entirely). Consider what happens if the IO can periodically change state or if it needs to block for a while (like many sockets do). Consider what happens if the same block of code is included multiple times. Does the variable instance get duplicated as well? Consider what happens if you want to have a version 2 of the same variable. What if you want to change its interface? Do you have to modify all the code that references it? Does it really make sense to infect all the code that uses the variable with knowledge of all the ways it can go bad?
Python game programming: is my IO object a legitimate candidate for being a global variable?
I'm programming a game in Python, where all IO activities are done by an IO object (in the hope that it will be easy to swap that object out for another which implements a different user interface). Nearly all the other objects in the game need to access the IO system at some point (e.g. printing a message, updating the position of the player, showing a special effect caused by an in-game action), so my question is this: Does it make sense for a reference to the IO object to be available globally? The alternative is passing a reference to the IO object into the __init__() of every object that needs to use it. I understand that this is good from a testing point of view, but is this worth the resulting "function signature pollution"? Thanks.
[ "Yes, this is a legitimate use of a global variable. If you'd rather not, passing around a context object that is equivalent to this global is another option, as you mentioned.\nSince I assume you're using multiple files (modules), why not do something like:\nimport io\nio.print('hello, world')\nio.clear()\n\nThis is a common way programs that have more complex I/O needs than simple printing do things like logging.\n", "Yes, I think so.\nAnother possibility would be to create a module loggerModule that has functions like print() and write(), but this would only marginally be better.\n", "Nope.\nVariables are too specific to be passed around in the global namespace. Hide them inside static functions/classes instead that can do magic things to them at run time (or call other ones entirely).\nConsider what happens if the IO can periodically change state or if it needs to block for a while (like many sockets do). \nConsider what happens if the same block of code is included multiple times. Does the variable instance get duplicated as well?\nConsider what happens if you want to have a version 2 of the same variable. What if you want to change its interface? Do you have to modify all the code that references it?\nDoes it really make sense to infect all the code that uses the variable with knowledge of all the ways it can go bad? \n" ]
[ 9, 1, 0 ]
[]
[]
[ "global_variables", "io", "python" ]
stackoverflow_0000687703_global_variables_io_python.txt
Q: How to get upper paths from a single path? How to get upper paths from a single path? So say you have a path like: 'C:\a\b\c\d\' How do I get to 'C:\a\b' or 'C:\a\b\c' Is there a pythonic way to do this? A: See os.path from os import path path.dirname("C:\\a\\b\\c\\d\\") A: Theres basic stuff like os.path methods. If you want a list of the full path names of each successive parent in the directory tree, heres a one liner: from os.path import dirname def f1(n): return [n] if n == dirname(n) else [n] + f1(dirname(n)) print f1("/a/b/c/d/e/f/g") A: os.path.split("C:\\a\\b\\c") will return a tuple: ('C:\a\b', 'c') You can continue to call split on the first element of the tuple. A: >>> def go_up(path, n): ... return os.path.abspath(os.path.join(*([path] + ['..']*n))) >>> path = 'C:\\a\\b\\c\\d\\' >>> go_up(path, 2) 'C:\\a\\b' >>> go_up(path, 1) 'C:\\a\\b\\c' >>> go_up(path, 0) 'C:\\a\\b\\c\\d' Not being a regular user of os.path, I don't know if this is an appropriate/pythonic solution. I compared it to an alternate function, define as follows: def go_up_2(path, n): for i in xrange(n): path = os.path.split(path)[0] return path The first thing to note is that go_up_2('C:\\a\\b\\', 1) != go_up_2('c:\\a\\b', 1), where it does with the original go_up. However, performance is significantly better, if that is an issue (probably not, but I was looking for some definitive way to say my own algorithm was better): import timeit g1 = """import os.path import ntpath os.path = ntpath def go_up(path, n): return os.path.abspath(os.path.join(*([path] + ['..']*n)))""" g2 = """import os.path import ntpath os.path = ntpath def go_up(path, n): for i in xrange(n-1): path = os.path.split(path)[0] return path""" t1 = timeit.Timer("go_up('C:\\a\\b\\c\\d', 3)", setup=g1).timeit() t2 = timeit.Timer("go_up('C:\\a\\b\\c\\d', 3)", setup=g2).timeit() print t1 print t2 This outputs (on my machine): 133.364659071 30.101334095 Not very useful information, but I was playing around, and figured it should be posted here anyway.
How to get upper paths from a single path?
How to get upper paths from a single path? So say you have a path like: 'C:\a\b\c\d\' How do I get to 'C:\a\b' or 'C:\a\b\c' Is there a pythonic way to do this?
[ "See os.path\nfrom os import path\npath.dirname(\"C:\\\\a\\\\b\\\\c\\\\d\\\\\")\n\n", "Theres basic stuff like os.path methods. \nIf you want a list of the full path names of each successive parent in the directory tree, heres a one liner:\nfrom os.path import dirname\n\ndef f1(n): return [n] if n == dirname(n) else [n] + f1(dirname(n))\n\nprint f1(\"/a/b/c/d/e/f/g\")\n\n", "os.path.split(\"C:\\\\a\\\\b\\\\c\") will return a tuple:\n('C:\\a\\b', 'c')\n\nYou can continue to call split on the first element of the tuple.\n", ">>> def go_up(path, n):\n... return os.path.abspath(os.path.join(*([path] + ['..']*n)))\n>>> path = 'C:\\\\a\\\\b\\\\c\\\\d\\\\'\n>>> go_up(path, 2)\n'C:\\\\a\\\\b'\n>>> go_up(path, 1)\n'C:\\\\a\\\\b\\\\c'\n>>> go_up(path, 0)\n'C:\\\\a\\\\b\\\\c\\\\d'\n\nNot being a regular user of os.path, I don't know if this is an appropriate/pythonic solution. I compared it to an alternate function, define as follows:\ndef go_up_2(path, n):\n for i in xrange(n):\n path = os.path.split(path)[0]\n return path\n\nThe first thing to note is that go_up_2('C:\\\\a\\\\b\\\\', 1) != go_up_2('c:\\\\a\\\\b', 1), where it does with the original go_up. However, performance is significantly better, if that is an issue (probably not, but I was looking for some definitive way to say my own algorithm was better):\nimport timeit\n\ng1 = \"\"\"import os.path\nimport ntpath\nos.path = ntpath\ndef go_up(path, n):\n return os.path.abspath(os.path.join(*([path] + ['..']*n)))\"\"\"\n\ng2 = \"\"\"import os.path\nimport ntpath\nos.path = ntpath\ndef go_up(path, n):\n for i in xrange(n-1):\n path = os.path.split(path)[0]\n return path\"\"\"\n\nt1 = timeit.Timer(\"go_up('C:\\\\a\\\\b\\\\c\\\\d', 3)\", setup=g1).timeit()\nt2 = timeit.Timer(\"go_up('C:\\\\a\\\\b\\\\c\\\\d', 3)\", setup=g2).timeit()\n\nprint t1\nprint t2\n\nThis outputs (on my machine):\n133.364659071\n30.101334095\n\nNot very useful information, but I was playing around, and figured it should be posted here anyway.\n" ]
[ 10, 4, 2, 2 ]
[]
[]
[ "directory", "python" ]
stackoverflow_0000687863_directory_python.txt
Q: soaplib with mod_wsgi/cherrypy I've followed the tutorials for setting up Apache with mod_wsgi to interface cherrypy and make a site running of it. This is my "myapp.wsgi", and opening http://localhost/ works great. Opening http://localhost/ape/ actually returns the text instead of a soap-response, and http://localhost/ape/service.wsdl returns a 500 HTTP error code. What am I doing wrong in getting such a simple SOAP service to run? How can I get it to return valid WSDL? My code follows below Cheers Nik import atexit, threading, cherrypy,sys from soaplib.wsgi_soap import SimpleWSGISoapApp from soaplib.service import soapmethod from soaplib.serializers.primitive import String, Integer, Array sys.stdout = sys.stderr cherrypy.config.update({'environment': 'embedded'}) class Root(object): def index(self): return 'Hello World!' index.exposed = True @soapmethod(_returns=String) def ape(self): return 'Ape!!' ape.exposed = True application = cherrypy.Application(Root(), None) A: I just tested this myself by replacing the last line of your file with cherrypy.quickstart(Root(), "/") and it worked just fine for me. I suggest trying this and seeing whether it works for you; if it does then you'll know that it's an issue relating to running it under Apache/mod_wsgi and not an inherent problem with your code. A: Eli is right; it's not enough to just make an Application instance. You have to mount it on cherrypy.tree, which quickstart() does for you.
soaplib with mod_wsgi/cherrypy
I've followed the tutorials for setting up Apache with mod_wsgi to interface cherrypy and make a site running of it. This is my "myapp.wsgi", and opening http://localhost/ works great. Opening http://localhost/ape/ actually returns the text instead of a soap-response, and http://localhost/ape/service.wsdl returns a 500 HTTP error code. What am I doing wrong in getting such a simple SOAP service to run? How can I get it to return valid WSDL? My code follows below Cheers Nik import atexit, threading, cherrypy,sys from soaplib.wsgi_soap import SimpleWSGISoapApp from soaplib.service import soapmethod from soaplib.serializers.primitive import String, Integer, Array sys.stdout = sys.stderr cherrypy.config.update({'environment': 'embedded'}) class Root(object): def index(self): return 'Hello World!' index.exposed = True @soapmethod(_returns=String) def ape(self): return 'Ape!!' ape.exposed = True application = cherrypy.Application(Root(), None)
[ "I just tested this myself by replacing the last line of your file with\ncherrypy.quickstart(Root(), \"/\")\n\nand it worked just fine for me. I suggest trying this and seeing whether it works for you; if it does then you'll know that it's an issue relating to running it under Apache/mod_wsgi and not an inherent problem with your code.\n", "Eli is right; it's not enough to just make an Application instance. You have to mount it on cherrypy.tree, which quickstart() does for you.\n" ]
[ 1, 1 ]
[]
[]
[ "cherrypy", "mod_wsgi", "python", "soap" ]
stackoverflow_0000678409_cherrypy_mod_wsgi_python_soap.txt
Q: Including Python standard libraries in your distribution For a project I'm working on I need to include some Python modules that come standard with the Python SDK because the platform I am targetting (to be precise, PyS60) does not include these modules. Are there any licensing issues I need to address? Do I need to include the PSF license in my project? My project is licensed under Apache 2.0. A: According to the PSF License FAQ: Can I bundle Python with my non-open-source application? Yes. Unlike some open source licenses, the PSF License allows Python to be included in non-open applications, either in unmodified or modified form. The FAQ goes on to explain about third-party module licensing. In effect, I think the answer is 'Yes'. DISCLAIMER: IANAL. A: The python license is very open. Python License Python is absolutely free, even for commercial use (including resale). You can sell a product written in Python or a product that embeds the Python interpreter. No licensing fees need to be paid for such usage. The Open Source Initiative has certified the Python license as Open Source, and includes it on their list of open source licenses. There is no GPL-like "copyleft" restriction. Distributing binary-only versions of Python, modified or not, is allowed. There is no requirement to release any of your source code. You can also write extension modules for Python and provide them only in binary form. However, the Python license is compatible with the GPL, according to the Free Software Foundation. You cannot remove the PSF's copyright notice from either the source code or the resulting binary.
Including Python standard libraries in your distribution
For a project I'm working on I need to include some Python modules that come standard with the Python SDK because the platform I am targetting (to be precise, PyS60) does not include these modules. Are there any licensing issues I need to address? Do I need to include the PSF license in my project? My project is licensed under Apache 2.0.
[ "According to the PSF License FAQ:\n\nCan I bundle Python with my non-open-source application?\nYes. Unlike some open source licenses, the PSF License allows Python to be included in non-open applications, either in unmodified or modified form.\n\nThe FAQ goes on to explain about third-party module licensing.\nIn effect, I think the answer is 'Yes'.\nDISCLAIMER: IANAL.\n", "The python license is very open.\nPython License\n\nPython is absolutely free, even for\ncommercial use (including resale).\nYou can sell a product written in\nPython or a product that embeds the\nPython interpreter. No licensing fees\nneed to be paid for such usage.\nThe Open Source Initiative has\ncertified the Python license as Open\nSource, and includes it on their list\nof open source licenses.\nThere is no GPL-like \"copyleft\"\nrestriction. Distributing binary-only\nversions of Python, modified or not,\nis allowed. There is no requirement\nto release any of your source code.\nYou can also write extension modules\nfor Python and provide them only in\nbinary form. However, the Python\nlicense is compatible with the GPL,\naccording to the Free Software\nFoundation.\nYou cannot remove the PSF's copyright\nnotice from either the source code or\nthe resulting binary.\n\n" ]
[ 10, 7 ]
[]
[]
[ "licensing", "python" ]
stackoverflow_0000688096_licensing_python.txt
Q: How to compile Python 1.0 For some perverse reason, I want to try Python 1.0.. How would I go about compiling it, or rather, what is the earlier version that will compile cleanly with current compilers? I'm using Mac OS X 10.5, although since it's for nothing more than curiosity (about how the language has changed), compiling in a Linux virtual machine is possible too.. A: Python 1.0.1 compiles perfectly under Ubuntu 8.10 using GCC 4.3.2. It should compile under Leopard, too. Download the source here, and compile the usual way: ./configure make UPDATE: I tested it, and it compiles under Leopard, too. A: Going further backwards in time, I pulled the 0.9.1p1 source from alt.sources via Google Groups' archive. That's 18+ year old code! I made a few changes (documented in README.reconstructed) to get it to compile on my OS 10.4 box. Source available for your enjoyment. I've also sent email to python.org maintainers to see if they want a copy of it. It doesn't compile cleanly. There are some warnings, mostly to do lack of prototypes. But it does work.
How to compile Python 1.0
For some perverse reason, I want to try Python 1.0.. How would I go about compiling it, or rather, what is the earlier version that will compile cleanly with current compilers? I'm using Mac OS X 10.5, although since it's for nothing more than curiosity (about how the language has changed), compiling in a Linux virtual machine is possible too..
[ "Python 1.0.1 compiles perfectly under Ubuntu 8.10 using GCC 4.3.2. It should compile under Leopard, too.\nDownload the source here, and compile the usual way:\n./configure\nmake\n\nUPDATE: I tested it, and it compiles under Leopard, too.\n", "Going further backwards in time, I pulled the 0.9.1p1 source from alt.sources via Google Groups' archive. That's 18+ year old code!\nI made a few changes (documented in README.reconstructed) to get it to compile on my OS 10.4 box. Source available for your enjoyment. I've also sent email to python.org maintainers to see if they want a copy of it.\nIt doesn't compile cleanly. There are some warnings, mostly to do lack of prototypes. But it does work.\n" ]
[ 10, 4 ]
[]
[]
[ "installation", "legacy", "python" ]
stackoverflow_0000685732_installation_legacy_python.txt
Q: Get the diff of two MSWord doc files and output to html Possible Duplicate: How to compare two word documents? How can you get the diff of two word .doc documents programatically? Where you can then take the resulting output and generate an html file of the result. (As you would expect to see in a normal gui diff tool) I imagine if you grabed the docs via COM and converted the output to text you could provide some diff funcitonality. Thoughts? Is there a way to do this without windows and COM? (Perferably in python, but I'm open to other solutions) UPDATE Original question asking about msword diff tools was a duplicate of: (Thanks Nathan) How to compare two word documents? A: Use this option in Word 2003: Tools | Compare and Merge Documents Or this in Word 2007: Review | Compare It prompts you for a file with which to compare the file you're editing. This question is a duplicate of How to compare two word documents?, and this answer is a duplicate of my answer there. A: I am not sure whether you are looking for following functionality. Microsoft itself has the option in office suite, Please check http://support.microsoft.com/kb/306484 A: It looks like if you have word and win32com installed it is relatively easy to get the text: import win32com.client app = win32com.client.Dispatch('Word.Application') doc = app.Documents.Open('c:\\files\\mydocument.doc') print doc.Content.Text app.Quit() Source: http://win32com.goermezer.de/content/view/158/192/ You can then run a standard diff on the resulting text. A: I use Araxis Merge to compare a variety of source files, but it also extracts and compares various office document formats such as MS Word, PDF, OpenDocument, etc. I think this would be your best bet if you're willing to spend a bit of money. http://www.araxis.com/merge/index.html A: Probably not relevant (because you already know this) but Word does have a change tracking feature (which needs to be switched on before hand). http://office.microsoft.com/en-us/word/HA012186901033.aspx A: If its a docx, and you are happy with java, you could use docx4j (ASL v2). This has diff functionality built in. See the CompareDocuments example If its a doc, it also has basic code for converting to docx (using poi), which you could do first.
Get the diff of two MSWord doc files and output to html
Possible Duplicate: How to compare two word documents? How can you get the diff of two word .doc documents programatically? Where you can then take the resulting output and generate an html file of the result. (As you would expect to see in a normal gui diff tool) I imagine if you grabed the docs via COM and converted the output to text you could provide some diff funcitonality. Thoughts? Is there a way to do this without windows and COM? (Perferably in python, but I'm open to other solutions) UPDATE Original question asking about msword diff tools was a duplicate of: (Thanks Nathan) How to compare two word documents?
[ "Use this option in Word 2003: \n\nTools | Compare and Merge Documents\n\nOr this in Word 2007: \n\nReview | Compare\n\nIt prompts you for a file with which to compare the file you're editing.\n\nThis question is a duplicate of How to compare two word documents?, and this answer is a duplicate of my answer there.\n", "I am not sure whether you are looking for following functionality.\nMicrosoft itself has the option in office suite,\nPlease check\nhttp://support.microsoft.com/kb/306484\n", "It looks like if you have word and win32com installed it is relatively easy to get the text:\nimport win32com.client\napp = win32com.client.Dispatch('Word.Application')\ndoc = app.Documents.Open('c:\\\\files\\\\mydocument.doc')\nprint doc.Content.Text\napp.Quit()\n\nSource: http://win32com.goermezer.de/content/view/158/192/\nYou can then run a standard diff on the resulting text.\n", "I use Araxis Merge to compare a variety of source files, but it also extracts and compares various office document formats such as MS Word, PDF, OpenDocument, etc. I think this would be your best bet if you're willing to spend a bit of money.\nhttp://www.araxis.com/merge/index.html\n", "Probably not relevant (because you already know this) but Word does have a change tracking feature (which needs to be switched on before hand). http://office.microsoft.com/en-us/word/HA012186901033.aspx\n", "If its a docx, and you are happy with java, you could use docx4j (ASL v2). This has diff functionality built in.\nSee the CompareDocuments example\nIf its a doc, it also has basic code for converting to docx (using poi), which you could do first.\n" ]
[ 7, 3, 3, 3, 0, 0 ]
[]
[]
[ "diff", "ms_word", "python" ]
stackoverflow_0000568320_diff_ms_word_python.txt
Q: Which version of python added the else clause for for loops? Which was the first version of python to include the else clause for for loops? I find that the python docs usually does a good job of documenting when features were added, but I can't seem to find the info on this feature. (It doesn't help that 'for' and 'else' are particularly difficult terms to google for on a programming website) A: It's been present since the beginning. To see that, get the source from alt.sources, specifically the message titled "Python 0.9.1 part 17/21". The date is Feb 21, 1991. This post included the grammar definition, which states: for_stmt: 'for' exprlist 'in' exprlist ':' suite ['else' ':' suite] You might be able to find the 0.9.0 sources if you try harder than I did, but as the first public release was 0.9.0 on 20 Feb, that would get you back one day. The 0.9.1 release was a minor patch that did not affect this part of the grammar. (Is that a UTSL reference or what? When was the last time you looked at a shar file? ;) BTW, I reconstructed the original source and tweaked it a bit to compile under gcc-4.0 on my OS X 10.4 box. Details for those interested few, including python-0.9.1.tar.gz. The entire development history is available from version control, even after changing version control systems twice. "hg log -p -r 6:7" from the cpython Mercurial archive shows that the "for/else" was committed on Sun Oct 14 12:07:46 1990 +0000, and the previous commit was Sat Oct 13 19:23:40 1990 +0000. for/else has been part of Python since October 1990. A: It's been around since at least 1.4, which is the oldest version of the documentation I know of. A: Since version 1.0.1, at least.. Python 1.0.1 (Mar 27 2009) Copyright 1991-1994 Stichting Mathematisch Centrum, Amsterdam >>> for x in range(2): ... print x ... else: ... print "loop done" ... 0 1 loop done
Which version of python added the else clause for for loops?
Which was the first version of python to include the else clause for for loops? I find that the python docs usually does a good job of documenting when features were added, but I can't seem to find the info on this feature. (It doesn't help that 'for' and 'else' are particularly difficult terms to google for on a programming website)
[ "It's been present since the beginning. To see that, get the source from alt.sources, specifically the message titled \"Python 0.9.1 part 17/21\". The date is Feb 21, 1991. This post included the grammar definition, which states:\nfor_stmt: 'for' exprlist 'in' exprlist ':' suite ['else' ':' suite] \n\nYou might be able to find the 0.9.0 sources if you try harder than I did, but as the first public release was 0.9.0 on 20 Feb, that would get you back one day. The 0.9.1 release was a minor patch that did not affect this part of the grammar.\n(Is that a UTSL reference or what? When was the last time you looked at a shar file? ;)\nBTW, I reconstructed the original source and tweaked it a bit to compile under gcc-4.0 on my OS X 10.4 box. Details for those interested few, including python-0.9.1.tar.gz.\nThe entire development history is available from version control, even after changing version control systems twice. \"hg log -p -r 6:7\" from the cpython Mercurial archive shows that the \"for/else\" was committed on Sun Oct 14 12:07:46 1990 +0000, and the previous commit was Sat Oct 13 19:23:40 1990 +0000. for/else has been part of Python since October 1990. \n", "It's been around since at least 1.4, which is the oldest version of the documentation I know of.\n", "Since version 1.0.1, at least..\nPython 1.0.1 (Mar 27 2009)\nCopyright 1991-1994 Stichting Mathematisch Centrum, Amsterdam\n>>> for x in range(2):\n... print x\n... else:\n... print \"loop done\"\n... \n0\n1\nloop done\n\n" ]
[ 33, 7, 1 ]
[]
[]
[ "for_loop", "python" ]
stackoverflow_0000682185_for_loop_python.txt
Q: Is there any use for Flex + Python/Ruby without a web framework (Django/Rails)? I often hear about Flex being combined with web frameworks on the backend. The idea being that Flex serves as the presentation framework while the web framework (Django/Rails) does the database lookups and sends the data to Flex to present in the form of XML. However, is there ever a situation where Flex and Python/Ruby would be combined without a web framework as an intermediary? Under what circumstances might such a combination make sense (if any)? (I'm trying to think of projects where the functionality of a scripting language would be complementary with the functionality of Flex - but also whether it's possible for the two to be combined without too much high jinx). A: You can still code against WSGI directly in Python. If that's the route you want to go, PEP 333 is about the only way to go. With that said, doing so is a good learning experience, but WSGI wasn't really intended to be used directly. You don't have to use a full-stack framework like Django if you don't want to. If you want something more light-weight, might I suggest CherryPy or web.py? They're a lot more light-weight than Django is. There are other options aside from WSGI, but they'll pretty much all have about the same caveats. In other words, it can be done, but usually isn't recommended. A: Flash player allows developers to open sockets to remote applications. It is feasible that you could create a Flex application that connected to a remote server and transferred binary or serialized data. This has the added benefit of supporting asynchronous communication, so such a thing might be practical for multiplayer games or chat clients. Adobe develops an application for this purpose called Flash Media Server (Unless the name has changed). There is also an open source project called Red5 with a similar feature set. Finally, there are several libraries that enable serialization and transfer of flash objects between languages. Some examples are AMFPHP http://www.amfphp.org/, and the much more advanced Flex Data Services http://www.onflex.org/ted/2006/05/flex-data-services-part-1.php.
Is there any use for Flex + Python/Ruby without a web framework (Django/Rails)?
I often hear about Flex being combined with web frameworks on the backend. The idea being that Flex serves as the presentation framework while the web framework (Django/Rails) does the database lookups and sends the data to Flex to present in the form of XML. However, is there ever a situation where Flex and Python/Ruby would be combined without a web framework as an intermediary? Under what circumstances might such a combination make sense (if any)? (I'm trying to think of projects where the functionality of a scripting language would be complementary with the functionality of Flex - but also whether it's possible for the two to be combined without too much high jinx).
[ "You can still code against WSGI directly in Python. If that's the route you want to go, PEP 333 is about the only way to go.\nWith that said, doing so is a good learning experience, but WSGI wasn't really intended to be used directly. You don't have to use a full-stack framework like Django if you don't want to. If you want something more light-weight, might I suggest CherryPy or web.py? They're a lot more light-weight than Django is.\nThere are other options aside from WSGI, but they'll pretty much all have about the same caveats. In other words, it can be done, but usually isn't recommended.\n", "Flash player allows developers to open sockets to remote applications. It is feasible that you could create a Flex application that connected to a remote server and transferred binary or serialized data. This has the added benefit of supporting asynchronous communication, so such a thing might be practical for multiplayer games or chat clients.\nAdobe develops an application for this purpose called Flash Media Server (Unless the name has changed).\nThere is also an open source project called Red5 with a similar feature set.\nFinally, there are several libraries that enable serialization and transfer of flash objects between languages. Some examples are AMFPHP http://www.amfphp.org/, and the much more advanced Flex Data Services http://www.onflex.org/ted/2006/05/flex-data-services-part-1.php.\n" ]
[ 4, 1 ]
[]
[]
[ "apache_flex", "django", "python", "ruby", "ruby_on_rails" ]
stackoverflow_0000686490_apache_flex_django_python_ruby_ruby_on_rails.txt
Q: Building Python PIL for JPEG looks okay, but fails the selftest I'm on Fedora Core 6 (64 bit) after "yum install libjpeg-devel" I have downloaded and built PIL. It gives the message: --- JPEG support ok Looks like JPEG built okay, but when running selftest.py: IOError: decoder jpeg not available Why would it appear to have built correctly, but fail the selftest? A: You probably need more packages. Install libjpeg which includes /usr/lib/libjpeg.so* and try again. On my Fedora (another version), PIL is installed with the python-imaging rpm : ldd _imaging.so linux-gate.so.1 => (0x004c6000) libjpeg.so.62 => /usr/lib/libjpeg.so.62 (0x00a07000) libz.so.1 => /lib/libz.so.1 (0x00b91000) libpython2.5.so.1.0 => /usr/lib/libpython2.5.so.1.0 (0x00110000) libpthread.so.0 => /lib/libpthread.so.0 (0x00ee8000) libc.so.6 => /lib/libc.so.6 (0x00260000) libdl.so.2 => /lib/libdl.so.2 (0x003c9000) libutil.so.1 => /lib/libutil.so.1 (0x00fcd000) libm.so.6 => /lib/libm.so.6 (0x00ad1000) /lib/ld-linux.so.2 (0x007a1000) Which means PIL needs libjpeg.so. A: Turns out this gets solved by completely removing the installed versions of PIL and starting the build again from scratch.
Building Python PIL for JPEG looks okay, but fails the selftest
I'm on Fedora Core 6 (64 bit) after "yum install libjpeg-devel" I have downloaded and built PIL. It gives the message: --- JPEG support ok Looks like JPEG built okay, but when running selftest.py: IOError: decoder jpeg not available Why would it appear to have built correctly, but fail the selftest?
[ "You probably need more packages. Install libjpeg which includes /usr/lib/libjpeg.so* and try again.\nOn my Fedora (another version), PIL is installed with the python-imaging rpm :\nldd _imaging.so\n linux-gate.so.1 => (0x004c6000)\n libjpeg.so.62 => /usr/lib/libjpeg.so.62 (0x00a07000)\n libz.so.1 => /lib/libz.so.1 (0x00b91000)\n libpython2.5.so.1.0 => /usr/lib/libpython2.5.so.1.0 (0x00110000)\n libpthread.so.0 => /lib/libpthread.so.0 (0x00ee8000)\n libc.so.6 => /lib/libc.so.6 (0x00260000)\n libdl.so.2 => /lib/libdl.so.2 (0x003c9000)\n libutil.so.1 => /lib/libutil.so.1 (0x00fcd000)\n libm.so.6 => /lib/libm.so.6 (0x00ad1000)\n /lib/ld-linux.so.2 (0x007a1000)\n\nWhich means PIL needs libjpeg.so.\n", "Turns out this gets solved by completely removing the installed versions of PIL and starting the build again from scratch.\n" ]
[ 1, 1 ]
[]
[]
[ "fedora", "jpeg", "libjpeg", "python", "python_imaging_library" ]
stackoverflow_0000689560_fedora_jpeg_libjpeg_python_python_imaging_library.txt
Q: Python XML - build flat record from dynamic nested "node" elements I need to parse an XML file and build a record-based output from the data. The problem is that the XML is in a "generic" form, in that it has several levels of nested "node" elements that represent some sort of data structure. I need to build the records dynamically based on the deepest level of the "node" element. Some example XML and expected output are at the bottom. I am most familiar w/ python's ElementTree, so I'd prefer to use that but I just can't wrap my head around a way to dynamically build the output record based on a dynamic node depth. Also - we can't assume that the nested nodes will be x levels deep, so just hardcoding each level w/ a loop isn't possible. Is there a way to parse the XML and build the output on the fly? Some Additional Notes: The node names are all "node" except the parent and detail info (rate, price, etc) The node depth is not static. So - assume further levels than displayed in the sample Each "level" can have multiple sub-levels. So - you need to loop on each child "node" to properly build each record. Any ideas / input would be greatly appreciated. <root> <node>101 <node>A <node>PlanA <node>default <rate>100.00</rate> </node> <node>alternative <rate>90.00</rate> </node> </node> </node> </node> <node>102 <node>B <node>PlanZZ <node>Group 1 <node>default <rate>100.00</rate> </node> <node>alternative <rate>90.00</rate> </node> </node> <node>Group 2 <node>Suba <node>default <rate>1.00</rate> </node> <node>alternative <rate>88.00</rate> </node> </node> <node>Subb <node>default <rate>200.00</rate> </node> <node>alternative <rate>4.00</rate> </node> </node> </node> </node> </node> </node> </root> The Output would look like this: SRV SUB PLAN Group SubGrp DefRate AltRate 101 A PlanA 100 90 102 B PlanB Group1 100 90 102 B PlanB Group2 Suba 1 88 102 B PlanB Group2 Subb 200 4 A: That's why you have Element Tree find method with an XPath. class Plan( object ): def __init__( self ): self.srv= None self.sub= None self.plan= None self.group= None self.subgroup= None self.defrate= None self.altrate= None def initFrom( self, other ): self.srv= other.srv self.sub= other.sub self.plan= other.plan self.group= other.group self.subgroup= other.subgroup def __str__( self ): return "%s %s %s %s %s %s %s" % ( self.srv, self.sub, self.plan, self.group, self.subgroup, self.defrate, self.altrate ) def setRates( obj, aSearch ): for rate in aSearch: if rate.text.strip() == "default": obj.defrate= rate.find("rate").text.strip() elif rate.text.strip() == "alternative": obj.altrate= rate.find("rate").text.strip() else: raise Exception( "Unexpected Structure" ) def planIter( doc ): for topNode in doc.findall( "node" ): obj= Plan() obj.srv= topNode.text.strip() subNode= topNode.find("node") obj.sub= subNode.text.strip() planNode= topNode.find("node/node") obj.plan= planNode.text.strip() l3= topNode.find("node/node/node") if l3.text.strip() in ( "default", "alternative" ): setRates( obj, topNode.findall("node/node/node") ) yield obj else: for group in topNode.findall("node/node/node"): grpObj= Plan() grpObj.initFrom( obj ) grpObj.group= group.text.strip() l4= group.find( "node" ) if l4.text.strip() in ( "default", "alternative" ): setRates( grpObj, group.findall( "node" ) ) yield grpObj else: for subgroup in group.findall("node"): subgrpObj= Plan() subgrpObj.initFrom( grpObj ) subgrpObj.subgroup= subgroup.text.strip() setRates( subgrpObj, subgroup.findall("node") ) yield subgrpObj import xml.etree.ElementTree as xml doc = xml.XML( doc ) for plan in planIter( doc ): print plan Edit Whoever gave you this XML document needs to find another job. This is A Bad Thing (TM) and indicates a fairly casual disregard for what XML means. A: I'm not too familiar with the ElementTree module, but you should be able to use the getchildren() method on an element, and recursively parse data until there are no more children. This is more sudo-code than anything: def parseXml(root, data): # INSERT CODE to populate your data object here with the values # you want from this node sub_nodes = root.getchildren() for node in sub_nodes: parseXml(node, data) data = {} # I'm guessing you want a dict of some sort here to store the data you parse parseXml(parse(file).getroot(), data) # data will be filled and ready to use
Python XML - build flat record from dynamic nested "node" elements
I need to parse an XML file and build a record-based output from the data. The problem is that the XML is in a "generic" form, in that it has several levels of nested "node" elements that represent some sort of data structure. I need to build the records dynamically based on the deepest level of the "node" element. Some example XML and expected output are at the bottom. I am most familiar w/ python's ElementTree, so I'd prefer to use that but I just can't wrap my head around a way to dynamically build the output record based on a dynamic node depth. Also - we can't assume that the nested nodes will be x levels deep, so just hardcoding each level w/ a loop isn't possible. Is there a way to parse the XML and build the output on the fly? Some Additional Notes: The node names are all "node" except the parent and detail info (rate, price, etc) The node depth is not static. So - assume further levels than displayed in the sample Each "level" can have multiple sub-levels. So - you need to loop on each child "node" to properly build each record. Any ideas / input would be greatly appreciated. <root> <node>101 <node>A <node>PlanA <node>default <rate>100.00</rate> </node> <node>alternative <rate>90.00</rate> </node> </node> </node> </node> <node>102 <node>B <node>PlanZZ <node>Group 1 <node>default <rate>100.00</rate> </node> <node>alternative <rate>90.00</rate> </node> </node> <node>Group 2 <node>Suba <node>default <rate>1.00</rate> </node> <node>alternative <rate>88.00</rate> </node> </node> <node>Subb <node>default <rate>200.00</rate> </node> <node>alternative <rate>4.00</rate> </node> </node> </node> </node> </node> </node> </root> The Output would look like this: SRV SUB PLAN Group SubGrp DefRate AltRate 101 A PlanA 100 90 102 B PlanB Group1 100 90 102 B PlanB Group2 Suba 1 88 102 B PlanB Group2 Subb 200 4
[ "That's why you have Element Tree find method with an XPath.\nclass Plan( object ):\n def __init__( self ):\n self.srv= None\n self.sub= None\n self.plan= None\n self.group= None\n self.subgroup= None\n self.defrate= None\n self.altrate= None\n def initFrom( self, other ):\n self.srv= other.srv\n self.sub= other.sub\n self.plan= other.plan\n self.group= other.group\n self.subgroup= other.subgroup\n def __str__( self ):\n return \"%s %s %s %s %s %s %s\" % (\n self.srv, self.sub, self.plan, self.group, self.subgroup,\n self.defrate, self.altrate )\n\ndef setRates( obj, aSearch ):\n for rate in aSearch:\n if rate.text.strip() == \"default\":\n obj.defrate= rate.find(\"rate\").text.strip()\n elif rate.text.strip() == \"alternative\":\n obj.altrate= rate.find(\"rate\").text.strip()\n else:\n raise Exception( \"Unexpected Structure\" )\n\ndef planIter( doc ):\n for topNode in doc.findall( \"node\" ):\n obj= Plan()\n obj.srv= topNode.text.strip()\n subNode= topNode.find(\"node\")\n obj.sub= subNode.text.strip()\n planNode= topNode.find(\"node/node\")\n obj.plan= planNode.text.strip()\n l3= topNode.find(\"node/node/node\")\n if l3.text.strip() in ( \"default\", \"alternative\" ):\n setRates( obj, topNode.findall(\"node/node/node\") )\n yield obj\n else:\n for group in topNode.findall(\"node/node/node\"):\n grpObj= Plan()\n grpObj.initFrom( obj )\n grpObj.group= group.text.strip()\n l4= group.find( \"node\" )\n if l4.text.strip() in ( \"default\", \"alternative\" ):\n setRates( grpObj, group.findall( \"node\" ) )\n yield grpObj\n else:\n for subgroup in group.findall(\"node\"):\n subgrpObj= Plan()\n subgrpObj.initFrom( grpObj )\n subgrpObj.subgroup= subgroup.text.strip()\n setRates( subgrpObj, subgroup.findall(\"node\") )\n yield subgrpObj\n\nimport xml.etree.ElementTree as xml\ndoc = xml.XML( doc )\n\nfor plan in planIter( doc ):\n print plan\n\n\nEdit\nWhoever gave you this XML document needs to find another job. This is A Bad Thing (TM) and indicates a fairly casual disregard for what XML means.\n", "I'm not too familiar with the ElementTree module, but you should be able to use the getchildren() method on an element, and recursively parse data until there are no more children. This is more sudo-code than anything:\ndef parseXml(root, data):\n # INSERT CODE to populate your data object here with the values \n # you want from this node\n sub_nodes = root.getchildren()\n for node in sub_nodes:\n parseXml(node, data)\n\ndata = {} # I'm guessing you want a dict of some sort here to store the data you parse\nparseXml(parse(file).getroot(), data)\n# data will be filled and ready to use\n\n" ]
[ 4, 0 ]
[]
[]
[ "elementtree", "python", "xml" ]
stackoverflow_0000689339_elementtree_python_xml.txt
Q: Reading and Grouping a List of Data in Python I have been struggling with managing some data. I have data that I have turned into a list of lists each basic sublist has a structure like the following <1x>begins <2x>value-1 <3x>value-2 <4x>value-3 some indeterminate number of other values <1y>next observation begins <2y>value-1 <3y>value-2 <4y>value-3 some indeterminate number of other values this continues for an indeterminate number of times in each sublist EDIT I need to get all the occurrences of <2,<3 & <4 separated out and grouped together I am creating a new list of lists [[<2x>value-1,<3x>value-2, <4x>value-3], [<2y>value-1, <3y>value-2, <4y>value-3]] EDIT all of the lines that follow <4x> and <4y> (and for that matter <4anyalpha> have the same type of coding and I don't know a-priori how high the numbers can go-just think of these as sgml tags that are not closed I used numbers because my fingers were hurting from all the coding I have been doing today. The solution I have come up with finally is not very pretty listINeed=[] for sublist in biglist: for line in sublist: if '<2' in line: var2=line if '<3' in line: var3=line if '<4' in line: var4=line templist=[] templist.append(var2) templist.append(var3) templist.append(var4) listIneed.append(templist) templist=[] var4=var2=var3='' I have looked at ways to try to clean this up but have not been successful. This works fine I just saw this as another opportunity to learn more about python because I would think that this should be processable by a one line function. A: You're off to a good start by noticing that your original solution may work but lacks elegance. You should parse the string in a loop, creating a new variable for each line. Here's some sample code: import re s = """<1x>begins <2x>value-1 <3x>value-2 <4x>value-3 some indeterminate number of other values <1y>next observation begins <2y>value-1 <3y>value-2 <4y>value-3""" firstMatch = re.compile('^\<1x') numMatch = re.compile('^\<(\d+)') listIneed = [] templist = None for line in s.split(): if firstMatch.match(line): if templist is not None: listIneed.append(templist) templist = [line] elif numMatch.match(line): #print 'The matching number is %s' % numMatch.match(line).groups(1) templist.append(line) if templist is not None: listIneed.append(templist) print listIneed A: If you want to pick out the second, third, and fourth elements of each sublist, this should work: listINeed = [sublist[1:4] for sublist in biglist] A: itertools.groupby() can get you by. itertools.groupby(biglist, operator.itemgetter(2)) A: If I've understood your question correctly: import re def getlines(ori): matches = re.finditer(r'(<([1-4])[a-zA-Z]>.*)', ori) mainlist = [] sublist = [] for sr in matches: if int(sr.groups()[1]) == 1: if sublist != []: mainlist.append(sublist) sublist = [] else: sublist.append(sr.groups()[0]) else: mainlist.append(sublist) return mainlist ...would do the job for you, if you felt like using regular expressions. The version below would break all of the data down into sublists (not just the first four in each grouping) which might be more useful depending what else you need to do to the data. Use David's listINeed = [sublist[1:4] for sublist in biglist] to get the first four results from each list for the specific task above. import re def getlines(ori): matches = re.finditer(r'(<(\d*)[a-zA-Z]>.*)', ori) mainlist = [] sublist = [] for sr in matches: if int(sr.groups()[1]) == 1: print "1 found!" if sublist != []: mainlist.append(sublist) sublist = [] else: sublist.append(sr.groups()[0]) else: mainlist.append(sublist) return mainlist
Reading and Grouping a List of Data in Python
I have been struggling with managing some data. I have data that I have turned into a list of lists each basic sublist has a structure like the following <1x>begins <2x>value-1 <3x>value-2 <4x>value-3 some indeterminate number of other values <1y>next observation begins <2y>value-1 <3y>value-2 <4y>value-3 some indeterminate number of other values this continues for an indeterminate number of times in each sublist EDIT I need to get all the occurrences of <2,<3 & <4 separated out and grouped together I am creating a new list of lists [[<2x>value-1,<3x>value-2, <4x>value-3], [<2y>value-1, <3y>value-2, <4y>value-3]] EDIT all of the lines that follow <4x> and <4y> (and for that matter <4anyalpha> have the same type of coding and I don't know a-priori how high the numbers can go-just think of these as sgml tags that are not closed I used numbers because my fingers were hurting from all the coding I have been doing today. The solution I have come up with finally is not very pretty listINeed=[] for sublist in biglist: for line in sublist: if '<2' in line: var2=line if '<3' in line: var3=line if '<4' in line: var4=line templist=[] templist.append(var2) templist.append(var3) templist.append(var4) listIneed.append(templist) templist=[] var4=var2=var3='' I have looked at ways to try to clean this up but have not been successful. This works fine I just saw this as another opportunity to learn more about python because I would think that this should be processable by a one line function.
[ "You're off to a good start by noticing that your original solution may work but lacks elegance. \nYou should parse the string in a loop, creating a new variable for each line.\nHere's some sample code: \nimport re\n\ns = \"\"\"<1x>begins\n<2x>value-1\n<3x>value-2\n<4x>value-3\n some indeterminate number of other values\n<1y>next observation begins\n<2y>value-1\n<3y>value-2\n<4y>value-3\"\"\"\nfirstMatch = re.compile('^\\<1x')\nnumMatch = re.compile('^\\<(\\d+)')\nlistIneed = []\ntemplist = None\nfor line in s.split():\n if firstMatch.match(line):\n if templist is not None: \n listIneed.append(templist)\n templist = [line]\n elif numMatch.match(line):\n #print 'The matching number is %s' % numMatch.match(line).groups(1)\n templist.append(line)\nif templist is not None: listIneed.append(templist)\n\nprint listIneed\n\n", "If you want to pick out the second, third, and fourth elements of each sublist, this should work:\nlistINeed = [sublist[1:4] for sublist in biglist]\n\n", "itertools.groupby() can get you by.\nitertools.groupby(biglist, operator.itemgetter(2))\n\n", "If I've understood your question correctly:\nimport re\ndef getlines(ori):\n matches = re.finditer(r'(<([1-4])[a-zA-Z]>.*)', ori)\n mainlist = []\n sublist = []\n for sr in matches:\n if int(sr.groups()[1]) == 1:\n if sublist != []:\n mainlist.append(sublist)\n sublist = []\n else:\n sublist.append(sr.groups()[0])\n else:\n mainlist.append(sublist)\n return mainlist\n\n...would do the job for you, if you felt like using regular expressions.\nThe version below would break all of the data down into sublists (not just the first four in each grouping) which might be more useful depending what else you need to do to the data. Use David's listINeed = [sublist[1:4] for sublist in biglist] to get the first four results from each list for the specific task above.\nimport re\ndef getlines(ori):\n matches = re.finditer(r'(<(\\d*)[a-zA-Z]>.*)', ori)\n mainlist = []\n sublist = []\n for sr in matches:\n if int(sr.groups()[1]) == 1:\n print \"1 found!\"\n if sublist != []:\n mainlist.append(sublist)\n sublist = []\n else:\n sublist.append(sr.groups()[0])\n else:\n mainlist.append(sublist)\n return mainlist\n\n" ]
[ 1, 1, 1, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0000688461_list_python.txt
Q: Changing timezone on an existing Django project Like an idiot, I completely overlooked the timezone setting when I first built an application that collects datetime data. It wasn't an issue then because all I was doing was "time-since" style comparisons and ordering. Now I need to do full reports that show the actual datetime and of course, they're all stored at America/Chicago (the ridiculous Django default). So yes. I've got a medium sized database full of these dates that are incorrect. I want to change settings.TIME_ZONE to 'UTC' but that doesn't help my existing data. What's the best (read: easiest, quickest) way to convert all that Model data en-masse? (All the data is from within the past two months, so there's thankfully no DST to convert) This project is currently on SQLite but I have another project on PostgreSQL with a similar problem that I might want to do the same on before DST kicks in... So ideally a DB-agnostic answer. A: I would do a mass update to the database tables by adding or subtracting hours to/from the datetime fields. Something like this works in SQL Server, and adds 2 hours to the date: update tblName set date_field = dateadd("hh", 2, data_field)
Changing timezone on an existing Django project
Like an idiot, I completely overlooked the timezone setting when I first built an application that collects datetime data. It wasn't an issue then because all I was doing was "time-since" style comparisons and ordering. Now I need to do full reports that show the actual datetime and of course, they're all stored at America/Chicago (the ridiculous Django default). So yes. I've got a medium sized database full of these dates that are incorrect. I want to change settings.TIME_ZONE to 'UTC' but that doesn't help my existing data. What's the best (read: easiest, quickest) way to convert all that Model data en-masse? (All the data is from within the past two months, so there's thankfully no DST to convert) This project is currently on SQLite but I have another project on PostgreSQL with a similar problem that I might want to do the same on before DST kicks in... So ideally a DB-agnostic answer.
[ "I would do a mass update to the database tables by adding or subtracting hours to/from the datetime fields.\nSomething like this works in SQL Server, and adds 2 hours to the date:\nupdate tblName set date_field = dateadd(\"hh\", 2, data_field)\n\n" ]
[ 3 ]
[]
[]
[ "database_agnostic", "django", "python", "pytz", "timezone" ]
stackoverflow_0000689831_database_agnostic_django_python_pytz_timezone.txt
Q: Is it possible to Access a Users Sent Email over POP? I have been asked to quote a project where they want to see sent email using POP. I am pretty sure this is not possible, but I thought if it was. So is it possible given a users POP email server details to access their sent mail? If so any examples in Python or fetchmail? A: POP3 only handles receiving email; sent mail is sent via SMTP in these situations, and may be sent via a different ISP to the receiver (say, when you host your own email server, but use your current ISP to send). As such, this isn't directly possible. IMAP could do it, as this offers server side email folders as well as having the server handle the interface to both send and receive SMTP traffic A: Pop doesn't support sent email. Pop is an inbox only, Sent mail will be stored in IMAP, Exchange or other proprietary system. A: Emails are not sent using POP, but collected from a server using POP. They are sent using SMTP, and they don't hang around on the server once they're gone. You might want to look into IMAP? A: The smtp (mail sending) server could forward a copy of all sent mail back to the sender, they could then access this over pop.
Is it possible to Access a Users Sent Email over POP?
I have been asked to quote a project where they want to see sent email using POP. I am pretty sure this is not possible, but I thought if it was. So is it possible given a users POP email server details to access their sent mail? If so any examples in Python or fetchmail?
[ "POP3 only handles receiving email; sent mail is sent via SMTP in these situations, and may be sent via a different ISP to the receiver (say, when you host your own email server, but use your current ISP to send). As such, this isn't directly possible.\nIMAP could do it, as this offers server side email folders as well as having the server handle the interface to both send and receive SMTP traffic\n", "Pop doesn't support sent email. Pop is an inbox only, Sent mail will be stored in IMAP, Exchange or other proprietary system.\n", "Emails are not sent using POP, but collected from a server using POP. They are sent using SMTP, and they don't hang around on the server once they're gone.\nYou might want to look into IMAP?\n", "The smtp (mail sending) server could forward a copy of all sent mail back to the sender, they could then access this over pop.\n" ]
[ 5, 3, 1, 1 ]
[]
[]
[ "email", "fetchmail", "pop3", "python" ]
stackoverflow_0000690527_email_fetchmail_pop3_python.txt
Q: Is this the best way to get unique version of filename w/ Python? Still 'diving in' to Python, and want to make sure I'm not overlooking something. I wrote a script that extracts files from several zip files, and saves the extracted files together in one directory. To prevent duplicate filenames from being over-written, I wrote this little function - and I'm just wondering if there is a better way to do this? Thanks! def unique_filename(file_name): counter = 1 file_name_parts = os.path.splitext(file_name) # returns ('/path/file', '.ext') while os.path.isfile(file_name): file_name = file_name_parts[0] + '_' + str(counter) + file_name_parts[1] counter += 1 return file_name I really do require the files to be in a single directory, and numbering duplicates is definitely acceptable in my case, so I'm not looking for a more robust method (tho' I suppose any pointers are welcome), but just to make sure that what this accomplishes is getting done the right way. A: One issue is that there is a race condition in your above code, since there is a gap between testing for existance, and creating the file. There may be security implications to this (think about someone maliciously inserting a symlink to a sensitive file which they wouldn't be able to overwrite, but your program running with a higher privilege could) Attacks like these are why things like os.tempnam() are deprecated. To get around it, the best approach is to actually try create the file in such a way that you'll get an exception if it fails, and on success, return the actually opened file object. This can be done with the lower level os.open functions, by passing both the os.O_CREAT and os.O_EXCL flags. Once opened, return the actual file (and optionally filename) you create. Eg, here's your code modified to use this approach (returning a (file, filename) tuple): def unique_file(file_name): counter = 1 file_name_parts = os.path.splitext(file_name) # returns ('/path/file', '.ext') while 1: try: fd = os.open(file_name, os.O_CREAT | os.O_EXCL | os.O_RDRW) return os.fdopen(fd), file_name except OSError: pass file_name = file_name_parts[0] + '_' + str(counter) + file_name_parts[1] counter += 1 [Edit] Actually, a better way, which will handle the above issues for you, is probably to use the tempfile module, though you may lose some control over the naming. Here's an example of using it (keeping a similar interface): def unique_file(file_name): dirname, filename = os.path.split(file_name) prefix, suffix = os.path.splitext(filename) fd, filename = tempfile.mkstemp(suffix, prefix+"_", dirname) return os.fdopen(fd), filename >>> f, filename=unique_file('/home/some_dir/foo.txt') >>> print filename /home/some_dir/foo_z8f_2Z.txt The only downside with this approach is that you will always get a filename with some random characters in it, as there's no attempt to create an unmodified file (/home/some_dir/foo.txt) first. You may also want to look at tempfile.TemporaryFile and NamedTemporaryFile, which will do the above and also automatically delete from disk when closed. A: Yes, this is a good strategy for readable but unique filenames. One important change: You should replace os.path.isfile with os.path.lexists! As it is written right now, if there is a directory named /foo/bar.baz, your program will try to overwrite that with the new file (which won't work)... since isfile only checks for files and not directories. lexists checks for directories, symlinks, etc... basically if there's any reason that filename could not be created. EDIT: @Brian gave a better answer, which is more secure and robust in terms of race conditions. A: Two small changes... base_name, ext = os.path.splitext(file_name) You get two results with distinct meaning, give them distinct names. file_name = "%s_%d%s" % (base_name, str(counter), ext) It isn't faster or significantly shorter. But, when you want to change your file name pattern, the pattern is on one place, and slightly easier to work with. A: If you want readable names this looks like a good solution. There are routines to return unique file names for eg. temp files but they produce long random looking names. A: if you don't care about readability, uuid.uuid4() is your friend. import uuid def unique_filename(prefix=None, suffix=None): fn = [] if prefix: fn.extend([prefix, '-']) fn.append(str(uuid.uuid4())) if suffix: fn.extend(['.', suffix.lstrip('.')]) return ''.join(fn) A: How about def ensure_unique_filename(orig_file_path): from time import time import os if os.path.lexists(orig_file_path): name, ext = os.path.splitext(orig_file_path) orig_file_path = name + str(time()).replace('.', '') + ext return orig_file_path time() returns current time in milliseconds. combined with original filename, it's fairly unique even in complex multithreaded cases.
Is this the best way to get unique version of filename w/ Python?
Still 'diving in' to Python, and want to make sure I'm not overlooking something. I wrote a script that extracts files from several zip files, and saves the extracted files together in one directory. To prevent duplicate filenames from being over-written, I wrote this little function - and I'm just wondering if there is a better way to do this? Thanks! def unique_filename(file_name): counter = 1 file_name_parts = os.path.splitext(file_name) # returns ('/path/file', '.ext') while os.path.isfile(file_name): file_name = file_name_parts[0] + '_' + str(counter) + file_name_parts[1] counter += 1 return file_name I really do require the files to be in a single directory, and numbering duplicates is definitely acceptable in my case, so I'm not looking for a more robust method (tho' I suppose any pointers are welcome), but just to make sure that what this accomplishes is getting done the right way.
[ "One issue is that there is a race condition in your above code, since there is a gap between testing for existance, and creating the file. There may be security implications to this (think about someone maliciously inserting a symlink to a sensitive file which they wouldn't be able to overwrite, but your program running with a higher privilege could) Attacks like these are why things like os.tempnam() are deprecated.\nTo get around it, the best approach is to actually try create the file in such a way that you'll get an exception if it fails, and on success, return the actually opened file object. This can be done with the lower level os.open functions, by passing both the os.O_CREAT and os.O_EXCL flags. Once opened, return the actual file (and optionally filename) you create. Eg, here's your code modified to use this approach (returning a (file, filename) tuple):\ndef unique_file(file_name):\n counter = 1\n file_name_parts = os.path.splitext(file_name) # returns ('/path/file', '.ext')\n while 1:\n try:\n fd = os.open(file_name, os.O_CREAT | os.O_EXCL | os.O_RDRW)\n return os.fdopen(fd), file_name\n except OSError:\n pass\n file_name = file_name_parts[0] + '_' + str(counter) + file_name_parts[1]\n counter += 1\n\n[Edit] Actually, a better way, which will handle the above issues for you, is probably to use the tempfile module, though you may lose some control over the naming. Here's an example of using it (keeping a similar interface):\ndef unique_file(file_name):\n dirname, filename = os.path.split(file_name)\n prefix, suffix = os.path.splitext(filename)\n\n fd, filename = tempfile.mkstemp(suffix, prefix+\"_\", dirname)\n return os.fdopen(fd), filename\n\n>>> f, filename=unique_file('/home/some_dir/foo.txt')\n>>> print filename\n/home/some_dir/foo_z8f_2Z.txt\n\nThe only downside with this approach is that you will always get a filename with some random characters in it, as there's no attempt to create an unmodified file (/home/some_dir/foo.txt) first.\nYou may also want to look at tempfile.TemporaryFile and NamedTemporaryFile, which will do the above and also automatically delete from disk when closed.\n", "Yes, this is a good strategy for readable but unique filenames.\nOne important change: You should replace os.path.isfile with os.path.lexists! As it is written right now, if there is a directory named /foo/bar.baz, your program will try to overwrite that with the new file (which won't work)... since isfile only checks for files and not directories. lexists checks for directories, symlinks, etc... basically if there's any reason that filename could not be created.\nEDIT: @Brian gave a better answer, which is more secure and robust in terms of race conditions.\n", "Two small changes...\nbase_name, ext = os.path.splitext(file_name) \n\nYou get two results with distinct meaning, give them distinct names.\nfile_name = \"%s_%d%s\" % (base_name, str(counter), ext)\n\nIt isn't faster or significantly shorter. But, when you want to change your file name pattern, the pattern is on one place, and slightly easier to work with.\n", "If you want readable names this looks like a good solution.\nThere are routines to return unique file names for eg. temp files but they produce long random looking names.\n", "if you don't care about readability, uuid.uuid4() is your friend.\nimport uuid\n\ndef unique_filename(prefix=None, suffix=None):\n fn = []\n if prefix: fn.extend([prefix, '-'])\n fn.append(str(uuid.uuid4()))\n if suffix: fn.extend(['.', suffix.lstrip('.')])\n return ''.join(fn)\n\n", "How about \ndef ensure_unique_filename(orig_file_path): \n from time import time\n import os\n\n if os.path.lexists(orig_file_path):\n name, ext = os.path.splitext(orig_file_path)\n orig_file_path = name + str(time()).replace('.', '') + ext\n\n return orig_file_path\n\ntime() returns current time in milliseconds. combined with original filename, it's fairly unique even in complex multithreaded cases.\n" ]
[ 24, 6, 2, 1, 1, 0 ]
[]
[]
[ "filenames", "python" ]
stackoverflow_0000183480_filenames_python.txt
Q: Handling output of python socket recv Apologies for the noob Python question but I've been stuck on this for far too long. I'm using python sockets to receive some data from a server. I do this: data = self.socket.recv(4) print "data is ", data print "repr(data) is ", repr(data) The output on the console is this: data is repr(data) is '\x00\x00\x00\x01' I want to turn this string containing essentially a 4 byte number into an int - or actually what would be a long in C. How can I turn this data object into a numerical value that I can easily manage? A: You probably want to use struct. The code would look something like: import struct data = self.socket.recv(4) print "data is ", data print "repr(data) is ", repr(data) myint = struct.unpack("!i", data)[0]
Handling output of python socket recv
Apologies for the noob Python question but I've been stuck on this for far too long. I'm using python sockets to receive some data from a server. I do this: data = self.socket.recv(4) print "data is ", data print "repr(data) is ", repr(data) The output on the console is this: data is repr(data) is '\x00\x00\x00\x01' I want to turn this string containing essentially a 4 byte number into an int - or actually what would be a long in C. How can I turn this data object into a numerical value that I can easily manage?
[ "You probably want to use struct.\nThe code would look something like:\nimport struct\n\ndata = self.socket.recv(4)\nprint \"data is \", data\nprint \"repr(data) is \", repr(data)\nmyint = struct.unpack(\"!i\", data)[0]\n\n" ]
[ 10 ]
[]
[]
[ "python", "sockets" ]
stackoverflow_0000691345_python_sockets.txt
Q: How do I order referenced objects from a Google App Engine Datastore query? I have Exhibit objects which reference Gallery objects both of which are stored in the Google App Engine Datastore. How do I order the Exhibit collection on each Gallery object when I get around to iterating over the values (ultimately in a Django template)? i.e. this does not work class Gallery(db.Model): title = db.StringProperty() position = db.IntegerProperty() class Exhibit(db.Model): gallery = db.ReferenceProperty(Gallery, collection_name='exhibits') title = db.StringProperty() position = db.IntegerProperty() galleries = db.GqlQuery('SELECT * FROM Gallery ORDER BY position') for gallery in galleries: gallery.exhibits.order('position') # ... send galleries off the the Django template When rendered in the template, the galleries are correctly ordered but the exhibits are not. A: Instead of relying on the collection property App Engine creates, you need to construct your own query: exhibits = Exhibit.all().filter("gallery =", gallery).order("position") Or equivalently, in GQL: exhibits = db.GqlQuery("SELECT * FROM Exhibit WHERE gallery = :1 ORDER BY position", gallery) If you want to be able to do this from inside the template, rather than passing in a list-of-lists of exhibits, you can define a simple method on the Gallery object that executes this query, and reference it from the template (Eg, {{gallery.exhibits_by_position}} will execute exhibits_by_position() on the Gallery object, which can then perform the query above). If you're concerned about the speed implications of this, don't worry: The collection property App Engine creates is simply syntactic sugar for this.
How do I order referenced objects from a Google App Engine Datastore query?
I have Exhibit objects which reference Gallery objects both of which are stored in the Google App Engine Datastore. How do I order the Exhibit collection on each Gallery object when I get around to iterating over the values (ultimately in a Django template)? i.e. this does not work class Gallery(db.Model): title = db.StringProperty() position = db.IntegerProperty() class Exhibit(db.Model): gallery = db.ReferenceProperty(Gallery, collection_name='exhibits') title = db.StringProperty() position = db.IntegerProperty() galleries = db.GqlQuery('SELECT * FROM Gallery ORDER BY position') for gallery in galleries: gallery.exhibits.order('position') # ... send galleries off the the Django template When rendered in the template, the galleries are correctly ordered but the exhibits are not.
[ "Instead of relying on the collection property App Engine creates, you need to construct your own query:\n\nexhibits = Exhibit.all().filter(\"gallery =\", gallery).order(\"position\")\n\nOr equivalently, in GQL:\n\nexhibits = db.GqlQuery(\"SELECT * FROM Exhibit WHERE gallery = :1 ORDER BY position\", gallery)\n\nIf you want to be able to do this from inside the template, rather than passing in a list-of-lists of exhibits, you can define a simple method on the Gallery object that executes this query, and reference it from the template (Eg, {{gallery.exhibits_by_position}} will execute exhibits_by_position() on the Gallery object, which can then perform the query above).\nIf you're concerned about the speed implications of this, don't worry: The collection property App Engine creates is simply syntactic sugar for this.\n" ]
[ 4 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0000691217_google_app_engine_google_cloud_datastore_python.txt
Q: Passing functions which have multiple return values as arguments in Python So, Python functions can return multiple values. It struck me that it would be convenient (though a bit less readable) if the following were possible. a = [[1,2],[3,4]] def cord(): return 1, 1 def printa(y,x): print a[y][x] printa(cord()) ...but it's not. I'm aware that you can do the same thing by dumping both return values into temporary variables, but it doesn't seem as elegant. I could also rewrite the last line as "printa(cord()[0], cord()[1])", but that would execute cord() twice. Is there an elegant, efficient way to do this? Or should I just see that quote about premature optimization and forget about this? A: printa(*cord()) The * here is an argument expansion operator... well I forget what it's technically called, but in this context it takes a list or tuple and expands it out so the function sees each list/tuple element as a separate argument. It's basically the reverse of the * you might use to capture all non-keyword arguments in a function definition: def fn(*args): # args is now a tuple of the non-keyworded arguments print args fn(1, 2, 3, 4, 5) prints (1, 2, 3, 4, 5) fn(*[1, 2, 3, 4, 5]) does the same. A: Try this: >>> def cord(): ... return (1, 1) ... >>> def printa(y, x): ... print a[y][x] ... >>> a=[[1,2],[3,4]] >>> printa(*cord()) 4 The star basically says "use the elements of this collection as positional arguments." You can do the same with a dict for keyword arguments using two stars: >>> a = {'a' : 2, 'b' : 3} >>> def foo(a, b): ... print a, b ... >>> foo(**a) 2 3 A: Actually, Python doesn't really return multiple values, it returns one value which can be multiple values packed into a tuple. Which means that you need to "unpack" the returned value in order to have multiples. A statement like x,y = cord() does that, but directly using the return value as you did in printa(cord()) doesn't, that's why you need to use the asterisk. Perhaps a nice term for it might be "implicit tuple unpacking" or "tuple unpacking without assignment".
Passing functions which have multiple return values as arguments in Python
So, Python functions can return multiple values. It struck me that it would be convenient (though a bit less readable) if the following were possible. a = [[1,2],[3,4]] def cord(): return 1, 1 def printa(y,x): print a[y][x] printa(cord()) ...but it's not. I'm aware that you can do the same thing by dumping both return values into temporary variables, but it doesn't seem as elegant. I could also rewrite the last line as "printa(cord()[0], cord()[1])", but that would execute cord() twice. Is there an elegant, efficient way to do this? Or should I just see that quote about premature optimization and forget about this?
[ "printa(*cord())\n\nThe * here is an argument expansion operator... well I forget what it's technically called, but in this context it takes a list or tuple and expands it out so the function sees each list/tuple element as a separate argument.\nIt's basically the reverse of the * you might use to capture all non-keyword arguments in a function definition:\ndef fn(*args):\n # args is now a tuple of the non-keyworded arguments\n print args\n\nfn(1, 2, 3, 4, 5)\n\nprints (1, 2, 3, 4, 5)\nfn(*[1, 2, 3, 4, 5])\n\ndoes the same.\n", "Try this:\n>>> def cord():\n... return (1, 1)\n...\n>>> def printa(y, x):\n... print a[y][x]\n...\n>>> a=[[1,2],[3,4]]\n>>> printa(*cord())\n4\n\nThe star basically says \"use the elements of this collection as positional arguments.\" You can do the same with a dict for keyword arguments using two stars:\n>>> a = {'a' : 2, 'b' : 3}\n>>> def foo(a, b):\n... print a, b\n...\n>>> foo(**a)\n2 3\n\n", "Actually, Python doesn't really return multiple values, it returns one value which can be multiple values packed into a tuple. Which means that you need to \"unpack\" the returned value in order to have multiples.\nA statement like \nx,y = cord()\n\ndoes that, but directly using the return value as you did in \nprinta(cord())\n\ndoesn't, that's why you need to use the asterisk. Perhaps a nice term for it might be \"implicit tuple unpacking\" or \"tuple unpacking without assignment\".\n" ]
[ 30, 6, 4 ]
[]
[]
[ "function_calls", "python", "return_value" ]
stackoverflow_0000691267_function_calls_python_return_value.txt
Q: Is there a method in python that's like os.path.split for other delimiters? I want to use something like this: os.path.split("C:\\a\\b\\c") With this kind of output: ('C:\a\b', 'c') However I want it to work on other delimiters like this: method ('a_b_c_d') With this kind of output: ('a_b_c', 'd') A: >>> 'a_b_c_d'.rsplit('_', 1) ['a_b_c', 'd'] Help on built-in function rsplit: rsplit(...) S.rsplit([sep [,maxsplit]]) -> list of strings Return a list of the words in the string S, using sep as the delimiter string, starting at the end of the string and working to the front. If maxsplit is given, at most maxsplit splits are done. If sep is not specified or is None, any whitespace string is a separator. A: string.split(separator)
Is there a method in python that's like os.path.split for other delimiters?
I want to use something like this: os.path.split("C:\\a\\b\\c") With this kind of output: ('C:\a\b', 'c') However I want it to work on other delimiters like this: method ('a_b_c_d') With this kind of output: ('a_b_c', 'd')
[ ">>> 'a_b_c_d'.rsplit('_', 1)\n['a_b_c', 'd']\n\n\nHelp on built-in function rsplit:\nrsplit(...)\n S.rsplit([sep [,maxsplit]]) -> list of strings\nReturn a list of the words in the string S, using sep as the\n delimiter string, starting at the end of the string and working\n to the front. If maxsplit is given, at most maxsplit splits are\n done. If sep is not specified or is None, any whitespace string\n is a separator.\n\n", "string.split(separator)\n\n" ]
[ 15, 0 ]
[]
[]
[ "python", "string" ]
stackoverflow_0000691740_python_string.txt
Q: Python: How do you login to a page and view the resulting page in a browser? I've been googling around for quite some time now and can't seem to get this to work. A lot of my searches have pointed me to finding similar problems but they all seem to be related to cookie grabbing/storing. I think I've set that up properly, but when I try to open the 'hidden' page, it keeps bringing me back to the login page saying my session has expired. import urllib, urllib2, cookielib, webbrowser username = 'userhere' password = 'passwordhere' url = 'http://example.com' webbrowser.open(url, new=1, autoraise=1) cj = cookielib.CookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) login_data = urllib.urlencode({'username' : username, 'j_password' : password}) opener.open('http://example.com', login_data) resp = opener.open('http://example.com/afterlogin') print resp webbrowser.open(url, new=1, autoraise=1) A: First off, when doing cookie-based authentication, you need to have a CookieJar to store your cookies in, much in the same way that your browser stores its cookies a place where it can find them again. After opening a login-page through python, and saving the cookie from a successful login, you should use the MozillaCookieJar to pass the python created cookies to a format a firefox browser can parse. Firefox 3.x no longer uses the cookie format that MozillaCookieJar produces, and I have not been able to find viable alternatives. If all you need to do is to retrieve specific (in advance known format formatted) data, then I suggest you keep all your HTTP interactions within python. It is much easier, and you don't have to rely on specific browsers being available. If it is absolutely necessary to show stuff in a browser, you could render the so-called 'hidden' page through urllib2 (which incidentally integrates very nicely with cookielib), save the html to a temporary file and pass this to the webbrowser.open which will then render that specific page. Further redirects are not possible. A: I've generally used the mechanize library to handle stuff like this. That doesn't answer your question about why your existing code isn't working, but it's something else to play with. A: The provided code calls: opener.open('http://example.com', login_data) but throws away the response. I would look at this response to see if it says "Bad password" or "I only accept IE" or similar.
Python: How do you login to a page and view the resulting page in a browser?
I've been googling around for quite some time now and can't seem to get this to work. A lot of my searches have pointed me to finding similar problems but they all seem to be related to cookie grabbing/storing. I think I've set that up properly, but when I try to open the 'hidden' page, it keeps bringing me back to the login page saying my session has expired. import urllib, urllib2, cookielib, webbrowser username = 'userhere' password = 'passwordhere' url = 'http://example.com' webbrowser.open(url, new=1, autoraise=1) cj = cookielib.CookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) login_data = urllib.urlencode({'username' : username, 'j_password' : password}) opener.open('http://example.com', login_data) resp = opener.open('http://example.com/afterlogin') print resp webbrowser.open(url, new=1, autoraise=1)
[ "First off, when doing cookie-based authentication, you need to have a CookieJar to store your cookies in, much in the same way that your browser stores its cookies a place where it can find them again.\nAfter opening a login-page through python, and saving the cookie from a successful login, you should use the MozillaCookieJar to pass the python created cookies to a format a firefox browser can parse. Firefox 3.x no longer uses the cookie format that MozillaCookieJar produces, and I have not been able to find viable alternatives.\nIf all you need to do is to retrieve specific (in advance known format formatted) data, then I suggest you keep all your HTTP interactions within python. It is much easier, and you don't have to rely on specific browsers being available. If it is absolutely necessary to show stuff in a browser, you could render the so-called 'hidden' page through urllib2 (which incidentally integrates very nicely with cookielib), save the html to a temporary file and pass this to the webbrowser.open which will then render that specific page. Further redirects are not possible.\n", "I've generally used the mechanize library to handle stuff like this. That doesn't answer your question about why your existing code isn't working, but it's something else to play with.\n", "The provided code calls:\nopener.open('http://example.com', login_data)\n\nbut throws away the response. I would look at this response to see if it says \"Bad password\" or \"I only accept IE\" or similar.\n" ]
[ 4, 1, 0 ]
[]
[]
[ "authentication", "python" ]
stackoverflow_0000663490_authentication_python.txt
Q: How do I track an animated object in Python? I want to automate playing a video game with Python. I want to write a script that can grab the screen image, diff it with the next frame and track an object to click on. What libraries would be useful for this other than PIL? A: There are a few options here. The brute force diff'ing approach will lead to a lot of frustration unless what you're tracking is very consistent. For this you could use any number of genetic approaches to train your program what to follow. After enough generations it would do the right thing reliably. If the thing you want to track is visually obvious (like a red ball on a white screen) then you could detect it yourself through simple brute force scanning of the bitmap. Another approach would be just looking at the memory of the running app, and figuring out what area is controlling the position of your object. For some more info and ideas on this, see how mumble got 3D positional audio working in various games. http://mumble.sourceforge.net/HackPositionalAudio A: Answer would depend on the platform and game too. e.g. I did once similar things for helicopter flash game, as it was very simple 2d game with well defined colored maze It was on widows with copy to clipboard and win32 key events using win32api bindings for python.
How do I track an animated object in Python?
I want to automate playing a video game with Python. I want to write a script that can grab the screen image, diff it with the next frame and track an object to click on. What libraries would be useful for this other than PIL?
[ "There are a few options here. The brute force diff'ing approach will lead to a lot of frustration unless what you're tracking is very consistent. For this you could use any number of genetic approaches to train your program what to follow. After enough generations it would do the right thing reliably. If the thing you want to track is visually obvious (like a red ball on a white screen) then you could detect it yourself through simple brute force scanning of the bitmap.\nAnother approach would be just looking at the memory of the running app, and figuring out what area is controlling the position of your object. For some more info and ideas on this, see how mumble got 3D positional audio working in various games.\nhttp://mumble.sourceforge.net/HackPositionalAudio\n", "Answer would depend on the platform and game too.\ne.g. I did once similar things for helicopter flash game, as it was very simple 2d game with well defined colored maze\nIt was on widows with copy to clipboard and win32 key events using win32api bindings for python.\n" ]
[ 0, 0 ]
[]
[]
[ "animation", "image_manipulation", "python" ]
stackoverflow_0000692259_animation_image_manipulation_python.txt
Q: Resolving dependency in python between modules I am a newbie to python. I do have two modules. Model M1 and module m2. From m2 , i need to refer m1 and m2 and m1 resides at two different locations in disk. When I am trying to import m1 before executing m2 , of course it's saying can't find m1. How I can point my interpreter to m1's location. Thanks J A: It's not entirely clear what your specific problem is (give more details!), but you may find these useful (further Googling will help you reach concrete answers for your specific needs): The PYTHONPATH environment variable .pth files in directories that appear in PYTHONPATH Manipulating sys.path before importing However, if m2 depends on m1, and they're distributed together, perhaps it's a better idea to place them in the same directory tree using packages. A: If you can't modify the shell environment, you can append any directories you want the interpreter to search for modules to sys.path from within your script. In fact, the PYTHONPATH environment variable is read and used to initialize sys.path. A: What's possible depends on the details of the modules, but usually you can just import the specifics objects needed from the modules, like this: in B.py from A import classA1, funA1 in A.py from B import classB1, funB1 so that you only import what's needed. If the dependencies are more complex, this may not work, but in general it should be possible (unless you actually have real mutual, recursive dependencies at the object level which you can't resolve!).
Resolving dependency in python between modules
I am a newbie to python. I do have two modules. Model M1 and module m2. From m2 , i need to refer m1 and m2 and m1 resides at two different locations in disk. When I am trying to import m1 before executing m2 , of course it's saying can't find m1. How I can point my interpreter to m1's location. Thanks J
[ "It's not entirely clear what your specific problem is (give more details!), but you may find these useful (further Googling will help you reach concrete answers for your specific needs):\n\nThe PYTHONPATH environment variable\n.pth files in directories that appear in PYTHONPATH\nManipulating sys.path before importing\n\nHowever, if m2 depends on m1, and they're distributed together, perhaps it's a better idea to place them in the same directory tree using packages.\n", "If you can't modify the shell environment, you can append any directories you want the interpreter to search for modules to sys.path from within your script. In fact, the PYTHONPATH environment variable is read and used to initialize sys.path.\n", "What's possible depends on the details of the modules, but usually you can just import the specifics objects needed from the modules, like this:\nin B.py\nfrom A import classA1, funA1\n\nin A.py\nfrom B import classB1, funB1\n\nso that you only import what's needed. If the dependencies are more complex, this may not work, but in general it should be possible (unless you actually have real mutual, recursive dependencies at the object level which you can't resolve!).\n" ]
[ 3, 2, 0 ]
[]
[]
[ "dependencies", "python" ]
stackoverflow_0000692506_dependencies_python.txt
Q: What library is best for GUI in python? Duplicate: Cross-platform gui toolkit for deploying Python applications I want to create a GUI application in python. Which library is best one? A: From the question Cross-platform gui toolkit for deploying Python applications: PyQt It's build on top of Qt, a C++ framework. It's quite advanced and has some good tools like the Qt Designer to design your applications. You should be aware though, that it doesn't feel like Python 100%, but close to it. This framework is really good. It's being actively developed by Trolltech, who is owned by Nokia. The bindings for Python are developed by Riverbank. Nokia announced that they'd start to use LGPL for the Qt-Framework starting with Qt 4.5 (to be released in April, I think), but it's not yet sure if Riverbank follows this and releases the bindings for Python under LGPL too. (They have a commercial and a GPL licence at the moment.) Qt is not only a GUI-framework but has a lot of other classes too, one can create an application by just using Qt classes. (Like SQL, networking…) Qt doesn't use native GUI elements, but wikipedia mentions that in recent versions Qt uses native widgets where possible. I haven't found evidence in the documentation but for Mac OS X. wxPython wxPython is a binding for Python using the wxWidgets-Framework. This framework is under the LGPL licence and is developed by the open source community. What I'm really missing is a good tool to design the interface, they have about 3 but none of them is usable. One thing I should mention is that I found a bug in the tab-view despite the fact that I didn't use anything advanced. (Only on Mac OS X) I think wxWidgets isn't as polished as Qt. wxPython is really only about the GUI-classes, there isn't much else. wxWidgets uses native GUI elements. Others I haven't got any experience with other GUI frameworks, maybe someone else has. A: wxWidgets (the Python flavor is called wxPython) is currently your best option IMHO, they have support for multi platform (Mac, Window, Linux) and the framework is pretty easy to work with. From the site: wxWidgets lets developers create applications for Win32, Mac OS X, GTK+, X11, Motif, WinCE, and more using one codebase. It can be used from languages such as C++, Python, Perl, and C#/.NET. Unlike other cross-platform toolkits, wxWidgets applications look and feel native. This is because wxWidgets uses the platform's own native controls rather than emulating them. It's also extensive, free, open-source, and mature. Why not give it a try, like A: I like PyQt. wxPython has many warts, and the code you write in PyQt is often much cleaner. The UI designer is very helpful as well. A: For general-purpose GUI applications, I would recommend wxPython. It's the python flavor of the wxWidgets project. It's easy to work with, cross-platform, full-featured and the demo is actually a great tutorial. For game-like GUIs, I would go with pyGame. It's also very simple and powerful: you can program a little game in minutes. A: I'd recommend you wxPython.
What library is best for GUI in python?
Duplicate: Cross-platform gui toolkit for deploying Python applications I want to create a GUI application in python. Which library is best one?
[ "From the question Cross-platform gui toolkit for deploying Python applications:\n\nPyQt\nIt's build on top of Qt, a C++\n framework. It's quite advanced and has\n some good tools like the Qt Designer\n to design your applications. You\n should be aware though, that it\n doesn't feel like Python 100%, but\n close to it.\nThis framework is really good. It's\n being actively developed by Trolltech,\n who is owned by Nokia. The bindings\n for Python are developed by Riverbank.\nNokia announced that they'd start to\n use LGPL for the Qt-Framework starting\n with Qt 4.5 (to be released in April,\n I think), but it's not yet sure if\n Riverbank follows this and releases\n the bindings for Python under LGPL\n too. (They have a commercial and a GPL\n licence at the moment.)\nQt is not only a GUI-framework but has\n a lot of other classes too, one can\n create an application by just using Qt\n classes. (Like SQL, networking…)\nQt doesn't use native GUI elements,\n but wikipedia mentions that in recent\n versions Qt uses native\n widgets where\n possible. I haven't found evidence in\n the documentation but for Mac OS\n X.\nwxPython\nwxPython is a binding for Python using\n the wxWidgets-Framework.\n This framework is under the LGPL\n licence and is developed by the open\n source community.\nWhat I'm really missing is a good tool\n to design the interface, they have\n about 3 but none of them is usable.\nOne thing I should mention is that I\n found a bug in the tab-view despite\n the fact that I didn't use anything\n advanced. (Only on Mac OS X) I think\n wxWidgets isn't as\n polished as Qt.\nwxPython is really only about the\n GUI-classes, there isn't much else.\nwxWidgets uses native GUI elements.\nOthers\nI haven't got any experience with\n other GUI frameworks, maybe someone\n else has.\n\n", "wxWidgets (the Python flavor is called wxPython) is currently your best option IMHO, they have support for multi platform (Mac, Window, Linux) and the framework is pretty easy to work with.\nFrom the site: \nwxWidgets lets developers create applications for Win32, Mac OS X, GTK+, X11, Motif, WinCE, and more using one codebase. It can be used from languages such as C++, Python, Perl, and C#/.NET. Unlike other cross-platform toolkits, wxWidgets applications look and feel native. This is because wxWidgets uses the platform's own native controls rather than emulating them. It's also extensive, free, open-source, and mature. Why not give it a try, like \n", "I like PyQt. wxPython has many warts, and the code you write in PyQt is often much cleaner. The UI designer is very helpful as well.\n", "For general-purpose GUI applications, I would recommend wxPython. It's the python flavor of the wxWidgets project. It's easy to work with, cross-platform, full-featured and the demo is actually a great tutorial.\nFor game-like GUIs, I would go with pyGame. It's also very simple and powerful: you can program a little game in minutes.\n", "I'd recommend you wxPython.\n" ]
[ 7, 5, 3, 1, 0 ]
[ "TKInter. easiest.\n" ]
[ -1 ]
[ "python", "user_interface" ]
stackoverflow_0000692566_python_user_interface.txt
Q: Django or CodeIgniter for Turn-Key Web Application I'm going to build a turn-key solution for a vertical market, and would like to offer both options: software as a service, and give them the opportunity to host the application on their own. In other words, I'm aiming to have similar deployment options as Joel's FogBugz. I'm a Python programmer, and I could fly over the project with Django. There are several reasons I prefer PHP though: 1) Django installation, and configuration assumes you have access to a shell (my target is not the programmer type). Although I could offer installation service, but not on their servers. 2) Django runs only on some specific hosts that must take special care to enable it. Installing mod_python/mod_wsgi, and most likely the minority of my potential clients would have root access, or even a cpanel. 3) Using PHP would mean I could run it on their existing server. I would have no need to move them to a Django-enabled server, and no downtime for their emails, while the DNS updates. On the other hand, I have very little experience with PHP. Smarty as a templating language looks nice, and works similarly to Django templates. It doesn't offer template inheritance though, except in a very hackish way in which I wish not to use as it could break the application if the designer messes them up. What do you think? Thanks in advance! A: Deployment is clearly a problem for all non-PHP based web apps, but I think things are getting better with the DreamHost/Engineyard type ISP's who provide Ruby/Python etc. out of the box. It also looks like there's going to be a lot of discussion at PyCon this week about ways to fix deployment problems. The growth in popularity of Django, Turbogears, and Pylons is driving demand for better deployment solutions. That said, if your target market are people hosting on the very low end $12 a year type ISP's then I don't think you have much choice other than PHP. Finally, one thing I disagree with you is running PHP and Django on the same server. I'm running a few PHP apps on my server with Apache and dozens of Django sites with mod_wsgi in daemon mode. Running it that way means the Python interpreter doesn't use up ram in the Apache workers and vice versa, the PHP interpreter isn't contaminating my mod_wsgi daemons :) A: If you want your application to be mainstream then your almost forced to go with PHP. Going from Django to PHP is alot easier than going from PHP to Django. You know the standards, you just need to learn the PHP syntax and functions. I would definitely use a PHP framework. Symfony and akelos are very similar to Rails (close to Django). On the other than theres Code Igniter which does what it should - organise your code. A: Based on your own conclusions, I would go with CodeIgniter. It seems like there would be a ton of work helping your customers install your web app, and I assume you don't want that. Build a simple-to-install web app so that you can concentrate your efforts on making it better and selling it, instead of working extra as a sysadmin or writing extensive installation tutorials. (With that said, FogBugz wasn't easy to install on our Linux server, even though it is written in PHP. It took me and my colleague (both programmers!) more than a full work day to install. So I think there will always be problems with installation of self-hosted web apps.)
Django or CodeIgniter for Turn-Key Web Application
I'm going to build a turn-key solution for a vertical market, and would like to offer both options: software as a service, and give them the opportunity to host the application on their own. In other words, I'm aiming to have similar deployment options as Joel's FogBugz. I'm a Python programmer, and I could fly over the project with Django. There are several reasons I prefer PHP though: 1) Django installation, and configuration assumes you have access to a shell (my target is not the programmer type). Although I could offer installation service, but not on their servers. 2) Django runs only on some specific hosts that must take special care to enable it. Installing mod_python/mod_wsgi, and most likely the minority of my potential clients would have root access, or even a cpanel. 3) Using PHP would mean I could run it on their existing server. I would have no need to move them to a Django-enabled server, and no downtime for their emails, while the DNS updates. On the other hand, I have very little experience with PHP. Smarty as a templating language looks nice, and works similarly to Django templates. It doesn't offer template inheritance though, except in a very hackish way in which I wish not to use as it could break the application if the designer messes them up. What do you think? Thanks in advance!
[ "Deployment is clearly a problem for all non-PHP based web apps, but I think things are getting better with the DreamHost/Engineyard type ISP's who provide Ruby/Python etc. out of the box. It also looks like there's going to be a lot of discussion at PyCon this week about ways to fix deployment problems. The growth in popularity of Django, Turbogears, and Pylons is driving demand for better deployment solutions.\nThat said, if your target market are people hosting on the very low end $12 a year type ISP's then I don't think you have much choice other than PHP.\nFinally, one thing I disagree with you is running PHP and Django on the same server. I'm running a few PHP apps on my server with Apache and dozens of Django sites with mod_wsgi in daemon mode. Running it that way means the Python interpreter doesn't use up ram in the Apache workers and vice versa, the PHP interpreter isn't contaminating my mod_wsgi daemons :)\n", "If you want your application to be mainstream then your almost forced to go with PHP. Going from Django to PHP is alot easier than going from PHP to Django. You know the standards, you just need to learn the PHP syntax and functions.\nI would definitely use a PHP framework. Symfony and akelos are very similar to Rails (close to Django). On the other than theres Code Igniter which does what it should - organise your code.\n", "Based on your own conclusions, I would go with CodeIgniter. It seems like there would be a ton of work helping your customers install your web app, and I assume you don't want that.\nBuild a simple-to-install web app so that you can concentrate your efforts on making it better and selling it, instead of working extra as a sysadmin or writing extensive installation tutorials.\n(With that said, FogBugz wasn't easy to install on our Linux server, even though it is written in PHP. It took me and my colleague (both programmers!) more than a full work day to install. So I think there will always be problems with installation of self-hosted web apps.)\n" ]
[ 4, 3, 2 ]
[]
[]
[ "codeigniter", "django", "php", "python" ]
stackoverflow_0000690856_codeigniter_django_php_python.txt
Q: Is it ever polite to put code in a python configuration file? One of my favorite features about python is that you can write configuration files in python that are very simple to read and understand. If you put a few boundaries on yourself, you can be pretty confident that non-pythonistas will know exactly what you mean and will be perfectly capable of reconfiguring your program. My question is, what exactly are those boundaries? My own personal heuristic was Avoid flow control. No functions, loops, or conditionals. Those wouldn't be in a text config file and people aren't expecting to have understand them. In general, it probably shouldn't matter the order in which your statements execute. Stick to literal assignments. Methods and functions called on objects are harder to think through. Anything implicit is going to be a mess. If there's something complicated that has to happen with your parameters, change how they're interpreted. Language keywords and error handling are right out. I guess I ask this because I came across a situation with my Django config file where it seems to be useful to break these rules. I happen to like it, but I feel a little guilty. Basically, my project is deployed through svn checkouts to a couple different servers that won't all be configured the same (some will share a database, some won't, for example). So, I throw a hook at the end: try: from settings_overrides import * LOCALIZED = True except ImportError: LOCALIZED = False where settings_overrides is on the python path but outside the working copy. What do you think, either about this example, or about python config boundaries in general? A: There is a Django wiki page, which addresses exactly the thing you're asking. http://code.djangoproject.com/wiki/SplitSettings Do not reinvent the wheel. Use configparser and INI files. Python files are to easy to break by someone, who doesn't know Python. A: Your heuristics are good. Rules are made so that boundaries are set and only broken when it's obviously a vastly better solution than the alternate. Still, I can't help but wonder that the site checking code should be in the parser, and an additional configuration item added that selects which option should be taken. I don't think that in this case the alternative is so bad that breaking the rules makes sense... -Adam A: I think it's a pain vs pleasure argument. It's not wrong to put code in a Python config file because it's all valid Python, but it does mean you could confuse a user who comes in to reconfigure an app. If you're that worried about it, rope it off with comments explaining roughly what it does and that the user shouldn't edit it, rather edit the settings_overrides.py file. As for your example, that's nigh on essential for developers to test then deploy their apps. Definitely more pleasure than pain. But you should really do this instead: LOCALIZED = False try: from settings_overrides import * except ImportError: pass And in your settings_overrides.py file: LOCALIZED = True ... If nothing but to make it clear what that file does.. What you're doing there splits overrides into two places. A: As a general practice, see the other answers on the page; it all depends. Specifically for Django, however, I see nothing fundamentally wrong with writing code in the settings.py file... after all, the settings file IS code :-) The Django docs on settings themselves say: A settings file is just a Python module with module-level variables. And give the example: assign settings dynamically using normal Python syntax. For example: MY_SETTING = [str(i) for i in range(30)] A: Settings as code is also a security risk. You import your "config", but in reality you are executing whatever code is in that file. Put config in files that you parse first and you can reject nonsensical or malicious values, even if it is more work for you. I blogged about this in December 2008.
Is it ever polite to put code in a python configuration file?
One of my favorite features about python is that you can write configuration files in python that are very simple to read and understand. If you put a few boundaries on yourself, you can be pretty confident that non-pythonistas will know exactly what you mean and will be perfectly capable of reconfiguring your program. My question is, what exactly are those boundaries? My own personal heuristic was Avoid flow control. No functions, loops, or conditionals. Those wouldn't be in a text config file and people aren't expecting to have understand them. In general, it probably shouldn't matter the order in which your statements execute. Stick to literal assignments. Methods and functions called on objects are harder to think through. Anything implicit is going to be a mess. If there's something complicated that has to happen with your parameters, change how they're interpreted. Language keywords and error handling are right out. I guess I ask this because I came across a situation with my Django config file where it seems to be useful to break these rules. I happen to like it, but I feel a little guilty. Basically, my project is deployed through svn checkouts to a couple different servers that won't all be configured the same (some will share a database, some won't, for example). So, I throw a hook at the end: try: from settings_overrides import * LOCALIZED = True except ImportError: LOCALIZED = False where settings_overrides is on the python path but outside the working copy. What do you think, either about this example, or about python config boundaries in general?
[ "There is a Django wiki page, which addresses exactly the thing you're asking.\nhttp://code.djangoproject.com/wiki/SplitSettings\nDo not reinvent the wheel. Use configparser and INI files. Python files are to easy to break by someone, who doesn't know Python. \n", "Your heuristics are good. Rules are made so that boundaries are set and only broken when it's obviously a vastly better solution than the alternate.\nStill, I can't help but wonder that the site checking code should be in the parser, and an additional configuration item added that selects which option should be taken.\nI don't think that in this case the alternative is so bad that breaking the rules makes sense...\n-Adam\n", "I think it's a pain vs pleasure argument. \nIt's not wrong to put code in a Python config file because it's all valid Python, but it does mean you could confuse a user who comes in to reconfigure an app. If you're that worried about it, rope it off with comments explaining roughly what it does and that the user shouldn't edit it, rather edit the settings_overrides.py file.\nAs for your example, that's nigh on essential for developers to test then deploy their apps. Definitely more pleasure than pain. But you should really do this instead:\nLOCALIZED = False\n\ntry:\n from settings_overrides import *\nexcept ImportError:\n pass\n\nAnd in your settings_overrides.py file:\nLOCALIZED = True\n\n... If nothing but to make it clear what that file does.. What you're doing there splits overrides into two places.\n", "As a general practice, see the other answers on the page; it all depends. Specifically for Django, however, I see nothing fundamentally wrong with writing code in the settings.py file... after all, the settings file IS code :-) \nThe Django docs on settings themselves say:\n\nA settings file is just a Python module with module-level variables.\n\nAnd give the example:\nassign settings dynamically using normal Python syntax. For example:\nMY_SETTING = [str(i) for i in range(30)]\n\n", "Settings as code is also a security risk. You import your \"config\", but in reality you are executing whatever code is in that file. Put config in files that you parse first and you can reject nonsensical or malicious values, even if it is more work for you. I blogged about this in December 2008.\n" ]
[ 11, 4, 4, 1, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0000690221_django_python.txt
Q: Best practice for two way hashing in python? I want to allow users to validate their email address by clicking on a link. The link would look something like http://www.example.com/verifyemail?id=some-random-string When I am sending this email, I want to be able to easily generate this 'some-random-string' from row id of user, an integer. and when user clicks on this link, generate that integer back. Only requirement is this 'some-random-string' should be as opaque and non-guessable to the user as possible. Finally, this is what I settled on def p3_encrypt_safe(plain, key): return base64.urlsafe_b64encode(p3_encrypt(plain, key)) used the nice crypto library from http://www.nightsong.com/phr/crypto/p3.py addition of base64 safe encoding is mine. A: Use encryption, that's exactly what it's designed for. Blowfish, AES, even DES3 if you don't need particularly high security. Alternatively, you could compute an SHA-256 or SHA-512 (or whatever) hash of the email address and store it in a database along with the email address itself. That way you can just look up the email address using the hash as a key. A: Your best choice is to generate a hash (one-way function) of some of the user's data. For example, to generate a hash of user's row id, you could use something like: >>> import hashlib >>> hashlib.sha1('3').hexdigest() '77de68daecd823babbb58edb1c8e14d7106e83bb' However, basing your pseudorandom string only on a row id is not very secure, as the user could easily reverse the hash (try googling 77de68daecd823babbb58edb1c8e14d7106e83bb) of such a short string. A simple solution here is to "salt" the hashed string, i.e. add the same secret string to every value that is hashed. For example: >>> hashlib.sha1('3' + 'email@of.user' + 'somestringconstant').hexdigest() 'b3ca694a9987f39783a324f00cfe8279601decd3' If you google b3ca694a9987f39783a324f00cfe8279601decd3, probably the only result will be a link to this answer :-), which is not a proof, but a good hint that this hash is quite unique.
Best practice for two way hashing in python?
I want to allow users to validate their email address by clicking on a link. The link would look something like http://www.example.com/verifyemail?id=some-random-string When I am sending this email, I want to be able to easily generate this 'some-random-string' from row id of user, an integer. and when user clicks on this link, generate that integer back. Only requirement is this 'some-random-string' should be as opaque and non-guessable to the user as possible. Finally, this is what I settled on def p3_encrypt_safe(plain, key): return base64.urlsafe_b64encode(p3_encrypt(plain, key)) used the nice crypto library from http://www.nightsong.com/phr/crypto/p3.py addition of base64 safe encoding is mine.
[ "Use encryption, that's exactly what it's designed for. Blowfish, AES, even DES3 if you don't need particularly high security.\nAlternatively, you could compute an SHA-256 or SHA-512 (or whatever) hash of the email address and store it in a database along with the email address itself. That way you can just look up the email address using the hash as a key.\n", "Your best choice is to generate a hash (one-way function) of some of the user's data. For example, to generate a hash of user's row id, you could use something like:\n>>> import hashlib\n>>> hashlib.sha1('3').hexdigest()\n'77de68daecd823babbb58edb1c8e14d7106e83bb'\n\nHowever, basing your pseudorandom string only on a row id is not very secure, as the user could easily reverse the hash (try googling 77de68daecd823babbb58edb1c8e14d7106e83bb) of such a short string.\nA simple solution here is to \"salt\" the hashed string, i.e. add the same secret string to every value that is hashed. For example:\n>>> hashlib.sha1('3' + 'email@of.user' + 'somestringconstant').hexdigest()\n'b3ca694a9987f39783a324f00cfe8279601decd3'\n\nIf you google b3ca694a9987f39783a324f00cfe8279601decd3, probably the only result will be a link to this answer :-), which is not a proof, but a good hint that this hash is quite unique.\n" ]
[ 5, 5 ]
[]
[]
[ "python" ]
stackoverflow_0000693826_python.txt
Q: Python module for VBox? I want to make some python scripts to create an "Appliance" with VirtualBox. However, I can't find any documentation anywhere on making calls to VBoxService.exe. Well, I've found stuff that works from OUTSIDE the Machine, but nothing from working from inside the machine. Does anyone know anything about this? If there's a library for another language like C I'd be okay with it, though Python would be heavily preferred. A: Consider using libvirt. The VirtualBox support is bleeding-edge (not in any release, may not even be in source control yet, but is available as a set of patches on the mailing list) -- but this single API, available for C, Python and several other languages, lets you control virtual machines and images running in Qemu/KVM, Xen, LXC (Linux Containers), UML (User-Mode Linux), OpenVZ and others. I build and administer virtual appliances (in an automated QA context) using libvirt with the qemu/KVM backend, and it meets my needs very well. libvirt can be configured to allow remote access (such as controlling or querying VBoxService or libvirtd from within one of the VMs, which you appear to want to do -- though I question the wisdom and utility), with numerous authentication and transport options available. [Caveat: libvirt principally targets Unixlike operating systems; it can be built for win32, but YMMV]
Python module for VBox?
I want to make some python scripts to create an "Appliance" with VirtualBox. However, I can't find any documentation anywhere on making calls to VBoxService.exe. Well, I've found stuff that works from OUTSIDE the Machine, but nothing from working from inside the machine. Does anyone know anything about this? If there's a library for another language like C I'd be okay with it, though Python would be heavily preferred.
[ "Consider using libvirt. The VirtualBox support is bleeding-edge (not in any release, may not even be in source control yet, but is available as a set of patches on the mailing list) -- but this single API, available for C, Python and several other languages, lets you control virtual machines and images running in Qemu/KVM, Xen, LXC (Linux Containers), UML (User-Mode Linux), OpenVZ and others.\nI build and administer virtual appliances (in an automated QA context) using libvirt with the qemu/KVM backend, and it meets my needs very well.\nlibvirt can be configured to allow remote access (such as controlling or querying VBoxService or libvirtd from within one of the VMs, which you appear to want to do -- though I question the wisdom and utility), with numerous authentication and transport options available.\n[Caveat: libvirt principally targets Unixlike operating systems; it can be built for win32, but YMMV]\n" ]
[ 2 ]
[]
[]
[ "python", "virtualbox" ]
stackoverflow_0000693752_python_virtualbox.txt
Q: How do I read an Excel file into Python using xlrd? Can it read newer Office formats? My issue is below but would be interested comments from anyone with experience with xlrd. I just found xlrd and it looks like the perfect solution but I'm having a little problem getting started. I am attempting to extract data programatically from an Excel file I pulled from Dow Jones with current components of the Dow Jones Industrial Average (link: http://www.djindexes.com/mdsidx/?event=showAverages) When I open the file unmodified I get a nasty BIFF error (binary format not recognized) However you can see in this screenshot that Excel 2008 for Mac thinks it is in 'Excel 1997-2004' format (screenshot: http://skitch.com/alok/ssa3/componentreport-dji.xls-properties) If I instead open it in Excel manually and save as 'Excel 1997-2004' format explicitly, then open in python usig xlrd, everything is wonderful. Remember, Office thinks the file is already in 'Excel 1997-2004' format. All files are .xls Here is a pastebin of an ipython session replicating the issue: http://pastie.textmate.org/private/jbawdtrvlrruh88mzueqdq Any thoughts on: How to trick xlrd into recognizing the file so I can extract data? How to use python to automate the explicit 'save as' format to one that xlrd will accept? Plan B? A: FWIW, I'm the author of xlrd, and the maintainer of xlwt (a fork of pyExcelerator). A few points: The file ComponentReport-DJI.xls is misnamed; it is not an XLS file, it is a tab-separated-values file. Open it with a text editor (e.g. Notepad) and you'll see what I mean. You can also look at the not-very-raw raw bytes with Python: >>> open('ComponentReport-DJI.xls', 'rb').read(200) 'COMPANY NAME\tPRIMARY EXCHANGE\tTICKER\tSTYLE\tICB SUBSECTOR\tMARKET CAP RANGE\ tWEIGHT PCT\tUSD CLOSE\t\r\n3M Co.\tNew York SE\tMMM\tN/A\tDiversified Industria ls\tBroad\t5.15676229508\t50.33\t\r\nAlcoa Inc.\tNew York SE\tA' You can read this file using Python's csv module ... just use delimiter="\t" in your call to csv.reader(). xlrd can read any file that pyExcelerator can, and read them better—dates don't come out as floats, and the full story on Excel dates is in the xlrd documentation. pyExcelerator is abandonware—xlrd and xlwt are alive and well. Check out http://groups.google.com/group/python-excel HTH John A: xlrd support for Office 2007/2008 (OpenXML) format is in alpha test - see the following post in the python-excel newsgroup: http://groups.google.com/group/python-excel/msg/0c5f15ad122bf24b?hl=en A: More info on pyExcelerator: To read a file, do this: import pyExcelerator book = pyExcelerator.parse_xls(filename) where filename is a string that is the filename to read (not a file-like object). This will give you a data structure representing the workbook: a list of pairs, where the first element of the pair is the worksheet name and the second element is the worksheet data. The worksheet data is a dictionary, where the keys are (row, col) pairs (starting with 0) and the values are the cell contents -- generally int, float, or string. So, for instance, in the simple case of all the data being on the first worksheet: data = book[0][1] print 'Cell A1 of worksheet %s is: %s' % (book[0][0], repr(data[(0, 0)])) If the cell is empty, you'll get a KeyError. If you're dealing with dates, they may (I forget) come through as integers or floats; if this is the case, you'll need to convert. Basically the rule is: datetime.datetime(1899, 12, 31) + datetime.timedelta(days=n) but that might be off by 1 or 2 (because Excel treats 1900 as a leap-year for compatibility with Lotus, and because I can't remember if 1900-1-1 is 0 or 1), so do some trial-and-error to check. Datetimes are stored as floats, I think (days and fractions of a day). I think there is partial support for forumulas, but I wouldn't guarantee anything. A: Well here is some code that I did: (look down the bottom): here Not sure about the newer formats - if xlrd can't read it, xlrd needs to have a new version released !
How do I read an Excel file into Python using xlrd? Can it read newer Office formats?
My issue is below but would be interested comments from anyone with experience with xlrd. I just found xlrd and it looks like the perfect solution but I'm having a little problem getting started. I am attempting to extract data programatically from an Excel file I pulled from Dow Jones with current components of the Dow Jones Industrial Average (link: http://www.djindexes.com/mdsidx/?event=showAverages) When I open the file unmodified I get a nasty BIFF error (binary format not recognized) However you can see in this screenshot that Excel 2008 for Mac thinks it is in 'Excel 1997-2004' format (screenshot: http://skitch.com/alok/ssa3/componentreport-dji.xls-properties) If I instead open it in Excel manually and save as 'Excel 1997-2004' format explicitly, then open in python usig xlrd, everything is wonderful. Remember, Office thinks the file is already in 'Excel 1997-2004' format. All files are .xls Here is a pastebin of an ipython session replicating the issue: http://pastie.textmate.org/private/jbawdtrvlrruh88mzueqdq Any thoughts on: How to trick xlrd into recognizing the file so I can extract data? How to use python to automate the explicit 'save as' format to one that xlrd will accept? Plan B?
[ "FWIW, I'm the author of xlrd, and the maintainer of xlwt (a fork of pyExcelerator). A few points:\n\nThe file ComponentReport-DJI.xls is misnamed; it is not an XLS file, it is a tab-separated-values file. Open it with a text editor (e.g. Notepad) and you'll see what I mean. You can also look at the not-very-raw raw bytes with Python:\n>>> open('ComponentReport-DJI.xls', 'rb').read(200)\n'COMPANY NAME\\tPRIMARY EXCHANGE\\tTICKER\\tSTYLE\\tICB SUBSECTOR\\tMARKET CAP RANGE\\\ntWEIGHT PCT\\tUSD CLOSE\\t\\r\\n3M Co.\\tNew York SE\\tMMM\\tN/A\\tDiversified Industria\nls\\tBroad\\t5.15676229508\\t50.33\\t\\r\\nAlcoa Inc.\\tNew York SE\\tA'\n\nYou can read this file using Python's csv module ... just use delimiter=\"\\t\" in your call to csv.reader().\nxlrd can read any file that pyExcelerator can, and read them better—dates don't come out as floats, and the full story on Excel dates is in the xlrd documentation.\npyExcelerator is abandonware—xlrd and xlwt are alive and well. Check out http://groups.google.com/group/python-excel\n\nHTH\nJohn\n", "xlrd support for Office 2007/2008 (OpenXML) format is in alpha test - see the following post in the python-excel newsgroup:\nhttp://groups.google.com/group/python-excel/msg/0c5f15ad122bf24b?hl=en \n", "More info on pyExcelerator: To read a file, do this:\nimport pyExcelerator\nbook = pyExcelerator.parse_xls(filename)\n\nwhere filename is a string that is the filename to read (not a file-like object). This will give you a data structure representing the workbook: a list of pairs, where the first element of the pair is the worksheet name and the second element is the worksheet data.\nThe worksheet data is a dictionary, where the keys are (row, col) pairs (starting with 0) and the values are the cell contents -- generally int, float, or string. So, for instance, in the simple case of all the data being on the first worksheet:\ndata = book[0][1]\nprint 'Cell A1 of worksheet %s is: %s' % (book[0][0], repr(data[(0, 0)]))\n\nIf the cell is empty, you'll get a KeyError. If you're dealing with dates, they may (I forget) come through as integers or floats; if this is the case, you'll need to convert. Basically the rule is: datetime.datetime(1899, 12, 31) + datetime.timedelta(days=n) but that might be off by 1 or 2 (because Excel treats 1900 as a leap-year for compatibility with Lotus, and because I can't remember if 1900-1-1 is 0 or 1), so do some trial-and-error to check. Datetimes are stored as floats, I think (days and fractions of a day).\nI think there is partial support for forumulas, but I wouldn't guarantee anything.\n", "Well here is some code that I did: (look down the bottom): here\nNot sure about the newer formats - if xlrd can't read it, xlrd needs to have a new version released !\n" ]
[ 26, 3, 1, 0 ]
[ "Do you have to use xlrd? I just downloaded 'UPDATED - Dow Jones Industrial Average Movers - 2008' from that website and had no trouble reading it with pyExcelerator.\nimport pyExcelerator\nbook = pyExcelerator.parse_xls('DJIAMovers.xls')\n\n" ]
[ -1 ]
[ "import_from_excel", "python", "xlrd" ]
stackoverflow_0000118516_import_from_excel_python_xlrd.txt
Q: Do you have a copy of Unipath-0.2.0.tar.gz? I need a copy of this library installed on my system because my software depends on this library. Unfortunately, at the moment, it's impossible install it trough easy_install: andrea@puzzle:~$ sudo easy_install Unipath [sudo] password for andrea: Searching for Unipath Reading http://pypi.python.org/simple/Unipath/ Reading http://sluggo.scrapping.cc/python/unipath/ Download error: (-2, 'Name or service not known') -- Some packages may not be found! Reading http://sluggo.scrapping.cc/python/unipath/ Download error: (-2, 'Name or service not known') -- Some packages may not be found! Best match: Unipath 0.2.0 Downloading http://sluggo.scrapping.cc/python/unipath/Unipath-0.2.0.tar.gz error: Download error for http://sluggo.scrapping.cc/python/unipath/Unipath-0.2.0.tar.gz: (-2, 'Name or service not known') I think that something weird happened on the DNS entry of sluggo.scrapping.cc. How can I get this library? I searched for a mirror on google but I didn't find it. Do you know if there is a another place from where I can download this library? Or ... do you have a copy of this library and you can send it to me? A: I found this newsgroup post written my Mike Orr (the creator of Unipath). In the last sentence he says that he's moving the project from the old server to Bitbucket. So may be that the problem will be fixed when the moving is finished. Mike Orr message is dated March 10 2009, at the time of writing March 29 2009 I can see yet the source code on http://bitbucket.org/sluggo/unipath Workaround I found an .egg file in the backup archive of old system of mine. I uploaded the file on the internet. But I think it solve the problem only for those people who have python 2.5. To install it use: easy_install http://trash-cli.googlecode.com/files/Unipath-0.2.1-py2.5.egg I hope the problem on the sluggo.scrapping.cc server would be soon fixed. A: I contacted the original author who confirmed me that there was a problem with the DNS entry and he's going to solve it. He also uploaded the latest tarball to pypi, so now you can install it with easy_install Unipath.
Do you have a copy of Unipath-0.2.0.tar.gz?
I need a copy of this library installed on my system because my software depends on this library. Unfortunately, at the moment, it's impossible install it trough easy_install: andrea@puzzle:~$ sudo easy_install Unipath [sudo] password for andrea: Searching for Unipath Reading http://pypi.python.org/simple/Unipath/ Reading http://sluggo.scrapping.cc/python/unipath/ Download error: (-2, 'Name or service not known') -- Some packages may not be found! Reading http://sluggo.scrapping.cc/python/unipath/ Download error: (-2, 'Name or service not known') -- Some packages may not be found! Best match: Unipath 0.2.0 Downloading http://sluggo.scrapping.cc/python/unipath/Unipath-0.2.0.tar.gz error: Download error for http://sluggo.scrapping.cc/python/unipath/Unipath-0.2.0.tar.gz: (-2, 'Name or service not known') I think that something weird happened on the DNS entry of sluggo.scrapping.cc. How can I get this library? I searched for a mirror on google but I didn't find it. Do you know if there is a another place from where I can download this library? Or ... do you have a copy of this library and you can send it to me?
[ "I found this newsgroup post written my Mike Orr (the creator of Unipath). In the last sentence he says that he's moving the project from the old server to Bitbucket. So may be that the problem will be fixed when the moving is finished.\nMike Orr message is dated March 10 2009, at the time of writing March 29 2009 I can see yet the source code on http://bitbucket.org/sluggo/unipath\nWorkaround\nI found an .egg file in the backup archive of old system of mine. I uploaded the file on the internet.\nBut I think it solve the problem only for those people who have python 2.5. To install it use:\neasy_install http://trash-cli.googlecode.com/files/Unipath-0.2.1-py2.5.egg\n\nI hope the problem on the sluggo.scrapping.cc server would be soon fixed.\n", "I contacted the original author who confirmed me that there was a problem with the DNS entry and he's going to solve it.\nHe also uploaded the latest tarball to pypi, so now you can install it with easy_install Unipath.\n" ]
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0000671542_python.txt
Q: Shortening a oft-used code segment for testing a return value in Python Consider this Python segment: def someTestFunction(): if someTest: return value1 elif someOtherTest: return value2 elif yetSomeOtherTest: return value3 return None def SomeCallingFunction(): a = someTestFunction() if a != None: return a ... normal execution continues Now, the question: the three-line segment in the beginning of SomeCallingFunction to get the value of the test function and bail out if it's not None, is repeated very often in many other functions. Three lines is too long. I want to shorten it to one. How do I do that? I can freely restructure this code and the contents of someTestFunction however needed. I thought of using exceptions, but those don't seem to help in cutting down the calling code length. (I've read a bit about Python decorators, but haven't used them. Would this be the place? How would it work?) A: If you want to use a decorator, it would look like this: def testDecorator(f): def _testDecorator(): a = someTestFunction() if a is None: return f() else: return a return _testDecorator @testDecorator def SomeCallingFunction(): ... normal execution When the module is first imported, it runs testDecorator, passing it your original SomeCallingFunction as a parameter. A new function is returned, and that gets bound to the SomeCallingFunction name. Now, whenever you call SomeCallingFunction, it runs that other function, which does the check, and returns either a, or the result of the original SomeCallingFunction. A: I often use a hash table in place of a series of elifs: def someTestFunction(decorated_test): options = { 'val1': return_val_1, 'val2': return_val_2 } return options[decorated_test] You can set up options as a defaultdict(None) to default to None if a key isn't found. If you can't get your tests in that form, then a series of if statements might actually be the best thing to do. One small thing you can do to shorten your code is to use this: if a: return a There may be other ways to shorten your code, but these are the ones I can come up with on the spot. A: I think this would do it: UPDATE Fixed! Sorry for yesterday, I rushed and didn't test the code! def test_decorator( test_func ): def tester( normal_function ): def tester_inner(): a = test_func() if a is not None: return a return normal_function() return tester_inner return tester #usage: @test_decorator( my_test_function ) def my_normal_function(): #.... normal execution continue ... It's similar to DNS's answer but allows you to specify which test function you want to use
Shortening a oft-used code segment for testing a return value in Python
Consider this Python segment: def someTestFunction(): if someTest: return value1 elif someOtherTest: return value2 elif yetSomeOtherTest: return value3 return None def SomeCallingFunction(): a = someTestFunction() if a != None: return a ... normal execution continues Now, the question: the three-line segment in the beginning of SomeCallingFunction to get the value of the test function and bail out if it's not None, is repeated very often in many other functions. Three lines is too long. I want to shorten it to one. How do I do that? I can freely restructure this code and the contents of someTestFunction however needed. I thought of using exceptions, but those don't seem to help in cutting down the calling code length. (I've read a bit about Python decorators, but haven't used them. Would this be the place? How would it work?)
[ "If you want to use a decorator, it would look like this:\ndef testDecorator(f):\n def _testDecorator():\n a = someTestFunction()\n if a is None:\n return f()\n else: return a\n return _testDecorator\n\n@testDecorator\ndef SomeCallingFunction():\n ... normal execution\n\nWhen the module is first imported, it runs testDecorator, passing it your original SomeCallingFunction as a parameter. A new function is returned, and that gets bound to the SomeCallingFunction name. Now, whenever you call SomeCallingFunction, it runs that other function, which does the check, and returns either a, or the result of the original SomeCallingFunction.\n", "I often use a hash table in place of a series of elifs:\ndef someTestFunction(decorated_test):\n options = {\n 'val1': return_val_1,\n 'val2': return_val_2\n }\n return options[decorated_test]\n\nYou can set up options as a defaultdict(None) to default to None if a key isn't found.\nIf you can't get your tests in that form, then a series of if statements might actually be the best thing to do.\nOne small thing you can do to shorten your code is to use this:\nif a: return a\n\nThere may be other ways to shorten your code, but these are the ones I can come up with on the spot.\n", "I think this would do it:\nUPDATE Fixed!\nSorry for yesterday, I rushed and didn't test the code!\ndef test_decorator( test_func ):\n def tester( normal_function ):\n def tester_inner():\n a = test_func()\n if a is not None: \n return a\n return normal_function()\n return tester_inner \n return tester \n\n\n#usage:\n@test_decorator( my_test_function )\ndef my_normal_function():\n #.... normal execution continue ...\n\nIt's similar to DNS's answer but allows you to specify which test function you want to use \n" ]
[ 9, 4, 2 ]
[]
[]
[ "optimization", "python" ]
stackoverflow_0000694775_optimization_python.txt
Q: What is the best way to internationalize a Python app with multiple i18n domains? I'm internationalizing a Python application, with two goals in mind: The application loads classes from multiple packages, each with its own i18n domain. So modules in package A are using domain A, modules in package B are using domain B, etc. The locale can be changed while the application is running. Python's gettext module makes internationalizing a single-domain single-language application very easy; you just set the locale, then call gettext.install(), which finds the right Translation and installs its ugettext method in the global namespace as _. But obviously a global value only works for a single domain, and since it loads a single Translation, it only works for that locale. I could instead load the Translation at the top of each module, and bind its ugettext method as _. Then each module would be using the _ for its own domain. But this still breaks when the locale is changed, because _ is for the wrong locale. So I guess I could load the correct ugettext at the top of every function, but that seems awfully cumbersome. An alternative would be to still do it per-module, but instead of binding ugettext, I would substitute my own function, which would check the current locale, get its Translation, and forward the string to it. Does anyone have a cleaner solution? A: how about you bind _ to a function roughly like this (for each module): def _(message): return my_gettext(__name__, message) This allows you to use gettext while at the same time perform any lookup on a per-module-per-call-base that allows you to switch locale as well.
What is the best way to internationalize a Python app with multiple i18n domains?
I'm internationalizing a Python application, with two goals in mind: The application loads classes from multiple packages, each with its own i18n domain. So modules in package A are using domain A, modules in package B are using domain B, etc. The locale can be changed while the application is running. Python's gettext module makes internationalizing a single-domain single-language application very easy; you just set the locale, then call gettext.install(), which finds the right Translation and installs its ugettext method in the global namespace as _. But obviously a global value only works for a single domain, and since it loads a single Translation, it only works for that locale. I could instead load the Translation at the top of each module, and bind its ugettext method as _. Then each module would be using the _ for its own domain. But this still breaks when the locale is changed, because _ is for the wrong locale. So I guess I could load the correct ugettext at the top of every function, but that seems awfully cumbersome. An alternative would be to still do it per-module, but instead of binding ugettext, I would substitute my own function, which would check the current locale, get its Translation, and forward the string to it. Does anyone have a cleaner solution?
[ "how about you bind _ to a function roughly like this (for each module):\ndef _(message):\n return my_gettext(__name__, message)\n\nThis allows you to use gettext while at the same time perform any lookup on a per-module-per-call-base that allows you to switch locale as well.\n" ]
[ 2 ]
[]
[]
[ "internationalization", "localization", "python" ]
stackoverflow_0000694768_internationalization_localization_python.txt
Q: Detect in python which keys are pressed I need to know which key is being pressed right now. I'm not looking to capture some specific keys to trigger an event or anything like that, I want to know which keys are pressed now and display a list of them. I also need to capture special keys like F1 ... F12, shift, alt, home, windows, etc. Basically all keys on the keyboard. How do I do this in python? How do I capture keyboard events? Related Cross platform keylogger Is there a cross-platform python low-level API to capture or generate keyboard events? EDIT Just so you know I'm not trying to make a keylogger. I'm trying to make a diagnoses tool (I split water on my laptop and the keyboard is starting to get crazy sometime!!) A: PyKeylogger mentioned in the related question might do the job. A: The easiest way to do something like this, if you're not too fussy, is to bring in a GUI toolkit such as pygame or wxPython. For example, run the wxPython Demo, then go to the demo for KeyEvents. A: I found the answer using a link in a related question to pyHook: pyHook tutorial: capturing keypress events
Detect in python which keys are pressed
I need to know which key is being pressed right now. I'm not looking to capture some specific keys to trigger an event or anything like that, I want to know which keys are pressed now and display a list of them. I also need to capture special keys like F1 ... F12, shift, alt, home, windows, etc. Basically all keys on the keyboard. How do I do this in python? How do I capture keyboard events? Related Cross platform keylogger Is there a cross-platform python low-level API to capture or generate keyboard events? EDIT Just so you know I'm not trying to make a keylogger. I'm trying to make a diagnoses tool (I split water on my laptop and the keyboard is starting to get crazy sometime!!)
[ "PyKeylogger mentioned in the related question might do the job.\n", "The easiest way to do something like this, if you're not too fussy, is to bring in a GUI toolkit such as pygame or wxPython. For example, run the wxPython Demo, then go to the demo for KeyEvents.\n", "I found the answer using a link in a related question to pyHook:\npyHook tutorial: capturing keypress events\n" ]
[ 6, 4, 2 ]
[]
[]
[ "events", "keyboard", "python" ]
stackoverflow_0000694296_events_keyboard_python.txt
Q: What is LLVM and How is replacing Python VM with LLVM increasing speeds 5x? Google is sponsoring an Open Source project to increase the speed of Python by 5x. Unladen-Swallow seems to have a good project plan Why is concurrency such a hard problem? Is LLVM going to solve the concurrency problem? Are there solutions other than Multi-core for Hardware advancement? A: LLVM is several things together - kind of a virtual machine/optimizing compiler, combined with different frontends that take the input in a particular language and output the result in an intermediate language. This intermediate output can be run with the virtual machine, or can be used to generate a standalone executable. The problem with concurrency is that, although it was used for a long time in scientific computing, it has just recently has become common in consumer apps. So while it's widely known how to program a scientific calculation program to achieve great performance, it is completely different thing to write a mail user agent/word processor that can be good at concurrency. Also, most of the current OS's were being designed with a single processor in mind, and they may not be fully prepared for multicore processors. The benefit of LLVM with respect to concurrency is that you have an intermediate output, and if in the future there are advances in concurrency, then by updating your interpreter you instantly gain those benefits in all LLVM-compiled programs. This is not so easy if you had compiled to a standalone executable. So LLVM doesn't solve the concurrency problem per se but it leaves an open door for future enhancements. Sure there are more possible advances for the hardware like quantum computers, genetics computers, etc. But we have to wait for them to become a reality. A: The switch to LLVM itself isn't solving the concurrency problem. That's being solved separately, by getting rid of the Global Interpreter Lock. I'm not sure how I feel about that; I use threads mainly to deal with blocking I/O, not to take advantage of multicore processors (for that, I would use the multiprocessing module to spawn separate processes). So I kind of like the GIL; it makes my life a lot easier not having to think about tricky synchronization issues. A: LLVM takes care of the nitty-gritty of code generation, so it lets them rewrite Psyco in a way that's more general, portable, maintainable. That in turn allows them to rewrite the CPython core, which lets them experiment with alternate GCs and other things needed to improve python's support for concurrency. In other words, LLVM doesn't solve the concurrency problem, it just frees up your hands so YOU can solve it.
What is LLVM and How is replacing Python VM with LLVM increasing speeds 5x?
Google is sponsoring an Open Source project to increase the speed of Python by 5x. Unladen-Swallow seems to have a good project plan Why is concurrency such a hard problem? Is LLVM going to solve the concurrency problem? Are there solutions other than Multi-core for Hardware advancement?
[ "LLVM is several things together - kind of a virtual machine/optimizing compiler, combined with different frontends that take the input in a particular language and output the result in an intermediate language. This intermediate output can be run with the virtual machine, or can be used to generate a standalone executable. \nThe problem with concurrency is that, although it was used for a long time in scientific computing, it has just recently has become common in consumer apps. So while it's widely known how to program a scientific calculation program to achieve great performance, it is completely different thing to write a mail user agent/word processor that can be good at concurrency. Also, most of the current OS's were being designed with a single processor in mind, and they may not be fully prepared for multicore processors.\nThe benefit of LLVM with respect to concurrency is that you have an intermediate output, and if in the future there are advances in concurrency, then by updating your interpreter you instantly gain those benefits in all LLVM-compiled programs. This is not so easy if you had compiled to a standalone executable. So LLVM doesn't solve the concurrency problem per se but it leaves an open door for future enhancements.\nSure there are more possible advances for the hardware like quantum computers, genetics computers, etc. But we have to wait for them to become a reality.\n", "The switch to LLVM itself isn't solving the concurrency problem. That's being solved separately, by getting rid of the Global Interpreter Lock.\nI'm not sure how I feel about that; I use threads mainly to deal with blocking I/O, not to take advantage of multicore processors (for that, I would use the multiprocessing module to spawn separate processes).\nSo I kind of like the GIL; it makes my life a lot easier not having to think about tricky synchronization issues.\n", "LLVM takes care of the nitty-gritty of code generation, so it lets them rewrite Psyco in a way that's more general, portable, maintainable. That in turn allows them to rewrite the CPython core, which lets them experiment with alternate GCs and other things needed to improve python's support for concurrency.\nIn other words, LLVM doesn't solve the concurrency problem, it just frees up your hands so YOU can solve it.\n" ]
[ 31, 17, 15 ]
[]
[]
[ "llvm", "multicore", "python", "unladen_swallow" ]
stackoverflow_0000695370_llvm_multicore_python_unladen_swallow.txt
Q: Understanding Python Class instances I'm working on a problem which uses a python class and has a constructor function to give the number of sides to one die and a function to roll the die with a random number returned based on the number of sides. I realize the code is very basic, but I'm having troubles understanding how to sum up the total of three rolled dice with different sides. Since a variable is passing the function instance what would be the best way to grab that value to add it up? Here is what I have. *To clarify... I can get the totals of the roll1.roll_dice() to add up, but I have to show each roll individually and then the total of the three dice. I can do either one of those but not both. class Die(): def __init__(self, s = 6): self.sides = s def roll_die(self): x = random.randint(1,self.sides) return x roll1 = Die() #Rolling die 1 with the default side of 6 roll2 = Die(4) #Rolling die 2 with 4 sides roll3 = Die(12) #Rolling die 3 with 12 sides print roll1.roll_die() print roll2.roll_die() print roll3.roll_die() A: You can store the results in a list: rolls = [Die(n).roll_die() for n in (6, 4, 12)] then you can show the individual results >>> print rolls [5, 2, 6] or sum them >>> print sum(rolls) 13 Or, instead, you could keep a running total: total = 0 for n in (6, 4, 12): value = Die(n).roll_die() print "Rolled a", value total += value print "Total is", total (edited to reflect the changes/clarifications to the question) A: I'm not sure exactly where you're confused. The simplest thing you need to do is separate the concept of a specific die you're going to roll (the object) with the action (rolling it). I would start here: d6 = Die() #create die 1 with the default side of 6 d4 = Die(4) #create die 2 with 4 sides d12 = Die(12) #create die 3 with 12 sides roll1 = d6.roll_die() roll2 = d4.roll_die() roll3 = d12.roll_die() print "%d\n%d\n%d\nsum = %d" % (roll1, roll2, roll3, roll1 + roll2 + roll3) ... and then get fancier with lists, etc. A: It may also be useful to just store the last roll so you can get it whenever you want. def __init__(self, s = 6): self.sides = s self.last_roll = None def roll_die(self): self.last_roll = random.randint(1,self.sides) return self.last_roll A: Since roll_die returns a value, you can add those values. Try this. roll1.roll_die() + roll2.roll_die() What happens? A: You can just sum the numbers. In case you want to sum the outcome of n rolls, consider adding this function to the class: def sum_of_n_rolls(self, n) return sum(self.roll_die() for _ in range(n)) Also, consider renaming roll_die to just roll. It's obvious that it's not about rolling a rock, since the method is part of the class Die. Edit: I now read you need to print intermediate rolls. Consider: def n_rolls(self, n): return [self.roll_die() for _ in range(n)] Now you can roll a 7-sided die 10 times: rolls = Die(7).n_rolls(10) print(rolls, sum(rolls)) A: Guess I'd do something like this: # Create dice sides = [6,4,12] dice = [Die(s) for s in sides] # Roll dice rolls = [die.roll_die() for die in dice] # Print rolls for roll in rolls: print roll You can also combine a few of these steps if you like: for num_sides in [6,4,12]: print Die(num_sides).roll_die() A: If I understood you correctly you want a class attribute. UPDATE: Added a way for automatically reseting the total import random class Die(): _total = 0 @classmethod def total(cls): t = cls._total cls._total = 0 return t def __init__(self, s=6): self.sides = s def roll_die(self): x = random.randint(1,self.sides) self.__class__._total += x return x roll1 = Die() #Rolling die 1 with the default side of 6 roll2 = Die(4) #Rolling die 2 with 4 sides roll3 = Die(12) #Rolling die 3 with 12 sides print roll1.roll_die() print roll2.roll_die() print roll3.roll_die() print Die.total() print "--" print roll1.roll_die() print roll2.roll_die() print roll3.roll_die() print Die.total() A: Let's get crazy :) (combined with my last answer as well) class Die(): def __init__(self, s = 6): self.sides = s self.last_roll = None def roll_die(self): self.last_roll = random.randint(1,self.sides) return self.last_roll dice = map(Die, (6, 4, 12)) rolls = map(Die.roll_die, dice) print rolls print sum(rolls)
Understanding Python Class instances
I'm working on a problem which uses a python class and has a constructor function to give the number of sides to one die and a function to roll the die with a random number returned based on the number of sides. I realize the code is very basic, but I'm having troubles understanding how to sum up the total of three rolled dice with different sides. Since a variable is passing the function instance what would be the best way to grab that value to add it up? Here is what I have. *To clarify... I can get the totals of the roll1.roll_dice() to add up, but I have to show each roll individually and then the total of the three dice. I can do either one of those but not both. class Die(): def __init__(self, s = 6): self.sides = s def roll_die(self): x = random.randint(1,self.sides) return x roll1 = Die() #Rolling die 1 with the default side of 6 roll2 = Die(4) #Rolling die 2 with 4 sides roll3 = Die(12) #Rolling die 3 with 12 sides print roll1.roll_die() print roll2.roll_die() print roll3.roll_die()
[ "You can store the results in a list:\nrolls = [Die(n).roll_die() for n in (6, 4, 12)]\n\nthen you can show the individual results\n>>> print rolls\n[5, 2, 6]\n\nor sum them\n>>> print sum(rolls)\n13\n\nOr, instead, you could keep a running total:\ntotal = 0\nfor n in (6, 4, 12):\n value = Die(n).roll_die()\n print \"Rolled a\", value\n total += value\nprint \"Total is\", total\n\n(edited to reflect the changes/clarifications to the question)\n", "I'm not sure exactly where you're confused. The simplest thing you need to do is separate the concept of a specific die you're going to roll (the object) with the action (rolling it). I would start here:\nd6 = Die() #create die 1 with the default side of 6\nd4 = Die(4) #create die 2 with 4 sides\nd12 = Die(12) #create die 3 with 12 sides\n\nroll1 = d6.roll_die()\nroll2 = d4.roll_die()\nroll3 = d12.roll_die()\n\nprint \"%d\\n%d\\n%d\\nsum = %d\" % (roll1, roll2, roll3, roll1 + roll2 + roll3)\n\n... and then get fancier with lists, etc.\n", "It may also be useful to just store the last roll so you can get it whenever you want.\ndef __init__(self, s = 6):\n self.sides = s\n self.last_roll = None\n\ndef roll_die(self):\n self.last_roll = random.randint(1,self.sides)\n return self.last_roll\n\n", "Since roll_die returns a value, you can add those values.\nTry this.\nroll1.roll_die() + roll2.roll_die()\n\nWhat happens?\n", "You can just sum the numbers. In case you want to sum the outcome of n rolls, consider adding this function to the class:\ndef sum_of_n_rolls(self, n)\n return sum(self.roll_die() for _ in range(n))\n\nAlso, consider renaming roll_die to just roll. It's obvious that it's not about rolling a rock, since the method is part of the class Die.\n\nEdit: I now read you need to print intermediate rolls. Consider:\ndef n_rolls(self, n):\n return [self.roll_die() for _ in range(n)]\n\nNow you can roll a 7-sided die 10 times:\nrolls = Die(7).n_rolls(10)\nprint(rolls, sum(rolls))\n\n", "Guess I'd do something like this:\n# Create dice\nsides = [6,4,12]\ndice = [Die(s) for s in sides]\n\n# Roll dice\nrolls = [die.roll_die() for die in dice]\n\n# Print rolls\nfor roll in rolls:\n print roll\n\nYou can also combine a few of these steps if you like:\nfor num_sides in [6,4,12]:\n print Die(num_sides).roll_die()\n\n", "If I understood you correctly you want a class attribute.\nUPDATE: Added a way for automatically reseting the total\nimport random\n\nclass Die():\n _total = 0\n\n @classmethod\n def total(cls):\n t = cls._total\n cls._total = 0\n return t\n\n def __init__(self, s=6):\n self.sides = s\n\n def roll_die(self):\n x = random.randint(1,self.sides)\n self.__class__._total += x\n return x\n\nroll1 = Die() #Rolling die 1 with the default side of 6\nroll2 = Die(4) #Rolling die 2 with 4 sides\nroll3 = Die(12) #Rolling die 3 with 12 sides\n\nprint roll1.roll_die() \nprint roll2.roll_die()\nprint roll3.roll_die()\nprint Die.total()\nprint \"--\"\nprint roll1.roll_die() \nprint roll2.roll_die()\nprint roll3.roll_die()\nprint Die.total()\n\n", "Let's get crazy :) (combined with my last answer as well)\nclass Die():\n def __init__(self, s = 6):\n self.sides = s\n self.last_roll = None\n\n def roll_die(self):\n self.last_roll = random.randint(1,self.sides)\n return self.last_roll\n\ndice = map(Die, (6, 4, 12))\nrolls = map(Die.roll_die, dice)\n\nprint rolls\nprint sum(rolls)\n\n" ]
[ 10, 3, 3, 1, 0, 0, 0, 0 ]
[]
[]
[ "class", "python", "sum" ]
stackoverflow_0000694002_class_python_sum.txt
Q: Help with Python loop weirdness? I'm learning Python as my second programming language (my first real one if you don't count HTML/CSS/Javascript). I'm trying to build something useful as my first real application - an IRC bot that alerts people via SMS when certain things happen in the channel. Per a request by someone, I'm (trying) to build in scheduling preferences where people can choose not to get alerts from between hours X and Y of the day. Anyways, here's the code I'm having trouble with: db = open("db.csv") for line in db: row = line.split(",") # storing stuff in a CSV, reading out of it recipient = row[0] # who the SMS is going to s = row[1] # gets the first hour of the "no alert" time range f = row[2] # gets last hour of above nrt = [] # empty array that will store hours curtime = time.strftime("%H") # current hour if s == "no": print "They always want alerts, sending email" # start time will = "no" if they always want alerts # send mail code goes here else: for hour in range(int(s), int(f)): #takes start, end hours, loops through to get hours in between, stores them in the above list nrt.append(hour) if curtime in nrt: # best way I could find of doing this, probably a better way, like I said I'm new print "They don't want an alert during the current hour, not sending" # <== what it says else: # they do want an alert during the current hour, send an email # send mail code here The only problem I'm having is somehow the script only ends up looping through one of the lines (or something like that) because I only get one result every time, even if I have more than one entry in the CSV file. A: If this is a regular CSV file you should not try to parse it yourself. Use the standard library csv module. Here is a short example from the docs: import csv reader = csv.reader(open("some.csv", "rb")) for row in reader: print row A: There are at least two bugs in your program: curtime = time.strftime("%H") ... for hour in range(int(s), int(f)): nrt.append(hour) # this is an inefficient synonym for # nrt = range(int(s), int(f)) if curtime in nrt: ... First, curtime is a string, whereas nrt is a list of integers. Python is strongly typed, so the two are not interchangeable, and won't compare equal: '4' == 4 # False '4' in [3, 4, 5] # False This revised code addresses that issue, and is also more efficient than generating a list and searching for the current hour in it: cur_hour = time.localtime().tm_hour if int(s) <= cur_hour < int(f): # You can "chain" comparison operators in Python # so that a op1 b op2 c is equivalent to a op1 b and b op2c ... A second issue that the above does not address is that your program will not behave properly if the hours wrap around midnight (e.g. s = 22 and f = 8). Neither of these problems are necessarily related to "the script only ends up looping through one of the lines", but you haven't given us enough information to figure out why that might be. A more useful way to ask questions is to post a brief but complete code snippet that shows the behavior you are observing, along with sample input and the resulting error messages, if any (along with traceback). A: Have you tried something more simple? Just to see how your file is actually read by Python: db = open("db.csv") for line in db: print line There can be problem with format of your csv-file. That happens, for instance, when you open Unix file in Windows environment. In that case the whole file looks like single string as Windows and Unix have different line separators. So, I don't know certain cause of your problem, but offer to think in that direction. Update: Your have multiple ways through the body of your loop: when s is "no": "They always want alerts, sending email" will be printed. when s is not "no" and curtime in nrt: "They don't want an alert during the current hour, not sending" will be printed. when s is not "no" and curtime in nrt is false (the last else): nothing will be printed and no other action undertaken. Shouldn't you place some print statement in the last else branch? Also, what is exact output of your snippet? Is it "They always want alerts, sending email"? A: I would check the logic in your conditionals. You looping construct should work. A: Be explicit with what's in a row. Using 0, 1, 2...n is actually your bug, and it makes code very hard to read in the future for yourself or others. So let's use the handy tuple to show what we're expecting from a row. This sort of works like code as documentation db = open("db.csv") for line in db.readlines(): recipient, start_hour, end_hour = line.split(",") nrt = [] etc... This shows the reader of your code what you're expecting a line to contain, and it would have shown your bug to you the first time you ran it :) A: You could go thro an existing well written IRC bot in Python Download
Help with Python loop weirdness?
I'm learning Python as my second programming language (my first real one if you don't count HTML/CSS/Javascript). I'm trying to build something useful as my first real application - an IRC bot that alerts people via SMS when certain things happen in the channel. Per a request by someone, I'm (trying) to build in scheduling preferences where people can choose not to get alerts from between hours X and Y of the day. Anyways, here's the code I'm having trouble with: db = open("db.csv") for line in db: row = line.split(",") # storing stuff in a CSV, reading out of it recipient = row[0] # who the SMS is going to s = row[1] # gets the first hour of the "no alert" time range f = row[2] # gets last hour of above nrt = [] # empty array that will store hours curtime = time.strftime("%H") # current hour if s == "no": print "They always want alerts, sending email" # start time will = "no" if they always want alerts # send mail code goes here else: for hour in range(int(s), int(f)): #takes start, end hours, loops through to get hours in between, stores them in the above list nrt.append(hour) if curtime in nrt: # best way I could find of doing this, probably a better way, like I said I'm new print "They don't want an alert during the current hour, not sending" # <== what it says else: # they do want an alert during the current hour, send an email # send mail code here The only problem I'm having is somehow the script only ends up looping through one of the lines (or something like that) because I only get one result every time, even if I have more than one entry in the CSV file.
[ "If this is a regular CSV file you should not try to parse it yourself. Use the standard library csv module.\nHere is a short example from the docs:\nimport csv\nreader = csv.reader(open(\"some.csv\", \"rb\"))\nfor row in reader:\n print row\n\n", "There are at least two bugs in your program:\ncurtime = time.strftime(\"%H\")\n...\nfor hour in range(int(s), int(f)):\n nrt.append(hour)\n# this is an inefficient synonym for\n# nrt = range(int(s), int(f))\n\nif curtime in nrt:\n ...\n\nFirst, curtime is a string, whereas nrt is a list of integers. Python is strongly typed, so the two are not interchangeable, and won't compare equal:\n'4' == 4 # False\n'4' in [3, 4, 5] # False\n\nThis revised code addresses that issue, and is also more efficient than generating a list and searching for the current hour in it:\ncur_hour = time.localtime().tm_hour\nif int(s) <= cur_hour < int(f):\n # You can \"chain\" comparison operators in Python\n # so that a op1 b op2 c is equivalent to a op1 b and b op2c\n ...\n\nA second issue that the above does not address is that your program will not behave properly if the hours wrap around midnight (e.g. s = 22 and f = 8).\nNeither of these problems are necessarily related to \"the script only ends up looping through one of the lines\", but you haven't given us enough information to figure out why that might be. A more useful way to ask questions is to post a brief but complete code snippet that shows the behavior you are observing, along with sample input and the resulting error messages, if any (along with traceback).\n", "Have you tried something more simple? Just to see how your file is actually read by Python:\ndb = open(\"db.csv\") \nfor line in db: \n print line\n\nThere can be problem with format of your csv-file. That happens, for instance, when you open Unix file in Windows environment. In that case the whole file looks like single string as Windows and Unix have different line separators. So, I don't know certain cause of your problem, but offer to think in that direction.\nUpdate:\nYour have multiple ways through the body of your loop: \n\nwhen s is \"no\": \"They always want alerts, sending email\" will be printed.\nwhen s is not \"no\" and curtime in nrt: \"They don't want an alert during the current hour, not sending\" will be printed.\nwhen s is not \"no\" and curtime in nrt is false (the last else): nothing will be printed and no other action undertaken.\n\nShouldn't you place some print statement in the last else branch?\nAlso, what is exact output of your snippet? Is it \"They always want alerts, sending email\"?\n", "I would check the logic in your conditionals. You looping construct should work. \n", "Be explicit with what's in a row. Using 0, 1, 2...n is actually your bug, and it makes code very hard to read in the future for yourself or others. So let's use the handy tuple to show what we're expecting from a row. This sort of works like code as documentation\ndb = open(\"db.csv\")\nfor line in db.readlines():\n recipient, start_hour, end_hour = line.split(\",\")\n nrt = []\n etc...\n\nThis shows the reader of your code what you're expecting a line to contain, and it would have shown your bug to you the first time you ran it :)\n", "You could go thro an existing well written IRC bot in Python Download\n" ]
[ 9, 7, 5, 0, 0, 0 ]
[]
[]
[ "csv", "loops", "python" ]
stackoverflow_0000695040_csv_loops_python.txt
Q: Parsing template schema with Python and Regular Expressions I'm working on a script for work to extract data from an old template engine schema: [%price%] { $54.99 } [%/price%] [%model%] { WRT54G } [%/model%] [%brand%]{ LINKSYS } [%/brand%] everything within the [% %] is the key, and everything in the { } is the value. Using Python and regex, I was able to get this far: (?<=[%)(?P\w*?)(?=\%]) which returns ['price', 'model', 'brand'] I'm just having a problem getting it match the bracket data as a value A: I agree with Devin that a single regex isn't the best solution. If there do happen to be any strange cases that aren't handled by your regex, there's a real risk that you won't find out. I'd suggest using a finite state machine approach. Parse the file line by line, first looking for a price-model-brand block, then parse whatever is within the braces. Also, make sure to note if any blocks aren't opened or closed correctly as these are probably malformed. You should be able to write something like this in python in about 30-40 lines of code. A: It looks like it'd be easier to do with re.Scanner (sadly undocumented) than with a single regular expression. A: just for grins: import re RE_kv = re.compile("\[%(.*)%\].*?\n?\s*{\s*(.*)") matches = re.findall(RE_kv, test, re.M) for k, v in matches: print k, v output: price $54.99 model WRT54G brand LINKSYS Note I did just enough regex to get the matches to show up, it's not even bounded at the end for the close brace. Use at your own risk.
Parsing template schema with Python and Regular Expressions
I'm working on a script for work to extract data from an old template engine schema: [%price%] { $54.99 } [%/price%] [%model%] { WRT54G } [%/model%] [%brand%]{ LINKSYS } [%/brand%] everything within the [% %] is the key, and everything in the { } is the value. Using Python and regex, I was able to get this far: (?<=[%)(?P\w*?)(?=\%]) which returns ['price', 'model', 'brand'] I'm just having a problem getting it match the bracket data as a value
[ "I agree with Devin that a single regex isn't the best solution. If there do happen to be any strange cases that aren't handled by your regex, there's a real risk that you won't find out.\nI'd suggest using a finite state machine approach. Parse the file line by line, first looking for a price-model-brand block, then parse whatever is within the braces. Also, make sure to note if any blocks aren't opened or closed correctly as these are probably malformed.\nYou should be able to write something like this in python in about 30-40 lines of code.\n", "It looks like it'd be easier to do with re.Scanner (sadly undocumented) than with a single regular expression.\n", "just for grins:\nimport re\nRE_kv = re.compile(\"\\[%(.*)%\\].*?\\n?\\s*{\\s*(.*)\")\nmatches = re.findall(RE_kv, test, re.M)\nfor k, v in matches:\n print k, v\n\noutput:\nprice $54.99\nmodel WRT54G\nbrand LINKSYS\n\nNote I did just enough regex to get the matches to show up, it's not even bounded at the end for the close brace. Use at your own risk.\n" ]
[ 4, 0, 0 ]
[]
[]
[ "grouping", "parsing", "python", "regex" ]
stackoverflow_0000695505_grouping_parsing_python_regex.txt
Q: Limiting the results of cProfile to lines containing "something" _and/or_ "something_else" I am using cProfile to profile the leading function of my entire app. It's working great except for some 3rd party libraries that are being profiled, and shown in the output as well. This is not always desirable when reading the output. My question is, how can i limit this? The documentation on python profilers mentions: p.sort_stats('time', 'cum').print_stats(.5, 'init') This line sorts statistics with a primary key of time, and a secondary key of cumulative time, and then prints out some of the statistics. To be specific, the list is first culled down to 50% (re: .5) of its original size, then only lines containing init are maintained, and that sub-sub-list is printed. It mentions that lines containing "init" will only be displayed. This works great, but i want to limit it in such a way so that i can say, limit lines containing "init" and/or "get". By trial and error i found that you can add another argument, a string, and it will be filtered further to display only lines containing string1 and string2. Using my previous example, this would look like: p.sort_stats('time', 'cum').print_stats(.5, 'init', 'get') Anyone know how you could limit the lines so that only lines containing "init" and/or "get" would be displayed? A: Per the docs you linked, the strings are regular expressions: Each restriction is either an integer ..., or a regular expression (to pattern match the standard name that is printed; as of Python 1.5b1, this uses the Perl-style regular expression syntax defined by the re module) Accordingly: p.sort_stats('time', 'cum').print_stats(.5, 'init|get') should work.
Limiting the results of cProfile to lines containing "something" _and/or_ "something_else"
I am using cProfile to profile the leading function of my entire app. It's working great except for some 3rd party libraries that are being profiled, and shown in the output as well. This is not always desirable when reading the output. My question is, how can i limit this? The documentation on python profilers mentions: p.sort_stats('time', 'cum').print_stats(.5, 'init') This line sorts statistics with a primary key of time, and a secondary key of cumulative time, and then prints out some of the statistics. To be specific, the list is first culled down to 50% (re: .5) of its original size, then only lines containing init are maintained, and that sub-sub-list is printed. It mentions that lines containing "init" will only be displayed. This works great, but i want to limit it in such a way so that i can say, limit lines containing "init" and/or "get". By trial and error i found that you can add another argument, a string, and it will be filtered further to display only lines containing string1 and string2. Using my previous example, this would look like: p.sort_stats('time', 'cum').print_stats(.5, 'init', 'get') Anyone know how you could limit the lines so that only lines containing "init" and/or "get" would be displayed?
[ "Per the docs you linked, the strings are regular expressions:\n\nEach restriction is either an integer\n ..., or a regular expression (to\n pattern match the standard name that\n is printed; as of Python 1.5b1, this\n uses the Perl-style regular expression\n syntax defined by the re module)\n\nAccordingly:\np.sort_stats('time', 'cum').print_stats(.5, 'init|get')\n\nshould work.\n" ]
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0000695501_python.txt
Q: Upgraded to ubuntu 9.04 django test are now slow Upgraded my laptop to Ubuntu 9.04 and runing latest trunk of django and my test suite has tripled in time to run. Python2.6 Mysql Django 1.1 beta 1 SVN-10137 A: Quote from the Official Jaunty IRC (#ubuntu+1 on Freenode) Jaunty is NOT RELEASED and NOT SUPPORTED. It will most certainly break your system. A: You should verify that your tests are running in a transaction. Is MySQL using the InnoDB or MyISAM backend? If you were using InnoDB before and now MyISAM there is no transaction support in MyISAM.
Upgraded to ubuntu 9.04 django test are now slow
Upgraded my laptop to Ubuntu 9.04 and runing latest trunk of django and my test suite has tripled in time to run. Python2.6 Mysql Django 1.1 beta 1 SVN-10137
[ "Quote from the Official Jaunty IRC (#ubuntu+1 on Freenode)\n\nJaunty is NOT RELEASED and NOT SUPPORTED. It will most certainly break your system.\n\n", "You should verify that your tests are running in a transaction. Is MySQL using the InnoDB or MyISAM backend? If you were using InnoDB before and now MyISAM there is no transaction support in MyISAM.\n" ]
[ 3, 0 ]
[]
[]
[ "django", "python", "testing", "ubuntu", "ubuntu_9.04" ]
stackoverflow_0000692294_django_python_testing_ubuntu_ubuntu_9.04.txt
Q: Bad Pickle get error I have been using a flash card program called Mnemosyne which uses python script. A short time ago my database of flash cards became inaccessible after my computer froze and I had to shut it down manually. Whenever I try to load the data base containing my cards I get this error. Invalid file format Traceback(innermost last): File "mnemosyne\core\mnemosyne_core.pyc", line 1012, in load_database BadPickleGet: 577" Help would be greatly appreciated. A: (Whilst CLayton's copy may be a binary distribution, the source to mnemosyne is freely available.) It's not much help though: line 1012 is just: db = cPickle.load(infile) Where ‘infile’ is the stored database file. So there's something corrupt in your database file. (BadPickleGet is a specific subclass of UnpicklingError, which is what you expect when the input is broken.) You could maybe change mnemosyne_core.py to use the plain Python pickle module instead of cPickle, allowing you to add debugging to pickle.py and work out exactly what it is in the file it doesn't like. But to be honest, if the file became corrupt due to a hardware fault/hard power down the chances are the contents are either truncated, unreadable or just total garbage. Prepare to be going through those early cards all over again...
Bad Pickle get error
I have been using a flash card program called Mnemosyne which uses python script. A short time ago my database of flash cards became inaccessible after my computer froze and I had to shut it down manually. Whenever I try to load the data base containing my cards I get this error. Invalid file format Traceback(innermost last): File "mnemosyne\core\mnemosyne_core.pyc", line 1012, in load_database BadPickleGet: 577" Help would be greatly appreciated.
[ "(Whilst CLayton's copy may be a binary distribution, the source to mnemosyne is freely available.)\nIt's not much help though: line 1012 is just:\ndb = cPickle.load(infile)\n\nWhere ‘infile’ is the stored database file. So there's something corrupt in your database file. (BadPickleGet is a specific subclass of UnpicklingError, which is what you expect when the input is broken.)\nYou could maybe change mnemosyne_core.py to use the plain Python pickle module instead of cPickle, allowing you to add debugging to pickle.py and work out exactly what it is in the file it doesn't like. But to be honest, if the file became corrupt due to a hardware fault/hard power down the chances are the contents are either truncated, unreadable or just total garbage.\nPrepare to be going through those early cards all over again...\n" ]
[ 1 ]
[]
[]
[ "pickle", "python" ]
stackoverflow_0000694192_pickle_python.txt
Q: How to distinguish between a function and a class method? If a variable refers to either a function or a class method, how can I find out which one it is and get the class type in case it is a class method especially when the class is still being declared as in the given example. eg. def get_info(function_or_method): print function_or_method class Foo(object): def __init__(self): pass get_info(__init__) def bar(): pass get_info(bar) Update to question after the first two responses from David and J. F. Sebastian To reemphasize a point which J.F. Sebastian alluded to, I want to be able to distinguish it when the function is being declared within the class (when the type I am getting is a function and not a bound or unbound method). ie. where the first call to get_info(__init__) happens I would like to be able to detect that its a method being declared as a part of a class. This question came up since I am putting a decorator around it and it gets a handle to the init function and I can't actually figure out if a method is being declared within a class or as a stand alone function A: You can distinguish between the two by checking the type: >>> type(bar) <type 'function'> >>> type(Foo.__init__) <type 'instancemethod'> or >>> import types >>> isinstance(bar, types.FunctionType) True >>> isinstance(bar, types.UnboundMethodType) True which is the way you'd do it in an if statement. Also, you can get the class from the im_class attribute of the method: >>> Foo.__init__.im_class __main__.Foo A: At the time you are calling get_info(__init__) (inside class definition) the __init__ is an ordinary function. def get_info(function_or_method): print function_or_method class Foo(object): def __init__(self): pass get_info(__init__) # function def bar(): pass get_info(Foo.__init__) # unbound method get_info(Foo().__init__) # bound method get_info(bar) # function Output (CPython, IronPython): <function __init__ at ...> <unbound method Foo.__init__> <bound method Foo.__init__ of <__main__.Foo object at ...>> <function bar at ...> Output (Jython): <function __init__ 1> <unbound method Foo.__init__> <method Foo.__init__ of Foo instance 2> <function bar 3> A: To reemphasize a point which J.F. Sebastian alluded to, I want to be able to distinguish it when the function is being declared within the class (when the type I am getting is a function and not a bound or unbound method). ie. where the first call to get_info(__init__) happens I would like to be able to detect that its a method being declared as a part of a class. This question came up since I am putting a decorator around it and it gets a handle to the init function and I can't actually figure out if a method is being declared within a class or as a stand alone function You can't. J.F. Sebastian's answer is still 100% applicable. When the body of the class definition is being executed, the class itself doesn't exist yet. The statements (the __init__ function definition, and the get_info(__init__) call) happen in a new local namespace; at the time the call to get_info occurs, __init__ is a reference to the function in that namespace, which is indistinguishable from a function defined outside of a class.
How to distinguish between a function and a class method?
If a variable refers to either a function or a class method, how can I find out which one it is and get the class type in case it is a class method especially when the class is still being declared as in the given example. eg. def get_info(function_or_method): print function_or_method class Foo(object): def __init__(self): pass get_info(__init__) def bar(): pass get_info(bar) Update to question after the first two responses from David and J. F. Sebastian To reemphasize a point which J.F. Sebastian alluded to, I want to be able to distinguish it when the function is being declared within the class (when the type I am getting is a function and not a bound or unbound method). ie. where the first call to get_info(__init__) happens I would like to be able to detect that its a method being declared as a part of a class. This question came up since I am putting a decorator around it and it gets a handle to the init function and I can't actually figure out if a method is being declared within a class or as a stand alone function
[ "You can distinguish between the two by checking the type:\n>>> type(bar)\n<type 'function'>\n>>> type(Foo.__init__)\n<type 'instancemethod'>\n\nor\n>>> import types\n>>> isinstance(bar, types.FunctionType)\nTrue\n>>> isinstance(bar, types.UnboundMethodType)\nTrue\n\nwhich is the way you'd do it in an if statement.\nAlso, you can get the class from the im_class attribute of the method:\n>>> Foo.__init__.im_class\n__main__.Foo\n\n", "At the time you are calling get_info(__init__) (inside class definition) the __init__ is an ordinary function.\ndef get_info(function_or_method):\n print function_or_method\n\nclass Foo(object):\n def __init__(self):\n pass\n get_info(__init__) # function\n\ndef bar():\n pass\n\nget_info(Foo.__init__) # unbound method\nget_info(Foo().__init__) # bound method\nget_info(bar) # function\n\nOutput (CPython, IronPython):\n<function __init__ at ...>\n<unbound method Foo.__init__>\n<bound method Foo.__init__ of <__main__.Foo object at ...>>\n<function bar at ...>\n\nOutput (Jython):\n<function __init__ 1>\n<unbound method Foo.__init__>\n<method Foo.__init__ of Foo instance 2>\n<function bar 3>\n\n", "\nTo reemphasize a point which J.F. Sebastian alluded to, I want to be able to distinguish it when the function is being declared within the class (when the type I am getting is a function and not a bound or unbound method). ie. where the first call to get_info(__init__) happens I would like to be able to detect that its a method being declared as a part of a class.\nThis question came up since I am putting a decorator around it and it gets a handle to the init function and I can't actually figure out if a method is being declared within a class or as a stand alone function\n\nYou can't. J.F. Sebastian's answer is still 100% applicable. When the body of the class definition is being executed, the class itself doesn't exist yet. The statements (the __init__ function definition, and the get_info(__init__) call) happen in a new local namespace; at the time the call to get_info occurs, __init__ is a reference to the function in that namespace, which is indistinguishable from a function defined outside of a class.\n" ]
[ 13, 9, 4 ]
[]
[]
[ "metaprogramming", "python", "reflection" ]
stackoverflow_0000695679_metaprogramming_python_reflection.txt
Q: How can I make this recursive crawl function iterative? For academic and performance sake, given this crawl recursive web-crawling function (which crawls only within the given domain) what would be the best approach to make it run iteratively? Currently when it runs, by the time it finishes python has climbed to using over 1GB of memory which isn't acceptable for running in a shared environment. def crawl(self, url): "Get all URLS from which to scrape categories." try: links = BeautifulSoup(urllib2.urlopen(url)).findAll(Crawler._match_tag) except urllib2.HTTPError: return for link in links: for attr in link.attrs: if Crawler._match_attr(attr): if Crawler._is_category(attr): pass elif attr[1] not in self._crawled: self._crawled.append(attr[1]) self.crawl(attr[1]) A: Use a BFS instead of crawling recursively (DFS): http://en.wikipedia.org/wiki/Breadth_first_search You can use an external storage solution (such as a database) for BFS queue to free up RAM. The algorithm is: //pseudocode: var urlsToVisit = new Queue(); // Could be a queue (BFS) or stack(DFS). (probably with a database backing or something). var visitedUrls = new Set(); // List of visited URLs. // initialization: urlsToVisit.Add( rootUrl ); while(urlsToVisit.Count > 0) { var nextUrl = urlsToVisit.FetchAndRemoveNextUrl(); var page = FetchPage(nextUrl); ProcessPage(page); visitedUrls.Add(nextUrl); var links = ParseLinks(page); foreach (var link in links) if (!visitedUrls.Contains(link)) urlsToVisit.Add(link); } A: Instead of recursing, you could put the new URLs to crawl into a queue. Then run until the queue is empty without recursing. If you put the queue into a file this uses almost no memory at all. A: @Mehrdad - Thank you for your reply, the example you provided was concise and easy to understand. The solution: def crawl(self, url): urls = Queue(-1) _crawled = [] urls.put(url) while not urls.empty(): url = urls.get() try: links = BeautifulSoup(urllib2.urlopen(url)).findAll(Crawler._match_tag) except urllib2.HTTPError: continue for link in links: for attr in link.attrs: if Crawler._match_attr(attr): if Crawler._is_category(attr): continue else: Crawler._visit(attr[1]) if attr[1] not in _crawled: urls.put(attr[1]) A: You can do it pretty easily just by using links as a queue: def get_links(url): "Extract all matching links from a url" try: links = BeautifulSoup(urllib2.urlopen(url)).findAll(Crawler._match_tag) except urllib2.HTTPError: return [] def crawl(self, url): "Get all URLS from which to scrape categories." links = get_links(url) while len(links) > 0: link = links.pop() for attr in link.attrs: if Crawler._match_attr(attr): if Crawler._is_category(attr): pass elif attr[1] not in self._crawled: self._crawled.append(attr[1]) # prepend the new links to the queue links = get_links(attr[1]) + links Of course, this doesn't solve the memory problem...
How can I make this recursive crawl function iterative?
For academic and performance sake, given this crawl recursive web-crawling function (which crawls only within the given domain) what would be the best approach to make it run iteratively? Currently when it runs, by the time it finishes python has climbed to using over 1GB of memory which isn't acceptable for running in a shared environment. def crawl(self, url): "Get all URLS from which to scrape categories." try: links = BeautifulSoup(urllib2.urlopen(url)).findAll(Crawler._match_tag) except urllib2.HTTPError: return for link in links: for attr in link.attrs: if Crawler._match_attr(attr): if Crawler._is_category(attr): pass elif attr[1] not in self._crawled: self._crawled.append(attr[1]) self.crawl(attr[1])
[ "Use a BFS instead of crawling recursively (DFS): http://en.wikipedia.org/wiki/Breadth_first_search\nYou can use an external storage solution (such as a database) for BFS queue to free up RAM.\nThe algorithm is:\n//pseudocode:\nvar urlsToVisit = new Queue(); // Could be a queue (BFS) or stack(DFS). (probably with a database backing or something).\nvar visitedUrls = new Set(); // List of visited URLs.\n\n// initialization:\nurlsToVisit.Add( rootUrl );\n\nwhile(urlsToVisit.Count > 0) {\n var nextUrl = urlsToVisit.FetchAndRemoveNextUrl();\n var page = FetchPage(nextUrl);\n ProcessPage(page);\n visitedUrls.Add(nextUrl);\n var links = ParseLinks(page);\n foreach (var link in links)\n if (!visitedUrls.Contains(link))\n urlsToVisit.Add(link); \n}\n\n", "Instead of recursing, you could put the new URLs to crawl into a queue. Then run until the queue is empty without recursing. If you put the queue into a file this uses almost no memory at all.\n", "@Mehrdad - Thank you for your reply, the example you provided was concise and easy to understand.\nThe solution:\n def crawl(self, url):\n urls = Queue(-1)\n _crawled = []\n\n urls.put(url)\n\n while not urls.empty():\n url = urls.get()\n try:\n links = BeautifulSoup(urllib2.urlopen(url)).findAll(Crawler._match_tag)\n except urllib2.HTTPError:\n continue\n for link in links:\n for attr in link.attrs:\n if Crawler._match_attr(attr):\n if Crawler._is_category(attr):\n continue\n else:\n Crawler._visit(attr[1])\n if attr[1] not in _crawled:\n urls.put(attr[1])\n\n", "You can do it pretty easily just by using links as a queue:\ndef get_links(url):\n \"Extract all matching links from a url\"\n try:\n links = BeautifulSoup(urllib2.urlopen(url)).findAll(Crawler._match_tag)\n except urllib2.HTTPError:\n return []\n\ndef crawl(self, url):\n \"Get all URLS from which to scrape categories.\"\n links = get_links(url)\n while len(links) > 0:\n link = links.pop()\n for attr in link.attrs:\n if Crawler._match_attr(attr):\n if Crawler._is_category(attr):\n pass\n elif attr[1] not in self._crawled:\n self._crawled.append(attr[1])\n # prepend the new links to the queue\n links = get_links(attr[1]) + links\n\nOf course, this doesn't solve the memory problem...\n" ]
[ 12, 5, 2, 0 ]
[]
[]
[ "python", "recursion", "web_crawler" ]
stackoverflow_0000694366_python_recursion_web_crawler.txt
Q: Populate a list in python I have a series of Python tuples representing coordinates: tuples = [(1,1), (0,1), (1,0), (0,0), (2,1)] I want to create the following list: l = [] for t in tuples: l[ t[0] ][ t[1] ] = something I get an IndexError: list index out of range. My background is in PHP and I expected that in Python you can create lists that start with index > 0, i.e. make gaps and then fill them up, but it seems you can't. The idea is to have the lists sorted afterwards. I know I can do this with a dictionary, but as far as I know dictionaries cannot be sorted by keys. Update: I now know they can - see the accepted solution. Edit: What I want to do is to create a 2D array that will represent the matrix described with the tuple coordinates, then iterate it in order. If I use a dictionary, i have no guarantee that iterating over the keys will be in order -> (0,0) (0,1) (0,2) (1,0) (1,1) (1,2) (2,0) (2,1) (2,2) Can anyone help? A: No, you cannot create list with gaps. But you can create a dictionary with tuple keys: tuples = [(1,1), (0,1), (1,0), (0,0), (2,1)] l = {} for t in tuples: l[t] = something Update: Try using NumPy, it provides wide range of operations over matrices and array. Cite from free pfd on NumPy available on the site (3.4.3 Flat Iterator indexing): "As mentioned previously, X.flat returns an iterator that will iterate over the entire array (in C-contiguous style with the last index varying the fastest". Looks like what you need. A: You should look at dicts for something like that. for t in tuples: if not l.has_key(t[0]): l[t[0]] = {} l[t[0]][t[1]] = something Iterating over the dict is a bit different than iterating over a list, though. You'll have the keys(), values() and items() functions to help with that. EDIT: try something like this for ordering: for x in sorted(l.keys()): for y in sorted(l[x].keys()): print l[x][y] A: You create a one-dimensional list l and want to use it as a two-dimensional list. Thats why you get an index error. You have the following options: create a map and use the tuple t as index: l = {} l[t] = something and you will get entries in l as: {(1, 1): something} if you want a traditional array structure I'll advise you to look at numpy. With numpy you get n-dimensional arrays with "traditional" indexing. As I mentioned use numpy, with numpy you can create a 2-dimensional array, filled with zeros or ones or ... Tha you can fill any desired value with indexing [x,y] as you desire. Of course you can iterate over rows and columns or the whole array as a list. A: If you know the size that you before hand,you can make a list of lists like this >>> x = 3 >>> y = 3 >>> l = [[None] * x for i in range(y)] >>> l [[None, None, None], [None, None, None], [None, None, None]] Which you can then iterate like you originally suggested. A: Extending the Nathan's answer, tuples = [(1,1), (0,1), (1,0), (0,0), (2,1)] x = max(tuples, key = lambda z : z[0])[0] + 1 y = max(tuples, key = lambda z : z[1])[1] + 1 l = [[None] * y for i in range(x)] And then you can do whatever you want A: What do you mean exactly by "but as far as I know dictionaries cannot be sorted by keys"? While this is not strictly the same as a "sorted dictionary", you can easily turn a dictionary into a list, sorted by the key, which seems to be what you're after: >>> tuples = [(1,1), (0,1), (1,0), (0,0), (2,1)] >>> l = {} >>> for t in tuples: ... l[t] = "something" >>> sorted(l) # equivalent to sorted(l.keys()) [(0, 0), (0, 1), (1, 0), (1, 1), (2, 1)] >>> sorted(l.items()) # make a list of (key, value) tuples, and sort by key [((0, 0), 'something'), ((0, 1), 'something'), ((1, 0), 'something'), ((1, 1), 'something'), ((2, 1), 'something')] (I turned something into the string "something" just to make the code work) To make use of this for your case however (if I understand it correctly, that is), you would still need to fill the dictionary with None values or something for every "empty" coordinate tuple) A: As mentioned earlier, you can't make lists with gaps, and dictionaries may be the better choice here. The trick is to makes sure that l[t[0]] exists when you put something in position t[1]. For this, I'd use a defaultdict. import collections tuples = [(1,1), (0,1), (1,0), (0,0), (2,1)] l = collections.defaultdict(dict) for t in tuples: l[t[0]][t[1]] = something Since l is a defaultdict, if l[t[0]] doesn't exist, it will create an empty dict for you to put your something in at position t[1]. Note: this ends up being the same as @unwesen's answer, without the minor tedium of hand-checking for existence of the inner dict. Chalk it up to concurrent answering. A: The dict solutions given are probably best for most purposes. For your issue of iterating over the keys in order, generally you would instead iterate over the coordinate space, not the dict keys, exactly the same way you would have for your list of lists. Use .get and you can specify the default value to use for the blank cells, or alternatively use "collections.defaultdict" to define a default at dict creation time. eg. for y in range(10): for x in range(10): value = mydict.get((x,y), some_default_value) # or just "value = mydict[x,y]" if used defaultdict If you do need an actual list of lists, you can construct it directly as below: max_x, max_y = map(max, zip(*tuples)) l=[[something if (x,y) in tuples else 0 for y in range(max_y+1)] for x in xrange(max_x+1)] If the list of tuples is likely to be long, the for performance reasons, you may want to use a set for the lookup,as "(x,y) in tuples" performs a scan of the list, rather than a fast lookup by hash. ie, change the second line to: tuple_set = set(tuples) l=[[something if (x,y) in tuple_set else 0 for y in range(max_y+1)] for x in xrange(max_x+1)]
Populate a list in python
I have a series of Python tuples representing coordinates: tuples = [(1,1), (0,1), (1,0), (0,0), (2,1)] I want to create the following list: l = [] for t in tuples: l[ t[0] ][ t[1] ] = something I get an IndexError: list index out of range. My background is in PHP and I expected that in Python you can create lists that start with index > 0, i.e. make gaps and then fill them up, but it seems you can't. The idea is to have the lists sorted afterwards. I know I can do this with a dictionary, but as far as I know dictionaries cannot be sorted by keys. Update: I now know they can - see the accepted solution. Edit: What I want to do is to create a 2D array that will represent the matrix described with the tuple coordinates, then iterate it in order. If I use a dictionary, i have no guarantee that iterating over the keys will be in order -> (0,0) (0,1) (0,2) (1,0) (1,1) (1,2) (2,0) (2,1) (2,2) Can anyone help?
[ "No, you cannot create list with gaps. But you can create a dictionary with tuple keys:\ntuples = [(1,1), (0,1), (1,0), (0,0), (2,1)]\nl = {}\nfor t in tuples:\n l[t] = something\n\nUpdate:\nTry using NumPy, it provides wide range of operations over matrices and array. Cite from free pfd on NumPy available on the site (3.4.3 Flat Iterator indexing): \"As mentioned previously, X.flat returns an iterator that will iterate over the entire array (in C-contiguous style with the last index varying the fastest\". Looks like what you need.\n", "You should look at dicts for something like that.\nfor t in tuples:\n if not l.has_key(t[0]):\n l[t[0]] = {}\n l[t[0]][t[1]] = something\n\nIterating over the dict is a bit different than iterating over a list, though. You'll have the keys(), values() and items() functions to help with that.\nEDIT: try something like this for ordering:\nfor x in sorted(l.keys()):\n for y in sorted(l[x].keys()):\n print l[x][y]\n\n", "You create a one-dimensional list l and want to use it as a two-dimensional list.\nThats why you get an index error.\nYou have the following options:\ncreate a map and use the tuple t as index:\nl = {}\nl[t] = something\n\nand you will get entries in l as:\n{(1, 1): something}\n\nif you want a traditional array structure I'll advise you to look at numpy. With numpy you get n-dimensional arrays with \"traditional\" indexing.\nAs I mentioned use numpy,\nwith numpy you can create a 2-dimensional array, filled with zeros or ones or ...\nTha you can fill any desired value with indexing [x,y] as you desire.\nOf course you can iterate over rows and columns or the whole array as a list.\n", "If you know the size that you before hand,you can make a list of lists like this\n>>> x = 3\n>>> y = 3\n>>> l = [[None] * x for i in range(y)]\n>>> l\n[[None, None, None], [None, None, None], [None, None, None]]\n\nWhich you can then iterate like you originally suggested.\n", "Extending the Nathan's answer, \ntuples = [(1,1), (0,1), (1,0), (0,0), (2,1)]\nx = max(tuples, key = lambda z : z[0])[0] + 1\ny = max(tuples, key = lambda z : z[1])[1] + 1\nl = [[None] * y for i in range(x)]\n\nAnd then you can do whatever you want\n", "What do you mean exactly by \"but as far as I know dictionaries cannot be sorted by keys\"?\nWhile this is not strictly the same as a \"sorted dictionary\", you can easily turn a dictionary into a list, sorted by the key, which seems to be what you're after:\n>>> tuples = [(1,1), (0,1), (1,0), (0,0), (2,1)]\n>>> l = {}\n>>> for t in tuples:\n... l[t] = \"something\"\n>>> sorted(l) # equivalent to sorted(l.keys())\n[(0, 0), (0, 1), (1, 0), (1, 1), (2, 1)]\n>>> sorted(l.items()) # make a list of (key, value) tuples, and sort by key\n[((0, 0), 'something'), ((0, 1), 'something'), ((1, 0), 'something'), ((1, 1), 'something'), ((2, 1), 'something')] \n\n(I turned something into the string \"something\" just to make the code work)\nTo make use of this for your case however (if I understand it correctly, that is), you would still need to fill the dictionary with None values or something for every \"empty\" coordinate tuple)\n", "As mentioned earlier, you can't make lists with gaps, and dictionaries may be the better choice here. The trick is to makes sure that l[t[0]] exists when you put something in position t[1]. For this, I'd use a defaultdict.\nimport collections\ntuples = [(1,1), (0,1), (1,0), (0,0), (2,1)]\nl = collections.defaultdict(dict)\nfor t in tuples:\n l[t[0]][t[1]] = something\n\nSince l is a defaultdict, if l[t[0]] doesn't exist, it will create an empty dict for you to put your something in at position t[1].\nNote: this ends up being the same as @unwesen's answer, without the minor tedium of hand-checking for existence of the inner dict. Chalk it up to concurrent answering.\n", "The dict solutions given are probably best for most purposes. For your issue of iterating over the keys in order, generally you would instead iterate over the coordinate space, not the dict keys, exactly the same way you would have for your list of lists. Use .get and you can specify the default value to use for the blank cells, or alternatively use \"collections.defaultdict\" to define a default at dict creation time. eg.\nfor y in range(10):\n for x in range(10):\n value = mydict.get((x,y), some_default_value)\n # or just \"value = mydict[x,y]\" if used defaultdict\n\nIf you do need an actual list of lists, you can construct it directly as below:\nmax_x, max_y = map(max, zip(*tuples))\nl=[[something if (x,y) in tuples else 0 for y in range(max_y+1)] \n for x in xrange(max_x+1)]\n\nIf the list of tuples is likely to be long, the for performance reasons, you may want to use a set for the lookup,as \"(x,y) in tuples\" performs a scan of the list, rather than a fast lookup by hash. ie, change the second line to:\ntuple_set = set(tuples)\nl=[[something if (x,y) in tuple_set else 0 for y in range(max_y+1)] \n for x in xrange(max_x+1)]\n\n" ]
[ 8, 6, 3, 2, 1, 1, 0, 0 ]
[ "I think you have only declared a one dimensional list. \nI think you declare it as \nl = [][]\n\n\nEdit: That's a syntax error\n>>> l = [][]\n File \"<stdin>\", line 1\n l = [][]\n ^\nSyntaxError: invalid syntax\n>>> \n\n" ]
[ -2 ]
[ "list", "python", "tuples" ]
stackoverflow_0000696874_list_python_tuples.txt
Q: What is the pythonic way to share common files in multiple projects? Lets say I have projects x and y in brother directories: projects/x and projects/y. There are some utility funcs common to both projects in myutils.py and some db stuff in mydbstuff.py, etc. Those are minor common goodies, so I don't want to create a single package for them. Questions arise about the whereabouts of such files, possible changes to PYTHONPATH, proper way to import, etc. What is the 'pythonic way' to use such files? A: The pythonic way is to create a single extra package for them. Why don't you want to create a package? You can distribute this package with both projects, and the effect would be the same. You'll never do it right for all instalation scenarios and platforms if you do it by mangling with PYTHONPATH and custom imports. Just create another package and be done in no time. A: You can add path to shared files to sys.path either directly by sys.path.append(pathToShared) or by defining .pth files and add them to with site.addsitedir. Path files (.pth) are simple text files with a path in each line. A: You can also create a .pth file, which will store the directory(ies) that you want added to your PYTHONPATH. .pth files are copied to the Python/lib/site-packages directory, and any directory in that file will be added to your PYTHONPATH at runtime. http://docs.python.org/library/site.html StackOVerflow question (see accepted solution) A: I agree with 'create a package'. If you cannot do that, how about using symbolic links/junctions (ln -s on Linux, linkd on Windows)? A: I'd advise using setuptools for this. It allows you to set dependencies so you can make sure all of these packages/individual modules are on the sys.path before installing a package. If you want to install something that's just a single source file, it has support for automagically generating a simple setup.py for it. This may be useful if you decide not to go the package route. If you plan on deploying this on multiple computers, I will usually set up a webserver with all the dependencies I plan on using so it can install them for you automatically. I've also heard good things about paver, but haven't used it myself.
What is the pythonic way to share common files in multiple projects?
Lets say I have projects x and y in brother directories: projects/x and projects/y. There are some utility funcs common to both projects in myutils.py and some db stuff in mydbstuff.py, etc. Those are minor common goodies, so I don't want to create a single package for them. Questions arise about the whereabouts of such files, possible changes to PYTHONPATH, proper way to import, etc. What is the 'pythonic way' to use such files?
[ "The pythonic way is to create a single extra package for them.\nWhy don't you want to create a package? You can distribute this package with both projects, and the effect would be the same.\nYou'll never do it right for all instalation scenarios and platforms if you do it by mangling with PYTHONPATH and custom imports.\nJust create another package and be done in no time.\n", "You can add path to shared files to sys.path either directly by sys.path.append(pathToShared) or by defining .pth files and add them to with site.addsitedir. Path files (.pth) are simple text files with a path in each line.\n", "You can also create a .pth file, which will store the directory(ies) that you want added to your PYTHONPATH. .pth files are copied to the Python/lib/site-packages directory, and any directory in that file will be added to your PYTHONPATH at runtime.\nhttp://docs.python.org/library/site.html \nStackOVerflow question (see accepted solution)\n", "I agree with 'create a package'.\nIf you cannot do that, how about using symbolic links/junctions (ln -s on Linux, linkd on Windows)?\n", "I'd advise using setuptools for this. It allows you to set dependencies so you can make sure all of these packages/individual modules are on the sys.path before installing a package. If you want to install something that's just a single source file, it has support for automagically generating a simple setup.py for it. This may be useful if you decide not to go the package route.\nIf you plan on deploying this on multiple computers, I will usually set up a webserver with all the dependencies I plan on using so it can install them for you automatically.\nI've also heard good things about paver, but haven't used it myself.\n" ]
[ 9, 1, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0000696792_python.txt
Q: How do I get the filepath for a class in Python? Given a class C in Python, how can I determine which file the class was defined in? I need something that can work from either the class C, or from an instance off C. The reason I am doing this, is because I am generally a fan off putting files that belong together in the same folder. I want to create a class that uses a Django template to render itself as HTML. The base implementation should infer the filename for the template based on the filename that the class is defined in. Say I put a class LocationArtifact in the file "base/artifacts.py", then I want the default behaviour to be that the template name is "base/LocationArtifact.html". A: You can use the inspect module, like this: import inspect inspect.getfile(C.__class__) A: try: import sys, os os.path.abspath(sys.modules[LocationArtifact.__module__].__file__) A: This is the wrong approach for Django and really forcing things. The typical Django app pattern is: /project /appname models.py views.py /templates index.html etc.
How do I get the filepath for a class in Python?
Given a class C in Python, how can I determine which file the class was defined in? I need something that can work from either the class C, or from an instance off C. The reason I am doing this, is because I am generally a fan off putting files that belong together in the same folder. I want to create a class that uses a Django template to render itself as HTML. The base implementation should infer the filename for the template based on the filename that the class is defined in. Say I put a class LocationArtifact in the file "base/artifacts.py", then I want the default behaviour to be that the template name is "base/LocationArtifact.html".
[ "You can use the inspect module, like this:\nimport inspect\ninspect.getfile(C.__class__)\n\n", "try:\nimport sys, os\nos.path.abspath(sys.modules[LocationArtifact.__module__].__file__)\n\n", "This is the wrong approach for Django and really forcing things.\nThe typical Django app pattern is:\n\n/project\n\n/appname\n\nmodels.py\nviews.py\n/templates\n\nindex.html\netc.\n\n\n\n\n" ]
[ 172, 46, 5 ]
[]
[]
[ "class", "introspection", "python" ]
stackoverflow_0000697320_class_introspection_python.txt
Q: Importing in Python In Python 2.5, I import modules by changing environment variables. It works, but using site-packages does not. Is there another way to import modules in directories other than C:\Python25 ? A: On way is with PYTHONPATH environment variable. Other one is to add path to sys.path either directly by sys.path.append(path) or by defining .pth files and add them to with site.addsitedir(dirWithPths). Path files (.pth) are simple text files with a path in each line. Every .pth file in dirWithPths will be read. A: Append the location to the module to sys.path. Edit: (to counter the post below ;-) ) os.path does something completely different. You need to use sys.path. sys.path.append("/home/me/local/modules") A: Directories added to the PYTHONPATH environment variable are searched after site-packages, so if you have a module in site-packages with the same name as the module you want from your PYTHONPATH, the site-packages version will win. Also, you may need to restart your interpreter and the shell that launched it for the change to the environment variable to take effect. If you want to add a directory to the search path at run time, without restarting your program, add the directory to sys.path. For example: import sys sys.path.append(newpath) If you want your new directory to be searched before site-packages, put the directory at the front of the list, like this: import sys sys.path.insert(0, newpath)
Importing in Python
In Python 2.5, I import modules by changing environment variables. It works, but using site-packages does not. Is there another way to import modules in directories other than C:\Python25 ?
[ "On way is with PYTHONPATH environment variable. Other one is to add path to sys.path either directly by sys.path.append(path) or by defining .pth files and add them to with site.addsitedir(dirWithPths). Path files (.pth) are simple text files with a path in each line. Every .pth file in dirWithPths will be read.\n", "Append the location to the module to sys.path. \nEdit: (to counter the post below ;-) )\nos.path does something completely different. You need to use sys.path.\nsys.path.append(\"/home/me/local/modules\")\n\n", "Directories added to the PYTHONPATH environment variable are searched after site-packages, so if you have a module in site-packages with the same name as the module you want from your PYTHONPATH, the site-packages version will win. Also, you may need to restart your interpreter and the shell that launched it for the change to the environment variable to take effect.\nIf you want to add a directory to the search path at run time, without restarting your program, add the directory to sys.path. For example:\nimport sys\nsys.path.append(newpath)\n\nIf you want your new directory to be searched before site-packages, put the directory at the front of the list, like this:\nimport sys\nsys.path.insert(0, newpath)\n\n" ]
[ 7, 4, 4 ]
[ "sys.path is a list to which you can append custom paths to search like this:\nsys.path.append(\"/home/foo\")\n\n" ]
[ -1 ]
[ "import", "python" ]
stackoverflow_0000697281_import_python.txt
Q: Processing XML into MySQL in good form I need to process XML documents of varying formats into records in a MySQL database on a daily basis. The data I need from each XML document is interspersed with a good deal of data I don't need, and each document's node names are different. For example: source #1: <object id="1"> <title>URL 1</title> <url>http://www.one.com</url> <frequency interval="60" /> <uselessdata>blah</uselessdata> </object> <object id="2"> <title>URL 2</title> <url>http://www.two.com</url> <frequency interval="60" /> <uselessdata>blah</uselessdata> </object> source #2: <object"> <objectid>1</objectid> <thetitle>URL 1</thetitle> <link>http://www.one.com</link> <frequency interval="60" /> <moreuselessdata>blah</moreuselessdata> </object> <object"> <objectid>2</objectid> <thetitle>URL 2</thetitle> <link>http://www.two.com</link> <frequency interval="60" /> <moreuselessdata>blah</moreuselessdata> </object> ...where I need the object's ID, interval, and URL. My ideas for approaches are: 1.) Having a separate function to parse each XML document and iteratively create the SQL query from within that function 2.) Having a separate function parse each document and iteratively add each object to my own object class, and have the SQL work done by a class method 3.) Using XSLT to convert all the documents into a common XML format and then writing a parser for that document. The XML documents themselves aren't all that large, as most will be under 1MB. I don't anticipate their structure changing often (if ever), but there is a strong possibility I will need to add and remove further sources as time goes on. I'm open to all ideas. Also, sorry if the XML samples above are mangled... they're not terribly important, just a rough idea to show that the node names in each document are different. A: Using XSLT is an overkill. I like approach (2), it makes a lot of sense. Using Python I'd try to make a class for every document type. The class would inherit from dict and on its __init__ parse the given document and populate itself with the 'id', 'interval' and 'url'. Then the code in main would be really trivial, just instantiate instances of those classes (which are also dicts) with the appropriate documents and then pass them off as normal dicts. A: I've been successfully using variant the third approach. But documents I've been processing were a lot bigger. If it's a overkill or not, well that really depends how fluent you are with XSLT. A: If your various input formats are unambiguous, you can do this: <xsl:template match="object"> <object> <id><xsl:value-of select="@id | objectid" /></id> <title><xsl:value-of select="title | thetitle" /></title> <url><xsl:value-of select="url | link" /></url> <interval><xsl:value-of select="frequency/@interval" /></interval> </object> </xsl:template> For your sample input, this produces: <object> <id>1</id> <title>URL 1</title> <url>http://www.one.com</url> <interval>60</interval> </object> <object> <id>2</id> <title>URL 2</title> <url>http://www.two.com</url> <interval>60</interval> </object> <object> <id>1</id> <title>URL 1</title> <url>http://www.one.com</url> <interval>60</interval> </object> <object> <id>2</id> <title>URL 2</title> <url>http://www.two.com</url> <interval>60</interval> </object> However, there may be faster methods to achieve a usable result than using XSLT. Just measure how fast each approach is, and how "ugly" if feels for you. I would tend to say that XSLT is the more elegant/maintainable solution to process XML. YMMV. If your input formats are ambiguous and the above solution produces wrong results, a more explicit aproach is needed, along the lines of: <xsl:template match="object"> <object> <xsl:choose> <xsl:when test="@id and title and url and frequency/@interval"> <xsl:apply-templates select="." mode="format1" /> </xsl:when> <xsl:when test="objectid and thetitle and link and frequency/@interval"> <xsl:apply-templates select="." mode="format2" /> </xsl:when> </xsl:choose> </object> </xsl:template> <xsl:template match="object" mode="format1"> <id><xsl:value-of select="@id" /></id> <title><xsl:value-of select="title" /></title> <url><xsl:value-of select="url" /></url> <interval><xsl:value-of select="frequency/@interval" /></interval> </xsl:template> <xsl:template match="object" mode="format2"> <id><xsl:value-of select="objectid" /></id> <title><xsl:value-of select="thetitle" /></title> <url><xsl:value-of select="link" /></url> <interval><xsl:value-of select="frequency/@interval" /></interval> </xsl:template>
Processing XML into MySQL in good form
I need to process XML documents of varying formats into records in a MySQL database on a daily basis. The data I need from each XML document is interspersed with a good deal of data I don't need, and each document's node names are different. For example: source #1: <object id="1"> <title>URL 1</title> <url>http://www.one.com</url> <frequency interval="60" /> <uselessdata>blah</uselessdata> </object> <object id="2"> <title>URL 2</title> <url>http://www.two.com</url> <frequency interval="60" /> <uselessdata>blah</uselessdata> </object> source #2: <object"> <objectid>1</objectid> <thetitle>URL 1</thetitle> <link>http://www.one.com</link> <frequency interval="60" /> <moreuselessdata>blah</moreuselessdata> </object> <object"> <objectid>2</objectid> <thetitle>URL 2</thetitle> <link>http://www.two.com</link> <frequency interval="60" /> <moreuselessdata>blah</moreuselessdata> </object> ...where I need the object's ID, interval, and URL. My ideas for approaches are: 1.) Having a separate function to parse each XML document and iteratively create the SQL query from within that function 2.) Having a separate function parse each document and iteratively add each object to my own object class, and have the SQL work done by a class method 3.) Using XSLT to convert all the documents into a common XML format and then writing a parser for that document. The XML documents themselves aren't all that large, as most will be under 1MB. I don't anticipate their structure changing often (if ever), but there is a strong possibility I will need to add and remove further sources as time goes on. I'm open to all ideas. Also, sorry if the XML samples above are mangled... they're not terribly important, just a rough idea to show that the node names in each document are different.
[ "Using XSLT is an overkill. I like approach (2), it makes a lot of sense.\nUsing Python I'd try to make a class for every document type. The class would inherit from dict and on its __init__ parse the given document and populate itself with the 'id', 'interval' and 'url'.\nThen the code in main would be really trivial, just instantiate instances of those classes (which are also dicts) with the appropriate documents and then pass them off as normal dicts.\n", "I've been successfully using variant the third approach. But documents I've been processing were a lot bigger. If it's a overkill or not, well that really depends how fluent you are with XSLT.\n", "If your various input formats are unambiguous, you can do this:\n<xsl:template match=\"object\">\n <object>\n <id><xsl:value-of select=\"@id | objectid\" /></id>\n <title><xsl:value-of select=\"title | thetitle\" /></title>\n <url><xsl:value-of select=\"url | link\" /></url>\n <interval><xsl:value-of select=\"frequency/@interval\" /></interval>\n </object>\n</xsl:template>\n\nFor your sample input, this produces:\n<object>\n <id>1</id>\n <title>URL 1</title>\n <url>http://www.one.com</url>\n <interval>60</interval>\n</object>\n<object>\n <id>2</id>\n <title>URL 2</title>\n <url>http://www.two.com</url>\n <interval>60</interval>\n</object>\n<object>\n <id>1</id>\n <title>URL 1</title>\n <url>http://www.one.com</url>\n <interval>60</interval>\n</object>\n<object>\n <id>2</id>\n <title>URL 2</title>\n <url>http://www.two.com</url>\n <interval>60</interval>\n</object>\n\nHowever, there may be faster methods to achieve a usable result than using XSLT. Just measure how fast each approach is, and how \"ugly\" if feels for you. I would tend to say that XSLT is the more elegant/maintainable solution to process XML. YMMV.\nIf your input formats are ambiguous and the above solution produces wrong results, a more explicit aproach is needed, along the lines of:\n<xsl:template match=\"object\">\n <object>\n <xsl:choose>\n <xsl:when test=\"@id and title and url and frequency/@interval\">\n <xsl:apply-templates select=\".\" mode=\"format1\" />\n </xsl:when>\n <xsl:when test=\"objectid and thetitle and link and frequency/@interval\">\n <xsl:apply-templates select=\".\" mode=\"format2\" />\n </xsl:when>\n </xsl:choose>\n </object>\n</xsl:template>\n\n<xsl:template match=\"object\" mode=\"format1\">\n <id><xsl:value-of select=\"@id\" /></id>\n <title><xsl:value-of select=\"title\" /></title>\n <url><xsl:value-of select=\"url\" /></url>\n <interval><xsl:value-of select=\"frequency/@interval\" /></interval>\n</xsl:template>\n\n<xsl:template match=\"object\" mode=\"format2\">\n <id><xsl:value-of select=\"objectid\" /></id>\n <title><xsl:value-of select=\"thetitle\" /></title>\n <url><xsl:value-of select=\"link\" /></url>\n <interval><xsl:value-of select=\"frequency/@interval\" /></interval>\n</xsl:template>\n\n" ]
[ 2, 0, 0 ]
[]
[]
[ "parsing", "python", "xml", "xslt" ]
stackoverflow_0000697741_parsing_python_xml_xslt.txt
Q: Easy way to parse .h file for comments using Python? How to parse in easy way a .h file written in C for comments and entity names using Python? We're suppose for a further writing the content into the word file already developed. Source comments are formatted using a simple tag-style rules. Comment tags used for an easy distinguishing one entity comment from the other and non-documenting comments. A comment could be in multi-line form. An each comment have stay straight upon the entity definition: //ENUM My comment bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla // could be multi-line. Bla bla bla bla bla bla bla bla bla. enum my_enum { //EITEM My enum item 1. // Just could be multi-line too. MY_ENUM_ITEM_1, //EITEM My enum item 2 MY_ENUM_ITEM_2, }; //STRUCT My struct struct my_struct { //MEMBER struct member 1 int m_1_; }; //FUNC my function 1 description. // Could be multi-line also. //INPUT arg1 - first argument //RETURN pointer to an allocated my_struct instance. my_struct* func_1(int arg1); A code-and-comments tree should come out as a result of this parsing. How does one make it quickly and without using third-party libraries? A: This has already been done. Several times over. Here is a parser for the C language written in Python. Start with this. http://wiki.python.org/moin/SeeGramWrap Other parsers. http://wiki.python.org/moin/LanguageParsing http://nedbatchelder.com/text/python-parsers.html You could probably download any ANSI C Yacc grammar and rework it into PLY format without too much trouble and use that as a jumping-off point. A: Here's a quick and dirty solution. It won't handle comments in strings, but since this is just for header files that shouldn't be an issue. S_CODE,S_INLINE,S_MULTLINE = range (3) f = open (sys.argv[1]) state = S_CODE comments = '' i = iter (lambda: f.read (1), '') while True: try: c = i.next () except StopIteration: break if state == S_CODE: if c == '/': c = i.next () if c == '*': state = S_MULTLINE elif c == '/': state = S_INLINE elif state == S_INLINE: comments += c if c == '\n': state == S_CODE elif state == S_MULTLINE: if c == '*': c = i.next () if c == '/': comments += '\n' state = S_CODE else: comments += '*%s' % c else: comments += c print comments A: Perhaps shlex module would do? If not, there are some more powerful alternatives: http://wiki.python.org/moin/LanguageParsing
Easy way to parse .h file for comments using Python?
How to parse in easy way a .h file written in C for comments and entity names using Python? We're suppose for a further writing the content into the word file already developed. Source comments are formatted using a simple tag-style rules. Comment tags used for an easy distinguishing one entity comment from the other and non-documenting comments. A comment could be in multi-line form. An each comment have stay straight upon the entity definition: //ENUM My comment bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla // could be multi-line. Bla bla bla bla bla bla bla bla bla. enum my_enum { //EITEM My enum item 1. // Just could be multi-line too. MY_ENUM_ITEM_1, //EITEM My enum item 2 MY_ENUM_ITEM_2, }; //STRUCT My struct struct my_struct { //MEMBER struct member 1 int m_1_; }; //FUNC my function 1 description. // Could be multi-line also. //INPUT arg1 - first argument //RETURN pointer to an allocated my_struct instance. my_struct* func_1(int arg1); A code-and-comments tree should come out as a result of this parsing. How does one make it quickly and without using third-party libraries?
[ "This has already been done. Several times over.\nHere is a parser for the C language written in Python. Start with this.\nhttp://wiki.python.org/moin/SeeGramWrap\nOther parsers.\nhttp://wiki.python.org/moin/LanguageParsing\nhttp://nedbatchelder.com/text/python-parsers.html\nYou could probably download any ANSI C Yacc grammar and rework it into PLY format without too much trouble and use that as a jumping-off point.\n", "Here's a quick and dirty solution. It won't handle comments in strings, but since this is just for header files that shouldn't be an issue.\nS_CODE,S_INLINE,S_MULTLINE = range (3)\nf = open (sys.argv[1])\nstate = S_CODE\ncomments = ''\ni = iter (lambda: f.read (1), '')\nwhile True:\n try:\n c = i.next ()\n except StopIteration:\n break\n if state == S_CODE:\n if c == '/':\n c = i.next ()\n if c == '*':\n state = S_MULTLINE\n elif c == '/':\n state = S_INLINE\n elif state == S_INLINE:\n comments += c\n if c == '\\n':\n state == S_CODE\n elif state == S_MULTLINE:\n if c == '*':\n c = i.next ()\n if c == '/':\n comments += '\\n'\n state = S_CODE\n else:\n comments += '*%s' % c\n else:\n comments += c\nprint comments\n\n", "Perhaps shlex module would do?\nIf not, there are some more powerful alternatives:\nhttp://wiki.python.org/moin/LanguageParsing\n" ]
[ 4, 3, 1 ]
[]
[]
[ "lexer", "parsing", "python" ]
stackoverflow_0000697945_lexer_parsing_python.txt
Q: Python tkinter label won't change at beginning of function I'm using tkinter with Python to create a user interface for a program that converts Excel files to CSV. I created a label to act as a status bar, and set statusBarText as a StringVar() as the textvariable. inputFileEntry and outputFileEntry are textvariables that contain the input and output file paths. def convertButtonClick(): statusBarText.set('Converting...') if inputFileEntry.get() == '' or outputFileEntry.get() == '': statusBarText.set('Invalid Parameters.') return retcode = subprocess.('Program.exe' ,shell=true) if retcode == 0: statusBarText.set('Conversion Successful!') else: statusBarText.set('Conversion Failed!') This function gets called when you click the convert button, and everything is working fine EXCEPT that the status bar never changes to say 'Converting...'. The status bar text will get changed to invalid parameters if either the input or output are empty, and it will change to success or failure depending on the return code. The problem is it never changes to 'Converting...' I've copied and pasted that exact line into the if statements and it works fine, but for some reason it just never changes before the subprocess runs when its at the top of the function. Any help would be greatly appreciated. A: Since you're doing all of this in a single method call, the GUI never gets a chance to update before you start your sub process. Check out update_idletasks() call... from http://infohost.nmt.edu/tcc/help/pubs/tkinter/universal.html w.update_idletasks() Some tasks in updating the display, such as resizing and redrawing widgets, are called idle tasks because they are usually deferred until the application has finished handling events and has gone back to the main loop to wait for new events. If you want to force the display to be updated before the application next idles, call the w.update_idletasks() method on any widget. A: How are you creating your Label? I have this little test setup: from Tkinter import * class LabelTest: def __init__(self, master): self.test = StringVar() self.button = Button(master, text="Change Label", command=self.change) self.button.grid(row=0, column=0, sticky=W) self.test.set("spam") self.testlabel = Label(master, textvariable = self.test).grid(row = 0,column = 1) def change(self): self.test.set("eggs") root = Tk() root.title("Label tester") calc = LabelTest(root) root.mainloop() And it works. Did you make sure to use "textvariable = StatusBarText" instead of "text=StatusBarText.get()"?
Python tkinter label won't change at beginning of function
I'm using tkinter with Python to create a user interface for a program that converts Excel files to CSV. I created a label to act as a status bar, and set statusBarText as a StringVar() as the textvariable. inputFileEntry and outputFileEntry are textvariables that contain the input and output file paths. def convertButtonClick(): statusBarText.set('Converting...') if inputFileEntry.get() == '' or outputFileEntry.get() == '': statusBarText.set('Invalid Parameters.') return retcode = subprocess.('Program.exe' ,shell=true) if retcode == 0: statusBarText.set('Conversion Successful!') else: statusBarText.set('Conversion Failed!') This function gets called when you click the convert button, and everything is working fine EXCEPT that the status bar never changes to say 'Converting...'. The status bar text will get changed to invalid parameters if either the input or output are empty, and it will change to success or failure depending on the return code. The problem is it never changes to 'Converting...' I've copied and pasted that exact line into the if statements and it works fine, but for some reason it just never changes before the subprocess runs when its at the top of the function. Any help would be greatly appreciated.
[ "Since you're doing all of this in a single method call, the GUI never gets a chance to update before you start your sub process. Check out update_idletasks() call...\nfrom http://infohost.nmt.edu/tcc/help/pubs/tkinter/universal.html\nw.update_idletasks()\nSome tasks in updating the display, such as resizing and redrawing widgets, are called idle tasks because they are usually deferred until the application has finished handling events and has gone back to the main loop to wait for new events.\n If you want to force the display to be updated before the application next idles, call the w.update_idletasks() method on any widget.\n", "How are you creating your Label?\nI have this little test setup:\nfrom Tkinter import *\nclass LabelTest:\n\n def __init__(self, master):\n self.test = StringVar()\n\n self.button = Button(master, text=\"Change Label\", command=self.change)\n self.button.grid(row=0, column=0, sticky=W)\n\n self.test.set(\"spam\")\n self.testlabel = Label(master, textvariable = self.test).grid(row = 0,column = 1)\n def change(self):\n\n self.test.set(\"eggs\")\n\n\n\nroot = Tk()\nroot.title(\"Label tester\")\ncalc = LabelTest(root)\n\nroot.mainloop()\n\nAnd it works.\nDid you make sure to use \"textvariable = StatusBarText\" instead of \"text=StatusBarText.get()\"?\n" ]
[ 11, 3 ]
[]
[]
[ "function", "label", "python", "statusbar", "tkinter" ]
stackoverflow_0000698707_function_label_python_statusbar_tkinter.txt
Q: Programmatically submitting a form in Python? Just started playing with Google App Engine & Python (as an excuse ;)). How do I correctly submit a form like this <form action="https://www.moneybookers.com/app/payment.pl" method="post" target="_blank"> <input type="hidden" name="pay_to_email" value="ENTER_YOUR_USER_EMAIL@MERCHANT.COM"> <input type="hidden" name="status_url" <!-- etc. --> <input type="submit" value="Pay!"> </form> w/o exposing the data to user? A: It sounds like you're looking for urllib. Here's an example of POSTing from the library's docs: >>> import urllib >>> params = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0}) >>> f = urllib.urlopen("http://www.musi-cal.com/cgi-bin/query", params) >>> print f.read() A: By hiding the sensitive bits of the form and submitting it via JavaScript. Make sure you have a good way of referring to the form element... <form ... id="moneybookersForm">...</form> ... and on page load, execute something like document.getElementById("moneybookersForm").submit(); At least I don't know of other ways. For JavaScript-disabled people, the Pay! button should be kept visible.
Programmatically submitting a form in Python?
Just started playing with Google App Engine & Python (as an excuse ;)). How do I correctly submit a form like this <form action="https://www.moneybookers.com/app/payment.pl" method="post" target="_blank"> <input type="hidden" name="pay_to_email" value="ENTER_YOUR_USER_EMAIL@MERCHANT.COM"> <input type="hidden" name="status_url" <!-- etc. --> <input type="submit" value="Pay!"> </form> w/o exposing the data to user?
[ "It sounds like you're looking for urllib.\nHere's an example of POSTing from the library's docs:\n>>> import urllib\n>>> params = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})\n>>> f = urllib.urlopen(\"http://www.musi-cal.com/cgi-bin/query\", params)\n>>> print f.read()\n\n", "By hiding the sensitive bits of the form and submitting it via JavaScript.\nMake sure you have a good way of referring to the form element...\n<form ... id=\"moneybookersForm\">...</form>\n\n... and on page load, execute something like\ndocument.getElementById(\"moneybookersForm\").submit();\n\nAt least I don't know of other ways. For JavaScript-disabled people, the Pay! button should be kept visible.\n" ]
[ 6, 0 ]
[]
[]
[ "forms", "google_app_engine", "post", "python" ]
stackoverflow_0000699238_forms_google_app_engine_post_python.txt
Q: Is it possible to create a class that represents another type in Python, when directly referenced? So if I have a class like: CustomVal I want to be able to represent a literal value, so like setting it in the constructor: val = CustomVal ( 5 ) val.SomeDefaultIntMethod Basically I want the CustomVal to represent whatever is specified in the constructor. I am not talking about custom methods that know how to deal with CustomVal, but rather making it another value that I need. Is this possible? Btw 5 is just an example, in reality it's a custom COM type that I want to instance easily. So by referencing CustomVal, I will have access to int related functionality (for 5), or the functionality of the object that I want to represent (for COM). So if the COM object is RasterizedImage, then I will have access to its methods directly: CustomVal.Raster () ... EDIT: This is what I mean: I don't want to access as an attribute, but the object itself: CustomVal instead of: CustomVal.SomeAttribute The reason I want this is because, the COM object is too involved to initialize and by doing it this way, it will look like the original internal implementation that app offers. A: The usual way to wrap an object in Python is to override __getattr__ in your class: class CustomVal(object): def __init__(self, value): self.value = value def __getattr__(self, attr): return getattr(self.value, attr) So then you can do >>> obj = CustomVal(wrapped_obj) >>> obj.SomeAttributeOfWrappedObj You can also override __setattr__ and __delattr__ to enable setting and deleting attributes, respectively (see the Python library documentation). A: You just might be overthinking this... You can put anything you want into your val, then call whatever method of the object you want: >>> val = ThingaMoBob(123, {p:3.14}, flag=False) >>> val.SomeCrazyMathod() Am I missing something?
Is it possible to create a class that represents another type in Python, when directly referenced?
So if I have a class like: CustomVal I want to be able to represent a literal value, so like setting it in the constructor: val = CustomVal ( 5 ) val.SomeDefaultIntMethod Basically I want the CustomVal to represent whatever is specified in the constructor. I am not talking about custom methods that know how to deal with CustomVal, but rather making it another value that I need. Is this possible? Btw 5 is just an example, in reality it's a custom COM type that I want to instance easily. So by referencing CustomVal, I will have access to int related functionality (for 5), or the functionality of the object that I want to represent (for COM). So if the COM object is RasterizedImage, then I will have access to its methods directly: CustomVal.Raster () ... EDIT: This is what I mean: I don't want to access as an attribute, but the object itself: CustomVal instead of: CustomVal.SomeAttribute The reason I want this is because, the COM object is too involved to initialize and by doing it this way, it will look like the original internal implementation that app offers.
[ "The usual way to wrap an object in Python is to override __getattr__ in your class:\nclass CustomVal(object):\n def __init__(self, value):\n self.value = value\n\n def __getattr__(self, attr):\n return getattr(self.value, attr)\n\nSo then you can do\n>>> obj = CustomVal(wrapped_obj)\n>>> obj.SomeAttributeOfWrappedObj\n\nYou can also override __setattr__ and __delattr__ to enable setting and deleting attributes, respectively (see the Python library documentation).\n", "You just might be overthinking this... You can put anything you want into your val, then call whatever method of the object you want:\n>>> val = ThingaMoBob(123, {p:3.14}, flag=False)\n>>> val.SomeCrazyMathod()\n\nAm I missing something?\n" ]
[ 7, 2 ]
[]
[]
[ "class", "object", "python" ]
stackoverflow_0000699510_class_object_python.txt
Q: python decorators and methods New here. Also I'm (very) new to python and trying to understand the following behavior. Can someone explain to me why the two methods in this example have different output? def map_children(method): def wrapper(self,*args,**kwargs): res = method(self,*args,**kwargs) for child in self._children: method(child,*args,**kwargs) return res return wrapper class Node(object): def __init__(self,name,parent=None): self._namestring = name if parent: self._parent = parent self._children = [] @map_children def decorated(self): if hasattr(self,'_parent'): print '%s (child of %s)'%(self._namestring,self._parent._namestring) else: print '%s'% self._namestring def undecorated(self): if hasattr(self,'_parent'): print '%s (child of %s)'%(self._namestring,self._parent._namestring) else: print '%s'% self._namestring for child in self._children: child.undecorated() def runme(): parent = Node('parent') child1 = Node('child1',parent) child2 = Node('child2',parent) grandchild = Node('grandchild',child1) child1._children.append(grandchild) parent._children.append(child1) parent._children.append(child2) print '**********result from decorator**********' parent.decorated() print '**********result by hand**********' parent.undecorated() Here is the output on my system: In[]:testcase.runme() **********result from decorator********** parent child1 (child of parent) child2 (child of parent) **********result by hand********** parent child1 (child of parent) grandchild (child of child1) child2 (child of parent) So why does the decorated call never descend to the grandchild node? I'm obviously missing something about the syntax... A: In the decorator, you are looping over the node's children and calling the original, non-recursive method on them method(child, *args, **kwargs) so you'll only go one level deep. Try replacing that line with map_children(method)(child, *args, **kwargs) and you'll get the same output as the manual recursive version.
python decorators and methods
New here. Also I'm (very) new to python and trying to understand the following behavior. Can someone explain to me why the two methods in this example have different output? def map_children(method): def wrapper(self,*args,**kwargs): res = method(self,*args,**kwargs) for child in self._children: method(child,*args,**kwargs) return res return wrapper class Node(object): def __init__(self,name,parent=None): self._namestring = name if parent: self._parent = parent self._children = [] @map_children def decorated(self): if hasattr(self,'_parent'): print '%s (child of %s)'%(self._namestring,self._parent._namestring) else: print '%s'% self._namestring def undecorated(self): if hasattr(self,'_parent'): print '%s (child of %s)'%(self._namestring,self._parent._namestring) else: print '%s'% self._namestring for child in self._children: child.undecorated() def runme(): parent = Node('parent') child1 = Node('child1',parent) child2 = Node('child2',parent) grandchild = Node('grandchild',child1) child1._children.append(grandchild) parent._children.append(child1) parent._children.append(child2) print '**********result from decorator**********' parent.decorated() print '**********result by hand**********' parent.undecorated() Here is the output on my system: In[]:testcase.runme() **********result from decorator********** parent child1 (child of parent) child2 (child of parent) **********result by hand********** parent child1 (child of parent) grandchild (child of child1) child2 (child of parent) So why does the decorated call never descend to the grandchild node? I'm obviously missing something about the syntax...
[ "In the decorator, you are looping over the node's children and calling the original, non-recursive method on them\nmethod(child, *args, **kwargs)\n\nso you'll only go one level deep. Try replacing that line with\nmap_children(method)(child, *args, **kwargs)\n\nand you'll get the same output as the manual recursive version. \n" ]
[ 7 ]
[]
[]
[ "decorator", "metaprogramming", "python" ]
stackoverflow_0000699526_decorator_metaprogramming_python.txt
Q: Python: Testing for unicode, and converting to time() Sometimes self.start is unicode: eg. >>>self.start u'07:30:00' Which makes datetime.combine complain start = datetime.combine(self.job_record.date, self.start) How does one: Test for unicode? Convert from u'07:30:00' to datetime.time? A: Checking for unicode: >>> import types >>> type(u'07:30:00') is types.UnicodeType True >>> type('regular string') is types.UnicodeType False Converting strings to time: >>> import time >>> time.strptime(u'07:30:00', '%H:%M:%S') (1900, 1, 1, 7, 30, 0, 0, 1, -1) A: datetime.combine is complaining because it expects the second argument to be a datetime.time instance, not a string (or unicode string). There are a few ways to convert your string to a datetime.time instance. One way would be to use datetime.strptime: t = datetime.strptime(self.start, "%H:%M:%S").time() start = datetime.combine(self.job_record.date, t) A: Assuming that there won't be extended charset characters in '07:30:00', then use str(self.start). If there is a possibility that the numbers in the time are charset-specific, use encode(), with an appropriate error argument specifier to convert to string. This may be a cases where it is more pythonic to try str() first and use except to handle cases that can't be converted (ask forgiveness rather than permission). If most of the values you are trying to convert fail, on the other hand, convert them first before applying the function. As an unwanted aside: the combine function expects a datetime.date object and a datetime.time object. If you really want to avoid unpredictable behaviour, then meet the requirements of the API and pass date and time objects, rather than trying to short-circuit the contract specified by the documentation: convert the arguments before you call combine, rather than asking combine to guess for you.
Python: Testing for unicode, and converting to time()
Sometimes self.start is unicode: eg. >>>self.start u'07:30:00' Which makes datetime.combine complain start = datetime.combine(self.job_record.date, self.start) How does one: Test for unicode? Convert from u'07:30:00' to datetime.time?
[ "Checking for unicode:\n>>> import types\n>>> type(u'07:30:00') is types.UnicodeType\nTrue\n>>> type('regular string') is types.UnicodeType\nFalse\n\nConverting strings to time:\n>>> import time\n>>> time.strptime(u'07:30:00', '%H:%M:%S')\n(1900, 1, 1, 7, 30, 0, 0, 1, -1)\n\n", "datetime.combine is complaining because it expects the second argument to be a datetime.time instance, not a string (or unicode string).\nThere are a few ways to convert your string to a datetime.time instance. One way would be to use datetime.strptime:\nt = datetime.strptime(self.start, \"%H:%M:%S\").time()\nstart = datetime.combine(self.job_record.date, t)\n\n", "Assuming that there won't be extended charset characters in '07:30:00', then use str(self.start).\nIf there is a possibility that the numbers in the time are charset-specific, use encode(), with an appropriate error argument specifier to convert to string.\nThis may be a cases where it is more pythonic to try str() first and use except to handle cases that can't be converted (ask forgiveness rather than permission). If most of the values you are trying to convert fail, on the other hand, convert them first before applying the function.\nAs an unwanted aside: the combine function expects a datetime.date object and a datetime.time object. If you really want to avoid unpredictable behaviour, then meet the requirements of the API and pass date and time objects, rather than trying to short-circuit the contract specified by the documentation: convert the arguments before you call combine, rather than asking combine to guess for you.\n" ]
[ 4, 2, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0000699570_django_python.txt
Q: navigating through different drive letters in python os.system I am having a problem with a bit of code on one windows machine but not all windows machines. i have the following code: path = "F:/dir/" os.system(path[0:2] + " && cd " + path + " && git init") On all but one of my windows systems it runs fine but on a windows 2003 server it gives a "directory not found" error but if i run the same command flat from the command prompt than it works. I'm sorry if my question comes off as vague but I'm totally stumped A: os.path contains many usefull path manipulation functions. Probably just handling the path cleanly will resolve your problem. >>> import os >>> >>> >>> path = "F:/dir/" >>> >>> clean_path = os.path.normpath(path) >>> clean_path 'F:\\dir' >>> drive, directory = os.path.splitdrive(clean_path) >>> drive 'F:' >>> directory '\\dir' Also, you might want to look into using the subprocess module, it gives you more control over processes. Replacing Older Functions with the subprocess Module
navigating through different drive letters in python os.system
I am having a problem with a bit of code on one windows machine but not all windows machines. i have the following code: path = "F:/dir/" os.system(path[0:2] + " && cd " + path + " && git init") On all but one of my windows systems it runs fine but on a windows 2003 server it gives a "directory not found" error but if i run the same command flat from the command prompt than it works. I'm sorry if my question comes off as vague but I'm totally stumped
[ "os.path contains many usefull path manipulation functions. Probably just handling the path cleanly will resolve your problem.\n>>> import os\n>>>\n>>>\n>>> path = \"F:/dir/\"\n>>>\n>>> clean_path = os.path.normpath(path)\n>>> clean_path\n'F:\\\\dir'\n>>> drive, directory = os.path.splitdrive(clean_path)\n>>> drive\n'F:'\n>>> directory\n'\\\\dir'\n\nAlso, you might want to look into using the subprocess module, it gives you more control over processes.\nReplacing Older Functions with the subprocess Module\n" ]
[ 3 ]
[]
[]
[ "cmd", "python", "windows" ]
stackoverflow_0000699550_cmd_python_windows.txt
Q: Browser interface to command line python program I have a command line tool that I have written (in Python) that interfaces to a SQLite database (one DB per user). This program presents a lot of data to the user which can be cumbersome in a terminal. One option is to provide a wxPython interface, but another thought is to leverage Firefox or Webkit to provide an interface. Anyone ever go about something like this? Or else any very easy ways to add graphical interfaces to manipulate large amounts of data in python programs? Thanks! A: The django automatic admin interface (you can use legacy DBs, and sqlite), or databrowse application are worth considering as easy, (almost) no-coding web interfaces. A: You might also look at Qt's model/view framework. It's trivial to take a SQL result set and map it into a table view etc... http://doc.trolltech.com/4.5/sql-tablemodel.html This works quite well from PyQt4 also.
Browser interface to command line python program
I have a command line tool that I have written (in Python) that interfaces to a SQLite database (one DB per user). This program presents a lot of data to the user which can be cumbersome in a terminal. One option is to provide a wxPython interface, but another thought is to leverage Firefox or Webkit to provide an interface. Anyone ever go about something like this? Or else any very easy ways to add graphical interfaces to manipulate large amounts of data in python programs? Thanks!
[ "The django automatic admin interface (you can use legacy DBs, and sqlite), or databrowse application are worth considering as easy, (almost) no-coding web interfaces.\n", "You might also look at Qt's model/view framework. It's trivial to take a SQL result set and map it into a table view etc...\nhttp://doc.trolltech.com/4.5/sql-tablemodel.html\nThis works quite well from PyQt4 also.\n" ]
[ 4, 1 ]
[]
[]
[ "firefox", "python", "sqlite", "webkit" ]
stackoverflow_0000699649_firefox_python_sqlite_webkit.txt
Q: What's the best way to tell if a Python program has anything to read from stdin? I want a program to do one thing if executed like this: cat something | my_program.py and do another thing if run like this my_program.py But if I read from stdin, then it will wait for user input, so I want to see if there is anything to read before trying to read from stdin. A: If you want to detect if someone is piping data into your program, or running it interactively you can use isatty to see if stdin is a terminal: $ python -c 'import sys; print sys.stdin.isatty()' True $ echo | python -c 'import sys; print sys.stdin.isatty()' False A: You want the select module (man select on unix) It will allow you to test if there is anything readable on stdin. Note that select won't work on Window with file objects. But from your pipe-laden question I'm assuming you're on a unix based os :) http://docs.python.org/library/select.html root::2832 jobs:0 [~] # cat stdin_test.py #!/usr/bin/env python import sys import select r, w, x = select.select([sys.stdin], [], [], 0) if r: print "READABLES:", r else: print "no pipe" root::2832 jobs:0 [~] # ./stdin_test.py no pipe root::2832 jobs:0 [~] # echo "foo" | ./stdin_test.py READABLES: [<open file '<stdin>', mode 'r' at 0xb7d79020>] A: Bad news. From a Unix command-line perspective those two invocations of your program are identical. Unix can't easily distinguish them. What you're asking for isn't really sensible, and you need to think of another way of using your program. In the case where it's not in a pipeline, what's it supposed to read if it doesn't read stdin? Is it supposed to launch a GUI? If so, you might want to have a "-i" (--interactive) option to indicate you want a GUI, not reading of stdin. You can, sometimes, distinguish pipes from the console because the console device is "/dev/tty", but this is not portable.
What's the best way to tell if a Python program has anything to read from stdin?
I want a program to do one thing if executed like this: cat something | my_program.py and do another thing if run like this my_program.py But if I read from stdin, then it will wait for user input, so I want to see if there is anything to read before trying to read from stdin.
[ "If you want to detect if someone is piping data into your program, or running it interactively you can use isatty to see if stdin is a terminal:\n$ python -c 'import sys; print sys.stdin.isatty()'\nTrue\n$ echo | python -c 'import sys; print sys.stdin.isatty()'\nFalse\n\n", "You want the select module (man select on unix) It will allow you to test if there is anything readable on stdin. Note that select won't work on Window with file objects. But from your pipe-laden question I'm assuming you're on a unix based os :)\nhttp://docs.python.org/library/select.html\nroot::2832 jobs:0 [~] # cat stdin_test.py\n#!/usr/bin/env python\nimport sys\nimport select\n\nr, w, x = select.select([sys.stdin], [], [], 0)\nif r:\n print \"READABLES:\", r\nelse:\n print \"no pipe\"\n\nroot::2832 jobs:0 [~] # ./stdin_test.py\nno pipe\n\nroot::2832 jobs:0 [~] # echo \"foo\" | ./stdin_test.py\nREADABLES: [<open file '<stdin>', mode 'r' at 0xb7d79020>]\n\n", "Bad news. From a Unix command-line perspective those two invocations of your program are identical.\nUnix can't easily distinguish them. What you're asking for isn't really sensible, and you need to think of another way of using your program.\nIn the case where it's not in a pipeline, what's it supposed to read if it doesn't read stdin?\nIs it supposed to launch a GUI? If so, you might want to have a \"-i\" (--interactive) option to indicate you want a GUI, not reading of stdin.\nYou can, sometimes, distinguish pipes from the console because the console device is \"/dev/tty\", but this is not portable.\n" ]
[ 68, 10, 3 ]
[ "I do not know the Python commands off the top of my head, but you should be able to do something with poll or select to look for data ready to read on standard input.\nThat might be Unix OS specific and different on Windows Python.\n" ]
[ -2 ]
[ "python" ]
stackoverflow_0000699390_python.txt
Q: Format a number as a string How do you format a number as a string so that it takes a number of spaces in front of it? I want the shorter number 5 to have enough spaces in front of it so that the spaces plus the 5 have the same length as 52500. The procedure below works, but is there a built in way to do this? a = str(52500) b = str(5) lengthDiff = len(a) - len(b) formatted = '%s/%s' % (' '*lengthDiff + b, a) # formatted looks like:' 5/52500' A: Format operator: >>> "%10d" % 5 ' 5' >>> Using * spec, the field length can be an argument: >>> "%*d" % (10,5) ' 5' >>> A: You can just use the %*d formatter to give a width. int(math.ceil(math.log(x, 10))) will give you the number of digits. The * modifier consumes a number, that number is an integer that means how many spaces to space by. So by doing '%*d' % (width, num)` you can specify the width AND render the number without any further python string manipulation. Here is a solution using math.log to ascertain the length of the 'outof' number. import math num = 5 outof = 52500 formatted = '%*d/%d' % (int(math.ceil(math.log(outof, 10))), num, outof) Another solution involves casting the outof number as a string and using len(), you can do that if you prefer: num = 5 outof = 52500 formatted = '%*d/%d' % (len(str(outof)), num, outof) A: '%*s/%s' % (len(str(a)), b, a) A: See String Formatting Operations: s = '%5i' % (5,) You still have to dynamically build your formatting string by including the maximum length: fmt = '%%%ii' % (len('52500'),) s = fmt % (5,) A: Not sure exactly what you're after, but this looks close: >>> n = 50 >>> print "%5d" % n 50 If you want to be more dynamic, use something like rjust: >>> big_number = 52500 >>> n = 50 >>> print ("%d" % n).rjust(len(str(52500))) 50 Or even: >>> n = 50 >>> width = str(len(str(52500))) >>> ('%' + width + 'd') % n ' 50'
Format a number as a string
How do you format a number as a string so that it takes a number of spaces in front of it? I want the shorter number 5 to have enough spaces in front of it so that the spaces plus the 5 have the same length as 52500. The procedure below works, but is there a built in way to do this? a = str(52500) b = str(5) lengthDiff = len(a) - len(b) formatted = '%s/%s' % (' '*lengthDiff + b, a) # formatted looks like:' 5/52500'
[ "Format operator:\n>>> \"%10d\" % 5\n' 5'\n>>> \n\nUsing * spec, the field length can be an argument:\n>>> \"%*d\" % (10,5)\n' 5'\n>>> \n\n", "You can just use the %*d formatter to give a width. int(math.ceil(math.log(x, 10))) will give you the number of digits. The * modifier consumes a number, that number is an integer that means how many spaces to space by. So by doing '%*d' % (width, num)` you can specify the width AND render the number without any further python string manipulation. \nHere is a solution using math.log to ascertain the length of the 'outof' number.\nimport math\nnum = 5\noutof = 52500\nformatted = '%*d/%d' % (int(math.ceil(math.log(outof, 10))), num, outof)\n\nAnother solution involves casting the outof number as a string and using len(), you can do that if you prefer:\nnum = 5\noutof = 52500\nformatted = '%*d/%d' % (len(str(outof)), num, outof)\n\n", "'%*s/%s' % (len(str(a)), b, a)\n", "See String Formatting Operations:\ns = '%5i' % (5,)\n\nYou still have to dynamically build your formatting string by including the maximum length:\nfmt = '%%%ii' % (len('52500'),)\ns = fmt % (5,)\n\n", "Not sure exactly what you're after, but this looks close:\n>>> n = 50\n>>> print \"%5d\" % n\n 50\n\nIf you want to be more dynamic, use something like rjust:\n>>> big_number = 52500\n>>> n = 50\n>>> print (\"%d\" % n).rjust(len(str(52500)))\n 50\n\nOr even:\n>>> n = 50\n>>> width = str(len(str(52500)))\n>>> ('%' + width + 'd') % n\n' 50'\n\n" ]
[ 8, 2, 2, 1, 0 ]
[]
[]
[ "format", "integer", "python", "string" ]
stackoverflow_0000700016_format_integer_python_string.txt
Q: function pointers in python I would like to do something like the following: def add(a, b): #some code def subtract(a, b): #some code operations = [add, subtract] operations[0]( 5,3) operations[1](5,3) In python, is it possible to assign something like a function pointer? A: Did you try it? What you wrote works exactly as written. Functions are first-class objects in Python. A: Python has nothing called pointers, but your code works as written. Function are first-class objects, assigned to names, and used as any other value. You can use this to implement a Strategy pattern, for example: def the_simple_way(a, b): # blah blah def the_complicated_way(a, b): # blah blah def foo(way): if way == 'complicated': doit = the_complicated_way else: doit = the_simple_way doit(a, b) Or a lookup table: def do_add(a, b): return a+b def do_sub(a, b): return a-b handlers = { 'add': do_add, 'sub': do_sub, } print handlers[op](a, b) You can even grab a method bound to an object: o = MyObject() f = o.method f(1, 2) # same as o.method(1, 2) A: Just a quick note that most Python operators already have an equivalent function in the operator module.
function pointers in python
I would like to do something like the following: def add(a, b): #some code def subtract(a, b): #some code operations = [add, subtract] operations[0]( 5,3) operations[1](5,3) In python, is it possible to assign something like a function pointer?
[ "Did you try it? What you wrote works exactly as written. Functions are first-class objects in Python.\n", "Python has nothing called pointers, but your code works as written. Function are first-class objects, assigned to names, and used as any other value.\nYou can use this to implement a Strategy pattern, for example:\ndef the_simple_way(a, b):\n # blah blah\n\ndef the_complicated_way(a, b):\n # blah blah\n\ndef foo(way):\n if way == 'complicated':\n doit = the_complicated_way\n else:\n doit = the_simple_way\n\n doit(a, b)\n\nOr a lookup table:\ndef do_add(a, b):\n return a+b\n\ndef do_sub(a, b):\n return a-b\n\nhandlers = {\n 'add': do_add,\n 'sub': do_sub,\n}\n\nprint handlers[op](a, b)\n\nYou can even grab a method bound to an object:\no = MyObject()\nf = o.method\nf(1, 2) # same as o.method(1, 2)\n\n", "Just a quick note that most Python operators already have an equivalent function in the operator module.\n" ]
[ 23, 8, 1 ]
[]
[]
[ "function_pointers", "python" ]
stackoverflow_0000307494_function_pointers_python.txt
Q: communication with long running tasks in python I have a python GUI app that uses a long running function from a .so/.dll it calls through ctypes. I'm looking for a way to communicate with the function while it's running in a separate thread or process, so that I can request it to terminate early (which requires some work on the C side before returning a partial result). I suppose this will need some kind of signal receiving or reading from pipes, but I want to keep it as simple as possible. What would you consider the best approach to solve this kind of problem? I am able to change the code on both the python and C sides. A: There's two parts you'll need to answer here: one if how to communicate between the two processes (your GUI and the process executing the function), and the other is how to change your function so it responds to asynchronous requests ("oh, I've been told to just return whatever I've got"). Working out the answer to the second question will probably dictate the answer to the first. You could do it by signals (in which case you get a signal handler that gets control of the process, can look for more detailed instructions elsewhere, and change your internal data structures before returning control to your function), or you could have your function monitor a control interface for commands (every millisecond, check to see if there's a command waiting, and if there is, see what it is). In the first case, you'd want ANSI C signal handling (signal(), sighandler_t), in the second you'd probably want a pipe or similar (pipe() and select()). A: You mention that you can change both the C and Python sides. To avoid having to write any sockets or signal code in C, it might be easiest to break up the large C function into 3 smaller separate functions that perform setup, a small parcel of work, and cleanup. The work parcel should be between about 1 ms and 1 second run time to strike a balance between responsiveness and low overhead. It can be tough to break up calculations into even chunks like this in the face of changing data sizes, but you would have the same challenge in a single big function that also did I/O. Write a worker process in Python that calls those 3 functions through ctypes. Have the worker process check a Queue object for a message from the GUI to stop the calculation early. Make sure to use the non-blocking Queue.get_nowait call instead of Queue.get. If the worker process finds a message to quit early, call the C clean up code and return the partial result. A: If you're on *nix register a signal handler for SIGUSR1 or SIGINT in your C program then from Python use os.kill to send the signal. A: You said it: signals and pipes. It doesn't have to be too complex, but it will be a heck of a lot easier if you use an existing structure than if you try to roll your own.
communication with long running tasks in python
I have a python GUI app that uses a long running function from a .so/.dll it calls through ctypes. I'm looking for a way to communicate with the function while it's running in a separate thread or process, so that I can request it to terminate early (which requires some work on the C side before returning a partial result). I suppose this will need some kind of signal receiving or reading from pipes, but I want to keep it as simple as possible. What would you consider the best approach to solve this kind of problem? I am able to change the code on both the python and C sides.
[ "There's two parts you'll need to answer here: one if how to communicate between the two processes (your GUI and the process executing the function), and the other is how to change your function so it responds to asynchronous requests (\"oh, I've been told to just return whatever I've got\").\nWorking out the answer to the second question will probably dictate the answer to the first. You could do it by signals (in which case you get a signal handler that gets control of the process, can look for more detailed instructions elsewhere, and change your internal data structures before returning control to your function), or you could have your function monitor a control interface for commands (every millisecond, check to see if there's a command waiting, and if there is, see what it is).\nIn the first case, you'd want ANSI C signal handling (signal(), sighandler_t), in the second you'd probably want a pipe or similar (pipe() and select()).\n", "You mention that you can change both the C and Python sides. To avoid having to write any sockets or signal code in C, it might be easiest to break up the large C function into 3 smaller separate functions that perform setup, a small parcel of work, and cleanup. The work parcel should be between about 1 ms and 1 second run time to strike a balance between responsiveness and low overhead. It can be tough to break up calculations into even chunks like this in the face of changing data sizes, but you would have the same challenge in a single big function that also did I/O.\nWrite a worker process in Python that calls those 3 functions through ctypes. Have the worker process check a Queue object for a message from the GUI to stop the calculation early. Make sure to use the non-blocking Queue.get_nowait call instead of Queue.get. If the worker process finds a message to quit early, call the C clean up code and return the partial result. \n", "If you're on *nix register a signal handler for SIGUSR1 or SIGINT in your C program then from Python use os.kill to send the signal.\n", "You said it: signals and pipes.\nIt doesn't have to be too complex, but it will be a heck of a lot easier if you use an existing structure than if you try to roll your own.\n" ]
[ 2, 2, 0, 0 ]
[]
[]
[ "ctypes", "multithreading", "process", "python" ]
stackoverflow_0000700073_ctypes_multithreading_process_python.txt
Q: How to add a Python import path using a .pth file If I put a *.pth file in site-packages it's giving an ImportError. I'm not getting how to import by creating a *.pth file. (Refers to importing in python) A: If you put a .pth file in the site-packages directory containing a path, python searches this path for imports. So I have a sth.pth file there that simply contains: K:\Source\Python\lib In that directory there are some normal Python modules: logger.py fstools.py ... This allows to directly import these modules from other scripts: import logger log = logger.Log() ... A: /tmp/$ mkdir test; cd test /tmp/test/$ mkdir foo; mkdir bar /tmp/test/$ echo -e "foo\nbar" > foobar.pth /tmp/test/$ cd .. /tmp/$ python Python 2.6 (r26:66714, Feb 3 2009, 20:52:03) [GCC 4.3.2 [gcc-4_3-branch revision 141291]] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import site, sys >>> site.addsitedir('test') >>> sys.path[-3:] ['/tmp/test', '/tmp/test/foo', '/tmp/test/bar']
How to add a Python import path using a .pth file
If I put a *.pth file in site-packages it's giving an ImportError. I'm not getting how to import by creating a *.pth file. (Refers to importing in python)
[ "If you put a .pth file in the site-packages directory containing a path, python searches this path for imports. So I have a sth.pth file there that simply contains:\nK:\\Source\\Python\\lib\n\nIn that directory there are some normal Python modules:\nlogger.py\nfstools.py\n...\n\nThis allows to directly import these modules from other scripts:\nimport logger\n\nlog = logger.Log()\n...\n\n", "/tmp/$ mkdir test; cd test\n/tmp/test/$ mkdir foo; mkdir bar\n/tmp/test/$ echo -e \"foo\\nbar\" > foobar.pth\n/tmp/test/$ cd ..\n/tmp/$ python\nPython 2.6 (r26:66714, Feb 3 2009, 20:52:03)\n[GCC 4.3.2 [gcc-4_3-branch revision 141291]] on linux2\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> import site, sys\n>>> site.addsitedir('test')\n>>> sys.path[-3:]\n['/tmp/test', '/tmp/test/foo', '/tmp/test/bar']\n\n" ]
[ 41, 27 ]
[]
[]
[ "python", "python_import" ]
stackoverflow_0000700375_python_python_import.txt
Q: Why isn't keyword DateField.input_formats recognized in django 1.0.2 and Python 2.5? With django 1.0.2 and Python 2.5, when I use the keyword DateField.input_formats, I get the error that __init__() got an unexpected keyword argument 'input_formats'. When I look in the __init__ file, I don't see input_formats as one of the acceptable keyword arguments. I thought that input_formats had been around long enough that it should be in there. Is the input_formats keyword not supported in this configuration? If not, how can I acquire an updated __init__ that does support it? Thank you. As suggested in the comment, I have added code below. I suspect the problem is that I am confusing the DateField form and DateField model, but I would be pleased if someone could confirm that. from django.db import models class Payment(models.Model): date_paid = models.DateField(blank=True, db_index=True, input_formats=['%m/%d/%y']) A: Having looked at the docs, like you suspected, models.DateField doesn't have an input_formats, but forms.DateField does (as does forms.DateTimeField)
Why isn't keyword DateField.input_formats recognized in django 1.0.2 and Python 2.5?
With django 1.0.2 and Python 2.5, when I use the keyword DateField.input_formats, I get the error that __init__() got an unexpected keyword argument 'input_formats'. When I look in the __init__ file, I don't see input_formats as one of the acceptable keyword arguments. I thought that input_formats had been around long enough that it should be in there. Is the input_formats keyword not supported in this configuration? If not, how can I acquire an updated __init__ that does support it? Thank you. As suggested in the comment, I have added code below. I suspect the problem is that I am confusing the DateField form and DateField model, but I would be pleased if someone could confirm that. from django.db import models class Payment(models.Model): date_paid = models.DateField(blank=True, db_index=True, input_formats=['%m/%d/%y'])
[ "Having looked at the docs, like you suspected, models.DateField doesn't have an input_formats, but forms.DateField does (as does forms.DateTimeField)\n" ]
[ 17 ]
[]
[]
[ "django", "python" ]
stackoverflow_0000690171_django_python.txt
Q: How to design multithreaded GUI-network application? I'm working on a small utility application in Python. The networking is gonna send and receive messages. The GUI is gonna display the messages from the GUI and provide user input for entering messages to be sent. There's also a storage part as I call it, which is gonna get all the network messages and save them in some kind of database to provide some kind of search later. What my question is, what would be the best way to design this? For sure all them have to happen in separate threads, but what I'm wondering is how to pass information between them the best way? What kind of signal passing / thread locking available in Python should I use to avoid possible problems? A: One, probably the best, solution for this problem is to use Twisted. It supports all the GUI toolkits. A: I think that you could use a Queue for passing messages between the GUI and the network threads. As for GUI and threads in general, you might find the PyGTK and Threading article interesting.
How to design multithreaded GUI-network application?
I'm working on a small utility application in Python. The networking is gonna send and receive messages. The GUI is gonna display the messages from the GUI and provide user input for entering messages to be sent. There's also a storage part as I call it, which is gonna get all the network messages and save them in some kind of database to provide some kind of search later. What my question is, what would be the best way to design this? For sure all them have to happen in separate threads, but what I'm wondering is how to pass information between them the best way? What kind of signal passing / thread locking available in Python should I use to avoid possible problems?
[ "One, probably the best, solution for this problem is to use Twisted. It supports all the GUI toolkits.\n", "I think that you could use a Queue for passing messages between the GUI and the network threads.\nAs for GUI and threads in general, you might find the PyGTK and Threading article interesting.\n" ]
[ 2, 1 ]
[]
[]
[ "multithreading", "python", "user_interface" ]
stackoverflow_0000700905_multithreading_python_user_interface.txt
Q: Is there a standard 3rd party Python caching class? I'm working on a client class which needs to load data from a networked database. It's been suggested that adding a standard caching service to the client could improve it's performance. I'd dearly like not to have to build my own caching class - it's well known that these provide common points of failure. It would be far better to use a class that somebody else has developed rather than spend a huge amount of my own time debugging a home-made caching system. Java developers have this: http://ehcache.sourceforge.net/ It's a general purpose high-performance caching class which can support all kinds of storage. It's got options for time-based expiry and other methods for garbage-collecting. It looks really good. Unfortunately I cannot find anything this good for Python. So, can somebody suggest a cache-class that's ready for me to use. My wish-list is: Ability to limit the number of objects in the cache. Ability to limit the maximum age of objects in the cache. LRU object expirey Ability to select multiple forms of storage ( e.g. memory, disk ) Well debugged, well maintained, in use by at least one well-known application. Good performance. So, any suggestions? UPDATE: I'm looking for LOCAL caching of objects. The server which I connect to is already heavily cached. Memcached is not appropriate because it requires an additional network traffic between the Windows client and the server. A: I'd recommend using memcached and using cmemcache to access it. You can't necessarily limit the number of objects in the cache, but you can set an expiration time and limit the amount of memory it uses. And memcached is used by a lot of big names. In fact, I'd call it kind of the industry standard. UPDATE: I'm looking for LOCAL caching of objects. You can run memcached locally and access it via localhost. I've done this a few times. Other than that, the only solution that I can think of is django's caching system. It offers several backends and some other configuration options. But that may be a little bit heavyweight if you're not using django. UPDATE 2: I suppose as a last resort, you can also use jython and access the java caching system. This may be a little difficult to do if you've already got clients using CPython though. UPDATE 3: It's probably a bit late to be of use to you, but a previous employer of mine used ZODB for this kind of thing. It's an actual database, but its read performance is fast enough to make it useful for caching.
Is there a standard 3rd party Python caching class?
I'm working on a client class which needs to load data from a networked database. It's been suggested that adding a standard caching service to the client could improve it's performance. I'd dearly like not to have to build my own caching class - it's well known that these provide common points of failure. It would be far better to use a class that somebody else has developed rather than spend a huge amount of my own time debugging a home-made caching system. Java developers have this: http://ehcache.sourceforge.net/ It's a general purpose high-performance caching class which can support all kinds of storage. It's got options for time-based expiry and other methods for garbage-collecting. It looks really good. Unfortunately I cannot find anything this good for Python. So, can somebody suggest a cache-class that's ready for me to use. My wish-list is: Ability to limit the number of objects in the cache. Ability to limit the maximum age of objects in the cache. LRU object expirey Ability to select multiple forms of storage ( e.g. memory, disk ) Well debugged, well maintained, in use by at least one well-known application. Good performance. So, any suggestions? UPDATE: I'm looking for LOCAL caching of objects. The server which I connect to is already heavily cached. Memcached is not appropriate because it requires an additional network traffic between the Windows client and the server.
[ "I'd recommend using memcached and using cmemcache to access it. You can't necessarily limit the number of objects in the cache, but you can set an expiration time and limit the amount of memory it uses. And memcached is used by a lot of big names. In fact, I'd call it kind of the industry standard.\nUPDATE:\n\nI'm looking for LOCAL caching of objects.\n\nYou can run memcached locally and access it via localhost. I've done this a few times.\nOther than that, the only solution that I can think of is django's caching system. It offers several backends and some other configuration options. But that may be a little bit heavyweight if you're not using django.\nUPDATE 2: I suppose as a last resort, you can also use jython and access the java caching system. This may be a little difficult to do if you've already got clients using CPython though.\nUPDATE 3: It's probably a bit late to be of use to you, but a previous employer of mine used ZODB for this kind of thing. It's an actual database, but its read performance is fast enough to make it useful for caching.\n" ]
[ 4 ]
[]
[]
[ "design_patterns", "python" ]
stackoverflow_0000701264_design_patterns_python.txt
Q: What's the common practice for enums in Python? Possible Duplicate: How can I represent an 'enum' in Python? What's the common practice for enums in Python? I.e. how are they replicated in Python? public enum Materials { Shaded, Shiny, Transparent, Matte } A: class Materials: Shaded, Shiny, Transparent, Matte = range(4) >>> print Materials.Matte 3 A: I've seen this pattern several times: >>> class Enumeration(object): def __init__(self, names): # or *names, with no .split() for number, name in enumerate(names.split()): setattr(self, name, number) >>> foo = Enumeration("bar baz quux") >>> foo.quux 2 You can also just use class members, though you'll have to supply your own numbering: >>> class Foo(object): bar = 0 baz = 1 quux = 2 >>> Foo.quux 2 If you're looking for something more robust (sparse values, enum-specific exception, etc.), try this recipe. A: I have no idea why Enums are not support natively by Python. The best way I've found to emulate them is by overridding _ str _ and _ eq _ so you can compare them and when you use print() you get the string instead of the numerical value. class enumSeason(): Spring = 0 Summer = 1 Fall = 2 Winter = 3 def __init__(self, Type): self.value = Type def __str__(self): if self.value == enumSeason.Spring: return 'Spring' if self.value == enumSeason.Summer: return 'Summer' if self.value == enumSeason.Fall: return 'Fall' if self.value == enumSeason.Winter: return 'Winter' def __eq__(self,y): return self.value==y.value Usage: >>> s = enumSeason(enumSeason.Spring) >>> print(s) Spring A: You could probably use an inheritance structure although the more I played with this the dirtier I felt. class AnimalEnum: @classmethod def verify(cls, other): return issubclass(other.__class__, cls) class Dog(AnimalEnum): pass def do_something(thing_that_should_be_an_enum): if not AnimalEnum.verify(thing_that_should_be_an_enum): raise OhGodWhy
What's the common practice for enums in Python?
Possible Duplicate: How can I represent an 'enum' in Python? What's the common practice for enums in Python? I.e. how are they replicated in Python? public enum Materials { Shaded, Shiny, Transparent, Matte }
[ "class Materials:\n Shaded, Shiny, Transparent, Matte = range(4)\n\n>>> print Materials.Matte\n3\n\n", "I've seen this pattern several times:\n>>> class Enumeration(object):\n def __init__(self, names): # or *names, with no .split()\n for number, name in enumerate(names.split()):\n setattr(self, name, number)\n\n>>> foo = Enumeration(\"bar baz quux\")\n>>> foo.quux\n2\n\nYou can also just use class members, though you'll have to supply your own numbering:\n>>> class Foo(object):\n bar = 0\n baz = 1\n quux = 2\n\n>>> Foo.quux\n2\n\nIf you're looking for something more robust (sparse values, enum-specific exception, etc.), try this recipe.\n", "I have no idea why Enums are not support natively by Python.\nThe best way I've found to emulate them is by overridding _ str _ and _ eq _ so you can compare them and when you use print() you get the string instead of the numerical value.\nclass enumSeason():\n Spring = 0\n Summer = 1\n Fall = 2\n Winter = 3\n def __init__(self, Type):\n self.value = Type\n def __str__(self):\n if self.value == enumSeason.Spring:\n return 'Spring'\n if self.value == enumSeason.Summer:\n return 'Summer'\n if self.value == enumSeason.Fall:\n return 'Fall'\n if self.value == enumSeason.Winter:\n return 'Winter'\n def __eq__(self,y):\n return self.value==y.value\n\nUsage:\n>>> s = enumSeason(enumSeason.Spring)\n\n>>> print(s)\n\nSpring\n\n", "You could probably use an inheritance structure although the more I played with this the dirtier I felt.\nclass AnimalEnum:\n @classmethod\n def verify(cls, other):\n return issubclass(other.__class__, cls)\n\n\nclass Dog(AnimalEnum):\n pass\n\ndef do_something(thing_that_should_be_an_enum):\n if not AnimalEnum.verify(thing_that_should_be_an_enum):\n raise OhGodWhy\n\n" ]
[ 375, 21, 10, 7 ]
[]
[]
[ "enums", "python" ]
stackoverflow_0000702834_enums_python.txt
Q: URL encode a non-value pair in Python I'm trying to use Google's AJAX (JSON) Web Search API in Python. I'm stuck because Python's urllib.urlencode() only takes value pairs, not strings by themselves, to encode. In Google's API, the query string is the search term and it doesn't associate with a variable. query = "string that needs to be encoded" params = urllib.urlencode(query) # THIS FAILS # http://code.google.com/apis/ajaxsearch/documentation/reference.html url = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&rsz=large&%s&%s" % (params, GOOGLE_API_KEY) request = urllib2.Request(url) request.add_header('Referer', GOOGLE_REFERER) search_results = urllib2.urlopen(request) raw_results = search_results.read() json = simplejson.loads(raw_results) estimatedResultCount = json['responseData']['cursor']['estimatedResultCount'] if estimatedResultCount != 0: print "Google: %s hits" % estimatedResultCount How do I urlencode my search terms? A: I think you're looking for urllib.quote instead.
URL encode a non-value pair in Python
I'm trying to use Google's AJAX (JSON) Web Search API in Python. I'm stuck because Python's urllib.urlencode() only takes value pairs, not strings by themselves, to encode. In Google's API, the query string is the search term and it doesn't associate with a variable. query = "string that needs to be encoded" params = urllib.urlencode(query) # THIS FAILS # http://code.google.com/apis/ajaxsearch/documentation/reference.html url = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&rsz=large&%s&%s" % (params, GOOGLE_API_KEY) request = urllib2.Request(url) request.add_header('Referer', GOOGLE_REFERER) search_results = urllib2.urlopen(request) raw_results = search_results.read() json = simplejson.loads(raw_results) estimatedResultCount = json['responseData']['cursor']['estimatedResultCount'] if estimatedResultCount != 0: print "Google: %s hits" % estimatedResultCount How do I urlencode my search terms?
[ "I think you're looking for urllib.quote instead.\n" ]
[ 37 ]
[]
[]
[ "json", "python", "urlencode" ]
stackoverflow_0000702986_json_python_urlencode.txt
Q: User editing own Active Directory data How can I build a web page that allows a logged on user of a Windows 2003 domain change details of his account (probably just First Name, Surname, and Phone number)? A: Check out Python-AD (Python Active Directory) which offers the bindings you'll want for communicating with the AD server. As for the very broad "how can I build a web page" portion of your request, SO has plenty of questions/answers on good web frameworks in python :-) A: Take a look at this http://www.novell.com/coolsolutions/feature/11204.html
User editing own Active Directory data
How can I build a web page that allows a logged on user of a Windows 2003 domain change details of his account (probably just First Name, Surname, and Phone number)?
[ "Check out Python-AD (Python Active Directory) which offers the bindings you'll want for communicating with the AD server.\nAs for the very broad \"how can I build a web page\" portion of your request, SO has plenty of questions/answers on good web frameworks in python :-)\n", "Take a look at this http://www.novell.com/coolsolutions/feature/11204.html \n" ]
[ 0, 0 ]
[]
[]
[ "active_directory", "asp.net", "python" ]
stackoverflow_0000702493_active_directory_asp.net_python.txt
Q: Executing Java programs through Python How do I do this? A: You can execute anything you want from Python with the os.system() function. os.system(command) Execute the command (a string) in a subshell. This is implemented by calling the Standard C function system, and has the same limitations. Changes to os.environ, sys.stdin, etc. are not reflected in the environment of the executed command. For more power and flexibility you will want to look at the subprocess module: The subprocess module allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes. A: Of course, Jython allows you to use Java classes from within Python. It's an alternate way of looking at it that would allow much tighter integration of the Java code.
Executing Java programs through Python
How do I do this?
[ "You can execute anything you want from Python with the os.system() function.\n\nos.system(command)\n Execute the command\n (a string) in a subshell. This is\n implemented by calling the Standard C\n function system, and has the same\n limitations. Changes to os.environ,\n sys.stdin, etc. are not reflected in\n the environment of the executed\n command.\n\nFor more power and flexibility you will want to look at the subprocess module:\n\nThe subprocess module allows you to\n spawn new processes, connect to their\n input/output/error pipes, and obtain\n their return codes.\n\n", "Of course, Jython allows you to use Java classes from within Python. It's an alternate way of looking at it that would allow much tighter integration of the Java code.\n" ]
[ 12, 5 ]
[]
[]
[ "java", "python" ]
stackoverflow_0000702861_java_python.txt
Q: Why does setuptools sometimes delete and then re-install the exact same egg? I'm trying to install an egg on a computer where an identical egg already exists. Why does it remove the egg and then re-install it? I'm calling easy_install from a script with the options: ['-v', '-m', '-f', 'R:/OPTIONS/Stephen/python_eggs', 'mypkg==1.0_r2009_03_12'] While running the easy_install command this was observed: Searching for mypkg==1.0-r2009-03-12 Best match: calyon 1.0-r2009-03-12 Processing calyon-1.0_r2009_03_12-py2.4-win32.egg Removing d:\devtools\python24\lib\site-packages\mypkg-1.0_r2009_03_12-py2.4-win32.egg Copying mypkg-1.0_r2009_03_12-py2.4-win32.egg to d:\devtools\python24\lib\site-packages What causes this? Why is it that some times the egg is removed and re-installed, and on other occasions the egg is preserved? I've seen it happen a few times on my own PC but I'm not sure how to consistently re-produce the behavior. I'm using setuptools 0.6c9 A: Here is what I am guessing is happening... This is a guess based on your description of the symptoms. Assuming in your example mypkg and calyon are the same, the use of -r2009-03-12 on the end of your is not an expected format for setuptools (the standard format for post release tags is without hyphens YYYYMMDD) so it cannot ensure that the current version is up to date. Check out the links below and make sure you are versioning correctly. Additionally, I believe easy_install manages its version info in the easy-install.pth file. What does your easy-install.pth file say about your package? http://peak.telecommunity.com/DevCenter/setuptools#specifying-your-project-s-version http://peak.telecommunity.com/DevCenter/setuptools#tagging-and-daily-build-or-snapshot-releases A: It may show up on the bug list, otherwise it'd be best to report it.
Why does setuptools sometimes delete and then re-install the exact same egg?
I'm trying to install an egg on a computer where an identical egg already exists. Why does it remove the egg and then re-install it? I'm calling easy_install from a script with the options: ['-v', '-m', '-f', 'R:/OPTIONS/Stephen/python_eggs', 'mypkg==1.0_r2009_03_12'] While running the easy_install command this was observed: Searching for mypkg==1.0-r2009-03-12 Best match: calyon 1.0-r2009-03-12 Processing calyon-1.0_r2009_03_12-py2.4-win32.egg Removing d:\devtools\python24\lib\site-packages\mypkg-1.0_r2009_03_12-py2.4-win32.egg Copying mypkg-1.0_r2009_03_12-py2.4-win32.egg to d:\devtools\python24\lib\site-packages What causes this? Why is it that some times the egg is removed and re-installed, and on other occasions the egg is preserved? I've seen it happen a few times on my own PC but I'm not sure how to consistently re-produce the behavior. I'm using setuptools 0.6c9
[ "Here is what I am guessing is happening... This is a guess based on your description of the symptoms.\nAssuming in your example mypkg and calyon are the same, the use of -r2009-03-12 on the end of your is not an expected format for setuptools (the standard format for post release tags is without hyphens YYYYMMDD) so it cannot ensure that the current version is up to date. Check out the links below and make sure you are versioning correctly.\nAdditionally, I believe easy_install manages its version info in the easy-install.pth file. What does your easy-install.pth file say about your package?\nhttp://peak.telecommunity.com/DevCenter/setuptools#specifying-your-project-s-version\nhttp://peak.telecommunity.com/DevCenter/setuptools#tagging-and-daily-build-or-snapshot-releases\n", "It may show up on the bug list, otherwise it'd be best to report it.\n" ]
[ 2, 0 ]
[]
[]
[ "python", "setuptools" ]
stackoverflow_0000685874_python_setuptools.txt
Q: Using email.HeaderParser with imaplib.fetch in python? Does anyone have a good example of using the HeaderParser class in Python for a message that you pull down with imaplib.fetch? I have been able to find a lot of related things, but nothing that does just this. Do I need to full down the fetch has an RFC822? I was hoping to simply pull down the subjects. Thanks! A: Good news: you're right... you don't need to pull down the RFC822. The message_parts parameter to fetch() lets you be quite fine-grained. Here's a simple example of how to fetch just the header: import imaplib from email.parser import HeaderParser conn = imaplib.IMAP4('my.host.com') conn.login('my@username.com', 'mypassword') conn.select() conn.search(None, 'ALL') # returns a nice list of messages... # let's say I pick #1 from this data = conn.fetch(1, '(BODY[HEADER])') # gloss over data structure of return... I assume you know these # gives something like: # ('OK', [(1 (BODY[HEADER] {1662', 'Received: etc....')]) header_data = data[1][0][1] parser = HeaderParser() msg = parser.parsestr(header_data) <email.message.Message instance at 0x2a> print msg.keys() ['Received', 'Received', 'Received', 'Cc', 'Message-Id', 'From', 'To', 'In-Reply-To', 'Content-Type', 'Content-Transfer-Encoding', 'Mime-Version', 'Subject', 'Date', 'References', 'X-Mailer', 'X-yoursite-MailScanner-Information', 'X-yoursite-MailScanner', 'X-yoursite-MailScanner-From', 'Return-Path', 'X-OriginalArrivalTime'] The full list of message parts that can be passed as the second argument to fetch is in the IMAP4 spec: https://www.rfc-editor.org/rfc/rfc1730#section-6.4.5
Using email.HeaderParser with imaplib.fetch in python?
Does anyone have a good example of using the HeaderParser class in Python for a message that you pull down with imaplib.fetch? I have been able to find a lot of related things, but nothing that does just this. Do I need to full down the fetch has an RFC822? I was hoping to simply pull down the subjects. Thanks!
[ "Good news: you're right... you don't need to pull down the RFC822. The message_parts parameter to fetch() lets you be quite fine-grained.\nHere's a simple example of how to fetch just the header:\nimport imaplib\nfrom email.parser import HeaderParser\n\nconn = imaplib.IMAP4('my.host.com')\nconn.login('my@username.com', 'mypassword')\nconn.select()\nconn.search(None, 'ALL') # returns a nice list of messages...\n # let's say I pick #1 from this\n\ndata = conn.fetch(1, '(BODY[HEADER])')\n\n# gloss over data structure of return... I assume you know these\n# gives something like:\n# ('OK', [(1 (BODY[HEADER] {1662', 'Received: etc....')])\nheader_data = data[1][0][1]\n\nparser = HeaderParser()\nmsg = parser.parsestr(header_data)\n<email.message.Message instance at 0x2a>\n\nprint msg.keys()\n['Received', 'Received', 'Received', 'Cc', 'Message-Id', 'From', 'To',\n'In-Reply-To', 'Content-Type', 'Content-Transfer-Encoding', 'Mime-Version',\n'Subject', 'Date', 'References', 'X-Mailer', \n'X-yoursite-MailScanner-Information',\n'X-yoursite-MailScanner', 'X-yoursite-MailScanner-From', 'Return-Path',\n'X-OriginalArrivalTime']\n\nThe full list of message parts that can be passed as the second argument to fetch is in the IMAP4 spec: https://www.rfc-editor.org/rfc/rfc1730#section-6.4.5\n" ]
[ 18 ]
[]
[]
[ "email", "python" ]
stackoverflow_0000703185_email_python.txt
Q: Python: an iteration over a non-empty list with no if-clause comes up empty. Why? How can an iterator over a non-empty sequence, with no filtering and no aggregation (sum(), etc.), yield nothing? Consider a simple example: sequence = ['a', 'b', 'c'] list((el, ord(el)) for el in sequence) This yields [('a', 97), ('b', 98), ('c', 99)] as expected. Now, just swap the ord(el) out for an expression that takes the first value out of some generator using (...).next() — forgive the contrived example: def odd_integers_up_to_length(str): return (x for x in xrange(len(str)) if x%2==1) list((el, odd_integers_up_to_length(el).next()) for el in sequence) This yields []. Yeah, empty list. No ('a',stuff) tuples. Nothing. But we're not filtering or aggregating or reducing. A generator expression over n objects without filtering or aggregation must yield n objects, right? What's going on? A: odd_integers_up_to_length(el).next() will raise StopIteration, which isn't caught there, but is caught for the generator expression within it, stopping it without ever yielding anything. look at the first iteration, when the value is 'a': >>> odd_integers_up_to_length('a').next() Traceback (most recent call last): File "<stdin>", line 1, in <module> StopIteration A: What happens is that the next() call raises a StopIteration exception, which bubbles up the stack to the outer generator expression and stops that iteration. A StopIteration is the normal way for an iterator to signal that it's done. Generally we don't see it, because generally the next() call occurs within a construct that consumes the iterator, e.g. for x in iterator or sum(iterator). But when we call next() directly, we are the ones responsible for catching the StopIteration. Not doing so springs a leak in the abstraction, which here leads to unexpected behavior in the outer iteration. The lesson, I suppose: be careful about direct calls to next(). A: str is a reserved keword, you should name your variable differently I was also to advise about the next A: >>> seq=['a','b','c'] >>> list((el,4) for el in seq) [('a',4), ('b',4), ('c',4)] So it's not list giving you trouble here...
Python: an iteration over a non-empty list with no if-clause comes up empty. Why?
How can an iterator over a non-empty sequence, with no filtering and no aggregation (sum(), etc.), yield nothing? Consider a simple example: sequence = ['a', 'b', 'c'] list((el, ord(el)) for el in sequence) This yields [('a', 97), ('b', 98), ('c', 99)] as expected. Now, just swap the ord(el) out for an expression that takes the first value out of some generator using (...).next() — forgive the contrived example: def odd_integers_up_to_length(str): return (x for x in xrange(len(str)) if x%2==1) list((el, odd_integers_up_to_length(el).next()) for el in sequence) This yields []. Yeah, empty list. No ('a',stuff) tuples. Nothing. But we're not filtering or aggregating or reducing. A generator expression over n objects without filtering or aggregation must yield n objects, right? What's going on?
[ "odd_integers_up_to_length(el).next() will raise StopIteration, which isn't caught there, but is caught for the generator expression within it, stopping it without ever yielding anything.\nlook at the first iteration, when the value is 'a':\n>>> odd_integers_up_to_length('a').next()\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nStopIteration\n\n", "What happens is that the next() call raises a StopIteration exception, which bubbles up the stack to the outer generator expression and stops that iteration.\nA StopIteration is the normal way for an iterator to signal that it's done. Generally we don't see it, because generally the next() call occurs within a construct that consumes the iterator, e.g. for x in iterator or sum(iterator). But when we call next() directly, we are the ones responsible for catching the StopIteration. Not doing so springs a leak in the abstraction, which here leads to unexpected behavior in the outer iteration.\nThe lesson, I suppose: be careful about direct calls to next().\n", "str is a reserved keword, you should name your variable differently\nI was also to advise about the next\n", ">>> seq=['a','b','c']\n>>> list((el,4) for el in seq)\n[('a',4), ('b',4), ('c',4)]\n\nSo it's not list giving you trouble here...\n" ]
[ 13, 4, 0, 0 ]
[]
[]
[ "generator", "iterator", "leaky_abstraction", "python" ]
stackoverflow_0000703520_generator_iterator_leaky_abstraction_python.txt
Q: How would I compute exactly 30 days into the past with Python (down to the minute)? In Python, I'm attempting to retrieve the date/time that is exactly 30 days (30*24hrs) into the past. At present, I'm simply doing: >>> import datetime >>> start_date = datetime.date.today() + datetime.timedelta(-30) Which returns a datetime object, but with no time data: >>> start_date.year 2009 >>> start_date.hour Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'datetime.date' object has no attribute 'hour' A: You want to use a datetime object instead of just a date object: start_date = datetime.datetime.now() - datetime.timedelta(30) date just stores a date and time just a time. datetime is a date with a time.
How would I compute exactly 30 days into the past with Python (down to the minute)?
In Python, I'm attempting to retrieve the date/time that is exactly 30 days (30*24hrs) into the past. At present, I'm simply doing: >>> import datetime >>> start_date = datetime.date.today() + datetime.timedelta(-30) Which returns a datetime object, but with no time data: >>> start_date.year 2009 >>> start_date.hour Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'datetime.date' object has no attribute 'hour'
[ "You want to use a datetime object instead of just a date object:\nstart_date = datetime.datetime.now() - datetime.timedelta(30)\n\ndate just stores a date and time just a time. datetime is a date with a time.\n" ]
[ 142 ]
[]
[]
[ "date", "datetime", "python", "time" ]
stackoverflow_0000703907_date_datetime_python_time.txt
Q: Most efficient way of loading formatted binary files in Python I have binary files no larger than 20Mb in size that have a header section and then a data section containing sequences of uchars. I have Numpy, SciPy, etc. and each library has different ways of loading in the data. Any suggestions for the most efficient methods I should use? A: Use the struct module, or possibly a custom module written in C if performance is critical. A: struct should work for the header section, while numpy's memmap would be efficient for the data section if you are going to manipulate it in numpy anyways. There's no need to stress out about being inconsistent here. Both methods are compatible, just use the right tool for each job. A: bdec seems promising. A: I found that array.fromfile is the fastest methods for homogeneous data.
Most efficient way of loading formatted binary files in Python
I have binary files no larger than 20Mb in size that have a header section and then a data section containing sequences of uchars. I have Numpy, SciPy, etc. and each library has different ways of loading in the data. Any suggestions for the most efficient methods I should use?
[ "Use the struct module, or possibly a custom module written in C if performance is critical.\n", "struct should work for the header section, while numpy's memmap would be efficient for the data section if you are going to manipulate it in numpy anyways. There's no need to stress out about being inconsistent here. Both methods are compatible, just use the right tool for each job.\n", "bdec seems promising.\n", "I found that array.fromfile is the fastest methods for homogeneous data.\n" ]
[ 8, 4, 1, 0 ]
[]
[]
[ "binaryfiles", "input", "python" ]
stackoverflow_0000703262_binaryfiles_input_python.txt
Q: How to send a session message to an anonymous user in a Django site? I often show messages about user actions to logged in users in my Django app views using: request.user.message_set.create("message to user") How could I do the same for anonymous (not logged in) users? There is no request.user for anonymous users, but the Django documentation says that using the "session" middleware you can do the same thing as the above code. The Django documentation that links to the session middleware claims it is possible, but I couldn't find how to do it from the session documentation. A: This is what I do, using context processors: project/application/context.py (check for messages and add them to the context): def messages(request): messages = {} if 'message' in request.session: message_type = request.session.get('message_type', 'error') messages = {'message': request.session['message'], 'message_type': message_type} del request.session['message'] if 'message_type' in request.session: del request.session['message_type'] return messages project/settings.py (add the context to the TEMPLATE_CONTEXT_PROCESSORS): TEMPLATE_CONTEXT_PROCESSORS = ( "django.core.context_processors.request", "django.core.context_processors.debug", "django.core.context_processors.media", "django.core.context_processors.auth", "project.application.context.messages", ) With the above the function messages will be called on every request and whatever it returns will be added to the template's context. With this in place, if I want to give a user a message, I can do this: def my_view(request): if someCondition: request.session['message'] = 'Some Error Message' Finally, in a template you can just check if there are errors to display: {% if message %} <div id="system_message" class="{{ message_type }}"> {{ message }} </div> {% endif %} The message type is just used to style depending on what it is ("error","notice","success") and the way that this is setup you can only add 1 message at a time for a user, but that is all I really ever need so it works for me. It could be easily changed to allow for multiple messages and such. A: Store the data directly in the session, which is a dict-like object. Then in the view/template, check for the value. More information here: http://docs.djangoproject.com/en/dev/topics/http/sessions/#using-sessions-in-views You could also create a middleware class to check for the session object on each request, and do your build up/tear down there. A: See http://code.google.com/p/django-session-messages/ until the patch that enables session based messages lands in Django tree (as I saw recently, it's marked for 1.2, so no hope for quick addition...). Another project with similar functionality is Django Flash (http://djangoflash.destaquenet.com/).
How to send a session message to an anonymous user in a Django site?
I often show messages about user actions to logged in users in my Django app views using: request.user.message_set.create("message to user") How could I do the same for anonymous (not logged in) users? There is no request.user for anonymous users, but the Django documentation says that using the "session" middleware you can do the same thing as the above code. The Django documentation that links to the session middleware claims it is possible, but I couldn't find how to do it from the session documentation.
[ "This is what I do, using context processors:\nproject/application/context.py (check for messages and add them to the context):\ndef messages(request):\n messages = {}\n if 'message' in request.session:\n message_type = request.session.get('message_type', 'error')\n messages = {'message': request.session['message'],\n 'message_type': message_type}\n del request.session['message']\n if 'message_type' in request.session:\n del request.session['message_type']\n return messages\n\nproject/settings.py (add the context to the TEMPLATE_CONTEXT_PROCESSORS):\nTEMPLATE_CONTEXT_PROCESSORS = (\n \"django.core.context_processors.request\",\n \"django.core.context_processors.debug\",\n \"django.core.context_processors.media\",\n \"django.core.context_processors.auth\",\n \"project.application.context.messages\", \n)\n\nWith the above the function messages will be called on every request and whatever it returns will be added to the template's context. With this in place, if I want to give a user a message, I can do this:\ndef my_view(request):\n if someCondition:\n request.session['message'] = 'Some Error Message'\n\nFinally, in a template you can just check if there are errors to display:\n{% if message %}\n <div id=\"system_message\" class=\"{{ message_type }}\">\n {{ message }}\n </div>\n{% endif %}\n\nThe message type is just used to style depending on what it is (\"error\",\"notice\",\"success\") and the way that this is setup you can only add 1 message at a time for a user, but that is all I really ever need so it works for me. It could be easily changed to allow for multiple messages and such.\n", "Store the data directly in the session, which is a dict-like object. Then in the view/template, check for the value.\nMore information here:\nhttp://docs.djangoproject.com/en/dev/topics/http/sessions/#using-sessions-in-views\nYou could also create a middleware class to check for the session object on each request, and do your build up/tear down there.\n", "See http://code.google.com/p/django-session-messages/ until the patch that enables session based messages lands in Django tree (as I saw recently, it's marked for 1.2, so no hope for quick addition...).\nAnother project with similar functionality is Django Flash (http://djangoflash.destaquenet.com/).\n" ]
[ 7, 4, 4 ]
[]
[]
[ "django", "django_views", "python", "session" ]
stackoverflow_0000697902_django_django_views_python_session.txt
Q: Importing in Python between three or more files not working I hav codes eg1.py , eg2.py , eg3.py eg3.py imports eg2.py which in turn imports eg1.py When i run eg3.py for first time everything is fine If i import it again and again only eg3.py runs I need a solution for this. I will code eg3.py in such a way that : while(1): import eg2.py Where I went wrong.Please give me a solution. A: Do you want to execute the code in eg2.py when you import it? That is not a good solution. You should have a function containing your code in eg2.py and then execute this function in your while loop. In eg2.py: def my_func(): # do useful stuff pass In eg3.py import eg2 while True: eg2.my_func() A: Huh? You can't loop an import, they are cached so it doesn't really do anything except waste cycles, after the first iteration. How do you know that "only eg3.py" runs? A: If you import a module that is already imported, executable code in that module will not be re-run. E.g.: >>> import this The Zen of Python, by Tim Peters Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those! >>> import this >>> Deleting the module from sys.modules will force a complete reload: E.g.: >>> import sys >>> import this The Zen of Python, by Tim Peters Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those! >>> del(sys.modules["this"]) >>> import this The Zen of Python, by Tim Peters Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those! >>> Edit: Also, what heikogerlach said: you're better off calling functions in the already imported modules than deleting/reloading them most of the time.
Importing in Python between three or more files not working
I hav codes eg1.py , eg2.py , eg3.py eg3.py imports eg2.py which in turn imports eg1.py When i run eg3.py for first time everything is fine If i import it again and again only eg3.py runs I need a solution for this. I will code eg3.py in such a way that : while(1): import eg2.py Where I went wrong.Please give me a solution.
[ "Do you want to execute the code in eg2.py when you import it? That is not a good solution. You should have a function containing your code in eg2.py and then execute this function in your while loop.\nIn eg2.py:\ndef my_func():\n # do useful stuff\n pass\n\nIn eg3.py\nimport eg2\nwhile True:\n eg2.my_func()\n\n", "Huh? You can't loop an import, they are cached so it doesn't really do anything except waste cycles, after the first iteration.\nHow do you know that \"only eg3.py\" runs?\n", "If you import a module that is already imported, executable code in that module will not be re-run.\nE.g.:\n>>> import this\nThe Zen of Python, by Tim Peters\n\nBeautiful is better than ugly.\nExplicit is better than implicit.\nSimple is better than complex.\nComplex is better than complicated.\nFlat is better than nested.\nSparse is better than dense.\nReadability counts.\nSpecial cases aren't special enough to break the rules.\nAlthough practicality beats purity.\nErrors should never pass silently.\nUnless explicitly silenced.\nIn the face of ambiguity, refuse the temptation to guess.\nThere should be one-- and preferably only one --obvious way to do it.\nAlthough that way may not be obvious at first unless you're Dutch.\nNow is better than never.\nAlthough never is often better than *right* now.\nIf the implementation is hard to explain, it's a bad idea.\nIf the implementation is easy to explain, it may be a good idea.\nNamespaces are one honking great idea -- let's do more of those!\n>>> import this\n>>> \n\nDeleting the module from sys.modules will force a complete reload:\nE.g.:\n>>> import sys\n>>> import this\nThe Zen of Python, by Tim Peters\n\nBeautiful is better than ugly.\nExplicit is better than implicit.\nSimple is better than complex.\nComplex is better than complicated.\nFlat is better than nested.\nSparse is better than dense.\nReadability counts.\nSpecial cases aren't special enough to break the rules.\nAlthough practicality beats purity.\nErrors should never pass silently.\nUnless explicitly silenced.\nIn the face of ambiguity, refuse the temptation to guess.\nThere should be one-- and preferably only one --obvious way to do it.\nAlthough that way may not be obvious at first unless you're Dutch.\nNow is better than never.\nAlthough never is often better than *right* now.\nIf the implementation is hard to explain, it's a bad idea.\nIf the implementation is easy to explain, it may be a good idea.\nNamespaces are one honking great idea -- let's do more of those!\n>>> del(sys.modules[\"this\"])\n>>> import this\nThe Zen of Python, by Tim Peters\n\nBeautiful is better than ugly.\nExplicit is better than implicit.\nSimple is better than complex.\nComplex is better than complicated.\nFlat is better than nested.\nSparse is better than dense.\nReadability counts.\nSpecial cases aren't special enough to break the rules.\nAlthough practicality beats purity.\nErrors should never pass silently.\nUnless explicitly silenced.\nIn the face of ambiguity, refuse the temptation to guess.\nThere should be one-- and preferably only one --obvious way to do it.\nAlthough that way may not be obvious at first unless you're Dutch.\nNow is better than never.\nAlthough never is often better than *right* now.\nIf the implementation is hard to explain, it's a bad idea.\nIf the implementation is easy to explain, it may be a good idea.\nNamespaces are one honking great idea -- let's do more of those!\n>>> \n\nEdit:\nAlso, what heikogerlach said: you're better off calling functions in the already imported modules than deleting/reloading them most of the time.\n" ]
[ 7, 1, 0 ]
[]
[]
[ "import", "python" ]
stackoverflow_0000704856_import_python.txt
Q: Add event to list I want to add event to list such that on adding items actions are taken based on the item e.g. genrating new data structures, change in screen output or raising exception. How do I accomplish this? A: You could create your own class that extends the list object: class myList(list): def myAppend(self, item): if isinstance(item, list): print 'Appending a list' self.append(item) elif isinstance(item, str): print 'Appending a string item' self.append(item) else: raise Exception L = myList() L.myAppend([1,2,3]) L.myAppend('one two three') print L #Output: #Appending a list #Appending a string item #[[1, 2, 3], 'one two three']
Add event to list
I want to add event to list such that on adding items actions are taken based on the item e.g. genrating new data structures, change in screen output or raising exception. How do I accomplish this?
[ "You could create your own class that extends the list object:\nclass myList(list):\n def myAppend(self, item):\n if isinstance(item, list):\n print 'Appending a list'\n self.append(item)\n elif isinstance(item, str):\n print 'Appending a string item'\n self.append(item)\n else:\n raise Exception\n\nL = myList()\nL.myAppend([1,2,3])\nL.myAppend('one two three')\nprint L\n\n#Output:\n#Appending a list\n#Appending a string item\n#[[1, 2, 3], 'one two three']\n\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0000705296_python.txt
Q: indentation of multiline string I have a script that uses the cmd Python module. The cmd module uses a triple quoted multiline string as it's help text. Something like this def x(self, strags = None): """class help text here and some more help text here""" When running the script, the command 'help x' will print the string. It will, however, print the newlines in front of the last two lines as well. I can overcome this by not indenting these lines, but that'll make my code ugl{y,ier}. How to overcome this indenting problem? How do the pro Python coders handle this? A: Personally I try to follow PEP 8 which refers the reader to PEP 257 for Docstring Conventions. It has an entire section on multi-line docstrings. A: I'd handle it by having consistent indents, like this: def x(self, strags = None): """ class help text here and some more help text here """ Sure, it takes two lines more, but it also injects clarity (in my opinion) by making the doc comment stand out quite well.
indentation of multiline string
I have a script that uses the cmd Python module. The cmd module uses a triple quoted multiline string as it's help text. Something like this def x(self, strags = None): """class help text here and some more help text here""" When running the script, the command 'help x' will print the string. It will, however, print the newlines in front of the last two lines as well. I can overcome this by not indenting these lines, but that'll make my code ugl{y,ier}. How to overcome this indenting problem? How do the pro Python coders handle this?
[ "Personally I try to follow PEP 8 which refers the reader to PEP 257 for Docstring Conventions. It has an entire section on multi-line docstrings.\n", "I'd handle it by having consistent indents, like this:\ndef x(self, strags = None):\n \"\"\"\n class\n help text here\n and some more help text here\n \"\"\"\n\nSure, it takes two lines more, but it also injects clarity (in my opinion) by making the doc comment stand out quite well.\n" ]
[ 2, 1 ]
[]
[]
[ "cmd", "indentation", "python" ]
stackoverflow_0000705370_cmd_indentation_python.txt
Q: Using python ctypes to get buffer of floats from shared library into python string I'm trying to use python ctypes to use these two C functions from a shared library: bool decompress_rgb(unsigned char *data, long dataLen, int scale) float* getRgbBuffer() The first function is working fine. I can tell by putting some debug code in the shared library and checking the input. The problem is getting the data out. The RGB buffer is a pointer to a float (obviously) and this pointer stays constant during the life of the application. Therefore whenever I want to decompress an image, I call decompress_rgb and then need to see what's at the location pointed to by getRgbBuffer. I know that the buffer size is (720 * 288 * sizeof(float)) so I guess this has to come into play somewhere. There's no c_float_p type so I thought I'd try this: getRgbBuffer.restype = c_char_p Then I do: ptr = getRgbBuffer() print "ptr is ", ptr which just outputs: ptr = 3078746120 I'm guessing that's the actual address rather than the content, but even if I was successfully dereferencing the pointer and getting the contents, it would only be the first char. How can I get the contents of the entire buffer into a python string? Edit: Had to change: getRgbBuffer.restype = c_char_p to getRgbBuffer.restype = c_void_p but then BastardSaint's answer worked. A: Not fully tested, but I think it's something along this line: buffer_size = 720 * 288 * ctypes.sizeof(ctypes.c_float) rgb_buffer = ctypes.create_string_buffer(buffer_size) ctypes.memmove(rgb_buffer, getRgbBuffer(), buffer_size) Key is the ctypes.memmove() function. From the ctypes documentation: memmove(dst, src, count) Same as the standard C memmove library function: copies count bytes from src to dst. dst and src must be integers or ctypes instances that can be converted to pointers. After the above snippet is run, rgb_buffer.value will return the content up until the first '\0'. To get all bytes as a python string, you can slice the whole thing: buffer_contents = rgb_buffer[:]. A: It's been a while since I used ctypes and I don't have something which returns a "double *" handy enough to test this out, but if you want a c_float_p: c_float_p = ctypes.POINTER(ctypes.c_float) Reading BastardSaint's answer, you just want the raw data, but I wasn't sure if you're doing that as a workaround to not having a c_float_p.
Using python ctypes to get buffer of floats from shared library into python string
I'm trying to use python ctypes to use these two C functions from a shared library: bool decompress_rgb(unsigned char *data, long dataLen, int scale) float* getRgbBuffer() The first function is working fine. I can tell by putting some debug code in the shared library and checking the input. The problem is getting the data out. The RGB buffer is a pointer to a float (obviously) and this pointer stays constant during the life of the application. Therefore whenever I want to decompress an image, I call decompress_rgb and then need to see what's at the location pointed to by getRgbBuffer. I know that the buffer size is (720 * 288 * sizeof(float)) so I guess this has to come into play somewhere. There's no c_float_p type so I thought I'd try this: getRgbBuffer.restype = c_char_p Then I do: ptr = getRgbBuffer() print "ptr is ", ptr which just outputs: ptr = 3078746120 I'm guessing that's the actual address rather than the content, but even if I was successfully dereferencing the pointer and getting the contents, it would only be the first char. How can I get the contents of the entire buffer into a python string? Edit: Had to change: getRgbBuffer.restype = c_char_p to getRgbBuffer.restype = c_void_p but then BastardSaint's answer worked.
[ "Not fully tested, but I think it's something along this line:\nbuffer_size = 720 * 288 * ctypes.sizeof(ctypes.c_float)\nrgb_buffer = ctypes.create_string_buffer(buffer_size) \nctypes.memmove(rgb_buffer, getRgbBuffer(), buffer_size)\n\nKey is the ctypes.memmove() function. From the ctypes documentation:\n\nmemmove(dst, src, count)\n Same as the standard C memmove library function: copies count bytes from src to dst. dst and src must be integers or ctypes instances that can be converted to pointers.\n\nAfter the above snippet is run, rgb_buffer.value will return the content up until the first '\\0'. To get all bytes as a python string, you can slice the whole thing: buffer_contents = rgb_buffer[:].\n", "It's been a while since I used ctypes and I don't have something which returns a \"double *\" handy enough to test this out, but if you want a c_float_p:\nc_float_p = ctypes.POINTER(ctypes.c_float)\n\nReading BastardSaint's answer, you just want the raw data, but I wasn't sure if you're doing that as a workaround to not having a c_float_p.\n" ]
[ 4, 2 ]
[]
[]
[ "ctypes", "pointers", "python", "return_value" ]
stackoverflow_0000704777_ctypes_pointers_python_return_value.txt
Q: Inventory Control Across Multiple Servers .. Ideas? We currently have an inventory management system that was built in-house. It works great, and we are constantly innovating it. This past Fall, we began selling products directly on one of our websites via a Shopping Cart checkout. Our inventory management system runs off a server in the office, while the three websites we currently have (only one actually sells things) runs off an outside source, obviously. See my problem here? Basically, I am trying to think of ways I can create a central inventory control system that allows both the internal software and external websites to communicate so that inventory is always up to date and we are not selling something we don't have. Our internal inventory tracking works great and flows well, but I have no idea on how I would implement a solid tracking system that can communicate between the two. The software is all written in Python, but it does not matter as I am mostly looking for ideas and methods on how would this be implemented. Thanks in advance for any answers, and I hope that made sense .. I can elaborate. A: One possibility would be to expose a web service interface on your inventory management system that allows the transactions used by the web shopfront to be accessed remotely. With a reasonably secure VPN link or ssh tunnel type arrangement, the web shopfront could get stock levels, place orders or execute searches against the inventory system. Notes: You would still have to add a reasonable security layer to the inventory service in case the web shopfront was compromised. You would have to make sure your inventory management application and server was big enough to handle the load, or could be reasonably easily scaled so it could do so. Your SLA for the inventory application would need to be good enough to support the web shopfront. This probably means some sort of hot failover arrangement. A: I don't see the problem... You have an application running on one server that manages your database locally. There's no reason a remote server can't also talk to that database. Of course, if you don't have a database and are instead using a homegrown app to act as some sort of faux-database, I recommend that you refactor to use something sort of actual DB sooner rather than later. A: I'm not sure if there is any one really good solution for your problem. I think the way you are doing it now works fine, but if you don't agree then I don't know what to tell you.
Inventory Control Across Multiple Servers .. Ideas?
We currently have an inventory management system that was built in-house. It works great, and we are constantly innovating it. This past Fall, we began selling products directly on one of our websites via a Shopping Cart checkout. Our inventory management system runs off a server in the office, while the three websites we currently have (only one actually sells things) runs off an outside source, obviously. See my problem here? Basically, I am trying to think of ways I can create a central inventory control system that allows both the internal software and external websites to communicate so that inventory is always up to date and we are not selling something we don't have. Our internal inventory tracking works great and flows well, but I have no idea on how I would implement a solid tracking system that can communicate between the two. The software is all written in Python, but it does not matter as I am mostly looking for ideas and methods on how would this be implemented. Thanks in advance for any answers, and I hope that made sense .. I can elaborate.
[ "One possibility would be to expose a web service interface on your inventory management system that allows the transactions used by the web shopfront to be accessed remotely. With a reasonably secure VPN link or ssh tunnel type arrangement, the web shopfront could get stock levels, place orders or execute searches against the inventory system.\nNotes:\n\nYou would still have to add a reasonable security layer to the inventory service in case the web shopfront was compromised.\nYou would have to make sure your inventory management application and server was big enough to handle the load, or could be reasonably easily scaled so it could do so.\n\nYour SLA for the inventory application would need to be good enough to support the web shopfront. This probably means some sort of hot failover arrangement.\n", "I don't see the problem... You have an application running on one server that manages your database locally. There's no reason a remote server can't also talk to that database.\nOf course, if you don't have a database and are instead using a homegrown app to act as some sort of faux-database, I recommend that you refactor to use something sort of actual DB sooner rather than later.\n", "I'm not sure if there is any one really good solution for your problem. I think the way you are doing it now works fine, but if you don't agree then I don't know what to tell you.\n" ]
[ 1, 0, 0 ]
[]
[]
[ "inventory", "python", "tracking" ]
stackoverflow_0000487642_inventory_python_tracking.txt
Q: any way to loop iteration with same item in python? It's a common programming task to loop iteration while not receiving next item. For example: for sLine in oFile : if ... some logic ... : sLine = oFile.next() ... some more logic ... # at this point i want to continue iteration but without # getting next item from oFile. How can this be done in python? A: I first thought you wanted the continue keyword, but that would of course get you the next line of input. I think I'm stumped. When looping over the lines of a file, what exactly should happen if you continued the loop without getting a new line? Do you want to inspect the line again? If so, I suggest adding an inner loop that runs until you're "done" with the input line, which you can then break out of, or use maybe the while-condition and a flag variable to terminate. A: Simply create an iterator of your own that lets you push data back on the front of the stream so that you can give the loop a line that you want to see over again: next_lines = [] def prependIterator(i): while True: if next_lines: yield(next_lines.pop()) else: yield(i.next()) for sLine in prependIterator(oFile): if ... some logic ... : sLine = oFile.next() ... some more logic ... # put the line back so that it gets read # again as we head back up to the "for # statement next_lines.append(sLine) If the prepend_list is never touched, then the prependIterator behaves exactly like whatever iterator it is passed: the if statement inside will always get False and it will just yield up everything in the iterator it has been passed. But if items are placed on the prepend_list at any point during the iteration, then those will be yielded first instead before it returns back to reading from the main iterator. A: What you need is a simple, deterministic finite state machine. Something like this... state = 1 for sLine in oFile: if state == 1: if ... some logic ... : state = 2 elif state == 2: if ... some logic ... : state = 1 A: Instead of looping through the file line by line, you can do a file.readlines() into a list. Then loop through the list (which allows you to look at the next item if you want). Example: list = oFile.readlines() for i in range(len(list)) #your stuff list[i] #current line list[i-1] #previous line list[i+1] #next line you can go to the previous or next line by simply using [i-1] or [i+1]. You just need to make sure that no matter what, i does not go out of range. A: Ugly. Wrap the body in another loop. for sLine in oFile : while 1: if ... some logic ... : sLine = oFile.next() ... some more logic ... continue ... some more logic ... break A little better: class pushback_iter(object): def __init__(self,iterable): self.iterator = iter(iterable) self.buffer = [] def next(self): if self.buffer: return self.buffer.pop() else: return self.iterator.next() def __iter__(self): return self def push(self,item): self.buffer.append(item) it_file = pushback_iter(file) for sLine in it_file: if ... some logic ... : sLine = it_file.next() ... some more logic ... it_file.push(sLine) continue ... some more logic ... Unfortunately no simple way of referencing the current iterator.
any way to loop iteration with same item in python?
It's a common programming task to loop iteration while not receiving next item. For example: for sLine in oFile : if ... some logic ... : sLine = oFile.next() ... some more logic ... # at this point i want to continue iteration but without # getting next item from oFile. How can this be done in python?
[ "I first thought you wanted the continue keyword, but that would of course get you the next line of input.\nI think I'm stumped. When looping over the lines of a file, what exactly should happen if you continued the loop without getting a new line?\nDo you want to inspect the line again? If so, I suggest adding an inner loop that runs until you're \"done\" with the input line, which you can then break out of, or use maybe the while-condition and a flag variable to terminate.\n", "Simply create an iterator of your own that lets you push data back on the front of the stream so that you can give the loop a line that you want to see over again:\n\nnext_lines = []\ndef prependIterator(i):\n while True:\n if next_lines:\n yield(next_lines.pop())\n else:\n yield(i.next())\n\nfor sLine in prependIterator(oFile):\n if ... some logic ... :\n sLine = oFile.next()\n ... some more logic ...\n # put the line back so that it gets read\n # again as we head back up to the \"for\n # statement\n next_lines.append(sLine)\n\nIf the prepend_list is never touched, then the prependIterator behaves exactly like whatever iterator it is passed: the if statement inside will always get False and it will just yield up everything in the iterator it has been passed. But if items are placed on the prepend_list at any point during the iteration, then those will be yielded first instead before it returns back to reading from the main iterator.\n", "What you need is a simple, deterministic finite state machine. Something like this...\nstate = 1\nfor sLine in oFile:\n if state == 1:\n if ... some logic ... :\n state = 2\n elif state == 2:\n if ... some logic ... :\n state = 1\n\n", "Instead of looping through the file line by line, you can do a file.readlines() into a list. Then loop through the list (which allows you to look at the next item if you want). Example:\nlist = oFile.readlines()\nfor i in range(len(list))\n #your stuff\n list[i] #current line\n list[i-1] #previous line\n list[i+1] #next line\n\nyou can go to the previous or next line by simply using [i-1] or [i+1]. You just need to make sure that no matter what, i does not go out of range.\n", "Ugly. Wrap the body in another loop.\nfor sLine in oFile :\n while 1:\n if ... some logic ... :\n sLine = oFile.next()\n ... some more logic ...\n continue\n ... some more logic ...\n break\n\nA little better:\nclass pushback_iter(object):\n def __init__(self,iterable):\n self.iterator = iter(iterable)\n self.buffer = []\n def next(self):\n if self.buffer:\n return self.buffer.pop()\n else:\n return self.iterator.next()\n def __iter__(self):\n return self\n def push(self,item):\n self.buffer.append(item)\n\nit_file = pushback_iter(file)\nfor sLine in it_file:\n if ... some logic ... :\n sLine = it_file.next()\n ... some more logic ...\n it_file.push(sLine)\n continue\n ... some more logic ...\n\nUnfortunately no simple way of referencing the current iterator.\n" ]
[ 3, 2, 1, 0, 0 ]
[ "You can assign your iterator to an variable then use the .next get te next one.\niter = oFile.xreadlines() # is this the correct iterator you want?\ntry:\n sLine = iter.next()\n while True:\n if ... some logic ... :\n sLine = iter.next()\n ... some more logic ...\n continue\n sLine = iter.next()\nexcept StopIterator:\n pass\n\n", "You just need to create a variable out of your iterator, and then manipulate that:\n% cat /tmp/alt-lines.py \n#! /usr/bin/python -tt\n\nimport sys\n\nlines = iter(open(sys.argv[1]))\nfor line in lines:\n print line,\n lines.next()\n\n% cat /tmp/test\n1\n2\n3\n4\n% /tmp/alt-lines.py /tmp/test\n1\n3\n\n...note that in this case we unconditionally do lines.next() so the above fails for files with odd lines, but I assume that isn't going to be the case for you (and adding the error checking is fairly trivial -- just catch and throw away StopIteration on the manual .next()).\n", "jle's approach should work, though you might as well use enumerate():\nfor linenr, line in enumerate(oFile):\n # your stuff\n\n" ]
[ -1, -1, -2 ]
[ "iterator", "python" ]
stackoverflow_0000705811_iterator_python.txt
Q: Caching data from other websites in Django Suppose I have a simple view which needs to parse data from an external website. Right now it looks something like this: def index(request): source = urllib2.urlopen(EXTERNAL_WEBSITE_URL) bs = BeautifulSoup.BeautifulSoup(source.read()) finalList = [] # do whatever with bs to populate the list return render_to_response('someTemplate.html', {'finalList': finalList}) First of all, is this an acceptable use? Obviously, this is not good performance-wise. The external website page is pretty big, and I am only extracting a small part of it. I thought of two solutions: Do all of this asynchronously. Load the rest of the page, populate with data once I get it. But I don't even know where to start. I'm just starting with Django and never done anything async up until now. I don't care if this data is updated every 2-3 minutes, so caching is a good solution as well (also saves me the extra round-trips). How would I go about caching this data? A: First, don't optimize prematurely. Get this to work. Then, add enough logging to see what the performance problems (if any) really are. You may find that end-user's PC is the slowest part; getting data from another site may, actually, be remarkably fast when you do not fetch .JS libraries and .CSS and artwork and the render then entire thing in a browser. Once you're absolutely sure that the fetch of the remote content really IS a problem. Really. Then you have to do the following. Write a "crontab" script that does the remote fetch form time to time. Design a place to cache the remote results. Database or file system, pick one. Update your Django app to get the data from the cache (database or filesystem) instead of the remote URL. Only after you have absolute proof that the urllib2 read of the remote site is the bottleneck. A: Caching with django is pretty easy, from django.core.cache import cache key = 'some-key' data = cache.get(key) if data is None: # soupify the page and what not cache.set(data, key, 60*60*8) return render_to_response ... return render_to_response To answer your questions, you can do this asynchronously, but then you would have to use something like django cron to update the cache ever so often. On the other hand you can write this as a standalone python script, replace the cache imported from django with memcache and it would work the same way. It would reduce some of the performance issues your site could have, and as long as you know the cache key, you can retrieve the data from the cache. Like Jarret said I would read django's caching docs and memcache's docs for more information. A: Django has robust, built-in support for caching views: http://docs.djangoproject.com/en/dev/topics/cache/#topics-cache. It offers solutions for caching entire views (such as in your case), or just certain parts of data in the view. There are even controls for how often to update the cache, and so forth.
Caching data from other websites in Django
Suppose I have a simple view which needs to parse data from an external website. Right now it looks something like this: def index(request): source = urllib2.urlopen(EXTERNAL_WEBSITE_URL) bs = BeautifulSoup.BeautifulSoup(source.read()) finalList = [] # do whatever with bs to populate the list return render_to_response('someTemplate.html', {'finalList': finalList}) First of all, is this an acceptable use? Obviously, this is not good performance-wise. The external website page is pretty big, and I am only extracting a small part of it. I thought of two solutions: Do all of this asynchronously. Load the rest of the page, populate with data once I get it. But I don't even know where to start. I'm just starting with Django and never done anything async up until now. I don't care if this data is updated every 2-3 minutes, so caching is a good solution as well (also saves me the extra round-trips). How would I go about caching this data?
[ "First, don't optimize prematurely. Get this to work.\nThen, add enough logging to see what the performance problems (if any) really are.\nYou may find that end-user's PC is the slowest part; getting data from another site may, actually, be remarkably fast when you do not fetch .JS libraries and .CSS and artwork and the render then entire thing in a browser.\nOnce you're absolutely sure that the fetch of the remote content really IS a problem. Really. Then you have to do the following.\n\nWrite a \"crontab\" script that does the remote fetch form time to time.\nDesign a place to cache the remote results. Database or file system, pick one.\nUpdate your Django app to get the data from the cache (database or filesystem) instead of the remote URL.\n\nOnly after you have absolute proof that the urllib2 read of the remote site is the bottleneck.\n", "Caching with django is pretty easy,\nfrom django.core.cache import cache\nkey = 'some-key'\ndata = cache.get(key)\nif data is None:\n # soupify the page and what not\n cache.set(data, key, 60*60*8)\n return render_to_response ...\nreturn render_to_response\n\nTo answer your questions, you can do this asynchronously, but then you would have to use something like django cron to update the cache ever so often. On the other hand you can write this as a standalone python script, replace the cache imported from django with memcache and it would work the same way. It would reduce some of the performance issues your site could have, and as long as you know the cache key, you can retrieve the data from the cache. \nLike Jarret said I would read django's caching docs and memcache's docs for more information.\n", "Django has robust, built-in support for caching views: http://docs.djangoproject.com/en/dev/topics/cache/#topics-cache.\nIt offers solutions for caching entire views (such as in your case), or just certain parts of data in the view. There are even controls for how often to update the cache, and so forth.\n" ]
[ 5, 3, 1 ]
[]
[]
[ "caching", "django", "python" ]
stackoverflow_0000705855_caching_django_python.txt
Q: Connection refused on Windows XP network This is only marginally a programming problem and more of a networking problem. I'm trying to get a Django web app to run in my home network and I can't get any machines on the network to get to the web page. I've run on ports 80 and 8000 with no luck. Error message is: "Firefox can't establish a connection to the server at 192.168.x.x." I've tried using sockets in python from the client: import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect ( ("192.168.x.x", 80) ) I just get "socket.error (10061, 'Connection refused')". Interestingly, I can connect with port 25. There is no Windows firewall running. There is a NetGear router/firewall in front of the cable modem. What should I be looking at to configure this? Also tried: import urllib2 urllib2.urlopen("http://192.168.x.x/") Same thing. Re: "Can you see the Django app from the machine it's running on?" Yes. It does work on the same machine. It does not work across the network. I can also set the server to run on whatever port I choose (80, 8000, etc.) and it is accessible locally, not across the network. Q. Is it netstat-able? A. Yes: Proto Local Address Foreign Address State .... TCP D3FL2J71:http localhost:1140 TIME_WAIT TCP D3FL2J71:http localhost:1147 TIME_WAIT I have the website visible in two browser windows locally. Use explicit external port (not rely on localhost): python manage.py runserver 192.168.x.x:8000 Bing bing bing! We have a winner! Wow, am I ever glad this is not a networking problem. "is the Django app definitely advertising itself on the 192.168.x.x address and not just on the loopback adapter?" It seems Jon was on the right track, too, but the comment did not point me in the direction to look -- check the Django server's setup call. A: I assume you're running the django dev server? If so, make sure you start it so that it will bind to the IP address the other machines need to use for the connection: python manage.py runserver 192.168.x.x:8000 You can ask the server to bind to all addresses with (haven't tried this on Windows myself, I admit): python manage.py runserver 0.0.0.0:8000 Normal runserver usage binds only to localhost, I'm afraid.
Connection refused on Windows XP network
This is only marginally a programming problem and more of a networking problem. I'm trying to get a Django web app to run in my home network and I can't get any machines on the network to get to the web page. I've run on ports 80 and 8000 with no luck. Error message is: "Firefox can't establish a connection to the server at 192.168.x.x." I've tried using sockets in python from the client: import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect ( ("192.168.x.x", 80) ) I just get "socket.error (10061, 'Connection refused')". Interestingly, I can connect with port 25. There is no Windows firewall running. There is a NetGear router/firewall in front of the cable modem. What should I be looking at to configure this? Also tried: import urllib2 urllib2.urlopen("http://192.168.x.x/") Same thing. Re: "Can you see the Django app from the machine it's running on?" Yes. It does work on the same machine. It does not work across the network. I can also set the server to run on whatever port I choose (80, 8000, etc.) and it is accessible locally, not across the network. Q. Is it netstat-able? A. Yes: Proto Local Address Foreign Address State .... TCP D3FL2J71:http localhost:1140 TIME_WAIT TCP D3FL2J71:http localhost:1147 TIME_WAIT I have the website visible in two browser windows locally. Use explicit external port (not rely on localhost): python manage.py runserver 192.168.x.x:8000 Bing bing bing! We have a winner! Wow, am I ever glad this is not a networking problem. "is the Django app definitely advertising itself on the 192.168.x.x address and not just on the loopback adapter?" It seems Jon was on the right track, too, but the comment did not point me in the direction to look -- check the Django server's setup call.
[ "I assume you're running the django dev server? If so, make sure you start it so that it will bind to the IP address the other machines need to use for the connection:\npython manage.py runserver 192.168.x.x:8000\n\nYou can ask the server to bind to all addresses with (haven't tried this on Windows myself, I admit):\npython manage.py runserver 0.0.0.0:8000\n\nNormal runserver usage binds only to localhost, I'm afraid.\n" ]
[ 3 ]
[]
[]
[ "networking", "python" ]
stackoverflow_0000707023_networking_python.txt
Q: Python source header comment What is the line #!/usr/bin/env python in the first line of a python script used for? A: In UNIX and Linux this tells which binary to use as an interpreter (see also Wiki page). For example shell script is interpreted by /bin/sh. #!/bin/sh Now with python it's a bit tricky, because you can't assume where the binary is installed, nor which you want to use. Thus the /usr/bin/env trick. It's use whichever python binary is first in the $PATH. You can check that executing which python With the interpreter line you can run the script by chmoding it to executable. And just running it. Thus with script beginning with #!/usr/bin/env python these two methods are equivalent: $ python script.py and (assuming that earlier you've done chmod +x script.py) $ ./script.py This is useful for creating system wide scripts. cp yourCmd.py /usr/local/bin/yourCmd chmod a+rx /usr/local/bin/yourCmd And then you call it from anywhere just with yourCmd A: This is called a shebang line: In computing, a shebang (also called a hashbang, hashpling, or pound bang) refers to the characters "#!" when they are the first two characters in a text file. Unix-like operating systems take the presence of these two characters as an indication that the file is a script, and try to execute that script using the interpreter specified by the rest of the first line in the file. For instance, shell scripts for the Bourne shell start with the first line: A: Under UNIX and similar operating systems, this line tells which interpreter is to be used if the file is executed. A: As Andri said. In Windows, the executable to run a file with when launched from the command line relies on an association: 16:12:40.68 C:\>assoc .py .py=Python.File 16:13:53.45 C:\>assoc Python.File Python.File=Python File 16:14:01.70 C:\>ftype Python.File Python.File="C:\Python30\python.exe" "%1" %* In Unix, the shell interpreter makes the inference by opening the file and seeing if there is a command named in the file. A: '/usr/bin/env python' searches $PATH for python and runs it. Usually env is used to set some environment variables for a program What that line does is tell your computer what to do with that file, if you simply try to run the file without specifying an interpreter.. more detail A: Just a note, this line is nothing more then a comment to the interpreter in Windows.
Python source header comment
What is the line #!/usr/bin/env python in the first line of a python script used for?
[ "In UNIX and Linux this tells which binary to use as an interpreter (see also Wiki page).\nFor example shell script is interpreted by /bin/sh.\n#!/bin/sh\n\nNow with python it's a bit tricky, because you can't assume where the binary is installed, nor which you want to use. Thus the /usr/bin/env trick. It's use whichever python binary is first in the $PATH. You can check that executing which python \nWith the interpreter line you can run the script by chmoding it to executable. And just running it. Thus with script beginning with\n#!/usr/bin/env python\n\nthese two methods are equivalent:\n$ python script.py\n\nand (assuming that earlier you've done chmod +x script.py)\n$ ./script.py\n\n\nThis is useful for creating system wide scripts. \ncp yourCmd.py /usr/local/bin/yourCmd\nchmod a+rx /usr/local/bin/yourCmd\n\nAnd then you call it from anywhere just with\nyourCmd\n\n", "This is called a shebang line:\n\nIn computing, a shebang (also called a hashbang, hashpling, or pound bang) refers to the characters \"#!\" when they are the first two characters in a text file. Unix-like operating systems take the presence of these two characters as an indication that the file is a script, and try to execute that script using the interpreter specified by the rest of the first line in the file. For instance, shell scripts for the Bourne shell start with the first line:\n\n", "Under UNIX and similar operating systems, this line tells which interpreter is to be used if the file is executed.\n", "As Andri said. In Windows, the executable to run a file with when launched from the command line relies on an association:\n16:12:40.68 C:\\>assoc .py\n.py=Python.File\n\n16:13:53.45 C:\\>assoc Python.File\nPython.File=Python File\n\n16:14:01.70 C:\\>ftype Python.File\nPython.File=\"C:\\Python30\\python.exe\" \"%1\" %*\n\nIn Unix, the shell interpreter makes the inference by opening the file and seeing if there is a command named in the file.\n", "'/usr/bin/env python' searches $PATH for python and runs it.\n\nUsually env is used to set some environment variables\n for a program\n\nWhat that line does is tell your computer what to do with that file, if you simply try to run the file without specifying an interpreter.. more detail\n", "Just a note, this line is nothing more then a comment to the interpreter in Windows. \n" ]
[ 27, 14, 5, 5, 3, 2 ]
[]
[]
[ "python", "shebang", "unix" ]
stackoverflow_0000707127_python_shebang_unix.txt
Q: how to hook to events / messages in windows using python in short: i want to intercept suspend/standby messages on my laptop, but my program doesn't receives all relevant messages. background: there's a bug in ms-excel on windows xp/2k, which prevents system suspend if a file is opened on a network/usb drive. i'm trying to work-around it programmatically (my toolbox include python, vb6, or command line tools). i know nothing about windows instrumentation :-) i have a sysinternals utility that suspends the system anyhow. i want to hook it to the close-lid event! in long: The notebook lid close (fujitsu u810) initiate the standby procedure [how?] The system then send everybody WM_POWERBROADCAST: PBT_APMQUERYSUSPEND (i can trace them using SPYXX.EXE) Every program answers "True", until excel answers "false", and the whole process stops. My questions: 1) my python program doesn't catch neither pbm_apmquerysuspend, nor PBT_APMQUERYSTANDBYFAILED, nor PBT_APMQUERYSUSPENDFAILED: ` ... query = "SELECT * FROM Win32_PowerManagementEvent" power_watcher = wmi.ExecNotificationQuery ( query ) power_event = power_watcher.NextEvent () ` it receives only PBT_APMSUSPEND, if standby finally occurs. Why not - and how do i intercept it? 2) Is there another way to intercept the standby process? in a prefect world, i would set the lid-close event to run a command i choose. in a perfect world, lid-closure is a documented event. thank you all :-) A: I've found an ugly workaround: I wrote an AutoIt script which detects the Excel's error MessageBox, closes it, and runs a sysinternals' utility which forces the computer to standby. Opt("WinWaitDelay",400) ; -- exact text match, to save LOTS of cup cycles! Opt("WinTitleMatchMode",3) Opt("WinDetectHiddenText",1) Opt("MouseCoordMode",0) ; Opt("WinSearchChildren",1) dim $title = "Microsoft Excel" dim $text = "Windows cannot go on standby because Microsoft Office documents or application components are being accessed from the network. You must close the open documents or exit the applications before you can put the computer on standby." While True ; wait for excel's error msg WinWait($title, $text) Run("psshutdown.exe -c -d -accepteula -m mooshmoosh -t 5") ; the annoying msgbox doesn't close without the 'sleep' Sleep(1000) ; close the annoying modal msgbox! WinClose($title) ;1 minute delay, save cpu (?) Sleep(1*60*1000) WEnd (this is an optimized version - the first trials were CPU intensive). now it sits in the system-tray and just works. the lost messages question is still open. though i realized it has nothing to do with python in the first place.
how to hook to events / messages in windows using python
in short: i want to intercept suspend/standby messages on my laptop, but my program doesn't receives all relevant messages. background: there's a bug in ms-excel on windows xp/2k, which prevents system suspend if a file is opened on a network/usb drive. i'm trying to work-around it programmatically (my toolbox include python, vb6, or command line tools). i know nothing about windows instrumentation :-) i have a sysinternals utility that suspends the system anyhow. i want to hook it to the close-lid event! in long: The notebook lid close (fujitsu u810) initiate the standby procedure [how?] The system then send everybody WM_POWERBROADCAST: PBT_APMQUERYSUSPEND (i can trace them using SPYXX.EXE) Every program answers "True", until excel answers "false", and the whole process stops. My questions: 1) my python program doesn't catch neither pbm_apmquerysuspend, nor PBT_APMQUERYSTANDBYFAILED, nor PBT_APMQUERYSUSPENDFAILED: ` ... query = "SELECT * FROM Win32_PowerManagementEvent" power_watcher = wmi.ExecNotificationQuery ( query ) power_event = power_watcher.NextEvent () ` it receives only PBT_APMSUSPEND, if standby finally occurs. Why not - and how do i intercept it? 2) Is there another way to intercept the standby process? in a prefect world, i would set the lid-close event to run a command i choose. in a perfect world, lid-closure is a documented event. thank you all :-)
[ "I've found an ugly workaround:\nI wrote an AutoIt script which detects the Excel's error MessageBox, closes it, and runs a sysinternals' utility which forces the computer to standby.\n\nOpt(\"WinWaitDelay\",400)\n; -- exact text match, to save LOTS of cup cycles!\nOpt(\"WinTitleMatchMode\",3)\nOpt(\"WinDetectHiddenText\",1)\nOpt(\"MouseCoordMode\",0)\n; Opt(\"WinSearchChildren\",1)\ndim $title = \"Microsoft Excel\"\ndim $text = \"Windows cannot go on standby because Microsoft Office documents or application components are being accessed from the network. You must close the open documents or exit the applications before you can put the computer on standby.\"\nWhile True\n ; wait for excel's error msg\n WinWait($title, $text)\n Run(\"psshutdown.exe -c -d -accepteula -m mooshmoosh -t 5\")\n ; the annoying msgbox doesn't close without the 'sleep'\n Sleep(1000)\n ; close the annoying modal msgbox!\n WinClose($title)\n ;1 minute delay, save cpu (?)\n Sleep(1*60*1000)\nWEnd\n\n(this is an optimized version - the first trials were CPU intensive).\nnow it sits in the system-tray and just works.\nthe lost messages question is still open. though i realized it has nothing to do with python in the first place.\n" ]
[ 2 ]
[]
[]
[ "power_management", "python", "windows", "wmi" ]
stackoverflow_0000694475_power_management_python_windows_wmi.txt
Q: What is the best way to pass a method (with parameters) to another method in python What's the best way to pass a method and a method parameter to another method? Is there a better way to do the following? def method1(name) return 'Hello ' + name def method2(methodToCall, methodToCallParams, question): greetings = methodToCall(methodToCallParams) return greetings + ', ' + question method2(method1, 'Sam', 'How are you?') A: If you want to package the invocation up in one hit, you can use the functools module: from functools import partial def some_function(param_one, param_two): print "Param One: %s" % param_one print "Param Two: %s" % param_two def calling_function(target): target() calling_function(partial(some_function, "foo", "bar")) You can do tweakier things with functools.partial too, such as binding only some parameters, leaving you with a function with a new signature. It's overkill in a lot of cases to use it but it certainly has it's place. A: You could do it this way: def method1(name): def wrapper(): return 'Hello ' + name return wrapper def method2(method, question): output = method() return output + ', ' + question method2(method1(name = 'Sam'), 'How are you?') You can of course pass some variables in the method() call too: def method1(name): def wrapper(greeting): return greeting + name return wrapper def method2(method, question): output = method(greeting = 'Hello ') return output + ', ' + question method2(method1(name = 'Sam'), 'How are you?') A: You can used functools.partial to do this, as jkp pointed out However, functools is new in Python 2.5, so to handle this in the past I used the following code (this code is in the Python docs for functools.partial, in fact). # functools is Python 2.5 only, so we create a different partialfn if we are # running a version without functools available try: import functools partialfn = functools.partial except ImportError: def partialfn(func, *args, **keywords): def newfunc(*fargs, **fkeywords): newkeywords = keywords.copy() newkeywords.update(fkeywords) return func(*(args + fargs), **newkeywords) newfunc.func = func newfunc.args = args newfunc.keywords = keywords return newfunc A: Another option, if you are working on a Python version pre 2.5 is to use a lambda as a closure: def some_func(bar): print bar def call_other(other): other() call_other(lambda param="foo": some_func(param)) HTH A: You're thinking of currying, where you bind a function and arguments together to be called later. Usually currying is used so that you can add additional arguments at the time the function is actually called. Rather than re-write the wheel, here's a link to an example: http://code.activestate.com/recipes/52549/. If, however, the case you've mocked up in the question really is that simple, you can pass a list of args as positional parameters, or a list of kwargs as named parameters, to another function. def method1(name): return 'Hello %s' % name args = ['Joe'] method1(*args) def method1a(name=None, salutation=None): return 'Hello %s %s' % (name, salutation) kwargs = {'name':'Joe', 'salutation':'Mr'} method1a(**kwargs)
What is the best way to pass a method (with parameters) to another method in python
What's the best way to pass a method and a method parameter to another method? Is there a better way to do the following? def method1(name) return 'Hello ' + name def method2(methodToCall, methodToCallParams, question): greetings = methodToCall(methodToCallParams) return greetings + ', ' + question method2(method1, 'Sam', 'How are you?')
[ "If you want to package the invocation up in one hit, you can use the functools module:\nfrom functools import partial\n\ndef some_function(param_one, param_two):\n print \"Param One: %s\" % param_one\n print \"Param Two: %s\" % param_two\n\ndef calling_function(target):\n target()\n\ncalling_function(partial(some_function, \"foo\", \"bar\"))\n\nYou can do tweakier things with functools.partial too, such as binding only some parameters, leaving you with a function with a new signature. It's overkill in a lot of cases to use it but it certainly has it's place.\n", "You could do it this way:\ndef method1(name):\n def wrapper():\n return 'Hello ' + name\n return wrapper\n\ndef method2(method, question):\n output = method()\n return output + ', ' + question\n\nmethod2(method1(name = 'Sam'), 'How are you?')\n\nYou can of course pass some variables in the method() call too:\ndef method1(name):\n def wrapper(greeting):\n return greeting + name\n return wrapper\n\ndef method2(method, question):\n output = method(greeting = 'Hello ')\n return output + ', ' + question\n\nmethod2(method1(name = 'Sam'), 'How are you?')\n\n", "You can used functools.partial to do this, as jkp pointed out\nHowever, functools is new in Python 2.5, so to handle this in the past I used the following code (this code is in the Python docs for functools.partial, in fact).\n# functools is Python 2.5 only, so we create a different partialfn if we are\n# running a version without functools available\ntry:\n import functools\n partialfn = functools.partial\nexcept ImportError:\n def partialfn(func, *args, **keywords):\n def newfunc(*fargs, **fkeywords):\n newkeywords = keywords.copy()\n newkeywords.update(fkeywords)\n return func(*(args + fargs), **newkeywords)\n newfunc.func = func\n newfunc.args = args\n newfunc.keywords = keywords\n return newfunc\n\n", "Another option, if you are working on a Python version pre 2.5 is to use a lambda as a closure:\ndef some_func(bar):\n print bar\n\ndef call_other(other):\n other()\n\ncall_other(lambda param=\"foo\": some_func(param))\n\nHTH\n", "You're thinking of currying, where you bind a function and arguments together to be called later. Usually currying is used so that you can add additional arguments at the time the function is actually called.\nRather than re-write the wheel, here's a link to an example: http://code.activestate.com/recipes/52549/.\nIf, however, the case you've mocked up in the question really is that simple, you can pass a list of args as positional parameters, or a list of kwargs as named parameters, to another function.\ndef method1(name):\n return 'Hello %s' % name\n\nargs = ['Joe']\nmethod1(*args)\n\ndef method1a(name=None, salutation=None):\n return 'Hello %s %s' % (name, salutation)\n\nkwargs = {'name':'Joe', 'salutation':'Mr'}\nmethod1a(**kwargs)\n\n" ]
[ 11, 3, 2, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0000706813_python.txt
Q: Python: import the containing package In a module residing inside a package, i have the need to use a function defined within the __init__.py of that package. how can i import the package within the module that resides within the package, so i can use that function? Importing __init__ inside the module will not import the package, but instead a module named __init__, leading to two copies of things with different names... Is there a pythonic way to do this? A: Also, starting in Python 2.5, relative imports are possible. e.g.: from . import foo Quoting from http://docs.python.org/tutorial/modules.html#intra-package-references: Starting with Python 2.5, in addition to the implicit relative imports described above, you can write explicit relative imports with the from module import name form of import statement. These explicit relative imports use leading dots to indicate the current and parent packages involved in the relative import. From the surrounding module for example, you might use: from . import echo from .. import formats from ..filters import equalizer A: This doesn't exactly answer your question, but I'm going to suggest that you move the function outside of the __init__.py file, and into another module inside that package. You can then easily import that function into your other module. If you want, you can have an import statement in the __init__.py file that will import that function (when the package is imported) as well. A: If the package is named testmod and your init file is therefore testmod/__init__.py and your module within the package is submod.py then from within submod.py file, you should just be able to say import testmod and use whatever you want that's defined in testmod. A: I'm not totally sure what the situation is, but this may solve your "different name" problem: import __init__ as top top.some_function() Or maybe?: from __init__ import some_function some_function() A: In Django, the file manage.py has from django.core.management import execute_manager, but execute_manager is not a module. It is a function within the __init__.py module of the management directory.
Python: import the containing package
In a module residing inside a package, i have the need to use a function defined within the __init__.py of that package. how can i import the package within the module that resides within the package, so i can use that function? Importing __init__ inside the module will not import the package, but instead a module named __init__, leading to two copies of things with different names... Is there a pythonic way to do this?
[ "Also, starting in Python 2.5, relative imports are possible. e.g.:\nfrom . import foo\n\nQuoting from http://docs.python.org/tutorial/modules.html#intra-package-references:\n\nStarting with Python 2.5, in addition to the implicit relative imports described above, you can write explicit relative imports with the from module import name form of import statement. These explicit relative imports use leading dots to indicate the current and parent packages involved in the relative import. From the surrounding module for example, you might use:\nfrom . import echo\nfrom .. import formats\nfrom ..filters import equalizer\n\n", "This doesn't exactly answer your question, but I'm going to suggest that you move the function outside of the __init__.py file, and into another module inside that package. You can then easily import that function into your other module. If you want, you can have an import statement in the __init__.py file that will import that function (when the package is imported) as well.\n", "If the package is named testmod and your init file is therefore testmod/__init__.py and your module within the package is submod.py then from within submod.py file, you should just be able to say import testmod and use whatever you want that's defined in testmod.\n", "I'm not totally sure what the situation is, but this may solve your \"different name\" problem:\nimport __init__ as top\ntop.some_function()\n\nOr maybe?:\nfrom __init__ import some_function\nsome_function()\n\n", "In Django, the file manage.py has from django.core.management import execute_manager, but execute_manager is not a module. It is a function within the __init__.py module of the management directory.\n" ]
[ 48, 23, 5, 1, 1 ]
[]
[]
[ "module", "package", "python", "python_import" ]
stackoverflow_0000436497_module_package_python_python_import.txt
Q: Debugging a running python process Is there a way to see a stacktrace of what various threads are doing inside a python process? Let's suppose I have a thread which allows me some sort of remote access to the process. A: Winpdb is a platform independent graphical GPL Python debugger with support for remote debugging over a network, multiple threads, namespace modification, embedded debugging, encrypted communication and is up to 20 times faster than pdb. Features: GPL license. Winpdb is Free Software. Compatible with CPython 2.3 through 2.6 and Python 3000 Compatible with wxPython 2.6 through 2.8 Platform independent, and tested on Ubuntu Gutsy and Windows XP. User Interfaces: rpdb2 is console based, while winpdb requires wxPython 2.6 or later. (source: winpdb.org) A: About 4 years ago, when I was using twisted, manhole was a great way to do what you're asking. http://twistedmatrix.com/projects/core/documentation/howto/telnet.html Right now most of my projects don't use twisted, so I just WingIDE's remote debugging hooks to introspect a running process. http://www.wingware.com/doc/debug/remote-debugging
Debugging a running python process
Is there a way to see a stacktrace of what various threads are doing inside a python process? Let's suppose I have a thread which allows me some sort of remote access to the process.
[ "Winpdb is a platform independent graphical GPL Python debugger with support for remote debugging over a network, multiple threads, namespace modification, embedded debugging, encrypted communication and is up to 20 times faster than pdb.\nFeatures:\n\nGPL license. Winpdb is Free Software.\nCompatible with CPython 2.3 through 2.6 and Python 3000\nCompatible with wxPython 2.6 through 2.8\nPlatform independent, and tested on Ubuntu Gutsy and Windows XP.\nUser Interfaces: rpdb2 is console based, while winpdb requires wxPython 2.6 or later.\n\n\n(source: winpdb.org) \n", "About 4 years ago, when I was using twisted, manhole was a great way to do what you're asking.\nhttp://twistedmatrix.com/projects/core/documentation/howto/telnet.html\nRight now most of my projects don't use twisted, so I just WingIDE's remote debugging hooks to introspect a running process.\nhttp://www.wingware.com/doc/debug/remote-debugging\n" ]
[ 6, 2 ]
[]
[]
[ "python", "remote_debugging" ]
stackoverflow_0000707999_python_remote_debugging.txt
Q: Decorators and in class Is there any way to write decorators within a class structure that nest well? For example, this works fine without classes: def wrap1(func): def loc(*args,**kwargs): print 1 return func(*args,**kwargs) return loc def wrap2(func): def loc(*args,**kwargs): print 2 return func(*args,**kwargs) return loc def wrap3(func): def loc(*args,**kwargs): print 3 return func(*args,**kwargs) return loc def merger(func): return wrap1(wrap2(wrap3(func))) @merger def merged(): print "merged" @wrap1 @wrap2 @wrap3 def individually_wrapped(): print "individually wrapped" merged() individually_wrapped() The output is: 1 2 3 merged 1 2 3 individually wrapped which is what I want. But now let's say that I want to make merged and individually_wrapped as static or class methods. This will also work, so long as the decorators are kept out of the class namespace. Is there any good way to put the decorators within the namespace? I'd rather not enumerate all the ways that won't work, but the main problem is that if merger is a method, it can't access the wrapX methods. Maybe this is a stupid thing to want to do, but has anyone gotten something like this to work, with all the decorators and decorated methods in the same class? A: "Is there any good way to put the decorators within the namespace?" There's no compelling reason for this. You have module files. Those are a tidy container for a class and some decorators. You don't ever need decorators as methods of the class -- you can just call one method from another. A: Actually, there should be no problem putting them all inside of a class. When inside of a class body, you can name any variable defined so far simply by naming it: class A(object): a = 1 b = 2 c = a + b print A.c That yields the result 3, because while Python is executing a class body the functions can "see" the variables a and b that have been declared. So the following also works: class B(object): @staticmethod def wrapper(*args, **kw): ... @wrapper def a(...): ... Now, what about your merger function? The problem is that the wrapper function gets run long after the class body is done executing, and the variables it defined are no longer in the enclosing scope. How can you refer to them, then? By using the name of the class as a prefix! Like this: class C(object): @staticmethod def wrap1(*args, **kw): ... @staticmethod def wrap2(*args, **kw): ... @staticmethod def wrap3(*args, **kw): ... @staticmethod def merger(*args, **kw): C.wrap1(C.wrap2(C.wrap3(...))) @merger def plain(...): ... So the general rule with Python is: code that runs right at the level of the class body can talk about all the variables and methods that have been defined so far inside of it, and this means you can use those class variables as wrappers. But once you are "inside" of a function in the class, whether it's a class function, a static function, or a method (and this wrapper is a class method since it takes args but no "self), then you have to use the name of the class to "get at" its contents.
Decorators and in class
Is there any way to write decorators within a class structure that nest well? For example, this works fine without classes: def wrap1(func): def loc(*args,**kwargs): print 1 return func(*args,**kwargs) return loc def wrap2(func): def loc(*args,**kwargs): print 2 return func(*args,**kwargs) return loc def wrap3(func): def loc(*args,**kwargs): print 3 return func(*args,**kwargs) return loc def merger(func): return wrap1(wrap2(wrap3(func))) @merger def merged(): print "merged" @wrap1 @wrap2 @wrap3 def individually_wrapped(): print "individually wrapped" merged() individually_wrapped() The output is: 1 2 3 merged 1 2 3 individually wrapped which is what I want. But now let's say that I want to make merged and individually_wrapped as static or class methods. This will also work, so long as the decorators are kept out of the class namespace. Is there any good way to put the decorators within the namespace? I'd rather not enumerate all the ways that won't work, but the main problem is that if merger is a method, it can't access the wrapX methods. Maybe this is a stupid thing to want to do, but has anyone gotten something like this to work, with all the decorators and decorated methods in the same class?
[ "\"Is there any good way to put the decorators within the namespace?\"\nThere's no compelling reason for this. You have module files. Those are a tidy container for a class and some decorators. \nYou don't ever need decorators as methods of the class -- you can just call one method from another. \n", "Actually, there should be no problem putting them all inside of a class. When inside of a class body, you can name any variable defined so far simply by naming it:\n\nclass A(object):\n a = 1\n b = 2\n c = a + b\n\nprint A.c\n\nThat yields the result 3, because while Python is executing a class body the functions can \"see\" the variables a and b that have been declared. So the following also works:\n\nclass B(object):\n @staticmethod\n def wrapper(*args, **kw):\n ...\n\n @wrapper\n def a(...):\n ...\n\nNow, what about your merger function? The problem is that the wrapper function gets run long after the class body is done executing, and the variables it defined are no longer in the enclosing scope. How can you refer to them, then? By using the name of the class as a prefix! Like this:\n\nclass C(object):\n @staticmethod\n def wrap1(*args, **kw):\n ...\n @staticmethod\n def wrap2(*args, **kw):\n ...\n @staticmethod\n def wrap3(*args, **kw):\n ...\n @staticmethod\n def merger(*args, **kw):\n C.wrap1(C.wrap2(C.wrap3(...)))\n\n @merger\n def plain(...):\n ...\n\nSo the general rule with Python is: code that runs right at the level of the class body can talk about all the variables and methods that have been defined so far inside of it, and this means you can use those class variables as wrappers. But once you are \"inside\" of a function in the class, whether it's a class function, a static function, or a method (and this wrapper is a class method since it takes args but no \"self), then you have to use the name of the class to \"get at\" its contents.\n" ]
[ 5, 2 ]
[]
[]
[ "decorator", "python" ]
stackoverflow_0000707090_decorator_python.txt
Q: Python comments: # vs. strings Regarding the "standard" way to put comments inside Python source code: def func(): "Func doc" ... <code> 'TODO: fix this' #badFunc() ... <more code> def func(): "Func doc" ... <code> #TODO: fix this #badFunc() ... <more code> I prefer to write general comments as strings instead of prefixing #'s. The official Python style guide doesn't mention using strings as comments (If I didn't miss it while reading it). I like it that way mainly because I think the # character looks ugly with comment blocks. As far as I know these strings don't do anything. Are there disadvantages in doing this? A: Don't misuse strings (no-op statements) as comments. Docstrings, e.g. the first string in a module, class or function, are special and definitely recommended. Note that docstrings are documentation, and documentation and comments are two different things! Documentation is important to understand what the code does. Comments explain how the code does it. Documentation is read by people who use your code, comments by people who want to understand your code, e.g. to maintain it. Using strings for commentation has the following (potential) disadvantages: It confuses people who don't know that the string does nothing. Comments and string literals are highlighted differently in code editors, so your style may make your code harder to read. It might affect performance and/or memory usage (if the strings are not removed during bytecode compilation, removing comments is done on the scanner level so it's definitively cheaper) Most important for Python programmers: It is not pythonic: There should be one—and preferably only one—obvious way to do it. Stick to the standards, use comments. A: I think that only the first string literal in a definition (or class) is "special", i.e. gets stored by the interpreter into the defined object's (or class') docstring. Any other string literals you place in the code will, at the worst, mean the interpreter will build the string value at run-time, and then just throw it away. This means that doing "comments" by littering the code with string constants might cost, performance-wise. Of course, I have not benchmarked this, and also don't know the Python interpreter well enough to say for sure. A: The disadvantage, of course, is that someone else reading it will find that the code strings and comment strings are interleaved, which could be confusing.
Python comments: # vs. strings
Regarding the "standard" way to put comments inside Python source code: def func(): "Func doc" ... <code> 'TODO: fix this' #badFunc() ... <more code> def func(): "Func doc" ... <code> #TODO: fix this #badFunc() ... <more code> I prefer to write general comments as strings instead of prefixing #'s. The official Python style guide doesn't mention using strings as comments (If I didn't miss it while reading it). I like it that way mainly because I think the # character looks ugly with comment blocks. As far as I know these strings don't do anything. Are there disadvantages in doing this?
[ "Don't misuse strings (no-op statements) as comments. Docstrings, e.g. the first string in a module, class or function, are special and definitely recommended.\nNote that docstrings are documentation, and documentation and comments are two different things!\n\nDocumentation is important to understand what the code does.\nComments explain how the code does it.\n\nDocumentation is read by people who use your code, comments by people who want to understand your code, e.g. to maintain it.\nUsing strings for commentation has the following (potential) disadvantages:\n\nIt confuses people who don't know that the string does nothing.\nComments and string literals are highlighted differently in code editors, so your style may make your code harder to read.\nIt might affect performance and/or memory usage (if the strings are not removed during bytecode compilation, removing comments is done on the scanner level so it's definitively cheaper)\n\nMost important for Python programmers: It is not pythonic:\n\nThere should be one—and preferably only one—obvious way to do it.\n\nStick to the standards, use comments.\n", "I think that only the first string literal in a definition (or class) is \"special\", i.e. gets stored by the interpreter into the defined object's (or class') docstring.\nAny other string literals you place in the code will, at the worst, mean the interpreter will build the string value at run-time, and then just throw it away. This means that doing \"comments\" by littering the code with string constants might cost, performance-wise.\nOf course, I have not benchmarked this, and also don't know the Python interpreter well enough to say for sure.\n", "The disadvantage, of course, is that someone else reading it will find that the code strings and comment strings are interleaved, which could be confusing.\n" ]
[ 67, 6, 6 ]
[]
[]
[ "python" ]
stackoverflow_0000708649_python.txt
Q: Create a standalone windows exe which does not require pythonXX.dll is there a way to create a standalone .exe from a python script. Executables generated with py2exe can run only with pythonXX.dll. I'd like to obtain a fully standalone .exe which does not require to install the python runtime library. It looks like a linking problem but using static library instead the dynamic one and it would be also useful to apply a strip in order to remove the unused symbols. Any idea ? Thanks. Alessandro A: You can do this in the latest version of py2exe... Just add something like the code below in your setup.py file (key part is 'bundle_files': 1). To include your TkInter package in the install, use the 'includes' key. distutils.core.setup( windows=[ {'script': 'yourmodule.py', 'icon_resources': [(1, 'moduleicon.ico')] } ], zipfile=None, options={'py2exe':{ 'includes': ['tkinter'], 'bundle_files': 1 } } ) A: Due to how Windows' dynamic linker works you cannot use the static library if you use .pyd or .dll Python modules; DLLs loaded in Windows do not automatically share their symbol space with the executable and so require a separate DLL containing the Python symbols. A: If your purpose of having a single executable is to ease downloading/emailing, etc., I've solved this by bundling the py2exe output using Inno Setup. This is actually better than having a single executable, because rather than providing an executable file that can be dropped into some directory, a well behaved Windows application will provide an uninstaller, show up in the Add/Remove Programs applet, etc. Inno handles all this for you. A: Another solution is to create a single exe with python and all your dependencies installed inside of it, including the python.dll. There's a bit of magic in the wrapper, but it just works. The details are here: http://code.google.com/p/pylunch/downloads/detail?name=PyLunch-0.2.pdf A: This is not the best way to do it, but you might consider using executable SFX Archive with both the .exe and .dll files inside, and setting it to execute your .exe file when it's double clicked.
Create a standalone windows exe which does not require pythonXX.dll
is there a way to create a standalone .exe from a python script. Executables generated with py2exe can run only with pythonXX.dll. I'd like to obtain a fully standalone .exe which does not require to install the python runtime library. It looks like a linking problem but using static library instead the dynamic one and it would be also useful to apply a strip in order to remove the unused symbols. Any idea ? Thanks. Alessandro
[ "You can do this in the latest version of py2exe... Just add something like the code below in your setup.py file (key part is 'bundle_files': 1).\nTo include your TkInter package in the install, use the 'includes' key.\ndistutils.core.setup(\n windows=[\n {'script': 'yourmodule.py',\n 'icon_resources': [(1, 'moduleicon.ico')]\n }\n ],\n zipfile=None,\n options={'py2exe':{\n 'includes': ['tkinter'],\n 'bundle_files': 1\n }\n }\n )\n\n", "Due to how Windows' dynamic linker works you cannot use the static library if you use .pyd or .dll Python modules; DLLs loaded in Windows do not automatically share their symbol space with the executable and so require a separate DLL containing the Python symbols.\n", "If your purpose of having a single executable is to ease downloading/emailing, etc., I've solved this by bundling the py2exe output using Inno Setup. This is actually better than having a single executable, because rather than providing an executable file that can be dropped into some directory, a well behaved Windows application will provide an uninstaller, show up in the Add/Remove Programs applet, etc. Inno handles all this for you.\n", "Another solution is to create a single exe with python and all your dependencies installed inside of it, including the python.dll. There's a bit of magic in the wrapper, but it just works. The details are here: \nhttp://code.google.com/p/pylunch/downloads/detail?name=PyLunch-0.2.pdf\n", "This is not the best way to do it, but you might consider using executable SFX Archive with both the .exe and .dll files inside, and setting it to execute your .exe file when it's double clicked.\n" ]
[ 17, 5, 4, 2, 1 ]
[]
[]
[ "py2exe", "python", "windows" ]
stackoverflow_0000707242_py2exe_python_windows.txt
Q: web.py: passing initialization / global variables to handler classes? I'm attempting to use web.py with Tokyo Cabinet / pytc and need to pass the db handle (the connection to tokyo cabinet) to my handler classes so they can talk to tokyo cabinet. Is there a way to pass the handler to the handler class's init function? Or should I be putting the handle in globals() ? What is globals() and how do you use it? A: The best way would be to add a load hook (described here for sqlalchemy). Define a function that connects to Tokyo Cabinet and adds the resulting db object as an .orm attribute to web.ctx, which is always available inside the controller.
web.py: passing initialization / global variables to handler classes?
I'm attempting to use web.py with Tokyo Cabinet / pytc and need to pass the db handle (the connection to tokyo cabinet) to my handler classes so they can talk to tokyo cabinet. Is there a way to pass the handler to the handler class's init function? Or should I be putting the handle in globals() ? What is globals() and how do you use it?
[ "The best way would be to add a load hook (described here for sqlalchemy). Define a function that connects to Tokyo Cabinet and adds the resulting db object as an .orm attribute to web.ctx, which is always available inside the controller.\n" ]
[ 2 ]
[]
[]
[ "python", "web.py" ]
stackoverflow_0000707841_python_web.py.txt
Q: python code convention using pylint I'm trying out pylint to check my source code for conventions. Somehow some variable names are matched with the regex for constants (const-rgx) instead of the variable name regex (variable-rgx). How to match the variable name with variable-rgx? Or should I extend const-rgx with my variable-rgx stuff? e.g. C0103: 31: Invalid name "settings" (should match (([A-Z_][A-Z1-9_]*)|(__.*__))$) A: Somehow some variable names are matched with the regex for constants (const-rgx) instead of the variable name regex (variable-rgx). Are those variables declared on module level? Maybe that's why they are treated as constants (at least that's how they should be declared, according to PEP-8). A: I just disable that warning because I don't follow those naming conventions. To do that, add this line to the top of you module: # pylint: disable-msg=C0103 If you want to disable that globally, then add it to the pylint command: python lint.py --disable-msg=C0103 ... A: (should match (([A-Z_][A-Z1-9_]*)|(__.*__))$) like you said that is the const-rgx that is only matching UPPERCASE names, or names surrounded by double underscores. the variables-rgx is ([a-z_][a-z0-9_]{2,30}$) if your variable is called 'settings' that indeed should match the variables-rgx I can think of only 2 reasons for this.. either settings is a constant or it is a bug in PyLint.
python code convention using pylint
I'm trying out pylint to check my source code for conventions. Somehow some variable names are matched with the regex for constants (const-rgx) instead of the variable name regex (variable-rgx). How to match the variable name with variable-rgx? Or should I extend const-rgx with my variable-rgx stuff? e.g. C0103: 31: Invalid name "settings" (should match (([A-Z_][A-Z1-9_]*)|(__.*__))$)
[ "\nSomehow some variable names are matched with the regex for constants (const-rgx) instead of the variable name regex (variable-rgx).\n\nAre those variables declared on module level? Maybe that's why they are treated as constants (at least that's how they should be declared, according to PEP-8).\n", "I just disable that warning because I don't follow those naming conventions.\nTo do that, add this line to the top of you module:\n# pylint: disable-msg=C0103\n\nIf you want to disable that globally, then add it to the pylint command:\npython lint.py --disable-msg=C0103 ...\n\n", "\n(should match (([A-Z_][A-Z1-9_]*)|(__.*__))$)\n\nlike you said that is the const-rgx that is only matching UPPERCASE names, or names surrounded by double underscores.\nthe variables-rgx is \n([a-z_][a-z0-9_]{2,30}$)\nif your variable is called 'settings' that indeed should match the variables-rgx\nI can think of only 2 reasons for this..\neither settings is a constant or it is a bug in PyLint.\n" ]
[ 27, 10, 0 ]
[]
[]
[ "conventions", "pylint", "python" ]
stackoverflow_0000709490_conventions_pylint_python.txt
Q: Accessing a MySQL database from python I have been trying for the past several hours to find a working method of accessing a mysql database in python. The only thing that I've managed to get to compile and install is pyodbc but the necessary driver is not available for ppc leopard. I already know about this. UPDATE: I've gotten setuptools to install, but now MySQL-python won't build. UPDATE: Now I've gotten sqlalchemy to install but while it will show up when called by the command line it won't import when used in my cgi script. A: Try SQL Alchemy. It is awesome. A: Install fink. It includes the MySQLdb package. A: UPDATE: Now I've gotten sqlalchemy to install but while it will show up when called by the command line it won't import when used in my cgi script. Can you verify that the Python being invoked from your CGI script is the same as the one you get when you run Python interactively? Check which python and compare it to your webserver CGI settings. That's the only thing I can think of that would cause this - getting it installed in one Python but not the other. What OS are you on? If you're on something like Ubuntu, sudo apt-get install python-mysqldb is much more reliable than trying to build it yourself. Also, unless I'm mistaken, SQLAlchemy won't actually help you make the connection itself if you don't have a DB-API2 module (like python-mysqldb) installed - SQLAlchemy sits at the next level up, using the DB-API2 connection and making access to it more Pythonic.
Accessing a MySQL database from python
I have been trying for the past several hours to find a working method of accessing a mysql database in python. The only thing that I've managed to get to compile and install is pyodbc but the necessary driver is not available for ppc leopard. I already know about this. UPDATE: I've gotten setuptools to install, but now MySQL-python won't build. UPDATE: Now I've gotten sqlalchemy to install but while it will show up when called by the command line it won't import when used in my cgi script.
[ "Try SQL Alchemy.\nIt is awesome.\n", "Install fink. It includes the MySQLdb package.\n", "\nUPDATE: Now I've gotten sqlalchemy to\n install but while it will show up when\n called by the command line it won't\n import when used in my cgi script.\n\nCan you verify that the Python being invoked from your CGI script is the same as the one you get when you run Python interactively? Check which python and compare it to your webserver CGI settings. That's the only thing I can think of that would cause this - getting it installed in one Python but not the other.\nWhat OS are you on? If you're on something like Ubuntu, sudo apt-get install python-mysqldb is much more reliable than trying to build it yourself.\nAlso, unless I'm mistaken, SQLAlchemy won't actually help you make the connection itself if you don't have a DB-API2 module (like python-mysqldb) installed - SQLAlchemy sits at the next level up, using the DB-API2 connection and making access to it more Pythonic.\n" ]
[ 2, 1, 0 ]
[]
[]
[ "database", "mysql", "python" ]
stackoverflow_0000621156_database_mysql_python.txt
Q: Is there a Perl equivalent to Python's `if __name__ == '__main__'`? Is there a way to determine if the current file is the one being executed in Perl source? In Python we do this with the following construct: if __name__ == '__main__': # This file is being executed. raise NotImplementedError I can hack something together using FindBin and __FILE__, but I'm hoping there's a canonical way of doing this. Thanks! A: unless (caller) { print "This is the script being executed\n"; } See caller. It returns undef in the main script. Note that that doesn't work inside a subroutine, only in top-level code. A: See the "Subclasses for Applications (Chapter 18)" portion of brian d foy's article Five Ways to Improve Your Perl Programming. A: unless caller is good, but a more direct parallel, as well as a more explicit check, is: use English qw<$PROGRAM_NAME>; if ( $PROGRAM_NAME eq __FILE__ ) { ... } Just thought I'd put that out there. EDIT Keep in mind that $PROGRAM_NAME (or '$0') is writable, so this is not absolute. But, in most practice--except on accident, or rampaging modules--this likely won't be changed, or changed at most locally within another scope.
Is there a Perl equivalent to Python's `if __name__ == '__main__'`?
Is there a way to determine if the current file is the one being executed in Perl source? In Python we do this with the following construct: if __name__ == '__main__': # This file is being executed. raise NotImplementedError I can hack something together using FindBin and __FILE__, but I'm hoping there's a canonical way of doing this. Thanks!
[ "unless (caller) {\n print \"This is the script being executed\\n\";\n}\n\nSee caller. It returns undef in the main script. Note that that doesn't work inside a subroutine, only in top-level code.\n", "See the \"Subclasses for Applications (Chapter 18)\" portion of brian d foy's article Five Ways to Improve Your Perl Programming.\n", "unless caller is good, but a more direct parallel, as well as a more explicit check, is: \nuse English qw<$PROGRAM_NAME>;\n\nif ( $PROGRAM_NAME eq __FILE__ ) { \n ...\n}\n\nJust thought I'd put that out there.\nEDIT \nKeep in mind that $PROGRAM_NAME (or '$0') is writable, so this is not absolute. But, in most practice--except on accident, or rampaging modules--this likely won't be changed, or changed at most locally within another scope. \n" ]
[ 49, 10, 4 ]
[]
[]
[ "executable", "perl", "python" ]
stackoverflow_0000707022_executable_perl_python.txt
Q: Python server side AJAX library? I want to have a browser page that updates some information on a timer or events. I'd like to use Python on the server side. It's quite simple, I don't need anything massively complex. I can spend some time figuring out how to do all this the "AJAX way", but I'm sure someone has written a nice Python library to do all the heavy lifting. If you have used such a library please let me know the details. Note: I saw how-to-implement-a-minimal-server-for-ajax-in-python but I want a library to hide the implementation details. A: AJAX stands for Asynchronous JavaScript and XML. You don't need any special library, other than the Javascript installed on the browser to do AJAX calls. The AJAX requests comes from the client side Javascript code, and goes to the server side which in your case would be handled in python. You probably want to use the Django web framework. Check out this tutorial on Django tips: A simple AJAX example. Here is a simple client side tutorial on XmlHTTPRequest / AJAX A: You can also write both the client and server side of the ajax code using python with pyjamas: Here's an RPC style server and simple example: http://www.machine-envy.com/blog/2006/12/10/howto-pyjamas-pylons-json/ Lots of people use it with Django, but as the above example shows it will work fine with Pylons, and can be used with TurboGears2 just as easily. I'm generally in favor of learning enough javascript to do this kind of thing yourself, but if your problem fits what pygjamas can do, you'll get results from that very quickly and easily. A: I suggest you to implement the server part in Django, which is in my opinion a fantastic toolkit. Through Django, you produce your XML responses (although I suggest you to use JSON, which is easier to handle on the web browser side). Once you have something that generates your reply on server side, you have to code the javascript code that invokes it (through the asynchronous call), gets the result (in JSON) and uses it to do something clever on the DOM tree of the page. For this, you need a JavaScript library. I did some experience with various javascript libraries for "Web 2.0". Scriptaculous is cool, and Dojo as well, but my absolute favourite is MochiKit, because they focus on a syntax which is very pythonic, so it will hide you quite well the differences between javascript and python.
Python server side AJAX library?
I want to have a browser page that updates some information on a timer or events. I'd like to use Python on the server side. It's quite simple, I don't need anything massively complex. I can spend some time figuring out how to do all this the "AJAX way", but I'm sure someone has written a nice Python library to do all the heavy lifting. If you have used such a library please let me know the details. Note: I saw how-to-implement-a-minimal-server-for-ajax-in-python but I want a library to hide the implementation details.
[ "AJAX stands for Asynchronous JavaScript and XML. You don't need any special library, other than the Javascript installed on the browser to do AJAX calls. The AJAX requests comes from the client side Javascript code, and goes to the server side which in your case would be handled in python.\nYou probably want to use the Django web framework.\nCheck out this tutorial on Django tips: A simple AJAX example. \nHere is a simple client side tutorial on XmlHTTPRequest / AJAX\n", "You can also write both the client and server side of the ajax code using python with pyjamas:\nHere's an RPC style server and simple example:\nhttp://www.machine-envy.com/blog/2006/12/10/howto-pyjamas-pylons-json/\nLots of people use it with Django, but as the above example shows it will work fine with Pylons, and can be used with TurboGears2 just as easily. \nI'm generally in favor of learning enough javascript to do this kind of thing yourself, but if your problem fits what pygjamas can do, you'll get results from that very quickly and easily. \n", "I suggest you to implement the server part in Django, which is in my opinion a fantastic toolkit. Through Django, you produce your XML responses (although I suggest you to use JSON, which is easier to handle on the web browser side).\nOnce you have something that generates your reply on server side, you have to code the javascript code that invokes it (through the asynchronous call), gets the result (in JSON) and uses it to do something clever on the DOM tree of the page. For this, you need a JavaScript library.\nI did some experience with various javascript libraries for \"Web 2.0\". Scriptaculous is cool, and Dojo as well, but my absolute favourite is MochiKit, because they focus on a syntax which is very pythonic, so it will hide you quite well the differences between javascript and python.\n" ]
[ 5, 5, 1 ]
[]
[]
[ "ajax", "python" ]
stackoverflow_0000709868_ajax_python.txt