text
stringlengths
226
34.5k
HTTPS for Mercurial 1.9.2 on windows server 2008/IIS 7 giving me Errno 10054 Question: We are a small company (its a Microsoft shop) we are currently using subversion with VisualSVN installed (pretty easy to setup btw) I am currently evaluating Mercurial because of branching nightmare in svn. So first i followed <http://www.firegarden.com/software/hosting-mercurial- repo-iis7-windows-server-2008r2-x64-python-isapi-cgi> with latest mercurial source code 1.9.2 and python 2.7 got the below error Failed to import callback module 'hgwebdir_wsgi' The specified module could not be found. so i **scratched** that and then i followed this <http://www.jeremyskinner.co.uk/mercurial-on-iis7/> and it worked until i reached the step **Enabling SSL** which is where the problem is. i even setup ssl certs using OpenSSL <http://www.dylanbeattie.net/docs/openssl_iis_ssl_howto.html> still nothing. this is the error i get URLError: [Errno 10054] An existing connection was forcibly closed by the remote host [command returned code 255...] Server side i have this hgweb.config [collections] C:\repository\hg = C:/repository/hg [web] #push_ssl = false allow_push = * baseurl = /hg cacerts = web.config <?xml version="1.0" encoding="UTF-8"?> <configuration> <system.webServer> <handlers> <add name="Python" path="*.cgi" verb="*" modules="CgiModule" scriptProcessor="C:\Python27\python.exe -u &quot;%s&quot;" resourceType="Unspecified" /> </handlers> <rewrite> <rules> <rule name="rewrite to hgweb" patternSyntax="Wildcard"> <match url="*" /> <conditions> <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" /> </conditions> <action type="Rewrite" url="hgweb.cgi/{R:1}" /> </rule> </rules> </rewrite> <security> <requestFiltering> <requestLimits maxAllowedContentLength ="2147482624" /> </requestFiltering> </security> </system.webServer> <system.web> <httpRuntime executionTimeout="540000" maxRequestLength="2097151"/> </system.web> client side hgrc [paths] default = https://webtest/hg/test/ [hostfingerprints] webtest = 50:de:a4:d9:72:59:68:fd:91 ... **EDIT** I tried to install MacHg on my macbook to test. i used <http://machghelp.jasonfharris.com/kb/connections/how-do-i-add-a-server- certificate-or-fingerprint-for-https> as walkthrough and it WORKS!! so this eliminates server(i.e.server can push & pull from both http & https) so now i am sure its my windows/TortoiseHg which has problem. (but following these steps for tortoiseHg gives me nothing :( ) **EDIT2** One more finding... i can't even clone using https, it only works for http. I tried to clone one of codeplex projects using https and that works!...This is really frustrating Am i missing something? any help will be appreciated. Answer: Setting up certificates with Mercurial is described in <http://mercurial.selenic.com/wiki/CACertificates> On this page there is that note that says "use openssl, not IIS, to generate certificates" - apparently an IIS7 self-signed certificates does not validate in the SSL library used by Mercurial. If you install TortoiseHg, your Mercurial certificates will be read from hgrc.d/cacert.pm. This means you must add your self-signed certificate here. Otherwise, the most efficient way to get help troubleshooting your installation is via [Mercurial IRC](http://mercurial.selenic.com/wiki/IRC)
Python RegEx nested search and replace Question: I need to to a RegEx search and replace of all commas found inside of quote blocks. i.e. "thing1,blah","thing2,blah","thing3,blah",thing4 needs to become "thing1\,blah","thing2\,blah","thing3\,blah",thing4 my code: inFile = open(inFileName,'r') inFileRl = inFile.readlines() inFile.close() p = re.compile(r'["]([^"]*)["]') for line in inFileRl: pg = p.search(line) # found comment block if pg: q = re.compile(r'[^\\],') # found comma within comment block qg = q.search(pg.group(0)) if qg: # Here I want to reconstitute the line and print it with the replaced text #print re.sub(r'([^\\])\,',r'\1\,',pg.group(0)) I need to filter only the columns I want based on a RegEx, filter further, then do the RegEx replace, then reconstitute the line back. How can I do this in Python? Answer: The `csv` module is perfect for parsing data like this as `csv.reader` in the default dialect ignores quoted commas. `csv.writer` reinserts the quotes due to the presence of commas. I used `StringIO` to give a file like interface to a string. import csv import StringIO s = '''"thing1,blah","thing2,blah","thing3,blah" "thing4,blah","thing5,blah","thing6,blah"''' source = StringIO.StringIO(s) dest = StringIO.StringIO() rdr = csv.reader(source) wtr = csv.writer(dest) for row in rdr: wtr.writerow([item.replace('\\,',',').replace(',','\\,') for item in row]) print dest.getvalue() result: "thing1\,blah","thing2\,blah","thing3\,blah" "thing4\,blah","thing5\,blah","thing6\,blah"
How to create page-locked memory from a existing numpy array in PyCUDA? Question: The [PyCUDA help explains how to create an empty or zeroed array](http://documen.tician.de/pycuda/driver.html#pagelocked-allocation) but not how to move(?) an existing numpy array into page-locked memory. Do I need to get a pointer for the numpy array and pass it to `pycuda.driver.PagelockedHostAllocation`? And how would I do that? **UPDATE** <\--sniped --> **UPDATE 2** Thanks **talonmies** for you help. Now the memory transfare is page-locked but the program ends with the following error: PyCUDA WARNING: a clean-up operation failed (dead context maybe?) cuMemFreeHost failed: invalid context This is the updated code: #!/usr/bin/env python # -*- coding: utf-8 -*- import numpy as np import ctypes from pycuda import driver, compiler, gpuarray from pycuda.tools import PageLockedMemoryPool import pycuda.autoinit memorypool = PageLockedMemoryPool() indata = np.random.randn(5).astype(np.float32) outdata = gpuarray.zeros(5, dtype=np.float32) pinnedinput = memorypool.allocate(indata.shape,np.float32) source = indata.ctypes.data_as(ctypes.POINTER(ctypes.c_float)) dest = pinnedinput.ctypes.data_as(ctypes.POINTER(ctypes.c_float)) sz = indata.size * ctypes.sizeof(ctypes.c_float) ctypes.memmove(dest,source,sz) kernel_code = """ __global__ void kernel(float *indata, float *outdata) { int globalid = blockIdx.x * blockDim.x + threadIdx.x ; outdata[globalid] = indata[globalid]+1.0f; } """ mod = compiler.SourceModule(kernel_code) kernel = mod.get_function("kernel") kernel( driver.In(pinnedinput), outdata, grid = (5,1), block = (1, 1, 1), ) print indata print outdata.get() memorypool.free_held() Answer: You will need to copy the data from your source array to the array holding the page locked allocation returned from pycuda. The most straightforward way to do that is via `ctypes`: import numpy import ctypes x=numpy.array([1,2,3,4],dtype=numpy.double) y=numpy.zeros_like(x) source = x.ctypes.data_as(ctypes.POINTER(ctypes.c_double)) dest = y.ctypes.data_as(ctypes.POINTER(ctypes.c_double)) sz = x.size * ctypes.sizeof(ctypes.c_double) ctypes.memmove(dest,source,sz) print y The `numpy.ctypes` interface can be used to get a pointer to the memory used to hold an arrays data, and then the `ctypes.memmove` used to copy between two different ndarrays. All the usual caveats of working with naked C pointers apply, so some care is required, but it is straightforward enough to use.
import sqlite3 with Python2.7 on Heroku Question: I'm trying Heroku with Python, I ran the ["hello word" example with Flask](http://blog.heroku.com/archives/2011/9/28/python_and_django/) successfully. I now want to deploy a very basic application, using sqlite3 and Flask, and I know the application was working. But I have trouble getting it to work, and I suspect the problem is with sqlite. When I started the Python shell that Heroku provides, here the import error log: $ heroku run python Running python attached to terminal... up, run.2 Python 2.7.1 (r271:86832, Jun 26 2011, 01:08:11) [GCC 4.4.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import sqlite3 Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/local/lib/python2.7/sqlite3/__init__.py", line 24, in <module> from dbapi2 import * File "/usr/local/lib/python2.7/sqlite3/dbapi2.py", line 27, in <module> from _sqlite3 import * ImportError: No module named _sqlite3 >>> Do I need to add something to the `requirements.txt`, the file used for dependencies? It only contains `Flask==0.8` so far. Import datetime in examples works as expected. I looked with `heroku logs` and this message appears as well, without any other important messages. Do I have any way to use some sqlite3 on Heroku? Thanks for help. Answer: This isn't possible on Heroku, as sqlite requires a permanent writable file system. Since Heroku does not provide a permanent writable file system, sqlite3 won't work. Something to consider: Heroku is a distributed environment. This means an application may run on many machines within many processes. In your case, this would generate multiple sqlite3 instances (each running locally), were it permitted. Also, see: [Heroku Devcenter - Read-only Filesystem](http://devcenter.heroku.com/articles/read-only-filesystem)
Remove Holidays and Weekends in a very long time-serie, how to model time-series in Python? Question: Is there some function in Python to handle this. GoogleDocs has a Weekday -operation so perhaps there is something like that in Python. I am pretty sure someone must have solved this, similar problems occur in sparse data such as in finance and research. I am basically just trying to organize a huge amount of different sized vectors indexed by days, time-series, I am not sure how I should hadle the days -- mark the first day with 1 and the last day with N or with unix -time or how should that be done? I am not sure whether the time- series should be saved into matrix so I could model them more easily to calculate correlation matrices and such things, any ready thing to do such things? Let's try to solve this problem without the "practical" extra clutter: import itertools seq = range(100000) criteria = cycle([True]*10 + [False]*801) list(compress(seq, criteria)) now have to change them into days and then change the $\mathbb R$ into $( \mathbb R, \mathbb R)$, tuple. So $V : \mathbb R \mapsto \mathbb R^{2}$ missing, investigating. **[Update]** Let's play! Below code solves the subproblem -- creates some test data to test things -- now we need to create arbitrary days and valuations there to try to test it on arbitrary timeseries. If we can create some function $V$, we are very close to solve this problem...it must consider though the holidays and weekends so maybe not easy (not sure). import itertools as i import time import math import numpy def createRandomData(): samples=[] for x in range(5): seq = range(5) criteria = i.cycle([True]*x+ [False]*3) samples += [list(i.compress( seq, criteria ))] return samples def createNNtriangularMatrix(data): N = len(data) return [aa+[0]*(N-len(aa)) for aa in data] A= createNNtriangularMatrix(createRandomData()) print numpy.array(A) print numpy.corrcoef(A) Answer: I think you should figure out someway the days you want to INCLUDE, and create a (probably looping) subroutine use slicing operations on your big list. For discontinuous slices, you can take a look at this question: [Discontinuous slice in python list](http://stackoverflow.com/questions/5805914/discontinuous-slice-in- python-list) Or perhaps you could make the days you do not want receive a null value (zero or None).
Python socked bound to secondary IP gets connection reset from server Question: I'm trying to create a python socket script that binds to a secondary IP and connects to a server. When I run the script python gives me a "socket.error: [Errno 111] Connection refused" The TCPdump shows that the server I try to connect to sends back a reset response. Running the script without the socket.bind works. The script: import socket port = 9009 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.bind(("123.123.123.123", port)) # Not the real IP I use sock.connect(("81.236.48.66", 80)) # Raises connection refused The tcpdump: 11:22:08.211502 IP 123.123.123.123.9009 > 81.236.48.66.80: Flags [S], seq 3687363746, win 5840, options [mss 1460,sackOK,TS val 1304421782 ecr 0,nop,wscale 6], length 0 11:22:08.211763 IP 81.236.48.66.80 > 123.123.123.123.9009: Flags [R.], seq 0, ack 3687363747, win 5840, length 0 I run the script on a linux box and the secondary IP I use is listen when I use the command: "ip list all" Thanks in advance and please bear with me since I'm not very experienced in socket programming. Answer: I found the error. The firewall was configured to block the response and sent a reset flag.
Print the first two rows of a csv file to a standard output Question: I would like to print (stdout) the first two lines of a csv file: #!/usr/bin/env python import csv afile = open('<directory>/*.csv', 'r+') csvReader1 = csv.reader(afile) for row in csvReader1: print row[0] print row[1] however, my output using this code print the first two columns. Any suggestions? Answer: You want to print a row, but your code asks to print the first and second members of each row Since you want to print the whole row - you can simply print it, and in addition, only read the first two #!/usr/bin/env python import csv afile = open('<directory>/*.csv', 'r+') csvReader1 = csv.reader(afile) for i in range(2): print csvReader1.next()
How to use "import oauth2" in Google App Engine? Question: I want to use Tumblr's API v2, which includes OAuth. so I need to find a OAuth module. I am supposed to use it like this: import oauth2 as oauth I have found the oauth2 source code here: <https://github.com/simplegeo/python-oauth2> 1. If I want to use it in my Linux Ubuntu 10.08, whats the process? I have installed git. I notice that there is a "setup.py", so I just have to run it? The ReadME <https://github.com/simplegeo/python-oauth2/blob/master/README.md> doesnt mention how to install, maybe it is too newbie. 2. If I want to use it in Google App Engine, how can I do it? Thanks for your help. I am pretty new to GIT stuff. Answer: On Ubuntu, simply `sudo apt-get install python-oauth2` and the package will be installed for you automatically. For AppEngine, you might take a look at the [Google API Python Client's](http://code.google.com/p/google-api-python-client/source/browse/) appengine examples. They have an OAuth2 client specifically designed to work with AppEngine.
Datetime difference to return Days only? Question: $ cat .t.py import re from datetime import datetime as dtt oldestDate = dateComp = dtt.strptime('1.1.1001', '%d.%m.%Y') dateComp = dtt.strptime('11.1.2011', '%d.%m.%Y') ind = re.sub(" days,.*", "", str((dateComp - oldestDate))) print ind print dateComp - oldestDate $ python .t.py 368905 368905 days, 0:00:00 How can I get days only without the regex code-smell? The problem escalate because I need to use the index in many locations. So some cleaner way to do this? Answer: Don't use `str()` so soon. The result you get back from subtracting one `datetime` from another is a [`timedelta`](http://docs.python.org/library/datetime.html#timedelta-objects) object, which has a `.days` property that you can read. (dateComp - oldestDate).days Note that reading _only_ the `.days` property will mean that it will round down the difference - if you instead want to round to the nearest number of days, you'll need to add some logic to check the `.seconds` property to see whether it's closer to 0 or 86400.
python class data descriptor list Question: I can't seem to figure out how to get a list of a classes data descriptors. Basically, I want to run some validation against the fields and unset fields. For instance: class Field (object): def __init__ (self, name, required=False): self.name = name self.required = required def __set__ (self, obj, val): obj.__dict__[self.name] = val def __get__ (self, obj): if obj == None: raise AttributeError if self.name not in obj.__dict__: raise AttributeError return obj.__dict__[self.name] Then I wanted to implement it in a model like so: class BaseModel (object): some_attr = Field('some_attr', required=True) def save (self): for field in fields: if field.required and field.name not in self.__dict__: raise Exeception, 'Validation Error' How would I go about getting a list of the fields I define? I was thinking, I could do the following: import inspect fields = [] for attr in self.__class__.__dict__: if inspect.isdatadescriptor(self.__class__.__dict__[attr]): fields.append(attr) But I ran into problems with inheritance, any ideas? Answer: In order to iterate over the classes' members you need to use `inpsect.getmembers`. So your last example would look like this: import inspect fields = [] for member_name, member_object in inspect.getmembers(self.__class__): if inspect.isdatadescriptor(member_object): fields.append(member_name) In your `descriptor` you should replace accessing `__dict__` directly with python's [getattr](http://docs.python.org/library/functions.html#getattr) and [setattr](http://docs.python.org/library/functions.html#setattr) builtins. Also, keep in mind that you want to make a distinction between the `descriptor` attribute's name on the class and the underlying instance's attribute. In cases like this I usually prepend and underscore. e.g.: class Field (object): def __init__(self, name, required=False): self.name = '_' + name self.required = required def __set__(self, obj, val): setattr(obj, self.name, val) def __get__(self, obj): return getattr(obj, self.name)
Tree plotting in Python Question: I want to plot trees using Python. Decision trees, Organizational charts, etc. Any library that helps me with that? Answer: There's graphviz - <http://www.graphviz.org/>. It uses the "DOT" language to plot graphs. You can either generate the DOT code yourself, or use pydot - <https://code.google.com/p/pydot/>. You could also use networkx - <http://networkx.lanl.gov/tutorial/tutorial.html#drawing-graphs>, which make it easy to draw to either graphviz or matplotlib. networkx + matplotlib + graphviz gives you the most flexibility and power, but you need to install a lot. If you want a quick solution, try: Install Graphviz. open('hello.dot','w').write("digraph G {Hello->World}") import subprocess subprocess.call(["path/to/dot.exe","-Tpng","hello.dot","-o","graph1.png"]) # I think this is right - try it form the command line to debug Then you install pydot, because pydot already does this for you. Then you can use networkx to "drive" pydot.
Looping Through Nested List - Convert from String to Float Question: I am new to Python, so apologies if this seems extremely simple: I have a csv file with 4 columns and a dozen rows. I import the contests as a list (list of lists), and the contents come in as strings. What I want to do is loop through the list (which can be a variable number of rows) and convert the index 2 string to a float. I run the following code, but when i print the list, everything is still a string: import csv def main(): benchmark = list(csv.reader(open('test.csv', 'r'))) for i in range((len(benchmark))): benchmark[i][2] = float(benchmark[i][2]) Any help would be much appreciated. Thanks! Answer: It's not necessary to cast your csv.reader to a list as it is already iterable. You can do something like the following: benchmark=[] with open('test.csv','r') as inp: csvin=csv.reader(inp) for row in csvin: benchmark.append(row[:1] + [float(row[1])] + row[2:])
Local Appengine stopped working Question: I tried to run one of my AppEnigne projects (python) today but it will no longer launch, this is the stack trace I'm getting. *** Running dev_appserver with the following flags: --admin_console_server= --port=8080 --clear_datastore Python command: /usr/bin/python2.5 Traceback (most recent call last): File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/dev_appserver.py", line 77, in <module> run_file(__file__, globals()) File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/dev_appserver.py", line 73, in run_file execfile(script_path, globals_) File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/dev_appserver_main.py", line 138, in <module> import logging ImportError: No module named logging I thought it could be a python 2.6 error but I adjusted my path to `/usr/bin/python2.5` and its still not working. I'm running OSX 10.6.8 and have the latest AppEngineLauncher 1.5.4 The only thing I changed recently that might have affected this is when I updated my XCode to the latest version, v4.2 build 4C199 Has anyone else faced this issue recently? EDIT I can't `import logging` from the terminal either, same message. Here's Python's path. Chriss-MacBook-Pro:bin chris$ /usr/bin/python2.5 Python 2.5.4 (r254:67916, Aug 2 2010, 20:09:39) [GCC 4.2.1 (Apple Inc. build 5646)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> sys.path ['', '/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python25.zip', '/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5', '/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/plat-darwin', '/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/plat-mac', '/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/plat-mac/lib-scriptpackages', '/System/Library/Frameworks/Python.framework/Versions/2.5/Extras/lib/python', '/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/lib-tk', '/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/lib-dynload', '/Library/Python/2.5/site-packages', '/System/Library/Frameworks/Python.framework/Versions/2.5/Extras/lib/python/PyObjC', '/System/Library/Frameworks/Python.framework/Versions/2.5/Extras/lib/python/wx-2.8-mac-unicode'] >>> Answer: Thanks to Nick and Wobble I've figured it out. I recently updated my XCode install to the 4.2 GM release and removed the beta versions. Along the way OSX forgot where gcc was installed and prevented it from compiling the python modules like `logging`. This resulted in missing `.pyo` files inside `/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python25/logging` which prevents `import logging` from working. Logging wasn't the only module that wasn't compiled, just the first one AppEngine tried to import. Solution: uninstall and do a clean install of XCode. Make sure gcc can be found on your PATH and everything should be fine.
Import contacts from yahoo in python Question: Is there are official way to import contacts from user address book from yahoo? For google it's really simple as: import gdata contacts_service = gdata.contacts.service.ContactsService() contacts_service.email = email contacts_service.password = password contacts_service.ProgrammaticLogin() query = gdata.contacts.service.ContactsQuery() query.max_results = GOOGLE_CONTACTS_MAX_RESULTS entries = contacts_service.GetContactsFeed(query.ToUri()) Is there such simple way for yahoo? I found some solutions, that don't use api and looks strange for serious game - for example [ContactGrabber](http://pypi.python.org/pypi/ContactGrabber/0.1). I found solutions, that require BBAuth Token in [django-friends app](https://github.com/jtauber/django-friends). But, I want official, clear, way to grab user contacts from yahoo. Does it exists? UPD: Finally I am avoiding use of yahoo api, and using [django- openinviter](https://github.com/tschellenbach/DjangoOpenInviter) for my purposes. But I am still looking for examples of importing user contacts using api. Answer: The [Contacts REST API](http://developer.yahoo.com/social/rest_api_guide/contacts-resource.html) is pretty straight-forward. The URL that you're after is http://social.yahooapis.com/v1/user/{guid}/contacts.json Here is a script that will extract things for you. You can expand this to include authentication. import urllib2 import json def get_contacts(guid): url = 'http://social.yahooapis.com/v1/user/{}/contacts.json'.format(guid) page = urllib2.urlopen(url) return json.load(page)['contacts']['contact']
Running Python in Windows Question: Am new to python, i installed python 3.2 in my windows and tried the following code, import urllib, urllister usock = urllib.urlopen("http://diveintopython.net/") parser = urllister.URLLister() parser.feed(usock.read()) usock.close() parser.close() for url in parser.urls: print(url) Its showing, Traceback (most recent call last): File "demo.py", line 1, in <module> import urllib, urllister ImportError: No module named urllister How to add that module? Answer: `urllister` is not part of the standard library. You must download file `urllister.py` [from here](http://dev.gentoo.org/~dberkholz/articles/diveintopython-5.4/py/urllister.py), and save it next to the script you're running.
How to pass variable to a python cgi script Question: What I want to do is have a single python program in cgi-bin that is executed by each of many pages on the site, and displays a line of HTML on each page that is different for each file, but keyed to the URL of that file on the site. I know how to get the URL using javascript (e.g. on <http://constitution.org/cs_event.htm> ): <script language="javascript"> var myurl = document.location.href; document.write(myurl); </script> <br> <script language="javascript"> var myurl = document.location.href; document.write("<A href=\"" + myurl + "\">" + myurl + "<\/A>"); </script> And I know how to create a link that opens a page to execute the .py script when one clicks on it: <a href="http://constitution.org/cgi-bin/copy01.py?myurl=myurl">Here</a> Here is the python script so far: #!/usr/bin/env python # This outputs a copyright notice to a web page import cgi print "Content-Type: text/html\n" form = cgi.FieldStorage() thisurl = form.getvalue("myurl") print """ <html><head></head> <body> """ print """ Copyright &copy; 1995-2011 Constitution Society. Permission granted to copy with attribution for non-profit purposes. """ print """ </body></html> """ print thisurl But it is not so obvious how to pass the variable value to the .py script, and have it automatically display the URL of that page the way the javascript does, or display a line of HTML that it will get from a dictionary in which the URLs are the keys and the HTML lines are the data. Ultimately, I want to be able to generate, using a single .py script, all the footer content of each page, that can be maintained from a single file that I can edit to make changes that propagate everywhere. Answer: CGI puts various things to do with the current request into the script's shell environment, which you can access in the normal way with `os.environ`. In particular, `os.environ['HTTP_HOST']` will get you the server name, and `os.environ['SCRIPT_NAME']` will get you the path.
Python sys.argv out of range, don't understand why Question: I have a script that I've been using for a some time to easily upload files to my server. It has been working great for a long time, but I can't get it to work on my new desktop computer. The code is simple: import os.path import sys import os from ftplib import FTP host = "" acc = "" pw = "" filepath = sys.argv[1] if (not os.path.isfile(filepath)): x = input("ERROR, invalid filepath") exit() filename = os.path.basename(filepath) file_object = open(filepath, 'rb') ftp = FTP(host) ftp.login(acc, pw) ftp.storbinary('STOR ' + filename, file_object) ftp.quit() file_object.close() I run it as: > file_uploader.py backup.sql I get the following error: > Traceback (most recent call last): > > File "C:\Users\Admin\Desktop\file_uploader.py", line 12, in > > filepath = sys.argv[1] > > IndexError: list index out of range I'm not sure why it's giving me an error that it can't find the first commandline argument even though I passed one to the script. I am running Windows 7 64-bit with Python 2.7.2 Thanks Answer: Your .py association in the registry is incorrect. It's missing `%*` at the end.
How to document python function parameter types? Question: I know that the parameters can be any object but for the documentation it is quite important to specify what you would expect. First is how to specify a parameter types like these below? * `str` (or use `String` or `string`?) * `int` * `list` * `dict` * function() * `tuple` * object instance of class `MyClass` Second, how to specify params that can be of multiple types like a function that can handle a single parameter than can be `int` or `str`? Please use the below example to demonstrate the syntax needed for documenting this with your proposed solution. Mind that it is desired to be able to hyperlink reference to the "Image" class from inside the documentation. def myMethod(self, name, image): """ Does something ... name String: name of the image image Image: instance of Image Class or a string indicating the filename. Return True if operation succeeded or False. """ return True Note, you are welcome to suggest the usage of any documentation tool (sphinx, oxygen, ...) as long it is able to deal with the requirements. ## Update: It seams that there is some kind of support for documenting parameter types in doxygen in. general. The code below works but adds an annoying $ to the param name (because it was initially made for php). @param str $arg description @param str|int $arg description Answer: There is a better way. We use def my_method(x, y): """ my_method description @type x: int @param x: An integer @type y: int|string @param y: An integer or string @rtype: string @return: Returns a sentence with your variables in it """ return "Hello World! %s, %s" % (x,y) That's it. In the PyCharm IDE this helps a lot. It works like a charm ;-)
python __getattr__ in parent class __init__ recursion error Question: following an advice here [subclassing beautifulsoup html parser, getting type error](http://stackoverflow.com/questions/7684794/subclassing-beautifulsoup- html-parser-getting-type-error/7685314#7685314) I'm trying to use class composition instead of subclassing BeautifulSoup. the basic Scraper class works fine on it's own (at least to my limited testing). the Scraper class: from BeautifulSoup import BeautifulSoup import urllib2 class Scrape(): """base class to be subclassed basically a wrapper that providers basic url fetching with urllib2 and the basic html parsing with beautifulsoupץ some useful methods are provided with class composition with BeautifulSoup. for direct access to the soup class you can use the _soup property.""" def __init__(self,file): self._file = file #very basic input validation #import re #import urllib2 #from BeautifulSoup import BeautifulSoup try: self._page = urllib2.urlopen(self._file) #fetching the page except (urllib2.URLError): print ('please enter a valid url starting with http/https/ftp/file') self._soup = BeautifulSoup(self._page) #calling the html parser #BeautifulSoup.__init__(self,self._page) # the next part is the class compostion part - we transform attribute and method calls to the BeautifulSoup class #search functions: self.find = self._soup.find self.findAll = self._soup.findAll self.__iter__ = self._soup.__iter__ #enables iterating,looping in the object self.__len__ = self._soup.__len__ self.__contains__ = self._soup.__contains__ #attribute fetching and setting - __getattr__ implented by the scraper class self.__setattr__ = self._soup.__setattr__ self.__getattribute__ = self._soup.__getattribute__ #Called to implement evaluation of self[key] self.__getitem__ = self._soup.__getitem__ self.__setitem__ = self._soup.__setitem__ self.__delitem__ = self._soup.__delitem__ self.__call__ = self._soup.__call__#Called when the instance is “called” as a function self._getAttrMap = self._soup._getAttrMap self.has_key = self._soup.has_key #walking the html document methods self.contents = self._soup.contents self.text = self._soup.text self.extract = self._soup.extract self.next = self._soup.next self.parent = self._soup.parent self.fetch = self._soup.fetch self.fetchText = self._soup.fetchText self.findAllNext = self._soup.findAllNext self.findChild = self._soup.findChild self.findChildren = self._soup.findChildren self.findNext = self._soup.findNext self.findNextSibling = self._soup.findNextSibling self.first = self._soup.first self.name = self._soup.name self.get = self._soup.get self.getString = self._soup.getString # comparison operators or similiar boolean checks self.__eq__ = self._soup.__eq__ self.__ne__ = self._soup.__ne__ self.__hash__ = self._soup.__hash__ self.__nonezero__ = self._soup.__nonzero__ #not sure # the class represntation magic methods: self.__str__ = self._soup.__str__ self.__repr__ =self._soup.__repr__ #self.__dict__ = self._soup.__dict__ def __getattr__(self,method): """basically this 'magic' method transforms calls for unknown attributes to and enables to traverse the html document with the .notation. for example - using instancename.div will return the first div. explantion: python calls __getattr__ if It didn't find any method or attribute correspanding to the call. I'm not sure this is a good or the right use for the method """ return self._soup.find(method) def clean(self,work=False,element=False): """clean method that provides:basic cleaning of head,scripts etc input 'work' soup object to clean from unneccesary parts:scripts,head,style has optional variable:'element' that can get a tuple of element that enables to override what element to clean""" self._work = work or self._soup self._cleanelements=element or ("head","style","script") #for elem in self._work.findAll(self._cleanelements): for elem in self.findAll(self._cleanelements): elem.extract() but when I subclass it I get some sort of recursion loop, I just can figure. here is the subclass(the relevant parts): class MainTraffic(Scrape): """class traffic - subclasses the Scrape class inputs a page url and a category""" def __init__(self, file, cat, caller = False): if not caller: self._file = file #import urllib2 #self._request = urllib2.Request(self._file)# request to post the show all questions Scrape.__init__(self,self._file) self.pagecat = cat self.clean(self) self.cleansoup = self.cleantotable(self) self.fetchlinks(self.cleansoup) #self.populatequestiondic() #del (self.cleansoup) def cleantotable(self): pass def fetchlinks(self,fetch): pass def length(self): from sqlalchemy import func self.len = session.query(func.count(Question.id)).scalar() return int(self.len) def __len__(self): return self.length() def __repr__(self): self.repr = "traffic theory question, current number of questions:{0}".format(self.length()) return self.repr def __getitem__(self,key): try: self._item = session.query(Question).filter_by(question_num=key).first() return self._item except (IndexError, KeyError): print "no such key:{0}".format(key) and here is the error message: File "C:\Python27\learn\traffic.py", line 117, in __init__ Scrape.__init__(self,self._file) File "C:\Python27\learn\traffic.py", line 26, in __init__ self._soup = BeautifulSoup(self._page) #calling the html parser File "C:\Python27\learn\traffic.py", line 92, in __getattr__ return self._soup.find(method) File "C:\Python27\learn\traffic.py", line 92, in __getattr__ return self._soup.find(method) File "C:\Python27\learn\traffic.py", line 92, in __getattr__ return self._soup.find(method) RuntimeError: maximum recursion depth exceeded I suspect the problem is with me misusing the `__getattr__`, but I couldn't figure out what should I change. Answer: ### Part 1 Your code doesn't work because `__getattr__()` accesses `self._soup` before it has been initialized. This happens due to four innocuous-looking lines: try: self._page = urllib2.urlopen(self._file) except (urllib2.URLError): print ('please enter a valid url starting with http/https/ftp/file') Why do you catch the exception and not actually handle it? The next line accesses self._page, which has not been set yet if urlopen() threw an exception: self._soup = BeautifulSoup(self._page) Since it hasn't been set, accessing it calls `__getattr__()`, which accesses `self._soup`, which has not been set yet so it accesses `__getattr__`. The easiest "fix" is to special-case _soup to prevent infinite recursion. Additionally, it seems to make more sense for `__getattr__` to simply do normal attribute lookup on soup: def __getattr__(self,attr): if attr == "_soup": raise AttributeError() return getattr(self._soup,attr) ### Part 2 Copying all the methods over is unlikely to work very well, and seems to miss the point of class composition entirely.
Python running out of memory parsing XML using cElementTree.iterparse Question: A simplified version of my XML parsing function is here: import xml.etree.cElementTree as ET def analyze(xml): it = ET.iterparse(file(xml)) count = 0 for (ev, el) in it: count += 1 print('count: {0}'.format(count)) This causes Python to run out of memory, which doesn't make a whole lot of sense. The only thing I am actually storing is the count, an integer. Why is it doing this: ![enter image description here](http://i.stack.imgur.com/HUGC0.png) See that sudden drop in memory and CPU usage at the end? That's Python crashing spectacularly. At least it gives me a `MemoryError` (depending on what else I am doing in the loop, it gives me more random errors, like an `IndexError`) and a stack trace instead of a segfault. But why is it crashing? Answer: [The documentation](http://docs.python.org/library/xml.etree.elementtree.html#xml.etree.ElementTree.iterparse) does tell you "Parses an XML section _into an element tree_ [my emphasis] incrementally" but doesn't cover how to avoid retaining uninteresting elements (which may be all of them). That is covered by [this article by the effbot](http://effbot.org/elementtree/iterparse.htm). I strongly recommend that anybody using `.iterparse()` should read [this article by Liza Daly](http://www.ibm.com/developerworks/xml/library/x-hiperfparse/). It covers both `lxml` and [c]ElementTree. Previous coverage on SO: [Using Python Iterparse For Large XML Files](http://stackoverflow.com/questions/7171140/using-python-iterparse-for- large-xml-files) [Can Python xml ElementTree parse a very large xml file?](http://stackoverflow.com/questions/3707155/can-python-xml-elementtree- parse-a-very-large-xml-file) [What is the fastest way to parse large XML docs in Python?](http://stackoverflow.com/questions/324214/what-is-the-fastest-way-to- parse-large-xml-docs-in-python)
tornado AsyncHTTPClient.fetch exception Question: I am using `tornado.httpclient.AsyncHTTPClient.fetch` to fetch domains from list. When I put domains to fetch with some big interval(500 for example) all works good, but when I decrease the inerval to 100, next exception occurs time to time: Traceback (most recent call last): File "/home/crchemist/python-2.7.2/lib/python2.7/site-packages/tornado/simple_httpclient.py", line 289, in cleanup yield File "/home/crchemist/python-2.7.2/lib/python2.7/site-packages/tornado/stack_context.py", line 183, in wrapped callback(*args, **kwargs) File "/home/crchemist/python-2.7.2/lib/python2.7/site-packages/tornado/simple_httpclient.py", line 384, in _on_chunk_length self._on_chunk_data) File "/home/crchemist/python-2.7.2/lib/python2.7/site-packages/tornado/iostream.py", line 180, in read_bytes self._check_closed() File "/home/crchemist/python-2.7.2/lib/python2.7/site-packages/tornado/iostream.py", line 504, in _check_closed raise IOError("Stream is closed") IOError: Stream is closed What can be the reason of this behavior? Code looks like this: def fetch_domain(domain): http_client = AsyncHTTPClient() request = HTTPRequest('http://' + domain, user_agent=CRAWLER_USER_AGENT) http_client.fetch(request, handle_domain) class DomainFetcher(object): def __init__(self, domains_iterator): self.domains = domains_iterator def __call__(self): try: domain = next(self.domains) except StopIteration: domain_generator.stop() ioloop.IOLoop.instance().stop() else: fetch_domain(domain) domain_generator = ioloop.PeriodicCallback(DomainFetcher(domains), 500) domain_generator.start() Answer: note that `tornado.ioloop.PeriodicCallback` [takes a cycle time **in integer ms**](http://www.tornadoweb.org/documentation/_modules/tornado/ioloop.html#PeriodicCallback) while the [`HTTPRequest`](http://www.tornadoweb.org/documentation/_modules/tornado/httpclient.html#HTTPRequest) object is configured with a `connect_timeout` and/or a `request_timeout` of float **seconds** ([see doc](http://www.tornadoweb.org/documentation/httpclient.html)). "_Users browsing the Internet feel that responses are "instant" when delays are less than 100 ms from click to response_ " ([from wikipedia](http://en.wikipedia.org/wiki/Network_performance#Relationship_between_latency_and_throughput)) See [this ServerFault question for **normal latency** values](http://serverfault.com/questions/137348/how-much-network-latency-is- typical-for-east-west-coast-usa). `IOError: Stream is closed` is validly being raised to inform you that your connection timed out without completing, or more accurately, you called the callback manually on a pipe that wasn't open yet. This is good, since it is not abnormal for latency to be > 100ms; if you expect your fetches to complete reliably you should raise this value. Once you've got your timeout set to something sane, consider wrapping your fetches in a try/except retry loop as this is a normal exception _that you can expect to occur in production_. Just be careful to set a retry limit! * * * Since you're using an async framework, why not let it handle the async callback itself instead of running said callback on a fixed interval? [Epoll/kqueue are efficient and supported by this framework.](http://www.tornadoweb.org/documentation/overview.html?highlight=epoll%20kqueue) import ioloop def handle_request(response): if response.error: print "Error:", response.error else: print response.body ioloop.IOLoop.instance().stop() http_client = httpclient.AsyncHTTPClient() http_client.fetch("http://www.google.com/", handle_request) ioloop.IOLoop.instance().start() ^ Copied verbatim [from the doc](http://www.tornadoweb.org/documentation/httpclient.html). If you go this route, the only gotcha is to code your request queue so that you have a maximum open connections enforced. Otherwise you're likely to end up with a race condition when doing serious scraping. It's been ~1yr since I touched Tornado myself, so please let me know if there are inaccuracies in this response and I will revise.
Unicode in Django unit test Question: I try to use a utf8 string in a Django unit test and have included # -*- coding: utf-8 -*- but django-admin.py still complaints there is no encoding. > Traceback (most recent call last): > > File "/home/basti/work/virtualenv/bin/django-admin.py", line 5, in > management.execute_from_command_line() > > File "/home/basti/work/virtualenv/lib/python2.7/site- > packages/django/core/management/**init**.py", line 429, in > execute_from_command_line utility.execute() > > File "/home/basti/work/virtualenv/lib/python2.7/site- > packages/django/core/management/**init**.py", line 379, in execute > self.fetch_command(subcommand).run_from_argv(self.argv) > > File "> /home/basti/work/virtualenv/lib/python2.7/site- > packages/django/core/management/base.py", line 191, in run_from_argv > self.execute(*args, **options.**dict**) > > File "/home/basti/work/virtualenv/lib/python2.7/site- > packages/django/core/management/base.py", line 220, in execute output = > self.handle(*args, **options) > > File "/home/basti/work/virtualenv/lib/python2.7/site- > packages/south/management/commands/test.py", line 8, in handle > super(Command, self).handle(*args, **kwargs) > > File "/home/basti/work/virtualenv/lib/python2.7/site- > packages/django/core/management/commands/test.py", line 37, in handle > failures = test_runner.run_tests(test_labels) > > File "/home/basti/work/virtualenv/lib/python2.7/site- > packages/django/test/simple.py", line 358, in run_tests suite = > self.build_suite(test_labels, extra_tests) > > File "/home/basti/work/virtualenv/lib/python2.7/site- > packages/django/test/simple.py", line 248, in build_suite > suite.addTest(build_suite(app)) > > File "/home/basti/work/virtualenv/lib/python2.7/site- > packages/django/test/simple.py", line 77, in build_suite test_module = > get_tests(app_module) > > File "/home/basti/work/virtualenv/lib/python2.7/site- > packages/django/test/simple.py", line 35, in get_tests test_module = > **import**('.'.join(app_path + [TEST_MODULE]), {}, {}, TEST_MODULE) > > SyntaxError: Non-ASCII character '\xc3' in file tests.py on line 242, but no > encoding declared; see <http://www.python.org/peps/pep-0263.html> for > details The code is # -_\- coding: utf-8 -_ \- """ This file demonstrates writing tests using the unittest module. These will pass when you run "manage.py test". Replace this with more appropriate tests for your application. """ from django.test import TestCase, Client from django.contrib.auth.models import User from django.db.utils import IntegrityError from django.core.urlresolvers import reverse from django.utils.encoding import smart_unicode class ViewTests(TestCase): def setUp(self): self.client = Client() def test_french(self): self.client.cookies["django_language"] = 'fr' r = self.client.get("/") self.assertTrue(smart_unicode(u"Se déconnecter") in r.content) I've tried to set TEST_CHARSET and TEST_DATABASE_CHARSET to utf8, but still no luck. Any hints on how to solve that? TIA && have a nice day! Basti Answer: Put: # -*- coding: utf-8 -*- As the first line for that file.
Python API for C++ Question: I have a code on C++, that creates file and writes data to it. Is it possible to use Python's functions to use Python's functionality in my C++ code? For example, I'd like to do this: # Content of function.py from PIL import Image imgObject = Image.open('myfile.jpg') # Create Image object pixArray = imgObject.load() # Create array of pixels pixColor = pixArray[25, 25] # Get color of pixel (25,25) I want to write pixColor to text file using C++ possibilities: #include <fstream> #include <iostream> int main() { ofstream fout('color.txt', ios_base::out | ios_base::binary); fout << pixColor; } That's only example. My application will really detect color of each pixel and will output it in 'color.txr' file, so I need something faster than Python. Is there a possibility to do it? Thanks a lot! Answer: You may have a look to boost::python library which is really great for interfacing python and C++.
Python, empty file after csv writer.. again Question: My python program loops through a bunch of csv-files, read them, and write specific columns in the file to another csv file. While the program runs, i can see the files being written in the correct manner, but once the program is finished, all the files i've just written become empty. The solution to all the other similar threads seems to be closing the file you write to properly, but i cant seem to figure out what im doing wrong. Anyone? import os import csv def ensure_dir(f): d = os.path.dirname(f) if not os.path.exists(d): os.makedirs(d) readpath = os.path.join("d:\\", "project") savepath=os.path.join("d:\\", "save") ensure_dir(savepath) contents_1=os.listdir(readpath) for i in contents_1[1:len(contents_1)]: readpath_2=os.path.join(readpath, i) if os.path.isdir(readpath_2)== True : contents_2=os.listdir(readpath_2) for i in contents_2: readpath_3=os.path.join(readpath_2, i) if os.path.isfile(readpath_3)== True : savefile=savepath + "\\" + i savefile = open(savefile, 'wb') writer = csv.writer(savefile, delimiter=';') readfile=open(readpath_3, 'rb') reader = csv.reader(readfile, delimiter=';') try: for row in reader: writer.writerow([row[0], row[3]]) except: print(i) finally: savefile.close() readfile.close() Answer: `savefile=savepath + "\\" + i` is the error. If both `"d:\\project\a\x.csv"` and `"d:\\project\b\x.csv"` exist, then you will write to `savepath + "\\" + i` more than once. If the second path as an empty `"x.csv"`, then it would overwrite the result with an empty file. Try this instead: import os import csv def ensure_dir(f): d = os.path.dirname(f) if not os.path.exists(d): os.makedirs(d) readpath = os.path.join("d:\\", "project") savepath = os.path.join("d:\\", "save") ensure_dir(savepath) for dname in os.listdir(readpath)[1:]: readpath_2 = os.path.join(dname, fname) if not os.path.isdir(readpath_2): continue for fname in os.listdir(readpath_2) fullfname = os.path.join(readpath_2, fname) if not os.path.isfile(fullfname): continue savefile = open(savepath + "\\" + dname + "_" + fname, wb) writer = csv.writer(savefile, delimiter=';') readfile=open(fullfname, 'rb') reader = csv.reader(readfile, delimiter=';') try: for row in reader: writer.writerow([row[0], row[3]]) except: print(i) finally: savefile.close() readfile.close() This code could be greatly improved with [`os.walk`](http://docs.python.org/library/os.html#os.walk)
Iterate variable for every node | Node Connectivity in Python Graph Question: I would like to find node connectivity between node 1 and rest of the nodes in a graph. The input text file format is as follows: 1 2 1 1 35 1 8 37 1 and so on for 167 lines. First column represents source node, second column represents destination node while the last column represents weight of the edge. I'm trying to read the source, destination nodes from input file and forming an edge between them. I need to then find out if it is a connected network (only one component of graph and no sub-components). Here is the code from numpy import* import networkx as nx G=nx.empty_graph() for row in file('out40.txt'): row = row.split() src = row[0] dest = row[1] #print src G.add_edge(src, dest) print src, dest for i in range(2, 41): if nx.bidirectional_dijkstra(G, 1, i): print "path exists from 1 to ", i manually adding the edges using G.add_edge(1, 2) works but is tedious and not suitable for large input files such as mine. The if loop condition works when I add edges manually but throws the following error for the above code: in neighbors_iter raise NetworkXError("The node %s is not in the graph."%(n,)) networkx.exception.NetworkXError: The node 2 is not in the graph. Any help will be much appreciated! Answer: In your code, you're adding nodes `"1"` and `"2"` et cetera (since reading from a file is going to give you strings unless you explicitly convert them). However, you're then trying to refer to nodes `1` and `2`. I'm guessing that `networkx` does not think that `2 == "2"`. Try changing this... G.add_edge(src, dest) to this: G.add_edge(int(src), int(dest))
using a python list as input for linux command that uses stdin as input Question: I am using python scripts to load data to a database bulk loader. The input to the loader is stdin. I have been unable to get the correct syntax to call the unix based bulk loader passing the contents of a python list to be loaded. I have been reading about Popen and PIPE but they have not been behaving as i expect. The python list contains database records to be bulkloaded. In linux it would look similar to this: echo "this is the string being written to the DB" | sql -c "COPY table FROM stdin" What would be the correct way replace the echo statement with a python list to be used with this command ? I do not have sample code for this process as i have been experimenting with the features of Popen and PIPE with some very simple syntax and not obtaining the desired result. Any help would be very much appreciated. Thanks Answer: If your data is short and simple, you could preformat the entire list and do it simple with subprocess like this: import subprocess data = ["list", "of", "stuff"] proc = subprocess.Popen(["sql", "-c", "COPY table FROM stdin"], stdin=subprocess.PIPE) proc.communicate("\n".join(data)) If the data is too big to preformat like this, then you can attempt to use the stdin pipe directly, though subprocess module is flaky when using the pipes if you need to read from stdout/stderr too. for line in data: print >>proc.stdin, line
Python Tkinter GUI:add text from an entry widget in a pop up window to a listbox in a different window? Question: I am trying to add an entry from a toplevel window into a listbox in the main window. So far I have managed to create a button that opens a new window containing 4 entry widgets(name, address, phone number and DOB). Is there any way, after I press the OK button on the pop up window, that all four entries are added to the listbox on the main window? Thanks. Answer: Unless I'm missing something in your problem description, the OK button command just needs to copy the values from the Entry fields to the Listbox. Was there more to it than that? from tkinter import Tk, Frame, Label, Entry, Button, Listbox def ok_button(): li.delete(0, "end") for i in range(len(fields)): li.insert("end", e[i].get()) root = Tk() root.title("Listbox") cf = Frame(root) cf.pack() fields = ("Name", "Address", "Phone", "DOB") e = [] for f in fields: i = len(e) Label(cf, text=f).grid(column=2, row=i, sticky="e") e.append(Entry(cf, width=16)) e[i].grid(column=4, row=i) Button(cf, text="OK", command=ok_button).grid(column=2, row=10, columnspan=3) li = Listbox(cf) li.grid(column=2, row=8, columnspan=3) root.mainloop()
Parsing/Extracting Data from API XML feed with Python and Beautiful Soup Question: Python/xml newb here playing around with Python and BeautifulSoup trying to learn how to parse XML, specifically messing with the Oodle.com API to list out car classifieds. I've had success with simple XML and BS, but when working with this, I can't seem to get the data I want no matter what I try. I tried reading the Soup documentation for hours and can't figure it out. The XML is structured like: <?xml version="1.0" encoding="utf-8"?> <oodle_response stat="ok"> <current> .... </current> <listings> <element> <id>8453458345</id> <title>2009 Toyota Avalon XL Sedan 4D</title> <body>...</body> <url>...</url> <images> <element>...</element> <element>...</element> </images> <attributes> <features>...</features> <mileage>32637</mileage> <price>19999</price> <trim>XL</trim> <vin>9234234234234234</vin> <year>2009</year> </attributes> </element> <element>.. Next car here ..</element> <element>..Aaaand next one here ..</element> </listings> <meta>...</meta> </oodle_response> I first make a request with urllib to grab the feed and save to a local file. Then: xml = open("temp.xml", "r") from BeautifulSoup import BeautifulStoneSoup soup = BeautifulStoneSoup(xml) Then I'm not sure what. I've tried a lot of things but everything seems to throw back way more junk than I want and it makes to difficult to find the issue. I'm trying just get the id, title, mileage, price, year, vin. So how do I get these and expedite the process with a loop? Ideally I wanted a for loop like: for soup.listings.element in soup.listings: id = soup.listings.element.id ... I know that doesn't work obviously but something that would fetch info for the listing, and store it into a list, then move onto the next ad. Appreciate the help guys Answer: You could do something like this: for element in soup('element'): id = element.id.text mileage = element.attributes.mileage.text price = element.attributes.price.text year = element.attributes.year.text vin = element.attributes.vin.text
Django, urls.py, include doesn't seem to be working Question: I'm trying to include an additional urls.py inside my main urls - however it doesn't seem to be working. I've done a bunch of searching and I can't seem to figure it out main urls.py file - the admin works fine from django.conf.urls.defaults import patterns, include, url from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', (r'^pnasser/',include('pnasser.urls')), (r'^admin/',include(admin.site.urls)), (r'^',include('pnasser.urls')), ) I then have a folder pnasser, with the file urls.py with the following: from django.conf.urls.defaults import patterns, include, url urlpatterns = patterns('pnasser.views', (r'^$','index'), (r'^login/$','login'), (r'^signup/$','signup'), (r'^insertaccount/$','insertaccount'), (r'^home/$','home'), (r'^update/(?P<accid>\d+)','update'), (r'^history/(?P<accid>\d+)','account_history'), (r'^logout/(?P<accid>\d+)','logout'), ) I'm not sure if I'm maybe missing something else in the configuration. if I visit mysite.com/admin it loads the admin correctly, if I goto mysite or any other url in the views I get 404 page not found: > Using the URLconf defined in mysite.urls, Django tried these URL patterns, > in this order: 1\. ^pnasser/ 2\. ^admin/ > > The current URL, , didn't match any of these. **edit** settings.py installed apps: INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', #'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', # Uncomment the next line to enable the admin: 'django.contrib.admin', # Uncomment the next line to enable admin documentation: # 'django.contrib.admindocs', 'pnasser', ) **Update 2** So, I also tried running my site via the dev server: `python manage.py runserver 0.0.0.0:8000` this works. I'm assuming somewhere in my integration with apache using mod_wsgi is the problem. However, I'm not sure where the problem would be Answer: The problem seemed to be in the django.wsgi file - and the differences in how the standard django.wsgi file loads a python site vs how the development server loads the site. I guess it's a well known issue, that I was unaware of. Thanks everyone for the suggestions. Alternative django.wsgi file found here: <http://blog.dscpl.com.au/2010/03/improved-wsgi-script-for-use-with.html>
How to enable Eclipse debugging features in a web application? Question: I am using Django framework for my Python Web Application using Eclipse IDE and PyDev Plugin. How can I use the debugging features? **UPDATES1** particularly using <http://pydev.org/updates> plugin **UPDATES2** I already did the following: **.pydevproject** <?xml version="1.0" encoding="UTF-8" standalone="no"?> <?eclipse-pydev version="1.0"?> <pydev_project> <pydev_property name="org.python.pydev.PYTHON_PROJECT_INTERPRETER">Python25 </pydev_property> <pydev_property name="org.python.pydev.PYTHON_PROJECT_VERSION">python 2.5 </pydev_property> <pydev_pathproperty name="org.python.pydev.PROJECT_SOURCE_PATH"> <path>/pi-proto</path> </pydev_pathproperty> <pydev_pathproperty name="org.python.pydev.PROJECT_EXTERNAL_SOURCE_PATH"> <path>C:\Program Files\GeoDjango\Django-1.0.2-final</path> <path>C:\eclipse-SDK-3.7-win32\plugins\org.python.pydev.debug_2.2.3.2011100616\pysrc </path> </pydev_pathproperty> </pydev_project> **manage.py** #!/usr/bin/env python from django.core.management import execute_manager try: import settings # Assumed to be in the same directory. except ImportError: import sys sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__) sys.exit(1) if __name__ == "__main__": import sys if len(sys.argv) > 1: command = sys.argv[1] if settings.DEBUG and (command == "runserver" or command == "testserver"): # Make pydev debugger works for auto reload. try: import pydevd except ImportError: sys.stderr.write("Error: " + "You must add org.python.pydev.debug.pysrc to your PYTHONPATH.") sys.exit(1) from django.utils import autoreload m = autoreload.main def main(main_func, args=None, kwargs=None): import os if os.environ.get("RUN_MAIN") == "true": def pydevdDecorator(func): def wrap(*args, **kws): pydevd.settrace(suspend=False) return func(*args, **kws) return wrap main_func = pydevdDecorator(main_func) return m(main_func, args, kwargs) autoreload.main = main execute_manager(settings) **Run Configurations - Arguments** runserver 0.0.0.0:8001 **UPDATES3** I am following this link <http://bear330.wordpress.com/2007/10/30/how-to-debug-django-web-application- with-autoreload/> But no success. Would you guide me on how to correctly follow the above link..Then I will update the result here. **UPDATES4** I am using Python 2.5.2, GeoDjango 1.2.7, Eclipse Indigo with PyDev Plugin. Answer: Here are some how-tos: * <http://matt.geek.nz/2009/02/debugging-django-apps-with-eclipse-and-pydev/> * [Django debugging with Eclipse and PyDev](http://stackoverflow.com/questions/3527934/django-debugging-with-eclipse-and-pydev) * <http://brill.no/debugging-django-apps-with-eclipse/>
Using Groupby to Group a Column in an Access Table in Python Question: I have been playing with the groupby function from the itertools module for a while now (like days) for k, g in groupby(data, keyfunc): I am really having trouble understanding the syntax. I've tried a variety of different things, but I really don't know what to put in for "data" and "keyfunc" and get it to return the groups of data I want in a print statement. What am I doing is looping through rows in an access table. I set a variable to a cursor search (which is sorted) in the access table and pull out the column I want. for row in cursor: print row.ROAD_TYPE This returns: TRUNK ROAD TRUNK ROAD TRUNK ROAD TRUNK ROAD COLLECTOR HIGHWAY COLLECTOR HIGHWAY ACCESS ROAD ACCESS ROAD ACCESS ROAD ACCESS ROAD ACCESS ROAD ACCESS ROAD ACCESS ROAD MAJOR ROAD MAJOR HIGHWAY I want to group these values together and have it return the string value for me so it prints something like this: TRUNK ROAD TRUNK ROAD TRUNK ROAD TRUNK ROAD COLLECTOR HIGHWAY COLLECTOR HIGHWAY ACCESS ROAD ACCESS ROAD ACCESS ROAD ACCESS ROAD ACCESS ROAD ACCESS ROAD ACCESS ROAD MAJOR ROAD MAJOR HIGHWAY Finally, I want to group a second column based on these new groups so that I get something like this: TRUNK ROAD M1 TRUNK ROAD M1 TRUNK ROAD M2 TRUNK ROAD M3 COLLECTOR HIGHWAY M1 COLLECTOR HIGHWAY M2 ACCESS ROAD M1 ACCESS ROAD M1 ACCESS ROAD M3 ACCESS ROAD M3 ACCESS ROAD M7 ACCESS ROAD M7 ACCESS ROAD M8 MAJOR ROAD M8 MAJOR HIGHWAY M8 I know this is probably way less difficult than I've made it out for myself, I feel there's a simple answer, but I'm completely stumped and I can't seem to find an example on the internet that explains the groupby syntax in a way that I understand. Please feel f Answer: import itertools as it for key, group in it.groupby(cursor, lambda row: row.ROAD_TYPE): for sec_col,pairs in it.groupby(group, lambda row: row.SECOND_COLUMN): for row in pairs: print('{t} {s}'.format(t=row.ROAD_TYPE,s=row.SECOND_COLUMN)) print print Here are two examples to help grok [groupby](http://docs.python.org/library/itertools.html#itertools.groupby): [list(g) for k, g in it.groupby('AAAABBBCCD')] # [['A', 'A', 'A', 'A'], ['B', 'B', 'B'], ['C', 'C'], ['D']] Above, all items which are the same, are grouped together. Now we add a key function, `keyfunc`: keyfunc=lambda x: x//3 data=range(13) [list(g) for k,g in it.groupby(data,keyfunc)] # [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11], [12]] [k for k,g in it.groupby(data,keyfunc)] # [0, 1, 2, 3, 4] Now instead of grouping by the items in data, we group according to `keyfunc(x)` for each `x` in `data`.
jinja2 macros vs jsp2.0 tags Question: I am a **java** programmer learning **python/jinja**. My biggest beef with jinja2 macros is the limitation of having a single caller(). for example, i could do the following in jsp2 tags: tag def: <% attribute name="title" fragment="true"> <div class='title'>${title}</div> <div class='body'><jsp:doBody/></div> usage: <myTag> <jsp:attribute name='title'> <c:if test='${blah}'>This is only here sometimes</c:if> </jsp:attribute> <jsp:body> <c:if test='${something}'>some dynamic content</c:if> </jsp:body> </myTag> what i want to **stress** here, is that both the body content and the 'title' attribute have content that is **dynamic**. also, there are no hacks here of setting variables to dynamic content and passing them in. now lets look at a jinja macro that does the same thing: {% macro myTag(title='', caller) -%} <div class='title'>{{ title }}</div> <div class='body'>{{ caller() }}</div> {%- endmacro %} but wait! **i cannot easily** put dynamic content into the title attribute! {% call myTag(title='imagine putting some content here that involves 5 loops, 4 ifs and whatnot?') %} {% if something %}some dynamic content{% endif %} {% endcall %} is this a problem with my being a newbie, or is this a shortcoming of jinja? Answer: So in fact this is a core feature of [Mako Templates for Python](http://www.makotemplates.org/). It's not as widely used of a feature but it's important to me, as it's pretty critical in custom template tags as you mention, so it's there: <http://www.makotemplates.org/docs/defs.html#calling-a-def-with-embedded- content-and-or-other-defs> JSP is one of several template systems Mako draws inspiration from.
Tweepy (twitter) socket.error Errno 104 (Connection reset by peer) Question: I am trying to acces the Streaming API, filter it by some terms and then print out the results, using Tweepy. However I am getting the following error: File "/usr/local/lib/python2.6/dist-packages/tweepy-1.7.1-py2.6.egg/tweepy/streaming.py", line 110, in _run resp = conn.getresponse() File "/usr/lib/python2.6/httplib.py", line 986, in getresponse response.begin() File "/usr/lib/python2.6/httplib.py", line 391, in begin version, status, reason = self._read_status() File "/usr/lib/python2.6/httplib.py", line 349, in _read_status line = self.fp.readline() File "/usr/lib/python2.6/socket.py", line 397, in readline data = recv(1) socket.error: [Errno 104] Connection reset by peer With the following code... import sys import tweepy from textwrap import TextWrapper from tweepy.streaming import StreamListener, Stream consumer_key = '' consumer_secret = '' access_token = '' access_token_secret = '' auth1 = tweepy.OAuthHandler(consumer_key, consumer_secret) auth1.set_access_token(access_token, access_token_secret) api = tweepy.API(auth1) class StreamListener(tweepy.StreamListener): status_wrapper = TextWrapper(width=60, initial_indent=' ', subsequent_indent=' ') def on_status(self, status): try: print self.status_wrapper.fill(status.text) print '\n %s %s via %s\n' % (status.author.screen_name, status.created_at, status.source) except Exception, e: pass def main(): l = StreamListener() streamer = tweepy.Stream(auth=auth1, listener=l, timeout=3000000000 ) setTerms = ['hello', 'goodbye', 'goodnight', 'good morning'] streamer.filter(None,setTerms) if __name__ == "__main__": main() Does anyone know how to solve it? Thanks... Answer: The reason was SSL, it seems to be forced by twitter now...
Python - ssh with password to foreign computer without using non-built-in modules Question: Before you down vote this, let me say that I've read ALOT of questions on this subject on SO and haven't found the answer. This one has the closest thing to what I need though on the answer by "Neil". [What is the simplest way to SSH using Python?](http://stackoverflow.com/questions/1233655/what-is-the-simplest-way- to-ssh-using-python) I would like to find a way to log into another host using ssh, providing a password, without importing non-standard python modules. I would then need to be able to send multiple commands using the ssh connection. I need to do this because I need to automate something on a lot of closed systems that I cannot get new modules on to (non internet accessible). The answer in the referenced question is: > If you want to avoid any extra modules, you can use the subprocess module to > run > > ssh [host] [command] and capture the output. > > Try something like: > > process = subprocess.Popen("ssh example.com ls", shell=True, > stdout=subprocess.PIPE, stderr=subprocess.STDOUT) output,stderr = > process.communicate() status = process.poll() print output To deal with > usernames and passwords, you can use subprocess to interact with the ssh > process, or you could install a public key on the server to avoid the > password prompt. Which sounds good, but I can't quite understand this well enough to take it farther. Can someone help me to get a baby step going? (1) log in to ssh (2) provide the password when its prompted (3) issue an ls command and display the result I can do the rest of the automation if I can just get pass password entry. PS: I tried using expect, but TCL isn't on the system so please don't tell me to use that! If you know something else I can call to aid python I'm happy to try it though as long as its likely to be built into a Fedora Enterprise Linux system by default. Answer: This code uses Popen.communicate() to run a command. As described in chapter 17 of the Python Library Reference, communicate() opens pipes for stdin, stdout, and stderr, starts up the subprocess, and waits for the process to terminate. FYI for other readers: startupinfo is the Windows-specific way of running the subprocess under a GUI app without popping up a black console window; it's not needed when running as a console script or under Linux. def runcmd(self, prog, args, inputs): cmd = " ".join((prog, args)) si = subprocess.STARTUPINFO() si.dwFlags = subprocess.STARTF_USESHOWWINDOW process = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE, startupinfo=si) return(process.communicate(input=inputs)) It can be called with: p = self.runcmd("c:\Program Files\ApplicationDir\application.exe", "arguments", "inputs") result = str(p[0],"ascii").strip() print(result) The result a 2-tuple (stdout, stderr), which should be converted from byte strings to strings. The password passed as "inputs" should be a byte string.
in python, is there a way to find the module that contains a variable or other object from the object itself? Question: As an example, say I have a variable defined where there may be multiple from __ import * from ____ import * etc. Is there a way to figure out where one of the variables in the namespace is defined? _edit_ Thanks, but I already understand that import * is often considered poor form. That wasn't the question though, and in any case I didn't write it. It'd just be nice to have a way to find where the variable came from. Answer: This is why it is considered bad form to use `from __ import *` in python in most cases. Either use `from __ import myFunc` or else `import __ as myLib`. Then when you need something from `myLib` it doesn't over lap something else. For help finding things in the current namespace, check out the [pprint library](http://docs.python.org/library/pprint.html), [the dir builtin](http://docs.python.org/library/functions.html#dir), [the locals builtin](http://docs.python.org/library/functions.html#locals), [and the globals builtin](http://docs.python.org/library/functions.html#globals).
How to set the sharing rights of a folder in Plone? Question: I want to set sharing rights of many folders by using a Python script in a Plone site. Answer: You need to look at the [`AccessControl/rolemanager.py`](https://github.com/zopefoundation/AccessControl/blob/master/src/AccessControl/rolemanager.py) module for details; the sharing tab in Plone is a friendly wrapper around that API. To add roles for a given userid, call [`manage_addLocalRoles`](https://github.com/zopefoundation/AccessControl/blob/master/src/AccessControl/rolemanager.py#L323-L336): context.manage_addLocalRoles('userid', ('Role1', 'Role2',)) The other two important methods are `manage_setLocalRoles(userid, roles)` (replace the current set of roles completely) and `manage_delLocalRoles(userid)` (delete all roles). `get_local_roles_for_userid(userid)` could be handy too, to see what local roles are already defined. You want to reindex security information after such changes: context.reindexObjectSecurity()
Converting strings into another data type, Python Question: I have the string `"(0, 0, 0)"`. I'd like to be able to convert this to a tuple. The built in `tuple` function doesn't work for my purposes because it treats each character as an individual item. I want to be able to convert `"(0, 0, 0)"` to `(0, 0, 0)` programmatically. Answer: You can use [ast.literal_eval](http://docs.python.org/library/ast.html#ast.literal_eval) >>> import ast >>> ast.literal_eval('(0,0,0)') (0, 0, 0)
PyQt4: Interrupted system call while calling commands.getoutput() in timer Question: The problem appeared to be very simple, but I can not find any solution after a day of googling and looking at stackoverflow. Originally I am developing a simple plasmoid which will send a specific request to local web-server every 30 minutes, parse output and display in a label on panel. I took an example of plasmoid - [BWC-Balance](https://bitbucket.org/svartalf/bwc-balance- plasmoid/src/) \- and modified it. Here is the code: #!/usr/bin/env python # coding: utf-8 """ BWC Balance plasmoid Site: http://bitbucket.org/svartalf/bwc-balance-plasmoid/ Author: SvartalF (http://svartalf.info) Original idea: m0nochr0me (http://m0nochr0me.blogspot.com) """ import re from urllib import urlencode import urllib2 import cookielib import datetime import sys import re import string import os import gobject import commands from PyQt4.QtCore import * from PyQt4.QtGui import * from PyKDE4.kio import * from PyKDE4.kdeui import * from PyKDE4.kdecore import * from PyKDE4.plasma import Plasma from PyKDE4 import plasmascript from PyKDE4.solid import Solid from settings import SettingsDialog parsed_ok = 0 curr_day = '' class BWCBalancePlasmoid(plasmascript.Applet): """Applet main class""" def __init__(self, parent, args=None): plasmascript.Applet.__init__(self, parent) def init(self): """Applet settings""" self.setHasConfigurationInterface(True) self.setAspectRatioMode(Plasma.Square) self.theme = Plasma.Svg(self) # self.theme.setImagePath("widgets/background") # self.setBackgroundHints(Plasma.Applet.DefaultBackground) self.layout = QGraphicsLinearLayout(Qt.Horizontal, self.applet) # Main label with balance value self.label = Plasma.Label(self.applet) self.label.setText(u'<b><font color=blue size=3>No data...</font></b>') self.layout.addItem(self.label) self.applet.setLayout(self.layout) self.resize(350, 30) self.startTimer(2500) def postInit(self): """Start timer and do first data fetching Fired only if user opened access to KWallet""" self.setLabelText() def update(self, value): """Update label text""" self.label.setText(value) def timerEvent(self, event): """Create thread by timer""" self.setLabelText() pass def setLabelText(self): login = 'mylogin' request = 'curl --ntlm -sn http://some.local.resource' out_exp = "" out_exp = commands.getoutput(request) table_name_exp = re.findall(r"some_regular_expression",out_exp) tp = '| html2text | grep -i -A3 ' + login out_exp = '' try: cmd_exp = 'curl --ntlm -sn ' + table_name_exp[0] + ' ' + tp out_exp = commands.getoutput(cmd_exp) except: cmd_exp = '' date_check = re.findall(r"one_more_regular_expression", out_exp) times_exp = re.findall(r"[0-9][0-9]:[0-9][0-9]", out_exp ) if len(times_exp) != 0 and len(date_check) != 0: self.label.setText(u'<b><font color=blue size=3>Start: ' + times_exp[0] + u' --- Finish: ' + str(int(string.split(times_exp[0], ':')[0]) + 9) + ':' + string.split(times_exp[0], ':')[1] + ' </span></b>') else: self.label.setText(u'<b><font color=blue size=3>No data...</span></b>') def CreateApplet(parent): return BWCBalancePlasmoid(parent) And what I get is the following error: # plasmoidviewer bwc-balance plasmoidviewer(25255)/kdecore (services) KServiceFactory::findServiceByDesktopPath: "" not found plasmoidviewer(25255)/libplasma Plasma::FrameSvg::resizeFrame: Invalid size QSizeF(0, 0) plasmoidviewer(25255)/libplasma Plasma::FrameSvg::resizeFrame: Invalid size QSizeF(0, 0) Traceback (most recent call last): File "/home/grekhov/.kde/share/apps/plasma/plasmoids/bwc-balance/contents/code/main.py", line 116, in timerEvent self.setLabelText() File "/home/grekhov/.kde/share/apps/plasma/plasmoids/bwc-balance/contents/code/main.py", line 146, in setLabelText out_exp = commands.getoutput(request) File "/usr/lib/python2.7/commands.py", line 50, in getoutput return getstatusoutput(cmd)[1] File "/usr/lib/python2.7/commands.py", line 60, in getstatusoutput text = pipe.read() IOError: [Errno 4] Interrupted system call As I understood after several hours of googling: reading from pipe is interrupted with some signal. But the only signal I have is timer. The only recommendation I have found is "get rid of the signal which interrupts your read". And it appears a bit strange and unrealistic for me: read data periodically without timer. Am I missing something? Maybe there should be used some other mechanism for accessing web-resource and parsing its output? Or "Interrupted system call" is a normal situation and should be handled somehow? Thanks in advance for help. Answer: It appears that a signal is being delivered whilst the pipe is still reading. So try stopping the timer before calling `setLabelText()`, and then restart it again afterwards. **EDIT** You should also try rewriting your code to use `subprocess` instead of the deprecated `commands` module. For example: pipe = subprocess.Popen(['curl', '--ntlm', '-sn', 'http://some.local.resource'], stdout=subprocess.PIPE) output = pipe.communicate()[0]
Pandas + Django + mod_wsgi + virtualenv Question: Pandas is producing **'module' object has no attribute 'core'** when being imported under django and mod_wsgi inside a virtual environment. It works fine running under the django development server inside the virtual environment. Other modules e.g.: numpy have no problems so I assume this means the virtual environment is set up correctly with mod_wsgi. Any advice would be appreciated. ### staging.wsgi import os import sys import site PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(__file__))) site_packages = os.path.join(PROJECT_ROOT, 'env/openportfolio/lib/python2.7/site-packages') site.addsitedir(os.path.abspath(site_packages)) sys.path.insert(0, PROJECT_ROOT) sys.path.insert(0, os.path.dirname(os.path.dirname(__file__))) os.environ['DJANGO_SETTINGS_MODULE'] = 'openportfolio.settings_staging' import pandas #triggers error import django.core.handlers.wsgi application = django.core.handlers.wsgi.WSGIHandler() ### Error Traceback (most recent call last): File "/usr/local/web/django/www/staging/openportfolio/apache/staging.wsgi", line 22, in <module> import pandas File "/usr/local/web/django/www/staging/env/openportfolio/lib/python2.7/site-packages/pandas/__init__.py", line 12, in <module> from pandas.core.api import * File "/usr/local/web/django/www/staging/env/openportfolio/lib/python2.7/site-packages/pandas/core/api.py", line 6, in <module> import pandas.core.datetools as datetools AttributeError: 'module' object has no attribute 'core' ### Python Path ['/usr/local/web/django/www/staging/openportfolio', '/usr/local/web/django/www/staging', '/Library/Python/2.7/site-packages/pip-1.0.2-py2.7.egg', '/usr/local/web/django/www/staging/env/openportfolio/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg', '/usr/local/web/django/www/staging/env/openportfolio/lib/python2.7/site-packages/pip-1.0.2-py2.7.egg', '/usr/local/web/django/www/staging/env/openportfolio/lib/python2.7/site-packages/matplotlib-1.1.0-py2.7-macosx-10.7-intel.egg', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python27.zip', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages', '/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-old', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload', '/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/PyObjC', '/Library/Python/2.7/site-packages', '/usr/local/web/django/www/staging/env/openportfolio/lib/python2.7/site-packages'] Answer: So it turns out this was a Python path order issue. By running sys.path.reverse() in my wsgi config file, the code now runs. Due to the order of Python path, the built in OS X numpy library must have been imported first over the virtual environment one causing the issue. 'RuntimeError: module compiled against API version 6 but this version of numpy is 4' was the error line I missed in my original post which could have helped debug the answer.
C++-classes with SWIG Question: I try to create a python interface (with swig) from C++-code. With the code below. When I remove the line: aClass z = aClass(1); from the .cpp-file i get the following error: Traceback (most recent call last): File "./testit.py", line 3, in <module> import testlib File "(...)/testlib.py", line 26, in <module> _testlib = swig_import_helper() File "(...)/testlib.py", line 22, in swig_import_helper _mod = imp.load_module('_testlib', fp, pathname, description) ImportError: (...)/_testlib.so: undefined symbol: _ZN6aClassC1Ei What am I doing wrong? **testlib.cpp** #include <iostream> #include <string.h> using namespace std; class aClass { public: aClass(int i) { iD = i; } void printiD() { cout << iD << endl; } private: int iD; }; void doSomething(string s) { cout << "testlib: I did something with:" << s << endl; } void outprintiD(aClass ff) { ff.printiD(); } string returnSomething(string s) { return s; } //Don't know why, but without the next line it doesn't work. :( aClass z = aClass(1); **testlib.i** %module testlib %include "std_string.i" using namespace std; %{ class aClass { public: aClass(int i); void printiD(); private: int iD; }; void outprintiD(aClass ff); void doSomething(std::string s); std::string returnSomething(std::string s); %} class aClass { public: aClass(int i) ; void printiD(); private: int iD; }; void outprintiD(aClass ff); void doSomething(std::string s); std::string returnSomething(std::string s); **testit.py** #!/usr/bin/python import testlib testlib.doSomething("doS"); var = testlib.returnSomething("rSo"); print var aClassInstance = testlib.aClass(42) testlib.outprintiD(aClassInstance) print "done..." **execution script** swig -c++ -python $1.i g++ -c -fPIC $1.cpp $1_wrap.cxx -I/usr/include/python2.7 g++ -shared $1.o $1_wrap.o -o _$1.so Answer: vines@Aspire-5755G:~$ c++filt _ZN6aClassC1Ei aClass::aClass(int) It's a linker error. Try: g++ -shared $1_wrap.o $1.o -o _$1.so i.e. swap the object files. It's because the order they are given matters, and it's reasonable to suppose that `$1_wrap.o` wants to pull some methods from `$1.o`.
main color detection in Python Question: I have about 3000 images and 13 different colors (the background of the majority of these images is white). If the main color of an image is one of those 13 different colors, I'd like them to be associated. I've seen similar questions like [Image color detection using python](http://stackoverflow.com/questions/2270874/image-color-detection- using-python) that ask for an average color algorithm. I've pretty much copied that code, using the Python Image Library and histograms, and gotten it to work - but I find that it's not too reliable for determining main colors. Any ideas? Or libraries that could address this? Thanks in advance! :EDIT: Thanks guys - you all pretty much said the same thing, to create "buckets" and increase the bucket count with each nearest pixel of the image. I seem to be getting a lot of images returning "White" or "Beige," which is also the background on most of these images. Is there a way to work around or ignore the background? Thanks again. Answer: You can use the [getcolors](http://effbot.org/tag/PIL.Image.Image.getcolors) function to get a list of all colors in the image. It returns a list of tuples in the form: (N, COLOR) where `N` is the number of times the color `COLOR` occurs in the image. To get the maximum occurring color, you can pass the list to the [max](http://docs.python.org/library/functions.html#max) function: >>> from PIL import Image >>> im = Image.open("test.jpg") >>> max(im.getcolors(im.size[0]*im.size[1])) (183, (255, 79, 79)) Note that I passed `im.size[0]*im.size[1]` to the getcolors function because that is the maximum `maxcolors` value (see [the docs](http://effbot.org/tag/PIL.Image.Image.getcolors) for details).
Adding testcase results to Quality Center Run from a outside Python Script Question: I want to try to add all the step details - Expected, Actual, Status, etc. to a QC Run for a testcase of a TestSet from a Python Script living outside the Quality Center. I have come till here (code given below) and I don't know how to add Step Expected and Step Actual Result. If anyone knows how do it, please help me out!! Please, I don't want any QTP solutions. Thanks, Code- # Script name - add_tsrun.py # C:\Python27\python.exe # This script lives locally on a Windows machine that has - Python 2.7, Win32 installed, IE8 # Dependencies on Windows Machine - Python 2.7, PythonWin32 installed, IE8, a QC Account, connectivity to QCServer import win32com.client, os tdc = win32com.client.Dispatch("TDApiOle80.TDConnection") tdc.InitConnection('http://QCSERVER:8080/qcbin') tdc.Login('USERNAME', 'PASSWORD') tdc.Connect('DOMAIN_NAME', 'PROJECT') tsFolder = tdc.TestSetTreeManager.NodeByPath('Root\\test_me\\sub_folder') tsList = tsFolder.FindTestSets('testset1') ts_object = tsList.Item(1) ts_dir = os.path.dirname('testset1') ts_name = os.path.basename('testset1') tsFolder = tdc.TestSetTreeManager.NodeByPath(ts_dir) tsList = tsFolder.FindTestSets(ts_name) ts_object = tsList.Item(1) TSTestFact = ts_object.TSTestFactory TestSetTestsList = TSTestFact.NewList("") ts_instance = TestSetTestsList.Item(1) newItem = ts_instance.RunFactory.AddItem(None) # newItem == Run Object newItem.Status = 'No Run' newItem.Name = 'Run 03' newItem.Post() newItem.CopyDesignSteps() # Copy Design Steps newItem.Post() steps = newItem.StepFactory.NewList("") step1 = steps[0] step1.Status = "Not Completed" step1.post() ## How do I change the Actual Result?? ## I can access the Actual, Expected Result by doing this, but not change it step1.Field('ST_ACTUAL') = 'My actual result' # This works in VB, not python as its a Syntax error!! Traceback ( File "<interactive input>", line 1 SyntaxError: can't assign to function call Hope this helps you guys out there. If you know the answer to set the Actual Result, please help me out and let me know. Thanks, Amit Answer: Found the answer after a lot of Google Search :) Simple -> Just do this: step1.SetField("ST_ACTUAL", "my actual result") # Wohhooooo!!!! If the above code fails to work, try to do the following:- (OPTIONAL) Set your win32 com as follows- (Making ''Late Binding'') # http://oreilly.com/catalog/pythonwin32/chapter/ch12.html a. Start PythonWin, and from the Tools menu, select the item COM Makepy utility. b. Using Windows Explorer, locate the client subdirectory (OTA COM Type Library) under the main win32com directory and double-click the file makepy.py. Thank you all...
Time and date on the basis of seconds elapsed since 1970 year Question: Using python I have to retrieve value of time and date of an event knowing how many seconds elapsed since `01/01/1970 00:00:00`. I started with: from datetime import timedelta a = timedelta(seconds=1317365200) print "%d days %02d:%02d:%02d" % (a.days, a.seconds / 3600, (a.seconds / 60) % 60, a.seconds % 60)1317365200 ` Record of seconds elapsed are stored in **Sqlite 3** database. Answer: from datetime import datetime a = datetime.fromtimestamp(1317365200) print a
Seeing exceptions from methods registered to SimpleXMLRPCServer Question: I'm writing an xmlrpc-based python 2.7 program, using SimpleXMLRPCServer. I import the class with all our logic and register it with: server = SimpleXMLRPCServer(("0.0.0.0", 9001)) server.register_instancce(classWithAllTheLogic()) server.serve_forever() When running this in console I can see the log messages from SimpleXMLRPCServer about what messages are being sent, but all of the debug information from methods within classWithAllTheLogic() seems to be surpressed. If a method throws an exception there, I don't see any error message in console, and the xmlrpc call bound to that method just silently fails. print statements within the classWithAllTheLogic methods also just don't show up. What's going on here? Answer: I am unable to reproduce this. Test script _test.py_ from xmlrpc.server import SimpleXMLRPCServer class classWithAllTheLogic: def __init__(self): print("Hi") raise Exception("INIT Exception") def hello(self): print("hello") raise Exception("Hello Exception") server = SimpleXMLRPCServer(("0.0.0.0", 9001)) server.register_instance(classWithAllTheLogic()) server.serve_forever() Run: E:\tmp>python test.py Hi Traceback (most recent call last): File "test.py", line 13, in <module> server.register_instance(classWithAllTheLogic()) File "test.py", line 6, in __init__ raise Exception("INIT Exception") Exception: INIT Exception E:\tmp> **?!**
How can I represent an infinite number in Python? Question: In python, when you want to give to a set of elements an associated value, and you use this value for comparisons between them, I would want this value as infinite. No matter which number you enter in the program, no number will be greater than this representation of infinity. Answer: In Python, you can do: test = float("inf") In Python 3.5, you can do: import math test = math.inf And then: test > 1 test > 10000 test > x Will always be true. Unless of course, as pointed out, x is also infinity or "nan" ("not a number"). Additionally (Python 2.x ONLY), in a comparison to `Ellipsis`, `float(inf)` is lesser, e.g: float('inf') < Ellipsis would return true.
Unusual issue with HTML image and 'file://' specified src Question: I'm loading an image on the page with a 'file:///some_dir/image.jpg' src path. I can access the image in a regular tab using this path. Also, saving the page as HTML and using this path for the image works. However, the image does not load on the live page. In chrome it shows part of the alt text, and in firefox it shows a narrow strip. I have tried changing width and height but to no avail. Is there something I'm missing? <img title="Click to enlarge" src="file:///Users/Aram/uploads/profile.image.985b0f707d972bf3.4372696242656464696e67616e645465657468696e67437269625261696c436f7665722e6a7067.jpg" class="profile-image"> **EDIT:** I noticed I am getting this in the console: > Not allowed to load local resource Is there any way around this? **EDIT 2:** Since I could not access the image through an http path, I have decided to read it in as base64 data. For anyone else using web2py or another Python framework: # Load the image data import os path = os.path.join(request.folder, 'uploads', filename) data_uri = open(path, 'rb').read().encode('base64').replace('\n', '') data = 'data:image/png;base64,%s' % data_uri return html.IMG( _src=data, _class='profile-image', _title='Click to enlarge' ) Answer: Websites are not allowed to use local files on the user's computer. Use a relative path to from the html file's directory. You can also encode and embed the image directly: How to embed the encoded stuff: <http://www.sweeting.org/mark/blog/2005/07/12/base64-encoded-images-embedded- in-html> Python Encoding Instructions: <http://www.daniweb.com/software- development/python/code/216635>
After installing matplotlib basemap via Macports, example python code for basemap is not running Question: I'm using Mac OS X 10.6.8. I installed Python 2.6 using the binary installer in <http://www.python.org/>. I've been using it along with SciPy and Matplotlib for my scientific computing needs since March 2011 without any problems. Recently, I have the need for the matplotlib library called Basemap. I followed this article on <https://modelingguru.nasa.gov/docs/DOC-1847>. It states that the easiest way to install the Basemap library is through Macports (or Fink). So I tried to install Basemap via Macports. I executed the command port install py-matplotlib-basemap and it seems to install so many things such as Python 2.4, etc. So to be specific, I used Macports again but this time using port install py26-matplotlib-basemap since I'm using Python 2.6. The installation didn't seem to have any problems. Now I tested if Basemap was properly installed by running a Python code example that uses basemap for graphing. But the terminal says the following before coming back to the prompt: Traceback (most recent call last): File "basemap-test.py", line 1, in <module> from mpl_toolkits.basemap import basemap File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/mpl_toolkits/basemap/__init__.py", line 45, in <module> import _geoslib, netcdftime ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/_geoslib.so, 2): Symbol not found: _GEOSArea Referenced from: /Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/_geoslib.so Expected in: dynamic lookup What may be wrong here? I know that Macports installs its own Python version, I don't know if that has an effect on this problem. Answer: As you noted, MacPorts installs its own Python version (by default, at `/opt/local/bin/python2.6`). If you install a Python package via MacPorts, like basemap, you normally will need to run everything under the MacPorts Python. Don't try to mix and match Python instances. Packages that include C extension modules or depend on other packages which include C libraries have to be built in a way that is compatible with the way the Python interpreter was built. The Python 2.6 installers from python.org are 32-bit-only and built to be compatible with a range of OS X versions. By default, what MacPorts builds will be 64-bit on 10.6, if possible, and only tailored for 10.6 systems. The safest and easiest option long term would be to switch to using the MacPorts Python, ensuring that all the packages you need are installed from MacPorts.
Boost / Python unix timestamps don't match Question: Python 2.6: import pytz import time import datetime time.mktime(datetime.datetime(1990, 1, 1, tzinfo=pytz.utc).timetuple()) Result: 631148400.0 Boost 1.46: auto a = boost::posix_time::ptime(boost::gregorian::date(1990, 1, 1)); auto b = boost::posix_time::ptime(boost::gregorian::date(1970, 1, 1)); // unix epoch boost::posix_time::time_duration x = a - b; std::cerr << x.total_seconds() << std::endl; Result: 631152000 Difference is 3600 (1 hour). Why? Answer: For the example below I set my time zone to GMT-01: >>> import datetime, time, pytz >>> tz = pytz.FixedOffset(-60) >>> dt = datetime.datetime(1990, 1, 1, tzinfo=pytz.utc) >>> tm = dt.astimezone(tz).timetuple(); tm time.struct_time(tm_year=1989, tm_mon=12, tm_mday=31, tm_hour=23, tm_min=0, tm_s ec=0, tm_wday=6, tm_yday=365, tm_isdst=0) >>> time.mktime(tm) 631152000.0 `mktime` takes a time tuple based on local time, so the UTC `datetime` object has to first be adjusted to local time.
Python check if a process is running or not Question: I am trying to create a python script which I will later run as a service. Now I want to run a particular part of the code only when iTunes is running. I understand from some research that polling the entire command list and then searching for the application for that list is expensive. I found out that Programs in unix based operating systems create a lock file to notify that a program is currently running. So we can use os.stat(location_of_file) to check if the file exists to determine if a program is running or not. Is there a similar lock file created in windows ? If not what are the various ways in python by which we can determine if a process is running or not ? I am using python 2.7 and iTunes COM interface. Answer: You can not rely on lock files in Linux or Windows. I would just bite the bullet and iterate through all the running programs. I really do not believe it will be as "expensive" as you think. [psutil](http://code.google.com/p/psutil/) is an excellent cross-platform python module cable of enumerating all the running programs on a system. import psutil "someProgram" in [psutil.Process(i).name for i in psutil.get_pid_list()]
working with combinations object in python Question: >>> import itertools >>> n = [1,2,3,4] >>> combObj = itertools.combinations(n,3) >>> >>> combObj <itertools.combinations object at 0x00000000028C91D8> >>> >>> list(combObj) [(1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4)] >>> >>> for i in list(combObj): #This prints nothing ... print(i) ... 1. How can i iterate through combObj ? 2. How can i convert `[(1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4)]` to `[[1, 2, 3], [1, 2, 4], [1, 3, 4], [2, 3, 4]]` Answer: Once you iterate through the `itertools.combinations` object once, it's been used up and you can't iterate over it a second time. If you need to reuse it, the proper way is to make it a `list` or `tuple` as you did. All you need to do is give it a name (assign it to a variable) so it sticks around. combList = list(combObject) # Don't iterate over it before you do this! If you want to iterate over it just once, you just don't call `list` on it at all: for i in combObj: # Don't call `list` on it before you do this! print(i) Side note: The standard way to name object instances / normal variables would be `comb_obj` rather than `combObj`. See [PEP-8](http://www.python.org/dev/peps/pep-0008/) for more info. To convert the inner `tuple`s to `list`s, use a list comprehension and the `list()` built-in: comb_list = [(1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4)] comb_list = [list(item) for item in comb_list]
How do I fix the syntax in my code to make my radio buttons work with my dictionary? Question: I am trying to learn how to use a _dictionary_ with a radio button. I have the code below but when ever I run it I get an error. The error says: Traceback (most recent call last): File "/Volumes/CHROME USB/STORAGE/TKinker GUI/Radiobutton + Dictionary.py", line 16, in <module> for i in sorted(choices.keys()): NameError: name 'choices' is not defined Here's my code: from Tkinter import * import time class App: def __init__(self, master): w = Label(master, text="1. Anxiety, nervousness, worry or fear") w.pack() choices = { 1: "not at all", 2: "somewhat", 3: "moderately", 4: "a lot" } for i in sorted(choices.keys()): label = "%s - %s" % (i, choices[i]) rb=Radiobutton(master, text=label, variable=v, value=i) rb.pack(side=TOP, anchor="w") choices = { 1: "not at all", 2: "somewhat", 3: "moderately", 4: "a lot" } v = IntVar() Radiobutton(master, text="0 for not at all", variable=v, value=1).pack(side=TOP, anchor="w") Radiobutton(master, text="1 for somewhat", variable=v, value=2).pack(side=TOP, anchor="w") Radiobutton(master, text="2 for moderatly", variable=v, value=3).pack(side=TOP, anchor="w") Radiobutton(master, text="3 for a lot", variable=v, value=4).pack(side=TOP, anchor="w") self.button = Button(master, text="BACK", fg="red", command=self.button6) self.button.pack(side=BOTTOM) self.button = Button(master, text="NEXT", fg="red", command=self.button5) self.button.pack(side=BOTTOM) def button6(self): print "Sam is awesome!GAJONGA" def button5(self): print "PYTHON FOR THE WIN! GIAN SAYS PYTHON = FILTHY" master = Tk() app = App(master) master.mainloop() Answer: You haven't provided the crucial info -- what line the error happens on. However, you appear to have an indentation error here: for i in sorted(choices.keys()): label = "%s - %s" % (i, choices[i]) rb=Radiobutton(master, text=label, variable=v, value=i) rb.pack(side=TOP, anchor="w") The lines inside the `for` loop need to be indented. If fixing that doesn't fix your problem please leave a comment on my answer and update your question with the line number and the code with the indentation fixed. * * * Updated answer for the updated question: Try this code: from Tkinter import * import time class App: def __init__(self, master): w = Label(master, text="1. Anxiety, nervousness, worry or fear") w.pack() choices = { 1: "not at all", 2: "somewhat", 3: "moderately", 4: "a lot" } for i in sorted(choices.keys()): v = IntVar() label = "%s - %s" % (i, choices[i]) rb=Radiobutton(master, text=label, variable=v, value=i) rb.pack(side=TOP, anchor="w") self.button = Button(master, text="BACK", fg="red", command=self.button6) self.button.pack(side=BOTTOM) self.button = Button(master, text="NEXT", fg="red", command=self.button5) self.button.pack(side=BOTTOM) def button6(self): print "Sam is awesome!GAJONGA" def button5(self): print "PYTHON FOR THE WIN! GIAN SAYS PYTHON = FILTHY" master = Tk() app = App(master) master.mainloop() That appears to be what you're trying to do. Observe the indentation closely and also where I moved the `v = IntVar()` line.
Difference between bson.objectid.ObjectId and bson.ObjectId? Question: I have generated an ObjectId through two different methods as follows: user@ubuntu:~$ python Python 2.7.1+ (r271:86832, Apr 11 2011, 18:05:24) [GCC 4.5.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> # Method one >>> from bson.objectid import ObjectId >>> idA = ObjectId() >>> print(idA) 4e9c45b91d41c8079a000000 >>> # Method two >>> import bson >>> idB = bson.ObjectId() >>> print(idB) 4e9c45ca1d41c8079a000001 Question> What is this difference between two methods? When should I use which? Thank you Answer: In [5]: bson.ObjectId Out[5]: bson.objectid.ObjectId They are exactly the same thing.
How do I ensure that a Python thread dies after its target function completes? Question: I have a service that spawns threads. The threads are started by providing a target function. It would appear that the thread doesn't "die" when the function ends. I know this because the thread makes some SSH connections with [Paramiko](http://www.lag.net/paramiko/) (via [Fabric](http://fabfile.org)), and if I do an `lsof` I see the SSH connections are still active after the function completes. How can I make sure that a thread dies when its target function completes? Here is an example of what I am working with: from time import sleep from threading import Thread from fabric.api import run, settings def thread_func(host): with settings(host_string=host): run('ls -lht /tmp') def spawn_thread(host): t = Thread( target=thread_func, args=(host,) ) t.start() spawn_thread('node1.example.com') while True: sleep(1) And if I run `sudo lsof | grep ssh` in another terminal while the above code is in its infinite loop I'll see the following, even after I _know_ that the thread should not exist anymore: python 6924 daharon 3u IPv4 170520 0t0 TCP 10.1.1.173:47368->node1.example.com:ssh (ESTABLISHED) python 6924 daharon 5u IPv4 170524 0t0 TCP 10.1.1.173:47369->node1.example.com:ssh (ESTABLISHED) python 6924 6930 daharon 3u IPv4 170520 0t0 TCP 10.1.1.173:47368->node1.example.com:ssh (ESTABLISHED) python 6924 6930 daharon 5u IPv4 170524 0t0 TCP 10.1.1.173:47369->node1.example.com:ssh (ESTABLISHED) python 6924 6932 daharon 3u IPv4 170520 0t0 TCP 10.1.1.173:47368->node1.example.com:ssh (ESTABLISHED) python 6924 6932 daharon 5u IPv4 170524 0t0 TCP 10.1.1.173:47369->node1.example.com:ssh (ESTABLISHED) Answer: Are you sure your fabric module is doing the ssh only for the duration of the ls command. That is, it should be doing the equivalent of ssh host ls -lht /tmp This commandline will open a remote shell to run the ls -lht command and then shutdown. But I suspect the Fabric library might be doing the equivalent of: ssh host host$ ls -lht /tmp . . Of course it's not providing a real tty but there are different ssh options that allow keeping a connection open without an interactive tty. This would be desirable in certain cases (e.g., if you run lots of commands on the same host, this technique will reuse the existing ssh session instead of opening new session every time. Check the documentation for arguments to enable or disable such session caching.
How to add OAuth 2.0 providers? Question: I could reproduce my bug using servside OAuth2.0 only so it's not javascript and the issue is that I must reload to make login / logout take effect and I want it to work without javascript. I have an idea that making logout twice makes logout effective so I could use a custom request handler for /login and/or /logour or just /sessionchange that will do a self.redirect but it's not the clean solution. Maybe you can take a look at the code and see why I must logout twice ie I must reload and can I workaround this using a `self.redirect` ? Am I using cookies the right way, the new cookie, or do I get it mixed up? I'm doing this both for the [website](http://koolbusiness.com) and for the [FB app](http://apps.facebook.com/koolbusiness). I'll be glad if you can come with any suggestion. There's a background of 2 related questions from before I removed the Javascript. And BTW should I use class Facebook or facebook.py? I think I commented out where the old cookie is set and that this will be correct once OAuth 2.0 handles my authentication serverside. Can you comment or answer? Thank you in advance if you can review and comment. [How to make my welcome text appear?](http://stackoverflow.com/questions/7775320/how-to-make-my-welcome- text-appear) [How to make this page reload on login / logout?](http://stackoverflow.com/questions/7747687/how-to-make-this-page- reload-on-login-logout) [Why my strange results rendering the user object?](http://stackoverflow.com/questions/7735502/why-my-strange-results- rendering-the-user-object) [login.html](http://www.koolbusiness.com/login) {% load i18n %} <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>{% trans "Log in" %}</title> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', '{{analytics}}']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> </head> <body> <div id="fb-root"></div> <script> window.fbAsyncInit = function() { FB.init({ appId : '164355773607006', // App ID channelURL : '//WWW.KOOLBUSINESS.COM/static/channel.html', // Channel File status : true, // check login status cookie : true, // enable cookies to allow the server to access the session oauth : true, // enable OAuth 2.0 xfbml : true // parse XFBML }); // Additional initialization code here }; // Load the SDK Asynchronously (function(d){ var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;} js = d.createElement('script'); js.id = id; js.async = true; js.src = "//connect.facebook.net/en_US/all.js"; d.getElementsByTagName('head')[0].appendChild(js); }(document)); </script> <a href="https://www.facebook.com/dialog/oauth?client_id=164355773607006&redirect_uri=http://{{host}}"><img src="/_/img/loginwithfacebook.png"></a> <a href="/_ah/login_redir?claimid=google.com/accounts/o8/id&continue=http://{{host}}"><img src="/_/img/loginwithgoogle.png"></a><br>{% if user %}<a href="{{ logout_url }}" class="logout">Logout Google</a>{% endif %} {% if current_user %}<a href="https://www.facebook.com/logout.php?next=http://{{host}}&access_token={{current_user.access_token}}" onclick="FB.logout()">Logout Facebook</a> {% endif %} {% if current_user %}<a href="/logout" onclick="FB.logout();">Logout Facebook JS</a> {% endif %} </body> </html> class BaseHandler(webapp.RequestHandler): facebook = None user = None csrf_protect = True @property def current_user(self): if not hasattr(self, "_current_user"): self._current_user = None cookie = facebook.get_user_from_cookie( self.request.cookies, facebookconf.FACEBOOK_APP_ID, facebookconf.FACEBOOK_APP_SECRET) logging.debug("logging cookie"+str(cookie)) if cookie: # Store a local instance of the user data so we don't need # a round-trip to Facebook on every request user = FBUser.get_by_key_name(cookie["uid"]) logging.debug("user "+str(user)) logging.debug("username "+str(user.name)) if not user: graph = facebook.GraphAPI(cookie["access_token"]) profile = graph.get_object("me") user = FBUser(key_name=str(profile["id"]), id=str(profile["id"]), name=profile["name"], profile_url=profile["link"], access_token=cookie["access_token"]) user.put() elif user.access_token != cookie["access_token"]: user.access_token = cookie["access_token"] user.put() self._current_user = user return self._current_user def initialize(self, request, response): """General initialization for every request""" super(BaseHandler, self).initialize(request, response) try: self.init_facebook() self.init_csrf() self.response.headers[u'P3P'] = u'CP=HONK' # iframe cookies in IE except Exception, ex: self.log_exception(ex) raise def handle_exception(self, ex, debug_mode): """Invoked for unhandled exceptions by webapp""" self.log_exception(ex) self.render(u'error', trace=traceback.format_exc(), debug_mode=debug_mode) def log_exception(self, ex): """Internal logging handler to reduce some App Engine noise in errors""" msg = ((str(ex) or ex.__class__.__name__) + u': \n' + traceback.format_exc()) if isinstance(ex, urlfetch.DownloadError) or \ isinstance(ex, DeadlineExceededError) or \ isinstance(ex, CsrfException) or \ isinstance(ex, taskqueue.TransientError): logging.warn(msg) else: logging.error(msg) def set_cookie(self, name, value, expires=None): if value is None: value = 'deleted' expires = datetime.timedelta(minutes=-50000) jar = Cookie.SimpleCookie() jar[name] = value jar[name]['path'] = u'/' if expires: if isinstance(expires, datetime.timedelta): expires = datetime.datetime.now() + expires if isinstance(expires, datetime.datetime): expires = expires.strftime('%a, %d %b %Y %H:%M:%S') jar[name]['expires'] = expires self.response.headers.add_header(*jar.output().split(u': ', 1)) def render(self, name, **data): """Render a template""" if not data: data = {} data[u'js_conf'] = json.dumps({ u'appId': facebookconf.FACEBOOK_APP_ID, u'canvasName': facebookconf.FACEBOOK_CANVAS_NAME, u'userIdOnServer': self.user.id if self.user else None, }) data[u'logged_in_user'] = self.user data[u'message'] = self.get_message() data[u'csrf_token'] = self.csrf_token data[u'canvas_name'] = facebookconf.FACEBOOK_CANVAS_NAME data[u'current_user']=self.current_user data[u'user']=users.get_current_user() data[u'facebook_app_id']=facebookconf.FACEBOOK_APP_ID user = users.get_current_user() data[u'logout_url']=users.create_logout_url(self.request.uri) if users.get_current_user() else 'https://www.facebook.com/dialog/oauth?client_id=164355773607006&redirect_uri='+self.request.uri host=os.environ.get('HTTP_HOST', os.environ['SERVER_NAME']) data[u'host']=host if host.find('.br') > 0: logo = 'Montao.com.br' logo_url = '/_/img/montao_small.gif' analytics = 'UA-637933-12' domain = None else: logo = 'Koolbusiness.com' logo_url = '/_/img/kool_business.png' analytics = 'UA-3492973-18' domain = 'koolbusiness' data[u'domain']=domain data[u'analytics']=analytics data[u'logo']=logo data[u'logo_url']=logo_url data[u'admin']=users.is_current_user_admin() if user: data[u'greeting'] = ("Welcome, %s! (<a href=\"%s\">sign out</a>)" % (user.nickname(), users.create_logout_url("/"))) self.response.out.write(template.render( os.path.join( os.path.dirname(__file__), 'templates', name + '.html'), data)) def init_facebook(self): facebook = Facebook() user = None # initial facebook request comes in as a POST with a signed_request if u'signed_request' in self.request.POST: facebook.load_signed_request(self.request.get('signed_request')) # we reset the method to GET because a request from facebook with a # signed_request uses POST for security reasons, despite it # actually being a GET. in webapp causes loss of request.POST data. self.request.method = u'GET' #self.set_cookie( #'u', facebook.user_cookie, datetime.timedelta(minutes=1440)) elif 'u' in self.request.cookies: facebook.load_signed_request(self.request.cookies.get('u')) # try to load or create a user object if facebook.user_id: user = FBUser.get_by_key_name(facebook.user_id) if user: # update stored access_token if facebook.access_token and \ facebook.access_token != user.access_token: user.access_token = facebook.access_token user.put() # refresh data if we failed in doing so after a realtime ping if user.dirty: user.refresh_data() # restore stored access_token if necessary if not facebook.access_token: facebook.access_token = user.access_token if not user and facebook.access_token: me = facebook.api(u'/me', {u'fields': _USER_FIELDS}) try: friends = [user[u'id'] for user in me[u'friends'][u'data']] user = FBUser(key_name=facebook.user_id, id=facebook.user_id, friends=friends, access_token=facebook.access_token, name=me[u'name'], email=me.get(u'email'), picture=me[u'picture']) user.put() except KeyError, ex: pass # ignore if can't get the minimum fields self.facebook = facebook self.user = user def init_csrf(self): """Issue and handle CSRF token as necessary""" self.csrf_token = self.request.cookies.get(u'c') if not self.csrf_token: self.csrf_token = str(uuid4())[:8] self.set_cookie('c', self.csrf_token) if self.request.method == u'POST' and self.csrf_protect and \ self.csrf_token != self.request.POST.get(u'_csrf_token'): raise CsrfException(u'Missing or invalid CSRF token.') def set_message(self, **obj): """Simple message support""" self.set_cookie('m', base64.b64encode(json.dumps(obj)) if obj else None) def get_message(self): """Get and clear the current message""" message = self.request.cookies.get(u'm') if message: self.set_message() # clear the current cookie return json.loads(base64.b64decode(message)) class Facebook(object): """Wraps the Facebook specific logic""" def __init__(self, app_id=facebookconf.FACEBOOK_APP_ID, app_secret=facebookconf.FACEBOOK_APP_SECRET): self.app_id = app_id self.app_secret = app_secret self.user_id = None self.access_token = None self.signed_request = {} def api(self, path, params=None, method=u'GET', domain=u'graph'): """Make API calls""" if not params: params = {} params[u'method'] = method if u'access_token' not in params and self.access_token: params[u'access_token'] = self.access_token result = json.loads(urlfetch.fetch( url=u'https://' + domain + u'.facebook.com' + path, payload=urllib.urlencode(params), method=urlfetch.POST, headers={ u'Content-Type': u'application/x-www-form-urlencoded'}) .content) if isinstance(result, dict) and u'error' in result: raise FacebookApiError(result) return result def load_signed_request(self, signed_request): """Load the user state from a signed_request value""" try: sig, payload = signed_request.split(u'.', 1) sig = self.base64_url_decode(sig) data = json.loads(self.base64_url_decode(payload)) expected_sig = hmac.new( self.app_secret, msg=payload, digestmod=hashlib.sha256).digest() # allow the signed_request to function for upto 1 day if sig == expected_sig and \ data[u'issued_at'] > (time.time() - 86400): self.signed_request = data self.user_id = data.get(u'user_id') self.access_token = data.get(u'oauth_token') except ValueError, ex: pass # ignore if can't split on dot @property def user_cookie(self): """Generate a signed_request value based on current state""" if not self.user_id: return payload = self.base64_url_encode(json.dumps({ u'user_id': self.user_id, u'issued_at': str(int(time.time())), })) sig = self.base64_url_encode(hmac.new( self.app_secret, msg=payload, digestmod=hashlib.sha256).digest()) return sig + '.' + payload @staticmethod def base64_url_decode(data): data = data.encode(u'ascii') data += '=' * (4 - (len(data) % 4)) return base64.urlsafe_b64decode(data) @staticmethod def base64_url_encode(data): return base64.urlsafe_b64encode(data).rstrip('=') facebook.py #!/usr/bin/env python # # Copyright 2010 Facebook # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """Python client library for the Facebook Platform. This client library is designed to support the Graph API and the official Facebook JavaScript SDK, which is the canonical way to implement Facebook authentication. Read more about the Graph API at http://developers.facebook.com/docs/api. You can download the Facebook JavaScript SDK at http://github.com/facebook/connect-js/. If your application is using Google AppEngine's webapp framework, your usage of this module might look like this: user = facebook.get_user_from_cookie(self.request.cookies, key, secret) if user: graph = facebook.GraphAPI(user["access_token"]) profile = graph.get_object("me") friends = graph.get_connections("me", "friends") """ from google.appengine.dist import use_library use_library('django', '1.2') import cgi import hashlib import time import urllib #from django.utils import translation, simplejson as json # Find a JSON parser try: # For Google AppEngine from django.utils import simplejson _parse_json = lambda s: simplejson.loads(s) except ImportError: try: import simplejson _parse_json = lambda s: simplejson.loads(s) except ImportError: import json _parse_json = lambda s: json.loads(s) class GraphAPI(object): """A client for the Facebook Graph API. See http://developers.facebook.com/docs/api for complete documentation for the API. The Graph API is made up of the objects in Facebook (e.g., people, pages, events, photos) and the connections between them (e.g., friends, photo tags, and event RSVPs). This client provides access to those primitive types in a generic way. For example, given an OAuth access token, this will fetch the profile of the active user and the list of the user's friends: graph = facebook.GraphAPI(access_token) user = graph.get_object("me") friends = graph.get_connections(user["id"], "friends") You can see a list of all of the objects and connections supported by the API at http://developers.facebook.com/docs/reference/api/. You can obtain an access token via OAuth or by using the Facebook JavaScript SDK. See http://developers.facebook.com/docs/authentication/ for details. If you are using the JavaScript SDK, you can use the get_user_from_cookie() method below to get the OAuth access token for the active user from the cookie saved by the SDK. """ def __init__(self, access_token=None): self.access_token = access_token def get_object(self, id, **args): """Fetchs the given object from the graph.""" return self.request(id, args) def get_objects(self, ids, **args): """Fetchs all of the given object from the graph. We return a map from ID to object. If any of the IDs are invalid, we raise an exception. """ args["ids"] = ",".join(ids) return self.request("", args) def get_connections(self, id, connection_name, **args): """Fetchs the connections for given object.""" return self.request(id + "/" + connection_name, args) def put_object(self, parent_object, connection_name, **data): """Writes the given object to the graph, connected to the given parent. For example, graph.put_object("me", "feed", message="Hello, world") writes "Hello, world" to the active user's wall. Likewise, this will comment on a the first post of the active user's feed: feed = graph.get_connections("me", "feed") post = feed["data"][0] graph.put_object(post["id"], "comments", message="First!") See http://developers.facebook.com/docs/api#publishing for all of the supported writeable objects. Most write operations require extended permissions. For example, publishing wall posts requires the "publish_stream" permission. See http://developers.facebook.com/docs/authentication/ for details about extended permissions. """ assert self.access_token, "Write operations require an access token" return self.request(parent_object + "/" + connection_name, post_args=data) def put_wall_post(self, message, attachment={}, profile_id="me"): """Writes a wall post to the given profile's wall. We default to writing to the authenticated user's wall if no profile_id is specified. attachment adds a structured attachment to the status message being posted to the Wall. It should be a dictionary of the form: {"name": "Link name" "link": "http://www.example.com/", "caption": "{*actor*} posted a new review", "description": "This is a longer description of the attachment", "picture": "http://www.example.com/thumbnail.jpg"} """ return self.put_object(profile_id, "feed", message=message, **attachment) def put_comment(self, object_id, message): """Writes the given comment on the given post.""" return self.put_object(object_id, "comments", message=message) def put_like(self, object_id): """Likes the given post.""" return self.put_object(object_id, "likes") def delete_object(self, id): """Deletes the object with the given ID from the graph.""" self.request(id, post_args={"method": "delete"}) def request(self, path, args=None, post_args=None): """Fetches the given path in the Graph API. We translate args to a valid query string. If post_args is given, we send a POST request to the given path with the given arguments. """ if not args: args = {} if self.access_token: if post_args is not None: post_args["access_token"] = self.access_token else: args["access_token"] = self.access_token post_data = None if post_args is None else urllib.urlencode(post_args) file = urllib.urlopen("https://graph.facebook.com/" + path + "?" + urllib.urlencode(args), post_data) try: response = _parse_json(file.read()) finally: file.close() if response.get("error"): raise GraphAPIError(response["error"]["type"], response["error"]["message"]) return response class GraphAPIError(Exception): def __init__(self, type, message): Exception.__init__(self, message) self.type = type ##### NEXT TWO FUNCTIONS PULLED FROM https://github.com/jgorset/facepy/blob/master/facepy/signed_request.py import base64 import hmac def urlsafe_b64decode(str): """Perform Base 64 decoding for strings with missing padding.""" l = len(str) pl = l % 4 return base64.urlsafe_b64decode(str.ljust(l+pl, "=")) def parse_signed_request(signed_request, secret): """ Parse signed_request given by Facebook (usually via POST), decrypt with app secret. Arguments: signed_request -- Facebook's signed request given through POST secret -- Application's app_secret required to decrpyt signed_request """ if "." in signed_request: esig, payload = signed_request.split(".") else: return {} sig = urlsafe_b64decode(str(esig)) data = _parse_json(urlsafe_b64decode(str(payload))) if not isinstance(data, dict): raise SignedRequestError("Pyload is not a json string!") return {} if data["algorithm"].upper() == "HMAC-SHA256": if hmac.new(secret, payload, hashlib.sha256).digest() == sig: return data else: raise SignedRequestError("Not HMAC-SHA256 encrypted!") return {} def get_user_from_cookie(cookies, app_id, app_secret): """Parses the cookie set by the official Facebook JavaScript SDK. cookies should be a dictionary-like object mapping cookie names to cookie values. If the user is logged in via Facebook, we return a dictionary with the keys "uid" and "access_token". The former is the user's Facebook ID, and the latter can be used to make authenticated requests to the Graph API. If the user is not logged in, we return None. Download the official Facebook JavaScript SDK at http://github.com/facebook/connect-js/. Read more about Facebook authentication at http://developers.facebook.com/docs/authentication/. """ cookie = cookies.get("fbsr_" + app_id, "") if not cookie: return None response = parse_signed_request(cookie, app_secret) if not response: return None args = dict( code = response['code'], client_id = app_id, client_secret = app_secret, redirect_uri = '', ) file = urllib.urlopen("https://graph.facebook.com/oauth/access_token?" + urllib.urlencode(args)) try: token_response = file.read() finally: file.close() access_token = cgi.parse_qs(token_response)["access_token"][-1] return dict( uid = response["user_id"], access_token = access_token, ) Some log traces are 2011-10-18 18:25:07.912 logging cookie{'access_token': 'AAACVewZBArF4BACUDwnDap5OrQQ5dx0sHEKuPJkIJJ8GdXlYdni5K50xKw6s8BSIDZCpKBtVWF9maHMoJeF9ZCRRYM1zgZD', 'uid': u'32740016'} D 2011-10-18 18:25:07.925 user <__main__.FBUser object at 0x39d606ae980b528> D 2011-10-18 18:25:07.925 username Niklas R Now looking at the code that does this it seems to me that I'm confusing the module facebook with the variable facebook where one is the class facebook from the example project and one is the new recommended module facebook.py: class BaseHandler(webapp.RequestHandler): facebook = None user = None csrf_protect = True @property def current_user(self): if not hasattr(self, "_current_user"): self._current_user = None cookie = facebook.get_user_from_cookie( self.request.cookies, facebookconf.FACEBOOK_APP_ID, facebookconf.FACEBOOK_APP_SECRET) logging.debug("logging cookie"+str(cookie)) if cookie: # Store a local instance of the user data so we don't need # a round-trip to Facebook on every request user = FBUser.get_by_key_name(cookie["uid"]) logging.debug("user "+str(user)) logging.debug("username "+str(user.name)) if not user: graph = facebook.GraphAPI(cookie["access_token"]) profile = graph.get_object("me") user = FBUser(key_name=str(profile["id"]), id=str(profile["id"]), name=profile["name"], profile_url=profile["link"], access_token=cookie["access_token"]) user.put() elif user.access_token != cookie["access_token"]: user.access_token = cookie["access_token"] user.put() self._current_user = user return self._current_user Answer: How to add Facebook as OAuth 2.0 provider: Here's how I make "Login with facebook" for my website with OAuth instead of javascript / cookie this is python only for OAuth 2.0 with Facebook and as far as I can tell it's working: class FBUser(db.Model): id = db.StringProperty(required=True) created = db.DateTimeProperty(auto_now_add=True) updated = db.DateTimeProperty(auto_now=True) name = db.StringProperty(required=True) profile_url = db.StringProperty() access_token = db.StringProperty(required=True) name = db.StringProperty(required=True) picture = db.StringProperty() email = db.StringProperty() friends = db.StringListProperty() class I18NPage(I18NHandler): def get(self): if self.request.get('code'): args = dict( code = self.request.get('code'), client_id = facebookconf.FACEBOOK_APP_ID, client_secret = facebookconf.FACEBOOK_APP_SECRET, redirect_uri = 'http://www.koolbusiness.com/', ) logging.debug("client_id"+str(args)) file = urllib.urlopen("https://graph.facebook.com/oauth/access_token?" + urllib.urlencode(args)) try: logging.debug("reading file") token_response = file.read() logging.debug("read file"+str(token_response)) finally: file.close() access_token = cgi.parse_qs(token_response)["access_token"][-1] graph = main.GraphAPI(access_token) user = graph.get_object("me") #write the access_token to the datastore fbuser = main.FBUser.get_by_key_name(user["id"]) logging.debug("fbuser "+str(fbuser)) if not fbuser: fbuser = main.FBUser(key_name=str(user["id"]), id=str(user["id"]), name=user["name"], profile_url=user["link"], access_token=access_token) fbuser.put() elif fbuser.access_token != access_token: fbuser.access_token = access_token fbuser.put() The login link is `<a href="https://www.facebook.com/dialog/oauth?client_id=164355773607006&redirect_uri=http://{{host}}/"><img src="/_/img/loginwithfacebook.png"></a>` that redirects and allows me to pick up the access_token in the method above and logout is straightforward: `<a href="https://www.facebook.com/logout.php?next=http://www.koolbusiness.com&access_token={{access_token}}">{% trans "Log out" %}</a>`
gstreamer - Wadsworth's constant thumbnailer Question: I'm trying to build a video thumbnailer using gst-python, it looks like this. from __future__ import division import sys import logging import pdb _log = logging.getLogger(__name__) logging.basicConfig() _log.setLevel(logging.DEBUG) try: import gobject gobject.threads_init() except: raise Exception('gobject could not be found') try: import pygst pygst.require('0.10') import gst from gst import pbutils from gst.extend import discoverer except: raise Exception('gst/pygst 0.10 could not be found') class VideoThumbnailer: ''' Creates a video thumbnail - Sets up discoverer & transcoding pipeline. Discoverer finds out information about the media file - Launches gobject.MainLoop, this triggers the discoverer to start running - Once the discoverer is done, it calls the __discovered callback function - The __discovered callback function launches the transcoding process - The _on_message callback is called from the transcoding process until it gets a message of type gst.MESSAGE_EOS, then it calls __stop which shuts down the gobject.MainLoop ''' def __init__(self, src, dst, **kwargs): _log.info('Initializing VideoThumbnailer...') # Set instance variables self.loop = gobject.MainLoop() self.source_path = src self.destination_path = dst self.destination_dimensions = kwargs.get('dimensions') or (180, 180) if not type(self.destination_dimensions) == tuple: raise Exception('dimensions must be tuple: (width, height)') # Run setup self._setup() # Run. self._run() def _setup(self): self._setup_pipeline() self._setup_discover() def _run(self): _log.info('Discovering...') self.discoverer.discover() _log.info('Done') _log.debug('Initializing MainLoop()') self.loop.run() def _setup_discover(self): self.discoverer = discoverer.Discoverer(self.source_path) # Connect self.__discovered to the 'discovered' event self.discoverer.connect('discovered', self.__discovered) def __discovered(self, data, is_media): ''' Callback for media discoverer. ''' if not is_media: self.__stop() raise Exception('Could not discover {0}'.format(self.source_path)) _log.debug('__discovered, data: {0}'.format(data)) self.data = data # Run any tasks that depend on the info from the discovery self._on_discovered() # Tell the transcoding pipeline to start running #self.pipeline.set_state(gst.STATE_PLAYING) _log.info('Transcoding...') def _on_discovered(self): self.__setup_capsfilter() def _setup_pipeline(self): # Create a new pipeline self.pipeline = gst.Pipeline('VideoThumbnailerPipeline') # Create the elements in the pipeline self.filesrc = gst.element_factory_make('filesrc', 'filesrc') self.filesrc.set_property('location', self.source_path) self.pipeline.add(self.filesrc) self.decoder = gst.element_factory_make('decodebin2', 'decoder') self.decoder.connect('new-decoded-pad', self._on_dynamic_pad) self.pipeline.add(self.decoder) self.ffmpegcolorspace = gst.element_factory_make( 'ffmpegcolorspace', 'ffmpegcolorspace') self.pipeline.add(self.ffmpegcolorspace) self.videoscale = gst.element_factory_make('videoscale', 'videoscale') self.videoscale.set_property('method', 'bilinear') self.pipeline.add(self.videoscale) self.capsfilter = gst.element_factory_make('capsfilter', 'capsfilter') self.pipeline.add(self.capsfilter) self.jpegenc = gst.element_factory_make('jpegenc', 'jpegenc') self.pipeline.add(self.jpegenc) self.filesink = gst.element_factory_make('filesink', 'filesink') self.filesink.set_property('location', self.destination_path) self.pipeline.add(self.filesink) # Link all the elements together self.filesrc.link(self.decoder) self.ffmpegcolorspace.link(self.videoscale) self.videoscale.link(self.capsfilter) self.capsfilter.link(self.jpegenc) self.jpegenc.link(self.filesink) self._setup_bus() def _on_dynamic_pad(self, dbin, pad, islast): ''' Callback called when ``decodebin2`` has a pad that we can connect to ''' # Intersect the capabilities of the video sink and the pad src # Then check if they have common capabilities. if not self.ffmpegcolorspace.get_pad_template('sink')\ .get_caps().intersect(pad.get_caps()).is_empty(): # It IS a video src pad. pad.link(self.ffmpegcolorspace.get_pad('sink')) def _setup_bus(self): self.bus = self.pipeline.get_bus() self.bus.add_signal_watch() self.bus.connect('message', self._on_message) def __setup_capsfilter(self): caps = ['video/x-raw-rgb'] if self.data.videoheight > self.data.videowidth: # Whoa! We have ourselves a portrait video! caps.append('height={0}'.format( self.destination_dimensions[1])) else: # It's a landscape, phew, how normal. caps.append('width={0}'.format( self.destination_dimensions[0])) self.capsfilter.set_property( 'caps', gst.caps_from_string( ', '.join(caps))) def _on_message(self, bus, message): _log.debug((bus, message)) t = message.type if t == gst.MESSAGE_EOS: self.__stop() _log.info('Done') elif t == gst.MESSAGE_ERROR: _log.error((bus, message)) self.__stop() def __stop(self): _log.debug(self.loop) self.pipeline.set_state(gst.STATE_NULL) gobject.idle_add(self.loop.quit) **What it does** 1. filesrc loads a video file 2. decodebin2 demuxes the video file, connects the video src pad to the ffmpegcolorspace sink 3. ffmpegcolorspace does whatever it does with the color spaces of the video stream 4. videoscale scales the video 5. capsfilter tells videoscale to make the video fit in a 180x180 box 6. jpegenc captures a single frame 7. filesink saves the jpeg file **What I want it to do** 1. filesrc loads a video file 2. decodebin2 demuxes the video file, connects the video src pad to the ffmpegcolorspace sink 3. ffmpegcolorspace does whatever it does with the color spaces of the video stream 4. videoscale scales the video 5. capsfilter tells videoscale to make the video fit in a 180x180 box 6. jpegenc captures a single frame **AT 30% INTO THE VIDEO** 7. filesink saves the jpeg file I've tried with self.decoder.seek_simple( gst.FORMAT_PERCENT, gst.SEEK_FLAG_FLUSH, self.WADSWORTH_CONSTANT) # int(30) placed in `_on_dynamic_pad`, after pad linking, alas to no avail. Answer: This is now implemented in the VideoThumbnailer class in <https://github.com/jwandborg/mediagoblin/blob/video_gstreamer- only/mediagoblin/media_types/video/transcoders.py#L53>.
Plone 4: List members that have been given Reviewer role on a specific folder Question: I've created a new view for a folder (based on Tabular view) the only the Title and Date for regular viewers, but if the logged in user had the "Editor" role, it shows an additional column. That column needs to list the users who have been given "Reviewer" role to that specific item. For instance, the columns would be: Title | Date | (Reviewers) Folder 1 | 10/04 | Johnny, Steve, Mary Sue Folder 2 | 10/13 | Sam, Betty, Johnny I've been able to hide/show the final column based on the authenticated user's role, but I can't seem to figure out how to list just the users who have reviewer access. I've tried using searchForMembers(), but in addition to being very slow, I can only get it to echo the entire list of Members, or narrowed based on site-wide roles, but I need to get just people who have been manually given Reviewer role on the specific folder. Here's the code for the entire column: <td tal:define="is_manager python:test(here.portal_membership.getAuthenticatedMember().has_role('Manager'), 1, 0);" tal:condition="is_manager"> <tal:block tal:define="results python:item.portal_membership.searchForMembers(roles=['Member']);"> <tal:block tal:condition="results" tal:repeat="user results"> <tal:block tal:define="fullname python:user.getProperty('fullname')"> <span tal:replace="fullname">Full Name</span><span>, </span> </tal:block> </tal:block> </tal:block> </td> It works when I have roles=['Member'], but if I change it to "Reviewer" I get nothing - I think because nobody is assigned as a Reviewer for the entire site, only for specific items. I've also tried using .listMembers() in various ways, but it seems that's restricted and I can't use it in the page template. Is there a way around this, or is this the "wrong way" to go about this in the first place? Answer: I've answered to a nearly identical question 2 day ago: [List folders that a user has Reviewer access to in Plone 4](http://stackoverflow.com/questions/7787352/list-folders-that-a-user-has- reviewer-access-to-in-plone-4/7787539#7787539) the updated code should look like this: from Products.CMFCore.utils import getToolByName portal_url = getToolByName(context, "portal_url") portal = portal_url.getPortalObject() acl_users = portal.acl_users res = [] local_roles = acl_users._getLocalRolesForDisplay(context) for name, roles, rtype, rid in local_roles: if 'Reviewer' in roles: res.append((name,roles,rtype,rid)) I'd suggest to put this kind of logic in the file python and not in the page template.
pyparsing - parse xml comment Question: I need to parse a file containing xml comments. Specifically it's a c# file using the MS `///` convention. From this I'd need to pull out `foobar`, or `/// foobar` would be acceptable, too. (Note - this still doesn't work if you make the xml all on one line...) testStr = """ ///<summary> /// foobar ///</summary> """ Here is what I have: import pyparsing as pp _eol = pp.Literal("\n").suppress() _cPoundOpenXmlComment = Suppress('///<summary>') + pp.SkipTo(_eol) _cPoundCloseXmlComment = Suppress('///</summary>') + pp.SkipTo(_eol) _xmlCommentTxt = ~_cPoundCloseXmlComment + pp.SkipTo(_eol) xmlComment = _cPoundOpenXmlComment + pp.OneOrMore(_xmlCommentTxt) + _cPoundCloseXmlComment match = xmlComment.scanString(testStr) and to output: for item,start,stop in match: for entry in item: print(entry) But I haven't had much success with the grammer working across multi-line. (note - I tested the above sample in python 3.2; it works but (per my issue) does not print any values) Thanks! Answer: I think `Literal('\n')` is your problem. You don't want to build a Literal with whitespace characters (since Literals by default skip over whitespace before trying to match). Try using `LineEnd()` instead. **EDIT 1:** Just because you get an infinite loop with LineEnd doesn't mean that Literal('\n') is any better. Try adding `.setDebug()` on the end of your `_eol` definition, and you'll see that it never matches anything. Instead of trying to define the body of your comment as "one or more lines that are not a closing line, but get everything up to the end-of-line", what if you just do: xmlComment = _cPoundOpenXmlComment + pp.SkipTo(_cPoundCloseXmlComment) + _cPoundCloseXmlComment (The reason you were getting an infinite loop with LineEnd() was that you were essentially doing OneOrMore(SkipTo(LineEnd())), but never consuming the LineEnd(), so the OneOrMore just kept matching and matching and matching, parsing and returning an empty string since the parsing position was _at_ the end of line.)
Python global threading.condition() and use in multiple modules Question: **EDIT: the problem I was experiencing was not related to the structure of my program. It was FAPWS3's routing picking a similar, closely named function.** I have a large program spread across multiple files. I need to use the threading.condition() locking functionality across these files. Here's an example of what I'm trying to do. In production I do not get any errors, but the state of the lock does not seem to be shared (I can acquire in one thread, and acquire in another thread without the previous being released). main.py import servera, serverb # some code that deploys server-a and server-b as threads constants.py import threading mylock = threading.Condition() servera.py from constants import mylock Class ServerA(): def doSomething(): mylock.acquire() # do something mylock.release() serverb.py from constants import mylock Class ServerB(): def doSomethingElse(): mylock.acquire() # do something else mylock.release() Answer: If I remember correct, when you import an module Python runs it. So I think you get a different mylock in each file. You could try printing it and look at the ids. Jeffs link posted below clears that: > Because there is only one instance of each module, any changes made to the > module object get reflected everywhere. So this is not a problem.
How to write a batch file showing path to executable and version of Python handling Python scripts on Windows? Question: It should display path to executable and version of Python for scripts run with direct invocation of Python (`python myscript.py`) as well as for scripts run directly (`myscript.py`). Script should not make too many assumptions on the configuration of the system. For instance it should handle situation where there might be no available Python. Rationale I'm playing with different ways of setting environment for running Python scripts and I thought it would be helpful to have a script telling me what the current configuration is. I'm concerned with the standard means provided by OS - the `PATH` environment variable and association of files' types with handlers (`assoc` and `ftype` commands as well as `PATHEXT` environment variable). This leaves [pylauncher](https://bitbucket.org/vinay.sajip/pylauncher/overview) outside of the scope of this question. Answer: Here's my first solution: SOLUTION 1 @echo off set test_script=.pyexe.py rem Let's create temporary Python script which prints info we need echo from __future__ import print_function; import sys; print(sys.executable); print(sys.version) > %test_script% echo Python accessible through system PATH: python %test_script% echo --- echo Python set as handler for Python files: %test_script% del %test_script% set test_script= I run into problem with this, however. When there's no valid Python interpreter associated with Python files trying to open Python file with `some_script.py` pops up _Open With_ system dialog. Solving this problem requires very good knowledge of batch files. Therefore trying to come up with a solution I've asked the following questions: * [How to prevent “Open With” dialog window when opening file from command window?](http://superuser.com/questions/348500/) * [How to escape variables with parentheses inside if-clause in a batch file?](http://stackoverflow.com/questions/7883169/) * [Why is delayed expansion in a batch file not working in this case?](http://stackoverflow.com/questions/7882395/) * [How to split double quoted strings with embedded spaces deliminated with spaces in a batch file?](http://stackoverflow.com/questions/7935308/) Improved version of the original batch file looks now like this: SOLUTION 1b @echo off setlocal set test_script=.pyexe.py rem Let's create temporary Python script which prints info we need echo from __future__ import print_function; import sys; print(sys.executable); print(sys.version) > %test_script% echo Python accessible through the system PATH: python %test_script% echo --- echo Python set as a handler for Python files: rem We need to check if a handler set in the registry exists to prevent "Open With" rem dialog box in case it doesn't exist rem ftype Python.File hypothetical return value: rem Python.File="%PYTHON_HOME%\python.exe" "%1" %* for /f "tokens=2 delims==" %%i in ('ftype Python.File') do set reg_entry=%%i rem ...now in 'reg_entry' variable we have everything after equal sign: rem "%PYTHON_HOME%\python.exe" "%1" %* set "handler=" setlocal enableDelayedExpansion for %%A in (!reg_entry!) do if not defined handler endlocal & set handler=%%A rem ...now in 'handler' variable we have the first token: rem "%PYTHON_HOME%\python.exe" rem Now we expand any environment variables that might be present rem in the handler's path for /f "delims=" %%i in ('echo %handler%') do set expanded_handler=%%i if exist "!expanded_handler!" ( "%test_script%" ) else ( if not "!handler!" == "!expanded_handler!" ( set "handler=!expanded_handler! ^(!handler!^)" ) echo Handler is set to !handler! which does not exist ) del %test_script% This is another take avoiding problems of the above two: SOLUTION 2 @echo off setlocal echo Python accessible through the system PATH: where python echo --- echo Python set as a handler for Python source files (.py): for /f "skip=2 tokens=1,2*" %%i in ('reg query HKCR\.py /ve') do set "file_type=%%k" for /f "skip=2 tokens=1,2*" %%i in ('reg query HKCR\%file_type%\shell\open\command /ve') do echo %%k ... and improved version: SOLUTION 2b @echo off setlocal EnableDelayedExpansion echo Python interpreter accessible through the system PATH: where python if not errorlevel 1 ( python -c "from __future__ import print_function; import sys; print(sys.version)" ) echo --- echo Python interpreter registered as a handler for Python source files (.py): reg query HKCR\.py /ve >nul 2>&1 if errorlevel 1 ( echo No "HKEY_CLASSES_ROOT\.py" registry key found ) else ( for /f "skip=2 tokens=1,2*" %%i in ('reg query HKCR\.py /ve 2^>nul') do set "file_type=%%k" if "!file_type!"=="(value not set)" ( echo "No file type set for .py extension" ) else ( reg query HKCR\!file_type!\shell\open\command /ve >nul 2>&1 if errorlevel 1 ( echo No "HKEY_CLASSES_ROOT\!file_type!\shell\open\command" registry key found ) else ( for /f "skip=2 tokens=1,2*" %%i in ('reg query HKCR\!file_type!\shell\open\command /ve 2^>nul') do set "handler=%%k" if "!handler!"=="(value not set)" ( echo No command set for !file_type! ) else ( echo !handler! ) ) ) )
Python's multiprocessing.Queue + Process: Properly terminating both programs Question: Given this Python program: # commented out code are alternatives I tried that don't work. from multiprocessing import Process, Queue #from multiprocessing import Process, JoinableQueue as Queue def start_process(queue): # queue.cancel_join_thread() while True: print queue.get() if __name__ == '__main__': queue = Queue() # queue.cancel_join_thread() process = Process(target=start_process, args=(queue,)) process.start() queue.put(12) process.join() When I kill this program with `CTRL-C`, this happens: $> python queuetest.py 12 ^CTraceback (most recent call last): File "queuetest.py", line 19, in <module> process.join() File ".../python2.7/multiprocessing/process.py", line 119, in join res = self._popen.wait(timeout) Process Process-1: File ".../python2.7/multiprocessing/forking.py", line 122, in wait Traceback (most recent call last): return self.poll(0) File ".../python2.7/multiprocessing/forking.py", line 107, in poll pid, sts = os.waitpid(self.pid, flag) File ".../python2.7/multiprocessing/process.py", line 232, in _bootstrap KeyboardInterrupt self.run() File ".../python2.7/multiprocessing/process.py", line 88, in run self._target(*self._args, **self._kwargs) File "queuetest.py", line 9, in start_process print queue.get() File ".../python2.7/multiprocessing/queues.py", line 91, in get res = self._recv() KeyboardInterrupt .. how do I properly terminate the two processess on signal ? What I want to achieve: In my non-minimal program the second process holds a SocketServer and needs an additional interactive command line interface. Answer: A solution is to send a specific message (eg 'exit' string in my sample) via queue, to terminate the worker(child process) normal. As the CTRL-C signal is send to all children, we need to ignored it. Here is sample code: from multiprocessing import Process, Queue def start_process(queue): while True: try: m = queue.get() if m == 'exit': print 'cleaning up worker...' # add here your cleaning up code break else: print m except KeyboardInterrupt: print 'ignore CTRL-C from worker' if __name__ == '__main__': queue = Queue() process = Process(target=start_process, args=(queue,)) process.start() queue.put(12) try: process.join() except KeyboardInterrupt: print 'wait for worker to cleanup...' queue.put('exit') process.join() ## or to kill anyway the worker if is not terminated after 5 seconds ... ## process.join(5) ## if process.is_alive(): ## process.terminate()
Trouble initiating a TCP connection in Python--blocking and timing out Question: For a class project I'm trying to do some socket programming Python but running into a very basic issue. I can't create a TCP connection from my laptop to a lab machine. (Which I'm hoping to use as the "server") Without even getting into the scripts I have written, I've been simply trying interpreter line commands with no success. On the lab machine (kh4250-39.cselabs.umn.edu) I type the following into Python: from socket import * sock = socket() sock.bind(('', 8353)) sock.listen(5) sock.accept() And then on my laptop I type: from socket import * sock = socket() sock.connect(('kh4250-39.cselabs.umn.edu', 8353)) At which point both machines block and don't do anything until the client times out or I send a SIGINT. This code is pretty much exactly copied from examples I've found online and from Mark Lutz's book Programming Python (using '' for the server host name apparently uses the OS default and is fairly common). If I run both ends in my computer and use 'localhost' for the hostname it works fine, so I suspect it's some problem with the hostnames I'm using on one or both ends. I'm really not sure what could be going wrong on such a simple example. Does anyone have an idea? Answer: A good way to confirm whether it's a firewall issue or not is to perform a `telnet` from the command-line to the destination host in question: % telnet kh4250-39.cselabs.umn.edu 8353 Trying 128.101.38.44... And then sometime later: telnet: connect to address 128.101.38.44: Connection timed out If it just hangs there at `Trying` and then eventually times out, chances are the connection to the remote host on that specific port is being blocked by a firewall. It could either be at the network layer (e.g. a real firewall or a router access-list) or at the host, such as iptables or other host-based filtering mechanisms. Access to this lab host might only be available from within the lab or the campus network. Talk with your professor or a network administrator or someone "in the know" on the network to find out for sure.
Setting Mac OSX Application Menu menu bar item to other than "Python" in my python Qt application Question: I am writing a GUI application using python and Qt. When I launch my application on Mac, the first menu item in the Mac menu bar at the top of the screen is "Python". I would prefer the application name there to be the name of my application. How can I get my program name up there? The following demo program creates a window with two menus: "Python", and "Foo". I don't like that, because it makes no difference to my users whether I wrote the app in python or COBOL. Instead I want menus "MyApp" and "Foo". #!/usr/bin/python # This example demonstrates unwanted "Python" # application menu name on Mac. # Makes no difference whether we use PySide or PyQt4 from PySide.QtGui import * # from PyQt4.QtGui import * import sys app = QApplication(sys.argv) # Mac menubar application menu is always "Python". # I want "DesiredAppTitle" instead. # setApplicationName() does not affect Mac menu bar. app.setApplicationName("DesiredAppTitle") win = QMainWindow() # need None parent for menubar on Mac to get custom menus at all mbar = QMenuBar() # Add a custom menu to menubar. fooMenu = QMenu(mbar) fooMenu.setTitle("Foo") mbar.addAction(fooMenu.menuAction()) win.setMenuBar(mbar) win.show() sys.exit(app.exec_()) How can I change that application menu name on Mac? EDIT: I would prefer to continue to use the system python (or whatever python is on the user PATH) if possible. Answer: You seem to need an OSX .app for this to work, as the `Info.plist` file in there contains the user-visible name for the application that is put there. This defaults to Python, which is the title you see for the program menu. [This blog](http://aralbalkan.com/1675) post outlines the steps you need to take, while the [OSX Developer Library](http://developer.apple.com/library/mac/#documentation/MacOSX/Conceptual/BPRuntimeConfig/Articles/ConfigFiles.html#//apple_ref/doc/uid/20002091-CJBJIEDH) has the docs on the property list you need to fill.
Array of colors in python Question: What's the quickest way to get an array of colors in python? Something I can index and pass to as the "color=" argument plotting in pylab. The best I can come up with is: colors = [(random(),random(),random()) for i in range(10)] but a solution that can generate well-spaced colors (interpolated?) would be preferable. Answer: from random import randint colors = [] for i in range(10): colors.append('%06X' % randint(0, 0xFFFFFF)) ## Result Example: `['#37AB65', '#3DF735', '#AD6D70', '#EC2504', '#8C0B90', '#C0E4FF', '#27B502', '#7C60A8', '#CF95D7', '#F6CC1D']` _ps: thanks to @Inerdia_
Nested loops for comparing 2 files Question: I am writing a program to compare two files. For each line in file 1, I want to compare it to all lines in file 2, then continue with the next line in file 1. The program is not continuing in file 1 after the first hit. Any suggestions? Code: Select all #! /usr/bin/env python import sys import fileinput # Open the two files f1 = open(sys.argv[1], "r") f2 = open(sys.argv[2], "r") for line in f1: chrR,chrStart,chrEnd,name,score,strand1,codingStart,codingEnd,itemRbg,blockCount,blockSize,BlockStart = line.strip().split() chr = range(int(chrStart), int(chrEnd)) lncRNA = set(chr) for line in f2: chrC,clustStart,clustEnd,annote,score,strand = line.strip().split() clust = range(int(clustStart), int(clustEnd)) cluster = set(clust) if strand1 == '-': if chrR == chrC: if strand1 == strand: if cluster & lncRNA: print name,annote,'transcript' continue else: continue continue break Answer: After the first line in `f1` you've already read all lines from `f2` file therefore `for line2 in f2` has zero iteration for the second and following lines in `f1` file unless `f2` file grows on disk. #!/usr/bin/env python import sys def intersect(r1, r2): return r2[0] < (r1[-1]+1) and r1[0] < (r2[-1]+1) with open(sys.argv[2]) as f2: chrC_set, strand_set, clusters = set(), set(), [] for i, line in enumerate(f2): parts = line.split() if len(parts) != 6: print >>sys.stderr, "%d line has %d parts: %s" % (i, len(parts), line), continue chrC, clustStart, clustEnd, annote, _, strand = parts chrC_set.add(chrC) strand_set.add(strand) clusters.append((xrange(int(clustStart), int(clustEnd)), annote)) with open(sys.argv[1]) as f1: for i, line in enumerate(f1): parts = line.split() if len(parts) < 6: print >>sys.stderr, "%d line has %d parts: %s" % (i, len(parts), line), continue chrR, chrStart, chrEnd, name, _, strand1 = parts[:6] if strand1 == '-' and chrR in chrC_set and strand1 in strand_set: lncRNA = xrange(int(chrStart), int(chrEnd)) for cluster, annote in clusters: if intersect(cluster, lncRNA): print name, annote, 'transcript'
Python DateUtil Converting string to a date and time Question: I'm trying to convert a parameter of type string to a date time. I'm using the dateUtil library from dateutil import parser myDate_string="2001/9/1 12:00:03" dt = parser.parse(myDate_string,dayfirst=True) print dt every time i run this i get > 2001-09-01 12:00:03 regardless of whether i have dayfirst set as true or Year first set as false. Ideally I just want to have a date in the format DD-MM-YYYY HH:MM:SS. I don't want anything fancy. I am willing to use the datetime library but this doesn't seem to work at all for me. Can anyone give simple expamples of how to convert strings to date time with an explicit format, I'm a noob, so the most basic examples are all i require. I'm using Python 2.7 Answer: The problem you're having is that any arguments you pass to parser.parse only affect how the string is parsed, not how the subsequent object is printed. parser.parse returns a datetime object - when you print it it will just use datetime's default __str__ method. If you replace your last line with print dt.strftime("%d-%m-%Y %H:%M:%S") it will work as you expect.
Obtaining Client IP address from a WSGI app using Eventlet Question: I'm currently writing a basic dispatch model server based on the Python Eventlet library (http://eventlet.net/doc/). Having looked at the WSGI docs on Eventlet (http://eventlet.net/doc/modules/wsgi.html), I can see that the eventlet.wsgi.server function logs the x-forwarded-for header in addition to the client IP address. However, the way to obtain this is to attach a file-like object (the default which is sys.stderr) and then have the server pipe that to that object. I would like to be able to obtain the client IP from within the application itself (i.e. the function that has start_response and environ as parameters). Indeed, an environ key would be perfect for this. Is there a way to obtain the IP address simply (i.e. through the environ dictionary or similar), without having to resort to redirecting the log object somehow? Answer: What you want is in the wsgi [environ](http://www.python.org/dev/peps/pep-0333/#environ-variables), specifically `environ['REMOTE_ADDR']`. However, if there is a proxy involved, then `REMOTE_ADDR` will be the address of the proxy, and the client address will be included (most likely) in `HTTP_X_FORWARDED_FOR`. Here's a function that should do what you want, for most cases (all credit to [Sævar](http://stackoverflow.com/questions/4581789/how-do-i-get-user-ip- address-in-django/5976065#5976065)): def get_client_address(environ): try: return environ['HTTP_X_FORWARDED_FOR'].split(',')[-1].strip() except KeyError: return environ['REMOTE_ADDR'] * * * You can easily see what is included in the wsgi environ by writing a simple wsgi app and pointing a browser at it, for example: from eventlet import wsgi import eventlet from pprint import pformat def show_env(env, start_response): start_response('200 OK', [('Content-Type', 'text/plain')]) return ['%s\r\n' % pformat(env)] wsgi.server(eventlet.listen(('', 8090)), show_env) * * * And combining the two ... from eventlet import wsgi import eventlet from pprint import pformat def get_client_address(environ): try: return environ['HTTP_X_FORWARDED_FOR'].split(',')[-1].strip() except KeyError: return environ['REMOTE_ADDR'] def show_env(env, start_response): start_response('200 OK', [('Content-Type', 'text/plain')]) return ['%s\r\n\r\nClient Address: %s\r\n' % (pformat(env), get_client_address(env))] wsgi.server(eventlet.listen(('', 8090)), show_env)
How-To - Update Live Running Python Application Question: I have a python application , to be more precise a Network Application that can't go down this means i can't kill the PID since it actually talks with other servers and clients and so on ... many € per minute of downtime , you know the usual 24/7 system. Anyway in my hobby projects i also work a lot with WSGI frameworks and i noticed that i have the same problem even during off-peak hours. Anyway imagine a normal server using TCP/UDP ( put here your favourite WSGI/SIP/Classified Information Server/etc). Now you perform a git pull in the remote server and there goes the new python files into the server (these files will of course ONLY affect the data processing and not the actual sockets so there is no need to re-raise the sockets or touch in any way the network part). I don't usually use File monitors since i prefer to use SIGNAL to wakeup the internal app updater. Now imagine the following code from mysuper.app import handler while True: data = socket.recv() if data: socket.send(handler(data)) Lets imagine that handler is a APP with DB connections, cache connections , etc. What is the best way to update the handler. Is it safe to call reload(handler) ? Will this break DB connections ? Will DB Connections survive to this restart ? Will current transactions be lost ? Will this create anti-matter ? What is the best-pratice patterns that you guys usually use if there are any ? Answer: It's safe to call `reload(handler)`. Depends where you initialize your connections. If you make the connections inside handler(), then yes, they'll be garbage collected when the `handler()` object falls out of scope. But you wouldn't be connecting inside your main loop, would you? I'd highly recommend something like: dbconnection = connect(...) while True: ... socket.send(handler(data, dbconnection)) if for no other reason than that you won't be making an expensive connection inside a tight loop. That said, I'd recommend going with an entirely different architecture. Make a listener process that does basically nothing more than listen for UDP datagrams, sends them to a messaging queue like [RabbitMQ](http://www.rabbitmq.com/), then waits for the reply message to send the results back to the client. Then write your actual servers that get their requests from the messaging queue, process them, and send a reply message back. If you want to upgrade the UDP server, launch the new instance listening on another port. Update your firewall rules to redirect incoming traffic to the new port. Reload the rules. Kill the old process. Voila: seamless cutover. The real win is from uncoupling your backend. Since multiple processes can listen for the same messages from your frontend "proxy" service, you can run several in parallel - on different machines, if you want to. To upgrade the backend, start a new instance then kill the old one so that there's no time when at least one instance isn't running. To scale your proxy, have multiple instances running on different ports or different hosts, and configure your firewall to randomly redirect incoming datagrams to one of the proxies. To scale your backend, run more instances.
How to import data from scanned text into Django models Question: I have a hundreds of pages of "quiz" questions, multiple-choice options and associated answer keys and explanations. I'm trying to create a simple Django app to administer these questions. I have created a simple but effective Python parser to parse the scanned, OCR'd pages into the proper objects. I want to have a "utility" to enable the administrator of this Django app to import quiz content from OCR'd paper into the relevant Django DB tables. This will be a rare task, and something that is not necessarily appropriate for inclusion in a web UI. I've asked about using intermediate JSON/YAML fixtures and was told that a more appropriate approach would be to directly create and save instances of my models [1]. I then tried to create a standalone script along the lines suggested by [2] and [3] but was unable to overcome the `kwargs = {"app_label": model_module.__name__.split('.')[-2]} IndexError: list index out of range` error. I also came across [4] about creating custom django-admin.py/manage.py commands. This seems like a logically appropriate way of dealing with the task; but, I'd love to hear from those with more experience and brains (I've eaten all mine :). ## References: 1. [Importing data from scanned text into Django as YAML fixture or SQL](http://stackoverflow.com/questions/7669550/importing-data-from-scanned-text-into-django-as-yaml-fixture-or-sql) 2. [what is the simplest way to create a table use django db api ,and base on 'Standalone Django scripts'](http://stackoverflow.com/questions/2211816/what-is-the-simplest-way-to-create-a-table-use-django-db-api-and-base-on-stand) 3. [Standalone Scripts](http://www.b-list.org/weblog/2007/sep/22/standalone-django-scripts/) 4. [Writing custom django-admin commands](https://docs.djangoproject.com/en/dev/howto/custom-management-commands/) ## Examples: * OCR'd Text > Page 12 34\. Hiedegger is a _____ . (a) philosopher (b) boozy beggar (c) > both a and b (d) none of these 35. ... * Django Models class Question(models.Model): text = models.TextField() class Choice(models.Model): question = models.ForeignKey(Question) order = models.IntegerField(default=1) text = models.TextField() * Goal, something like this... q = Question.objects.create(text="Hiedegger is a _____ .") q.save() c = Choice(text="philosopher", order=1, question=q.pk) c.save() Answer: This is the working version I came up with. Dirty, but effective. Both @akonsu and @Ivan Kharlamov were helpful. Thanks... import os, re, Levenshtein as lev, codecs from SimpleQuiz.quiz.models import Choice, Question from django.core.management.base import BaseCommand, CommandError import optparse class Command(BaseCommand): args = '--datapath=/path/to/text/data/' can_import_settings = True help = 'Imports scanned text into Questions and Choices' option_list = BaseCommand.option_list + ( optparse.make_option('--datapath', action='store', type='string', dest='datapath', help='Path to OCRd text files to be parsed.'), ) requires_model_validation = True # Parser REs BACKUP_RE = re.compile(r'\~$|bak$|back$|backup$') QUEST_RE = re.compile(r'^[0-9]{1,3}[.][ ]') CHOICE_RE = re.compile(r'^[a-e][.][ ]') def handle(self, *args, **options): # get the data path try: os.path.exists(options['datapath']) except Exception as e: raise CommandError("None or invalid path provided: %s" % e.message) self.datapath = os.path.expanduser(options['datapath']) # generate list of text strings from lines in target files self.data_lines = [] for fn in os.listdir(os.path.join(self.datapath, 'questions/')): if self.BACKUP_RE.search(fn): self.stderr.write("Skipping backup: %s\n" % (fn)) else: for line in codecs.open(os.path.join(self.datapath, 'questions/', fn), 'r', encoding='latin-1'): if not self.is_boilerplate(line): if not line.strip() == '': self.data_lines.append(line) #----------------------------------------------------------------------- #--------------------- Parse the text lines and create Questions/Choices #----------------------------------------------------------------------- cur_quest = None cur_choice = None cur_is_quest = False questions = {} choices = {} for line in self.data_lines: if self.is_question(line): [n, txt] = line.split('.', 1) qtext = txt.rstrip() + " " q = Question.objects.create(text=qtext) q.save() cur_quest = q.pk questions[cur_quest] = q cur_is_quest = True elif self.is_choice(line): [n, txt] = line.split('.', 1) num = self.char2dig(n) ctext = txt.rstrip() + " " c = Choice.objects.create(text=ctext, order=num, question=questions[cur_quest]) c.save() cur_choice = c.pk choices[cur_choice] = c cur_is_quest = False else: if cur_is_quest: questions[cur_quest].text += line.rstrip() + " " questions[cur_quest].save() else: choices[cur_choice].text += line.rstrip() + " " choices[cur_choice].save() self.stdout.write("----- FINISHED -----\n") return None def is_question(self, arg_str): if self.QUEST_RE.search(arg_str): return True else: return False def is_choice(self, arg_str): if self.CHOICE_RE.search(arg_str): return True else: return False def char2dig(self, x): if x == 'a': return 1 if x == 'b': return 2 if x == 'c': return 3 if x == 'd': return 4 if x == 'e': return 5 def is_boilerplate(self, arg_str): boilerplate = [u'MFT PRACTICE EXAMINATIONS', u'BERKELEY TRAINING ASSOCIATES ' + u'\u00A9' + u' 2009', u'BERKELEY TRAINING ASSOCIATES', u'MARRIAGE AND FAMILY THERAPY', u'PRACTICE EXAMINATION 41', u'Page 0', u'Page 1', u'Page 2', u'Page 3', u'Page 4', u'Page 5', u'Page 6', u'Page 7', u'Page 8', u'Page 9', ] for bp in boilerplate: if lev.distance(bp.encode('utf-8'), arg_str.encode('utf-8')) < 4: return True return False
Unable to import SimPy Question: I am new to SimPy I used the easy_install to install SimPy module then on the command line I simply tried `from SimPy.Simulation import *` but I get the following error Python 2.6.7 (r267:88850, Aug 22 2011, 14:13:38) [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> from SymPy.Simulation import * Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: No module named SymPy.Simulation I use easy_install to install packages, I have simplejson install without any problem and when I import simplejson I don't get the above error. I did an update and easy_install successfully updated the SymPy module yet I still cant import the SimPy Module [/Library/Python/2.6/site-packages]$easy_install -U SimPy Searching for SimPy Reading http://pypi.python.org/simple/SimPy/ Reading http://SimPy.SourceForge.net Reading http://simpy.sourceforge.net/ Reading https://sourceforge.net/projects/simpy/files/ Reading http://pypi.python.org/simple/SimPy/simpy.sourceforge.net Reading http://sourceforge.net/project/showfiles.php?group_id=62366 Best match: SimPy 2.2 Processing SimPy-2.2-py2.6.egg SimPy 2.2 is already the active version in easy-install.pth Using /Library/Python/2.6/site-packages/SimPy-2.2-py2.6.egg Processing dependencies for SimPy Finished processing dependencies for SimPy I also check the `easy-install.pth` file, and looks like everything has been added properly. [/Library/Python/2.6/site-packages]$more easy-install.pth import sys; sys.__plen = len(sys.path) ./simplejson-2.1.3-py2.6.egg ./SimPy-2.2-py2.6.egg import sys; new=sys.path[sys.__plen:]; del sys.path[sys.__plen:]; p=getattr(sys,'__egginsert',0); sys.path[p:p]=new; sys.__egginsert = p+len(new) It will be great if I could get any help on this. Best; NH Answer: Try: `from sympy import *` <http://docs.sympy.org/0.7.1/tutorial.html#first-steps-with-sympy>
Extend all occurences in a string in Python Question: The goal is to prefix and suffix all occurrences of a substring (case- insensitive) in a source string. I basically need to figure out how to get from source_str to target_str. source_str = 'You ARe probably familiaR with wildcard' target_str = 'You [b]AR[/b]e probably famili[b]aR[/b] with wildc[b]ar[/b]d' In this example, I am finding all occurrences of 'ar' (case insensitive) and replacing each occurrence by **itself** (i.e. AR, aR and ar respectively), with a prefix ([b])and suffix ([/b]). Answer: >>> import re >>> source_str = 'You ARe probably familiaR with wildcard' >>> re.sub(r"(ar)", r"[b]\1[/b]", source_str, flags=re.IGNORECASE) 'You [b]AR[/b]e probably famili[b]aR[/b] with wildc[b]ar[/b]d'
What dose (.*) mean in python? Question: I was reading a learning python book, and this was in one of the examples so I was wonder if this meant something. Answer: (.*) doesn't mean anything specific in Python. However, it can mean specific things to certain functions when a part of a string. Hence `'(.*)'` might mean something to a function, although it means nothing to Python itself. Since Two functions that do take strings containing (.*) are [glob.glob](http://docs.python.org/library/glob.html), [fnmatch.fnmatch](http://docs.python.org/library/fnmatch.html) and the re modules functions. In glob and fnmatch it is `'*'` that has special meaning, it means "anything". You typically use it to match filenames: >>> import glob >>> glob.glob('/tmp/foobar.*') ['/tmp/foobar.tmp', '/tmp/foobar.txt', '/tmp/foobar.conf'] And you can also list everything with a specific ending: >>> import glob >>> glob.glob('/tmp/*.txt') ['/tmp/foobar.txt', '/tmp/frotz.txt', '/tmp/wfsh.txt'] Hence, in these modules `'(.*)'` would mean anything starts with (. and ends with ) with anything in between it. In the re module you handle regular expressions. regular expressions is a highly magical text matching language. There `'.'` means "any character (except newlines, unless you set a special flag to make it mean newlines as well)", and '*' means "zero to infinite amount of repetitions of the previous match". Hence `'.*'` means "pretty much anything", and is a common thing to stick into regular expressions, as `'foobar.*'` would mean anything that start with foobar. Parenthesis means "groups", and to know what that mean you'll just have to read the [documentation](http://docs.python.org/library/re.html). You probably won't get it without some experimentation so you see what happens. Basically '(.*)' matches anything. I'm assuming your regular expression has text before and after it as well?
Introspection on pygtk3 possible? Question: One of the great things of python is the ability to have introspection on methods and functions. As an example, to get the function signature of `math.log` you can (in ipython) run this: In [1]: math.log? Type: builtin_function_or_method Base Class: <type 'builtin_function_or_method'> String Form: <built-in function log> Namespace: Interactive Docstring: log(x[, base]) Return the logarithm of x to the given base. If the base not specified, returns the natural logarithm (base e) of x. And see that `x` and optionally `base` are the parameters of this function. With the new gtk3 and the [automaticall generated pygobject bindings](https://live.gnome.org/PyGObject), I can in all examples I tried only ever get `(*args, **kwargs)` as the parameters of every gtk method. Example: Label.set_text [which requires a string](http://python- gtk-3-tutorial.readthedocs.org/en/latest/label.html): In [1]: from gi.repository import Gtk In [2]: mylabel = Gtk.Label("hello") In [3]: mylabel.set_text? Type: instancemethod Base Class: <type 'instancemethod'> String Form: <bound method Label.set_text of <Label object at 0x275b230 (GtkLabel at 0x28cd040)>> Namespace: Interactive File: /usr/lib/python2.7/dist-packages/gi/types.py Definition: L.set_text(*args, **kwargs) Docstring: <no docstring> NOW THE QUESTION: is this (the loss of method introspection for python bindings) something that will change once more (documentation) effort has gone into pygobjects or is this something that is here to stay due to the way pygobjects works? Answer: Right now, I think this isn't yet ready. However, you can still do manual introspection looking at `Gtk-3.0.gir` file (in my system located in `/usr/share/gir-1.0/Gtk-3.0.gir`). The gir file is just an xml file that is supposed to be used exactly to explore the exposed interface regardless of the programming language that you are using. For example, the `Label` class can be found looking for `<class name="Label"`. Inside the `class` tag there's a `doc` tag with extensive information about what this widget is supposed to do. Also there are many `method` tags and one of them is the one you're interested in in you example: `<method name="set_text"`. Inside this `method` tag there's not only a `doc` tag that describes the method, but also a `parameters` tag that, in turn, contains some `parameter` tag that are used to describe each parameter in terms of name, description and type: <parameters> <parameter name="str" transfer-ownership="none"> <doc xml:whitespace="preserve">The text you want to set</doc> <type name="utf8" c:type="gchar*"/> </parameter> </parameters> So all the information is already there.
Performance of scipy.weave.inline Question: I am a Python novice who is trying to learn a bit about this fantastic programming language. I have tried using scipy.weave.inline to speed up some computation. Just to learn a bit, I tried to implement a matrix multiplication using scipy.weave.inline. I have not included any error handling - just trying it out to better understand it. The code is as follows: import scipy.weave def cmatmul(A,B): R = numpy.zeros((A.shape[0],B.shape[1])) M = R.shape[0] N = R.shape[1] K = A.shape[1] code = \ """ for (int i=0; i<M; i++) for (int j=0; j<N; j++) for (int k=0; k<K; k++) R(i,j) += A(i,k) * B(k,j); """ scipy.weave.inline(code, ['R','A','B','M','N','K'], \ type_converters=scipy.weave.converters.blitz, \ compiler='gcc') return R When I compare with numpy.dot, I experience that the weave.inline version takes roughly 50x the time as numpy.dot. I know that numpy is very fast when it can be applied. The difference is even seen for large matrices such as size 1000 x 1000. I have checked both numpy.dot and scipy.weave.inline and both appear to use one core 100% when computing. Numpy.dot delivers 10.0 GFlops compared to the theoretical 11.6 GFlops of my laptop (double precision). In single precision I measure the double performance as expected. But the scipy.weave.inline is way behind. 1/50 times this performance for scipy.weave.inline. Is this difference to be expected? Or what am I doing wrong? Answer: You implemented a naive matrix multiplication algorithm, which `scipy.weave` compiles to fast machine code. However, there are non-obvious, more CPU cache efficient [algorithms for matrix multiplication](http://en.wikipedia.org/wiki/Matrix_multiplication#Algorithms_for_efficient_matrix_multiplication) (which usually split the matrix into blocks and deal with those), and additional speed can be gained with CPU-specific optimizations. Numpy by default uses an optimized BLAS library for this operation, if you have one installed. These libraries will likely be fast compared to anything you can code up yourself without doing an amount of research.
multiprocessing.Pool - PicklingError: Can't pickle <type 'thread.lock'>: attribute lookup thread.lock failed Question: `multiprocessing.Pool` is driving me crazy... I want to upgrade many packages, and for every one of them I have to check whether there is a greater version or not. This is done by the `check_one` function. The main code is in the `Updater.update` method: there I create the Pool object and call the `map()` method. Here is the code: def check_one(args): res, total, package, version = args i = res.qsize() logger.info('\r[{0:.1%} - {1}, {2} / {3}]', i / float(total), package, i, total, addn=False) try: json = PyPIJson(package).retrieve() new_version = Version(json['info']['version']) except Exception as e: logger.error('Error: Failed to fetch data for {0} ({1})', package, e) return if new_version > version: res.put_nowait((package, version, new_version, json)) class Updater(FileManager): # __init__ and other methods... def update(self): logger.info('Searching for updates') packages = Queue.Queue() data = ((packages, self.set_len, dist.project_name, Version(dist.version)) \ for dist in self.working_set) pool = multiprocessing.Pool() pool.map(check_one, data) pool.close() pool.join() while True: try: package, version, new_version, json = packages.get_nowait() except Queue.Empty: break txt = 'A new release is avaiable for {0}: {1!s} (old {2}), update'.format(package, new_version, version) u = logger.ask(txt, bool=('upgrade version', 'keep working version'), dont_ask=self.yes) if u: self.upgrade(package, json, new_version) else: logger.info('{0} has not been upgraded', package) self._clean() logger.success('Updating finished successfully') When I run it I get this weird error: Searching for updates Exception in thread Thread-1: Traceback (most recent call last): File "/usr/lib/python2.7/threading.py", line 552, in __bootstrap_inner self.run() File "/usr/lib/python2.7/threading.py", line 505, in run self.__target(*self.__args, **self.__kwargs) File "/usr/local/lib/python2.7/dist-packages/multiprocessing/pool.py", line 225, in _handle_tasks put(task) PicklingError: Can't pickle <type 'thread.lock'>: attribute lookup thread.lock failed Answer: multiprocessing passes tasks (which include `check_one` and `data`) to the worker processes through a `Queue.Queue`. Everything put in the `Queue.Queue` must be pickable. `Queue`s themselves are not pickable: import multiprocessing as mp import Queue def foo(queue): pass pool=mp.Pool() q=Queue.Queue() pool.map(foo,(q,)) yields this exception: UnpickleableError: Cannot pickle <type 'thread.lock'> objects Your `data` includes `packages`, which is a Queue.Queue. That might be the source of the problem. * * * Here is a possible workaround: The `Queue` is being used for two purposes: 1. to find out the approximate size (by calling `qsize`) 2. to store results for later retrieval. Instead of calling `qsize`, to share a value between multiple processes, we could use a `mp.Value`. Instead of storing results in a queue, we can (and should) just return values from calls to `check_one`. The `pool.map` collects the results in a queue of its own making, and returns the results as the return value of `pool.map`. For example: import multiprocessing as mp import Queue import random import logging # logger=mp.log_to_stderr(logging.DEBUG) logger = logging.getLogger(__name__) qsize = mp.Value('i', 1) def check_one(args): total, package, version = args i = qsize.value logger.info('\r[{0:.1%} - {1}, {2} / {3}]'.format( i / float(total), package, i, total)) new_version = random.randrange(0,100) qsize.value += 1 if new_version > version: return (package, version, new_version, None) else: return None def update(): logger.info('Searching for updates') set_len=10 data = ( (set_len, 'project-{0}'.format(i), random.randrange(0,100)) for i in range(set_len) ) pool = mp.Pool() results = pool.map(check_one, data) pool.close() pool.join() for result in results: if result is None: continue package, version, new_version, json = result txt = 'A new release is avaiable for {0}: {1!s} (old {2}), update'.format( package, new_version, version) logger.info(txt) logger.info('Updating finished successfully') if __name__=='__main__': logging.basicConfig(level=logging.DEBUG) update()
python memory leak Question: I have an array of 'cell' objects created like so: class Cell: def __init__(self, index, type, color): self.index = index self.type = type self.score = 0 self.x = index%grid_size self.y = int(index/grid_size) self.color = colour alpha = 0.8 b = 2.0 grid_size = 100 scale = 5 number_cells = grid_size*grid_size num_cooperators = int(number_cells*alpha) cells = range(number_cells) random.shuffle(cells) cooperators = cells[0:num_cooperators] defectors = cells[num_cooperators:number_cells] cells = [Cell(i, 'C', blue) for i in cooperators] cells += [Cell(i, 'D', red) for i in defectors] cells.sort(compare) I am grabbing attributes from them in a loop like so: while 1: pixArr = pygame.PixelArray(windowSurfaceObj) for cell in cells: x = cell.x y = cell.y color = cell.color for y_offset in range(0,scale): for x_offset in range(0,scale): pixArr[x*scale + x_offset][y*scale + y_offset] = color del pixArr pygame.display.update() I am leaking memory like crazy... what's going on? Answer: There appears to be a bug in PixelArray. The following code replicates the memory leak by setting a single pixel each loop, and you don't even have to update the display to cause the problem: import pygame, sys from pygame.locals import * ScreenWidth, ScreenHeight = 640, 480 pygame.init() Display = pygame.display.set_mode((ScreenWidth,ScreenHeight), 0, 32) pygame.display.set_caption('Memory Leak Test') while True: PixelArray = pygame.PixelArray(Display) PixelArray[ScreenWidth-1][ScreenHeight-1] = (255,255,255) del PixelArray for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() #pygame.display.update() If you can handle the performance hit, replacing direct pixel setting with (very short) lines avoids the memory leak, ie: pygame.draw.line(Display, Colour, (X,Y), (X,Y), 1)
How would I write a syntax checker? Question: I am interested in writing a syntax checker for a language. Basically what I want to do is make a cli tool that will take an input file, and then write errors that it finds. The language I would want to parse is basically similar to Turing, and it is rather ugly and sometimes a pain to work with. The only other syntax checker for it must be used What language should I use? I figured I would write it in Ruby, but Python may be faster or have better parsing libraries. What libraries should I use, in Ruby or Pearl? Which would be easier. Is there a primer to read for defining a grammar? Such a task can become confusing, and I'm not sure how I would handle it. Answer: If it were me, I would write it in Ruby, and worry about speed later. If the program is a runaway hit, I might add a native gem to speed up the slowest bit, but leave most of it in Ruby. If it becomes the most important program in the world, or if I had nothing else to do, I might rewrite it in C or C++ at that point, but not before. And I would do all [parsing using Treetop.](http://treetop.rubyforge.org/) I might add that writing and optimizing a language parser directly in C is an interesting learning experience. You get roughly no string handling help, so you end up doing all the parsing, but you have a chance to do only the minimum amount of processing. It's sort of the opposite of the Ruby experience. To get maximum speed you end up doing things like writing frond-ends for malloc, where multiple objects you know you never have to free get allocated permanently within a malloced block. Although it is typical to use yacc(1) with C/C++, you can certainly write a recursive-descent parser and have an even deeper learning experience. Of course, having done all that already, I'm happy to stick with Ruby these days.
Mocking a function throughout a project Question: I would like to [mock](http://pypi.python.org/pypi/mock) a certain function in a utility module throughout my project, as part of a testing suite. I could of course patch and mock this function for each module using it, but there are a lot of these and it would be non-robust and tedious. Is there a way to patch\mock it throughout the project? If I patch and mock it in the utility module before any other module imports it, would the function be imported or the mock? Answer: Sure, just `import module` in your script, patch it, then import the other modules that use it and invoke whatever you need to test in them. Modules are imported only once in a session; additional `import` statements use the already-imported module. So the other modules that import the patched module will automatically get the patches.
python setuptools installation in centos Question: i have to install mysqldb module of python in my centos server. i have 2 versions of python 1. 2.4.3 the default one 2. 2.6 which i installed i want to install mysqldb module for 2.6 version of the python. i installed it from [here](http://ben.timby.com/?p=123) but when i am on the line python2.6 setup.py install it says Traceback (most recent call last): File "setup.py", line 5, in <module> from setuptools import setup, Extension ImportError: No module named setuptools so i went for installing setup tools from [here](http://pypi.python.org/pypi/setuptools#id6).using the command setuptools-0.6c11-py2.6.egg because i installed 2.6 python so i installed this rpm. but when i execute this command it says Traceback (most recent call last): File "<string>", line 1, in <module> zipimport.ZipImportError: can't decompress data; zlib not available but when i did locate command i do find the package and rpm installed for zlib. /usr/share/doc/zlib-1.2.3 /usr/share/doc/zlib-1.2.3/README /var/cache/yum/base/packages/zlib-devel-1.2.3-4.el5.x86_64.rpm can any one please help me in this. I exactly want to install mysqldb module for python 2.6 i installed on my /usr/local/bin/ directory. any help or idea will be highly appreciated. Answer: When you installed Python 2.6, you most likely didn't have zlib-devel installed, so your Python doesn't have that feature built in. I recommend that you install readline-devel sqlite-devel zlib-devel openssl-devel before compiling your own Python. After installing the newly compiled Python, fetch the setuptools source package and install it with: python2.6 setup.py install
How do I poll the subversion history/log remotely from python? Question: I need to find the first committer of a branch without having to do a checkout of all the entire branches. From command line that is very easy to do: svn log -v --stop-on-copy http://subversion.repository.com/svn/repositoryname I need to do this from a python script, any idea how can I do that? I checked the python subversion bindings but I cannot understand how to do it even if it seemed it can be done. Any help will be appreciated. Answer: You could just use Python's [`subprocess`](http://docs.python.org/library/subprocess.html#using-the- subprocess-module) module: from subprocess import Popen, PIPE p = Popen('svn log -v --stop-on-copy http://subversion.repository.com/svn/repositoryname', stdout=PIPE) stdout, stderr = p.communicate() This way you can run any SVN command you want: just examine `stdout` (and perhaps `stderr`) to get the command's result. You could then use for example a regex to parse the retrieved data: >>> s = Popen('svn log', shell=True, stdout=PIPE).communicate()[0] >>> m = re.search('\r\nr(?P<rev>\d+)\s+\|\s+(?P<author>\w+)\s+\|\s+(?P<timestamp>.*?)\s|', s) {'timestamp': '2011-10-10 10:45:01 +0000 (wed, okt 10 2011)', 'rev': '1234', 'author': 'someuser' }
Python 2.7: Print thread safe Question: I've seen a similar post [here](http://stackoverflow.com/questions/3029816/how-do-i-get-a-thread-safe- print-in-python-2-6) however it refers to Python 2.6 and I was hoping there was an easier way. From reading the thread it seems the best way is to just replace all my print statements with sys.stdout.write(s + '\n') ? I was hoping there was a nicer way that allowed me still to use print Answer: from __future__ import print_function print = lambda x: sys.stdout.write("%s\n" % x) Is a nice cheap and dirty hack.
Using anchors in python regex to get exact match Question: I need to validate a version number consisting of 'v' plus positive int, and nothing else eg "v4", "v1004" I have import re pattern = "\Av(?=\d+)\W" m = re.match(pattern, "v303") if m is None: print "noMatch" else: print "match" But this doesn't work! Removing the \A and \W will match for v303 but will also match for v30G, for example Thanks Answer: Pretty straightforward. First, put anchors on your pattern: "^patternhere$" Now, let's put together the pattern: "^v\d+$" That should do it.
Why Does This Program Run on Linux Python Shell But Not on Windows? Question: I ran this program on Linux with Python 2.6.2 and it ran fine returning me with decimal values but when I run it on Python 2.7.2 on Windows it does not work and just gives a blank space for a while and then a memory error but I can't figure out why..I need it to run on Windows its a program to calculate stock equity (ROE). Thanks. The CSV file needed to run the program is [here](http://www.cse.msu.edu/~cse231/Projects/proj05.dir/SBUX.csv). . import csv csvname = raw_input("Enter csv name: ") sbuxfile = csv.reader(open(csvname), delimiter=',', quotechar='|') # List of Data row5, row8, row3, row7, avgequity, roe1, roe2 = ([] for i in range(7)) count = 0 # Grab data and numerical values from CSV. for row in sbuxfile: count += 1 if count == 8: row8 = row elif count == 5: row5 = row elif count == 3: row3 = row elif count == 7: row7 = row a = 1 # Perform calculations for average equity and ROE. while a < 8 : if a == 1: avgequity.append(round(float(row8[a]),2)) roe1.append(float(row5[a]) / float(row8[a])) roe2.append((float(row5[a]) / float(row3[a])) * (float(row3[a]) / float(row7[a])) * (float(row7[a]) / float(row8[a]))) else: avgequity.append(round(float((row8[a]),2) + float(row8[a-1]))/2) roe1.append(float(row5[a]) / float(row8[a])) roe2.append((float(row5[a]) / float(row3[a])) * (float(row3[a]) / float(row7[a])) * (float(row7[a]) / ((float(row8[a]) + float(row8[a-1]))/2))) a+=1 print "\nAverage equity is " + str(avgequity) + "\n" print "ROE method 1 is " + str(roe1) + "\n" print "ROE method 2 is " + str(roe2) Answer: You have stuffed up the indentation of your `a+=1` line, possibly because of (mis)use of tabs in your source file. As displayed here on SO, `a` will never be incremented and so the loop will never be exited.
Copy data from the clipboard on Linux, Mac and Windows with a single Python script Question: I am trying to create a script in Python that will collect data put in the clipboard by the user and preferably save it as a list or in a text file or string/array/variable to work with later on. This should work on Linux all versions (I would assume Ubuntu), Mac OS all versions and Windows all versions. I am not sure if 32bit and 64bit systems have different ways of accessing the data at the clipboard, if they do I guess it would be safe to make this work for the 32bit versions only so people running the 64bit versions can fall back onto the 32bit version of the OS. The tricky part, apart from this having to work on the mentioned OS, is that I would like the script to run as long as the user does not stop it and while it runs all the data copied into the clipboard by the user is being copied to a list or in a text file or string/array/variable. Of course there is a time limit at which the user can input data into the clipboard so I was thinking of having a loop scanning the clipboard every second or every 500 milliseconds, check if the content has changed, and if it has, copy it, otherwise don't copy it. Is there a unified way or module that does this on all different OS or would it be better to write separate scripts for this task for the various OS? The thing is, this is part of a bigger project that I would like to make work on Linux, Mac and Windows, so having those three options covered and then use Python code that can be used across the mentioned OS for the rest of the script/project would be ideal. Am I asking too much in general from this script concerning it having to work on Linux, Mac and Windows? Answer: You're probably better off using a more advanced gui toolkit than Tk, but it's in the standard library, so it's available everywhere. As a really simple example: import Tkinter root = Tkinter.Tk() root.withdraw() # Hide the main window (optional) text_in_clipboard = root.clipboard_get() print text_in_clipboard
Another Token error: EOF in multi-line statement Question: **The following code gives me this error "Token Error: EOF in multi-line statement". I cannot seem to find the error though! Maybe someone else will see it?** import easygui import time namegui = easygui.enterbox(msg='Enter your name:', title='Name query', default='Gian') situationgui = easygui.enterbox(msg='Please enter your situation:', title='Thought Log(Situation)') thoughtsgui = easygui.enterbox(msg='Please enter your thoughts:', title='Thought Log(Thoughts') emotionsgui = easygui.enterbox(msg='Please enter your emotions: \n Sad, Mad, Hurt, Depressed, Anxious, Tense, etc.', title='Thought Log(Emotions') behaviorgui = easygui.enterbox(msg='Please enter your behavior:', title='Thought Log(Behavior') #thinking_trapsgui = easygui.enterbox(msg='Please identify your thinking traps: \n \n' # 'FORTUNE-TELLING: This occurs when we predict that things will turn out badly. However, we cannot predict the future because we do not have a magic ball! \n \n' # 'MIND-READING: This happens when we believe that we know what others are thinking and we assume that they are thinking the worst of us. However, we cannot mind-read so we do not know what others are thinking! \n \n' # 'LABELING: Sometimes we talk to ourselves in a mean way and we use a single negative word to describe ourselves. However, this kind of thinking is unfair and we are too complex to be summed up in a single word! \n \n' # 'FILTERING: This happens when we take note of all the bad things that happen, but ignore any good things. \n \n' # 'OVERESTIMATING: This happens when we believe that something that is unlikely to occur is actually about to happen. \n \n' # 'CATASTROPHIZING: This is when we imagine the worst possible thing is about to happen and we will be unable to cope with it. \n \n' # 'OVERGENERALIZING: This is when we use words like always or never to describe situations or events. This is a problematic way of thinking because it does not take all situation or events into account \n \n', # title='Thought Log(Identify Your Thinking Traps)') thinking_trapsgui = easygui.choicebox( msg='Please identify your thinking traps: \n \n', title='Thought Log(Identify Your Thinking Traps)', choices=('FORTUNE-TELLING: This occurs when we predict that things will turn out badly. However, we cannot predict the future because we do not have a magic ball! \n \n' 'MIND-READING: This happens when we believe that we know what others are thinking and we assume that they are thinking the worst of us. However, we cannot mind-read so we do not know what others are thinking! \n \n' 'LABELING: Sometimes we talk to ourselves in a mean way and we use a single negative word to describe ourselves. However, this kind of thinking is unfair and we are too complex to be summed up in a single word! \n \n' 'FILTERING: This happens when we take note of all the bad things that happen, but ignore any good things. \n \n' 'OVERESTIMATING: This happens when we believe that something that is unlikely to occur is actually about to happen. \n \n' 'CATASTROPHIZING: This is when we imagine the worst possible thing is about to happen and we will be unable to cope with it. \n \n' 'OVERGENERALIZING: This is when we use words like always or never to describe situations or events. This is a problematic way of thinking because it does not take all situation or events into account \n \n' ) alt_behaviorgui = easygui.enterbox(msg='Please enter alternative behavior:', title='Thought Log(Alt Behavior)') alt_thoughtsgui = easygui.enterbox(msg='Please enter alternative thoughts:', title='Thought Log(Alt Thoughts)') yeargui = easygui.enterbox(msg='Enter the current year:', title='Current Year', default='2011') monthgui = easygui.enterbox(msg='Enter the current month:', title='Current Month') daygui = easygui.enterbox(msg='Enter the current day:', title='Current Day') time_hourgui = easygui.enterbox(msg='Enter the current hour:', title='Current Hour') time_minutegui = easygui.enterbox(msg='Please enter current minutes:', title='Current Minute') am_pmgui = easygui.enterbox(msg='Please enter either am or pm:', title='AM OR PM') file = open('Thought Record 1.0.txt', 'a') file.write(namegui + '\n') file.write(daygui) file.write('/') file.write(monthgui) file.write('/') file.write(yeargui) file.write('\n') file.write('Your situation:') file.write(situationgui) file.write('\n') file.write('Your thoughts:') file.write(thoughtsgui) file.write('\n') file.write('Your emotions:') file.write(emotionsgui) file.write('\n') file.write('Your behavior:') file.write(behaviorgui) file.write('\n') file.write('Thinking traps:') file.write(thinking_trapsgui) file.write('\n') file.write('Alternative bahvior:') file.write(alt_behaviorgui) file.write('\n') file.write('Alternative thoughts:') file.write(alt_thoughtsgui) file.write('\n') file.write('\n') file.close() Also the error always highlights the last line after `file.close()`. I do not understand why? **I am running Python 2.5 on Mac OS X 10.6** Answer: You are missing a closing ) for variable thinking_trapsgui. Check if thats the problem. A missing ) usually gives a Syntax Error so I am not really sure, but EOF multi-line Token Error could be pointing to that. EDIT You have written thinking_trapsgui = easygui.choicebox( msg='Please identify your thinking traps: \n \n', title='Thought Log(Identify Your Thinking Traps)', choices=('FORTUNE-TELLING: This occurs when we predict that things will turn out badly. However, we cannot predict the future because we do not have a magic ball! \n \n' 'MIND-READING: This happens when we believe that we know what others are thinking and we assume that they are thinking the worst of us. However, we cannot mind-read so we do not know what others are thinking! \n \n' 'LABELING: Sometimes we talk to ourselves in a mean way and we use a single negative word to describe ourselves. However, this kind of thinking is unfair and we are too complex to be summed up in a single word! \n \n' 'FILTERING: This happens when we take note of all the bad things that happen, but ignore any good things. \n \n' 'OVERESTIMATING: This happens when we believe that something that is unlikely to occur is actually about to happen. \n \n' 'CATASTROPHIZING: This is when we imagine the worst possible thing is about to happen and we will be unable to cope with it. \n \n' 'OVERGENERALIZING: This is when we use words like always or never to describe situations or events. This is a problematic way of thinking because it does not take all situation or events into account \n \n' ) The last ')' above is for chioces argument. So just add another ')' at the end of the above line.
hadoop streaming: how to see application logs? Question: I can see all hadoop logs on my `/usr/local/hadoop/logs` path but where can I see application level logs? for example : mapper.py import logging def main(): logging.info("starting map task now") // -- do some task -- // print statement reducer.py import logging def main(): for line in sys.stdin: logging.info("received input to reducer - " + line) // -- do some task -- // print statement Where I can see `logging.info` or related log statements of my application? I am using `Python` and using `hadoop-streaming` Thank you Answer: Hadoop gathers stderr, which can be viewed on hadoop map/reduce status site. So you can just write to stderr.
How to install database with Spring MVC Question: I've got a Spring MVC project which I've received from another developer. I usually find .sql files there to initialize the DB, but this code doesn't seem to have anything like that. I doesn't use Roo or any tools that I know that can do database initialization. I've been using Python/Django for a while now, so I guess my question is: is there something I could use with Spring MVC like Django's "manage.py syncdb" to initialize the database based on the code? Maybe a build task or a script or anything other than reverse engineering the code and figuring out what tables should go to the DB? Thanks! Answer: ## The easiest solution * If you can still talk to that "other developer" => **just ask** If the above does not work... You have to understand what persistence mechanism / technology this project is based on. Here are few examples: ## It Is Based On Hibernate Just search for the word `hibernate` in all the files. Do you see anything? Take a look at project's dependencies, does it have any hibernate jars? etc.. If it is indeed Hibernate, you can generate your schema based on your domain objects (close to Django's "manage.py syncdb"), by adding the following Hibernate property: <prop key="hibernate.hbm2ddl.auto">create</prop> to a sessionFactory bean. It would look similar to [this](https://github.com/anatoly-polinsky/money-making- project/blob/master/src/main/resources/META-INF/conf/spring/persistence- spring-config.xml) configuration. Or if you have "persistence.xml" file instead, add this property ( under Hibernate properties ) there. You'd have to "run" the project in order to create this schema. ## It Is Based On Spring JDBC ([Template](http://static.springsource.org/spring/docs/3.1.x/javadoc- api/org/springframework/jdbc/core/JdbcTemplate.html)) Again, search for it. In this case you will have to write some SQL ( think about it as Rails migration, but in SQL :) ). Once you do that, you can use _in memory_ DB, such as [H2](http://www.h2database.com/html/main.html) (by default it uses HSQLDB), to actually achieve the same effect as with "hibernate.hbm2ddl.auto": <jdbc:embedded-database id="dataSource"> <jdbc:script location="classpath:schema.sql"/> <jdbc:script location="classpath:test-data.sql"/> </jdbc:embedded-database> Here is more about [Embedded DB Support](http://static.springsource.org/spring/docs/3.1.x/spring-framework- reference/html/jdbc.html#jdbc-embedded-database-support) ## It Is Based On Magic Nothing to search for really in this case (well, maybe for `DAO` or `Repository`), but the simplest approach would be to just take a single service, and follow the white rabbit: service.rememberThePlace( place ) { placeDao.save( place ) } Now look at the Dao.. does it have any `Hibernate` imports? What about `...JdbcTemplate`, etc..
popen3 and return code Question: I want to get stdout and stderr of a command along with the return code. Can someone point me to a python function that already accomplishes this? I modified a function that I found on this site as follows -- but I am not able to grab the return code of the command. In this snippet, sts always seems to be 0. def Getstatusoutput(cmd): """Return (status, output) of executing cmd in a shell.""" import sys mswindows = (sys.platform == "win32") import os if not mswindows: cmd = '{ ' + cmd + '; }' fi,fo,fe=os.popen3(cmd) textOut = fo.read() textErr = fe.read() sts = fo.close() if sts is None: sts = 0 if textOut[-1:] == '\n': textOut = textOut[:-1] return sts, textOut, textErr Answer: Use the [subprocess](http://docs.python.org/library/subprocess.html) module. [This section](http://docs.python.org/library/subprocess.html#replacing-os- popen-os-popen2-os-popen3) shows how to replace `os.popen3` calls.
The results of sha1 encryption are different between python and java Question: An application, i need sha1 encryption,but the results are different between python and java, java is correct. Because there is no byte object in python, and java byte is used for hash calculation. How to get the correct results with python? Answer: As usual, the difference is **not** in the digest implementation (those are well-documented and implemented correctly in all major libraries). The difference is in how you _represent_ the resulting data. `md.digest()` returns a `byte[]` with the binary data produced by the digest. `new String(md.digest())` tries to interpret those bytes as text in the platform default encoding which is _almost certainly_ not what you want. You _probably_ want the digest to be represented in a hex- or Base64 encoding. Try this (make sure to import [`javax.xml.bind.DatatypeConverter`](http://download.oracle.com/javase/7/docs/api/javax/xml/bind/DatatypeConverter.html)): String result = DatatypeConverter.printHexBinary(md.digest()); Alternatively, if you need Base64, use `printBase65Binary()` instead.
What is the correct callback signature for a function called using ctypes in python? Question: I have to define a callback function in Python, one that will be called from a DLL. BOOL setCallback (LONG nPort, void ( _stdcall *pFileRefDone) (DWORD nPort, DWORD nUser), DWORD nUser); I tried this code, that seems to work in Python 2.5 but with Python 2.7 it crashes and I assume I did something wrong. import ctypes, ctypes.wintypes from ctypes.wintypes import DWORD def cbFunc(port, user_data): print "Hurrah!" CB_Func = ctypes.WINFUNCTYPE(None, DWORD, DWORD) mydll.setCallback(ctypes.c_long(0), CB_Func(cbFunc), DWORD(0)) Where is the mistake? Note: The platform is running on 32bit only (both Windows and Python). The DLL loads successfully and also other functions from inside do work just fine while called from Python. A full sample code that reproduces this is available at <https://github.com/ssbarnea/pyHikvision> \- just run Video.py under py25 and py27. Answer: Your CB_Func(cbFunc) parameter gets garbage-collected right after the setCallback function. That object has to persist as long as the callback can be called ([15.17.1.17. Callback functions](http://docs.python.org/library/ctypes.html?highlight=ctypes#callback- functions), last paragraph). Assign it to a variable and keep it around. Here's my working example: ### DLL typedef unsigned int DWORD; typedef long LONG; typedef int BOOL; #define TRUE 1 #define FALSE 0 typedef void (__stdcall *CALLBACK)(DWORD,DWORD); CALLBACK g_callback = 0; DWORD g_port = 0; DWORD g_user = 0; BOOL __declspec(dllexport) setCallback (LONG nPort, CALLBACK callback, DWORD nUser) { g_callback = callback; g_port = nPort; g_user = nUser; return TRUE; } void __declspec(dllexport) Fire() { if(g_callback) g_callback(g_port,g_user); } ### Failing Script from ctypes import * def cb_func(port,user): print port,user x = CDLL('x') CALLBACK = WINFUNCTYPE(None,c_uint,c_uint) #cbfunc = CALLBACK(cb_func) x.setCallback(1,CALLBACK(cb_func),2) x.Fire() ### Passing Script from ctypes import * def cb_func(port,user): print port,user x = CDLL('x') CALLBACK = WINFUNCTYPE(None,c_uint,c_uint) cbfunc = CALLBACK(cb_func) x.setCallback(1,cbfunc,2) x.Fire() **Edit** : Also, since `CALLBACK` is a function returning a function, it can be used as a decorator for the Python callback, eliminating problem of the callback going out of scope: from ctypes import * CALLBACK = WINFUNCTYPE(None,c_uint,c_uint) @CALLBACK def cb_func(port,user): print port,user x = CDLL('x') x.setCallback(1,cb_func,2) x.Fire()
Passing Structure to Windows API in python ctypes Question: I'm trying to set the date in a SysDateTimeObject in an application on Windows 7. I'm using python 2.7 and the ctypes library with the following code which tries to send a DTM_SETSYSTEMTIME message to the SysDateTimeObject: from ctypes import * from ctypes.wintypes import BOOL,HWND,RECT,LPCSTR,UINT,INT,DWORD,WORD import sys import time class SYSTEMTIME(Structure): _fields_=[('wYear',WORD), ('wMonth',WORD), ('wDayOfWeek',WORD), ('wDay',WORD), ('wHour',WORD), ('wMinute',WORD), ('wSecond',WORD), ('wMilliseconds',WORD)] self.user32 = windll.user32 my_time=SYSTEMTIME(2035,0,0,0,0,0,0,0) self.user32.SendMessageW(window,c_uint(0x1002),0,byref(my_time)) window is a HWND to the correct SysDateTimeObject and 0x1002 is the code for the DTM_SETSYSTEMTIME message. The third parameter of SendMessageW is a constant to enable or disable the DateTimeControl. I can set it to 1 and it will disable the control, as expected. The fourth parameter is a pointer to a filled in SYSTEMTIME structure. However, it seems to do nothing as written above. I am able to send other messages but when a function requires a pointer to a structure, things start failing. Am I using ctypes wrong here? Answer: I was using [pywinauto](http://pypi.python.org/pypi/pywinauto) and ran into this need and managed to solve it. The cause of the trouble is that you're trying to run it in a different process, while your `SYSTEMTIME` structure is in your own process's private memory space. Thus, whenever it tries to do anything with the passed structure, it fails—access denied. You need a remote memory block to resolve the problem. `pywinauto.controls.common_controls._RemoteMemoryBlock` does exactly this. The eventual effect is that you will have code like this: remote_mem = common_controls._RemoteMemoryBlock(window) remote_mem.Write(my_time) user32.SendMessageW(window, win32defines.DTM_SETSYSTEMTIME, win32defines.GDT_VALID, remote_mem) If you need to use DTM_GETSYSTEMTIME, you would then put `my_time = remote_mem.Read(my_time)` after the SendMessage call.
finding absolute path from a relative path in python Question: my question is pretty much what the title suggests. my research has led me to try something like this: import os pathname = os.path.abspath("some/relative/directory") print pathname this problem is that whenever i do something like this, it simply returns whatever relative directory i gave it preceded by my python directory. for example: C:\Python27\some\relative\directory which is not even an existing directory on my computer. i understand that the python interpreter searches the working directory by default, but what i'd like to do is have it search my entire computer for an absolute path that contains the partial directory i specify. the purpose of this is for me to create an exe (using py2exe) that can search for an arbitrary directory on any computer. is there a method for doing this in the standard library or through some available module - or would i have to implement the algorithm myself? Answer: [`abspath`](http://docs.python.org/library/os.path.html#os.path.abspath) is based on [`getcwd`](http://docs.python.org/library/os.html#os.getcwd). Most likely, your current working directory simply isn't what you expect. You can change the code that launches your script, change directories manually, or just use [`chdir`](http://docs.python.org/library/os.html#os.chdir) in Python.
How do I change a value while debugging python with pdb? Question: I want to run pdb, step through the code, and at some point change the value pointed at by some name. So I might want to change the value pointed at by the name 'stationLat'. But it seems I can't. Here's the example: >>> import extractPercentiles >>> import pdb >>> pdb.run( "extractPercentiles.extractOneStation()" ) > <string>(1)<module>()->None (Pdb) s --Call-- > /scratch/extractPercentiles.py(96)extractOneStation() -> def extractOneStation() : (Pdb) tbreak 132 Breakpoint 3 at /scratch/extractPercentiles.py:132 (Pdb) c Deleted breakpoint 3 > /scratch/extractPercentiles.py(132)extractOneStation() -> stationLon = float(stationLoc[3]) So now I'm at a place where I would like to change the value of stationlat. Pdb appears to allow me to set stationLat to a new value, but when I inspect the value, it is unchanged: (Pdb) stationLat -34.171100000000003 (Pdb) stationLat = -40 (Pdb) stationLat -34.171100000000003 (Pdb) !stationLat = -40 (Pdb) stationLat -34.171100000000003 (Pdb) You can see I tried using ! as well, without success. The pdb manual says I should be able to change variables: _Commands that the debugger doesn’t recognize are assumed to be Python statements and are executed in the context of the program being debugged. Python statements can also be prefixed with an exclamation point (!). This is a powerful way to inspect the program being debugged;**it is even possible to change a variable_** or call a function Is this a question of scope? Is it to do with the way I have started pdb? I tried the embedded "pdb.set_trace" idiom and I got the same result. Thanks for reading. Answer: This appears to be a [bug in Python 2.6](http://bugs.python.org/issue5215). You should be able to do this in Python 2.7.
how can I input a file and run an asynchronously command on it in python? Question: I'm trying to write a script that asks for an input file and then runs some command on it. when I run the script it askes me for filename and when I give the file (e.g example.bam) then I get this error: > NameError: name 'example.bam' is not defined I tried many things but I couldn't fix it. Can someone tell me what is wrong? This is my comand: from subprocess import call filename = input ("filename: "); with open (filename, "r") as a: for command in ("samtools tview 'a' /chicken/chick_build2.1_unmasked.fa",): call(command, shell=True) This is a short version of my command: it has to do much more stuff. I'm also thinking to input 4-6 files at same time (perhaps this information is helpful to clarify my intentions). Answer: `input` is equivalent to `eval(raw_input(prompt))`. So what your script currently tries to do is interpret your input ("example", in your case), and execute as if it were a statement in your script. For user input (and might I simply say "for any input" -- unless you know what you're doing), always use the `raw_input` function. So, to solve it, replace `input` with `raw_input`: filename = raw_input("filename: ")
ImportError: No module named lines Question: from lines import lines Traceback (most recent call last): File "<pyshell#4>", line 1, in <module> import lines ImportError: No module named lines This is taken from [this](http://packages.python.org/pycha/examples.html) example for Pycha. How I can install this Module? Answer: The module `lines.py` is part of the Pycha examples. You can find a copy of that module [in that directory](https://bitbucket.org/lgs/pycha/src/bb277e830d92/examples/lines.py). To follow the example correctly, you should call the `examples/barchart.py` example while still maintaining the rest of the `examples` directory. Then it will work. If you want to create an own script based on the example, you’ll have to replace that module with your own code/data.
What is the recommended way to replace multiple strings in one large string in Python? Question: I have many string pairs and one large string (which is the content of a file). I need to replace each and every occurrence of the first member in each pair with the respective second one. For instance, having pairs ("AA", "BB") and ("qq", "rt") I need to replace every occurrence of **AA** with **BB** and of **qq** with **rt**. The strings in the pairs are all unique, so the order of replacements does not matter on the final result. My python code is the most naive - I apply the string.replace method in succession until all the pairs are exhausted: >>> s="frsfsdAAsdfvsdfvqqdsff" >>> pairs=[('AA', 'BB'), ('qq', 'rt')] >>> for p in pairs: ... s=s.replace(p[0], p[1]) ... >>> s 'frsfsdBBsdfvsdfvrtdsff' >>> I believe this is a bad solution for large strings. Can anyone suggest a more efficient one? **The question is about how to do it in Python.** Thanks. Answer: There's something else wrong with your proposed solution: after the first replacement is made the resulting string could match and the same characters could be replaced again. For example your solution would not give the desired result if you tried to swap `'qq'` and `'ff'` by setting `pairs = [('qq','ff'), ('ff','qq')]`. You could try this instead: >>> d = dict(pairs) >>> import re >>> pattern = re.compile('|'.join(re.escape(k) for k in d)) >>> pattern.sub(lambda k:d[k.group()], s)) frsfsdBBsdfvsdfvrtdsff
How to tell if python's ZipFile.writestr() failed because file is full? Question: Without using zip64 extensions, a Zip file cannot be more than 2GB in size, so trying to write to a file that would put it over that limit won't work. I expected that when such a writing was attempted, it would raise an exception, but I've not been able to cause one to be raised. (The documentation is silent on the matter.) If an exception doesn't get raised in such a circumstance, how would I (efficiently) go about determining if the write succeeded or not? Answer: import os size = os.path.getsize("file") #Get the size of the file. size = size/1073741824 #Converting bytes to GB. if size < 2: # < is probably safer than <= #do the zipping else: print "The file is too large!" This isn't ideal, of course, but it might serve as a temporary solution until a better one has been found. Again, I don't think this is a very good way of using zip. But if there is no appropriate exception (which there should), it might serve as a temporary solution.
Manipulating a Python file from C# Question: I'm working on some tools for a game I'm making. The tools serve as a front end to making editing game files easier. Several of the files are python scripting files. For instance, I have an Items.py file that contains the following (minimalized for example) from ItemModule import * import copy class ScriptedItem(Item): def __init__(self, name, description, itemtypes, primarytype, flags, usability, value, throwpower): Item.__init__(self, name, description, itemtypes, primarytype, flags, usability, value, throwpower, Item.GetNextItemID()) def Clone(self): return copy.deepcopy(self) ItemLibrary.AddItem(ScriptedItem("Abounding Crystal", "A colourful crystal composed of many smaller crystals. It gives off a warm glow.", ItemType.SynthesisMaterial, ItemType.SynthesisMaterial, 0, ItemUsage.Unusable, 0, 50)) As I Mentioned, I want to provide a front end for editing this file without requring an editor to know python/edit the file directly. My editor needs to be able to: 1. Find and list all the class types (in this example, it'd be only Scripted Item) 2. Find and list all created items (in this case there'd only be one, Abounding Crystal). I'd need to find the type (in this caseScriptedItem) and all the parameter values 3. Allow editing of parameters and the creation/removal of items. To do this, I started writing my own parser, looking for the class keyword and when these recorded classes are use to construct objects. This worked for simple data, but when I started using classes with complex constructors (lists, maps, etc.) it became increasing difficult to correctly parse. After searching around, I found IronPython made it easy to parse python files, so that's what I went about doing. Once I built the Abstract Syntax Tree I used PythonWalkers to identify and find all the information I need. This works perfectly for reading in data, but I don't see an easy way to push updated data into the Python file. As far as I can tell, there's no way to change the values in the AST and much less so to convert the AST back into a script file. If I'm wrong, I'd love for someone to tell me how I could do this. What I'd need to do now is search through the file until I find the correctly line, then try to push the data into the constructor, ensuring correct ordering. Is there some obvious solution I'm not seeing? Should I just keeping working on my parser and make it support more complex data types? I really though I had it with the IronPython parser, but I didn't think about how tricky it'd be to push modified data back into the file. Any suggestions would be appreciated Answer: You want a source-to-source [program transformation tool](http://en.wikipedia.org/wiki/Program_transformation). Such a tool parses a language to an internal data structure (invariably an AST), allows you to modify the AST, and then can regenerate source text from the modified AST without changing essentially anything about the source except where the AST changes were made. Such a program transformation tool has to parse text to ASTs, and "anti-parse" (called "Prettyprint") ASTs to text. If IronPython has a prettyprinter, that's what you need. If it doesn't, you can build one with some (maybe a lot) of effort; as you've observed, this isn't as easy as one might think. See my answer [Compiling an AST back to source code](http://stackoverflow.com/questions/5832412/compiling-an-ast-back-to- source-code/5834775#5834775) If that doesn't work, our [DMS Software Reengineering Toolkit](http://www.semanticdesigns.com/Products/DMS/DMSToolkit.html) with its [Python front end](http://www.semanticdesigns.com/Products/FrontEnds/PythonFrontEnd.html) might do the trick. It has all the above properties.
How to use SSL with Django app (deployed using mod_wsgi and virtualenv) Question: Disclaimer: I don't really know what I'm doing, so I may have phrased things wrong. I've also never asked/answered a question on here before! I have a Django app running on Apache that I deployed using mod_wsgi and virtualenv. I want some parts of the app to use SSL, however when I install the SSL certificate, the https URL goes to the index.html file from my public_html folder instead of the app (which is outside of public_html) For example, visit <https://tradekandi.com>. That URL is just a basic HTML file: public_html/index.html Then visit <http://tradekandi.com>. That's my Django page (in maintenance mode). I've searched stackoverflow and Google all day. I've tried removing the documentroot from the virtual hosts file but that did nothing. I tried adding a SetEnvIf X-Forwarded-Proto https HTTPS=1 line to it but that did nothing either. My virtual hosts file has these lines in it: SSLEngine on SSLCertificateFile /etc/ssl/certs/tradekandi.com.crt SSLCertificateKeyFile /etc/ssl/private/tradekandi.com.key SSLCACertificateFile /etc/ssl/certs/tradekandi.com.cabundle Whenever I make any changes, I restart apache and "touch" the app's wsgi file. How can I make the https URL load the Django app? Any help would be much appreciated. Thank you. More of httpd configuration: <VirtualHost 69.65.42.153:80> ServerName tradekandi.com ServerAlias www.tradekandi.com DocumentRoot /home/trade/public_html ServerAdmin [email protected] UseCanonicalName Off CustomLog /usr/local/apache/domlogs/tradekandi.com combined CustomLog /usr/local/apache/domlogs/tradekandi.com-bytes_log "%{%s}t %I .\n%{%s}t %O ." ## User trade # Needed for Cpanel::ApacheConf <IfModule mod_suphp.c> suPHP_UserGroup trade trade </IfModule> <IfModule !mod_disable_suexec.c> SuexecUserGroup trade trade </IfModule> ScriptAlias /cgi-bin/ /home/trade/public_html/cgi-bin/ Include "/usr/local/apache/conf/userdata/*.conf" Include "/usr/local/apache/conf/userdata/*.owner-root" Include "/usr/local/apache/conf/userdata/std/*.conf" Include "/usr/local/apache/conf/userdata/std/*.owner-root" Include "/usr/local/apache/conf/userdata/std/2/*.conf" Include "/usr/local/apache/conf/userdata/std/2/*.owner-root" Include "/usr/local/apache/conf/userdata/std/2/trade/*.conf" Include "/usr/local/apache/conf/userdata/std/2/trade/tradekandi.com/*.conf" </VirtualHost> <VirtualHost 69.65.42.153:443> ServerName tradekandi.com ServerAlias www.tradekandi.com DocumentRoot /home/trade/public_html ServerAdmin [email protected] UseCanonicalName Off CustomLog /usr/local/apache/domlogs/tradekandi.com combined CustomLog /usr/local/apache/domlogs/tradekandi.com-bytes_log "%{%s}t %I .\n%{%s}t %O ." ## User nobody # Needed for Cpanel::ApacheConf <IfModule mod_suphp.c> suPHP_UserGroup nobody nobody </IfModule> ScriptAlias /cgi-bin/ /home/trade/public_html/cgi-bin/ SSLEngine on SSLCertificateFile /etc/ssl/certs/tradekandi.com.crt SSLCertificateKeyFile /etc/ssl/private/tradekandi.com.key SSLCACertificateFile /etc/ssl/certs/tradekandi.com.cabundle CustomLog /usr/local/apache/domlogs/tradekandi.com-ssl_log combined SetEnvIf User-Agent ".*MSIE.*" nokeepalive ssl-unclean-shutdown <Directory "/home/trade/public_html/cgi-bin"> SSLOptions +StdEnvVars </Directory> Include "/usr/local/apache/conf/userdata/*.conf" </VirtualHost> If it's relevant, this is a dedicated server running CentOS & I am also using it to host one PHP-based site. Wsgi file: import os import sys sys.stdout = sys.stderr from os.path import abspath, dirname, join from site import addsitedir sys.path.append('/home/trade/sites/tradekandi.com.env/lib/python2.7/site-packages') sys.path.insert(0, abspath(join(dirname(__file__), "../../"))) from django.conf import settings os.environ["DJANGO_SETTINGS_MODULE"] = "trade.settings" sys.path.insert(0, join(settings.PROJECT_ROOT, "apps")) from django.core.handlers.wsgi import WSGIHandler application = WSGIHandler() extra.conf with mod_wsgi directives: Alias /static/ /home/trade/public_html/static/ <Directory /home/trade/public_html/static> Order deny,allow Allow from all </Directory> WSGIDaemonProcess trade python-path=/home/trade/sites/tradekandi.com.env/lib/python2.7/site-packages WSGIProcessGroup trade WSGIScriptAlias / /home/trade/sites/tradekandi.com.env/site/trade/deploy/pinax.wsgi <Directory /home/trade/sites/tradekandi.com.env/site/trade/deploy> Order deny,allow Allow from all </Directory> Answer: Answering my own question for the benefit of anyone who may come across this: I added the following lines: WSGIProcessGroup tradek WSGIScriptAlias / /home/trade/sites/tradekandi.com.env/site/trade/deploy/pinax.wsgi to a .conf file located in /usr/local/apache/conf/userdata/ssl/2/trade/tradekandi.com, then used the command /scripts/ensure_vhost_includes --user=trade (I also happened to change the ProcessGroup name) Seems to have done the trick, although now I need to get rid of the insecure elements on the page! Thanks to Graham, because it was one of your answers to someone else that helped me figure this out.
How to define a chi2 value function for arbitrary function? Question: I am doing some data fitting using the pyminuit Python bindings for the minuit minimisation code (http://code.google.com/p/pyminuit/). The minimiser accepts a function and uses introspection to extract the parameters to be minimised. In general, I want to minimise the chi squared value for a dataset given a particular function to describe the dataset. My question: Is there a way to define a chi squared function which, given an arbitrary function with varying numbers of parameters, returns a function which gives the chi squared value for that function _and_ only contains the parameters to be minimised in the function argument specification? Example: from scipy import * import minuit # Generate some data to fit data_x = arange(50) noise = 0.3 data_y = data_x**3 + normal(0.0, noise) # Fit function, e.g. a cubic fit_func = lambda x, a1, a2, a3, a4: a1 + a2*x + a3*x**2 + a4*x**3 # Minimisation function e.g. chi squared # Note this has only the parameters to be minimised in the definition (eg not data_x) min_func = lambda a1, a2, a3, a4: sum( (fit_func(data_x, a1, a2, a3, a4) - data_y)**2 / noise**2 ) THIS is where I'd like to write something like `min_func = make_chi2(fit_func)`. I don't know what to do as `data_x` and `data_y` are only defined outside of the function. The rest of the minimisation routine, for completeness, looks like: # Initialise minimiser object with initial values m = minuit.Minuit(min_func, {'a1': 1.0, 'a2': 1.0, 'a3': 1.0, 'a4': 1.0}) # Run minimiser m.migrad() # Print minimised values - example output print m.values >>> {'a1': 0.000, 'a2': 0.000, 'a3': 0.000, 'a4': 1.000} Thanks for your help in advance! Answer: Since PyMinuit uses introspection, you have to use introspection, too. `make_chi_squared()` could be implemented like this: import inspect chi_squared_template = """ def chi_squared(%(params)s): return (((f(data_x, %(params)s) - data_y) / errors) ** 2).sum() """ def make_chi_squared(f, data_x, data_y, errors): params = ", ".join(inspect.getargspec(f).args[1:]) exec chi_squared_template % {"params": params} return chi_squared Example usage: import numpy def f(x, a1, a2, a3, a4): return a1 + a2*x + a3*x**2 + a4*x**3 data_x = numpy.arange(50) errors = numpy.random.randn(50) * 0.3 data_y = data_x**3 + errors chi_squared = make_chi_squared(f, data_x, data_y, errors) print inspect.getargspec(chi_squared).args printing ['a1', 'a2', 'a3', 'a4']
namespace on python pickle Question: I got an error when I use pickle with unittest. I wrote 3 program files: 1. for a class to be pickled, 2. for a class which use class in #1, 3. unittest for testing class in #2. and the real codes are as follows respectively. #1. ClassToPickle.py import pickle class ClassToPickle(object): def __init__(self, x): self.x = x if __name__=="__main__": p = ClassToPickle(10) pickle.dump(p, open('10.pickle', 'w')) #2. SomeClass.py from ClassToPickle import ClassToPickle import pickle class SomeClass(object): def __init__(self): self.pickle = pickle.load(open("10.pickle", 'r')) self.x = self.pickle.x print self.x if __name__ == "__main__": SomeClass() #3. SomeClassTest.py import unittest from SomeClass import SomeClass from ClassToPickle import ClassToPickle # REQUIRED_LINE class SomeClassTest(unittest.TestCase): def testA(self): sc = SomeClass() self.assertEqual(sc.x, 10) def main(): unittest.main() if __name__ == "__main__": main() I ran #1 program first to make pickle file. And then, when I run program file #2 alone (i.e. enter "python SomeClass.py"), it works. And, when I run program #3 alone (i.e. enter "python SomeClassTest.py"), it also works. However, when I run program #3 as "unit-test" in eclipse+pydev, it returns an error message below. > ====================================================================== > ERROR: testA (SomeClassTest.SomeClassTest) > \---------------------------------------------------------------------- > Traceback (most recent call last): > $ File "/home/tmp/pickle_problem/SomeClassTest.py", line 9, in testA > sc = SomeClass() > $ File "/home/tmp/pickle_problem/SomeClass.py", line 8, in **init** > self.pickle = pickle.load(open("10.pickle", 'r')) > $ File "/usr/lib/python2.7/pickle.py", line 1378, in load > return Unpickler(file).load() > $ File "/usr/lib/python2.7/pickle.py", line 858, in load > dispatchkey > File "/usr/lib/python2.7/pickle.py", line 1090, in load_global > klass = self.find_class(module, name) > $ File "/usr/lib/python2.7/pickle.py", line 1126, in find_class > klass = getattr(mod, name) > $ AttributeError: 'module' object has no attribute 'ClassToPickle' > > \---------------------------------------------------------------------- > Ran 1 test in 0.002s > > FAILED (errors=1) > > And also, when I commented out a line that import ClassToPickle class (line 3 in program #3 and commented as "REQUIRED_LINE"), It doesn't work and return an error message described below. > E > ====================================================================== > ERROR: testA (**main**.SomeClassTest) > \---------------------------------------------------------------------- > Traceback (most recent call last): > File "SomeClassTest.py", line 9, in testA > sc = SomeClass() > File "/home/tmp/pickle_problem/SomeClass.py", line 8, in **init** > self.pickle = pickle.load(open("10.pickle", 'r')) > File "/usr/lib/python2.7/pickle.py", line 1378, in load > return Unpickler(file).load() > File "/usr/lib/python2.7/pickle.py", line 858, in load > dispatchkey > File "/usr/lib/python2.7/pickle.py", line 1090, in load_global > klass = self.find_class(module, name) > File "/usr/lib/python2.7/pickle.py", line 1126, in find_class > klass = getattr(mod, name) > AttributeError: 'module' object has no attribute 'ClassToPickle' > > \---------------------------------------------------------------------- > Ran 1 test in 0.001s > > FAILED (errors=1) > I guess the problem is about namespace in python, but I don't know what happened exactly and what can I do for resolving it. How can I "run as unit-test (in eclipse+pydev)" #3 program correctly, and run #3 program in command line without the line which imports ClassToPickle? Please help me. Answer: That because `__main__.ClassToPickle != ClassToPickle.ClassToPickle`, think of it like this: When you pickled the class instance of ClassToPickle in the `ClassToPickle.py` script, the pickle module will pickle all the reference to the class which mean it will pickle the module name where the class was defined, and because you executed the script `ClassToPickle.py` this mean that the module will be set to `__main__` which mean that `pickle` module will pickle `__main__.ClassToPickle`. And when you tried to load the pickled instance it fail because it didn't find the instance's class which is `__main__.ClassToPickle` and not the one that you imported using `from ClassToPickle import ClassToPickle` because this latest is `ClassToPickle.ClassToPickle`. A fix will be to create another script that will handle dumping instead of doing it in `ClassToPickle.py` e.g. import pickle from ClassToPickle import ClassToPickle if __name__=="__main__": p = ClassToPickle(10) pickle.dump(p, open('10.pickle', 'w'))