text
stringlengths
226
34.5k
Google App Engine Guestbook application gives error Question: I upload the Google App Engine application which is at the url developers.google.com/appengine/docs/python/memcache/usingmemcache#Memcache When I run the application on Google App Engine Launcher, it runs but the website shows: (First error is there us no Python "PIL" module but I am not using image. Could you please suggest what is causing the error? *** Running dev_appserver with the following flags: --skip_sdk_update_check=yes --port=13080 --admin_port=8005 Python command: /usr/bin/python2.7 INFO 2014-01-17 20:43:22,217 devappserver2.py:660] Skipping SDK update check. WARNING 2014-01-17 20:43:22,222 api_server.py:331] Could not initialize images API; you are likely missing the Python "PIL" module. INFO 2014-01-17 20:43:22,226 api_server.py:138] Starting API server at: localhost:55385 INFO 2014-01-17 20:43:22,230 dispatcher.py:171] Starting module "default" running at: localhost:13080 INFO 2014-01-17 20:43:22,238 admin_server.py:117] Starting admin server at: localhost:8005 ERROR 2014-01-17 20:43:24,601 wsgi.py:262] Traceback (most recent call last): File "/Users/Desktop/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/runtime/wsgi.py", line 239, in Handle handler = _config_handle.add_wsgi_middleware(self._LoadHandler()) File "/Users/Desktop/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/runtime/wsgi.py", line 301, in _LoadHandler raise err ImportError: <module 'guestbookw2' from '/Users/guestbookw2/guestbookw2.pyc'> has no attribute application INFO 2014-01-17 20:43:24,607 module.py:617] default: "GET / HTTP/1.1" 500 - ERROR 2014-01-17 20:43:24,727 wsgi.py:262] Traceback (most recent call last): File "/Users/Desktop/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/runtime/wsgi.py", line 239, in Handle handler = _config_handle.add_wsgi_middleware(self._LoadHandler()) File "/Users/Desktop/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/runtime/wsgi.py", line 301, in _LoadHandler raise err ImportError: <module 'guestbookw12' from '/Users/guestbookw2/guestbookw2.pyc'> has no attribute application INFO 2014-01-17 20:43:24,732 module.py:617] default: "GET /favicon.ico HTTP/1.1" 500 - Answer: Make sure that you have the following files in the path that you are uploading your application from: 1. **index.yaml** (auto-generated; you don't need to add or change anything in here at this point). 2. **favicon.ico** (in the correct format; should be 16x16 or 32x32 pixels if I remember correctly). 3. **main.py** (mapping all the paths in your web-site; example given below): from webapp2 import WSGIApplication from Server import MainRequestHandler from Server import SomeRequestHandler from Server import OtherRequestHandler app = WSGIApplication([ ('/' ,MainRequestHandler), ('/abc' ,SomeRequestHandler), ('/def' ,SomeRequestHandler), ('/xyz' ,OtherRequestHandler), ]) 4. **app.yaml** (with the following contents; using `<...>` where you need to set a value): application: <the app-id you chose when use signed in for GAE> version: 1 runtime: python27 api_version: 1 threadsafe: yes handlers: - url: /favicon\.ico static_files: favicon.ico upload: favicon\.ico - url: .* script: main.app libraries: - name: webapp2 version: "2.5.1" // you might need to change this as well **Note** : if you wish to avoid handling 'favicon.ico' request, then you must remove the reference in file 'app.yaml'. **Supplemental** : You will need to implement all the request handlers imported in 'main.py'. In the example above, 'main.py' expects to find them in a Python module named 'Server'. Each request handler must inherit `class RequestHandler`, imported from `webapp2`. **Supplemental #2** : In order to solve the 'PIL' issue (had a similar problem if memory serves correctly), simply install it. From a Windows command line, enter: pip install pil.
Mutable objects in python and constants Question: I have a class which contains data as attributes and which has a method to return a tuple containing these attributes: class myclass(object): def __init__(self,a,b,c): self.a = a self.b = b self.c = c def tuple(self): return (self.a, self.b, self.c) I use this class essentially as a tuple where the items (attributes) can be modified/read through their attribute name. Now I would like to create objects of this class, which would be constants and have pre-defined attribute values, which I could then assign to a variable/mutable object, thereby initializing this variable object's attributes to match the constant object, while at the same time retaining the ability to modify the attributes' values. For example I would like to do this: constant_object = myclass(1,2,3) variable_object = constant_object variable_object.a = 999 Now of course this doesn't work in python, so I am wondering what is the best way to get this kind of functionality? Answer: import copy class myclass(object): def __init__(self,a,b,c): self.a = a self.b = b self.c = c def tuple(self): return (self.a, self.b, self.c) constant_object = myclass(1,2,3) variable_object = copy.deepcopy(constant_object) variable_object.a = 999 print constant_object.a print variable_object.a Output: 1 999
parsing MySQL database with python MySQLdb to extract hashtags Question: I have tweets scraped in MySQL database and I manage to connect to it and query for column that contains tweets' text. Now what I want to do is parse this and extract hashtags into a csv file. So far, I have this code that is working until the last loop: import re import MySQLdb # connects to database mydb = MySQLdb.connect(host='****', user='****', passwd='****', db='****') cursor = mydb.cursor() # queries for column with tweets text getdata = 'SELECT text FROM bitscrape' cursor.execute(getdata) results = cursor.fetchall() for i in results: hashtags = re.findall(r"#(\w+)", i) print hashtags I get the following error: TypeError: expected string or buffer. And the problem is in line hashtags = re.findall(r"#(\w+)", i). Any suggestions? Thanks! Answer: `cursor.fetchall()` returns a list of **tuples**. Take the first element from each row and pass it to `findall()`: for row in results: hashtags = re.findall(r"#(\w+)", row[0]) Hope that helps.
Importing module from relative path Question: I'm looking for some advice on a python issue I am having. I am a novice at python. I believe that I am relying on my programming experience from other languages to make this work and I have finally come to a stand-still. Here is the scenario, I am importing a module that relies on another module. My driver for the program, called test.py, starts out like this: import sys sys.path.append(r'C:\Program Files (x86)\Zorba XQuery Processor 2.9.1\share\zorba\uris\com\nuemeta\www\modules\DDEXpedite\bindings\Python\Code and Other Files') import QueryDDEX Then in the QueryDDEX.py file I have: import sys,os temp = os.getcwd() os.chdir(os.path.dirname(os.path.realpath(__file__))) sys.path.append(os.path.realpath("..\..\..\..\..\..\..\..\..\python")) print sys.path import zorba_api os.chdir(temp) In my head I was thinking (1)Save the current working directory, (2)Change the current working directory to the directory of the QueryDDEX.py module, (3) import the zorba_api module from a relative path because if I deploy this module to other computers they may not have the same file structure as mine, and (4) change the current working directory back to what it was initially. Now, I have read that it is not okay to use relative paths and I have also read that it is okay. I do not see another choice because I did not write the zorba_api so I do not have too much control over it. Anyway, the output of the program is this: ['C:\\Users\\Administrator\\Desktop', 'C:\\Python27\\Lib\\idlelib', 'C:\\Windows\\SYSTEM32\\python27.zip', 'C:\\Python27\\DLLs', 'C:\\Python27\\lib', 'C:\\Python27\\lib\\plat-win', 'C:\\Python27\\lib\\lib-tk', 'C:\\Python27', 'C:\\Python27\\lib\\site-packages', 'C:\\Program Files (x86)\\Zorba XQuery Processor 2.9.1\\share\\zorba\\uris\\com\\nuemeta\\www\\modules\\DDEXpedite\\bindings\\Python\\Code and Other Files', 'C:\\Program Files (x86)\\Zorba XQuery Processor 2.9.1\\share\\zorba\\python'] Traceback (most recent call last): File "C:\Users\Administrator\Desktop\Test.py", line 4, in <module> import QueryDDEX File "C:\Program Files (x86)\Zorba XQuery Processor 2.9.1\share\zorba\uris\com\nuemeta\www\modules\DDEXpedite\bindings\Python\Code and Other Files\QueryDDEX.py", line 9, in <module> import zorba_api ImportError: No module named zorba_api This is where things get tricky in my opinion, the zorba_api module is located at C:\\Program Files (x86)\\Zorba XQuery Processor 2.9.1\\share\\zorba\\python and we can see by my debug statement that it IS in the python class path. So why am I getting this error? Answer: Check out this scenario. You have the file `alpha.py` at `C:\projects\test\`. Then you also have a file called `beta.py` at `C:\projects\test\modules\` so to import `beta` from `alpha` you should do: import modules.beta Or, not very good but useful, adding the `modules` directory to your `sys.path`. Then if you want to import modules from your `beta.py` file you will have to take care that you're not at `C:\projects\test\modules\` directory, you're in the `alpha.py` directory. So for example, if there's a third file called `gamma.py` at `modules/`, if you want to import it from `beta.py` you should use: import modules.gamma Because you are at the _importer file_ (`alpha.py`) path, not at the _imported file_ (`beta.py`) path. Hope it helps to solve your problem!
Pass a file as a parameter in two Python Scripts Question: New Python'er has a question _"hand raised"_. I have two Python Scripts and a XML file. "mysecondpython.py" needs to call "myfirstpython.py" with a parameter of "data.xml" so that it can write something in, which then returns a file. From command-line, I should type `python mysecondpython.py` and it should be viola! But I got no cigars. What is this new python'er doing wrong? **myfirstpython.py** import xml.etreeElementTree as et def allmytrees(file): dest_tree = et.parse(file) dest_root = dest_tree.getroot() def inserter(): dest_root.insert(0, "hello world") def printer(): dest_tree.write('out.xml', xml_declaration=True, encoding='utf-8') if __name__ == "__main__": allmytrees(file) inserter() printer() **mysecondpython.py** import myfirstpython def callingscripts(file) callpython = myfirstpython(file) if __name__ == "__main__": file = "data.xml" callingscripts(file) **data.xml** <root> <nothing-here>123</nothing-here> </root> _I'm in tears._ Answer: When you import a file, it's `__name__` does not `== "__main__"`. In fact, the statement `if __name__ == "__main__":` is specifically designed to say "am I the program that is running, or am I being imported (in which case don't do this stuff)" You need to write a function in myfirstpython.py, and call it from mysecondpython.py
Matplotlib + Ubuntu + GTK3 no plot shown Question: I can see the GUI but not the plot. No errors, even the mouse coordinates are okay, but no plot using import matplotlib.pyplot as plt plt.plot([1,2,3,4]) plt.ylabel('some numbers') plt.show() Then $ python -c 'import matplotlib; import matplotlib.pyplot; print(matplotlib.backends.backend)' GTK3Agg I installed the following on Ubuntu 12.04: sudo apt-get install python-gi sudo apt-get install libgtk-3-devel sudo pip install matplotlib sudo pip install numpy What could be the problem? Or how can I further debug this? Answer: This is working on Ubuntu 14.04. All packages from apt: #!/usr/bin/env python3 import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk import matplotlib.pyplot as plt plt.plot([1,2,3,4]) plt.ylabel('some numbers') plt.show()
parsing JSON which contains "objects" Question: I'm getting data from an application that returns what seems to be an JSON, but with some "objects". For instance: {"rgEvtData":[new VisData(0,0,1,0,1,0,0,0,0,-1),new VisData(0,1,1,1,1,0,0,0,0,-1),new VisData(0,2,1,2,1,0,0,0,0,-1),new VisData(0,3,2,0,1,0,0,0,0,-1),new VisData(0,4,2,1,1,0,0,0,0,-1),new VisData(0,5,2,2,1,0,0,0,0,-1),new VisData(0,6,2,3,1,0,0,0,0,-1),new VisData(0,7,3,0,1,0,0,0,0,-1),new VisData(0,8,3,1,1,0,0,0,0,-1)]} any idea if I can parse it on python without dirty workarounds (ie, replace() or regexp)? Answer: No, you can't. Even if python could parse it, what would it do with the `VisData`s? I think your only option (except the stick approach mentioned), to translate this string into valid JSON somehow. For example, replacing `new VisData(...)` with `[...]`, or `{"class": "VisData", "args": [...]}` if you have multiple classnames. But you said you don't want that. **Update** I have an example, I think it is what you need. It handles custom classes in the format you provided. It would also handle multiple classes and any number/type of constructor arguments. import re import json # our python VisData class class VisData(object): def __init__(self, *args): self.args = args # object hook to convert our {"class":"VisData","args":[...]} dict to VisData insances def object_hook(obj): # if we recognize our object describer dict if len(obj) == 2 and "class" in obj and "args" in obj: # instantiate our classes by name clazz = globals()[obj["class"]] args = obj["args"] return clazz(*args) return obj # input input_string = '{"rgEvtData":[new VisData(0,0,1,0,1,0,0,0,0,-1),new VisData(0,1,1,1,1,0,0,0,0,-1)]}' # make it json json_string = re.sub(r'new (\w+)\(([^\)]*)\)', r'{"class":"\1","args":[\2]}', input_string) # parse it with our object hook data = json.loads(json_string, object_hook=object_hook) # result print(data) # -> {u'rgEvtData': [<__main__.VisData object at 0x1065d8210>, <__main__.VisData object at 0x1065d8250>]} print(data["rgEvtData"][0]) # -> <__main__.VisData object at 0x1065d8210> print(data["rgEvtData"][0].args) # -> (0, 0, 1, 0, 1, 0, 0, 0, 0, -1)
randomly choose from list using random.randint in python Question: How to use `random.randint()` to select random names given in a list in python. I want to print 5 names from that list. Actually i know how to use `random.randint()` for numbers. but i don't know how to select random names from a given list. we are not allowed to use `random.choice`. help me please Answer: This will not guarantee no repeats, since random.choice is better for that. import random names = ["A", "B", "C", "D", "E", "F", "G", "H", "I"] print([names[random.randint(0, len(names)-1)] for i in range(5)])
Python: Get Twitter Trends in tweepy, and parse JSON Question: _Ok, so please note this is my first post_ So, I am trying to use Python to get Twitter Trends, I am using python 2.7 and Tweepy. I would like something like this (which works): #!/usr/bin/python # -*- coding: utf-8 -*- import tweepy consumer_key = 'secret' consumer_secret = 'secret' access_token = 'secret' access_token_secret = 'secret' # OAuth process, using the keys and tokens auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) api = tweepy.API(auth) trends1 = api.trends_place(1) print trends1 That gives a massive JSON string, I would like to extract each trend name to a variable, in string format `str(trendsname)` ideally. Which would ideally have the names of trends like so: `trendsname = str(trend1) + " " +str(trend2) + " "` and so on, for each of the trend names. Please note I am only learning Python. Answer: It looks like Tweepy deserializes the JSON for you. As such, `trends1` is just an ordinary Python list. This being the case, you can simply do the following: trends1 = api.trends_place(1) # from the end of your code # trends1 is a list with only one element in it, which is a # dict which we'll put in data. data = trends1[0] # grab the trends trends = data['trends'] # grab the name from each trend names = [trend['name'] for trend in trends] # put all the names together with a ' ' separating them trendsName = ' '.join(names) print(trendsName) Result: #PolandNeedsWWATour #DownloadElyarFox #DünMürteciBugünHaşhaşi #GalatasaraylılıkNedir #KnowTheTruth Tameni Video Anisa Rahma Mikaeel Manado JDT
Calculating mean of sample in monte carlo simulation Question: I did a Monte Carlo simulation of n samples. For each sample i, I need to calculate the value Xi so probably, the results that I will obtain is: > X = [X1, X2, ..., Xn] (Here Xi can be a matrix or number). Now I want to calculate the mean of theses samples that I call Xmean. So I need to obtain something like this: > Xmean = [X1, (X1+X2)/2, (X1+X2+X3)/3 ... , (X1+X2+...+Xn)/n] In Python, I write a code: for i in range(N): for j in range(i+1): Xmean(i) = Xmean(i) + X(j) Xmean(i) = Xmean(i) / (i+1) It works well but too slow, I would like to know if I can speed up this code? And if you guys could suggest to me some interesting Python's library that help for Monte Carlo simulation. Thanks, Answer: import timeit, numpy setup = ''' from __main__ import mc0, mc1, mc2 import random, numpy random.seed(0) n = 10**3 data = [random.randint(0, 2**32-1) for _ in range(n)] np_data = numpy.array([float(x) for x in data]) ''' # your implementation def mc0(data): xmean = [] for i in range(len(data)): xmean.append(0) for j in range(i+1): xmean[i] += data[j] xmean[i] = xmean[i] / (i+1) return xmean # my implementation def mc1(data): xmean = [] for i, x in enumerate(data): if i == 0: new = x else: new = x/(i+1) + xmean[i-1] * (i/(i+1)) xmean.append(new) return xmean # Donbeo's numpy implementation def mc2(data): xmean = numpy.cumsum(data) / numpy.array(range(1, len(data)+1)) return xmean number = 100 things = [('mc0', 'mc0(data)'), ('mc1', 'mc1(data)'), ('mc2', 'mc2(np_data)')] for note, call in things: print('{:20} {}'.format(note, timeit.timeit(call, setup=setup, number=number))) Result: mc0 26.023956370918587 mc1 0.1423197092108488 mc2 0.13584513496654083 There's no point in redoing the sum over `x(1)..x(i)` at each loop iteration, when you already have that information available in `xmean`. The numpy version by Donbeo is marginally faster than the pure-Python version by me, both of which are nearly 200 times faster (for these data, anyway) than the original version.
Drawing tangent plot in Python (matplotlib) Question: Today I decided to write simple program in Python, just to practice before exam. Firstly, I wanted to draw sin and cos plot, which wasn't so hard. But then, I decided to challenge myself and draw tangent plot. import pylab as p x= p.arange(-1.0,1.0,0.1) y= (p.sin(2*p.pi*x)) / (p.cos(2*p.pi*x)) p.plot(x,y,'g-',lw=1) p.show() It returns... ugh... this: ![enter image description here](http://i.stack.imgur.com/fpANl.png) As you can see, it looks more like ECK plot than tangent plot. Does anyone knows what's wrong? Answer: If you increase the number of points in `x`, import pylab as p import numpy as np x = p.linspace(-1.0, 1.0, 1000) y = (p.sin(2 * p.pi * x)) / (p.cos(2 * p.pi * x)) p.plot(x, y, 'g-', lw=1) p.show() you get something like this: ![enter image description here](http://i.stack.imgur.com/vklgJ.png) Notice how large the `y-range` is getting. Matplotlib is not able to show you much of the small values in the tangent curve because the range is so large. The plot can be improved by ignoring the extremely large values near the asymptotes. Using [Paul's workaround](http://stackoverflow.com/a/2542065/190597) to handle asymptotes, import pylab as p import numpy as np x = p.linspace(-1.0, 1.0, 1000) y = (p.sin(2 * p.pi * x)) / (p.cos(2 * p.pi * x)) tol = 10 y[y > tol] = np.nan y[y < -tol] = np.nan p.plot(x, y, 'g-', lw=1) p.show() you get ![enter image description here](http://i.stack.imgur.com/XzLmQ.png)
Python-social, Django-nonrel, and GAE fighting over files, python-tk Question: I'm trying to host a Django app on Google App Engine, so I'm using [Django nonrel](https://github.com/django-nonrel/django) and following [these instructions](http://www.allbuttonspressed.com/projects/djangoappengine). Now, trying to get [Python social auth](https://github.com/omab/python-social-auth) working on it, I'm running into two problems. First, when working with code very similar to the [example Django config](https://github.com/omab/python-social- auth/tree/master/examples/django_example/example) from Python social, trying to load a url from a running server, I get this: Traceback (most recent call last): File "/home/pablo/scripts/google_appengine/google/appengine/tools/dev_appserver.py", line 2989, in _HandleRequest self._Dispatch(dispatcher, self.rfile, outfile, env_dict) File "/home/pablo/scripts/google_appengine/google/appengine/tools/dev_appserver.py", line 2832, in _Dispatch request_file = open(request_file_name, 'wb') File "/home/pablo/scripts/google_appengine/google/appengine/dev_appserver_import_hook.py", line 605, in __init__ raise IOError('invalid mode: %s' % mode) IOError: invalid mode: wb Somewhere, the app is trying to create local files, which App Engine doesn't allow, but I'm confused because this is coming _from App Engine's code_. Does anyone know where this might be coming from? Secondly, when I try to access root on the server, I get the following error: ... [many lines elided] File "/home/pablo/scripts/google_appengine/google/appengine/tools/dev_appserver_import_hook.py", line 692, in Decorate return func(self, *args, **kwargs) File "/home/pablo/scripts/google_appengine/google/appengine/tools/dev_appserver_import_hook.py", line 1642, in FindAndLoadModule description) File "/home/pablo/scripts/google_appengine/google/appengine/tools/dev_appserver_import_hook.py", line 692, in Decorate return func(self, *args, **kwargs) File "/home/pablo/scripts/google_appengine/google/appengine/tools/dev_appserver_import_hook.py", line 1589, in LoadModuleRestricted description) File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 42, in <module> raise ImportError, str(msg) + ', please install the python-tk package' ImportError: No module named _tkinter, please install the python-tk package Somewhere, Django is trying to use `python-tk` for `Tkinter`, but as I understand it, python-tk is a GUI library. How did it get here, and how can I get rid of any code that needs it? For reference, here's the function getting called for the domain I'm trying in `urls.py` when accessing the running server (and getting these errors): def home(request): """Home view, displays login mechanism""" if request.user.is_authenticated(): return redirect('done') return render_to_response('home.html', { 'plus_id': getattr(settings, 'SOCIAL_AUTH_GOOGLE_PLUS_KEY', None) }, RequestContext(request)) Any help would be appreciated -- I'm pretty new to Django and Python, and I'd love to move forward from this :D Answer: Python on Google App Engine is behaving a bit different, as you already realised with the local files. Another thing that needs a special treatment is the 3rd party libraries that in order to make them available, they should be [handled properly](http://stackoverflow.com/a/14851686/8418). In many cases, even if you're going to include these libraries into your GAE app, they might be using something that is not supported on the production so the whole thing is not going to work.
Validating SAML signature in python Question: I need to implement authentication in python from a 3rd party by using SAML2. I have looked into [pysaml2](https://pypi.python.org/pypi/pysaml2/1.1.0) and found that to be quite confusing, and decided to give [M2Crypto](https://pypi.python.org/pypi/M2Crypto) a chance after I found [this question](http://stackoverflow.com/questions/9704919/saml-signature- verification-using-python-m2crypto) by [Ennael](http://stackoverflow.com/users/518959/ennael). The SAML token I receive [can be found here](http://pastebin.com/vehrUdkB). I have already extracted all the information I need from the `Assertion` tag (the user's SSN, IP and the SAML tokens expiration window) but I can't get the `verify_signature` function from Ennael (and the [revised code](http://stackoverflow.com/questions/9704919/saml-signature-verification- using-python-m2crypto/17372895#17372895) from [Ezra Nugroho](http://stackoverflow.com/users/2464942/ezra-nugroho)) to return True. I have also tried to change `verify_EVP.reset_context(md='sha1')` to `verify_EVP.reset_context(md='sha256')` but that didn't work either. I think my mistake must be in the signed_info part. What do I pass to `verify_signature` for that part? Do I have to preprocess it in any way? I have been looking into the Transform tag but don't know where too look next. Any help will be greatly appreciated. If someone needs the XML before the obfuscation to test and help me just PM me. **EDIT** This is my code (very similar to the things i linked to. The main function is at the bottom): def verify_signature(signed_info, cert, signature): from M2Crypto import EVP, RSA, X509, m2 x509 = X509.load_cert_string(base64.decodestring(cert), X509.FORMAT_DER) pubkey = x509.get_pubkey().get_rsa() verify_EVP = EVP.PKey() verify_EVP.assign_rsa(pubkey) verify_EVP.reset_context(md='sha1') verify_EVP.verify_init() verify_EVP.verify_update(signed_info) return verify_EVP.verify_final(signature.decode('base64')) def decode_response(resp): return base64.b64decode(resp) def get_xmldoc(xmlstring): return XML(xmlstring) def get_signature(doc): return doc.find('{http://www.w3.org/2000/09/xmldsig#}Signature') def get_signed_info(signature): signed_info = signature.find( '{http://www.w3.org/2000/09/xmldsig#}SignedInfo') signed_info_str = tostring(signed_info) # return parse(StringIO(signed_info_str)) return signed_info_str def get_cert(signature): ns = '{http://www.w3.org/2000/09/xmldsig#}' keyinfo = signature.find('{}KeyInfo'.format(ns)) keydata = keyinfo.find('{}X509Data'.format(ns)) certelem = keydata.find('{}X509Certificate'.format(ns)) return certelem.text def get_signature_value(signature): return signature.find( '{http://www.w3.org/2000/09/xmldsig#}SignatureValue').text def parse_saml(saml): dec_resp = decode_response(saml) xml = get_xmldoc(dec_resp) signature = get_signature(xml) signed_info = get_signed_info(signature) cert = get_cert(signature) signature_value = get_signature_value(signature) is_valid = verify_signature(signed_info, cert, signature_value) **UPDATE** : Is it possible I need some more information from the 3rd party authentication provider? Do I need a private key for any of this? Answer: I faced the same problem, and had to develop a module for it: <https://github.com/kislyuk/signxml>. I chose to rely only on PyCrypto and pyOpenSSL, since M2Crypto is less popular and not well-maintained, which is a hazard from both compatibility (e.g. PyPy) and security perspectives. I also use lxml for the canonicalization (c14n). From the signxml docs: from signxml import xmldsig cert = open("example.pem").read() key = open("example.key").read() root = ElementTree.fromstring(data) xmldsig(root).verify()
How to remove trailing `\r` in shell? Question: I have a file that looks like this: 1 0.1951 0.1766 0.1943 0.1488 0.1594 0.2486 0.2044 0.2013 0.1859 0.1559 0.1761 0.1666 0.1737 0.1595 0.1940 1 0.2398 0.1894 0.1532 0.1749 0.2397 1 0.1654 0.1622 0.1940 0.1895 0.1659 1 0.1384 0.1489 0.1547 0.1648 0.1390 1 0.1840 0.2472 0.2256 0.2281 0.1878 Somehow it's created in windows so it has this irritating `\r` character at the end. But I am running my shell line in linux. In python I could have read the file and do a `line.strip('\r')` while looping through the lines in the file. But i have to use shell to run a loop and somehow the '\r' keep appearing. Is there any way to remove it while in the `while` loop? I am trying to do a loop for this script in shell: <https://github.com/alvations/meanie/blob/master/amgm.py>: # -*- coding: utf-8 -*- import math, operator def arithmetic_mean(x): # x is a list of values. """ Returns the arithmetic mean given a list of values. """ return sum(x)/len(x) def geometric_mean(x): # x is a list of values """ Returns the geometric mean given a list of values. """ return math.pow(reduce(operator.mul, x, 1), 1/float(len(x))) def arigeo_mean(x, threshold = 1e-10): # x is a list of values arith = arithmetic_mean(x) geo = geometric_mean(x) while math.fabs(arith - geo) > threshold: [arith,geo] = [(arith + geo) / 2.0, math.sqrt(arith * geo)] return arith def main(means): print means means = map(float,means) print "arithmetic mean = ", arithmetic_mean(means) print "geometric mean = ", geometric_mean(means) print "arithmetic-geometric mean = ", arigeo_mean(means) if __name__ == '__main__': import sys if len(sys.argv) < 2: sys.stderr.write('Usage: python %s mean1 mean2 mean3 ... \n' % sys.argv[0]) sys.exit(1) so I tried the following shell line to iterate through my textfile: alvas@ubi:~/git/meanie$ while read line; do python amgm.py $line; done < out.tab and got these errors: ['1', '0.1951', '0.1766', '0.1943', '0.1488', '\r'] Traceback (most recent call last): File "amgm.py", line 32, in <module> main(sys.argv[1:]) File "amgm.py", line 22, in main means = map(float,means) ValueError: could not convert string to float: ['0.1594', '0.2486', '0.2044', '0.2013', '0.1859', '\r'] Traceback (most recent call last): File "amgm.py", line 32, in <module> main(sys.argv[1:]) File "amgm.py", line 22, in main means = map(float,means) ValueError: could not convert string to float: ['0.1559', '0.1761', '0.1666', '0.1737', '0.1595', '\r'] Traceback (most recent call last): File "amgm.py", line 32, in <module> main(sys.argv[1:]) File "amgm.py", line 22, in main means = map(float,means) ValueError: could not convert string to float: ['0.1940', '1', '0.2398', '0.1894', '0.1532', '\r'] Traceback (most recent call last): File "amgm.py", line 32, in <module> main(sys.argv[1:]) File "amgm.py", line 22, in main means = map(float,means) ValueError: could not convert string to float: ['0.1749', '0.2397', '1', '0.1654', '0.1622', '\r'] Traceback (most recent call last): File "amgm.py", line 32, in <module> main(sys.argv[1:]) File "amgm.py", line 22, in main means = map(float,means) ValueError: could not convert string to float: ['0.1940', '0.1895', '0.1659', '1', '0.1384', '\r'] Traceback (most recent call last): File "amgm.py", line 32, in <module> main(sys.argv[1:]) File "amgm.py", line 22, in main means = map(float,means) ValueError: could not convert string to float: ['0.1489', '0.1547', '0.1648', '0.1390', '1', '\r'] Traceback (most recent call last): File "amgm.py", line 32, in <module> main(sys.argv[1:]) File "amgm.py", line 22, in main means = map(float,means) ValueError: could not convert string to float: ['0.1840', '0.2472', '0.2256', '0.2281', '0.1878', '\r'] Traceback (most recent call last): File "amgm.py", line 32, in <module> main(sys.argv[1:]) File "amgm.py", line 22, in main means = map(float,means) ValueError: could not convert string to float: Note: I'm NOT allowed to change the python script though =( Answer: You should be able to strip any trailing whitespace from the line before passing it to your python program. Consider one of the suggestions [here](http://stackoverflow.com/questions/369758/how-to-trim-whitespace-from- bash-variable). If you're running bash, the second answer doesn't involve invoking an additional program, if you're not, you may look at the the sed option if your shell doesn't support parameter expansion. Another option would be to use the `dos2unix` (or similar) utility that converts the windows line ending (`\r\n`) to the unix line ending (`\n`). Alternatively, you could get crazy and _always_ trim off the last character irrespective of what it was with a bash parameter expansion like the one described [here](http://www.cyberciti.biz/faq/bash-remove-last-character-from- string-line-word/). But I would consider this the least-favorable option.
How to generate HTML color diff from git using python Question: So I figured out creating HTML git diff i can embed in email but don't know why is it all being spit in one line ? here is how I did it!! import sys import subprocess import os from ansi2html.converter import Ansi2HTMLConverter ansiText = os.path.expanduser('~/Desktop/colorDiff') pr = subprocess.Popen( "git diff HEAD^ HEAD --color > "+ansiText , cwd = os.getcwd() , shell = True, stdout = subprocess.PIPE, stderr = subprocess.PIPE ) (out, error) = pr.communicate() conv = Ansi2HTMLConverter() ansi = '' with open(ansiText, 'r+') as fh: fh.readline() for line in fh: ansi += ''.join(line.split()) html = conv.convert(ansi) with open("%s.html" % ansiText, 'w+') as wf: wf.write(html) os.remove(ansiText) print str(error).capitalize() maybe its too late to be awake... Answer: figured out myself import sys import subprocess import os from ansi2html.converter import Ansi2HTMLConverter ansiText = os.path.expanduser('~/Desktop/colorDiff') proc = subprocess.Popen('git diff HEAD^ HEAD --color', shell=True, stdout=subprocess.PIPE, stderr = subprocess.PIPE ) diffData = proc.stdout.read() conv = Ansi2HTMLConverter() html = conv.convert(diffData) with open("%s.html" % ansiText, 'w') as wf: wf.write(html)
Calculate the greatest distance between any two strings in a group, using Python Question: My question is how to calculate greatest distance between any two strings that correspond to a certain group. Each line in my file starts with a 'group number' followed by a long string. I want to know, for each group, what the greatest distance between any two strings in a group, for each group. Below is the kind of file I'm working with (the strings have been shortened). Notice the groups aren't necessarily in order, and some of my groups only have one string associated with them, so I would want to just skip over them (Group '3' in the below example): 0 GCAGACGGGUGAGUAACGCGUGGGAACGUACCAUUUGCUACGGAAUAACUCAGG 0 GCAGACGGGUGAGUAACGCGUGGGAACGUACCAUUUGCUACGGAAUAACUCAGG 1 CGAACGGGUGAGUAACACGUGGGCAAUCUGCCCUGCACUCUGGGACAAGCCCUG 1 CGAACGGGUGAGUAACACGUGGGCAAUCUGCCCUGCACUCUGGGACAAGCCCUG 1 CGAACGGGUGAGUAACACGUGGGCAAUCUGCCCUGCACUCUGGGACAAGCCCUG 2 GCCCUUCGGGGUACUCGAGUGGCGAACGGGUGAGUAACACGUGGGUGAUCUGCC 2 GCCCUUCGGGGUACUCGAGUGGCGAACGGGUGAGUAACACGUGGGUGAUCUGCC 2 GCCCUUCGGGGUACUCGAGUGGCGAACGGGUGAGUAACACGUGGGUGAUCUGCC 0 GCAGACGGGUGAGUAACGCGUGGGAACGUACCAUUUGCUACGGAAUAACUCAGG 0 GCAGACGGGUGAGUAACGCGUGGGAACGUACCAUUUGCUACGGAAUAACUCAGG 3 GCAGACGGGUGAGUAACAAAAAGGAACGUACCAUUUGCUACGGAAUAACUCAGG I want to create something that will create an output that looks something like this: Group0 = 0 Group1 = 1.2 Group2 = 2.1 Average = 1.1 This output would be giving me the group number and then the greatest difference for that group. And also the overall average of the greatest difference between all groups (again skipping over the groups with only one string associated with them): My real file has about 5000 groups, and the strings I'm comparing are ~400 characters long. I think I could start solving this by looking at this [Question](http://stackoverflow.com/questions/3106994/algorithm-to-calculate- percent-difference-betweem-two-blobs-of-text), but I'm not sure how to only calculate percent differences for strings in the same group, avoid groups with only one string, and calculate the overall average percent difference for all the groups. Any help would be greatly appreciated, thank you very much for any ideas! EDIT: Here are a few truncated lines from the file I'm working with. The 'group' numbers range from 0 to ~ 6000. The string of letters is actually 426 characters long. The file format is [number][a whitespace][string of letters][end of line character] `7 UGGCGAACGGGUGAGUAAC 35 GUGGGGAUUAGUGGCGAAC 50 AAACGAGAUGUAGCAAUAC 82 GGAGAGAGCUUGCUCUCUU 479 UCAGGAGCUUGCUCCUGU 46 CGAGGAGCUUGCUCCUUU 24 AACUGGGUCUAAUACCUU` Answer: You could also try to use [difflib](http://docs.python.org/2/library/difflib.html)'s SequenceMatcher from the standard library: >>> import difflib >>> from itertools import groupby, combinations >>> def find_max_ratio(lines): lines = [row.split() for row in lines] # the file should already break at each line break lines = [(int(row[0]), row[1]) for row in lines] lines = groupby(sorted(lines), lambda x: x[0]) # combine strings into their respective groups, sorting them first on int of first element group_max = dict() for group in lines: strings = list(group[1]) # need to convert group[1] from iterator into list if len(strings) > 1: # if the number of strings is 1, then there is nothing to compare the string with in its group similarity = 1 for line1, line2 in combinations(strings, 2): s = difflib.SequenceMatcher(None, line1[1], line2[1]) # need to compare second element in each list and exclude the first element (which is the group number) similarity = s.ratio() if s.ratio() < similarity else similarity group_max[line1[0]] = 1 - similarity # gives difference ratio return group_max >>> t = open('test.txt') >>> print find_max_ratio(t) # it appears that your examples don't have any differences {'1': 0, '0': 0, '2': 0} You can then calculate the average as follows: >>> max_ratios = find_max_ratio(t) >>> average = sum(max_ratios.values())/float(len(max_ratios)) >>> average 0.0 # there are no differences in your test data above **EDIT: Writing to a file** >>> output = sorted(max_ratios.items(), key=lambda x: x[1], reverse=True) # sorting by descending ratios >>> with open('test2.txt', 'w') as f: # a new file name >>> f.write('\n'.join([group + ': ' + str(ratio) for group, ratio in output]) + '\n\nAverage: ' + str(average)) **EDIT 2: Adding minimum difference** You can add the minimum difference into your result (here in the form of a tuple `(<max_difference>, <min_difference>)` like this: def find_maxmin_ratios(lines): lines = [row.split() for row in lines] # the file should already break at each line break lines = [(int(row[0]), row[1]) for row in lines] lines = groupby(sorted(lines), lambda x: x[0]) # combine strings into their respective groups, sorting them first on int of first element group_minmax = dict() for index, group in lines: strings = list(group) # need to convert group[1] from iterator into list if len(strings) > 1: # if the number of strings is 1, then there is nothing to compare the string with in its group max_similarity = 1 min_similarity = 0 for line1, line2 in combinations(strings, 2): s = difflib.SequenceMatcher(None, line1[1], line2[1]) # need to compare second element in each list and exclude the first element (which is the group number) max_similarity = s.ratio() if s.ratio() < max_similarity else max_similarity min_similarity = s.ratio() if s.ratio() > min_similarity else min_similarity group_minmax[index] = (1 - max_similarity, 1 - min_similarity) # gives max difference ratio and then min difference ratio return group_minmax Then you can find the respective averages like this: >>> t = open('test.txt') >>> maxmin_ratios = find_maxmin_ratios(t) >>> maxmin_ratios {'1': (0, 0.0), '0': (0, 0.0), '2': (0, 0.0)} # again, no differences in your test data >>> average_max = sum([maxmin[0] for maxmin in maxmin_ratios.values()])/float(len(maxmin_ratios)) >>> average_min = sum([maxmin[1] for maxmin in maxmin_ratios.values()])/float(len(maxmin_ratios)) >>> average_max, average_min (0.0, 0.0) # no differences in your test data **Edit 3: Optimization Concerns** Finally, in light of your last comment, I'm not sure if you will be able to optimize this function too much in its present form. If your computer can't handle it, you may need to process smaller chunks of text and then compile the results at the end. `difflib` doesn't require huge amounts of memory, but it DOES do a LOT of work. Your performance SHOULD be a lot better than mine (depending on your machine) because every line of mine was random. If your lines are more similar than dissimilar, you should do a lot better. Here are the results of cProfile on my machine for the following scenario (3.172 hours total): text2.txt - 9700 lines of text - each line begins with one random number (1 to 10) - each line has 400 random characters that follow the random number # if your data is not random, you should do CONSIDERABLY better than this Note that the majority of the cumtime (the total time for a given function and all functions below it) was spent in difflib, which is outside of your control with the present function. In fact, the rest of the function takes very little time at all. 4581938093 function calls in 11422.852 seconds Ordered by: tottime # the total time spent in a given function, excluding time spent in subfunctions ncalls tottime percall cumtime percall filename:lineno(function) 81770876 8579.568 0 9919.636 0 difflib.py:350(find_longest_match) -724102230 1268.238 0 1268.238 0 {method 'get' of 'dict' objects} 4700900 874.878 0 1143.419 0 difflib.py:306(__chain_b) 9401960 160.366 0 10183.511 0.001 difflib.py:460(get_matching_blocks) 2060343126 141.242 0 141.242 0 {method 'append' of 'list' objects} 1889761800 110.013 0 110.013 0 {method 'setdefault' of 'dict' objects} 81770876 32.433 0 55.41 0 <string>:8(__new__) 130877001 32.061 0 32.061 0 {built-in method __new__ of type object at 0x1E228030} 81770876 29.773 0 29.773 0 {method 'pop' of 'list' objects} 1 23.259 23.259 11422.852 11422.852 <pyshell#50>:1(find_maxmin_ratios) 49106125 21.45 0 33.218 0 <string>:12(_make) 9401960 20.539 0 10239.234 0.001 difflib.py:636(ratio) 335752019 17.719 0 17.719 0 {len} 9401960 17.607 0 30.829 0 {_functools.reduce} 4700900 16.778 0 49.996 0 {map} 230344786 16.42 0 16.42 0 {method __contains__' of 'set' objects} 191093877 14.962 0 14.962 0 {method 'add' of 'set' objects} 98214517 13.222 0 13.222 0 difflib.py:658(<lambda>) 4700900 6.428 0 6.428 0 {method 'sort' of 'list' objects} 4700900 5.794 0 5.794 0 {method 'items' of 'dict' objects} 4700900 5.339 0 1148.758 0 difflib.py:261(set_seq2) 4700900 4.333 0 1160.351 0 difflib.py:154(__init__) 4700900 3.83 0 1156.018 0 difflib.py:223(set_seqs) 4700900 3.43 0 3.43 0 difflib.py:235(set_seq1) 9401960 3.162 0 3.162 0 difflib.py:41(_calculate_ratio) 9700 0.003 0 0.003 0 {method 'strip' of 'str' objects} 1 0.003 0.003 0.003 0.003 {sorted} 9700 0.001 0 0.001 0 <pyshell#50>:3(<lambda>) 1 0 0 11422.852 11422.852 <string>:1(<module>) 1 0 0 0 0 {method 'disable' of '_lsprof.Profiler' objects} If your machine can handle it, I would just run this function and be prepared to wait two or three hours. A LOT is happening here in order to compare these strings character-by-character.
Python - step through list -TypeError: 'int' object is not iterable Question: Trying to learn python, I am trying to do: list0=['A','B']; list1=['C','D']; z=0 while z < 2: for q in list(z): print q z += 1 I would like it to print A B C D but i get the following error: Traceback (most recent call last): File "main.py", line 6, in for q in list(z): TypeError: 'int' object is not iterable Is this possible in python? I know I have done this or something similar in other languages. Answer: 1. You can gather both the lists as another list and then you can index it like this list0=['A','B'] # We don't need semicolons list1=['C','D'] lists=[list0, list1] # Create a list of lists z=0 while z < 2: for q in lists[z]: # We access list's index with [], not with () print q z += 1 **Output** A B C D 2. The same effect can be achieved like this for current_list in [list0, list1]: for current_item in current_list: print current_item 3. There is a builtin python module, which comes with a [`itertools.chain`](http://docs.python.org/2/library/itertools.html#itertools.chain) method, which can be used like this import itertools for current_item in itertools.chain(list0, list1): print current_item
Error while installing Fabric on OSX using recommended pip. Xcode is latest version Question: I just tried to install Fabric on my Mac, and I was thrown this error after using `pip install fabric` Installing collected packages: fabric, paramiko, pycrypto, ecdsa Cleaning up... Exception: Traceback (most recent call last): File "/Library/Python/2.7/site-packages/pip-1.5-py2.7.egg/pip/basecommand.py", line 122, in main status = self.run(options, args) File "/Library/Python/2.7/site-packages/pip-1.5-py2.7.egg/pip/commands/install.py", line 275, in run requirement_set.install(install_options, global_options, root=options.root_path) File "/Library/Python/2.7/site-packages/pip-1.5-py2.7.egg/pip/req.py", line 1371, in install requirement.install(install_options, global_options, *args, **kwargs) File "/Library/Python/2.7/site-packages/pip-1.5-py2.7.egg/pip/req.py", line 655, in install self.move_wheel_files(self.source_dir, root=root) File "/Library/Python/2.7/site-packages/pip-1.5-py2.7.egg/pip/req.py", line 885, in move_wheel_files pycompile=self.pycompile, File "/Library/Python/2.7/site-packages/pip-1.5-py2.7.egg/pip/wheel.py", line 209, in move_wheel_files clobber(source, lib_dir, True) File "/Library/Python/2.7/site-packages/pip-1.5-py2.7.egg/pip/wheel.py", line 196, in clobber os.makedirs(destsubdir) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 157, in makedirs mkdir(name, mode) OSError: [Errno 13] Permission denied: '/Library/Python/2.7/site-packages/fabfile' Storing debug log for failure in /Users/michaelsnowden/Library/Logs/pip.log Here is the entire [debug log](https://gist.github.com/doctordoder/8501645) What does this mean, and why am I getting this error? Answer: For a system wide pip install you need to do a sudo: sudo pip install fabric Since the system wide packages are available globally, they are written outside paths that have write permission for a normal user. In that case you need to do a sudo other permission to write to those folders would be denied to you. When installed globally, you can invoke the Python interpreter anywhere in your system and `import fabric` would be available to you. Also, it would be available to any user of your system.
Flask - run function every hour Question: I have a Flask web hosting with no access to `cron` command. How can I execute some Python function every hour? Answer: You could make use of [`APScheduler`](http://pythonhosted.org/APScheduler/) in your Flask application and run your jobs via its interface: import atexit from apscheduler.scheduler import Scheduler from flask import Flask app = Flask(__name__) cron = Scheduler(daemon=True) # Explicitly kick off the background thread cron.start() @cron.interval_schedule(hours=1) def job_function(): # Do your work here # Shutdown your cron thread if the web process is stopped atexit.register(lambda: cron.shutdown(wait=False)) if __name__ == '__main__': app.run()
Python. Is it possible to print without using the print function? Question: I wondered whether it is possible to print (for example a string) in python without the print command. This can be done by a command or by some trick. For example, in C there are printf and puts. Can someone show me a way to print or to deny this possibility? **EDIT** I know about sys.stdout.write(). I also read the documentation. I just wanted to know whether there is another way to print, and without using import. I didn't find such a way, and could not find whether there is another way for printing. Answer: sys.stdout.write("hello world\n")
Left factoring using Python Question: Is there any predefined function in Python to identify the common prefixes on the right side of a production rule? For example, I need to turn this sort of data structure: ['abc', 'ab', 'd', 'dc'] into a dictionary of prefix-to-corresponding suffixes pairs. So my output for this example should look something like this: {'ab': set(['c', '']), 'd': set(['c', ''])} # ab is a common prefix and d is a common prefix In more general terms, I need to convert this sort of input: S -> abc|ab|d|dc into this sort of output: S -> abA|dA # prefixes ab and d followed by A A -> c|NULL # where A is either c or an equivalent of None I want to use this output to perform left factoring of a grammar. Answer: Another solution, let me know if that works: from itertools import takewhile,izip def groupby(ls): d = {} ls = [ y[0] for y in x ] initial = list(set(ls)) for y in initial: for i in x: if i.startswith(y): if y not in d: d[y] = [] d[y].append(i) return d def prefix(x): return len(set(x)) == 1 x=['abc','ab','d','dc'] for k, l in groupby(x).iteritems(): r = [l[0] for l in takewhile(prefix ,izip(*l))] print ''.join(r) Output: ab d
reading data from stackoverflow rest api Question: Playing around with the raspberry pi and python. so bear with me :) When trying to decode the response data from the stackoverflow api I keep on receiving the error `utf-8 codec can't decode byte 0x8b in position 1: invalid start byte` Here is the entire code that I have hacked up at the moment import http.client import json import zlib c = http.client.HTTPConnection('api.stackoverflow.com') c.request('GET', '/1.1/questions?answers=true&page=1&pagesize=5&tagged=sql') r = c.getresponse() compressedData = r.read() uncompressedData= zlib.decompress(compressedData, 15+32) data = str(compressedData, 'utf-8') print(data) But the response data is encoded in utf-8 format? Not quite sure why this is happening... Answer: Your code looks fine but... data = str(compressedData, 'utf-8') you're trying to decode the _compressed_ data. Try decoding the uncompressed data :-)
Virtualenv doesn't install pip Question: I have installed `python3` via homebrew, updated `pip` & `setuptools`, installed `virtualenv` via `pip`. Now I'm trying to create a virtual env. Unfortunately, I can't get it to add pip to the virtualenv. Basically: $ ls -lha venv/bin/ total 80 drwxr-xr-x 9 foghin staff 306B Jan 19 17:16 . drwxr-xr-x 6 foghin staff 204B Jan 19 17:16 .. -rw-r--r-- 1 foghin staff 2.2K Jan 19 17:16 activate -rw-r--r-- 1 foghin staff 1.2K Jan 19 17:16 activate.csh -rw-r--r-- 1 foghin staff 2.4K Jan 19 17:16 activate.fish -rw-r--r-- 1 foghin staff 1.1K Jan 19 17:16 activate_this.py lrwxr-xr-x 1 foghin staff 7B Jan 19 17:16 python -> python3 -rwxr-xr-x 1 foghin staff 13K Jan 19 17:16 python3 lrwxr-xr-x 1 foghin staff 7B Jan 19 17:16 python3.3 -> python3 AFAIK `pip` is supposed to be there as well. Creating the virtual env with high verbosity yields this: Installing setuptools, pip... Running command /Users/foghin/code/tastekid/venv/bin/python3 -c "import sys, pip; pip...ll\"] + sys.argv[1:])" setuptools pip Ignoring indexes: https://pypi.python.org/simple/ Requirement already satisfied (use --upgrade to upgrade): setuptools in /usr/local/lib/python3.3/site-packages Requirement already satisfied (use --upgrade to upgrade): pip in /usr/local/lib/python3.3/site-packages Cleaning up... ...Installing setuptools, pip...done. This means that all the packages I install while the virtual env is activated go to my global site packages (`/usr/local/lib/python3.3/site-packages`), but they are not picked up by the sandboxed python. How can I get `virtualenv` to properly install pip in my local environment? **Update:** virtualenv version is 1.11. Answer: As of this writing, Homebrew installs Python 3.3.3 (`$ brew info python3`). And as of Python 3.3, Python's standard library now includes its own virtual environment implementation, and does not require the virtualenv package. See the [`venv` module documentation](http://docs.python.org/3/library/venv.html). With the Homebrew Python 3 package, the command-line tool is named `pyvenv-3.3`. I believe using this implementation should resolve the issues you're encountering.
Python - alternating lists Question: I have two lists in python: l = [1,1,1,1,1,1] b = ['-', 2, 2, 2, '-', 2] In the end, I'd like to have a list like this: result = [1, 1, 2, 1, 2, 1, 2, 1, 1, 2] Algorithm: If there is a '-' in b, do nothing, else append element from b after element in l at same index (Second 2 from b should go after second 1 in l). How can I do this? for idx, i2 in enumerate(b): if i2 != '-' and count == 1: l.insert(prev+2,i2) prev = prev+2 print "in if1" print l print prev elif i2 != '-' and count == 0: l.insert(idx+1,i2) prev = idx+2 count = 1 print "in if2" print l print prev Answer: l, b = [1,1,1,1,1,1], ['-', 2, 2, 2, '-', 2] print [item for items in zip(l, b) for item in items if item != '-'] **Output** [1, 1, 2, 1, 2, 1, 2, 1, 1, 2] If the number of elements in either of the lists is not going to be equal to the other, you can use [`itertools.izip_longest`](http://docs.python.org/2/library/itertools.html#itertools.izip_longest) like this l, b = [1,1,1,1,1,1], ['-', 2, 2, 2, '-', 2, 2, 2] from itertools import izip_longest print [e for items in izip_longest(l,b) for e in items if e != None and e != '-'] **Output** [1, 1, 2, 1, 2, 1, 2, 1, 1, 2, 2, 2]
Python alternative to fscanf C code Question: I have some C code that works well: #include<stdio.h> #include<stdlib.h> int main() { FILE *fp; struct emp { char name[40]; int age; float bs; }; struct emp e; fp=fopen("EMPLOYEE.DAT","r"); if(fp==NULL) { puts("Cannot open file"; exit(1); } while(fscanf(f,"%s %d %f",&e.name,&e.age,&e.bs)!=EOF) printf("%s %d %f\n",e.name,e.age,e.bs); fclose(fp); return 0; } data inside `EMPLOYEE.DAT`: Sunil 34 1250.50 Sameer 21 1300.50 rahul 34 1400.50 I'm having trouble translating this code to Python: while(fscanf(f,"%s %d %f",&e.name,&e.age,&e.bs)!=EOF) printf("%s %d %f\n",e.name,e.age,e.bs); Is there any way to implement that in Python? Furthermore, what are Pythonic alternatives of `exit()` & `EOF`? Answer: Something like: with open("EMPLOYEE.DAT") as f: # open the file for reading for line in f: # iterate over each line name, age, bs = line.split() # split it by whitespace age = int(age) # convert age from string to int bs = float(bs) # convert bs from string to float print(name, age, bs) If you want to store the data in a structure, you can use the builtin `dict` type (hash map) person = {'name': name, 'age': age, 'bs': bs} person['name'] # access data Or you could define your own class: class Employee(object): def __init__(self, name, age, bs): self.name = name self.age = age self.bs = bs e = Employee(name, age, bs) # create an instance e.name # access data **EDIT** Here's a version that handles the error if the file does not exist. And returns an `exit` code. import sys try: with open("EMPLOYEE.DAT") as f: for line in f: name, age, bs = line.split() age = int(age) bs = float(bs) print(name, age, bs) except IOError: print("Cannot open file") sys.exit(1)
Examples given in the Python BeautifulSoup 4 Documentation Question: I am learning the BeautifulSoup 4 Documentation, and want to exercise the examples given. I am trying the examples however it’s not successful. An example below. Seems I am not putting it in a right way, and problem lies in the ‘url’. Could some kindness showing me the right way to put them? Thanks. from bs4 import BeautifulSoup import re import urllib2 url = '<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>' page = urllib2.urlopen(url) soup = BeautifulSoup(page.read()) Learning = soup.find_all("a", class_="sister") print Learning Answer: `'<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>'` is not an url. The code contains html; You don't need to use `urllib2.urlopen`. from bs4 import BeautifulSoup page = '<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>' soup = BeautifulSoup(page) Learning = soup.find_all("a", class_="sister") print Learning
Bottle Displays Old Template? Question: I made a first draft of a template, called `batch.tpl`. I have updated it, however, the old template still displays. I have shut off the controller script and turned it back on multiple times. I have removed everything from the template except for the following: `cat views/batch.tpl` <HTML> <HEAD> <TITLE> Batch Manager </TITLE> </HEAD> <BODY> THIS ISN'T DISPLAYING IN BROWSER </BODY> </HTML> Yet that will not show, just the old template. Here is my controller: `cat brew_bottle.py` from bottle import route, run, template, debug, post, request import MySQLdb import pymongo from datetime import datetime, timedelta import datetime @route('/batch') def batch(): con = MySQLdb.connect('localhost', 'root', 'pi', 'brew') cursor = con.cursor() batch_sql = "SELECT name, material, start_date, active, end_begin_date, end_end_date, min_temp, max_temp FROM batch WHERE active='Y'" cursor.execute(batch_sql) batches = cursor.fetchall() return template('batch', batches=batches) #... debug(True) run(host='0.0.0.0', port='8080', reloader=True) However, when I go to `http://<hostname>:8080/batch`, I see the old template that I had wrote: ![enter image description here](http://i.stack.imgur.com/OVNpR.png) I am sure I am missing something easy. What is it? I created a new directory and moved everything to it. Then when I start the python script, I am able to see the correct page. But the python script in the old directory displays the old template? Answer: According to the [Bottle docs](http://bottlepy.org/docs/dev/tutorial.html#auto-reloading), auto reloading (`reloading`) is only triggered by changes to module files. > Changes in template files will not trigger a reload. Please use debug mode > to deactivate template caching. Turn on [Bottle's debug mode](http://bottlepy.org/docs/dev/tutorial.html#debug-mode) this way: bottle.debug(True) > Here is an incomplete list of things that change in debug mode: > > The default error page shows a traceback. Templates are not cached. Plugins > are applied immediately. Just make sure not to use the debug mode on a > production server. * * * N.B., I see that someone already asked you whether restarting the server caused the updated template to appear, and that you indicated that it did not. That's highly suspicious. In any case, try fixing the problem above and see whether that solves your problem. Good luck!
Writing and reading variables in a file in Python Question: I am new to the Python language and I am scratching my head on how to make my code create a file where it can define variables and then later read the variables so they are useable in my code. How would I do this? Thanks, Chandler. Answer: [You can use the pickle module to accomplish this.](http://docs.python.org/2/library/pickle.html#example) import pickle Here's some sample data: key_value_mapping = dict(tuple=(), string='', list=[], int=0, set=set()) Provide a path that you want the file to exist at, e.g.: file_location= '/temp/foobar' We need to open a file to write (w) as a binary (b) file (see the `'wb'` flags being passed to the open function). These two lines demonstrate how to do this: with open(file_location, 'wb') as file: pickle.dump(key_value_mapping, file) Finally, we need to open the file to read (r) it as a binary (b) file, and retrieve the data: with open(file_location, 'rb') as file: data = pickle.load(file) print(data) {'tuple': (), 'set': set(), 'int': 0, 'list': [], 'string': ''}
Python dicerolling program skipping the roll Question: I have been trying to create a program that will simulate a dice roll, with the option to choose between a 4, 6, or 12 sided die. At the moment the problem I am having is that the program skips the rolling entirely no matter what option I choose and immediately asks me if I want to roll again. Im using Portable Python 3.2.1.1 to create the code. This is what I have so far: #!/usr/bin/env python import random def fourdie(): min = 1 max = 4 print (random.randint(min, max)); return; def sixdie(): min = 1 max = 6 print (random.randint(min, max)); return; def twelvedie(): min = 1 max = 12 print (random.randint(min, max)); return; roll = "yes" y = 1 while roll == "yes" or roll == "y": x = raw_input("What die do you want to roll? 4, 6 or 12?"); if x == 4: print (fourdie()); elif x == 6: print (sixdie()); elif x == 12: print (twelvedie()); else: print = "Sorry, I dont appear to have that dice type"; roll = raw_input("Do you want to roll again?"); Any help would be appreciated. Thank you for your time! Answer: `input` function returns a string. You can convert this string to int and then compare it to 4, 6, or 12: x = int(input("What die do you want to roll? 4, 6 or 12?")) if x == 4: // whatever elif x == 6: // whatever Or you can compare `x` directly to a string: x = input("... whatever ...") if x == "4": // whatever elif x == "6": // whatever And one other thing: there is no need to end lines with the semicolon in python. Makes Guido van Rossum happy.
Sending string via socket (python) Question: I have two scripts, Server.py and Client.py. I have two objectives in mind: 1. To be able to send data again and again to server from client. 2. To be able to send data from Server to client. here is my Server.py : import socket serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) host = "192.168.1.3" port = 8000 print (host) print (port) serversocket.bind((host, port)) serversocket.listen(5) print ('server started and listening') while 1: (clientsocket, address) = serversocket.accept() print ("connection found!") data = clientsocket.recv(1024).decode() print (data) r='REceieve' clientsocket.send(r.encode()) and here is my client : #! /usr/bin/python3 import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) host ="192.168.1.3" port =8000 s.connect((host,port)) def ts(str): s.send('e'.encode()) data = '' data = s.recv(1024).decode() print (data) while 2: r = input('enter') ts(s) s.close () The function works for the first time ('e' goes to the server and I get return message back), but how do I make it happen over and over again (something like a chat application) ? The problem starts after the first time. The messages don't go after the first time. what am I doing wrong? I am new with python, so please be a little elaborate, and if you can, please give the source code of the whole thing. Answer: import socket from threading import * serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) host = "192.168.1.3" port = 8000 print (host) print (port) serversocket.bind((host, port)) class client(Thread): def __init__(self, socket, address): Thread.__init__(self) self.sock = socket self.addr = address self.start() def run(self): while 1: print('Client sent:', self.sock.recv(1024).decode()) self.sock.send(b'Oi you sent something to me') serversocket.listen(5) print ('server started and listening') while 1: clientsocket, address = serversocket.accept() client(clientsocket, address) This is a very VERY simple design for how you could solve it. First of all, you need to either accept the client (server side) before going into your `while 1` loop because in every loop you accept a new client, or you do as i describe, you toss the client into a separate thread which you handle on his own from now on.
LoginUser API access from Python Question: Is there a way to call the following method from Python? <http://msdn.microsoft.com/en- us/library/windows/desktop/aa378184(v=vs.85).aspx> Any help would be greatly appreciated. Answer: You may use [ctypes](http://docs.python.org/2/library/ctypes.html). This example seems to work (Python 2.7): from ctypes import * from ctypes.wintypes import HANDLE # Example use of WinAPI windll.user32.MessageBoxW(None, u"Example", u"Example", 0) x = HANDLE() print windll.advapi32.LogonUserW(u"Tupteq", None, u"passwd", 4, 0, pointer(x)) print windll.kernel32.GetLastError() print x In my case `GetLastError()` returned `1326` in case of bad password and `1327` when password was correct. You may need to adjust values of `dwLogonType` and `dwLogonProvider`.
Wrap derived template class with Boost::python Question: I have a derived class from a template class : template<typename X, typename Y> class BaseFunction { static void export_BaseFunction() { ????? }; }; class Function : public BaseFunction<pair<double, double>, double> { Function() : BaseFunction<pair<double, double>, double>() {}; static void export_Function() { BaseFunction::export_BaseFunction(); boost::python::class_<Function, boost::python::bases<BaseFunction<pair<double, double>, double>>, boost::shared_ptr<Function>>("Function"); } }; So Boost::Python asks me to create a class wrapper for BaseFunction but I don't find any information to write a template class, only template function... Have I to define a class wrapper for each base class ? Have I to define a class wrapper for each type used into my template class ? Thank you for your helpful answers Answer: The `RuntimeError` occurs because a requirement for the [`class_`](http://www.boost.org/doc/libs/1_55_0/libs/python/doc/v2/class.html#class_- spec)'s `Bases` template parameter is not being met: > A specialization of `bases<...>` which specifies previously-exposed C++ base > classes of `T` With previously-exposed being [explained](http://www.boost.org/doc/libs/1_55_0/libs/python/doc/v2/class.html#footnote_1) as: namespace python = boost::python; python::class_<Base>("Base"); python::class_<Derived, python::bases<Base> >("Derived"); To resolve the `RuntimeError`, either: * Omit the `bases` information if the exposed API does not need to perform upcasting or downcasting with `Function` and `BaseFunction<...>`. For example, if none of the C++ functions exposed to Python have a parameter type of `BaseFunction<...>` or return a `Function` object as a `BaseFunction<...>&`, then Boost.Python does not need to know about type relationship. * Otherwise, the base class needs to be exposed and `Function` needs to expose the relationship: namespace python = boost::python; typedef BaseFunction<pair<double, double>, double> function_base_type; python::class_<function_base_type>("Base"); python::class_<Function, python::bases<function_base_type> >("Function"); When registering the specific type instance of `BaseFunction`, the string identifier needs to be unique. * * * Below is a complete example that has `Function` expose `BaseFunction`. The `export_BaseFunction()` function will check if it has already been registered to prevent warning about duplicated conversions, and will use C++ type information name to disambiguate between different template instantiations of `BaseFunction`. #include <utility> // std::pair #include <typeinfo> // typeid #include <boost/python.hpp> template<typename X, typename Y> class BaseFunction { public: static void export_BaseFunction() { // If type is already registered, then return early. namespace python = boost::python; bool is_registered = (0 != python::converter::registry::query( python::type_id<BaseFunction>())->to_python_target_type()); if (is_registered) return; // Otherwise, register the type as an internal type. std::string type_name = std::string("_") + typeid(BaseFunction).name(); python::class_<BaseFunction>(type_name.c_str(), python::no_init); }; }; class Function : public BaseFunction<std::pair<double, double>, double> { private: typedef BaseFunction<std::pair<double, double>, double> parent_type; public: static void export_Function() { // Explicitly register parent. parent_type::export_BaseFunction(); // Expose this type and its relationship with parent. boost::python::class_<Function, boost::python::bases<parent_type>, boost::shared_ptr<Function> >("Function"); } }; /// @brief Example function to demonstrate upcasting. void spam(BaseFunction<std::pair<double, double>, double>&) {} BOOST_PYTHON_MODULE(example) { Function::export_Function(); boost::python::def("spam", &spam); } Interactive usage: >>> import example >>> f = example.Function() >>> f <example.Function object at 0xb7ec5464> >>> example.spam(f)
Using 'exec' function to run script in the interpreter shell Question: I try to run a script in Python3 by exec() function. I'm studying Python with the book 'Learning Python', O'Reilly 5th Edition. In the "CHAPTER 2 How Python Runs Programs" there is a method to like this: >>> exec(open('script1.py').read()) This is my file script1.py # A first script in python. import sys print(sys.platform) print(2 **100) x = 'Spam!' print(x * 8) input() The expectec output is: win32 1267650600228229401496703205376 Spam!Spam!Spam!Spam!Spam!Spam!Spam!Spam! In the work I only can use WinXP :-( But the real output in Python3 is: >>> exec(open('script1.py').read()) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<string>", line 1 # A first script in python. ^ SyntaxError: invalid character in identifier >>> And the output in Python2 is: >>> exec(open('script1.py').read()) win32 1267650600228229401496703205376 Spam!Spam!Spam!Spam!Spam!Spam!Spam!Spam! Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<string>", line 7, in <module> File "<string>", line 0 ^ SyntaxError: unexpected EOF while parsing >>> I don't understand why that isn't working like the book says. Answer: The problem is in your editor, that adds an ''incorrect symbol'' (actually, the symbol is correct per se) at the beginning of the file. Please check it. If you want to check this conjecture, please do print open('script1.py').read(1) in the python repl. It is probably BOM in the file (thanks @devnull). If it is so, you can open the file with encondig `utf-8-sig`: open('script1.py', encoding='utf-8-sig') More on that you can read here: * [Reading Unicode file data with BOM chars in Python](http://stackoverflow.com/questions/13590749/reading-unicode-file-data-with-bom-chars-in-python) What is BOM (Byte Order Mark), you can find here: * <http://en.wikipedia.org/wiki/Byte_order_mark> And of course, you must avoid BOMs in your scripts in the future. Please check settings of your editor, and make sure it doesn't create BOMs when saving scripts.
Is there a way to implement **kwargs behavior when calling a Python script from the command line Question: Say I have a function as follows: def foo(**kwargs): print kwargs And then call the function like this, I get this handy little dict of all `kwargs`. >>> foo(a = 5, b = 7) {'a': 5, 'b': 7} I want to do this directly to scripts I call from command line. So entering this: python script.py a = 5 b = 7 Would create a similar dict to the example above. Can this be done? **Here's what I have so far:** import sys kwargs_raw = sys.argv[1:] kwargs = {key:val for key, val in zip(kwargs_raw[::3], kwargs_raw[1::3])} print kwargs And here's what this produces: Y:\...\Python>python test.py a = 5 b = 7 {'a': '5', 'b': '7'} So you may be wondering why this isn't good enough 1. Its very structured, and thus, won't work if `a` or `b` are anything other that strings, ints, or floats. 2. I have no way of determining if the user intended to have 5 be an int, string, or float I've seen `ast.literal_eval()` around here before, but I couldn't figure out how to get that to work. Both my attempts failed: >>> ast.literal_eval("a = 5") Traceback (most recent call last): File "<stdin>", line 1, in <module> File "Y:\admin\Anaconda\lib\ast.py", line 49, in literal_eval node_or_string = parse(node_or_string, mode='eval') File "Y:\admin\Anaconda\lib\ast.py", line 37, in parse return compile(source, filename, mode, PyCF_ONLY_AST) File "<unknown>", line 1 a = 5 and >>> ast.literal_eval("{a:5,b:7}") Traceback (most recent call last): File "<stdin>", line 1, in <module> File "Y:\admin\Anaconda\lib\ast.py", line 80, in literal_eval return _convert(node_or_string) File "Y:\admin\Anaconda\lib\ast.py", line 63, in _convert in zip(node.keys, node.values)) File "Y:\admin\Anaconda\lib\ast.py", line 62, in <genexpr> return dict((_convert(k), _convert(v)) for k, v File "Y:\admin\Anaconda\lib\ast.py", line 79, in _convert raise ValueError('malformed string') ValueError: malformed string If it matters, I'm using Python 2.7.6 32-bit on Windows 7 64-bit. Thanks in advance Answer: It seems what you're _really_ looking for is a way to parse command-line arguments. Take a look at the `argparse` module: <http://docs.python.org/2/library/argparse.html#module-argparse> Alternately, if you really want to give your arguments in dictionary-ish form, just use the `json` module: import json, sys # Run your program as: # python my_prog.py "{'foo': 1, 'bar': 2}" # (the quotes are important) data = json.loads(sys.argv[1])
Django NoReverseMatch Question: I'm making a simple login app in django 1.6 (and python 2.7) and I get an error at the beggining that is not letting me continue. This is the site's url.py from django.conf.urls import patterns, include, url from django.contrib import admin import login admin.autodiscover() urlpatterns = patterns('', url(r'^$', include('login.urls', namespace='login')), url(r'^admin/', include(admin.site.urls)), ) And this is login/urls.py: from django.conf.urls import patterns, url from login import views urlpatterns = patterns('', url(r'^$', views.index, name='index'), url(r'^auth/', views.auth, name='auth'), ) This is login/views,py from django.shortcuts import render from django.contrib.auth import authenticate def auth(request): user = authenticate(username=request.POST['username'], password=request.POST['password']) if user is not None: # the password verified for the user if user.is_active: msg = "User is valid, active and authenticated" else: msg = "The password is valid, but the account has been disabled!" else: # the authentication system was unable to verify the username and password msg = "The username and password were incorrect." return render(request, 'login/authenticate.html', {'MESSAGE': msg}) def index(request): return render(request, 'login/login_form.html') I have a form that has this as action: {% url 'login:auth' %} And that's where the problem is, when I try to load the page, I get: Reverse for 'auth' with arguments '()' and keyword arguments '{}' not found. 1 pattern(s) tried: [u'$auth/'] But if I set the url pattern to url(r'', views.auth, name='auth') it works fine, only it sets the action as '/'. I've been looking all around for an answer and I don't understand why it doesn't work. I tried changing the login url pattern to url(r'^login/$', include('login.urls', namespace='login')), and it didn't change anything. Answer: The problem is in the way you include the auth URLs in the main one. Because you use both ^ and $, only the empty string matches. Drop the $.
Passing values to array indexes in Python Question: Is there any way to assign values to keys in array in Python? Example in PHP: $inputArr = array( 'vertex'=>values[0], 'visited'=>values[1], 'letter' => $values[2] ) This is the way i tried to do in Python: file_name = input('Enter a file name: ') f = open(file_name, 'r') data = f.readlines() //Read the lines for line in data: values = line.split(' ') Split line following the spaces inputArr = array( 'vertex'=>values[0], //Pass each value to a key in that array 'visited'=>values[1], 'letter' => $values[2] ) print (inputArr) Answer: You want to use [`dict`s](http://docs.python.org/2/library/stdtypes.html#dict): array = { 'vertex': values[0], 'visited': values[1], 'letter': values[2], } # access via array['vertex'] Note however that this does **not** preserve the order. Iterating over the dictionary can produce an arbitrary order. There is an [`OrderedDict`](http://docs.python.org/2/library/collections.html#collections.OrderedDict) class in recent versions of python, however keep in mind that it takes more than twice as much memory as a plain `dict`. If your array is fixed, and only has those 3 elements, it might be better to use a [`namedtuple`](http://docs.python.org/2/library/collections.html#collections.namedtuple): from collections import namedtuple NamedSeq = namedtuple('NamedSeq', ('vertex', 'visited', 'letter')) array = NamedSeq(values[0], values[1], values[2]) #or array = NamedSeq(vertex=values[0], letter=values[2], visited=values[1]) This preserves the order and you can access `vertex` via `array.vertex` etc. Or you can access the data using `array[0]` for the value of `vertex`, `array[1]` for the `visited` etc. Note that however that `namedtuple`s are _immutable_ , i.e. you cannot modify them.
UWSGI timer and cron decorators running duplicate jobs Question: I have been trying to make the uwsgi python spooler work properly for quite some time. I have a setup in which I run a django application with two worker processes. I have tried setting a cron spooler (and a timer spooler) to run a task every ten minutes, but no matter what configuration of settings I've tried, it always seems to register the signal multiple times, and running the task multiple times. This is how I run uwsgi: #!/bin/bash sudo uwsgi --emperor /etc/uwsgi/vassals --uid http --gid http --enable-threads --pidfile=/tmp/uwsgi.pid --daemonize=/var/log/uwsgi/uwsgi.log This is my uwsgi vassal config in /etc/uwsgi/vassals/django.ini: [uwsgi] chdir = /home/user/django module = django.wsgi master = true processes = 2 socket = /tmp/uwsgi-django.sock vacuum = true pidfile = /tmp/uwsgi-django.pid daemonize = /home/user/django/log.log env = DJANGO_SETTINGS_MODULE=django.settings #lazy-apps = false #lazy = false spooler = %(chdir)/tasks #spooler-processes = 1 #import = django-app/spooler.py #spooler-import = django-app/spooler.py shared-import = django-app/spooler.py (I have changed some of the path names for privacy reasons). The lines that are commented out are various attempts at making it not duplicate my signals, but every time it seems to register the signal twice, and sometimes even thrice (presumably in both the workers and the single spooler process). [uwsgi-signal] signum 0 registered (wid: 0 modifier1: 0 target: default, any worker) [uwsgi-signal] signum 1 registered (wid: 1 modifier1: 0 target: default, any worker) [uwsgi-signal] signum 1 registered (wid: 2 modifier1: 0 target: default, any worker) Does anyone know why this is happening, and how to properly prevent it? This is the spooler.py file: @cron(-10, -1, -1, -1, -1) def periodicUpdate(signal): print "Running cron job..." _getStats() also tried @timer(600) def periodicUpdate(signal): print "Running cron job..." _getStats() I also tried adding `target='spooler'` to the timer/cron-decorator, but it did not seem to many any difference. Answer: Are you sure you do not have other signals registered in django.wsgi, settings.py or other django-related file ? --shared-import will only load things one time (in the master). Btw i do not get what you are trying to accomplish. This is not how the spooler is supposed to work, and even if you want to use it as a signal handler target you have to specify it when you register signals (with target='spooler' in the decorator)
Cython with python 3.3 Question: I have been using python 3.3 This is an old problem as I searched, and this is what I did: helloworld.pyx print("Hello world!") Then, in ipython, I did: import pyximport; pyximport.install() import helloworld It says: > ImportError: Building module helloworld failed: ["ValueError: ['path']\n"] The same problem did not happen with python 2.7 I googled this: <https://github.com/cython/cython/wiki/64BitCythonExtensionsOnWindows> and realized that I have to install Windows SDK for Windows 7 and .NET Framework 4. As it comes with the VC++2010 Redistributables, I did not install the redistributables alone again. I thought I had everything ready, but the import error still remains. Could anyone please help me solve it? Thank you! -Shawn Answer: I was having the same issue and the same environment (win7 64bit, python-3.3.3 64bit). I have 1. installed the Windows 7 SDK as described on the wiki [cython wiki](https://github.com/cython/cython/wiki/64BitCythonExtensionsOnWindows) as you did, 2. applied the patch (`msvccompiler9_33.diff`) from this [python bug](http://bugs.python.org/issue7511), 3. fixed the above patch by defining a missing variable as described [here](http://bugs.python.org/msg196929) 4. Installed MS Visual C++ Express 2010 (seems to be required) 5. Updated the Windows 7 SDK to include the "Windows Headers and Libraries", "Tools" and of course the "Visual C++ Compilers" the MSVC++2010 redistributable. And now I can compile and import the `helloworld.py` just fine.
Why can't node handle this regex but python can? Question: I have a large text file that I am extracting URLs from. If I run: import re with open ('file.in', 'r') as fh: for match in re.findall(r'http://matchthis\.com', fh.read()): print match it runs in a second or so user time and gets the URLs I was wanting, but if I run either of these: var regex = /http:\/\/matchthis\.com/g; fs.readFile('file.in', 'ascii', function(err, data) { while(match = regex.exec(data)) console.log(match); }); OR fs.readFile('file.in', 'ascii', function(err, data) { var matches = data.match(/http:\/\/matchthis\.com/g); for (var i = 0; i < matches.length; ++i) { console.log(matches[i]); } }); I get: FATAL ERROR: CALL_AND_RETRY_0 Allocation failed - process out of memory What is happening with the `node.js` regex engine? Is there any way I can modify things such that they work in `node`? **EDIT:** The error appears to be `fs` centric as this also produces the error: fs.readFile('file.in', 'ascii', function(err, data) { }); `file.in` is around 800MB. Answer: You should process the file line by line using the streaming file interface. Something like this: var fs = require('fs'); var byline = require('byline'); var input = fs.createReadStream('tmp.txt'); var lines = input.pipe(byline.createStream()); lines.on('readable', function(){ var line = lines.read().toString('ascii'); var matches = line.match(/http:\/\/matchthis\.com/g); for (var i = 0; i < matches.length; ++i) { console.log(matches[i]); } }); In this example, I'm using the `byline` module to split the stream into lines so that you won't miss matches by getting partial chunks of lines per `.read()` call. To elaborate more, what you were doing is allocating ~800MB of RAM as a Buffer (outside of V8's heap) and then converting that to an ASCII string (and thus transferring it into V8's heap), which will take at least 800MB and likely more depending on V8's internal optimizations. I believe V8 stores strings as UCS2 or UTF16, which means each character will be 2 bytes (given ASCII input) so your string would really be about 1600MB. Node's max allocated heap space is 1.4GB, so by trying to create such a large string, you cause V8 to throw an exception. Python does not have this problem because it does not have a maximum heap size and will chew through all of your RAM. As others have pointed out, you should also avoid `fh.read()` in Python since that will copy all the file data into RAM as a string instead of streaming it line by line with an iterator.
Unable to import PIL.Image for qrcode Question: I run into this weird error, I need to use `qrcode` with `pillow`, so I did `pip install pillow qrcode` (after initiating the virtual environment). Then, the following thing happens >>> from PIL import Image >>> Image <module 'PIL.Image' from '/vagrant/env/local/lib/python2.7/site-packages/PIL/Image.pyc'> >>> import qrcode; >>> qrcode.make("1").show() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/vagrant/env/local/lib/python2.7/site-packages/qrcode/main.py", line 8, in make return qr.make_image() File "/vagrant/env/local/lib/python2.7/site-packages/qrcode/main.py", line 186, in make_image from qrcode.image.pil import PilImage File "/vagrant/env/local/lib/python2.7/site-packages/qrcode/image/pil.py", line 5, in <module> import Image ImportError: No module named Image `from PIL import Image` works but `qrcode` doesn't work. Not sure what is going on Answer: install PIL on Ubuntu: <http://askubuntu.com/questions/156484/how-do-i- install-python-imaging-library-pil> header for your program, code: ##some magic for 3rd party packages import site site.main() ##headers from PIL import Image ##programm #here your program!!! \-- Your friend!!!
Django + Boto + Python 3 Question: How can I store my Django uploaded files on S3 using Python 3 on EC2 Amazon Linux? If I can't, how can I share uploaded files between 2 EC2 instances if I'm using ELB? I tried to use the django-storages-py3 + boto#py3kport but it doesn't work, when I'm trying to upload files I get an exception: `string expected bytes given` UPDATE: This is how I'm using the django-storages-py3 + boto#py3kport from django.core.files.storage import default_storage fd = default_storage.open('%s/%s' % ('uploadstg', str(filename)), 'wb') for chunk in file.chunks(): fd.write(chunk) fd.close() fd - S3BotoStorageFile: uploadstg/a6d2532d-34c9-4793-9d43-e9a3e475fc6f.png file - InMemoryUploadedFile: 1.png (image/png) **Traceback** Environment: Request Method: POST Request URL: http://---/items/Tpp/create/ Django Version: 1.6.1 Python Version: 3.3.3 Installed Applications: ('django.contrib.admin', 'haystack', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'modeltranslation', 'south', 'core', 'storages', 'appl') Installed Middleware: ('django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'tpp.SiteUrlMiddleWare.SiteUrlMiddleWare') Traceback: File "/usr/local/bin/test/lib/python3.3/site-packages/django/core/handlers/base.py" in get_response 114. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/var/www/html/tpp/tppcenter/views.py" in get_item_form 95. com = form.save(request.user) File "/var/www/html/tpp/tppcenter/forms.py" in save 212. self._save_file(self.fields[title].initial, title, path_to_images) File "/var/www/html/tpp/tppcenter/forms.py" in _save_file 239. fd.write(chunk) File "/usr/local/bin/test/lib/python3.3/site-packages/django_storages-1.1.8-py3.3.egg/storages/backends/s3boto.py" in write 161. return super(S3BotoStorageFile, self).write(*args, **kwargs) Exception Type: TypeError at /items/Tpp/create/ Exception Value: string argument expected, got 'bytes' Upload using Django admin: Environment: Request Method: POST Request URL: http://----/admin/core/user/1/ Django Version: 1.6.1 Python Version: 3.3.3 Installed Applications: ('django.contrib.admin', 'haystack', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'modeltranslation', 'south', 'core', 'storages', 'appl') Installed Middleware: ('django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'tpp.SiteUrlMiddleWare.SiteUrlMiddleWare') Traceback: File "/usr/local/bin/test/lib/python3.3/site-packages/django/core/handlers/base.py" in get_response 114. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/bin/test/lib/python3.3/site-packages/django/contrib/admin/options.py" in wrapper 432. return self.admin_site.admin_view(view)(*args, **kwargs) File "/usr/local/bin/test/lib/python3.3/site-packages/django/utils/decorators.py" in _wrapped_view 99. response = view_func(request, *args, **kwargs) File "/usr/local/bin/test/lib/python3.3/site-packages/django/views/decorators/cache.py" in _wrapped_view_func 52. response = view_func(request, *args, **kwargs) File "/usr/local/bin/test/lib/python3.3/site-packages/django/contrib/admin/sites.py" in inner 198. return view(request, *args, **kwargs) File "/usr/local/bin/test/lib/python3.3/site-packages/django/utils/decorators.py" in _wrapper 29. return bound_func(*args, **kwargs) File "/usr/local/bin/test/lib/python3.3/site-packages/django/utils/decorators.py" in _wrapped_view 99. response = view_func(request, *args, **kwargs) File "/usr/local/bin/test/lib/python3.3/site-packages/django/utils/decorators.py" in bound_func 25. return func(self, *args2, **kwargs2) File "/usr/local/bin/test/lib/python3.3/site-packages/django/db/transaction.py" in inner 339. return func(*args, **kwargs) File "/usr/local/bin/test/lib/python3.3/site-packages/django/contrib/admin/options.py" in change_view 1230. self.save_model(request, new_object, form, True) File "/usr/local/bin/test/lib/python3.3/site-packages/django/contrib/admin/options.py" in save_model 860. obj.save() File "/usr/local/bin/test/lib/python3.3/site-packages/django/db/models/base.py" in save 545. force_update=force_update, update_fields=update_fields) File "/usr/local/bin/test/lib/python3.3/site-packages/django/db/models/base.py" in save_base 573. updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) File "/usr/local/bin/test/lib/python3.3/site-packages/django/db/models/base.py" in _save_table 632. for f in non_pks] File "/usr/local/bin/test/lib/python3.3/site-packages/django/db/models/base.py" in <listcomp> 632. for f in non_pks] File "/usr/local/bin/test/lib/python3.3/site-packages/django/db/models/fields/files.py" in pre_save 252. file.save(file.name, file, save=False) File "/usr/local/bin/test/lib/python3.3/site-packages/django/db/models/fields/files.py" in save 86. self.name = self.storage.save(name, content) File "/usr/local/bin/test/lib/python3.3/site-packages/django/core/files/storage.py" in save 49. name = self._save(name, content) File "/usr/local/bin/test/lib/python3.3/site-packages/django_storages-1.1.8-py3.3.egg/storages/backends/s3boto.py" in _save 392. self._save_content(key, content, headers=headers) File "/usr/local/bin/test/lib/python3.3/site-packages/django_storages-1.1.8-py3.3.egg/storages/backends/s3boto.py" in _save_content 403. rewind=True, **kwargs) File "/usr/local/bin/test/src/boto/build/lib/boto/s3/key.py" in set_contents_from_file 1241. chunked_transfer=chunked_transfer, size=size) File "/usr/local/bin/test/src/boto/build/lib/boto/s3/key.py" in send_file 726. chunked_transfer=chunked_transfer, size=size) File "/usr/local/bin/test/src/boto/build/lib/boto/s3/key.py" in _send_file_internal 893. if self.base64md5: File "/usr/local/bin/test/src/boto/build/lib/boto/s3/key.py" in _get_base64md5 177. return binascii.b2a_base64(self.local_hashes['md5']).rstrip('\n') Exception Type: TypeError at /admin/core/user/1/ Exception Value: Type str doesn't support the buffer API Answer: tinys3 - Quick and minimal S3 uploads for Python <https://github.com/smore- inc/tinys3>
How to get the field value and assign to the variable in python Question: I am using **openerp 6**.My `form` contains one `text box` and I need to get that value and assign it to a variable so to perform calculations and to return a result to store in a new `textbox`... Answer: I have give .py file here. This will calculate square of the number from osv import osv from osv import fields class test_base(osv.osv): _name='test.base' _columns={ 'first':fields.integer('Enter Number here'), 'result':fields.integer('Display calclation result'), } def first_change(self, cr, uid, ids,first,context=None): r=first*first return {'value':{'result':r}} test_base() xml file is given here <?xml version="1.0" encoding="utf-8"?> <openerp> <data> <record model="ir.ui.view" id="test_base_form"> <field name="name">test.base.form</field> <field name="model">test.base</field> <field name="type">form</field> <field name="arch" type="xml"> <form string="best Base"> <field name="first" on_change="first_change(first)"/> <field name="result"/> </form> </field> </record> <record model="ir.ui.view" id="test_base_tree"> <field name="name">test.base.tree</field> <field name="model">test.base</field> <field name="type">tree</field> <field name="arch" type="xml"> <tree string="Test Base"> <field name="first"/> <field name="result"/> </tree> </field> </record> <record model="ir.actions.act_window" id="action_test_seq"> <field name="name">Test Base</field> <field name="res_model">test.base</field> <field name="view_type">form</field> <field name="view_mode">form,tree</field> </record> <menuitem id="menu_test_base_main" name="Test Base"> </menuitem> <menuitem id="menu_test_base_sub" parent="menu_test_base_main" name="Square number" action="action_test_seq"> </menuitem> </data> </openerp>
shapely and geos break in distance method Question: I'm having problems using the distance method in shapely (I suspect incompatibility with the geos package). The following code: from shapely.geometry import Point print Point(0,0).distance(Point(1,1)) creates the following error: python: GeometryComponentFilter.cpp:34: virtual void geos::geom::GeometryComponentFilter::filter_ro(const geos::geom::Geometry*): Assertion `0' failed. Aborted (core dumped) I’m running CentOS 6, python 2.6, geos 3.4.2 (although it creates a link from libgeos_c to 1.8.2) Googling it yielded a few old posts which didn't really help me. Thanks, Raz Answer: This looks like a GEOS bug ([#535](http://trac.osgeo.org/geos/ticket/535)). As a work around, try fetching a development snapshot [that appears to solve this issue](http://trac.osgeo.org/geos/changeset/3960): svn co http://svn.osgeo.org/geos/trunk@3960 geos-svn cd geos-svn ./autogen.sh ./configure make make check If the last command throws any similar errors, consider contributing feedback to the bug report. But if all is good, then it should be good for shapely. As root: make install ldconfig
Python- How to check if program gets aborted by user while running? Question: If I am running a python program on linux terminal and i abort it manually by pressing ctrl+c, how can i make my program do something when this event occurs. something like: if sys.exit(): print "you chose to end the program" Answer: Well, you can use `KeyBoardInterrupt`, using a try-except block: try: # some code here except KeyboardInterrupt: print "You exited Try the following in your command line: import time try: while True: time.sleep(1) print "Hello" except KeyboardInterrupt: print "No more Hellos"
Struggling to append a relative path to my sys.path Question: So there are a lot of pretty similar questions but none of the answers seems to satisfy what I'm looking for. Essentially I am running a python script using an absolute directory in the command line. Within this file itself, I want to import a module/file,I currently use an absolute path to do this (`sys.path.append(/....)`. But I would like to use a relative path, relative to the script itself. All I seem to be able to do is append a path relative to my present working directory. How do I do this? Answer: **Example 1** main script: /some/path/foo/foo.py module to import: /some/path/foo/bar/sub/dir/mymodule.py Add in `foo.py` import sys, os sys.path.append(os.path.join(sys.path[0],'bar','sub','dir')) from mymodule import MyModule * * * **Example 2** main script: /some/path/work/foo/foo.py module to import: /some/path/work/bar/mymodule.py Add in `foo.py` import sys, os sys.path.append(os.path.join(os.path.dirname(sys.path[0]),'bar')) from mymodule import MyModule * * * **These two above examples should cover all use cases** * These two above examples apply to both Python versions 2 and 3 * `sys.path[0]` is `/some/path/foo` in the two examples * `os.path.join('a','b','c')` is more portable than `'a/b/c'` * `os.path.dirname(mydir)` is more portable than `os.path.join(mydir,'..')` See also documentation about importing modules: * in [Python 2](https://docs.python.org/2/tutorial/modules.html) * in [Python 3](https://docs.python.org/3/tutorial/modules.html)
subprocess.Popen("ssh host@remote cmd") failed Question: I'm new to python subprocess. When I want to use python subprocess.Popen.communicate to accomplish interact passwd with shell cmd "net ads join -U administrator", it's output didn't redirect into PIPE, but in stdout.My code is under: import subprocess import os import sys passwd = b'123456' cmd = "net ads join -U administrator" s1 = ("%s\n" % str(passwd)).encode('utf-8') p1 = subprocess.Popen(cmd1,shell=True,stdin=subprocess.PIPE,stdout=subprocess.PIPE, stderr=subprocess.PIPE,close_fds=True) out,err = p1.communicate(s1) print(out) When I run the test, communicate didn't work, the output still in the stdout. $ python ads.py Enter administrator's password: When I change the cmd to "ssh root@ip ls /", I also met with the problem. I tried pdb, but the problem seems not here. Any advise to deal with this problem? Thank You Answer: Here is a snippet class for SSH and run command remotely, that I used in one of my scripts, please let me know if that works, Here I am using python standard [PTY Module](http://docs.python.org/2/library/pty.html) for pseudo terminal. import pty import os import re class BaseError(Exception): pass class SSHError(BaseError): pass class Ssh: """SSH on the box""" def __init__(self, ip, passwd, user, port): self.ip = ip self.passwd = passwd self.user = user self.port = port def run_cmd(self, c): (pid, f) = pty.fork() if pid == 0: os.execlp( "ssh", "ssh", '-o ConnectTimeout=10', '-o StrictHostKeyChecking=no', '-o UserKnownHostsFile=/dev/null', '-q', '-p %d' % self.port, self.user + '@' + self.ip, c) else: return (pid, f) def run_scp(self, src, dst): (pid, f) = pty.fork() if pid == 0: os.execlp( "scp", "scp", '-o StrictHostKeyChecking=no', '-o UserKnownHostsFile=/dev/null', '-q', '-P %d' % self.port, "-r", src, self.user + '@' + self.ip + ':' + dst) else: return (pid, f) def read(self, f): x = "" try: x = os.read(f, 2024) except Exception: pass return x def sshOutputs(self, pid, f): output = "" readOutLoud = self.read(f) m = re.search("authenticity of host", readOutLoud) if m: os.write(f, 'yes\n') while True: readOutLoud = self.read(f) m = re.search("Permanently added", readOutLoud) if m: break readOutLoud = self.read(f) m = re.search("assword:", readOutLoud) if m: os.write(f, self.passwd + '\n') tmp = self.read(f) tmp += self.read(f) m = re.search("Permission denied", tmp) if m: raise SSHError("Invalid passwd") p = re.search("[pP]assword", tmp) if p: raise SSHError("Invalid passwd") # passwd was accepted readOutLoud = tmp while readOutLoud and len(readOutLoud) > 0: output += readOutLoud readOutLoud = self.read(f) os.waitpid(pid, 0) os.close(f) return output def exe_ssh_cmd(self, c): (pid, f) = self.run_cmd(c) return self.sshOutputs(pid, f) def exe_scp_cmd(self, src, dst): (pid, f) = self.run_scp(src, dst) return self.sshOutputs(pid, f)
Splitting string and removing whitespace Python Question: I would like to split a String by comma `','` and remove whitespace from the beginning and end of each split. For example, if I have the string: `"QVOD, Baidu Player"` I would like to split and strip to: `['QVOD', 'Baidu Player']` Is there an elegant way of doing this? Possibly using a list comprehension? Answer: Python has a spectacular function called `split` that will keep you from having to use a regex or something similar. You can split your string by just calling `my_string.split(delimiter)` After that python has a `strip` function which will remove all whitespace from the beginning and end of a string. [item.strip() for item in my_string.split(',')] Benchmarks for the two methods are below: >>> import timeit >>> timeit.timeit('map(str.strip, "QVOD, Baidu Player".split(","))', number=100000) 0.3525350093841553 >>> timeit.timeit('map(stripper, "QVOD, Baidu Player".split(","))','stripper=str.strip', number=100000) 0.31575989723205566 >>> timeit.timeit("[item.strip() for item in 'QVOD, Baidu Player'.split(',')]", number=100000) 0.246596097946167 So the list comp is about 33% faster than the map. Probably also worth noting that as far as being "pythonic" goes, Guido himself votes for the LC. <http://www.artima.com/weblogs/viewpost.jsp?thread=98196>
Changing Microsoft Query in Excel with Python (pywin32) or VBA Question: I need to create reports for the financial year of the individual sales of each customer (around 500) from 1-Apr 2014 to 31-Mar 2015. Last year when I did this I went in to each report from the previous year and simply changed the date in the query so it brought through that financial year. However, our customer base has grown even further and now it looks like I'll spend hours doing this unless I find out a way to change the query in the background. I can go through each worksheet in the folder containing these reports and open each file for editing: import os, pythoncom from win32com.client import Dispatch for path, subdirs, files in os.walk("location\of\folder"): # Open each workbook for filename in files: xl = Dispatch("Excel.Application") wb = xl.Workbooks.Add(path+"\\"+filename) ws = wb.Worksheets(1) # Method to alter the query here!!!! # Would even be open to doing this with VBA and just calling a macro to run # change the query if that's possible?! wb.Close() xl.Quit() pythoncom.CoUninitialize() Any help would be greatly appreciated, as it's likely to save me hours upon hours of monotonous work. Many thanks! I have just tried the following method for trying to change the SQL using VBA. Sub change_date() Sheets(1).Select ActiveSheet.QueryTables(1).CommandText = Replace(ActiveSheet.QueryTables(1).CommandText, "WHERE (Customers.InvoiceDate>={ts '2013-04-01 00:00:00'} And Customers.InvoiceDate<={ts '2014-03-31 00:00:00'})", "WHERE (Customers.InvoiceDate>={ts '2014-04-01 00:00:00'} And Customers.InvoiceDate<={ts '2015-03-31 00:00:00'})") End Sub But I am getting a Runtime (9) error: Subscript Out of Range. Any help would be appreciated. Answer: I've figured it out for all who are concerned. Sub change_date() Dim sh As Worksheet, LO As ListObject, QT As QueryTable Set sh = ActiveSheet Set QT = sh.ListObjects.Item(1).QueryTable With QT .CommandType = xlCmdSql .CommandText = Replace(QT.CommandText, "WHERE (Customers.InvoiceDate>={ts '2013-04-01 00:00:00'} And Customers.InvoiceDate<={ts '2014-03-31 00:00:00'})", "WHERE (Customers.InvoiceDate>={ts '2014-04-01 00:00:00'} And Customers.InvoiceDate<={ts '2015-03-31 00:00:00'})") .Refresh End With End Sub
python list generation/saving bug Question: I am trying to make program that prints all the possible combinations for `a` to `zzz`. I tried to add a save state feature, and it works fine but there is this bug. Let's say I interrupted the program when it printed something like `e`. When I execute the program again, it works fine until `z` but after `z` instead of printing `aa` it prints `ba` and continues from `ba`. This happens right after it prints `zz` too. it prints `baa` instead of `aaa`. How can I fix this? Here is what I did so far: import pickle,os,time alphabet="abcdefghijklmnopqrstuvwxyz" try: if os.path.isfile("save.pickle")==True: with open("save.pickle","rb") as f: tryn=pickle.load(f) for i in range(3): a=[x for x in alphabet] for j in range(i): a=[x+i for x in alphabet for i in a] b=a[tryn:] for k in b: print(k) time.sleep(0.01) tryn+=1 else: tryn=0 for i in range(3): a=[x for x in alphabet] for j in range(i): a=[x+i for x in alphabet for i in a] for k in a: print(k) tryn+=1 time.sleep(0.01) except KeyboardInterrupt: with open("save.pickle","wb") as f: pickle.dump(tryn,f) Answer: If you're using python2, or python3 as the tag suggests, this exists in the standard library already. See itertools, [product py2](http://docs.python.org/2/library/itertools.html#itertools.product), and [product py3](http://docs.python.org/3/library/itertools.html#itertools.product), for a simple way to solve this problem.
Make python process stop/wait/sleep for 0.2 seconds [Works] Question: Title says it all, is it possible to make python sleep for less than a second? WORKS: import time print ("foo") time.sleep(0.2) #talking about the value of the time print ("bar") If not, then is there any other way? Thanks Using python 3.2.2 EDIT: Thanks guys, I'm pretty sure I have tried the above code before and it didn't work. Oh well... sorry for your waste if time. It worked now and I upgraded to 3.3 Answer: Based on the [`time.sleep()`](http://docs.python.org/3/library/time.html#time.sleep) documentation: > The actual suspension time **may be less than** that requested because any > caught signal will terminate the sleep() following execution of that > signal’s catching routine. Also, the suspension time **may be longer than** > requested by an arbitrary amount because of the scheduling of other activity > in the system. So it works but there are no guarantees.
python scientific notation with forced leading zero Question: I want to have Python2.7 print out floating point numbers in scientific notation, forced to start with 0. For instance, assume a=1234567890e12 print '{:22.16E}'.format(a) 1.2345678900000000E+21 However, I want a print output that looks like: 0.1234567890000000E+22 Notice that the exponent is raised by one since the desired output is forced to a leading zero. How can I achieve this? Thanks. Answer: The fortranformat package will do what you are looking for. import fortranformat as ff a=1234567890e12 lineformat = ff.FortranRecordWriter('(1E26.16)') lineformat.write([a]) Output: ' 0.1234567890000000E+22'
Making Python 2.7 code run with Python 2.6 Question: I have this simply python function that can extract a zip file (platform independent) def unzip(source, target): with zipfile.ZipFile(source , "r") as z: z.extractall(target) print "Extracted : " + source + " to: " + target This runs fine with Python 2.7 but fails with Python 2.6: AttributeError: ZipFile instance has no attribute '__exit__': I found this suggestions that an upgrade is required 2.6 -> 2.7 <https://bugs.launchpad.net/horizon/+bug/955994> But is it possible to port the above code to work with Python 2.6 and still keep it cross platform? Answer: What about: import contextlib def unzip(source, target): with contextlib.closing(zipfile.ZipFile(source , "r")) as z: z.extractall(target) print "Extracted : " + source + " to: " + target `contextlib.closing` does exactly what the missing `__exit__` method on the `ZipFile` would be supposed to do. Namely, call the `close` method
adding lines to a file in it doesnt exist in python Question: so what i am doing is first reading the /var/log/secure file for ipaddresses that i want to block and saving that list to a file. then i am trying read that file and determine if the address is outside of the US, and if it is, then i want to block the address in the iptables. i also want to predetermine if that address has already been added to the iptables before i write to it: #!/usr/bin/env python import GeoIP import os os.system("cat /var/log/secure | grep 'Failed password for invalid user' | grep -oE '((1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])\.){3}(1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])' >> /home/user/ipaddresses.txt") iptables_file = open('/etc/sysconfig/iptables', 'r') loglist = iptables_file.readlines() iptables_file.close() found = False gi = GeoIP.new(GeoIP.GEOIP_MEMORY_CACHE) for line in file("/home/user/ipaddresses.txt", "r"): line = line[:-1] # strip the last from the line #print line, "-", gi.country_code_by_addr(line) if str(gi.country_code_by_addr(line)) != "US": for ip in loglist: if str(line) in line: print str(line) + " found in iptables, skipping ip address" break else: print "adding " + str(line) + " to iptables" #os.system("iptables -A INPUT -s " + str(line) + " -j DROP") #os.system("service iptables save") obviously i dont want to write to my iptables until i know that its working so thats why i have it commented out. what am i doing wrong? this is the error: grep: write error cat: write error: Broken pipe Answer: The second grep command: grep -oE '((1?[0-9]...[0-5])' /var/log/secure has /var/log/secure as an argument. That should not be there. It is reading the file and not reading standard input, and that is causing the error.
how to turn a sorted list into tab delimited values in Python? Question: I have a sorted list that looks like this [('100','abc'),('99','bca')]. I want to turn this into something like this into a text file. abc 100<br> bca 99 I have tried this import csv writer = csv.writer(f, delimiter = '\t') writer.writerows(d) but this gives me the output as: 100 abc<br> 99 bca Answer: Using the [csv module](http://docs.python.org/2/library/csv.html), this is pretty straight-forward: import csv data = [('100','abc'),('99','bca')] # Use 'w' for other OS's than Windows with open('my_data.csv', 'wb') as ofile: writer = csv.writer(ofile, delimiter='\t') for row in data: writer.writerow(list(reversed(row))) **`my_data.csv`:** abc 100 bca 99
Does nitrous.io support the endpoint library? Question: Developing a python project on the platform and attempting [appengine endpoints](https://developers.google.com/appengine/docs/python/endpoints/getstarted/backend/write_api). `import endpoints` throws `google.appengine.api.yaml_errors.EventError: the library "endpoints" is not supported`. The full stack trace is below. Traceback (most recent call last): File "/home/action/.google_appengine/dev_appserver.py", line 182, in <module> _run_file(__file__, globals()) File "/home/action/.google_appengine/dev_appserver.py", line 178, in _run_file execfile(script_path, globals_) File "/home/action/.google_appengine/google/appengine/tools/devappserver2/devappserver2.py", line 695, in <module> main() File "/home/action/.google_appengine/google/appengine/tools/devappserver2/devappserver2.py", line 688, in main dev_server.start(options) File "/home/action/.google_appengine/google/appengine/tools/devappserver2/devappserver2.py", line 525, in start options.yaml_files) File "/home/action/.google_appengine/google/appengine/tools/devappserver2/application_configuration.py", line 556, in __init__ server_configuration = ServerConfiguration(yaml_path) File "/home/action/.google_appengine/google/appengine/tools/devappserver2/application_configuration.py", line 82, in __init__ self._yaml_path) File "/home/action/.google_appengine/google/appengine/tools/devappserver2/application_configuration.py", line 272, in _parse_configuration return appinfo_includes.ParseAndReturnIncludePaths(f) File "/home/action/.google_appengine/google/appengine/api/appinfo_includes.py", line 63, in ParseAndReturnIncludePaths appyaml = appinfo.LoadSingleAppInfo(appinfo_file) File "/home/action/.google_appengine/google/appengine/api/appinfo.py", line 1715, in LoadSingleAppInfo listener.Parse(app_info) File "/home/action/.google_appengine/google/appengine/api/yaml_listener.py", line 226, in Parse self._HandleEvents(self._GenerateEventParameters(stream, loader_class)) File "/home/action/.google_appengine/google/appengine/api/yaml_listener.py", line 177, in _HandleEvents raise yaml_errors.EventError(e, event_object) google.appengine.api.yaml_errors.EventError: the library "endpoints" is not supported in "./app.yaml", line 21, column 1 Answer: 1. Start with a non-python project. 2. Download appengine for Linux python: ` curl -O http://googleappengine.googlecode.com/files/google_appengine_1.8.9.zip ` 3. Unzip and export directory in `~/.bash_profile`: ` export PATH="$HOME/google_appengine:$PATH" ` 4. Build endpoint python app [as described](https://developers.google.com/appengine/docs/python/endpoints/getstarted/backend/write_api) and run `dev_appserver.py`. 5. You can't view the Google APIs Explorer when launched from Nitrous.io, unless you [port forward](http://help.nitrous.io/nitrous-desktop/), but you can still use as a developing endpoint.
Installing LightBlue (BlueTooth) for Python Question: I'm trying to import lightblue for Python. I have a brand new Mac (so 10.9 I believe), I have Xcode installed, and I am running... Python 2.7.6 :: Anaconda 1.8.0 (x86_64) I downloaded lightblue-0.4.tar.gz to my desktop and then ran $ python setup.py install and I keep getting this message: xcode-select: error: tool 'xcodebuild' requires Xcode, but active developer directory '/Library/Developer/CommandLineTools' is a command line tools instance and when I try to import lightblue in python I get this error message: --------------------------------------------------------------------------- ImportError Traceback (most recent call last) <ipython-input-1-7fea8c968f08> in <module>() ----> 1 import lightblue . . . /Users/home/anaconda/lib/python2.7/site-packages/lightblue/_LightAquaBlue.py in <module>() 30 if not os.path.isdir(_FRAMEWORK_PATH): 31 raise ImportError("Cannot load LightAquaBlue framework, not found at" + \ ---> 32 _FRAMEWORK_PATH) 33 34 try: ImportError: Cannot load LightAquaBlue framework, not found at/Library/Frameworks/LightAquaBlue.framework Any ideas? Thanks, John Answer: The Xcode Command Line Tools are not automatically installed when you install Xcode. If you already have the latest version of Xcode, the Command Line Tools can be obtained from Apple as a seperate package that can be downloaded and installed. You can install Xcode Command Line Tools at the command line (via Terminal.app) like so: /usr/bin/sudo /usr/bin/xcode-select --install A new window will appear to request permission and manage the download.
Count how many matrices have full rank for all submatrices Question: I would like to count how many m by n matrices whose elements are 1 or -1 have the property that all its `floor(m/2)+1 by n` submatrices have full rank. My current method is naive and slow and is in the following python/numpy code. It simply iterates over all matrices and tests all the submatrices. import numpy as np import itertools from scipy.misc import comb m = 8 n = 4 rowstochoose = int(np.floor(m/2)+1) maxnumber = comb(m, rowstochoose, exact = True) matrix_g=(np.array(x).reshape(m,n) for x in itertools.product([-1,1], repeat = m*n)) nofound = 0 for A in matrix_g: count = 0 for rows in itertools.combinations(range(m), int(rowstochoose)): if (np.linalg.matrix_rank(A[list(rows)]) == int(min(n,rowstochoose))): count+=1 else: break if (count == maxnumber): nofound+=1 print nofound, 2**(m*n) Is there a better/faster way to do this? I would like to do this calculation for n and m up to 20 but any significant improvements would be great. **Context.** I am interested in getting some exact solutions for <http://math.stackexchange.com/questions/640780/probability-that-every-vector- is-not-orthogonal-to-half-of-the-others> . * * * As a data point to compare implementations. `n,m = 4,4` should output 26880 . `n,m=5,5` is too slow for me to run. For `n =` 2 and `m = 2,3,4,5,6` the outputs should be `8, 0, 96, 0, 1280`. * * * **Current status Feb 2, 2014:** * The answer of leewangzhong is fast but is not correct for m > n . leewangzhong is considering how to fix it. * The answer of Hooked does not run for m > n . Answer: (Now a partial solution for n = m//2+1, and the requested code.) Let k := m//2+1 This is somewhat equivalent to asking, "How many collections of m n-dimensional vectors of {-1,1} have no linearly dependent sets of size min(k,n)?" For those matrices, we know or can assume: * The first entry of every vector is 1 (if not, multiply the whole by -1). This reduces the count by a factor of 2**m. * All vectors in the list are distinct (if not, any submatrix with two identical vectors has non-full rank). This eliminates a lot. There are choose(2**m,n) matrices of distinct vectors. * The list of vectors are sorted lexicographically (rank isn't affected by permutations). So we're really thinking about sets of vectors instead of lists. This reduces the count by a factor of m! (because we require distinctness). With this, we have a solution for n=4, m=8. There are only eight different vectors with the property that the first entry is positive. There is only one combination (sorted list) of 8 distinct vectors from 8 distinct vectors. array([[ 1, 1, 1, 1], [ 1, 1, 1, -1], [ 1, 1, -1, 1], [ 1, 1, -1, -1], [ 1, -1, 1, 1], [ 1, -1, 1, -1], [ 1, -1, -1, 1], [ 1, -1, -1, -1]], dtype=int8) 100 size-4 combinations from this list have rank 3. So there are 0 matrices with the property. * * * For a more general solution: Note that there are `2**(n-1)` vectors with first coordinate -1, and `choose(2**(n-1),m)` matrices to inspect. For n=8 and m=8, there are 128 vectors, and 1.4297027e+12 matrices. It might help to answer, "For i=1,...,k, how many combinations have rank i?" Alternatively, "What kind of matrices (with the above assumptions) have less than full rank?" ~~And I think the answer is exactly,~~ A sufficient condition is, "Two columns are multiples of each other". ~~I have a feeling that this is true, and I tested this for all 4x4, 5x5, and 6x6 matrices.~~(Must've screwed up the tests) Since the first column was chosen to be homogeneous, and since all homogeneous vectors are multiples of each other, any submatrix of size k with a homogeneous column other than the first column will have rank less than k. This is not a necessary condition, though. The following matrix is singular (first plus fourth is equal to third plus second). array([[ 1, 1, 1, 1, 1], [ 1, 1, 1, 1, -1], [ 1, 1, -1, -1, 1], [ 1, 1, -1, -1, -1], [ 1, -1, 1, -1, 1]], dtype=int8) Since there are only two possible values (-1 and 1), all mxn matrices where `m>2, k := m//2+1, n = k` and with first column -1 have a majority member in each column (i.e. at least k members are the same). So for n=k, the answer is 0. * * * For n<=8, here's code to generate the vectors. from numpy import unpackbits, arange, uint8, int8 #all distinct n-length vectors from -1,1 with first entry -1 def nvectors(n): if n > 8: raise ValueError #is that the right error? return -1 + 2 * ( #explode binary numbers to arrays of 8 zeroes and ones unpackbits(arange(2**(n-1),dtype=uint8)) #unpackbits only takes uint .reshape((-1,8)) #unpackbits flattens, so we need to shape it to 8 bits [:,-n:] #only take the last n bytes .view(int8) #need signed ) Matrix generator: #generate all length-m matrices that are combinations of distinct n-vectors def matrix_g(n,m): return (array(mat) for mat in combinations(nvectors(n),m)) The following is a function to check that all submatrices of length maxrank have full rank. It stops if any have less than maxrank, instead of checking all combinations. rankof = np.linalg.matrix_rank #all submatrices of at least half size have maxrank #(we only need to check the maxrank-sized matrices) def halfrank(matrix,maxrank): return all(rankof(submatr) == maxrank for submatr in combinations(matrix,maxrank)) Generate all matrices that have all half-matrices with full rank def nicematrices(m,n): maxrank = min(m//2+1,n) return (matr for matr in matrix_g(n,m) if halfrank(matr,maxrank)) Putting it all together: import numpy as np from numpy import unpackbits, arange, uint8, int8, array from itertools import combinations #all distinct n-length vectors from -1,1 with first entry -1 def nvectors(n): if n > 8: raise ValueError #is that the right error? if n==0: return array([]) return -1 + 2 * ( #explode binary numbers to arrays of 8 zeroes and ones unpackbits(arange(2**(n-1),dtype=uint8)) #unpackbits only takes uint .reshape((-1,8)) #unpackbits flattens, so we need to shape it to 8 bits [:,-n:] #only take the last n bytes .view(int8) #need signed ) #generate all length-m matrices that are combinations of distinct n-vectors def matrix_g(n,m): return (array(mat) for mat in combinations(nvectors(n),m)) rankof = np.linalg.matrix_rank #all submatrices of at least half size have maxrank #(we only need to check the maxrank-sized matrices) def halfrank(matrix,maxrank): return all(rankof(submatr) == maxrank for submatr in combinations(matrix,maxrank)) #generate all matrices that have all half-matrices with full rank def nicematrices(m,n): maxrank = min(m//2+1,n) return (matr for matr in matrix_g(n,m) if halfrank(matr,maxrank)) #returns (number of nice matrices, number of all matrices) def count_nicematrices(m,n): from math import factorial return (len(list(nicematrices(m,n)))*factorial(m)*2**m, 2**(m*n)) for i in range(0,6): print (i, count_nicematrices(i,i)) `count_nicematrices(5,5)` takes about 15 seconds for me, the vast majority of which is taken by the `matrix_rank` function.
Celery import error Question: I am hitting an import error in starting celery. This is confusing, because this was working a few days ago, and git shows nothing changed. I think celery's heuristics for import directories are colliding with my split-out setting structure, and maybe my path/env is different than it was when the invokation was working? How should I tweak my invokation or environment to help celery load all of its downstream imports? This is Celery 3.1.7 and Django 1.6. My invokation: celery worker --app=proj.proj The error: Traceback (most recent call last): File "/home/ben/.virtualenvs/proj/bin/celery", line 8, in <module> load_entry_point('celery==3.1.7', 'console_scripts', 'celery')() File "/home/ben/.virtualenvs/proj/local/lib/python2.7/site-packages/celery/__main__.py", line 30, in main main() File "/home/ben/.virtualenvs/proj/local/lib/python2.7/site-packages/celery/bin/celery.py", line 80, in main cmd.execute_from_commandline(argv) File "/home/ben/.virtualenvs/proj/local/lib/python2.7/site-packages/celery/bin/celery.py", line 723, in execute_from_commandline super(CeleryCommand, self).execute_from_commandline(argv))) File "/home/ben/.virtualenvs/proj/local/lib/python2.7/site-packages/celery/bin/base.py", line 303, in execute_from_commandline return self.handle_argv(self.prog_name, argv[1:]) File "/home/ben/.virtualenvs/proj/local/lib/python2.7/site-packages/celery/bin/celery.py", line 715, in handle_argv return self.execute(command, argv) File "/home/ben/.virtualenvs/proj/local/lib/python2.7/site-packages/celery/bin/celery.py", line 669, in execute ).run_from_argv(self.prog_name, argv[1:], command=argv[0]) File "/home/ben/.virtualenvs/proj/local/lib/python2.7/site-packages/celery/bin/worker.py", line 175, in run_from_argv return self(*args, **options) File "/home/ben/.virtualenvs/proj/local/lib/python2.7/site-packages/celery/bin/base.py", line 266, in __call__ ret = self.run(*args, **kwargs) File "/home/ben/.virtualenvs/proj/local/lib/python2.7/site-packages/celery/bin/worker.py", line 208, in run state_db=self.node_format(state_db, hostname), **kwargs File "/home/ben/.virtualenvs/proj/local/lib/python2.7/site-packages/celery/worker/__init__.py", line 95, in __init__ self.app.loader.init_worker() File "/home/ben/.virtualenvs/proj/local/lib/python2.7/site-packages/celery/loaders/base.py", line 128, in init_worker self.import_default_modules() File "/home/ben/.virtualenvs/proj/local/lib/python2.7/site-packages/celery/loaders/base.py", line 121, in import_default_modules tuple(maybe_list(self.app.conf.CELERY_INCLUDE)) File "/home/ben/.virtualenvs/proj/local/lib/python2.7/site-packages/celery/loaders/base.py", line 103, in import_task_module return self.import_from_cwd(module) File "/home/ben/.virtualenvs/proj/local/lib/python2.7/site-packages/celery/loaders/base.py", line 112, in import_from_cwd package=package, File "/home/ben/.virtualenvs/proj/local/lib/python2.7/site-packages/celery/utils/imports.py", line 101, in import_from_cwd return imp(module, package=package) File "/home/ben/.virtualenvs/proj/local/lib/python2.7/site-packages/celery/loaders/base.py", line 106, in import_module return importlib.import_module(module, package=package) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/home/ben/Projects/proj/proj/proj/matches/management/tasks/valve_api_calls.py", line 9, in <module> from matches.models import Match, LobbyType, GameMode,\ File "/home/ben/Projects/proj/proj/proj/matches/models.py", line 1, in <module> from django.db import models File "/home/ben/.virtualenvs/proj/local/lib/python2.7/site-packages/django/db/__init__.py", line 11, in <module> if settings.DATABASES and DEFAULT_DB_ALIAS not in settings.DATABASES: File "/home/ben/.virtualenvs/proj/local/lib/python2.7/site-packages/django/conf/__init__.py", line 53, in __getattr__ self._setup(name) File "/home/ben/.virtualenvs/proj/local/lib/python2.7/site-packages/django/conf/__init__.py", line 48, in _setup self._wrapped = Settings(settings_module) File "/home/ben/.virtualenvs/proj/local/lib/python2.7/site-packages/django/conf/__init__.py", line 134, in __init__ raise ImportError("Could not import settings '%s' (Is it on sys.path?): %s" % (self.SETTINGS_MODULE, e)) ImportError: Could not import settings 'proj.settings.local' (Is it on sys.path?): No module named settings.local My project looks like: proj <git root> └──proj <project root> └── manage.py └── proj <project app>    └── celery_app.py    └── settings    └── local.py My env vars are: DJANGO_SETTINGS_MODULE=proj.settings.local DJANGO_PROJECT_DIR=/home/ben/Projects/proj/proj/proj EDIT: I am using virtualenv, so my $PATH on startup looks like PATH=/home/ben/.virtualenvs/proj/bin: /usr/local/heroku/bin:/usr/lib/lightdm/lightdm: /usr/local/sbin:/usr/local/bin: /usr/sbin: /usr/bin: /sbin: /bin: /usr/games: /usr/local/games Answer: My virtualenv got corrupted somehow. A new virtualenv with identical env vars and installed software works.
Bottle framework: how to return datetime in JSON response Question: When I try to return JSON containing `datetime` value, I'm getting File "/usr/lib/python2.7/json/encoder.py", line 178, in default raise TypeError(repr(o) + " is not JSON serializable") TypeError: datetime.datetime(2014, 2, 1, 0, 0) is not JSON serializable Which is normal. Is there an easy way to add an object hook to `bottle` like from bson import json_util import json json.dumps(anObject, default=json_util.default) to get `datetime` values converted? Answer: Interesting question! I can see a couple of ways of doing this. The one would be to write a custom plugin that wraps the `JSONPlugin`: from bottle import route, run, install, JSONPlugin from bson import json_util class JSONDefaultPlugin(JSONPlugin): def __init__(self): super(JSONDefaultPlugin, self).__init__() self.plain_dump = self.json_dumps self.json_dumps = lambda body: self.plain_dump(body, default=json_util.default) Which can then be used like this: @route('/hello') def index(name): return {'test': datetime.datetime(2014, 2, 1, 0, 0)} install(JSONDefaultPlugin()) run(host='localhost', port=8080) And will give output like this: {"test": {"$date": 1391212800000}} Another, shorter, way is to simply specify the `json_loads` parameter when instantiating the JSONPlugin class: import json from bson import json_util install(JSONPlugin(json_dumps=lambda body: json.dumps(body, default=json_util.default))) This produces the same result. ### Background This all makes a little more sense when you look at the [source code for bottle](https://github.com/defnull/bottle/blob/master/bottle.py) (some parts removed below for brevity): class JSONPlugin(object): name = 'json' api = 2 def __init__(self, json_dumps=json_dumps): self.json_dumps = json_dumps def apply(self, callback, route): dumps = self.json_dumps if not dumps: return callback def wrapper(*a, **ka): ... if isinstance(rv, dict): ... elif isinstance(rv, HTTPResponse) and isinstance(rv.body, dict): rv.body = dumps(rv.body) rv.content_type = 'application/json' return rv return wrapper All we need to do is make sure the call to `dumps` there receives the `default` keyword argument you wish to provide.
How to take sum and average of indexed values in a list? Question: List B is expanded at index positions where list A has adjacent matching values using [groupby](http://docs.python.org/2/library/itertools.html) A = [476, 1440, 3060, 3060, 500,500] B = [0,4,10,15] so resultant list is: B_update1 = [0,4,10,10,15,15] which after some intermediate steps will be: B_update2 = [0,4,12,10,20,20] Now I want to take sum and mean of duplicated values which will give me back: B_mean = [0,4,11,20] B_sum = [0,4,22,40] I am not sure how to do it. Any suggestions? Answer: B_update1, B_update2, B_mean, B_sum = [0,4,10,10,15,15], [0,4,12,10,20,20], [],[] from itertools import groupby from operator import itemgetter for num, grp in groupby(enumerate(B_update1), itemgetter(1)): tmp_list = [B_update2[idx] for idx, _ in grp] B_mean.append(sum(tmp_list)/len(tmp_list)) B_sum.append(sum(tmp_list)) print B_mean, B_sum **Output** [0, 4, 11, 20] [0, 4, 22, 40]
creating surface data for axes3d Question: Okay, apologies for this question but I'm pulling my hair out here. I have a data structure loaded in python in the form: [(1,0,#),(1,1,#),(1,2,#),(1,3,#),(2,0,#),(2,1,#) ... (26,3,#)] with # being a different number each time that I wish to represent on the z-axis. You can see that x and y are always integers. Plotting a scatter graph is simple: x,y,z = zip(*data) fig = plt.figure() ax = fig.gca(projection = '3d') surface = ax.scatter(x, y, z) plt.show() But when it comes to surfaces, I can see two methods: 1) Call `ax.plot_trisurf()`, which should work with 1D arrays similar to `ax.scatter()` and apparently works [here](http://stackoverflow.com/questions/17367558/plot-a-3d-surface-from-x-y- z-scatter-data-in-python), but for me gives me an error: "AttributeError: Axes3D subplot object has not attribute 'plot_trisurf'" This error also appears if I use the example source code at: <http://matplotlib.org/mpl_toolkits/mplot3d/tutorial.html#tri-surface-plots>, suggesting it's something wrong with my installation - my Matplotlib version is 1.1.1rc,. This error does not appear if, for example, `ax.plot_surface()` is called, nor `ax.scatter()`. 2) Use `meshgrid()` or `griddata()` in combination with `ax.plot_surface()` \- in either case, after two days' of pouring over the documentation and examples, I still don't understand how to correctly use these in my case, particularly when it comes to generating the values for Z. Any help would be much appreciated. Answer: To address your first question (1) I believe you need to import `Axes3D` from the `mplot3d` library, even if you're not directly calling it. Maybe try adding from mpl_toolkits.mplot3d import Axes3D before your main code (this line triggered a memory while reading [the tutorial](http://matplotlib.org/mpl_toolkits/mplot3d/tutorial.html)). As for (2), `X`, `Y` and `Z` need to be matrix (2d array) type objects. This can get confusing, but you may consider an example: # two arrays - one for each axis x = np.arange(-5, 5, 0.25) y = np.arange(-5, 5, 0.25) # create a mesh / matrix like object from the arrays X, Y = np.meshgrid(x, y) # create Z values - also in a mesh like shape Z = np.sin(np.sqrt(X**2 + Y**2)) # plot! surface = ax.plot_surface(X, Y, Z)
Find the most recent file on a http server (python) Question: I have a site: <http://planet.osm.ch/replication/hour/000/006/> and I need to get the most recent file listed on the server. How can I accomplish this through python 2.6.x and using only the standard library. Thank you Edit: When I mean the most recent, I mean the most recent files listed by the date field. Answer: Many people prefer to use Beautiful Soup for these tasks. But since you want to use only the standard library , here is a quick solution using the re and urllib2 modules. import urllib2 import re page = urllib2.urlopen(Your_site).read() print re.findall(r"<a.+>(\d+.+)</a>",page)[-1] Note : I know it is bad practice to use re to parse HTML, but this is a simple website and the question requires so.
How to share a string amongst multiple processes using Managers() in Python? Question: I need to read strings written by multiprocessing.Process instances from the main process. I already use Managers and queues to pass arguments to processes, so using the Managers seems obvious, [but Managers do not support strings](http://docs.python.org/2/library/multiprocessing.html#sharing-state- between-processes): > A manager returned by Manager() will support types list, dict, Namespace, > Lock, RLock, Semaphore, BoundedSemaphore, Condition, Event, Queue, Value and > Array. How do I share state represented by a string using Managers from the multiprocessing module? Answer: multiprocessing's Managers can hold [Values](http://docs.python.org/2/library/multiprocessing.html#multiprocessing.Value) which in turn can hold instances of the type [c_char_p](http://docs.python.org/2/library/ctypes.html#fundamental-data- types) from the ctypes module: >>> import multiprocessing >>> import ctypes >>> v = multiprocessing.Value('c', "Hello, World!") Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python2.7/multiprocessing/__init__.py", line 253, in Value return Value(typecode_or_type, *args, **kwds) File "/usr/lib/python2.7/multiprocessing/sharedctypes.py", line 99, in Value obj = RawValue(typecode_or_type, *args) File "/usr/lib/python2.7/multiprocessing/sharedctypes.py", line 73, in RawValue obj.__init__(*args) TypeError: one character string expected >>> cstring = multiprocessing.Value(ctypes.c_char_p, "Hello, World!") >>> cstring <Synchronized wrapper for c_char_p(166841564)> >>> cstring.value 'Hello, World!' See also: [Post with the original solution](http://stackoverflow.com/a/16485061/906658) that I had a hard time finding. So a Manager can be used to share a string beneath multiple processes in Python like this: >>> from multiprocessing import Process, Manager, Value >>> from ctypes import c_char_p >>> >>> def greet(string): >>> string.value = string.value + ", World!" >>> >>> if __name__ == '__main__': >>> manager = Manager() >>> string = manager.Value(c_char_p, "Hello") >>> process = Process(target=greet, args=(string,)) >>> process.start() >>> process.join() >>> print string.value 'Hello, World!'
python error when added a function to a class Question: i just added this function to my class def getTotalPopulation(): print 'there are {0} people in the world'.format(Person.population) when i call it, i got this error: Traceback (most recent call last): File "<interactive input>", line 1, in <module> TypeError: unbound method getTotalPopulation() must be called with Person instance as first argument (got nothing instead) I call it like this: from MyTests import Person >>> Person.Person.getTotalPopulation() ### for people who need all code class Person: population = 0 def __init__(self, name, age): self.name = name self.age = age Person.population += 1 print '{A} has been born'.format(A = self.name) def __str__(self): return '{0} is {1} years old'.format(self.name, self.age) def __del__(self): Person.population -=1 print '{0} is dying :( '.format(self.name) def getTotalPopulation(): print 'there are {0} people in the world'.format(Person.population) Answer: you need to make that a classmethod: change class Person: def getTotalPopulation(self): return Person.population to: class Person(object): @classmethod def getTotalPopulation(cls): return cls.population that is, add the `@classmethod` decorator right before the `def`. additionally, the first parameter of a classmethod is conventionally spelled `cls` instead of `self`; and you should use it in the method body to support subclasses properly. That's for python 2, though. For python three, your code works correctly, because methods can be used implicitly as though they are `staticmethod`s. I wouldn't particularly reccomend that, though, since you almost never need that feature, but `classmethod`s are terrifically useful.
How to find set of most frequently occurring word-pairs in a file using python? Question: I have a data set as follows: "485","AlterNet","Statistics","Estimation","Narnia","Two and half men" "717","I like Sheen", "Narnia", "Statistics", "Estimation" "633","MachineLearning","AI","I like Cars, but I also like bikes" "717","I like Sheen","MachineLearning", "regression", "AI" "136","MachineLearning","AI","TopGear" and so on I want to find out the most frequently occurring word-pairs e.g. (Statistics,Estimation:2) (Statistics,Narnia:2) (Narnia,Statistics) (MachineLearning,AI:3) The two words could be in any order and at any distance from each other Can someone suggest a possible solution in python? This is a very large data set. Any suggestion is highly appreciated So this is what I tried after suggestions from @275365 @275365 I tried the following with input read from a file def collect_pairs(file): pair_counter = Counter() for line in open(file): unique_tokens = sorted(set(line)) combos = combinations(unique_tokens, 2) pair_counter += Counter(combos) print pair_counter file = ('myfileComb.txt') p=collect_pairs(file) text file has same number of lines as the original one but has only unique tokens in a particular line. I don't know what am I doing wrong since when I run this it splits the words in letters rather than giving output as combinations of words. When I run this file it outputs split letters rather than combinations of words as expected. I dont know where I am making a mistake. Answer: You might start with something like this, depending on how large your corpus is: >>> from itertools import combinations >>> from collections import Counter >>> def collect_pairs(lines): pair_counter = Counter() for line in lines: unique_tokens = sorted(set(line)) # exclude duplicates in same line and sort to ensure one word is always before other combos = combinations(unique_tokens, 2) pair_counter += Counter(combos) return pair_counter The result: >>> t2 = [['485', 'AlterNet', 'Statistics', 'Estimation', 'Narnia', 'Two and half men'], ['717', 'I like Sheen', 'Narnia', 'Statistics', 'Estimation'], ['633', 'MachineLearning', 'AI', 'I like Cars, but I also like bikes'], ['717', 'I like Sheen', 'MachineLearning', 'regression', 'AI'], ['136', 'MachineLearning', 'AI', 'TopGear']] >>> pairs = collect_pairs(t2) >>> pairs.most_common(3) [(('MachineLearning', 'AI'), 3), (('717', 'I like Sheen'), 2), (('Statistics', 'Estimation'), 2)] Do you want numbers included in these combinations or not? Since you didn't specifically mention excluding them, I have included them here. **EDIT: Working with a file object** The function that you posted as your first attempt above is very close to working. The only thing you need to do is change each line (which is a string) into a tuple or list. Assuming your data looks exactly like the data you posted above (with quotation marks around each term and commas separating the terms), I would suggest a simple fix: you can use `ast.literal_eval`. (Otherwise, you might need to use a regular expression of some kind.) See below for a modified version with `ast.literal_eval`: from itertools import combinations from collections import Counter import ast def collect_pairs(file_name): pair_counter = Counter() for line in open(file_name): # these lines are each simply one long string; you need a list or tuple unique_tokens = sorted(set(ast.literal_eval(line))) # eval will convert each line into a tuple before converting the tuple to a set combos = combinations(unique_tokens, 2) pair_counter += Counter(combos) return pair_counter # return the actual Counter object Now you can test it like this: file_name = 'myfileComb.txt' p = collect_pairs(file_name) print p.most_common(10) # for example
Strategies for searching through strings in python? Question: What are efficient ways to search for substrings in strings? \- Are there specific functions built in python we can use? \- Can we convert them to lists then access elements in the list? \- Can we use for loops to search through individual elements? \- Is there one generally accepted method by Python programmers? It would be helpful to understand the different strategies to help me solve the following problem: Return the number of times that the string `"code"` appears anywhere in the given string, except we'll accept any letter for the `'d'`, so `"cope"` and `"cooe"` count. count_code('aaacodebbb') → 1 count_code('codexxcode') → 2 count_code('cozexxcope') → 2 Answer: You can use `regex`: >>> import re def count(s): return sum(1 for m in re.finditer(r'co.e', s)) ... >>> count('aaacodebbb') 1 >>> count('codexxcode') 2 >>> count('cozexxcope') 2 Here `.` matches any character, if you only want to match alphabets then use `r'co[a-zA-Z]e'`.
Can not start boa-constructor successfully Question: When I start boa-constructor from the command line by starting the script "Boa.py", I got the message says " D:\Python27\Lib\site-packages\boa-constructor>python Boa.py Starting Boa Constructor v0.6.1 importing wxPython reading user preferences Traceback (most recent call last): File "Boa.py", line 271, in <module> import Preferences, Utils File "D:\Python27\Lib\site-packages\boa-constructor\Preferences.py", line 151 in <module> execfile(file) File "C:\Users\madfrog\.boa-constructor\prefs.rc.py", line 26, in <module> splitterStyle = wx.SP_LIVE_UPDATE | wx.SP_3DSASH | wx.NO_3D AttributeError: 'module' object has no attribute 'NO_3D' My python version is 2.7.4 and I download wxPyton "32-bit Python 2.7". There are someone say it because the unmatched wxPython version, but there are only 64-bit or 32 bit for me, I don't know how to handle this problem. Maybe should I reinstall the python, which version is 2.6? Thanks for your help. Answer: I had the same problem. I can't tell you why. I can just tell you how I fixed it. After you download and unzip the boa files go into the boa folder (On a Mac this could be: /Users/your_user_name/Downloads/boa-constructor-0.6.1). Then: "grep" for every file containing NO_3D (or use whatever you want to search for a string in a set of files, I don't know how windows does this): In my case I did: grep -ir NO_3D * A list of files comes up. Simply edit each such file (there are ~6) and remove any mentioning of "wx.NO_3D". E.g., in Companions/BaseCompanions.py I find a match: "self.windowStyles = ['wx.CAPTION', 'wx.MINIMIZE_BOX', 'wx.MAXIMIZE_BOX', 'wx.THICK_FRAME', 'wx.SIMPLE_BORDER', 'wx.DOUBLE_BORDER', 'wx.SUNKEN_BORDER', 'wx.RAISED_BORDER', 'wx.STATIC_BORDER',. 'wx.TRANSPARENT_WINDOW', 'wx.NO_3D', 'wx.TAB_TRAVERSAL',. 'wx.WANTS_CHARS', 'wx.NO_FULL_REPAINT_ON_RESIZE', 'wx.VSCROLL',. 'wx.HSCROLL', 'wx.CLIP_CHILDREN', 'wx.NO_BORDER', 'wx.ALWAYS_SHOW_SB']" You see the '**wx.NO_3D** ' in the middle somewhere. Remove it and save the file. Keep doing this for all files. However, there is a minor complication in one file: "Inspector.py". Here, you cannot simply remove wx.NO_3D. In particular, the match is: **self.categories = wx.SplitterWindow(self, -1, style=wx.NO_3D | wx.SP_3D | wx.SP_LIVE_UPDATE)** What I did was to replace "style=wx.NO_3D" with "style=wx.DEFAULT_FRAME_STYLE" (I found this default name in one of the other files; you see how there are different "styles" recognized by the program so I just chose some other style than NO_3D). Then I just ran Boa with: "python Boa.py" and it worked (assuming you have the module wx installed and whatever else is needed for Boa to run in the first place of course).
Requiring help in figuring out indent error in python code Question: I get an indentation error when trying to run the code below. I am trying to print out the URLs of a set of html pages recursively. import urllib2 from BeautifulSoup import * from urlparse import urljoin # Create a list of words to ignore ignorewords=set(['the','of','to','and','a','in','is','it']) def crawl(self,pages,depth=2): for i in range(depth): newpages=set() for page in pages: try: c=urllib2.urlopen(page) except: print "Could not open %s" % page continue soup=BeautifulSoup(c.read()) self.addtoindex(page,soup) links=soup('a') for link in links: if ('href' in dict(link.attrs)): url=urljoin(page,link['href']) if url.find("'")!=-1: continue url=url.split('#')[0] # remove location portion if url[0:4]=='http' and not self.isindexed(url): newpages.add(url) linkText=self.gettextonly(link) self.addlinkref(page,url,linkText) self.dbcommit() pages=newpages Answer: Well you're coded is totally unindented so Python will cry when you try and run it. Remember in Python whitespace is important. Indenting with 4 spaces rather than tab saves a lot of "invisible" indentation errors. I've down-voted as the code was pasted unformatted/unindented which means either the poster doesn't understand python (and hasn't read a basic tutorial) or pasted the code without re-indenting , which makes it impossible for anyone to answer.
How to delete an image file from GridFS by file metadata? Question: I have an image with the following metadata: > db.fs.files.find().pretty() { "_id" : ObjectId("4576874577342672346"), "chunkSize" : 262144, "user_name" : "my name", "filename" : "image.jpg", "length" : 7103, "uploadDate" : ISODate("2014-01-23T13:31:48.155Z"), "user_email" : "[email protected]", "md5" : "1234567890" } > I want to delete the image from Python (PyMongo). The documentation on `delete()` seems to stipulate that the only accepted parameter in the `delete()` function is the `file_id`: <http://api.mongodb.org/python/current/api/gridfs/#gridfs.GridFS.delete> Programmatically, I have the following values available that can be matched in the files metadata: * user_name * filename * user_email How do I either: * Get the `file_id` (through use of the above values if necessary) or * Delete the file based on metadata fields other than `file_id`? Additionally, I am only currently testing with single chunk files, if interacting with larger files in the future will deleting by `file_id` or other metadata remove all associated chunks as well? Answer: Here's something I just tried without thinking if it's necessary or the best way to do it, but it works. So programatically I could have the `_id` available from querying on the files metadata: _Python Shell:_ >>> import pymongo >>> import os >>> hostname = os.environ['OPENSHIFT_MONGODB_DB_URL'] >>> conn = pymongo.MongoClient(host=hostname) >>> db = conn.grid_files >>> collection = db.fs.files >>> result = collection.find_one({"user_email":"[email protected]","name":"my name","filename":"image.jpg"}) >>> result['_id'] ObjectId('52e119c47091447a86891d98') # now use the _id to delete the file >>> files_id = result['_id'] >>> import gridfs >>> fs = gridfs.GridFS(db) >>> fs.delete(files_id)
Type error when calling sdlttf.TTF_OpenFont() with the pysdl2 Python bindings Question: I have all dependencies correctly installed (SDL2, SDL2_TTF, pysdl2). I've tried to provide just the filename for the font and I've tried to hard code the full path. The font is in the same directory as the python file. import sys try: from sdl2 import * import sdl2.ext as sdl2ext import sdl2.sdlttf as sdlttf except ImportError: import traceback traceback.print_exc() sys.exit(1) def run(): sdl2ext.init() sdlttf.TTF_Init() RESOURCES = sdl2ext.Resources(__file__, "") # print(RESOURCES.get_path("arial.ttf")) font = sdlttf.TTF_OpenFont(RESOURCES.get_path("arial.ttf"), 24) window = sdl2ext.Window("SDL_TTF test", size=(800, 600)) message = sdlttf.TTF_RenderText_Solid(font, "Hello World", (255, 255, 255)) window.show() running = True while running: events = sdl2ext.get_events() for event in events: if event.type == SDL_QUIT: running = False break window.refresh() return 0 if __name__ == "__main__": sys.exit(run()) Returns: Traceback (most recent call last): File "sdl2_test.py", line 32, in <module> sys.exit(run()) File "sdl2_test.py", line 17, in run font = sdlttf.TTF_OpenFont(RESOURCES.get_path("arial.ttf"), 24) ctypes.ArgumentError: argument 1: <class 'TypeError'>: wrong type Answer: I got it. Since I'm using Python 3 the type is incorrect due to the standard type used for representing strings in Python 3. I solved it by using str.encode()
Modifying Active Directory Passwords via ldapmodify Question: I'm investigating the scripting of various LDAP operations. However, I've hit a bit of a speed bump with Active Directory user creation. The following LDIF fails when I load it in via the `ldapmodify` command: dn: CN=Frank,CN=Users,DC=domain,dc=local changeType: add objectClass: top objectClass: person objectClass: organizationalPerson objectClass: user cn: Frank userPrincipalName: [email protected] sAMAccountName: frank givenName: Frank sn: Stein displayName: Frank Stein description: Frankenstein's User userAccountControl: 512 unicodePwd: "AnExamplePassword1!" When attempting to add the user via LDIF, I used the following command: ldapmodify -H 'ldaps://<ip-of-server>:636' -D 'DOMAIN\Administrator' -x -W -f frank-add.ldif This fails with the following error: ldap_add: Server is unwilling to perform (53) additional info: 0000001F: SvcErr: DSID-031A120C, problem 5003 (WILL_NOT_PERFORM), data 0 This is a problem with the password policy denying the user. However, the following Python script works: #!/usr/bin/python import ldap import ldap.modlist as modlist AD_LDAP_URL='ldaps://<ip-of-server>:636' ADMIN_USER='DOMAIN\Administrator' # User must be authorized to create accounts, naturally. ADMIN_PASSWORD='password for ADMIN_USER' BASE_DN='dc=domain,dc=local' username='frank' firstname='Frank' surname='Stein' displayName = "Frank Stein" password='AnExamplePassword1!' # The value of password still needs to adhere to the domain's password policy. unicode_pass = unicode('\"' + password + '\"', 'iso-8859-1') password_value = unicode_pass.encode('utf-16-le') l = ldap.initialize(AD_LDAP_URL) l.simple_bind_s(ADMIN_USER, ADMIN_PASSWORD) dn=str('CN=%s,CN=Users,DC=domain,dc=local' % firstname) attrs = {} attrs['objectclass'] = ['top','person','organizationalPerson','user'] attrs['cn'] = str(username) attrs['sAMAccountname'] = str(username) attrs['unicodePwd'] = str(password_value) attrs['givenName'] = str(firstname) attrs['sn'] = str(surname) attrs['displayName'] = str(displayName) attrs['description'] = str("Frankenstein's User") attrs['userPrincipalName'] = str("%[email protected]" % username) attrs['userAccountControl'] = str(512) ldif = modlist.addModlist(attrs) l.add_s(dn,ldif) Using the Python script, I am immediately able to sign in using the user's password (minus the quotes that were escaped out). I can still trigger the same "Unwilling to Perform" error by picking a password like 'password' that is too simple. However, in this case the password being used is the same. So far as I can see, the operations should be identical. The difference that breaks the LDIF file is the way that I deal with the quotes that I need to enclose the password in. Creation via LDIF succeeds if I make a disabled account by setting the value of userAccountControl to 544 and not including a password. However, this means that I would need to manually go and reset the user's password. So far, I've tried the following password formats via LDIF: * Without quotes. * Plain quotes. * Escaped quotes via \ * Escaped quotes via ASCII: {\22} * Using Python to Base64-encode the password (With and without quotes, and with the format of the LDIF modified to `unicodePwd::`) While I'm happy that I have a working method of adding users via the Python, I'm still a bit confused about how to properly escape out password values when using LDIF files and `ldapmodify`. Is there an alternate method that I'm not considering? Answer: Why not use ldifde and unicode base64 encode the password as described here: <http://support.microsoft.com/kb/263991> Your python script seems to be encoding the password as unicode / base64. Perhaps your password needs to be encoded in your ldif file (with the quotes when encoding) rather than plain text as you are doing in your example. Eg: unicodePwd:: IgBBAG4ARQB4AGEAbQBwAGwAZQBQAGEAcwBzAHcAbwByAGQAMQAhACIA For the example password you provided.
variable in try clause not accessible in finally clause - python Question: I am new to python, so sorry if this question is dumb, but can someone tell me what's going on here. When I run the following code with no errors in the mdb.connect() call, the code runs fine. But when I purposely insert an error (for example, put in 'localhostblahblah'), I get a 'NameError: name 'con' is not defined' error when I execute. I thought that variables defined in the try clause should be accessible in the finally clause. What's going on? #!/usr/bin/python import MySQLdb as mdb import sys try: con = mdb.connect('localhost','jmtoung','','ptb_genetics') except mdb.Error, e: print "Error" sys.exit(1) finally: if con: con.close() Answer: If `mdb.connect` errors, there's nothing to assign to `con`, so it doesn't get defined. Instead of `finally`, try using `else`, which is run only when there was no exception. [Docs](http://docs.python.org/2/tutorial/errors.html#handling- exceptions) try: con = mdb.connect('localhost','jmtoung','','ptb_genetics') except mdb.Error as e: print "Error" sys.exit(1) else: # else instead of finally con.close()
Keyword values for error_kw in Python bar plots Question: I want to adjust error bar properties in a bar plot. Apparently this is to be done by using keyword arguments (i.e. in error_kw). e.g. from pylab import * fig = figure() ax = fig.add_subplot(111) ax.plot( left=0, width=1, height=5, error_kw=dict(elinewidth=3, ecolor='b') ) However, I cannot find a listing of the possible error_kw values. I apologize in advance for asking such a trivial question, but I cannot find this anywhere and it drives me nuts. Answer: See the parameters for matplotlib.pyplot.bar Parameters: left : sequence of scalars the x coordinates of the left sides of the bars height : sequence of scalars the heights of the bars width : scalar or array-like, optional, default: 0.8 the width(s) of the bars bottom : scalar or array-like, optional, default: None the y coordinate(s) of the bars color : scalar or array-like, optional the colors of the bar faces edgecolor : scalar or array-like, optional the colors of the bar edges linewidth : scalar or array-like, optional, default: None width of bar edge(s). If None, use default linewidth; If 0, don’t draw edges. xerr : scalar or array-like, optional, default: None if not None, will be used to generate errorbar(s) on the bar chart yerr :scalar or array-like, optional, default: None : if not None, will be used to generate errorbar(s) on the bar chart ecolor : scalar or array-like, optional, default: None specifies the color of errorbar(s) capsize : integer, optional, default: 3 determines the length in points of the error bar caps error_kw : : dictionary of kwargs to be passed to errorbar method. ecolor and capsize may be specified here rather than as independent kwargs. align : [‘edge’ | ‘center’], optional, default: ‘edge’ If edge, aligns bars by their left edges (for vertical bars) and by their bottom edges (for horizontal bars). If center, interpret the left argument as the coordinates of the centers of the bars. orientation : ‘vertical’ | ‘horizontal’, optional, default: ‘vertical’ The orientation of the bars. log : boolean, optional, default: False If true, sets the axis to be log scale
How do I right click on a windows tray icon and clicking on item on context menu in Python? Question: I need to right click on a Windows Notification Tray icon, and select (left clicking) one of the items on the resulting context menu. I have tried to use [pywinauto](http://pywinauto.googlecode.com/), and while running this code from the code on the [How To's](http://pywinauto.googlecode.com/hg/pywinauto/docs/HowTo.html#how-to- access-the-system-tray-aka-systray-aka-notification-area) page: from pywinauto.application import Application from pywinauto import taskbar # connect to outlook outlook = Application().connect_(process=4436) # click on Outlook's icon taskbar.ClickSystemTrayIcon(12) # Select an item in the popup menu outlook.PopupMenu.MenuClick("Cancel Server Request") I am getting the following error: Traceback (most recent call last): File "C:\dev\consumertms\temp.py", line 25, in <module> taskbar.ClickSystemTrayIcon(12) File "C:\Python27\lib\site-packages\pywinauto\taskbar.py", line 52, in ClickSystemTrayIcon button = _get_visible_button_index(button) File "C:\Python27\lib\site-packages\pywinauto\taskbar.py", line 42, in _get_visible_button_index if not SystemTrayIcons.GetButton(i).fsState & \ File "C:\Python27\lib\site-packages\pywinauto\controls\common_controls.py", line 1878, in GetButton button.idCommand) RuntimeError: GetButtonInfo failed for button with command id 2 I am currently running Windows 8, but will require this to run on Windows XP onwards. I have searched around and was unable to find a workaround for this. My Question: Is there a workaround for this error? If not, is there some other Python module I can use to automate this process? Some code snippets will be very much appreciated. Thanks Answer: A context menu or dropdown menu can be a window context on it's own. You will need to find it with _findwindows.find_windows()_. I encountered this problem when I needed to access dropdown menu items on a non-native GUI. The easiest way to get the class name of that windows is by using SWAPY, which lists all window objects and creates handy pywinauto code <https://code.google.com/p/swapy/>. A typical approach would be like this: outlook = Application().connect_(process=4436) taskbar.ClickSystemTrayIcon(12) # Use SWAPY to find the class name of the popup menu w_handle = findwindows.find_windows(title=u'', class_name='name-found-in-SWAPY')[0] popup = app.window_(handle=w_handle) popup.Click(coords=(x,y))
Python - create next file Question: I am writing a small script. The script creates `.txt` files. I do not want to replace existing files. So what I want python to do is to check if the file already exists. If it does not it can proceed. If the file does exists I would like python to increment the name and than check again if the file already exists. If the file does not already exist python may create it. EXAMPLE: current dir has these files in it: `file_001.txt` `file_002.txt` I want python to see that the two files exists and make the next file: `file_003.txt` creating files can be done like this: f = open("file_001.txt", "w") f.write('something') f.close() [checking](http://stackoverflow.com/questions/82831/how-do-i-check-if-a-file- exists-using-python) if a file exists: import os.path os.path.isfile(fname) Answer: If you want to check whether it's both a file and that it exist then use `os.path.exists` along with `os.path.isfile`. Or else just the former seems suffice. Following might help: import os.path as op print op.exists(fname) and op.isfile(fname) or just `print op.exists(fname)`
15 Python scripts into one executable? Question: Ive been tinkering around all day with solutions from here and here: [How would I combine multiple .py files into one .exe with Py2Exe](http://stackoverflow.com/questions/7950335/how-would-i-combine- multiple-py-files-into-one-exe-with-py2exe) [Packaging multiple scripts in PyInstaller](http://stackoverflow.com/questions/8888813/packaging-multiple- scripts-in-pyinstaller) but Its not quite working the way I thought it might. I have a program that Ive been working on for the last 6 months and I just sourced out one of its features to another developer who did his work in Python. What I would like to do is use his scripts without making the user have to download and install python. The problem as I see it is that 1 python script calls the other 14 python scripts for various tasks. So what I'm asking is whats the best way to go about this? Is it possible to package 15 scripts and all their dependencies into 1 exe that I can call normally? or is there another way that I can package the initial script into an exe and that exe can call the .py scripts normally? or should I just say f' it and include a python installer with my setup file? This is for Python 2.7.6 btw And this is how the initial script calls the other scripts. import printSub as ps import arrayWorker as aw import arrayBuilder as ab import rootWorker as rw import validateData as vd etc... If this was you trying to incorporate these scripts, how would you go about it? Thanks Answer: You can really use **py2exe** , it behaves the way you want. See answer to the mentioned question: [How would I combine multiple .py files into one .exe with Py2Exe](http://stackoverflow.com/questions/7950335/how- would-i-combine-multiple-py-files-into-one-exe-with-py2exe) Usually, py2exe bundles your main script to exe file and all your dependent scripts (it parses your imports and finds all nescessary python files) to library zip file (pyc files only). Also it collects dependent DLL libraries and copies them to distribution directory so you can distribute whole directory and user can run exe file from this directory. The benefit is that you can have a large number of scripts - smaller exe files - to use one large library zip file and DLLs. Alternatively, you can configure py2exe to bundle all your scripts and requirements to 1 standalone exe file. Exe file consists of main script, dependent python files and all DLLs. I am using these options in setup.py to accomplish this: setup( ... options = { 'py2exe' : { 'compressed': 2, 'optimize': 2, 'bundle_files': 1, 'excludes': excludes} }, zipfile=None, console = ["your_main_script.py"], ... ) * * * Working code: from distutils.core import setup import py2exe, sys, os sys.argv.append('py2exe') setup( options = { 'py2exe' : { 'compressed': 1, 'optimize': 2, 'bundle_files': 3, #Options 1 & 2 do not work on a 64bit system 'dist_dir': 'dist', # Put .exe in dist/ 'xref': False, 'skip_archive': False, 'ascii': False, } }, zipfile=None, console = ['thisProject.py'], )
Bitcoinrpc connection to remote server Question: Hey I was wondering if anyone knew how to connect to a bitcoin wallet located on another server with bitcoinrpc I am running a web program made in django and using a python library called bitcoinrpc to make connections. When testing locally, I can use bitcoinrpc.connect_to_local), or even bitcoinrpc.connect_to_remote('account','password') and this works as well as long as the account and password match the values specified in my 'bitcoin.conf' file. I can then use the connection object to get values and do some tasks in my django site. The third parameter in connect_to_local is default localhost. I was wondering: A) What to specify for this third parameter in order to connect from my webserver to the wallet stored on my home comp (is it my IP address?) B) Because the wallet is on my PC and not some dedicated server, does that mean that my IP will change and I won't be able to access the wallet? C) The connection string is in the django app - which is hosted on heroku. Heroku apps are launched by pushing with git but I believe it is to a private repository. Still, if anyone could see the first few lines of my 'view' they would have all they need to take my BTC (or, more accurately, mBTC). Anyone know how bad this is - or any ways to go about doing btc payments/movements in a more secure way. Thanks a lot. Answer: I'm currently doing something very similar (heroku using express/nodejs instead of django/python tho) so I will try to share my thoughts. In spite of using other library and other language, all the wallet remote libraries should be primarily a wrapper around JSON RPC (remote procedure call) API, which is actually the same for most of the coins out there (i would say all, but that would be a wild guess). Specifically to your questions: A) To access the wallet from outside, use your external ip (fastest way to find it is to query google for it). Depending on your ISP you hopefully have static external address. You must provide this address to `bitcoin.conf` file under `rpcallowip=` option to allow incomming connections. Moreover you should forward the used port in your home router (usually under NAT settings) to your local machine so the incoming connection from the server is allowed and redirected to your wallet computer. There is one important thing to consider (<https://en.bitcoin.it/wiki/Running_Bitcoin>): By default, only RPC connections from localhost are allowed. Specify as many rpcallowip= settings as you like to allow connections from other hosts (and you may use * as a wildcard character). NOTE: opening up the RPC port to hosts outside your local trusted network is NOT RECOMMENDED, because the rpcpassword is transmitted over the network unencrypted. I am yet to look into it further, from this comment alone it seems totally unusable for monetary transactions. B) As I said before, it depends on your home ISP, type of connection and the service provided to you. C) If I understand correctly from a django point of view, as long as the login parameters (username/password) are inside a view (`views.py` of your app) and the debug mode is turned off, source code of the server should not be publicly accessible. But the security concern from A still applies.
SKLearn - Principal Component Analysis leads to horrible results in knn predictions Question: by adding PCA to the algorithm, I'm working to improve %96.5 SKlearn kNN prediction score for kaggle digit recognition tutorial, yet new kNN predictions based on PCA output are horrible like 23%. below is the full code and i appreciate if you point out where i am mistaken. import pandas as pd import numpy as np import pylab as pl import os as os from sklearn import metrics %pylab inline os.chdir("/users/******/desktop/python") traindata=pd.read_csv("train.csv") traindata=np.array(traindata) traindata=traindata.astype(float) X,y=traindata[:,1:],traindata[:,0] from sklearn.cross_validation import train_test_split X_train, X_test, y_train, y_test= train_test_split(X,y,test_size=0.25, random_state=33) #scale & PCA train data from sklearn import preprocessing from sklearn.decomposition import PCA X_train_scaled = preprocessing.scale(X_train) estimator = PCA(n_components=350) X_train_pca = estimator.fit_transform(X_train_scaled) # sum(estimator.explained_variance_ratio_) = 0.96 from sklearn.neighbors import KNeighborsClassifier neigh = KNeighborsClassifier(n_neighbors=6) neigh.fit(X_train_pca,y_train) # scale & PCA test data X_test_scaled=preprocessing.scale(X_test) X_test_pca=estimator.fit_transform(X_test_scaled) y_test_pred=neigh.predict(X_test_pca) # print metrics.accuracy_score(y_test, y_test_pred) = 0.23 # print metrics.classification_report(y_test, y_test_pred) Answer: When you are processing the test data, you used `fit_transform(X_test)` which actually recomputes another PCA transformation on the test data. You should be using `transform(X_test)`, so that the test data undergoes the same transformation as the training data. The portion of code will look something like (thanks ogrisel for the `whiten` tip): estimator = PCA(n_components=350, whiten=True) X_train_pca = estimator.fit_transform(X_train) X_test_pca = estimator.transform(X_test) Try and see if it helps?
Tracking CPU time of Python process and children Question: Is there an easy way to track the CPU time of not only a Process but of any child processes launched by it? I tried sub-classing `multiprocessing.Process` to time an arbitrary function, like: import time from multiprocessing import Process class TimedProcess(Process): daemon = True def __init__(self, *args, **kwargs): super(TimedProcess, self).__init__(*args, **kwargs) self.t0 = time.clock() @property def duration_seconds(self): return time.clock() - self.t0 p = TimedProcess(target=my_long_running_func) p.start() while p.is_alive(): print p.duration_seconds time.sleep(1) However, when I tried to time functions involving Scikits-learn or other code involving c-extensions or sub-processes, I found my `duration_sections` would often report 0, or just a few seconds, even though the code would run for hours. How would I fix this? Answer: Your code almost prints the CPU time, but you're calling `time.clock()` in the parent process instead of the child process. By using `multiprocessing.Pipe`, you can pass the values from the child to the parent process: import time from threading import Thread from multiprocessing import Process, Pipe class TimedProcess(Process): daemon = True def __init__(self, *args, **kwargs): super(TimedProcess, self).__init__(*args, **kwargs) self.parent_conn, self.child_conn = Pipe() self.child_finished = False self._duration = 0.0 def get_duration(self): if not self.child_finished: self.parent_conn.send(None) result = self.parent_conn.recv() if result == 'done': self.child_finished = True else: self._duration = result return self._duration def run(self): try: t0 = time.clock() Thread(target=self._run).start() while True: request = self.child_conn.recv() self.child_conn.send(time.clock() - t0) if request == 'stop': break finally: self.child_conn.send('done') def _run(self): try: super(TimedProcess, self).run() finally: self.parent_conn.send('stop') p = TimedProcess(target=my_long_running_func) p.start() while p.is_alive(): time.sleep(1) print p.get_duration()
Split .TIF file using PIL Question: I took a look at the [Split multi-page tiff with python](http://stackoverflow.com/questions/9627652/split-multi-page-tiff-with- python) file for Splitting a .TIFF File, however to be honest, I didn't fully understand the answers, and I'm hoping for a little clarification. I am attempting to take a .Tif file with multiple Invoices in it and Split it into each page which will then be Zipped Up and uploaded into a database. PIL is installed on the computers that will be running this program, as such I'd like to stick with the PIL Library. I know that I can view information such as the Size of each Image using PIL after it's open, however when I attempt to Save each it gets dicey. (Example Code Below) def Split_Images(img,numFiles): ImageFile = Image.open(img) print ImageFile.size[0] print ImageFile.size[1] ImageFile.save('InvoiceTest1.tif')[0] ImageFile.save('InvoiceTest2.tif')[1] However when I run this code I get the following Error: TypeError: 'NoneType' object has no attribute '__getitem__' Any Suggestions? Thank you in advance, Answer: You need the PIL Image "seek" method to access the different pages. from PIL import Image img = Image.open('multipage.tif') for i in range(4): try: img.seek(i) img.save('page_%s.tif'%(i,)) except EOFError: break
Python Kerberos-1.1.1.tar.gz Install Failure on Windows Question: I run Python on windows based environments (2003, win 7, 2008 r2, etc) both 32 and 64-bit flavors. I've recently had to authenticate to various corporate, internally facing web-sites using both NTLM and Kerberos authentication schemes. I was successful with NTLM authentication using the 'requests' module. Specifically there is some documentation discussing ways for [Other Authentication](http://docs.python- requests.org/en/latest/user/authentication/#new-forms-of-authentication). Installing the 'requests-ntlm' packages worked great! Unfortunately I cannot seem to get the requests-kerberos package to work. The requirements.txt indicates that the kerberos-1.1.1 package is required, but I am unable to build/install that package. Here is what happens if I try to import the requests-kerberos library without the kerberos-1.1.1: >>> import requests >>> from requests_kerberos import HTTPKerberosAuth Traceback (most recent call last): File "<stdin>", line 1, in <module> File "requests_kerberos\__init__.py", line 17, in <module> from .kerberos_ import HTTPKerberosAuth, REQUIRED, OPTIONAL, DISABLED File "requests_kerberos\kerberos_.py", line 1, in <module> import kerberos ImportError: No module named kerberos >>> And here is my errors when trying to build the kerberos-1.1.1 package from one of my WIN 7 machines (with python 2.6.5): >python setup.py install --install-lib "C:\tmp" running install running build running build_ext building 'kerberos' extension c:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\BIN\cl.exe /c /nologo /Ox /MD /W3 /GS- /DNDEBUG -IC:\Python26\ArcGIS10.0\include -IC:\Python26\ArcGIS10.0\ PC /Tcsrc/kerberos.c /Fobuild\temp.win32-2.6\Release\src/kerberos.obj '{' is not recognized as an internal or external command, operable program or batch file. cl : Command line warning D9024 : unrecognized source file type ''{'', object fi le assumed cl : Command line warning D9027 : source file ''{'' ignored cl : Command line warning D9024 : unrecognized source file type 'is', object fil e assumed cl : Command line warning D9027 : source file 'is' ignored cl : Command line warning D9024 : unrecognized source file type 'not', object fi le assumed cl : Command line warning D9027 : source file 'not' ignored cl : Command line warning D9024 : unrecognized source file type 'recognized', ob ject file assumed cl : Command line warning D9027 : source file 'recognized' ignored cl : Command line warning D9024 : unrecognized source file type 'as', object fil e assumed cl : Command line warning D9027 : source file 'as' ignored cl : Command line warning D9024 : unrecognized source file type 'an', object fil e assumed cl : Command line warning D9027 : source file 'an' ignored cl : Command line warning D9024 : unrecognized source file type 'internal', obje ct file assumed cl : Command line warning D9027 : source file 'internal' ignored cl : Command line warning D9024 : unrecognized source file type 'or', object fil e assumed cl : Command line warning D9027 : source file 'or' ignored cl : Command line warning D9024 : unrecognized source file type 'external', obje ct file assumed cl : Command line warning D9027 : source file 'external' ignored cl : Command line warning D9024 : unrecognized source file type 'command,', obje ct file assumed cl : Command line warning D9027 : source file 'command,' ignored cl : Command line warning D9024 : unrecognized source file type 'operable', obje ct file assumed cl : Command line warning D9027 : source file 'operable' ignored cl : Command line warning D9024 : unrecognized source file type 'program', objec t file assumed cl : Command line warning D9027 : source file 'program' ignored cl : Command line warning D9024 : unrecognized source file type 'or', object fil e assumed cl : Command line warning D9027 : source file 'or' ignored cl : Command line warning D9024 : unrecognized source file type 'batch', object file assumed cl : Command line warning D9027 : source file 'batch' ignored cl : Command line warning D9024 : unrecognized source file type 'file.', object file assumed cl : Command line warning D9027 : source file 'file.' ignored kerberos.c \src\kerberosbasic.h(17) : fatal error C108 3: Cannot open include file: 'gssapi/gssapi.h': No such file or directory error: command '"c:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\BIN\cl.ex e"' failed with exit status 2 I also have tried one of my WIN 2008 R2 servers (with python 2.7.2), but get a different error: >python.exe "setup.py" install -- install-lib "C:\tmp" running install running build running build_ext building 'kerberos' extension error: Unable to find vcvarsall.bat I think this has to do that these are being built from source and need some sort of C or C++ compiler, whereas most other modules I've installed in the past worked great. Any advise is appreciated! Answer: I managed to fix this problem. 1. Install `$ pip install kerberos-sspi` 2. Download `requests-kerberos` ZIP from GitHub 3. In 'requests-kerberos/kerberos_.py', change the line `import kerberos` to `import kerberos_sspi as kerberos` 4. In 'requirements.txt', delete 'kerberos==1.1.1' 5. Run `$ python setup.py install`. If you want to run `test_requests_kerberos.py` that is in requests-kerberos/ you need to change `import kerberos` with `import kerberos_sspi as kerberos`. Beside that you need to change all occurrences of: with patch.multiple('kerberos', ...) with: with patch.multiple('kerberos_sspi', ...) That worked for me.
How python custom class differ from any other in-built object like list? Question: I m not sure my question title is correct but : My problem is : When I created a new class called **classA** and i did **deepcopy** to another name called **classB** and did **equality and identity test** : Here is my first snippet: Creating class using `type` >>> import copy >>> classA = type('X', (object,), {}) >>> classB = copy.deepcopy(classA) >>> classB is classA True >>> classB == classA True >>> Second snippet: testing on class creating by using keywords 'class': >>> class X(object): pass ... >>> import copy >>> Y = copy.deepcopy(X) >>> Y is X True >>> Y == X True >>> Third snippet: And when i do the same testing on list object: >>> import copy >>> objA = list() >>> objB = copy.deepcopy(objA) >>> objB == objA True >>> objB is objA False >>> Why the first and remaining two are different ? Could someone please explain me ? Answer: It is [documented](http://docs.python.org/2/library/copy.html) behavior: > This module does not copy types like module, method, stack trace, stack > frame, file, socket, window, array, or any similar types. It does “copy” > functions and classes (shallow and deeply), by returning the original object > unchanged; this is compatible with the way these are treated by the pickle > module. As to why it was done that way, presumably it was because people don't have a lot of need for having multiple identical but distinct classes.
Stuck at os.rename can't quite figure out how to tie it in with the rest of my script Question: I am new to programming and python and this is my first program I decided to try and tackle. This loops through my files in the directory that I run it from and takes out the string of text I don't want and leaves me with the file name I would like (in theory). It all works except the problem I am stuck with is that I can not figure out how to get `os.rename` (I think that is what I need to use) to work from inside my loop. I have read up on it but I guess I just don't get how to tie it in. I'm using python 2.7. This is what I have got so far: import os file_count = 0 for files in os.listdir('.'): #Open for loop in the current dir. if files.find('_The_Hype_Machine_') and files.endswith('.128.mp3') : mod_list = list(files) #Turns filenames into a list so they can be edited del(mod_list[-38:-4]) #specifies the piece of string I need taken out of each filename. files =''.join(mod_list) #Turns the list back to a string file_count += 1 updated_file = files.replace('_', ' ') os.rename(files, **"not sure what goes here"**) print updated_file print 'Your modifed MP3 File Count: ', file_count; I could use some direction and Help with understanding if anyone is up for it. Thanks in advance. Answer: I've made a few tweaks to your program, and annotated it with instructional comments: import os # Each time through the following loop, "afile" will take on the next file name # also we can use "enumerate" to give us a file_count as we go (instead # of tracking the count separately) # In general, we shouldn't change a list we're iterating over, so we'll save it off file_list = os.listdir('.') # (as sk4x0r mentioned) for file_count, afile in enumerate(file_list): #Open for loop in the current dir. # using the 'some_string' in some_text is more typical python useage if '_The_Hype_Machine_' in afile and afile.endswith('.128.mp3'): # Now, strings are immutable, so we can't exactly remove the # inside of a string # What we can do is create a brand new string composed # of everything we want to keep new_name = afile[:-38] + afile[-4:] updated_file = new_name.replace('_', ' ') os.rename(afile, updated_file) print updated_file print 'Your modifed MP3 File Count: ', file_count
connect to telnet in python with a quizz as login? Question: I need to connect to a remote server via telnet. To authenticate to the server I have to answer like a 100 questions. So I tried to automate this task in python using telnetlib but the prompt halts without returning any message. here is what I did import telnetlib port = 2002 host = "23.23.190.204" tn = telnetlib.Telnet(host, port) tn.read_until(""" Welcome to EULER! ================= Answer 100 simple questions to authenticate yourself """) print tn.read_all() tn.close() in the command line prompt I get this message Welcome to EULER! ================= Answer 100 simple questions to authenticate yourself then I am getting asked a question if the answer is correct I get the next question till I finished the 100. But in the python program I not getting neither the message nor the questions! what to do? **EDIT:** after setting the debug level for telnet, I get the answer of the server. Could you please explain why is that? tn.set_debuglevel(9) Answer: This is a fake telnet server using netcat (`ncat` from [Nmap](http://nmap.org/)): $ ncat -l 9000 < msg.txt > log.txt listing on port 9000 and passes a file named `msg.txt` (the questions) and log the input into `log.txt` (the answers), it should simulate your server. The file `msg.txt` content: Welcome to EULER! ================= Answer 100 simple questions to authenticate yourself What is your name? How old are you? Do you use Python? the file content in hex (using `hexdump msg.txt`): 00000000: 0A 57 65 6C 63 6F 6D 65 20 74 6F 20 45 55 4C 45 | Welcome to EULE| 00000010: 52 21 0A 3D 3D 3D 3D 3D 3D 3D 3D 3D 3D 3D 3D 3D |R! =============| 00000020: 3D 3D 3D 3D 0A 41 6E 73 77 65 72 20 31 30 30 20 |==== Answer 100 | 00000030: 73 69 6D 70 6C 65 20 71 75 65 73 74 69 6F 6E 73 |simple questions| 00000040: 20 74 6F 20 61 75 74 68 65 6E 74 69 63 61 74 65 | to authenticate| 00000050: 20 79 6F 75 72 73 65 6C 66 0A 57 68 61 74 20 69 | yourself What i| 00000060: 73 20 79 6F 75 72 20 6E 61 6D 65 3F 0A 48 6F 77 |s your name? How| 00000070: 20 6F 6C 64 20 61 72 65 20 79 6F 75 3F 0A 44 6F | old are you? Do| 00000080: 20 79 6F 75 20 75 73 65 20 50 79 74 68 6F 6E 3F | you use Python?| 00000090: 0A | | 00000091; | | notice the new line character, it's `\x0A` or `\n` (it can also be `\x0D\x0A` or `\n\r`). The client: import telnetlib port = 9000 host = "127.0.0.1" tn = telnetlib.Telnet(host, port) r = tn.read_until("""\nWelcome to EULER! ================= Answer 100 simple questions to authenticate yourself\n""") tn.read_until("What is your name?\n") tn.write("foo\n") # The client sends `\n`, notice the server may expects `\n\r`. print("Question 1 answered.") tn.read_until("How old are you?\n") tn.write("100\n") print("Question 2 answered.") tn.read_until("Do you use Python?\n") tn.write("yep\n") print("Question 3 answered.") tn.close() now lets test it, on the client side: $ python client.py Question 1 answered. Question 2 answered. Question 3 answered. $ on the server side, dump the log file content: $ ncat -l 9000 < msg.txt > log.txt $ $ cat log.txt # or `type log.txt` on windows foo 100 yep $ $ hexdump log.txt 00000000: 66 6F 6F 0A 31 30 30 0A 79 65 70 0A |foo 100 yep | 0000000c; $ put it together you should get the idea.
Sending an HTML rich email using python Question: I am trying to send HTML rich email, so far the code is working but the colour formatting i had in html message content is not showing when I check in my mailbox i sent to. So far here is the code : from email.MIMEMultipart import MIMEMultipart from email.MIMEBase import MIMEBase from email.MIMEText import MIMEText from email.Utils import COMMASPACE, formatdate from email import Encoders import smtplib class EMail(object): """ Class defines method to send email of attachment """ def __init__(self, sendto, mailFrom, server, usrname, password, files, debug=False, subjt=None): self.debug = debug self.mailto = sendto self.mailFrom = mailFrom self.smtpserver = server self.EMAIL_PORT = 587 self.usrname = usrname self.password = password self.subject = subjt # self.send(files) def sendMessage(self, msgContent, files): #collect info and prepare email if files: if self.subject == "": #Subject should contains of file attached if len(files) <=3: subjAdd = ','.join(files) if len(files) > 3: subjAdd = ','.join(files[:3]) + '...' self.subject= self.systemLogin() +" sent mail from maya "+ os.path.basename(subjAdd) print "subject: ", self.subject msg = self.prepareMail(self.mailFrom, self.mailto, self.subject, msgContent, files) # connect to server and send email server=smtplib.SMTP(self.smtpserver, port=self.EMAIL_PORT) server.ehlo() server.starttls()#use encrypted SSL mode server.ehlo() # to make starttls work server.login(self.usrname, self.password) server.set_debuglevel(self.debug) try: failed = server.sendmail(From, to, msg.as_string()) except Exception as er: print er finally: server.quit() def prepareMail(self, From, to, subject, msgHTML, attachments): msg = MIMEMultipart() msg['From'] = From msg['To'] = to msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject #The Body message msg.attach(MIMEText(msgHTML, 'html')) msg.attach(MIMEText("Sent from maya by Mini Me")) if attachments: for phile in attachments: #we could check for MIMETypes here part = MIMEBase('application',"octet-stream") part.set_payload(open(phile, "rb").read()) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(phile)) msg.attach(part) return msg and here is the HTML formatted text I am sending, (I have removed the HTML head section it being long due to css) <body class="body_foreground body_background" style="font-size: normal;" > <pre> --- send.py | 4 <span class="ansi32">+</span><span class="ansi31">---</span> 1 file changed, 1 insertion(+), 3 deletions(-) <span class="ansi1">diff --git a/send.py b/send.py</span> <span class="ansi1">index 87126d5..abb1fd8 100644</span> <span class="ansi1">--- a/send.py</span> <span class="ansi1">+++ b/send.py</span> <span class="ansi36">@@ -49,14 +49,12 @@</span> class EMail(object): server.quit() def prepareMail(self, From, to, subject, msgHTML, attachments): <span class="ansi31">- msg = MIMEMultipart('alternative')</span> <span class="ansi32">+</span> <span class="ansi32">msg = MIMEMultipart()</span> msg['From'] = From msg['To'] = to msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject <span class="ansi31">- print msgHTML</span> <span class="ansi31">-</span> #The Body message msg.attach(MIMEText(msgHTML, 'html')) msg.attach(MIMEText("Sent from maya by Mini Me")) -- 1.8.3.4 (Apple Git-47) </pre> </body> </html> it seems only pre tag formatting is working not the css .. why would that be ? Answer: Gmail doesn't support `<style>` blocks. You can see a css support comparison between popular mail clients here: [Guide to CSS support in email](http://www.campaignmonitor.com/css/).
HTTP Server Python: how to test it in local? Question: I have 2 networks on my computer (Wifi network for internet, and local network based on wired cable) with specific mask and IP (this configuration works). I have a Python HTTP server (on my computer) for the local network: or simply >>> python server.py Serving on localhost:8000 You can use this to test GET and POST methods. """ import SimpleHTTPServer import SocketServer import logging import cgi import sys if len(sys.argv) > 2: PORT = int(sys.argv[2]) I = sys.argv[1] elif len(sys.argv) > 1: PORT = int(sys.argv[1]) I = "" else: PORT = 8000 I = "" class ServerHandler(SimpleHTTPServer.SimpleHTTPRequestHandler): def do_GET(self): print "======= GET STARTED =======" logging.warning("======= GET STARTED =======") logging.warning(self.headers) SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self) def do_POST(self): print "======= POST STARTED =======" logging.warning("======= POST STARTED =======") logging.warning(self.headers) form = cgi.FieldStorage( fp=self.rfile, headers=self.headers, environ={'REQUEST_METHOD':'POST', 'CONTENT_TYPE':self.headers['Content-Type'], }) logging.warning("======= POST VALUES =======") for item in form.list: logging.warning(item) logging.warning("\n") SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self) Handler = ServerHandler httpd = SocketServer.TCPServer(("10.0.0.2", PORT), Handler) print "@rochacbruno Python http server version 0.1 (for testing purposes only)" print "Serving at: http://%(interface)s:%(port)s" % dict(interface=I or "localhost", port=PORT) httpd.serve_forever() I just want to try if this server works: from my Google CHrome, I set this URL: 10.0.0.2/?method=1234 And no trace appears on the Python shell... So, my question is: how can I test this Python server from my computer in first (to be sure it works) ? Thank you very much guys for your help Anthony Answer: Ok guys, I found the problem: it was the port number; I changed it to 888 for example and it works now :-) Anthony
Why running a same script in different location cause errors? Question: I try to run a script that's using third party module (completely install by `pip install module`) in Ubuntu 13.10. This script located in NTFS partition. import foo API_KEY = "xxx" api = foo.FOO(APIKEY) and it's return error like $ python test.py Traceback (most recent call last): File "test.py", line 3, in <module> import foo File "/media/path/to/project/test.py", line 6, in <module> api = foo.Foo(API_KEY) AttributeError: 'module' object has no attribute 'Foo' but when I copy a same code to `~/Desktop/test.py` then it's work correctly. Is script's location cause these error or if it's not what's the problem? Answer: Check whether there is `foo.py` file in the directory. If there's one, it could prevent importing the module you want. Issuing following command in both directory will give you the path of foo module: python -c "import foo; print(foo.__file__)" If you find there's unexpected `foo.py`, rename it or remove it. (Make sure there's no `foo.pyc` remain)
Python couldn't insert row to MySQL Question: I'm trying to accomplish following query: sql = "INSERT INTO adr_citydistricts (CityDistrict, CityDistrictRU) VALUES (% (ua) s,% (ru) s);" data = {'ua': 'ukrainian', 'ru': 'russian'} cursor.execute (sql, data) After executing this query, there is no such record in table. If do the same query in SQLyog, record will exists. I've also tried: sql = "INSERT INTO adr_citydistricts (CityDistrict, CityDistrictRU) VALUES ('123 ', '333');" cursor.execute (sql) print sql and there is no row in the table. The console displays : `INSERT INTO adr_citydistricts (CityDistrict, CityDistrictRU) VALUES ('123 ', '333');` Executing this query in SQLyog, normally inserts a row in the table. I've created another table with the same structure. Can someone help me, please? Answer: You need to [`cursor.commit()`](http://dev.mysql.com/doc/connector- python/en/connector-python-api-mysqlconnection-commit.html) to reflect changes. > ### [9.2.3. Method > `MySQLConnection.commit()`](http://dev.mysql.com/doc/connector- > python/en/connector-python-api-mysqlconnection-commit.html) > > This method sends a COMMIT statement to the MySQL server, committing the > current transaction. Since by default Connector/Python does not autocommit, > it is important to call this method after every transaction that modifies > data for tables that use transactional storage engines.
convert list into random list within list python Question: Let us imagine that in python we have list of numbers, like this: [1, 3, 4, 5, 6, 7, 8, 9] What is the simplest possible way to convert this list of numbers into a random series of lists within lists? Like this: [[1, 2, 3], [4], 5, 6, [7, 8], 9] Answer: Using [`random.randint`](http://docs.python.org/3/library/random.html#random.randint): import random def random_series(lst, size=3): start = end = 0 n = len(lst) while end < n: end += random.randint(1, size) if end - start == 1: yield lst[start] else: yield lst[start:end] start = end Example usage: >>> lst = [1, 2, 3, 4, 5, 6, 7, 8, 9] >>> list(random_series(lst)) [[1, 2, 3], 4, 5, [6, 7], [8, 9]] >>> list(random_series(lst)) [[1, 2], [3, 4], [5, 6], 7, 8, 9] >>> list(random_series(lst)) [[1, 2], [3, 4, 5], [6, 7], [8, 9]] >>> list(random_series(lst)) [[1, 2, 3], [4, 5, 6], 7, [8, 9]]
multiprocessing.Queue deadlocks after "reader" process death Question: I've been playing with multiprocessing package and noticed that queue can be deadlocked for reading when: 1. The "reader" process is using [get](http://docs.python.org/2/library/multiprocessing.html#multiprocessing.Queue.get) with _timeout_ > 0: self.queue.get(timeout=3) 2. "reader" dies while [get](http://docs.python.org/2/library/multiprocessing.html#multiprocessing.Queue.get) is blocking due to _timeout_. After that queue is locked forever. ### Application demonstrating the problem I create two child processes "Worker" (putting into queue) and "Receiver" (getting from queue). Also parent process periodically checks if his children [are alive](http://docs.python.org/2/library/multiprocessing.html#multiprocessing.Process.is_alive) and starts new child if needed. #!/usr/bin/env python # -*- coding: utf-8 -*- import multiprocessing import procname import time class Receiver(multiprocessing.Process): ''' Reads from queue with 3 secs timeout ''' def __init__(self, queue): multiprocessing.Process.__init__(self) self.queue = queue def run(self): procname.setprocname('Receiver') while True: try: msg = self.queue.get(timeout=3) print '<<< `{}`, queue rlock: {}'.format( msg, self.queue._rlock) except multiprocessing.queues.Empty: print '<<< EMPTY, Queue rlock: {}'.format( self.queue._rlock) pass class Worker(multiprocessing.Process): ''' Puts into queue with 1 sec sleep ''' def __init__(self, queue): multiprocessing.Process.__init__(self) self.queue = queue def run(self): procname.setprocname('Worker') while True: time.sleep(1) print 'Worker: putting msg, Queue size: ~{}'.format( self.queue.qsize()) self.queue.put('msg from Worker') if __name__ == '__main__': queue = multiprocessing.Queue() worker = Worker(queue) worker.start() receiver = Receiver(queue) receiver.start() while True: time.sleep(1) if not worker.is_alive(): print 'Restarting worker' worker = Worker(queue) worker.start() if not receiver.is_alive(): print 'Restarting receiver' receiver = Receiver(queue) receiver.start() ### How processes tree looks like in _ps_ bash \_ python queuetest.py \_ Worker \_ Receiver ### Console output $ python queuetest.py Worker: putting msg, Queue size: ~0 <<< `msg from Worker`, queue rlock: <Lock(owner=None)> Worker: putting msg, Queue size: ~0 <<< `msg from Worker`, queue rlock: <Lock(owner=None)> Restarting receiver <-- killed Receiver with SIGTERM Worker: putting msg, Queue size: ~0 Worker: putting msg, Queue size: ~1 Worker: putting msg, Queue size: ~2 <<< EMPTY, Queue rlock: <Lock(owner=SomeOtherProcess)> Worker: putting msg, Queue size: ~3 Worker: putting msg, Queue size: ~4 Worker: putting msg, Queue size: ~5 <<< EMPTY, Queue rlock: <Lock(owner=SomeOtherProcess)> Worker: putting msg, Queue size: ~6 Worker: putting msg, Queue size: ~7 Is there any way to bypass this? Using [get_nowait](http://docs.python.org/2/library/multiprocessing.html#multiprocessing.Queue.get_nowait) combined with sleep seems to be some kind of workaround but it does not read the data "as it comes". ### System information $ uname -sr Linux 3.11.8-200.fc19.x86_64 $ python -V Python 2.7.5 In [3]: multiprocessing.__version__ Out[3]: '0.70a1' ### "it just works" solution While writing this question I came up with some silly modification to Receiver class: class Receiver(multiprocessing.Process): def __init__(self, queue): multiprocessing.Process.__init__(self) self.queue = queue def run(self): procname.setprocname('Receiver') while True: time.sleep(1) while True: try: msg = self.queue.get_nowait() print '<<< `{}`, queue rlock: {}'.format( msg, self.queue._rlock) except multiprocessing.queues.Empty: print '<<< EMPTY, Queue rlock: {}'.format( self.queue._rlock) break But it doesn't seem very good to me. Answer: It's probably because *not_empty.release()* from _Queue.get()_ never happends (the proccess has been killed already). Did you try to catch the TERM signal in Receiver and release the Queue mutex before exiting?
how to work with time.strftime in django 1.6 Question: I am one of the new user in django 1.6 but one thing very bad I have noticed in this version of django is that time.strftime("%H:%M:%S") does not working and giving a wrong time in my view . Is there any alternating approach for getting a right time in django view or not ? _**Note : if you type print(time.strftime("%H:%M:%S")) in python 3 you will see a right time but in django 1.6 it is not true_** Thank you. Answer: Maybe you're dealing with UTC time. Convert it to local time before call `strftime`: >>> from django.utils import timezone >>> now = timezone.now() >>> now.strftime('%H:%M:%S') '13:23:52' >>> timezone.localtime(now).strftime('%H:%M:%S') '22:23:52' See [Time zones | Django documentation](https://docs.djangoproject.com/en/1.6/topics/i18n/timezones/).
Python findAll not working on beautifulsoup 3 Question: I am trying to parse a html file and write the results to a csv file. The html file is: <table BORDER='1' CELLSPACING='0' CELLPADDING='0'> <tr> <td><small>15</small></td > <td><small><small>Cat</small></small></td> </tr> <tr> <td><small><small>16</small></small></td> <td><small><small>&nbsp;</small></small></td> </tr> <tr> <td><small>17</small></td > <td><small><small>Dog</small></small></td> </tr> </table> and the code I have atm is: import csv from BeautifulSoup import BeautifulSoup as bs soup = bs (open("Animals.html")) for i in soup.findAll('small'): if "&nbsp;" in i.text: i.string = '-' print soup f = csv.writer(open("Animals.csv", "a")) # Open the output file for writing before the loop trs = soup.findAll('tr') for tr in trs: tds = tr.findAll("td") try: #we are using "try" because the table is not well formatted. This allows the program to continue after encountering an error. id = str(tds[0].get_text()) # This structure isolate the item by its column in the table and converts it into a string. animal = str(tds[1].get_text()) except: print "Bad tr string" continue #This tells the computer to move on to the next item after it encounters an error f.writerow([id, animal]) When I print out the contents of soup after replacing the `%nbsp;` I get: <table BORDER='1' CELLSPACING='0' CELLPADDING='0'> <tr> <td><small>15</small></td > <td><small></small><small>Cat</small></td > </tr> <tr> <td><small><small>16</small></small></td > <td><small></small><small>-</small></td > </tr> <tr> <td><small>17</small></td > <td><small></small><small>Dog</small></td > </tr> </table> But when I look at the .csv file it is empty. However if I change the code to use BeautifulSoup 4, then I can't replace the `&nbsp;` but the results will be saved to the .csv file. The other code that I use is: import csv from bs4 import BeautifulSoup as bs soup = bs (open("Animals.html")) f = csv.writer(open("Animals.csv", "w")) # Open the output file for writing before the loop trs = soup.find_all('tr') for tr in trs: tds = tr.find_all("td") try: #we are using "try" because the table is not well formatted. This allows the program to continue after encountering an error. id = str(tds[0].get_text()) # This structure isolate the item by its column in the table and converts it into a string. animal = str(tds[1].get_text()) except: print "Bad tr string" continue #This tells the computer to move on to the next item after it encounters an error f.writerow([id, animal]) The reason why that one won't do me is because I want the `&nbsp;` to be replaced with `-` and I haven't been able to get that (the find_all()) to work with beautifulsoup 4. What is causing the information to be saved to the csv file and how can I fix it (and/or get it working with beautifulsoup 4)? Answer: BeautifulSoup 4 will convert that 'nbsp;' into a Unicode character \xa0 when the 'soup' is constructed. If you search-and-replace on that unicode character it will work: soup = BeautifulSoup(html) for i in soup.find_all('small'): i.string.replace_with(i.string.replace(u'\xa0', '-')) The syntax there is a little verbose. This is because `i.string` is not a string, but a `bs4.element.NavigableString`. You can't edit these in place with a straightforward `i.string.replace(...)`; instead you must call beautifulsoup's own `replace_with` method. `replace_with` accepts just one argument, so we have to generate the new version of the string and pass it in. For this we can use Python's built in `replace` method for strings, to strip out the u'\xa0' characters and replace them with '-' Alternatively, you could just use regular expressions on the original HTML. If all you need is to replace all `&nbsp;` instances with a `-`: import re newhtml = re.sub(r'&nbsp;', '-', html) Though you could customise this further so it only affects `<small>` tags - let me know if you'd like this added to the answer.
Python 2.6 ImportError: No module named argparse Question: I'm trying to run git-cola from Red Hat Enterprise Linux Server release 6.5 and receive: Traceback (most recent call last): File "....../bin/git-cola", line 24, in <module> from argparse import ArgumentParser ImportError: No module named argparse I think I have all of the required packages installed: * git-1.7.1-3.el6_4.1.x86_64 * python-2.6.6-51.el6.x86_64 * PyQt4.x86_64 0:4.6.2-9.el6 * /usr/lib/python2.6/site-packages/argparse-1.2.1-py2.6.egg I read in other blogs that there may be a problem with Python 2.6 and may need to move to 2.7. Additional information - @iljau noticed that argparse is in a 32 bit lib, while the rest of python is in 64 bits. I would have expected that: easy_install argparse would have sorted this out and installed the 64 bit version. Additional question: Does anyone know how to install the 64 bit version of argparse. It is not apparent to me from searching the internet. I will continue looking. I installed argparse by downloading the tar file and python setup.py install However, it still installed it in the lib rather than lib64 path - and it looks like a 64 bit install. So something else must be the problem in referencing argparse properly. I don't know Python enough to debug it, but I suspect that git-cola needs some work for Python 2.6. Answer: As a simple solution copy `argparse.py` from <https://code.google.com/p/argparse/source/browse/argparse.py> to your project folder. * * * And indeed, for Python 2.6 `argparse` needs to be installed separately. From: <https://pypi.python.org/pypi/argparse> > As of Python >= 2.7 _.._ the argparse module is maintained within the Python > standard library. For users who still need to support Python < 2.7 _.._ it > is also provided as a separate package, which _.._ also supports older > Python versions. But even after you install `argparse`, it may refuse to work for some mysterious reasons. Additional debugging tips may be found in answers and comments to question ["ImportError: No module named argparse"](http://stackoverflow.com/q/15093444/2419207).
How do I import a text file with no separators in python, using numpy? Question: How do I import a file with no separators? I have a file named `text.txt` which contains 2 lines of text: > 00000000011100000000000000000000 > 00000000011111110000000000000000 When I use > f = open("text.txt") > data = np.loadtxt(f) I get > [ 1.11000000e+22 1.11111100e+22] Using `sep=""` changes nothing. I would like to get this result, in the form of many single digit integers: > [ [00000000011100000000000000000000] > [00000000011111110000000000000000] ] Any help is appreciated. **UPDATE:** Thank you all for the great answers and the many valid solutions to an awkward question. Answer: I'll take the statement "I would like to get this result, in the form of many single digit integers:" literally, and ignore the format of the sample that follows it (which appears to be just two integers, rather than many single digit integers). You can do that with [`genfromtxt`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.genfromtxt.html) by using the arguments `delimiter=1` and `dtype=int`. When `delimiter` is an integer or a sequence of integers, the values are interpreted as the field widths of a file containing fixed-width fields of data. For example: In [15]: genfromtxt('text.txt', delimiter=1, dtype=int) Out[15]: array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]])
No module named _graphviz Question: I installed graphviz and pygraphviz, when I open a cmd and type python import _graphviz _graphviz can be imported, but when I run a C++ program which will invoke a .py file, there is a line in this .py file which is import pygraphviz as pgv Then it will not be able to import _graphviz, it shows the following info: Traceback (most recent call last): File "E:\project\graph\analysis\x64\Debug\gengraph.py", line 1, in <module> import pygraphviz as pgv File "C:\Program Files\Python27\lib\site-packages\pygraphviz\__init__.py", lin e 54, in <module> from agraph import AGraph, Node, Edge, Attribute, ItemAttribute File "C:\Program Files\Python27\lib\site-packages\pygraphviz\agraph.py", line 20, in <module> import graphviz as gv File "C:\Program Files\Python27\lib\site-packages\pygraphviz\graphviz.py", lin e 7, in <module> import _graphviz ImportError: No module named _graphviz Can you help me, any advice is welcome, thank you! Answer: What system are you using? I spent a good 4 hours trying to figure it out on Windows but ended up migrating my project to Ubuntu. From what I've learned, it's caused by the program not finding the pygraphviz file. It searches in this sequence on Windows: 1,register; 2,PATH; 3,folders. Some methods availables: **Find the block in setup.py for register and skip it.** **Rename folder of pygraphviz installation(remove blanks) and move it to a path without blanks** In Ubuntu, you could simply "sudo easy-install pygraphviz" which worked for me.
feature_importances_ showing up as NoneType in ExtraTreesClassifier :TypeError: 'NoneType' object is not iterable Question: I am trying to select important features (or at least understand which features explain more variabilty) for a given dataset. Towards this I use both ExtraTreesClassifier and GradientBoostingRegressor - and then use :- clf = ExtraTreesClassifier(n_estimators=10,max_features='auto',random_state=0) # stops after 10 estimation passes, right ? clf.fit(x_train, y_train) feature_importance=clf.feature_importances_ # does NOT work - returns NoneType for feature_importance Post this **I am really interested** in plotting them(for visual representation) - or even preliminary, just **looking at the relative order of importance and the corresponding indices** # Both of these do not work as the feature_importance is of NoneType feature_importance = 100.0 * (feature_importance / feature_importance.max()) indices = numpy.argsort(feature_importance)[::-1] What I found puzzling was - if I were to use GradientBoostingRegressor as below, I do get the feature_importance and the indices thereof. What am I doing wrong ? #Works with GradientBoostingRegressor params = {'n_estimators': 100, 'max_depth': 3, 'learning_rate': 0.1, 'loss': 'lad'} clf = GradientBoostingRegressor(**params).fit(x_train, y_train) clf.fit(x_train, y_train) feature_importance=clf.feature_importances_ _other info_ : I have 12 independent vars(x_train) and one label var(y_train)) with multiple values (say 4,5,7) and type(x_train) is and type(feature_importance) is _Acknowledgments_ : Some elements are borrowed from this post <http://www.tonicebrian.com/2012/11/05/training-gradient-boosting-trees-with- python/> Answer: When initializing an [ExtraTreeClassifier](http://scikit- learn.org/stable/modules/generated/sklearn.tree.ExtraTreeClassifier.html), there is an option `compute_importances` which defaults to `None`. In other words, you need to initialize `ExtraTreeClassifier` as clf = ExtraTreesClassifier(n_estimators=10,max_features='auto',random_state=0,compute_importances=True) so that it will compute the feature importance. Where as for [GradientBoostedRegressor](http://scikit- learn.org/stable/modules/generated/sklearn.ensemble.GradientBoostingRegressor.html), there is no such option and feature importance will always be computed.
path.py not recognized in eclipse Question: I installed the path package: easy_install path.py running ipython I can validly run: from path import path Eclipse (after restart) does not recognize this (unresolved import "path"). It also will not auto-complete class members and functions. Any idea how to solve this? Answer: Accroding to [PyDev FAQ](http://pydev.org/faq.html#PyDevFAQ- IhavealibraryinstalledandPyDevdoesnotfindit): > ## I have a library installed and PyDev does not find it > > Well, problems have been reported on Mac and Linux, and the main reason > seems to be symlinks. PyDev will only find extensions that are 'really' > below the python install directory. This happens because the 'less common > denominator', which in this case is windows, does not have symlinks. A > workaround to this problem includes **manually adding the given folder > installation to the pythonpath** or **changing the installation of the > package to be under the site-packages folder.**
Using Flask-Mail asynchronously results in "RuntimeError: working outside of application context" Question: I am trying to send some mail asynchronously (based on the code in [The Flask Mega-Tutorial, Part XI: Email Support](http://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-xi- email-support)). However, I get the following error about working outside an application context. How do I fix this problem? Traceback (most recent call last): File "C:\Users\Primoz\Desktop\RecycleFlaskServer\recycleserver\helpers.py", line 17, in send_async_email mail.send(msg) File "C:\Python33\lib\site-packages\flask_mail-0.9.0-py3.3.egg\flask_mail.py", line 434, in send message.send(connection) File "C:\Python33\lib\site-packages\flask_mail-0.9.0-py3.3.egg\flask_mail.py", line 369, in send connection.send(self) File "C:\Python33\lib\site-packages\flask_mail-0.9.0-py3.3.egg\flask_mail.py", line 173, in send email_dispatched.send(message, app=current_app._get_current_object()) File "C:\Python33\lib\site-packages\werkzeug-0.9.4-py3.3.egg\werkzeug\local.py", line 297, in _get_current_object return self.__local() File "C:\Python33\lib\site-packages\flask-0.10.1-py3.3.egg\flask\globals.py", line 34, in _find_app raise RuntimeError('working outside of application context') RuntimeError: working outside of application context from flask import Flask from flask.ext.mail import Mail app = Flask(__name__) app.config.from_object('recycleserver.settings') mail = Mail(app) def async(f): def wrapper(*args, **kwargs): thr = Thread(target = f, args = args, kwargs = kwargs) thr.start() return wrapper @async def send_async_email(msg): mail.send(msg) def send_simple_mail(subject, sender, to_who, text_body="", html_body=""): msg = Message(subject=subject,sender=sender, recipients=to_who) msg.body = text_body msg.html = html_body send_async_email(msg) Answer: The code should run in an app context. Add `with app.app_context()`: @async def send_async_email(msg): with app.app_context(): mail.send(msg)
Is there an NSCoding-like facility in Python? Question: As an iOS developer recently experimenting with Python, I'm curious to know if there's something like `NSCoding` that would allow me to implement a method or a pair of methods which would define how my objects can be automatically saved to disk, much like `NSCoding`. I've found [this repo](https://code.google.com/p/jsstep/source/browse/trunk/framework/python/jsstep/foundation/protocols/NSCoding.py?r=38) but I'm not sure if it's part of a larger framework, which I'd rather not incorporate into my (small) project. Is there something that ships with Python? Anything popular out there that deals with object persistence in a primitive yet powerful way? Answer: The `pickle` module is used for serializing objects. <http://docs.python.org/2/library/pickle.html> You can usually just use it as-is, but if you need to define how objects should be serialized, you can override the special methods, `__getstate__` and `__setstate__` import cPickle as pickle # faster implementation path = 'test.dat' obj = ('Hello, world!', 123, {'x': 0}) # save to disk with open(path, 'wb') as fp: pickle.dump(obj, fp) # load from disk with open(path, 'rb') as fp: obj = pickle.load(fp) print obj
Searching for equivalent of FileNotFoundError in Python 2 Question: I created a class named Options. It works fine but not not with Python 2. And I want it to work on both Python 2 and 3. The problem is identified: FileNotFoundError doesn t exist in Python 2. But if I use IOError it doesn t work in Python 3 Changed in version 3.3: EnvironmentError, IOError, WindowsError, VMSError, socket.error, select.error and mmap.error have been merged into OSError. What should I do ???(Please do not discuss my choice of portability, I have reasons.) Here s the code: #!/usr/bin/python #-*-coding:utf-8* #option_controller.py #Walle Cyril #25/01/2014 import json import os class Options(): """Options is a class designed to read, add and change informations in a JSON file with a dictionnary in it. The entire object works even if the file is missing since it re-creates it. If present it must respect the JSON format: e.g. keys must be strings and so on. If something corrupted the file, just destroy the file or call read_file method to remake it.""" def __init__(self,directory_name="Cache",file_name="options.json",imported_default_values=None): #json file self.option_file_path=os.path.join(directory_name,file_name) self.directory_name=directory_name self.file_name=file_name #self.parameters_json_file={'sort_keys':True, 'indent':4, 'separators':(',',':')} #the default data if imported_default_values is None: DEFAULT_INDENT = 2 self.default_values={\ "translate_html_level": 1,\ "indent_size":DEFAULT_INDENT,\ "document_title":"Titre"} else: self.default_values=imported_default_values def read_file(self,read_this_key_only=False): """returns the value for the given key or a dictionary if the key is not given. returns None if it s impossible""" try: text_in_file=open(self.option_file_path,'r').read() except FileNotFoundError:#not 2.X compatible text_in_file=""#if the file is not there we re-make one with default values if text_in_file=="":#same if the file is empty self.__insert_all_default_values() text_in_file=open(self.option_file_path,'r').read() try: option_dict=json.loads(text_in_file) except ValueError: #if the json file is broken we re-make one with default values self.__insert_all_default_values() text_in_file=open(self.option_file_path,'r').read() option_dict=json.loads(text_in_file) if read_this_key_only: if read_this_key_only in option_dict: return option_dict[read_this_key_only]# else: #if the value is not there it should be written for the next time if read_this_key_only in self.default_values: self.add_option_to_file(read_this_key_only,self.default_values[read_this_key_only]) return self.default_values[read_this_key_only] else: #impossible because there is not default value so the value isn t meant to be here return None else: return option_dict def add_option_to_file(self,key,value):#or update """Adds or updates an option(key and value) to the json file if the option exists in the default_values of the object.""" option_dict=self.read_file() if key in self.default_values: option_dict[key]=value open(self.option_file_path,'w').write(\ json.dumps(option_dict,sort_keys=True, indent=4, separators=(',',':'))) def __insert_all_default_values(self): """Recreate json file with default values. called if the document is empty or non-existing or corrupted.""" try: open(self.option_file_path,'w').write(\ json.dumps(self.default_values,sort_keys=True, indent=4, separators=(',',':'))) except FileNotFoundError: os.mkdir(self.directory_name)#Create the directory if os.path.isdir(self.directory_name):#succes self.__insert_all_default_values() else: print("Impossible to write in %s and file %s not found" % (os.getcwd(),self.option_file_path)) #demo if __name__ == '__main__': option_file_object=Options() print(option_file_object.__doc__) print(option_file_object.read_file()) option_file_object.add_option_to_file("","test")#this should have no effect option_file_object.add_option_to_file("translate_html_level","0")#this should have an effect print("value of translate_html_level:",option_file_object.read_file("translate_html_level")) print(option_file_object.read_file()) Answer: If `FileNotFoundError` isn't there, define it: try: FileNotFoundError except NameError: FileNotFoundError = IOError Now you can catch `FileNotFoundError` in Python 2 since it's really `IOError`. Be careful though, `IOError` has other meanings. In particular, any message should probably say "file could not be read" rather than "file not found."