text
stringlengths
226
34.5k
pylab scilimits not working Question: I'm trying to make a simple graph in with python 2.7's matplotlib module. The problem I'm having is that the function `ticklabel_format(style='sci',axis='y',scilimits=(-3.0e-6,-1.0e-6))` is not applying the given scilimit values. I've tried turning off the autoscaling before and after the plot command If I use the values in the `ylim` function it does work, but it won't be in scientific notation. Any help would be hot. from pylab import * v=[-1,-2,-3,-4,-5] i=[-1.57e-6,-1.8e-6,-1.97e-6,-2.18e-6,-2.30e-6] plot(v,i,"bo") autoscale(enable=False) xlim(-6,0) #ylim(-3e-6,-1e-6) ticklabel_format(style='sci',axis='y',scilimits=(-3.0e-6,-1.0e-6)) xlabel("Voltage/(V)") ylabel("Current/(A)") title("Current vs Voltage \n(Schottky Reverse Bias)") grid() show() Answer: Try: gca().ticklabel_format(style='sci',axis='y',scilimits=(0,0)) ylim(-3e-6,-1e-6)
Resolve Substitutions in RestructuredText Question: I want to take the following restructured text snippet that contains a [substitution definition](http://docutils.sourceforge.net/docs/ref/rst/restructuredtext.html#substitution- definitions): text = """ |python| .. |python| image:: python.jpg """ And resolve the definitions so the substitution text is displayed: resolved_text = """ .. image:: python.jpg """ Is there a function or utility in docutils or another module that can do this? Answer: `docutils` provides [publisher functions](http://docutils.sourceforge.net/docs/api/publisher.html#publisher- convenience-functions) to use docutils as a library. So using `docutils.core.publish_string` could be an option for your usecase. In [90]: from docutils import core In [91]: text = '|python|\n\n.. |python| image:: python.jpg\n' In [92]: print core.publish_string(text) <document source="<string>"> <paragraph> <image alt="python" uri="python.jpg"> <substitution_definition names="python"> <image alt="python" uri="python.jpg"> By default `puplish_string` uses a `pseudoxml` writer, which you can see in the output. However if you really want to have the plain text output from your question, you need a custom writer class derived from `docutils.writers.Writer`. I'm not sure how to implement this, maybe the `Sphinx` [TextWriter](https://bitbucket.org/birkenfeld/sphinx/src/8ec0b3a74e791e59dfee2d484380c34881530a89/sphinx/writers/text.py?at=default#cl-133) could be a starting point. Seems that if you really only need the simple substitution, using `replace` on your text would be a simpler solution, if you need more complicated things, implement this using docutils is complicated, too.
Python BeautifulSoup Extract specific URLs Question: Is it possible to get only specific URLs? Like: <a href="http://www.iwashere.com/washere.html">next</a> <span class="class">...</span> <a href="http://www.heelo.com/hello.html">next</a> <span class="class">...</span> <a href="http://www.iwashere.com/wasnot.html">next</a> <span class="class">...</span> Output should be only URLs from `http://www.iwashere.com/` like, output URLs: http://www.iwashere.com/washere.html http://www.iwashere.com/wasnot.html I did it by string logic. Is there any direct method using BeautifulSoup? Answer: You can match multiple aspects, including using a regular expression for the attribute value: import re soup.find_all('a', href=re.compile('http://www\.iwashere\.com/')) which matches (for your example): [<a href="http://www.iwashere.com/washere.html">next</a>, <a href="http://www.iwashere.com/wasnot.html">next</a>] so any `<a>` tag with a `href` attribute that has a value that starts with the string `http://www.iwashere.com/`. You can loop over the results and pick out just the `href` attribute: >>> for elem in soup.find_all('a', href=re.compile('http://www\.iwashere\.com/')): ... print elem['href'] ... http://www.iwashere.com/washere.html http://www.iwashere.com/wasnot.html To match all relative paths instead, use a negative look-ahead assertion that tests if the value does _not_ start with a schem (e.g. `http:` or `mailto:`), or a double slash (`//hostname/path`); any such value _must_ be a relative path instead: soup.find_all('a', href=re.compile(r'^(?!(?:[a-zA-Z][a-zA-Z0-9+.-]*:|//))'))
Python not calling an external program part 3 Question: I have been having problems trying to run an external program from a python program that was generated from a trigger in a postgres 9.2 database. The trigger works. It writes to a file. I had tried just running the external program but the permissions would not allow it to run. I was able to create a folder (using os.system(“mkdir”) ). The owner of the folder is NETWORK SERVICE. I need to run a program called sdktest. When I try to run it no response happens so I think that means that the python program does not have enough permissions (with an owner of NETWORK SERVICE) to run it. I have been having my program copy files that it needs into that directory so they would have the correct permissions and that has worked to some degree but the program that I need to run is the last one and it is not running because it does not have enough permissions. My python program runs a C++ program called PG_QB_Connector which calls sdktest. Is there any way I can change the owner of the process to be a “normal” owner? Is there a better way to do this? Basically I just need to have this C++ program have eniough perms to run correctly. BTW, when I run the C++ program by hand, the line that runs the sdktest program runs correctly, however, when I run it from the postgres/python it does not do anything... I have Windows 7, python 3.2. The other 2 questions that I asked about this are located [here](http://stackoverflow.com/questions/14278109/python-not- calling-external-program) and [here](http://stackoverflow.com/questions/14364928/python-not-calling-an- external-program-part-2) The python program: CREATE or replace FUNCTION scalesmyone (thename text) RETURNS int AS $$ a=5 f = open('C:\\JUNK\\frompython.txt','w') f.write(thename) f.close() import os os.system('"mkdir C:\\TEMPWITHOWNER"') os.system('"mkdir C:\\TEMPWITHOWNER\\addcustomer"') os.system('"copy C:\\JUNK\\junk.txt C:\\TEMPWITHOWNER\\addcustomer"') os.system('"copy C:\\BATfiles\\junk6.txt C:\\TEMPWITHOWNER\\addcustomer"') os.system('"copy C:\\BATfiles\\run_addcust.bat C:\\TEMPWITHOWNER\\addcustomer"') os.system('"copy C:\\Workfiles\\PG_QB_Connector.exe C:\\TEMPWITHOWNER\\addcustomer"') os.system('"copy C:\\Workfiles\\sdktest.exe C:\\TEMPWITHOWNER\\addcustomer"') import subprocess return_code = subprocess.call(["C:\\TEMPWITHOWNER\\addcustomer\\PG_QB_Connector.exe", '"hello"']) $$ LANGUAGE plpython3u; The C++ program that is called from the python program and calls sdktest.exe is below command = "copy C:\\Workfiles\\AddCustomerFROMWEB.xml C:\\TEMPWITHOWNER\\addcustomer\\AddCustomerFROMWEB.xml"; system(command.c_str()); //everything except for the qb file is in my local folder command = "C:\\TEMPWITHOWNER\\addcustomer\\sdktest.exe \"C:\\Users\\Public\\Documents\\Intuit\\QuickBooks\\Company Files\\Shain Software.qbw\" C:\\TEMPWITHOWNER\\addcustomer\\AddCustomerFROMWEB.xml C:\\TEMPWITHOWNER\\addcustomer\\outputfromsdktestofaddcust.xml"; system(command.c_str()); Answer: It sounds like you want to invoke a command-line program from within a PostgreSQL trigger or function. A usually-better alternative is to have the trigger send a `NOTIFY` and have a process with a PostgreSQL connection `LISTEN`ing for notifications. When a notification comes in, the process can start your program. This is the approach I would recommend; it's a lot cleaner and it means your program doesn't have to run under PostgreSQL's user ID. See [`NOTIFY`](http://www.postgresql.org/docs/current/static/sql-notify.html) and [`LISTEN`](http://www.postgresql.org/docs/current/static/sql-listen.html). If you really need to run commands from inside Pg: You can use [`PL/Pythonu`](http://www.postgresql.org/docs/current/static/plpython.html) with `os.system` or `subprocess.check_call`; [`PL/Perlu`](http://www.postgresql.org/docs/current/static/plperl.html) with `system()`; etc. All these can run commands from inside Pg if you need to. You can't invoke programs directly from PostgreSQL, you need to use one of the 'untrusted' (meaning fully privileged, not sandboxed) procedural languages to invoke external executables. PL/TCL can probably do it too. **Update** : Your Python code as shown above has several problems: * Using `os.system` in Python to copy files is just wrong. Use the `shutil` library: <http://docs.python.org/3/library/shutil.html> to copy files, and the simple `os.mkdir` command to create directories. * The double-layered quoting looks wrong; didn't you mean to quote only each argument not the whole command? You should be using `subprocess.call` instead of `os.system` anyway. * Your final `subprocess.call` invocation appears OK, but fails to check the error code so you'll never know if it went wrong; you should use `subprocess.check_call` instead. The C++ code also appears to fail to check for errors from the `system()` invocations so you'll never know if the command it runs fails. Like the Python code, copying files in C++ by using the `copy` shell command is generally wrong. Microsoft Windows provides the [`CopyFile`](http://msdn.microsoft.com/en- us/library/windows/desktop/aa363851%28v=vs.85%29.aspx) function for this; equivalents or alternatives exist on other platforms and you can use portable- but-less-efficient stream copying too.
Python's NLTK documentation Question: Where can I found the offline documentation for NLTK? It's not in usr/share/doc, where I mostly find docs of Python modules. And there is no nltk-doc package that can be installed. Answer: Okay so it definitely doesn't come with any package. However it can be built. So first: sudo apt-get install python-epydoc This is needed to build the documentation. Then I made this script to automate the build process for you: #!/bin/bash NLTK_VERSION=$(python -c 'import nltk; print nltk.__version__') NLTK_URL=$(python -c 'import nltk; print nltk.__url__') EPYDOC_OPTS = --name=nltk --navlink="nltk ${NLTK_VERSION}"\ --url=${NLTK_URL} --inheritance=listed --debug # Rebuild from scratch [[ -e ~/python-nltk-docs ]] && rm -rf ~/python-nltk-docs mkdir ~/python-nltk-docs epydoc ${EPYDOC_OPTS} -o ~/python-nltk-docs /usr/share/pyshared/nltk This will drop html docs into `~/python-nltk-docs` for your viewing. I basically pulled this together from their [doc Makefile](https://code.google.com/p/nltk/source/browse/trunk/nltk/doc/Makefile).
Running django-celery on windows. EOFError Question: I am using windows 7 64 bit. I installed the latest versions of billiard, django-celery,and kombu. I included: import djcelery djcelery.setup_loader() to my project setting.py When I run the following from the root of my project: python manage.py celeryd -l info I get the following message (this is the last part of the message): File "c:\python27\lib\pickle.py", line 562, in save_tuple save(element) File "c:\python27\lib\pickle.py", line 286, in save f(self, obj) # Call unbound method with explicit self File "c:\python27\lib\pickle.py", line 548, in save_tuple save(element) File "c:\python27\lib\pickle.py", line 306, in save rv = reduce(self.proto) File "c:\python27\lib\site-packages\celery\app\base.py", line 412, in __reduce__ (self.__class__, self.Pickler) + self.__reduce_args__(), File "c:\python27\lib\site-packages\celery\app\base.py", line 422, in __reduce_args__ else self.conf._pickleable_changes()) File "c:\python27\lib\site-packages\celery\app\utils.py", line 77, in _pickleable_changes R.update(d) TypeError: 'LazySettings' object is not iterable C:\sources\tourtle>Traceback (most recent call last): File "<string>", line 1, in <module> File "c:\python27\lib\site-packages\billiard\forking.py", line 530, in main self = load(from_parent) File "c:\python27\lib\pickle.py", line 1378, in load return Unpickler(file).load() File "c:\python27\lib\pickle.py", line 858, in load dispatch[key](self) File "c:\python27\lib\pickle.py", line 880, in load_eof raise EOFError EOFError I installed MinGW and added distutils.cfg to c:\MinGW\bin but it did not help Thanks Answer: Check this discussion on github: <https://github.com/celery/django-celery/issues/228> A workaround is that you change celery/app/base.py (lines 418-419) in the way asksol proposes there: from: conf = (self.conf.changes if _forking._forking_is_enabled else self.conf._pickleable_changes())' to: conf = (self.conf.changes if _forking._forking_is_enabled else {}) It should then work fine
Can't run Popen.communicate() twice. (Python subprocess module) Question: Can anyone explain why I get this error if I run the communicate function twice? For instance from subprocess import * SVN=Popen('which svn', shell=True, stdout=PIPE) print SVN.communicate()[0] returns "/usr/bin/svn" but running communicate again... print SVN.communicate()[0] returns... Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 746, in communicate stdout = _eintr_retry_call(self.stdout.read) File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 478, in _eintr_retry_call return func(*args) ValueError: I/O operation on closed file Answer: Because the "file", which is actually the stdout of the program being invoked, has been closed. This means you have already read all the output in the previous `communicate()`, so calling it again can never produce anything.
Square root of number python Question: Here's my code: import cmath root = (cmath.sqrt(25)) print (root) raw_input() The problem i face is the result of root is 5+0j which is undesirable i only want the square root. How can i fix this? Answer: Use the `math` module instead of the `cmath` module; the latter is for complex numbers only: >>> import math >>> print math.sqrt(25) 5.0 For what it's worth, the `cmath` result is correct, _if you expected a complex number_. You could take just the `.real` component of the result, but since there is a regular floating point equivalent in the `math` module there is no point in having your computer do the extra work.
beautifulsoup "list object has no attribute" error Question: I'm trying to scrape temperatures from a [weather site](http://www.wunderground.com/history/airport/KAPA/2013/3/1/DailyHistory.html) using the following: import urllib2 from BeautifulSoup import BeautifulSoup f = open('airport_temp.tsv', 'w') f.write("Location" + "\t" + "High Temp (F)" + "\t" + "Low Temp (F)" + "\t" + "Mean Humidity" + "\n" ) eventually parse from http://www.wunderground.com/history/airport/\w{4}/2012/\d{2}/1/DailyHistory.html for x in range(10): locationstamp = "Location " + str(x) print "Getting data for " + locationstamp url = 'http://www.wunderground.com/history/airport/KAPA/2013/3/1/DailyHistory.html' page = urllib2.urlopen(url) soup = BeautifulSoup(page) location = soup.findAll('h1').text locsent = location.split() loc = str(locsent[3,6]) hightemp = soup.findAll('nobr')[6].text htemp = hightemp.split() ht = str(htemp[1]) lowtemp = soup.findAll('nobr')[10].text ltemp = lowtemp.split() lt = str(ltemp[1]) avghum = soup.findAll('td')[23].text f.write(loc + "\t|" + ht + "\t|" + lt + "\t|" + avghum + "\n" ) f.close() Unfortunately, I get an error saying: Getting data for Location 0 Traceback (most recent call last): File "airportweather.py", line 18, in <module> location = soup.findAll('H1').text AttributeError: 'list' object has no attribute 'text' I've looked through BS and Python documentation, but am still pretty green, so I couldn't figure it out. Please help this newbie! Answer: The `.findAll()` method returns a _list_ of matches. If you wanted _one_ result, use the `.find()` method instead. Alternatively, pick out a specific element like the rest of the code does, or loop over the results: location = soup.find('h1').text or locations = [el.text for el in soup.findAll('h1')] or location = soup.findAll('h1')[2].text
Python replace function [replace once] Question: I need help with a program I'm making in Python. Assume I wanted to replace every instance of the word `"steak"` to `"ghost"` (just go with it...) but I also wanted to replace every instance of the word `"ghost"` to `"steak"` at the same time. The following code does not work: s="The scary ghost ordered an expensive steak" print s s=s.replace("steak","ghost") s=s.replace("ghost","steak") print s it prints: `The scary steak ordered an expensive steak` What I'm trying to get is `The scary steak ordered an expensive ghost` Answer: I'd probably use a regex here: >>> import re >>> s = "The scary ghost ordered an expensive steak" >>> sub_dict = {'ghost':'steak','steak':'ghost'} >>> regex = '|'.join(sub_dict) >>> re.sub(regex, lambda m: sub_dict[m.group()], s) 'The scary steak ordered an expensive ghost' Or, as a function which you can copy/paste: import re def word_replace(replace_dict,s): regex = '|'.join(replace_dict) return re.sub(regex, lambda m: replace_dict[m.group()], s) Basically, I create a mapping of words that I want to replace with other words (`sub_dict`). I can create a regular expression from that mapping. In this case, the regular expression is `"steak|ghost"` (or `"ghost|steak"` \-- order doesn't matter) and the regex engine does the rest of the work of finding non- overlapping sequences and replacing them accordingly. * * * _Some possibly useful modifications_ * `regex = '|'.join(map(re.escape,replace_dict))` \-- Allows the regular expressions to have special regular expression syntax in them (like parenthesis). This escapes the special characters to make the regular expressions match the literal text. * `regex = '|'.join(r'\b{0}\b'.format(x) for x in replace_dict)` \-- make sure that we don't match if one of our words is a substring in another word. In other words, change `he` to `she` but not `the` to `tshe`.
How do I insert a row in my google fusion table using Python Question: I am working on a project and part of it involves inserting rows in to a Google Fusion Table for the Project from a python script. I have spent the last couple days trying to figure out just how to do that and I am officially confused. My research seems to indicate that I need to use Oauth 2.0 to access the API. In doing so I can successfully get an access token but I can't seem to successfully get a refresh token. I'm not sure if this is going to hamper my ability to successfully integrate access to my Fusion Table with my Python code. The second problem I am having is that I don't really understand how exactly to code inserting a row in my table. Most of the material I have found on it is from the deprecated Fusion Tables SQL API and I don't fully understand the new way of doing it. I'm a beginner at this sort of thing and any direction to help me is very much appreciated! Edit: So the code I have working so far looks like this: client_id = "<client_i>" client_secret = "<client_secret>" table_id = "<table_id>" access_token = "" refresh_token = "<refresh_token>" # the refresh token is used to request a new access token data = urllib.urlencode({ 'client_id': client_id, 'client_secret': client_secret, 'refresh_token': refresh_token, 'grant_type': 'refresh_token'}) request = urllib2.Request( url='https://accounts.google.com/o/oauth2/token', data=data) request_open = urllib2.urlopen(request) response = request_open.read() request_open.close() tokens = json.loads(response) access_token = tokens['access_token'] # Read the table request_read = urllib2.Request( url='https://www.google.com/fusiontables/api/query?%s' % \ (urllib.urlencode({'access_token': access_token, 'sql': 'SELECT * FROM table_id'}))) request_open = urllib2.urlopen(request_read) response = request_open.read() request_open.close() print response And my code for trying to insert a new row into my table: date = str(datetime.now().date()) time = str(datetime.now().time()) query = 'INSERT INTO table_id (Date,Time,Saskatoon,Regina,MeadowLake)VALUES(date,time,60.01,60.02,59.99)' data = urllib2.Request( url='https://www.google.com/fusiontables/api/query?%s' % \ (urllib.urlencode({'access_token': access_token, 'sql': query}))) request_open = urllib2.urlopen(data) When I run this i get > HTTP Error 400: HTTP GET can only be used for select queries. I am know I'm supposed to be making a POST not a GET for the INSERT, I'm just not sure what needs to change in my code for that to happen. Sorry for being a noob. 2ND EDIT: Sorry for making this longer but I feel it is pertinent to show where I've gotten so far. I switched to the library requests and things have gotten somewhat easier however I still haven't successfully made a POST. My new code for importing rows is as follows: def importRows(self): print 'IMPORT ROWS' date = str(datetime.now().date()) time = str(datetime.now().time()) data = {'Date': date, 'Time': time, 'Saskatoon': '60.01', 'Regina': '59.95'} url = 'https://www.googleapis.com/upload/fusiontables/v1/tables/%s/import/%s' % \ (tableid, self.params) # self.params is access token importRow = requests.post(url, params=data) print importRow.status_code print importRow.text Which gives me 400 { "error": { "errors": [ { "domain": "fusiontables", "reason": "badImportInputEmpty", "message": "Content is empty." } ], "code": 400, "message": "Content is empty." } } Answer: > If your application needs offline access to a Google API, then the request > for an authorization code should include the access_type parameter, where > the value of that parameter is offline. <https://developers.google.com/accounts/docs/OAuth2WebServer#offline> Then, to obtain an access token using the refresh token you send a POST request including `grant_type` with value `refresh_token`. Basically, the way SQL works is you send POST requests using a subset of SQL statements `https://www.googleapis.com/fusiontables/v1/query?sql=STATEMENT_HERE` Refer to <https://developers.google.com/fusiontables/docs/v1/reference/query> <https://developers.google.com/fusiontables/docs/v1/sql-reference> Edit: Since you are using `urllib2` without a data parameter, it defaults to GET. To fix this you should either use another HTTP library that allows for explicitly specifying method (like [`requests`](http://docs.python- requests.org/en/latest/) or `httplib`) or do something like this: query = "INSERT INTO %s(EXAMPLE_COL1,EXAMPLE_COL2) VALUES"\ "('EXAMPLE_INFO1','EXAMPLE_INFO2')" % table_id # Single quotes opener = urllib2.build_opener(urllib2.HTTPHandler) request = urllib2.Request('https://www.google.com/fusiontables/api/query?%s' % \ (urllib.urlencode({'access_token': access_token, 'sql': query})), headers={'Content-Length':0}) # Manually set length to avoid 411 error request.get_method = lambda: 'POST' # Change HTTP request method response = opener.open(request).read() print response Important to notice: 1. Monkey patch the method to do what we want (POST with an empty body) otherwise we would receive `HTTP Error 400: HTTP GET can only be used for SELECT queries`. 2. Manually specify that we do not have a body (`Content-Length` is `0`) otherwise we would receive `HTTP Error 411: Length Required`. 3. Must use **double quotes with single quotes inside** or **escape the inner quotes** to submit strings via the query. In other words, `"INSERT INTO %s(EXAMPLE_COL1,EXAMPLE_COL2) VALUES(EXAMPLE_INFO1,EXAMPLE_INFO2)" % table_id` does not work. If we tried to use the previous line we would get something like `HTTP Error 400: Parse error near 'SOME_STRING' (line X, position Y)` See for info on changing method with urllib2: [Is there any way to do HTTP PUT in python](http://stackoverflow.com/questions/111945/is-there-any-way-to-do-http- put-in-python)
Reading stderr of subprocess while it is executing Question: I'd like to read what is written to stderr by a subprocess while it is executing. However, when I use this script that I've written, stderr does not seem to have anything for me to read until the subprocess has exited. #!/usr/bin/env python2 import sys from subprocess import Popen, PIPE, STDOUT if len(sys.argv) < 2: print "Please provide a command" sys.exit(1) sub = Popen(sys.argv[1:], stdout=PIPE, stderr=STDOUT) for i, line in enumerate(sub.stdout): sys.stdout.write("%d: %s" % (i, line)) **edit:** Ok, I've gotten closer now. If I specify the number of bytes to read it overcomes the buffering. #!/usr/bin/env python2 import sys from subprocess import Popen, PIPE, STDOUT if len(sys.argv) < 2: print "Please provide a command" sys.exit(1) sub = Popen(sys.argv[1:], stdout=PIPE, stderr=STDOUT) i = 0 while sub.poll() is None: line = sub.stdout.read(64) line.strip("\b") sys.stdout.write("%d: %s\n" % (i, line)) i += 1 Snippet of output: 58: 86 q=21.0 size= 4541841kB time=00:00:22.08 bitrate=1685014.2kbi frame= 567 fps= 86 q=22.0 size= 4543667kB time=00:00:2 frame= 621 fps= 87 q=20.0 sizs/s frame= 4545352kB time=00:00:26.11 bitrate=1425939.2kbits/s 62: = 686 fps= 90 q=12.0 size= 4546970kB time=00:00:28.89 bitrate=1 frame= 758 fps= 93 q=25.0 size= 4548534kB t frame= 794 fps= 92 bitrate=1168185.5kbits/s 65: q=27.0 size= 4550901kB time=00:00:33.40 bitrate=1115897.0kbits/ frame= 827 fps= 91 q=27.0 size= 4552324kB time=00:00:34.7 frame= 857 fps= 89 q=26.0 size= frame= 254kB time=00:00:36.12 bitrate=1032874.9kbits/s 69: 892 fps= 88 q=25.0 size= 4556598kB time=00:00:37.36 bitrate=9988 frame= 948 fps= 89 q=19.0 size= 4558565kB time= frame= 1006 fps= 90 q=19937320.4kbits/s 72: .0 size= 4560139kB time=00:00:42.16 bitrate=885880.0kbits/s 73: frame= 1060 fps= 91 q=19.0 size= 4561958kB time=00:00:44.49 bitr frame= 1122 fps= 93 q=18.0 size= 4563460 frame= 1173 fps=0:47.08 bitrate=793898.4kbits/s It looks like my problem now is that ffmpeg is using backspace characters or similar to mess with stdout. Not sure what's happening here. Answer: I suggest to use [sh](https://pypi.python.org/pypi/sh) module. It is very nice piece of software which wraps subprocesses in python and gives you pythonic, beautiful interface which you will love. Look at the [docs](http://amoffat.github.com/sh/). If you really do not want `sh` module, use [communicate](http://docs.python.org/2/library/subprocess.html#subprocess.Popen.communicate) method of `Popen`
How can I install packages on my heroku app? Question: I have an app that makes use of shortuuid (<https://pypi.python.org/pypi/shortuuid/0.1>) that is working fine locally when I run it with runapp.py: import os from paste.deploy import loadapp from waitress import serve if __name__ == "__main__": port = int(os.environ.get("PORT", 5000)) app = loadapp('config:production.ini', relative_to='.') serve(app, host='0.0.0.0', port=port) It does not work, however, when I try and run it with ../bin/pserve development.ini. I get the error: import error: no module named shortuuid. When I push it to heroku I get the same error. I have installed shortuuid into my virtual environment where my app is run and can only conclude that the absence of this installation on heroku is whats causing the problem. I have tried replacing the development.ini code with the production.ini code and it still does not work so I assume its something else (maybe the import os line on runapp.py?) Answer: I usually create a `requirements.txt` file that contains the packages: Flask==0.9 Jinja2==2.6 Werkzeug==0.8.3 distribute==0.6.27 wsgiref==0.1.2 Flask-Cache==0.10.0 gunicorn==0.17.2 You can create that file with `pip`: $ pip freeze > requirements.txt
Argument types differ in normal and reflected operator overload (__sub__ / __rsub__) Question: How do I get access to the properties of an numpy array after passing it through an righthand operator like `__rsub__`? I wrote a very simple class in python that defines the two functions: class test(object): def __sub__(self, other): return other def __rsub__(self, other): return other Basically they should do the same. The left-hand operator `__sub__` works as expected, but it seems that the numpy array is stripped off its properties on the right-hand operator from skimage import data from skimage.color import rgb2gray lena = data.lena() grayLena = rgb2gray(lena) t = test() ## overloaded - operator left_hand = t - grayLena print left_hand # Output: #array([[ 0.60802863, 0.60802863, 0.60779059, ..., 0.64137412, # 0.57998235, 0.46985725], # [ 0.60802863, 0.60802863, 0.60779059, ..., 0.64137412, # 0.57998235, 0.46985725], # [ 0.60802863, 0.60802863, 0.60779059, ..., 0.64137412, # 0.57998235, 0.46985725], # ..., # [ 0.13746353, 0.13746353, 0.16881412, ..., 0.37271804, # 0.35559529, 0.34377725], # [ 0.14617059, 0.14617059, 0.18730588, ..., 0.36788784, # 0.37292549, 0.38467529], # [ 0.14617059, 0.14617059, 0.18730588, ..., 0.36788784, # 0.37292549, 0.38467529]]) right_hand = grayLena - t print right_hand # Output: # array([[0.6080286274509803, 0.6080286274509803, 0.6077905882352941, ..., # 0.6413741176470589, 0.5799823529411765, 0.4698572549019608], # [0.6080286274509803, 0.6080286274509803, 0.6077905882352941, ..., # 0.6413741176470589, 0.5799823529411765, 0.4698572549019608], # [0.6080286274509803, 0.6080286274509803, 0.6077905882352941, ..., # 0.6413741176470589, 0.5799823529411765, 0.4698572549019608], # ..., # [0.1374635294117647, 0.1374635294117647, 0.1688141176470588, ..., # 0.3727180392156863, 0.35559529411764706, 0.34377725490196076], # [0.1461705882352941, 0.1461705882352941, 0.18730588235294118, ..., # 0.3678878431372549, 0.37292549019607846, 0.3846752941176471], # [0.1461705882352941, 0.1461705882352941, 0.18730588235294118, ..., # 0.3678878431372549, 0.37292549019607846, 0.3846752941176471]], dtype=object) So the difference between both operations is that `__rsub__` receives an array of dtype=object. If I would just set the dtype of this array, everything would work fine. However, it works only with the return value, outside of `__rsub__`. Inside my `__rsub__` I get only rubbish, that I cannot convert back, namely if I do npArray = np.array(other, dtype=type(other)) I get a 1D array of the type (floats in my case). But for some reason, the shape information is lost. Has anyone done this or an idea how I can access the original properties of the array (shape and type)? Answer: I am not sure of what the exact control flow inside the `ndarray`'s machinery is, but what's happening in your case is more or less clear: What `ndarray` is delegating to your object's `__rsub__` method is not the overall substraction operation, but the substraction of your object from each of the items in the array. And apparently when it has to delegate an operation to the object's methods, the return type is set to `object` regardless of what gets returned. You can check it with this slight modification of your code: class test(object): def __sub__(self, other): return other def __rsub__(self, other): return other if other != 1 else 666 In [11]: t = test() In [12]: t - np.arange(4) Out[12]: array([0, 1, 2, 3]) In [13]: np.arange(4) - t Out[13]: array([0, 666, 2, 3], dtype=object) I don't think there is an easy way of overriding this behaviour. You could try [making `test` a subclass of `ndarray`](http://docs.scipy.org/doc/numpy/user/basics.subclassing.html#array- wrap-for-ufuncs) with a high `__array_priority__` and abuse a little the `__array_wrap__` method: class test(np.ndarray): __array_priority__ = 100 def __new__(cls): obj = np.int32([1]).view(cls) return obj def __array_wrap__(self, arr, context) : if context is not None : ufunc = context[0] args = context[1] if ufunc == np.subtract : if self is args[0] : return args[1] elif self is args[1] : return args[0] return arr And now: >>> t = test() >>> np.arange(4) - t array([0, 1, 2, 3]) >>> t - np.arange(4) array([0, 1, 2, 3]) But: >>> np.arange(4) + t test([1, 2, 3, 4]) >>> t + np.arange(4) test([1, 2, 3, 4]) It is a little bit wasteful, because we are doing the operation of adding the `1` inside `t` to every value in the array, and then silently discarding it, but I can't think of any way of overriding that.
syntax error on production server where running bin/python setup.py test-q Question: When I attempt to do the following on a production server: $ sudo -u vretnet ../bin/python setup.py test -q It will show the following error, how should I fix this? Or could it be that my development.ini went wrong? Traceback (most recent call last): File "setup.py", line 34, in <module> paster_plugins=['pyramid'], File "/opt/python3.2.3/lib/python3.2/distutils/core.py", line 148, in setup dist.run_commands() File "/opt/python3.2.3/lib/python3.2/distutils/dist.py", line 917, in run_commands self.run_command(cmd) File "/opt/python3.2.3/lib/python3.2/distutils/dist.py", line 936, in run_command cmd_obj.run() File "/home/vretnet/env/lib/python3.2/site-packages/distribute-0.6.34-py3.2.egg/setuptools/command/test.py", line 138, in run self.with_project_on_sys_path(self.run_tests) File "/home/vretnet/env/lib/python3.2/site-packages/distribute-0.6.34-py3.2.egg/setuptools/command/test.py", line 118, in with_project_on_sys_path func() File "/home/vretnet/env/lib/python3.2/site-packages/distribute-0.6.34-py3.2.egg/setuptools/command/test.py", line 164, in run_tests testLoader = cks File "/opt/python3.2.3/lib/python3.2/unittest/main.py", line 123, in __init__ self.parseArgs(argv) File "/opt/python3.2.3/lib/python3.2/unittest/main.py", line 191, in parseArgs self.createTests() File "/opt/python3.2.3/lib/python3.2/unittest/main.py", line 198, in createTests self.module) File "/opt/python3.2.3/lib/python3.2/unittest/loader.py", line 132, in loadTestsFromNames suites = [self.loadTestsFromName(name, module) for name in names] File "/opt/python3.2.3/lib/python3.2/unittest/loader.py", line 132, in <listcomp> suites = [self.loadTestsFromName(name, module) for name in names] File "/opt/python3.2.3/lib/python3.2/unittest/loader.py", line 91, in loadTestsFromName module = __import__('.'.join(parts_copy)) File "/home/vretnet/env/ECommerce/ecommerce/__init__.py", line 1, in <module> from pyramid.config import Configurator File "/home/vretnet/env/lib/python3.2/site-packages/pyramid-1.4-py3.2.egg/pyramid/config/__init__.py", line 10, in <module> from webob.exc import WSGIHTTPException as WebobWSGIHTTPException File "/home/vretnet/env/lib/python3.2/site-packages/WebOb-1.2.3-py3.2.egg/webob/exc.py", line 1115, in <module> from paste import httpexceptions File "/home/vretnet/env/lib/python3.2/site-packages/Paste-1.7.5.1-py3.2.egg/paste/httpexceptions.py", line 634 except HTTPException, exc: ^ SyntaxError: invalid syntax Answer: It is Python 3, you should write `as`: except HTTPException as exc:
How to perform an assignment inside a lambda function Question: Python 2.7.1 I would like to understand why I can't do the following which seems like a sensible thing to do def do_stuff(): # return a function which takes a map as an argument and puts a key in there f = lambda map: map['x'] = 'y' #compilation error return f x = do_stuff() map = {} x(map) print map['x'] I can have that lambda function to be somethign simpler something like `f = lambda map: os.path.exists` however I cannot get it to change the map. Can someone tell me how I can achieve this? If this is not possible at all why? Answer: You can't use assignment in an expression, it is a statement. A `lambda` can only contain _one_ expression, and statements are not included. You _can_ assign to the map though, by using the [`operator.setitem()` function](http://docs.python.org/2/library/operator.html#operator.setitem) instead: import operator lambda map: operator.setitem(map, 'x', 'y')
scipy.misc module has no attribute imread? Question: I am trying to read an image with scipy. However it does not accept the `scipy.misc.imread` part. What could be the cause of this? >>> import scipy >>> scipy.misc <module 'scipy.misc' from 'C:\Python27\lib\site-packages\scipy\misc\__init__.pyc'> >>> scipy.misc.imread('test.tif') Traceback (most recent call last): File "<pyshell#11>", line 1, in <module> scipy.misc.imread('test.tif') AttributeError: 'module' object has no attribute 'imread' Answer: You need to install [PIL](http://www.pythonware.com/products/pil/). From [the docs](http://docs.scipy.org/doc/scipy/reference/misc.html) on `scipy.misc`: > Note that the Python Imaging Library (PIL) is not a dependency of SciPy and > therefore the pilutil module is not available on systems that don’t have PIL > installed. After installing PIL, I was able to access `imread` as follows: In [1]: import scipy.misc In [2]: scipy.misc.imread Out[2]: <function scipy.misc.pilutil.imread>
Python PIL library not working image.thumbnail(size, Image.ANTIALIAS) Question: I'm trying to debug this script in python from PIL import Image, ImageChops, ImageOps I've searched all over the problem seems to be "image.thumbnail(size, Image.ANTIALIAS)" here. Anyone have any ideas? Thanks image = Image.open(f_in) print "got here" image.thumbnail(size, Image.ANTIALIAS) print "cannot get here" image_size = image.size if pad: thumb = image.crop( (0, 0, size[0], size[1]) ) offset_x = max( (size[0] - image_size[0]) / 2, 0 ) offset_y = max( (size[1] - image_size[1]) / 2, 0 ) thumb = ImageChops.offset(thumb, offset_x, offset_y) else: thumb = ImageOps.fit(image, size, Image.ANTIALIAS, (0.5, 0.5)) thumb.save(f_out) **EDIT** Thanks for the quick answer Mark. I figured it out. I had to: pip uninstall PIL sudo apt-get install libjpeg8-dev pip install PIL I didn't have libjpeg installed. Not sure why I didn't get an error. Answer: If the program never gets to the line "cannot get here" then the problem is that `thumbnail` is throwing an exception. You didn't mention that in the question though, it should have generated an error. PIL uses lazy image loading - in the `open` call it might open the file, but it doesn't actually try to read the whole thing in. If your file is corrupt or in the wrong format it will fail once you try to do something with the image, as `thumbnail` is doing.
how to check which compiler was used to build Python Question: Is there a way to tell which compiler was used to build a `Python` install on a specific linux machine? I tried using `ldd` on the `Python` dynamic libraries [1], but I didn't manage to understand if it was compiled with `gcc` or Intel compiler. [1] $ ldd libpython2.7.so.1.0 linux-vdso.so.1 => (0x00007fff4a5ff000) libpthread.so.0 => /lib64/libpthread.so.0 (0x00002ab8de8ae000) libdl.so.2 => /lib64/libdl.so.2 (0x00002ab8deac9000) libutil.so.1 => /lib64/libutil.so.1 (0x00002ab8deccd000) libm.so.6 => /lib64/libm.so.6 (0x00002ab8deed1000) libc.so.6 => /lib64/libc.so.6 (0x00002ab8df154000) /lib64/ld-linux-x86-64.so.2 (0x0000003b9a400000) Answer: I think you have it in `sys.version`: >>> import sys >>> print(sys.version) 3.2.3 (default, Oct 19 2012, 19:53:16) [GCC 4.7.2] It should also usually tell you when you start the interactive interpreter: wim@wim-zenbook:~$ python3 Python 3.2.3 (default, Oct 19 2012, 19:53:16) [GCC 4.7.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>>
HTML Email Rendered Incorrectly When Carriage Returns Are Not Used Question: The following python script generates an email file that can be piped to sendmail. When I send this to my gmail account, lines 25, 50, and 51 are not what I would have expected. All other lines appear as expected. import sys print "From:[email protected]" print "To:[email protected]" print "Subject: test no carriage return" print "MIME-Version: 1.0" print "Content-Disposition: inline;" print "Content-Type: text/html" sys.stdout.write ("<html>" ) count = 1 while ( count < 55): # output without a carriage return sys.stdout.write( "<tr><td>test" + str(count) + " no carriage returns!</td>") count = count + 1 sys.stdout.write ("</html>") In the email I would expect this for lines 25,50,51: test25 no carriage returns! test50 no carriage returns! test51 no carriage returns! instead, this is rendered: test25 no carriage retur! ns! test50 no ca! rriage returns! test51 no carriage returns! test52 no carriage returns! If I change the output to use `print` instead of `stdout`, then the email displays as expected. I have also tried this in an MS Outlook with the same effect. What is the reasoning for the unexpected result when carriage returns are not used? Answer: Not sure if it is a typo, but for one thing you are not closing your row. You are missing a: </tr> As well as opening and closing table tags.
How to use a python context manager inside a generator Question: In python, should with-statements be used inside a generator? To be clear, I am not asking about using a decorator to create a context manager from a generator function. I am asking whether there is an inherent issue using a with-statement as a context manager inside a generator as it will catch `StopIteration` and `GeneratorExit` exceptions in at least some cases. Two examples follow. A good example of the issue is raised by Beazley's example (page 106). I have modified it to use a with statement so that the files are explicitly closed after the yield in the opener method. I have also added two ways that an exception can be thrown while iterating the results. import os import fnmatch def find_files(topdir, pattern): for path, dirname, filelist in os.walk(topdir): for name in filelist: if fnmatch.fnmatch(name, pattern): yield os.path.join(path,name) def opener(filenames): f = None for name in filenames: print "F before open: '%s'" % f #f = open(name,'r') with open(name,'r') as f: print "Fname: %s, F#: %d" % (name, f.fileno()) yield f print "F after yield: '%s'" % f def cat(filelist): for i,f in enumerate(filelist): if i ==20: # Cause and exception f.write('foobar') for line in f: yield line def grep(pattern,lines): for line in lines: if pattern in line: yield line pylogs = find_files("/var/log","*.log*") files = opener(pylogs) lines = cat(files) pylines = grep("python", lines) i = 0 for line in pylines: i +=1 if i == 10: raise RuntimeError("You're hosed!") print 'Counted %d lines\n' % i In this example, the context manager successfully closes the files in the opener function. When an exception is raised, I see the trace back from the exception, but the generator stops silently. If the with-statement catches the exception why doesn't the generator continue? When I define my own context managers for use inside a generator. I get runtime errors saying that I have ignored a `GeneratorExit`. For example: class CManager(object): def __enter__(self): print " __enter__" return self def __exit__(self, exctype, value, tb): print " __exit__; excptype: '%s'; value: '%s'" % (exctype, value) return True def foo(n): for i in xrange(n): with CManager() as cman: cman.val = i yield cman # Case1 for item in foo(10): print 'Pass - val: %d' % item.val # Case2 for item in foo(10): print 'Fail - val: %d' % item.val item.not_an_attribute This little demo works fine in case1 with no exceptions raised, but fails in case2 where an attribute error is raised. Here I see a `RuntimeException` raised because the with statement has caught and ignored a `GeneratorExit` exception. Can someone help clarify the rules for this tricky use case? I suspect it is something I am doing, or not doing in my `__exit__` method. I tried adding code to re-raise `GeneratorExit`, but that did not help. Answer: from the [Data model entry for `object.__exit__`](http://docs.python.org/2/reference/datamodel.html#object.__exit__) > If an exception is supplied, and the method wishes to suppress the exception > (i.e., prevent it from being propagated), it should return a true value. > Otherwise, the exception will be processed normally upon exit from this > method. In your `__exit__` function, you're returning `True` which will suppress _all_ exceptions. If you change it to return `False`, the exceptions will continue to be raised as normal (with the only difference being that you guarantee that your `__exit__` function gets called and you can make sure to clean up after yourself) For example, changing the code to: def __exit__(self, exctype, value, tb): print " __exit__; excptype: '%s'; value: '%s'" % (exctype, value) if exctype is GeneratorExit: return False return True allows you to do the right thing and not suppress the `GeneratorExit`. Now you _only_ see the attribute error. Maybe the rule of thumb should be the same as with any Exception handling -- **only intercept Exceptions if you know how to handle them**. Having an `__exit__` return `True` is on par (maybe slightly worse!) than having a bare except: try: something() except: #Uh-Oh pass * * * Note that when the `AttributeError` is raised (and not caught), I believe that causes the reference count on your generator object to drop to 0 which then triggers a `GeneratorExit` exception within the generator so that it can clean itself up. Using my `__exit__`, play around with the following two cases and hopefully you'll see what I mean: try: for item in foo(10): print 'Fail - val: %d' % item.val item.not_an_attribute except AttributeError: pass print "Here" #No reference to the generator left. #Should see __exit__ before "Here" and g = foo(10) try: for item in g: print 'Fail - val: %d' % item.val item.not_an_attribute except AttributeError: pass print "Here" b = g #keep a reference to prevent the reference counter from cleaning this up. #Now we see __exit__ *after* "Here"
python webdriver os window Question: I need to upload a file using Python and Selenium. When I click the upload HTML element a "File Upload" window is opened and the click() method does not return since it waits to fully load the page. Therefore I cannot continue using pywinauto code to control the window. The first method clicks the HTML element (an img) to upload a new file: def add_file(self): return self.selenium.find_element(By.ID, "add_file").click() and the second method is using pywinauto to type the path to the file and then click open def upload(self): from pywinauto import application app = application.Application() app.connect_(title_re = "File Upload") app.file_upload.TypeKeys("C:\\Path\\To\\FIle") app.file_upload.Open.Click() How can I force add_file method to return and to be able to run the upload method? Answer: Solve it. There was an iframe dealing with the upload but was hidden and didn't see it in the first place. The iframe contains an input of type file also hidden. To solve it make the iframe visible using javascript: selenium.execute_script("document.getElementById('iframe_id').style.display = 'block';") then switch to the iframe and make the input visible also: selenium.switch_to_frame(0) selenium.execute_script("document.getElementById('input_field_id').type = 'visible';") and simply send the path to the input: selenium.find_element(By.ID, 'input_field_id').send_keys("path\\\\to\\\\file") For windows use 4 '\\\\\\\' as path separator.
Python iterator that iterates a function Question: So I must make the following function -> iterate. On first call it should return identity, on second func, on third func.func. Any idea how to do it? I tried looking at the **iter** and **next** method buf failed: ( >>> def double(x): return 2 * x >>> i = iterate(double) >>> f = next(i) >>> f(3) 3 >>> f = next(i) >>> f(3) 6 >>> f = next(i) >>> f(3) 12 >>> f = next(i) >>> f(3) 24 Answer: Something like this perhaps: >>> import functools >>> def iterate(fn): def repeater(arg, _count=1): for i in range(_count): arg = fn(arg) return arg count = 0 while True: yield functools.partial(repeater, _count=count) count += 1 >>> i = iterate(double) >>> f, f2, f3, f4 = next(i), next(i), next(i), next(i) >>> f(3), f2(3), f3(3), f4(3) (3, 6, 12, 24) >>> f(3), f2(3), f3(3), f4(3) (3, 6, 12, 24) So you write a function that calls the original function the number of times specified as a parameter and you pre-bind the count parameter.
Read Excel Files and Only Use Specific Files Question: in my past questions, I've stated that I'm new to python. I've only used it once for work. And yet again, there's a small project I have to do for work. I have to read an excel file, and in that excel file, there are 3 columns (col1, col2, col3). There are about 100 rows. col1 has 2 values A and B. col2 has values ranging from ONLY 1 - 10. col3, there are plenty of different values. But I want my python program to look at each distinct value in col1, and then at each distinct value in col2, and then calculate the avg of all the corresponding values of col3. Hopefully, the output can look something like this: A - 1 = 2.3 A - 2 = 6.2 A - 3 = 5.7 etc. etc. B - 1 = 3.5 B - 2 = 4.1 B - 3 = 8.1 etc. etc. I know, it's a lot to ask, but I've done this so far: import xlrd #import package #opening workbook and reading first sheet book = xlrd.open_workbook('trend.xls') sheet = book.sheet_by_index(0) #print sheet name, number of rows and columns #print sheet.name #print sheet name #print sheet.nrows #print number of rows #print sheet.ncols #print number of colums #print cellname along with value in for loop for row_index in range(sheet.nrows): for col_index in range(sheet.ncols): print xlrd.cellname(row_index,col_index),'-', print sheet.cell(row_index,col_index).value It started printing all the values within each cell, along with the name and such. But then I realized it's not doing what it's supposed to really be doing. And I can't find a proper tutorial on how to do this. If any of you have any suggestions, I'll appreciate it very much. Thank you so much! Answer: Try this: import xlrd book = xlrd.open_workbook('trend.xls') sheet = book.sheet_by_index(0) unique_combinations = {} for row_index in range(sheet.nrows): cell_1 = sheet.cell(row_index, 0) cell_2 = sheet.cell(row_index, 1) cell_3 = sheet.cell(row_index, 2) unique_combo = (cell_1.value, int(cell_2.value)) if unique_combinations.has_key(unique_combo): unique_combinations[unique_combo].append(cell_3.value) else: unique_combinations[unique_combo] = [cell_3.value] for k in unique_combinations.keys(): values = unique_combinations[k] average = sum(values ) / len(values ) print '%s - %s = %s' % (k[0], k[1], average)
WindowsError: [Error 193] %1 is not a valid Win32 application in Python Question: I wish to import [liblas](http://www.liblas.org/tutorial/python.html) module in Python 2.7 on window 64bit. If I import the module with IDLE (Python GUI) I have no problem. If I use [PyScripter](https://code.google.com/p/pyscripter/downloads/detail?name=PyScripter-v2.5.3-x64-Setup.exe&can=2&q=) "PyScripter-v2.5.3-x64-Setup.exe" I get this error message. >>> import liblas Traceback (most recent call last): File "<interactive input>", line 1, in <module> File "C:\Python27\lib\site-packages\liblas\__init__.py", line 2, in <module> from core import get_version File "C:\Python27\lib\site-packages\liblas\core.py", line 138, in <module> las = ctypes.CDLL(os.path.join(local_dlls, lib_name)) File "C:\Python27\Lib\ctypes\__init__.py", line 365, in __init__ self._handle = _dlopen(self._name, mode) WindowsError: [Error 193] %1 is not a valid Win32 application I have used liblas in PyScripter many times without problem and right now I can load all standard modules (e.g.: numpy, GDAL, etc.), but tonight (I need to finish an analysis!!!) I have this inconvenience. Answer: Please make sure to have Python 2.7 64b edition :) or even though you are working on 64b OS, use the x86 (AKA 32b) edition of PyScripter **Edit 1 (following comments exchange w/ Gianni)** One should verify his/her _entire_ Python process "composed" from same entities in the sense of 32b/64b builds (e.g. if your Python interpreter is 32b one, then it must use C types coming from C dll Python extensions which were compiled as 32b dlls). In our example (liblas) one should go to `C:\Python27\lib\site- packages\liblas` , find the extension dll and see its type via [dumpbin](http://www.mohid.com/wiki/index.php?title=Dumpbin) , here is some picture for demonstration : ![enter image description here](http://i.stack.imgur.com/yKWpD.jpg)
How to selectively import module in python? Question: I have several different modules, and I need to import one of them depending on different situations, for example: if check_situation() == 1: import helper_1 as helper elif check_situation() == 2: import helper_2 as helper elif ... ... else: import helper_0 as helper these helpers contain same dictionaries `dict01`, `dict02`, `dict03`...but have different values to be called in different situations. But this has some problems: 1. import sentences are all written in the top of a file, but `check_situation()` function here needs prerequisites so that it's now far from top. 2. more than 1 file needs this helper module, so it's hard and ugly to use this kind of import. So, how to re-arrange these helpers? Answer: You can use `__import__()`, it accepts a string and returns that module: helper=__import__("helper_{0}".format(check_situation())) example : In [10]: mod=__import__("{0}math".format(raw_input("enter 'c' or '': "))) enter 'c' or '': c #imports cmath In [11]: mod.__file__ Out[11]: '/usr/local/lib/python2.7/lib-dynload/cmath.so' In [12]: mod=__import__("{0}math".format(raw_input("enter 'c' or '': "))) enter 'c' or '': In [13]: mod.__file__ Out[13]: '/usr/local/lib/python2.7/lib-dynload/math.so' As pointed out by @wim and from python3.x docs on `__import__()`: > Import a module. Because this function is meant for use by the Python > interpreter and not for general use it is better to use > `importlib.import_module()` to programmatically import a module.
How can I further profile and optimize this string tokenization function? Question: Feel free to skip my long-winded explanation if looking at the source code is easier! So I've written a function to tokenize strings of text. In the simplest case, it takes a string like `It's a beautiful morning` and returns a list of tokens. For the preceding example, the output would be `['It', "'", 's', ' ', 'a', ' ', 'beautiful', ' ', 'morning']`. This is achieved with the first two lines of the function: separators = dict.fromkeys(whitespace + punctuation, True) tokens = [''.join(g) for _, g in groupby(phrase, separators.get)] The thing to notice here is that `It's` get's split into `["It", "'", "s"]`. In most cases, this is not a problem, but sometimes it is. For this reason, I added the `stop_words` kwarg, which takes a set of strings that are to be "un- tokenized". For example: >>> tokenize("It's a beautiful morning", stop_words=set("It's")) >>> ["It's", , ' ', 'a', ' ', 'beautiful', ' ', 'morning'] This "un-tokenization" works by means of a sliding-window that moves across the list of tokens. Consider the schema below. The window is depicted as `[]` Iteration 1: ['It', "'",] 's', ' ', 'a', ' ', 'beautiful', ' ', 'morning' Iteration 2: 'It', ["'", 's',] ' ', 'a', ' ', 'beautiful', ' ', 'morning' Iteration 3: 'It', "'", ['s', ' ',] 'a', ' ', 'beautiful', ' ', 'morning' At each iteration, the strings contained in the window are joined and checked against the contents of `stop_words`. If the window reaches the end of the token list and no match is found, then the window's size increases by 1. Thus: Iteration 9: ['It', "'", 's',] ' ', 'a', ' ', 'beautiful', ' ', 'morning' Here we have a match, so the entire window is replaced with a single element: its contents, joined. Thus, at the end of iteration 9, we obtain: "It's", ' ', 'a', ' ', 'beautiful', ' ', 'morning' _Now_ , we have to start all over again in case this new token, when combined it's neighbors, forms a stop word. The algorithm sets the window size back to 2 and continues on. **The entire process stops at the end of the iteration in which the window-size is equal to the length of the token list.** This recursion is the source of my algorithm's inefficiency. For small strings with few untokenizations, it works very quickly. However, the computational time seems to grow exponentially with the number of untokenizations and the overall length of the original string. Here is the full source code for the function: from itertools import groupby, tee, izip from string import punctuation, whitespace def tokenize(phrase, stop_words=None): separators = dict.fromkeys(whitespace + punctuation, True) tokens = [''.join(g) for _, g in groupby(phrase, separators.get)] if stop_words: assert isinstance(stop_words, set), 'stop_words must be a set' window = 2 # Iterating over single tokens is useless while window <= len(tokens): # "sliding window" over token list iters = tee(tokens, window) for i, offset in izip(iters, xrange(window)): for _ in xrange(offset): next(i, None) # Join each window and check if it's in `stop_words` for offset, tkgrp in enumerate(izip(*iters)): tk = ''.join(tkgrp) if tk in stop_words: pre = tokens[0: offset] post = tokens[offset + window + 1::] tokens = pre + [tk] + post window = 1 # will be incremented after breaking from loop break window += 1 return tokens And here are some hard numbers to work with (the best I could do, in any case). >>> import cProfile >>> strn = "it's a beautiful morning." >>> ignore = set(["they're", "we'll", "she'll", "it's", "we're", "i'm"]) >>> cProfile.run('tokenize(strn * 100, ignore=ignore)') cProfile.run('tokenize(strn * 100, ignore=ignore)') 57534203 function calls in 15.737 seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 1 10.405 10.405 15.737 15.737 <ipython-input-140-6ef74347708e>:1(tokenize) 1 0.000 0.000 15.737 15.737 <string>:1(<module>) 1 0.000 0.000 0.000 0.000 {built-in method fromkeys} 899 0.037 0.000 0.037 0.000 {itertools.tee} 900 0.000 0.000 0.000 0.000 {len} 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects} 365450 1.459 0.000 1.459 0.000 {method 'join' of 'str' objects} 57166950 3.836 0.000 3.836 0.000 {next} From this I gathered that the majority of execution time was taking place in my function's scope. As stated above, I _suspect_ that the incessant resetting of `window` is responsible for the inefficiency, but I'm not sure how to diagnose this any further. **My questions are as follows:** 1. How can I further profile this function to ascertain whether it is, indeed, the resetting of `window` that is responsible for the long execution time? 2. What can I do to improve performance? Thanks very much in advance! Answer: I might have misunderstood the problem, but it seems like just searching for the ignored words before spliting will solve the issue: def tokenize(phrase, stop_words=()): stop_words = '|'.join(re.escape(x) + r'\b' for x in stop_words) other = '\s+|\w+|[^\s\w]+' regex = stop_words + '|' + other if stop_words else other return re.findall(regex, phrase) As pointed by Michael Anderson, you should add `\b` to avoid matching parts of words Edit: the new regex will separate whitespace from punctuation.
Match href value with a regular expression Question: My input is similar to this: <a href="link">text</a> <a href="correctLink">See full summary</a> From this string i want to get only `correctLink` (the link that has _See full summary_ as text) . I'm working with python, and i tried: re.compile( '<a href="(.*?)">See full summary</a>', re.DOTALL | re.IGNORECASE ) but the only string i get with `findall()` is `link">text</a> <a href="correctLink`. Where is my mistake? Answer: Limit your link pattern to non-quote characters: re.compile('<a href="([^"]+?)">See full summary</a>', re.DOTALL | re.IGNORECASE) giving: >>> import re >>> patt = re.compile('<a href="([^"]+?)">See full summary</a>', re.DOTALL | re.IGNORECASE) >>> patt.findall('<a href="link">text</a> <a href="correctLink">See full summary</a>') ['correctLink'] Better yet, use a proper HTML parser. Using [BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/), finding that link would be as easy as: soup.find('a', text='See full summary')['href'] for an exact text match: >>> from bs4 import BeautifulSoup >>> soup=BeautifulSoup('<a href="link">text</a> <a href="correctLink">See full summary</a>') >>> soup.find('a', text='See full summary')['href'] u'correctLink'
Using distutils to make a package sutiable for zipimport Question: I'm embedding python in an application that I'm creating and I'm looking for a convenient way to distribute the python code with it. I recently read about `zipimport` and figured that would be a convenient way to distribute all my python code rather than including the fully expanded tree. So, I set up my package similarly to this: . ├── setup.py └── testpack ├── __init__.py └── pack1 ├── foo.py └── __init__.py where `setup.py` looks like: from distutils.core import setup setup( name='testpack', author='FatalError', version='1.0', packages=['testpack.pack1'] ) and then I ran `python setup.py bdist --format=zip`. But then when I look at the content of the zip: $ unzip -l testpack-1.0.linux-x86_64.zip Archive: testpack-1.0.linux-x86_64.zip Length Date Time Name --------- ---------- ----- ---- 183 2013-03-13 10:47 usr/local/lib/python2.7/dist-packages/testpack-1.0.egg-info 152 2013-03-13 10:47 usr/local/lib/python2.7/dist-packages/testpack/pack1/__init__.pyc 181 2013-03-13 10:47 usr/local/lib/python2.7/dist-packages/testpack/pack1/foo.pyc 0 2013-03-13 10:41 usr/local/lib/python2.7/dist-packages/testpack/pack1/__init__.py 33 2013-03-13 10:41 usr/local/lib/python2.7/dist-packages/testpack/pack1/foo.py --------- ------- 549 5 files Clearly the result is (not so surprisingly) not suitable for use with `zipimport`. Rather, this is a zip archive meant to be unzipped at `/` to install the package. Is there any way to get `distutils` (or `setuptools`, etc) to instead build the package so that it will work with `zipimport`? Since the code I have is really application specific, it doesn't belong installed into the system library. I realize that I can script it myself, but well, then what fun is that? For example, I want to make sure everything is pre-compiled and my package includes a unit test package that isn't meant to be distributed. So, I was hoping one of these tools could do it for me. Answer: `egg` archives are zipimport-capable (unless flagged to the contrary, in which case they'll be unpacked during installation). Use `python setup.py bdist --formats=egg`.
BDD in Scala - Does it have to be ugly? Question: I've used [lettuce](http://lettuce.it) for python in the past. It is a simple BDD framework where specs are written in an external plain text file. Implementation uses regex to identify each step, proving reusable code for each sentence in the specification. Using scala, either with [specs2](http://etorreborre.github.com/specs2/) or [scalatest](http://www.scalatest.org/) I'm being forced to write the the specification alongside the implementation, making it impossible to reuse the implementation in another test (sure, we could implement it in a function somewhere) and making it impossible to separate the test implementation from the specification itself (something that I used to do, providing acceptance tests to clients for validation). Concluding, I raise my question: Considering the importance of validating tests by clients, is there a way in BDD frameworks for scala to load the tests from an external file, raising an exception if a sentence in the test is not implemented yet and executing the test normally if all sentences have been implemented? Answer: I've just discovered a [cucumber plugin for sbt](http://blog.knoldus.com/2013/01/15/atdd-cucumber-and-scala/). Tests would be implemented under test/scala and specifications would be kept in test/resources as plain txt files. I'm just not sure on how reliable the library is and if it will have support in the future. Edit: The above is a wrapper for the following plugin wich solves perfectly the problem and supports Scala. <https://github.com/cucumber/cucumber-jvm>
SQL / Python Create Table Error Question: I am getting a strange error when I am trying to create this table.... When I track it back I have nothing on line 5? Can anyone help me on how to track this error? import settings import mysql.connector from database import login_info import datetime as dt def main(): db = mysql.connector.Connect(**login_info) cursor = db.cursor() sql =('DROP TABLE IF EXISTS messages') cursor.execute(sql) db.commit() message_table = """\ CREATE TABLE messages( msgID INTEGER AUTO_INCREMENT PRIMARY KEY, message VARCHAR(500) DEFAULT NULL, subject VARCHAR(500) DEFAULT NULL, )""" cursor.execute(message_table) db.commit() Error == mysql.connector.errors.ProgrammingError: 1064: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ')' at line 5 I can connect ot SQl in an interactive window no problem. Answer: Try removing the `,` at the end of line 4.
Most efficient way of sending a string with multiple variables as POST data using urllib Question: I feel really dumb for having to post this, but I am brand new to Python, and it isn't anything like PHP, which I do know. I have a string of data, which contains 1 or more variables, example: "var1=value1&var2=value2&var3=value3" I need to send this data to a web server using POST, using urllib. I have no problems manually formatting the POST data, and send it, but I am having trouble figuring out how to do this with code, without having to write complex code. It's pretty easy to use split('&') to change this string into an array, but then what? It looks like I need convert the data to the following syntax before I can urllib.urlencode it: {"var1":"value1","var2":"value2","var3":"value3"} Any suggestions would be greatly appreciated! Answer: Python has functions for most operations you will have to do with querystrings/urls. You can turn your string into a dict (like below) Python 2.7.3 (default, Aug 1 2012, 05:14:39) [GCC 4.6.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> qs = "var1=value1&var2=value2&var3=value3" >>> from urlparse import parse_qs >>> parse_qs(qs) {'var1': ['value1'], 'var3': ['value3'], 'var2': ['value2']} >>> data_dict = parse_qs(qs) >>> import urllib >>> post_data_str = urllib.urlencode(data_dict) >>> post_data_str 'var1=%5B%27value1%27%5D&var3=%5B%27value3%27%5D&var2=%5B%27value2%27%5D'
How to silently uninstall Python 2.7 on Windows? Question: Does anyone know how to silently uninstall Python 2.7 - i.e. uninstall it unattended, with no need for user interaction? I need to do it as part of an uninstallation script that installs a bunch of software silently. I've tried running msiexec with the /x and /qn flags on the msi file that was originally installed, but it fails - it just throws up the general help message, implying that I'm using invalid options. I've done a Google search, and can find help for earlier versions - they can be uninstalled silently by running the unwise.exe that's installed with them, with the right options. But 2.7 doesn't seem to include an unwise.exe, so I can't do that. Does anyone know how to do this? **Edit** : The answer turned out to be embarrassingly simple. Those were the correct command-line options all along - it's just that the order matters. The correct command was: `msiexec /x python-2.7.3.amd64.msi /qn` The important thing was to have the /qn option _after_ the msi file. Answer: **_Edit:_** Ignore what I previously said, here's the solution according to the [Python 2.4 Documentation](http://www.python.org/getit/releases/2.4/msi/): It is not necessary to have the MSI file available for uninstallation; alternatively, **the package or product code can also be specified**. You can find the product code by looking at the **properties of the Uninstall shortcut** that Python installs in the start menu. Hit the Windows Key, search Python Uninstall, right click it and go to Properties. The Product Key is in the Target field, you can use that to uninstall by doing: msiexec /x {03mY-L0NG-A77-K3Y}.msi /qn
PHP and Importing pylab Question: I have a PHP script that calls in a python program. Here is the php script: <?php $last_line = popen('/Library/Frameworks/Python.framework/Versions/Current/bin/python test.py', 'r'); $results = fgets($last_line); print $results; ?> and this is the content of test.py: test.py: import numpy as np from matplotlib.patches import Ellipse # import matplotlib.pyplot as plt # from matplotlib.pyplot import figure, show # import pylab print "Hello World!" Now, this works fine and I get "Hello World!" in browser. However, if I uncomment any of the imports (i.e., import matplotlib.pyplot as plt, import matplotlib.pyplot as plt or import pylab) I don't get the result from PHP. It will be great if someone could help me with this as I need all the plotting functions from Python. Answer: No complete answer but perhaps helpful: Assuming you're on Mac OS, I have changed your `.php` file to to: <br><br>==== Start ====<br><br> <?php error_reporting(E_ALL); $handle = popen('python test.py 2>&1', 'r'); while (($buffer = fgets($handle, 4096)) !== false) { echo $buffer."<br>"; } pclose($handle); ?> <br><br>==== End ====<br><br> and the `.py` file to: import numpy as np import matplotlib.pyplot as plt print "Hello World!" The `2>&1` redirects the error output of programs to the standard output, this can usefull for debugging purposes. The result on the page in the browser contained: > File "/Library/Python/2.6/site- > packages/matplotlib-0.91.1-py2.6-macosx-10.6-universal.egg/matplotlib/**init**.py", > line 403, in _get_configdir raise RuntimeError("Failed to create > %s/.matplotlib; consider setting MPLCONFIGDIR to a writable directory for > matplotlib configuration data"%h) RuntimeError: Failed to create > /Library/WebServer/.matplotlib; consider setting MPLCONFIGDIR to a writable > directory for matplotlib configuration data Than i did as root: mkdir /Library/WebServer/.matplotlib chown _www /Library/WebServer/.matplotlib/ And than the page in the browser contained as last error: > File "/Library/Python/2.6/site- > packages/matplotlib-0.91.1-py2.6-macosx-10.6-universal.egg/matplotlib/numerix/ma/**init**.py", > line 16, in from numpy.core.ma import * ImportError: No module named ma hmm, thats still disappointing, however you're mileage may vary, the problem has probably to do with the environment/permissions of the webserver user (_www).
Django: No module named 'app' Question: Django barfs with ImportError at /store/ No module named store But right there is the debug message there is the setting INSTALLED_APPS = ('django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.admin', 'django.contrib.admindocs', 'store') Environment: Request Method: GET Request URL: http://localhost:8000/ Django Version: 1.4.5 Python Version: 2.7.3 Installed Applications: ('django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.admin', 'django.contrib.admindocs', 'store') Installed Middleware: ('django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware') Traceback: File "/usr/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response 111. response = callback(request, *callback_args, **callback_kwargs) File "/home/paul/cs462/store/store/views.py" in main 37. return redirect(reverse('django.contrib.auth.views.login')) File "/usr/lib/python2.7/site-packages/django/core/urlresolvers.py" in reverse 476. return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)) File "/usr/lib/python2.7/site-packages/django/core/urlresolvers.py" in _reverse_with_prefix 363. possibilities = self.reverse_dict.getlist(lookup_view) File "/usr/lib/python2.7/site-packages/django/core/urlresolvers.py" in reverse_dict 276. self._populate() File "/usr/lib/python2.7/site-packages/django/core/urlresolvers.py" in _populate 253. for name in pattern.reverse_dict: File "/usr/lib/python2.7/site-packages/django/core/urlresolvers.py" in reverse_dict 276. self._populate() File "/usr/lib/python2.7/site-packages/django/core/urlresolvers.py" in _populate 265. lookups.appendlist(pattern.callback, (bits, p_pattern, pattern.default_args)) File "/usr/lib/python2.7/site-packages/django/core/urlresolvers.py" in callback 216. self._callback = get_callable(self._callback_str) File "/usr/lib/python2.7/site-packages/django/utils/functional.py" in wrapper 27. result = func(*args) File "/usr/lib/python2.7/site-packages/django/core/urlresolvers.py" in get_callable 105. not module_has_submodule(import_module(parentmod), submod)): File "/usr/lib/python2.7/site-packages/django/utils/importlib.py" in import_module 35. __import__(name) Exception Type: ImportError at / Exception Value: No module named store The shell works just fine (for what I try), but this error is displayed at every page I have. Doesn't having 'store' in the apps means that the module is imported??? EDIT: I've used Django for project many times. This was working a few hours ago. There is a blank `__init__.py` file in store/. Moreover, by using a print statement, I was able to determine that this gets executed (twice). `urls.py` and `models.py` also are executed (but not `views.py`). I have no idea what I could do to get this error. Answer: If it were not for version control, I would have never found this. As it was, it took me almost an hour to track it down. The mistake was in store/urls.py: urlpatterns = patterns('store.views', url(r'^$', 'main'), url(r'^new_delivery_user/$', 'new_delivery_user'), ... url(r'^event_signal/$', 'store.views.event_signal'), # problem ) I had moved the last URL from the project url.py to this app-specific one, which used the shorthand 'store.views' for prepending each of the views. It should have appeared: url(r'^event_signal/$', 'event_signal'),
Why my python and objective-c code get different hmac-sha1 result? Question: I am writing a client/server project that need a signature. I use `base64(hmac-sha1(key, data))` to generate a signature. But I got different signatures between python code and objective-c code: get_signature('KEY', 'TEXT') //python get 'dAOnR2oXWP9xa4vUBdDvVXTpzQo=' [self hmacsha1:@"KEY" @"TEXT"] //obj-c get '7FH0NG0Ou4nb5luKUyjfrdWunos=' Not only the base64 values are different, the hmac-sha1 digest values are different too. I'm trying to work it out with my friend for a few hours, still don't get it. Where is the problem of my code? My python code: import hmac import hashlib import base64 def get_signature(key, msg): return base64.b64encode(hmac.new(key, msg, hashlib.sha1).digest()) My friend's objective-c code (copy from [Objective-C sample code for HMAC- SHA1](http://stackoverflow.com/questions/756492/objective-c-sample-code-for- hmac-sha1)): (NSString *)hmac_sha1:(NSString *)key text:(NSString *)text{ const char *cKey = [key cStringUsingEncoding:NSASCIIStringEncoding]; const char *cData = [text cStringUsingEncoding:NSASCIIStringEncoding]; unsigned char cHMAC[CC_SHA1_DIGEST_LENGTH]; CCHmac(kCCHmacAlgSHA1, cKey, strlen(cKey), cData, strlen(cData), cHMAC); NSData *HMAC = [[NSData alloc] initWithBytes:cHMAC length:sizeof(cHMAC)]; NSString *hash = [GTMBase64 stringByEncodingData:HMAC]; return hash; } SOLVED: Thanks for everyone below. But I'm not gotta tell you that the real reason is I typed "TE **S** T" in my python IDE while typed "TE **X** T" in this post :P For not wasting your time, I made some tests and got a nicer solution, base on your answers: print get_signature('KEY', 'TEXT') # 7FH0NG0Ou4nb5luKUyjfrdWunos= print get_signature(bytearray('KEY'), bytearray('TEXT')) # 7FH0NG0Ou4nb5luKUyjfrdWunos= print get_signature('KEY', u'你好'.encode('utf-8')) # best solution, i think! # PxEm7Oibj7ijZ55ko7V3isSkD1Q= print get_signature('KEY', bytearray(u'你好')) # TypeError: unicode argument without an encoding print get_signature('KEY', u'你好') # UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128) print get_signature(u'KEY', 'TEXT') # TypeError: character mapping must return integer, None or unicode print get_signature(b'KEY', b'TEXT') # 7FH0NG0Ou4nb5luKUyjfrdWunos= Conclusion: 1. The message to be signature should be encoded to utf-8 string with both sides. 2. (Thanks to [DJV](http://stackoverflow.com/users/1974792/djv))In python 3, strings are all unicode, so they should be used with 'b', or bytearray(thanks to [Burhan Khalid](http://stackoverflow.com/users/790387/burhan-khalid)), or encoded to utf-8 string. Answer: Your friend is completely right, but so are you (sorta). Your function is completely right in both Python 2 and Python 3. However, your call is a little erroneous in Python 3. You see, in Python 3, [strings](http://docs.python.org/3.0/howto/unicode.html#the-string-type) are unicode, so in order to pass an ASCII string (as your Objective C friend does and as you would do in Python 2), you need to call your function with: get_signature(b'KEY', b'TEXT') in order to specify that those strings are [bytes](http://docs.python.org/3.0/library/functions.html#bytes) a.k.a. ASCII strings. **EDIT:** As [Burhan Khalid](http://stackoverflow.com/users/790387/burhan- khalid) noted, the flexible way of doing this in Python 3 is to either call your function like this: get_signature(key.encode('ascii'), test.encode('ascii')) or define it as: def get_signature(key, msg): if(isinstance(key, str)): key = key.encode('ascii') if(isinstance(msg, str)): msg = msg.encode('ascii') return base64.b64encode(hmac.new(key, msg, hashlib.sha1).digest())
Bash can't find python library but pydev can Question: I am trying to write some script using Python DNS library (dnspython). I installed it (python-dns and python-dnspython) using packet manager (apt-get install). I was trying to write the script interactively on the shell, but it keeps saying that it can't find the library. >>> import dns Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: No module named dns The funny part is, when I make the same import on Eclipse (pydev) it has no problem placing it. It must be something I do wrong, like not defining the path etc (although this one isn't very likely, since -as far as I know- apt- get is supposed to handle it automatically). OS: Ubuntu 12.04 Python version: 2.7.3 I am a beginner on Linux and on Python (bad combination, I know). Any help will be appreciated. Thanks in advance! Answer: Try this in both environments to see what the difference is: import sys print sys.path
How do I get Boto to return EC2 instances - S3 works fine Question: I'm having some issues with the EC2 bit of Boto (Boto v2.8.0, Python v2.6.7). The first command returns a list of S3 Buckets - all good! The second command to get a list of EC2 instances blows up with a 403 with "Query-string authentication requires the Signature, Expires and AWSAccessKeyId parameters" s3_conn = S3Connection(AWSAccessKeyId, AWSSecretKey) print s3_conn.get_all_buckets() ec2_conn = EC2Connection(AWSAccessKeyId, AWSSecretKey) print ec2_conn.get_all_instances() Also, my credentials are all good (Full admin) - I tested them using the Ruby aws-sdk, both EC2 and S3 work fine. I also noticed that the **host** attribute in the ec2_conn object is **s3-eu- west-1.amazonaws.com** , "s3"...? Surely thats wrong? I've tried retro fixing it to the correct endpoint but no luck. Any help would be great appreciate Thanks Answer: Here's some working code I use to list all my instances across potentially multiple regions. Its doing a lot more than you need, but maybe you can pare it down to what you want. #!/usr/bin/python import boto import boto.ec2 import sys class ansi_color: red = '\033[31m' green = '\033[32m' reset = '\033[0m' grey = '\033[1;30m' def name(i): if 'Name' in i.tags: n = i.tags['Name'] else: n = '???' n = n.ljust(16)[:16] if i.state == 'running': n = ansi_color.green + n + ansi_color.reset else: n = ansi_color.red + n + ansi_color.reset return n def pub_dns( i ): return i.public_dns_name.rjust(43) def pri_dns( i ): return i.private_dns_name.rjust(43) def print_instance( i ): print ' ' + name(i) + '| ' + pub_dns(i) + ' ' + pri_dns(i) regions = sys.argv[1:] if len(regions)==0: regions=['us-east-1'] if len(regions)==1 and regions[0]=="all": rr = boto.ec2.regions() else: rr = [ boto.ec2.get_region(x) for x in regions ] for reg in rr: print "========" print reg.name print "========" conn = reg.connect() reservations = conn.get_all_instances() for r in reservations: # print ansi_color.grey + str(r) + ansi_color.reset for i in r.instances: print_instance(i)
Retrieve JPEG image from a redirected URL and display it on a GUI window Question: I'm trying to download a JPEG file from a URL and display it on a tkinter GUI window This is the code I am trying to use to download and display the JPEG: picURL = "https://graph.facebook.com/" + ID + "/picture" picBytes= urlopen(picURL).read() picData = io.BytesIO(picBytes) picPil = Image.open(picData) picTk = ImageTk.PhotoImage(picPil) label_9 = Label(image = picTK, bg = "blue").pack() The problem is that the image isn't showing up. All I get is a blue box. How can i make it so the picture is shown? Thanks Im using python 3.3 on windows Answer: What library are you using to access the image? I would recommend [requests](http://docs.python-requests.org/en/latest/ "requests"). It automatically handles redirects for you: import requests import Image from StringIO import StringIO r = requests.get(https://graph.facebook.com/userID/picture) im = Image.open(StringIO(r.content))
Python-opencv: Read image data from stdin Question: How can I read image data from stdin rather than from a file? With the C++ interface, it seems to be possible: <http://stackoverflow.com/a/5458035/908515>. The function `imdecode` is available in Python as well. But it expects a `numpy array` as (first) argument. I have no idea how to convert the stdin data. This is what I tried: import cv import sys import numpy stdin = sys.stdin.read() im = cv.imdecode(numpy.asarray(stdin), 0) Result: `TypeError: <unknown> data type = 18 is not supported` Answer: Looks like python stdin buffer is too small for images. You can run your program with `-u` flag in order to remove buffering. More details in [this](http://stackoverflow.com/a/3670470/723891) answer. Second is that `numpy.asarray` probably not right way to get numpy array from the data, `numpy.frombuffer` works for me very well. So here is working code (only I used `cv2` instead of `cv` hope it wont matter too much): import sys import cv2 import numpy stdin = sys.stdin.read() array = numpy.frombuffer(stdin, dtype='uint8') img = cv2.imdecode(array, 1) cv2.imshow("window", img) cv2.waitKey() Can be executed this way: python -u test.py < cat.jpeg
Setting up Python Flask app with admin section Question: I've built a few small Flask apps before that were read only and I really enjoyed the process. now I'm adding an admin section to a Flask app and I'm looking for some guidance. Current directory structure looks like this: ├── Makefile ├── Procfile ├── app.py ├── requirements.txt ├── static │   ├── css │   ├── fonts │   ├── img │   └── js └── templates ├── about.html ├── base.html ├── contact.html └── index.html My app.py file looks like this: import os from flask import Flask, render_template app = Flask(__name__) app.debug = True # MAIN APPLICATION @app.route('/') @app.route('/work/<gallery>/') def index(gallery='home'): return render_template('index.html', gallery=gallery) @app.route('/views/<view>/') def view(view): return render_template(view + '.html') @app.route('/data/<gallery>/<size>/') def data(gallery='home', size='md'): data = '[\ {"image": "/static/img/photos/md/img_1.jpg","color": "white"},\ {"image": "/static/img/photos/md/img_2.jpg","color": "white"},\ {"image": "/static/img/photos/md/img_3.jpg","color": "black"}\ ]' return data if __name__ == '__main__': # Bind to PORT if defined, otherwise default to 5000. port = int(os.environ.get('PORT', 5000)) app.run(host='0.0.0.0', port=port) I've done some research and found the [Blueprints framework](http://flask.pocoo.org/docs/blueprints/) and [Flask- Admin](https://github.com/mrjoes/flask-admin) which seem like they might work together. Does anyone have an alternate suggestion that might be more efficient or easier to set up? Answer: Blueprints allow you to group functionality into isolated modules. If you feel your service will be very small, there's no need to use blueprints - you can add routes to the Flask application, like you do in your example. However, if application will get bigger, it is better to split it into smaller pieces by using blueprints. In your example, "work" is first possible blueprint, "views" is another, etc. Flask-Admin allows you to build administrative interface a-la Django admin. It does not matter how you're structuring rest of your application - you add Flask-Admin and it just works.
Calling Custom functions from Python using rpy2 Question: Is there a way to call functions defined in a file say myfunc.r ---------------myfunc.r -------------- myfunc = function(){ return(c(1,2,3,4,5,6,7,8,9,10)) } getname = function(){ return("chart title") } ---- Python How to call getname() here ? Any help would be greatly appreciated ? Answer: The are features in rpy2 that should help making this cleaner than dumping objects into the global workspace. from rpy2.robjects.packages import STAP # if rpy2 < 2.6.1 do: # from rpy2.robjects.packages import SignatureTranslatedAnonymousPackage # STAP = SignatureTranslatedAnonymousPackage with open('myfunc.r', 'r') as f: string = f.read() myfunc = STAP(string, "myfunc") The objects in the R file can now be accessed with `myfunc.myfunc` and `myfunc.getname`. Check the documention about [importing arbitrary R code as a package](http://rpy2.readthedocs.org/en/version_2.7.x/robjects_rpackages.html#importing- arbitrary-r-code-as-a-package) (older doc [here](http://rpy.sourceforge.net/rpy2/doc- dev/html/robjects_rpackages.html#importing-arbitrary-r-code-as-a-package)).
Convert String In Python to insert into MySQL DB date column date Question: I have an unusual date string that I want to insert into a MySQL DB. date = 'Thu, 14 Mar 2013 13:33:07 -0400' And here is the insert statement self.cursor.execute("INSERT INTO table1 (`DATE`)VALUES (%s);",(date)) When I do it like this it shows up in the database like : 0000-00-00 00:00:00 Even if I enter the SQL manualy it shows up the same way. How do I convert the date string into a mysql readable date for insert? Answer: from dateutil.parser import parse date = 'Thu, 14 Mar 2013 13:33:07 -0400' parse(date).strftime("%Y-%m-%d %H:%M:%S")
Error importing gtk with python on OS X Question: I've just installed pygtk through Homebrew(awesome tool) as well as its dependences (including gtk+); the thing is when I try to import gtk on the python interpreter it throws an ImportError, which don't happens when importing pygtk or any other module into the interpreter, I can't figure out what's wrong. :S Answer: After clarification from the OP, the original answer does not describe his problem… although I think it's related, and it may help other people, so I will leave it. But first, the relevant part. Before you can `import gtk`, you need to call `pygtk.require`, as shown in the [Getting Started](http://www.pygtk.org/pygtk2tutorial/ch-GettingStarted.html) section of the tutorial. (For more details, see the [PyGTK FAQ](http://faq.pygtk.org/index.py?req=show&file=faq02.006.htp).) That should solve your problem… but you're just crashing with `Fatal Python error: PyThreadState_Get: no current thread`. There are a number of reasons you can get this, but the most likely in this case is that you're running a C extension (`pygtk`/`gtk`/whatever) built for one version of Python against a different version of Python. (This is actually [covered in the PyGTK FAQ](http://faq.pygtk.org/index.py?req=show&file=faq01.010.htp) as well, but in this case it's a more general issue with CPython C extension modules, not something PyGTK specific.) If you have multiple Python 2.7 versions (and if you have 2.7.3, you very definitely have two, because Apple's is 2.7.2), you have to figure out which ones you have, and which one you used to build `pygtk`, and make sure you use it from the same one. And that takes us back to the original answer, which I've left below. * * * There are two reasons you can have this problem. * * * First, if you haven't installed any extra Python versions besides the ones that came with OS X, you may not have read the instructions that `brew` prints out about `pygtk` whenever you install it, or info it, etc.: For example: $ brew info pygtk pygtk: stable 2.24.0 ... ==> Caveats For non-Homebrew Python, you need to amend your PYTHONPATH like so: export PYTHONPATH=/usr/local/lib/python2.7/site-packages:$PYTHONPATH Homebrew installs Python packages into /usr/local/lib/pythonX.Y—even if it's installing for Apple's Python installation. But Apple's Python installation doesn't look for packages there by default. So, you need to do what this says. Just typing this line at the Terminal will work for the rest of that terminal session. If you want to make it permanent… well, there are many options, depending on exactly what you want. See [this answer](http://stackoverflow.com/questions/603785/environment-variables-in- mac-os-x/4567308#4567308) for details. This is explained in more detail at [Gems, Eggs and Perl Modules](https://github.com/mxcl/homebrew/wiki/Gems,-Eggs-and-Perl-Modules) and [Homebrew and Python](https://github.com/mxcl/homebrew/wiki/Homebrew-and- Python). (This is one of the multiple reasons why Homebrew usually recommends using `pip` whenever possible, rather than looking for packages in `brew`. But there are a few exceptions, and I could easily believe pygtk is one of them.) * * * Second, if you installed Homebrew's Python, you probably don't have your PATH set up right, so you're installing packages into the Homebrew Python's site packages, but then running the Apple Python installation instead. If you're just typing `python` and don't know which one you're running, `which python` should tell you. If it's `/usr/bin/python` it's Apple's; if it's `/usr/local/bin/python`, that's Homebrew's. You can also tell from the Python startup banner, because Mountain Lion comes with 2.7.2, while Homebrew will install 2.7.3. (Also, IIRC, Apple used a prerelease clang to build their Python, while anything you build with Homebrew will be built with whatever clang/gcc/llvm-gcc you have, which is not going to be a prerelease build…) **NOTE: Just because you see the word "Apple" somewhere in the banner doesn't mean it's Apple's Python!** If you build a Homebrew Python, or install a python.org Python, it will almost certainly be built with Apple GCC, Apple Clang, or Apple LLVM-GCC. And it's running on an Apple OS, too. So, "Apple" or "apple" will appear up to three times in the banner for _any_ Python, Apple or not. The fix for this is to run the Python you want to run. For example: * Use `virtualenv` to create one or more virtual environments based on either or both installations, and pick and choose using the venv tools. * Always use full paths—e.g., type `/usr/local/bin/python` to run Homebrew's Python, `/usr/bin/python` to run Apple's. (And modify the shebang lines in any of your scripts to do the same.) * Change your `PATH` variable to make sure whichever one you want first comes first. For Homebrew, you want either /usr/local/Cellar/python/2.7.3/bin (for just Python) or /usr/local/bin (for everything) before /usr/bin; for Apple, the other way around. * Add the Python framework bin directory(ies) to the PATH, so you can manipulate their order separately from general binaries. (This one isn't really relevant with Homebrew Python, because the Cellar directory serves the same purpose. But it can be useful with other third-party Python installations.) All of this applies to other tools. Many people get into trouble by having, e.g., one installation's `pip` or `idle` come first in the path, while a different installation's `python` does… * * * If you've installed a _different_ Python, e.g., by using the installers from python.org, you could easily have _both_ of the above problems. For example, you could be installing stuff for python.org Python, but running Apple Python, and on top of that, neither one may be configured to look in the Homebrew site-packages directory.
Django: Can't find template files. / App works without template files? Question: Yesterday I tried to edit a template in my django app and noticed that the template-file isn't even used (anymore). Even if I delete it the app will continue to work and changes I make in the file wont appear online. I couldn't find any other template file on my server, so could it be that Django imported it somehow or copied/saved it somewhere else? The app is hosted on a shared host, with Python2.7, Django 1.4.5 and FCGI. My settings.py looks like this: # Hosts/domain names that are valid for this site; required if DEBUG is False # See https://docs.djangoproject.com/en/1.4/ref/settings/#allowed-hosts ALLOWED_HOSTS = ['*'] #FORCE_SCRIPT_NAME = '/polls' # Local time zone for this installation. Choices can be found here: # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name # although not all choices may be available on all operating systems. # In a Windows environment this must be set to your system time zone. TIME_ZONE = 'Europe/Berlin' # Language code for this installation. All choices can be found here: # http://www.i18nguy.com/unicode/language-identifiers.html LANGUAGE_CODE = 'de-de' SITE_ID = 1 # If you set this to False, Django will make some optimizations so as not # to load the internationalization machinery. USE_I18N = True # If you set this to False, Django will not format dates, numbers and # calendars according to the current locale. USE_L10N = True # If you set this to False, Django will not use timezone-aware datetimes. USE_TZ = True # Absolute filesystem path to the directory that will hold user-uploaded files. # Example: "/home/media/media.lawrence.com/media/" MEDIA_ROOT = '' # URL that handles the media served from MEDIA_ROOT. Make sure to use a # trailing slash. # Examples: "http://media.lawrence.com/media/", "http://example.com/media/" MEDIA_URL = '' # Absolute path to the directory static files should be collected to. # Don't put anything in this directory yourself; store your static files # in apps' "static/" subdirectories and in STATICFILES_DIRS. # Example: "/home/media/media.lawrence.com/static/" STATIC_ROOT = 'http://ulli.cepheus.uberspace.de/static/' # URL prefix for static files. # Example: "http://media.lawrence.com/static/" STATIC_URL = 'http://ulli.cepheus.uberspace.de/static/' # Additional locations of static files STATICFILES_DIRS = ( "/var/www/virtual/ulli/html/static", # Put strings here, like "/home/html/static" or "C:/www/django/static". # Always use forward slashes, even on Windows. # Don't forget to use absolute paths, not relative paths. ) # List of finder classes that know how to find static files in # various locations. STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', # 'django.contrib.staticfiles.finders.DefaultStorageFinder', ) # List of callables that know how to import templates from various sources. TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', # 'django.template.loaders.eggs.Loader', ) MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', # Uncomment the next line for simple clickjacking protection: # 'django.middleware.clickjacking.XFrameOptionsMiddleware', ) ROOT_URLCONF = 'mysite.urls' # Python dotted path to the WSGI application used by Django's runserver. WSGI_APPLICATION = 'mysite.wsgi.application' TEMPLATE_DIRS = ( # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates". # Always use forward slashes, even on Windows. # Don't forget to use absolute paths, not relative paths. "/template", "/template/polls", "/var/www/virtual/ulli/html/template/polls", "http://ulli.cepheus.uberspace.de/template", ) INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', # Uncomment the next line to enable the admin: 'django.contrib.admin', # Uncomment the next line to enable admin documentation: # 'django.contrib.admindocs', 'polls', ) # A sample logging configuration. The only tangible logging # performed by this configuration is to send an email to # the site admins on every HTTP 500 error when DEBUG=False. # See http://docs.djangoproject.com/en/dev/topics/logging for # more details on how to customize your logging configuration. LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse' } }, 'handlers': { 'mail_admins': { 'level': 'ERROR', 'filters': ['require_debug_false'], 'class': 'django.utils.log.AdminEmailHandler' } }, 'loggers': { 'django.request': { 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': True, }, } } Thank you for your help! :) Answer: Just a guess, but the template [might be cached](https://docs.djangoproject.com/en/dev/ref/templates/api/#django.template.loaders.cached.Loader). Although, I don't see this cached loader in your settings. Might worth trying a restart anyway?
Python, IDLE: Too many recursive errors Question: This is supposedly a problem with the IDLE editor for Python. (I'm running Python 3.3.0 on OSX, but the same problem occurs with 2.7.3) I'm using IDLE to write Python programs. My problem is: Calling a recursive function, which calls itself too many times (1000 times), doesn't give me a single runtime error, but rather, it keeps sending me error messages until I close the program. The error which it should be sending is: "RuntimeError: maximum recursion depth exceeded." The error which it sends a thousand times isntead is simply a point out to where in the script the problem is: Traceback (most recent call last): File "<pyshell#112>", line 1, in <module> factorial(1.5) File "/Users/User/Documents/Python/Scripts/program1.py", line 187, in factorial recurse = factorial(n-1) File "/Users/User/Documents/Python/Scripts/program1.py", line 187, in factorial recurse = factorial(n-1) etc. This goes with all recursive functions calling itself too many times, but the specific function used here is: def factorial(n): if n == 0: return 1 else: recurse = factorial(n-1) result = n * recurse return result Answer: To stop python from showing those hundreds of errors, you can use a `try- except` block: def factorial(n): if n == 0: return 1 else: recurse = factorial(n-1) result = n * recurse return result try: print (factorial(6000)) except RuntimeError as e: print (e) output: #print factorial(1000) 93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000 #print factorial(6000) maximum recursion depth exceeded in comparison In your case this error occurs because python has a limit on the maximum recursion depth,it is there to stop the C stack from overflow. But you can change it using `sys.setrecursionlimit`: In [4]: import sys In [5]: sys.getrecursionlimit() Out[5]: 1000
pycurl login joomla website Question: I try create small script for login joomla web site whit python pycurl, im write this code : import sys, re import pycurl import cStringIO import time import urllib def LoginJoomla(url): buf = cStringIO.StringIO() c = pycurl.Curl() c.setopt(c.URL, url) post_params = [('usrname','admin'),('passwd','1234567789'),('submit','Login')] resp_data = urllib.urlencode(post_params) c.setopt(c.POSTFIELDS, resp_data) c.setopt(pycurl.POST, 1) c.setopt(c.WRITEFUNCTION, buf.write) c.perform() html = buf.getvalue() buf.close() print html LoginJoomla("http://www.domain.com/administrator/index.php?option=com_user&view=login") Bat not working, give me the normal login webpage, please any body can say me where i wrong. Answer: Read the BUT first! You need to get the URL parameters right (I think your URL is bad): `POST to http://www.example.com/administrator/` with the **following parameters:** * option=com_login * task=login * username=YOURUSER (not usrname! as you have) * passwd **BUT** from my knowledge about Joomla! autentication, you can't do it this way, because Joomla! from the web browser will send a token, to make sure the form was posted from a browser. If it's not posted from a browser, an error like 'The most recent request was denied because it contained an invalid security token. Please refresh the page and try again.' I know it's possible to remotely login to Joomla!, just keep searching. You may need a custom authentication plugin.
Refresh a list content with another list in Python Question: How would I extend the content of a given list with another given list without using the method `.extend()`? I imagine that I could use something with dictionaries. **Code** >>> tags =['N','O','S','Cl'] >>> itags =[1,2,4,3] >>> anew =['N','H'] >>> inew =[2,5] I need a function which returns the refreshed lists tags =['N','O','S','Cl','H'] itags =[3,2,4,3,5] When an element is already in the list, the number in the other list is added. If I use the `extend()` method, the the element `N` will appear in list `tags` twice: >>> tags.extend(anew) >>>itags.extend(inew) >>> print tags,itags ['N','O','S','Cl','N','H'] [1,2,4,3,5,2,5] Answer: You probably want a [Counter](http://docs.python.org/2/library/collections.html?highlight=collections#collections.Counter) for this. from collections import Counter tags = Counter({"N":1, "O":2, "S": 4, "Cl":3}) new = Counter({"N": 2, "H": 5}) tags = tags + new print tags output: Counter({'H': 5, 'S': 4, 'Cl': 3, 'N': 3, 'O': 2})
Python Xml Parsing for Wolfram Api Question: I'm trying to get the out put of the wolfram api using a python xml parsing script. Here's my script: import urllib import urllib.request import xml.etree.ElementTree as ET xml_data=urllib.request.urlopen("http://api.wolframalpha.com/v2/query?input=sqrt+2&appid=APLTT9-9WG78GYE65").read() root = ET.fromstring(xml_data) for child in root: print (child.get("title")) print (child.attrib) I know It's only getting the attributes of everything in the title portion of the code but it's a start. Here's a snippet of the output: <pod title="Input" scanner="Identity" id="Input" position="100" error="false" numsubpods="1"> <subpod title=""> <plaintext>sqrt(2)</plaintext> I'm trying to get it to only print out what is in the tags. Does anyone know how to edit the code to get that? Answer: Only the `<plaintext>` elements contain text: for pt in root.findall('.//plaintext'): if pt.text: print(pt.text) The `.text` attribute holds the text of an element. For your URL, that prints: sqrt(2) 1.4142135623730950488016887242096980785696718753769480... [1; 2^_] Pythagoras's constant sqrt(2)~~1.4142 (real, principal root) -sqrt(2)~~-1.4142 (real root) It looks like the `<pod>` tags have interesting titles too: for pod in root.findall('.//pod'): print(pod.attrib['title']) for pt in pod.findall('.//plaintext'): if pt.text: print('-', pt.text) which then prints: Input - sqrt(2) Decimal approximation - 1.4142135623730950488016887242096980785696718753769480... Number line Continued fraction - [1; 2^_] Constant name - Pythagoras's constant All 2nd roots of 2 - sqrt(2)~~1.4142 (real, principal root) - -sqrt(2)~~-1.4142 (real root) Plot of all roots in the complex plane
Why does my contextmanager-function not work like my contextmanager class in python? Question: In my code, I need to be able to open and close a device properly, and therefore see the need to use a context manager. While a context manager is usually defined as a class with `__enter__` and `__exit__` methods, there also seem to be the possibility to decorate a function for use with the context manager (see [a recent post](http://stackoverflow.com/questions/15427361/how- to-use-the-context-manager-to-avoid-the-use-of-del-in- python/15427892?noredirect=1#15427892) and [another nice example here](http://preshing.com/20110920/the-python-with-statement-by-example)). In the following (working) code snippet, I have implemented the two possibilities; one just need to swap the commented line with the other one: import time import contextlib def device(): return 42 @contextlib.contextmanager def wrap(): print("open") yield device print("close") return class Wrap(object): def __enter__(self): print("open") return device def __exit__(self, type, value, traceback): print("close") #with wrap() as mydevice: with Wrap() as mydevice: while True: time.sleep(1) print mydevice() What I try is to run the code and stop it with `CTRL-C`. When I use the `Wrap` class in the context manager, the `__exit__` method is called as expeced (the text 'close' is printed in the terminal), but when I try the same thing with the `wrap` function, the text 'close' is not printed to the terminal. My question: Is there a problem with the code snippet, am I missing something, or why is the line `print("close")` not called with the decorated function? Answer: The example in the documentation for `contextmanager` is somewhat misleading. The portion of the function after `yield` does not really correspond to the `__exit__` of the context manager protocol. The key point in the documentation is this: > If an unhandled exception occurs in the block, it is reraised inside the > generator at the point where the yield occurred. Thus, you can use a > `try...except...finally` statement to trap the error (if any), or ensure > that some cleanup takes place. So if you want to handle an exception in your contextmanager-decorated function, you need to write your own `try` that wraps the `yield` and handle the exceptions yourself, executing cleanup code in a `finally` (or just block the exception in `except` and execute your cleanup after the `try/except`). For example: @contextlib.contextmanager def cm(): print "before" exc = None try: yield except Exception, exc: print "Exception was caught" print "after" if exc is not None: raise exc >>> with cm(): ... print "Hi!" before Hi! after >>> with cm(): ... print "Hi!" ... 1/0 before Hi! Exception was caught after [This page](http://pymotw.com/2/contextlib/index.html#from-generator-to- context-manager) also shows an instructive example.
How to ensure all string literals are unicode in python Question: I have a fairly large python code base to go through. It's got an issue where some string literals are strings and others are unicode. And this causes bugs. I am trying to convert everything to unicode. I was wondering if there is a tool that can convert all literals to unicode. I.e. if it found something like this: print "result code %d" % result['code'] to: print u"result code %d" % result[u'code'] If it helps I use PyCharm (in case there is an extension that does this), however I am would be happy to use a command like too as well. Hopefully such a tool exists. Answer: You can use [tokenize.generate_tokens](http://docs.python.org/2/library/tokenize.html#tokenize.generate_tokens) break the string representation of Python code into tokens. `tokenize` also classifies the tokens for you. Thus you can identify string literals in Python code. It is then not hard to manipulate the tokens, adding `'u'` where desired: * * * import tokenize import token import io import collections class Token(collections.namedtuple('Token', 'num val start end line')): @property def name(self): return token.tok_name[self.num] def change_str_to_unicode(text): result = text.splitlines() # Insert a dummy line into result so indexing result # matches tokenize's 1-based indexing result.insert(0, '') changes = [] for tok in tokenize.generate_tokens(io.BytesIO(text).readline): tok = Token(*tok) if tok.name == 'STRING' and not tok.val.startswith('u'): changes.append(tok.start) for linenum, s in reversed(changes): line = result[linenum] result[linenum] = line[:s] + 'u' + line[s:] return '\n'.join(result[1:]) text = '''print "result code %d" % result['code'] # doesn't touch 'strings' in comments 'handles multilines' + \ 'okay' u'Unicode is not touched' ''' print(change_str_to_unicode(text)) yields print u"result code %d" % result[u'code'] # doesn't touch 'strings' in comments u'handles multilines' + u'okay' u'Unicode is not touched'
PySide - PyQt4 - Draw on one table widget Question: In the following code, I would like to draw fro exemple a circle on the cell of coordinate (4,5). How could I achieve this ? #! /usr/bin/env python2.7 # -*- coding: utf-8 -*- import sys from PySide import QtCore, QtGui class MainWindow(QtGui.QWidget): def __init__( self, parent = None ): super(MainWindow, self).__init__(parent) # General grid self.table = QtGui.QTableWidget(self) self.nbrow, self.nbcol = 9, 9 self.table.setRowCount(self.nbrow) self.table.setColumnCount(self.nbcol) # Each cell has dimension 50 pixels x 50 pixels for row in range(0, self.nbrow): self.table.setRowHeight(row, 50) for col in range(0, self.nbcol): self.table.setColumnWidth(col, 50) # Each cell contains one single QTableWidgetItem for row in range(0, self.nbrow): for col in range(0, self.nbcol): item = QtGui.QTableWidgetItem() item.setTextAlignment( QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter ) self.table.setItem(row, col, item) # Header formatting font = QtGui.QFont() font.setFamily(u"DejaVu Sans") font.setPointSize(12) self.table.horizontalHeader().setFont(font) self.table.verticalHeader().setFont(font) # Font used font = QtGui.QFont() font.setFamily(u"DejaVu Sans") font.setPointSize(20) self.table.setFont(font) # Global Size self.resize(60*9, 60*9 + 20) # Layout of the table layout = QtGui.QGridLayout() layout.addWidget(self.table, 0, 0) self.setLayout(layout) # Set the focus in the first cell self.table.setFocus() self.table.setCurrentCell(0, 0) if __name__ == "__main__": app = QtGui.QApplication(sys.argv) fen = MainWindow() fen.show() sys.exit(app.exec_()) Answer: I guess you can reimplement the paint method like in the following example which captures a right-mouse click and places a little circle on the corresponding coordinates. #!/usr/bin/python #-*- coding:utf-8 -*- from PyQt4.QtCore import * from PyQt4.QtGui import * class PaintTable(QTableWidget): def __init__(self, parent): QTableWidget.__init__(self, parent) self.setRowCount(10) self.setColumnCount(10) self.center = QPoint(-10,-10) def paintEvent(self, event): painter = QPainter(self.viewport()) #See: http://stackoverflow.com/questions/12226930/overriding-qpaintevents-in-pyqt painter.drawEllipse(self.center,10,10) QTableWidget.paintEvent(self,event) def mousePressEvent(self, event): if event.buttons() == Qt.RightButton: self.center = QPoint(event.pos().x(), event.pos().y()) print self.center self.viewport().repaint() elif event.buttons() == Qt.LeftButton: QTableWidget.mousePressEvent(self,event) class mainWindow(QMainWindow): def __init__(self, parent=None): super(mainWindow, self).__init__(parent) self.table = PaintTable(self) self.setCentralWidget(self.table) if __name__ == "__main__": import sys app = QApplication(sys.argv) main = mainWindow() main.show() sys.exit(app.exec_()) Applied to your minimal working example this would look like this: #! /usr/bin/env python2.7 # -*- coding: utf-8 -*- import sys #from PyQt4 import QtCore, QtGui from PySide import QtCore, QtGui #Just tested it for PyQt4 since I don't have PySide installed... class PaintTable(QtGui.QTableWidget): def __init__(self, parent): QtGui.QTableWidget.__init__(self, parent) self.center = QtCore.QPoint(-10,-10) def paintEvent(self, event): painter = QtGui.QPainter(self.viewport()) #See: http://stackoverflow.com/questions/12226930/overriding-qpaintevents-in-pyqt painter.drawEllipse(self.center,10,10) QtGui.QTableWidget.paintEvent(self,event) def mousePressEvent(self, event): if event.buttons() == QtCore.Qt.RightButton: self.center = QtCore.QPoint(event.pos().x(), event.pos().y()) print self.center self.viewport().repaint() elif event.buttons() == QtCore.Qt.LeftButton: QtGui.QTableWidget.mousePressEvent(self,event) class MainWindow(PaintTable): def __init__( self, parent = None ): super(MainWindow, self).__init__(parent) # General grid self.table = PaintTable(self) self.nbrow, self.nbcol = 9, 9 self.table.setRowCount(self.nbrow) self.table.setColumnCount(self.nbcol) for row in range(0, self.nbrow): self.table.setRowHeight(row, 50) for col in range(0, self.nbcol): self.table.setColumnWidth(col, 50) # Each cell contains one single QTableWidgetItem for row in range(0, self.nbrow): for col in range(0, self.nbcol): item = QtGui.QTableWidgetItem() item.setTextAlignment( QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter ) self.table.setItem(row, col, item) # Header formatting font = QtGui.QFont() font.setFamily(u"DejaVu Sans") font.setPointSize(12) self.table.horizontalHeader().setFont(font) self.table.verticalHeader().setFont(font) # Font used font = QtGui.QFont() font.setFamily(u"DejaVu Sans") font.setPointSize(20) self.table.setFont(font) # Global Size self.resize(60*9, 60*9 + 20) # Layout of the table layout = QtGui.QGridLayout() layout.addWidget(self.table, 0, 0) self.setLayout(layout) # Set the focus in the first cell self.table.setFocus() self.table.setCurrentCell(0, 0) if __name__ == "__main__": app = QtGui.QApplication(sys.argv) fen = MainWindow() fen.show() sys.exit(app.exec_()) ![output](http://i.stack.imgur.com/jKiaL.png)
Trouble authenticating Tor with python Question: Probably doing something very silly here, but I'm having some trouble authenticating automatically through Tor. I'm using 32 bit ubuntu 12.04 with obfuscated bridges. This should be all the relevant code, but let me know if there's something else that would be useful in debugging this issue: import socket import socks import httplib def connectTor(): socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, "127.0.0.1", 9050, True) #9050 is the Tor proxy port socket.socket = socks.socksocket def newIdentity(): socks.setdefaultproxy() #Disconnect from Tor network s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(("127.0.0.1", 46594)) s.send("AUTHENTICATE\r\n") response = s.recv(128) #128 bytes of data for now, just to see how Tor responds print response if response.startswith("250"): #250 is the code for a positive response from Tor s.send("SIGNAL NEWNYM\r\n") #Use a new identity s.close() connectTor() #Just to make sure we're still connected to Tor Whenever I run this I get the following error: 515 Authentication failed: Password did not match HashedControlPassword value from configuration. Maybe you tried a plain text password I tried using the --hash-password option and pasting that in the place of the AUTHENTICATE string, but that just caused the script to hang. Thoughts? Answer: That error means that you set the HashedControlPassword option in your torrc. I would suggest option for `CookieAuthentication 1` instead then using a controller library rather than doing this from scratch. What you're trying to do here (issue a NEWNYM) is a very, very common request ([1](http://stackoverflow.com/questions/17013707/how-can-i-change-my-tor- process-endpoint-in-stem), [2](http://stackoverflow.com/questions/16987518/how-to-request-new-tor- identity-in-terminal)) so I just added a [FAQ entry](https://stem.torproject.org/faq.html#how-do-i-request-a-new-identity- from-tor) for it. Here's an example using [stem](https://stem.torproject.org/)... from stem import Signal from stem.control import Controller with Controller.from_port(port = 9051) as controller: controller.authenticate() controller.signal(Signal.NEWNYM)
Befuddling Python string index out of range error Question: I looked through the other questions on this topic, but couldn't find something that really addresses what I'm trying to figure out. The problem is this: I'm trying to create a program that looks for palindromes in two complementary strands of DNA, returning the position and length of each palindrome identified. For instance, if given the sequence TTGATATCTT, the program should find the complement (AACTATAGAA), and then identify the second index as being the start of a 6-character palindrome. I'm brand new to programming, so it might look totally goofy, but the code I came up with looks like this: '''This first part imports the sequence (usually consisting of multiple lines of text) from a file. I have a feeling there's an easier way of doing this, but I just don't know what that would be.''' length = 4 li = [] for line in open("C:/Python33/Stuff/Rosalind/rosalind_revp.txt"): if line[0] != ">": li.append(line) seq = (''.join(li)) '''The complement() function takes the starting sequence and creates its complement''' def complement(seq): li = [] t = int(len(seq)) for i in range(0, t): n = (seq[i]) if n == "A": li.append(n.replace("A", "T")) if n == "T": li.append(n.replace("T", "A")) if n == "C": li.append(n.replace("C", "G")) if n == "G": li.append(n.replace("G", "C")) answer = (''.join(li)) return(answer) '''the ip() function goes letter by letter, testing to see if it matches with the letter x spaces in front of it on the complementary strand(x being specified by length). If the letter doesn't match, it continues to the next one. After checking all possibilities for one length, the function runs again with the argument length+1.''' def ip(length, seq): n = 0 comp = complement(seq) while length + n <= (len(seq)): for i in range(0, length-1): if seq[n + i] != comp[n + length - 1 - i]: n += 1 break if (n + i) > (n + length - 1 - i): print(n + 1, length) n += 1 if length <= 12: ip(length + 1, seq) ip(length, seq) The thing runs absolutely perfectly when starting with short sequences (TCAATGCATGCGGGTCTATATGCAT, for example), but with longer sequences, I invariably get this error message: Traceback (most recent call last): File "C:/Python33/Stuff/Ongoing/palindrome.py", line 48, in <module> ip(length, seq) File "C:/Python33/Stuff/Ongoing/palindrome.py", line 39, in ip if seq[n + i] != comp[n + length - 1 - i]: IndexError: string index out of range The message is given after the program finishes checking the possible 4-character palindromes, before starting the function for length + 1. I understand what the message is saying, but I don't understand why I'm getting it. Why would this work for some strings and not others? I've been checking for the past hour to see if it makes a difference whether the sequence has an odd number of characters or an even number of characters, is a multiple of 4, is just shy of a multiple of 4, etc. I'm stumped. What am I missing? Any help would be appreciated. P.S. The problem comes from the Rosalind Website (Rosalind.info), which uses 1-based numbering. Hence the print(n+1, length) at the end. Answer: The`IndexError`can be avoided by changing the last line of: if line[0] != ">": li.append(line) to if line[0] != ">": li.append(line.rstrip()) near the beginning of your code. This prevents any trailing whitespace, especially newlines, read from the file from becoming part of the`seq`string. Having them in it is a problem because the`complement()`function ignores and thus removes them, so the`answer`string it returns isn't necessarily the same length as the input argument. This causes `comp` and `seq` to not be the same length in the in`ip()`function. You didn't ask, but here's how I'd shorten your code and make it more "Pythonic": COMPLEMENT = str.maketrans("ATCG", "TAGC") LENGTH = 4 with open("palindrome.txt") as input: seq = ''.join(line.rstrip() for line in input if line[0] != ">") def complement(seq): return seq.translate(COMPLEMENT) def ip(length, seq): n = 0 comp = complement(seq) while length + n <= len(seq): for i in range(0, length-1): if seq[n + i] != comp[n + length - 1 - i]: n += 1 break if n + i > n + length - 1 - i: print(n + 1, length) n += 1 if length <= 12: ip(length + 1, seq) print(repr(seq)) print(repr(complement(seq))) ip(LENGTH, seq) BTW, those two `print()` function calls added near the end are what gave me the clue about what was wrong.
Python "for" loop, division error Question: I'm using python 2.7.3 When I try a = [1,2,3,4] b = [] for i in a: b.append(1/i) I'm getting an unexpected output as b = [1,0,0,0]. But if I print the value of i loop works fine. for i in a: b.append(i) will give b =[1, 2, 3, 4] What is the reason for this. Also how I can do the same in correct way? Answer: In python 2, `/` means integer divison when both operands are integers. Try `1.0 / i`. In [2]: 1 / 2 Out[2]: 0 In [3]: 1.0 / 2 Out[3]: 0.5 In [4]: 1 / 2.0 Out[4]: 0.5 To make the `/` operator behave like it does in python 3, use `from __future__ import division`: In [11]: from __future__ import division In [12]: 1 / 2 Out[12]: 0.5
Matching line number with string in a table. Question: I have a file with a list of columns describing particular parameters: size magnitude luminosity I need only particular data (in particular lines, and columns) from this file. So far I have a code in python, where I have appended the necessary line numbers. I just need to know how i can match it to get the right string in the text file along with just the variables in columns (magnitude) and (luminosity.) Any suggestions on how I could approach this? Here is a sample of my code (#comments describe what I have done and what I want to do): temp_ListMatch = (point[5]).strip() if temp_ListMatch: ListMatchaddress = (point[5]).strip() ListMatchaddress = re.sub(r'\s', '_', ListMatchaddress) ListMatch_dirname = '/projects/XRB_Web/apmanuel/499/Lists/' + ListMatchaddress #print ListMatch_dirname+"\n" try: file5 = open(ListMatch_dirname, 'r') except IOError: print 'Cannot open: '+ListMatch_dirname Optparline = [] for line in file5: point5 = line.split() j = int(point5[1]) Optparline.append(j) #Basically file5 contains the line numbers I need, #and I have appended these numbers to the variable j. temp_others = (point[4]).strip() if temp_others: othersaddress = (point[4]).strip() othersaddress =re.sub(r'\s', '_', othersaddress) othersbase_dirname = '/projects/XRB_Web/apmanuel/499/Lists/' + othersaddress try: file6 = open(othersbase_dirname, 'r') except IOError: print 'Cannot open: '+othersbase_dirname gmag = [] z = [] rh = [] gz = [] for line in file6: point6 = line.split() f = float(point6[2]) g = float(point6[4]) h = float(point6[6]) i = float(point6[9]) # So now I have opened file 6 where this list of data is, and have # identified the columns of elements that I need. # I only need the particular rows (provided by line number) # with these elements chosen. That is where I'm stuck! Answer: Load the whole data file in to a pandas DataFrame (assuming that the data file has a header from which we can get the column names) import pandas as pd df = pd.read_csv('/path/to/file') Load the file of line numbers into a pandas Series (assuming there's one per line): # squeeze = True makes the function return a series row_numbers = pd.read_csv('/path/to/rows_file', squeeze = True) Return only those lines which are in the row number file, and the columns magnitude and luminosity (this assumes that the first row is numbered 0): relevant_rows = df.ix[row_numbers][['magnitude', 'luminosity']
IndentationError in my python script Question: my python version is 2.7.2, and my OS is win XP. this is my script: import sqlite3 import os from flask import Flask, request, session, g, redirect, url_for, \ abort, render_template, flash DATABASE = 'C:\Python27\flaskr.db' DEBUG = True SECRET_KEY = 'development key' USERNAME = 'admin' PASSWORD = 'default' app = Flask(__name__) app.config.from_object(__name__) def connect_db(): return sqlie3.connect(app.config['DATABASE'] if __name__ == '__main__': app.run() The error came up when I was running it as a module with python shell. if __name__ == '__main__': app.run() Right at the “:” is the place where the idle gave the error message that there's a invalid syntax. But I can hardly find out any syntax error. Answer: You have missed to close one parenthesis at: def connect_db(): return sqlie3.connect(app.config['DATABASE'] It should be: def connect_db(): return sqlie3.connect(app.config['DATABASE']) And the reason it goes all the way to the `:` is that Python tries to interpret this as a [conditional expression](http://docs.python.org/2/reference/expressions.html#conditional- expressions): def connect_db(): return sqlie3.connect(app.config['DATABASE'] if __name__ == '__main__': ... But because `:` cannot be a part of a valid [boolean operation](http://docs.python.org/2/reference/expressions.html#boolean- operations) it gives you this lovely syntax error.
How to speed up python starting up and/or reduce file search while loading libraries? Question: I have a framework composed of different tools written in python in a multi- user environment. The first time I log to the system and start one command it takes 6 seconds just to show a few line of help. If I immediately issue the same command again it takes 0.1s. After a couple of minutes it gets back to 6s. (proof of short- lived cache) The system sits on a GPFS so disk throughput should be ok, though access might be low because of the amount of files in the system. strace -e open python tool | wc -l shows 2154 files being accessed when starting the tool. strace -e open python tool | grep ENOENT | wc -l shows 1945 missing files being looked for. (A very bad hit/miss ratio is you ask me :-) I have a hunch that the excessive time involved in loading the tool is consumed by querying the GPFS about all those files, and these are cached for the next call (at either system or GPFS level), though I don't know how to test/prove it. I have no root access to the system and I can only write to GPFS and /tmp. Is it possible to improve this `python quest for missing files`? Any idea on how to test this in a simple way? (Reinstalling everything on /tmp is not simple, as there are many packages involved, virtualenv will not help either (I think), since it's just linking the files on the gpfs system). An option would be of course to have a daemon that forks, but that's far from "simple" and would be a last resort solution. Thanks for reading. Answer: Python 2 looks for modules as relative to the current package first. If your library code has a lot of imports for a lot of top-level modules those are all looked up as relative first. So, if package `foo.bar` import `os`, then Python _first_ looks for `foo/bar/os.py`. This miss is cached by Python itself too. In Python 3, the default has moved to absolute imports instead; you can switch Python 2.5 and up to use absolute imports _per module_ with: from __future__ import absolute_import Another source of file lookup misses is loading `.pyc` bytecode cache files; if those are missing for some reason (filesystem not writable for the current Python process) then Python will continue to look for those on every run. You can create these caches with the [`compileall` module](http://docs.python.org/2/library/compileall.html): python -m compileall /path/to/directory/with/pythoncode provided you run that with the correct write permissions.
pack a software in Python using py2exe with 'libiomp5md.dll' not found Question: I have Python 2.7 on Window 7 OS. I wish to pack my project.py in an Executable using py2exe. Following the instruction i wrote a setup.py file from distutils.core import setup import py2exe setup(console=["project.py"]) and I got this message ![enter image description here](http://i.stack.imgur.com/VpoAs.jpg) i tried to exclude '**libiomp5md.dll** ' from distutils.core import setup import py2exe setup(console=["SegmentationAccuracy.py"]) dll_excludes = ['libiomp5md.dll'] but always i got the same error message **"error: libiomo5md.dll: No such file or directory"** my executable contains: import math import os import numpy as np import sys import ogr from progressbar import ProgressBar from shapely.geometry import Polygon nan = np.nan Answer: I had the same problem, but calling `import numpy` within `setup.py` resolved the issue
Calculating the Fisher criterion in Python Question: Is there a python module that when given two vectors x and y, where y is a two-class (0,1), it calculates the Fisher criterion, as shown in the formula here <http://compbio.soe.ucsc.edu/genex/genexTR2html/node12.html> Please note that I am not looking to apply Fisher's linear discriminant, only the Fisher criterion :). Thanks in advance! Answer: Not as far as I can tell, but you could write your own (please test that this result is correct, I'm only going by my understanding of the formula). import numpy as np def fisher_criterion(v1, v2): return abs(np.mean(v1) - np.mean(v2)) / (np.var(v1) + np.var(v2)) Which gives, for example, >>> fisher_criterion([0, 1, 2], [0, 1]) 0.54545454545454553
saving constructor arguments automatically Question: Frequently the constructor of a class will take it's arguments and save them on the instance. For example: class Example(object): def __init__(self, title='',backtitle='', height=20, width=50): self.title = title self.backtitle = backtitle self.height = height self.width = width This is repetitious so I made a helper function to do this automatically: from inspect import getargspec def save_args(values): for i in getargspec(values['self'].__init__).args[1:]: values['self'].__dict__[i] = values[i] class Example(object): def __init__(self, title='',backtitle='', height=20, width=50): save_args(vars()) My questions are as follows: * Will this fail with certain classes or agruments * Is it portable, will it work on Jython, etc.. It worked for me on python 2.7 and 3.2 * Is there a simpler alternative? * Is there a python package out there that already does this? Answer: It'll fail when your class uses [`__slots__`](http://docs.python.org/3/reference/datamodel.html#slots). You could use [`setattr()`](http://docs.python.org/3/library/functions.html#setattr) instead: from inspect import getargspec def save_args(values): for i in getargspec(values['self'].__init__).args[1:]: setattr(values['self'], i, values[i]) provided the arguments keyword arguments to `__init__` are all declared slots of course. Otherwise this should work on any Python implementation. You may be interested in a [previous discussion of the topic](http://stackoverflow.com/q/1389180), which sparked a [Python-ideas list thread](http://mail.python.org/pipermail/python- ideas/2011-April/thread.html#9930).
Bluetooth communication between Arduino and PyBluez Question: I am trying to establish bluetooth communication between an Arduino Uno board (with a bluetooth shield) and my Linux OS, using Python PyBluez. I've successfully paired my laptop to the Uno. I'm able to connect to the board, however the board is not reading the data being sent nor is it able to send data. Here is the Arduino Sketch #include <SoftwareSerial.h> #define RxD 0 //receive data on digital 0 #define TxD 1 //transmit on digital 1 SoftwareSerial blueToothSerial(RxD, TxD); int counter = 0; int incoming; void setup(void){ Serial.begin(9600); //pinMode(RxD,INPUT); //pinMode(TxD,OUTPUT); setupBlueToothConnection(); } void setupBlueToothConnection(){ blueToothSerial.begin(19200); blueToothSerial.print("\r\n+STWMOD=0\r\n"); //set the bluetooth work in slave mode blueToothSerial.print("\r\n+STNA=SeeedBTSlave\r\n"); //set the bluetooth name as "SeeedBTSlave" blueToothSerial.print("\r\n+STOAUT=1\r\n"); // Permit Paired device to connect me //blueToothSerial.print("\r\n+STAUTO=0\r\n"); // Auto-connection should be forbidden here delay(2000); // This delay is required. blueToothSerial.print("\r\n+INQ=1\r\n"); //make the slave bluetooth inquirable Serial.println("The slave bluetooth is inquirable!"); delay(2000); // This delay is required. blueToothSerial.flush(); } void loop(){ if(blueToothSerial.available()) Serial.println(blueToothSerial.read()); blueToothSerial.write('x'); } And my Python Module: import bluetooth import sys bd_addr = "00:12:10:23:10:18" #itade address port = 1 sock=bluetooth.BluetoothSocket( bluetooth.RFCOMM ) sock.connect((bd_addr, port)) print 'Connected' sock.settimeout(1.0) sock.send("x") print 'Sent data' data = sock.recv(1) print 'received [%s]'%data sock.close() I have Arduino IDE 1.0.4, my laptop is running Ubuntu 11.10 Answer: Using the Itade Studio Bluetooth Shield, you have to upload the code without the shield attached, and then attach the shield. I'm curious if this is so with other bluetooth units. For the sake of completion, to establish communication between your laptop and Arduino Uno w/BT shield: 1. Pair your laptop with the bluetooth shield 2. Upload Arduino code with shield detached. 3. Attach the shield 4. Run python module. On the itade shield, you know when connection is established when the D1 led turns solid green, as oppose to flickering green.
Python: TypeError: an integer is required Question: I am trying to get the md5 checksum of some files and write them into a temp file. import os import hashlib PID = str(os.getpid()) manifest = open('/temp/tmp/MANIFEST.'+ PID + '.tmp','w') #e.g. MANIFEST.48938.tmp for elmt in files_input: input = open(elmt['file'], "r", 'us-ascii') #'us-ascii' when I ran "file --mime" manifest.write(hashlib.md5(input.read()).hexdigest()) From this I get a Python error that I haven't able to resolve: Traceback (most recent call last): File "etpatch.py", line 131, in <module> input = open(elmt['file'], "r", 'us-ascii') TypeError: an integer is required Some people have had this error from doing "from os import *" but I am not doing this nor am I using import * on any other module. Answer: The third argument to [`open()`](http://docs.python.org/2/library/functions.html#open) is expected to be an integer: > > open(name[, mode[, buffering]]) > > > The optional buffering argument specifies the file’s desired buffer size: 0 > means unbuffered, 1 means line buffered, any other positive value means use > a buffer of (approximately) that size (in bytes). A negative buffering means > to use the system default, which is usually line buffered for tty devices > and fully buffered for other files. If omitted, the system default is used. > [2]
multi-threading of a matrix multiplication in python Question: I want to create n threads and that each thread computes an entire row of the result matrix. I have tried the following code, import numpy import random import threading class MatrixMult(threading.Thread): """A thread which computes the i,j entry of A * B""" def __init__(self, A, B, i): super(MatrixMult, self).__init__() self.A = A self.B = B self.i = i #self.j = j def run(self): print "Computing %i, %i" % (self.i, self.i) x = 0 result=[] for k in range(self.A.shape[0]) x += self.A[self.i,k] * self.B[k,self.i self.result=x print "Completed %i, %i" % (self.i, self.j) def mult(n): """A function to randomly create two n x n matrices and multiply them""" # Create two random matrices A = numpy.zeros((n,n)) B = numpy.zeros((n,n)) for i in range(n): for j in range(n): A[i,j] = random.randrange(0, 100) B[i,j] = random.randrange(0, 100) # Create and start the threads threads = [] for i in range(n): # for j in range(n): t = MatrixMult(A, B, i) threads.append(t) t.start() for t in threads: t.join() C = numpy.zeros((n,n)) for t in threads: C[t.i] = t.result return C print multi(30) however it prints out many weird matrices: [ 66695. 66695. 66695. 66695. 66695. 66695. 66695. 66695. 66695. 66695. 66695. 66695. 66695. 66695. 66695. 66695. 66695. 66695. 66695. 66695. 66695. 66695. 66695. 66695. 66695. 66695. 66695. 66695. 66695. 66695.] [ 88468. 88468. 88468. 88468. 88468. 88468. 88468. 88468. 88468. 88468. 88468. 88468. 88468. 88468. 88468. 88468. 88468. 88468. 88468. 88468. 88468. 88468. 88468. 88468. 88468. 88468. 88468. 88468. 88468. 88468.]] anyone see a problem in my code? I don't see what i am doing wrong. Answer: Your code sets C[t.i] = t.result which sets an entire row of `C` to the value `t.result`, which is a scalar. I see some commented stuff about `j` in there; you presumably want to account for that, and also fix x += self.A[self.i,k] * self.B[k,self.i to use `j` (and also not be a syntax error). As-is, it seems like you're computing `C[i, i]` and then assigning that value to the whole row. Also: you know this code is guaranteed to be much, much, much slower than `np.dot`, right? Between doing tight loops in python, distributing computational work across threads despite the [GIL](http://wiki.python.org/moin/GlobalInterpreterLock), and also being [an inefficient algorithm for matrix multiplication](http://en.wikipedia.org/wiki/Matrix_multiplication#Algorithms_for_efficient_matrix_multiplication) in the first place. If your goal is actually to speed up matrix multiplies using multiple cores, link your numpy to MKL, OpenBLAS, or ACML, use `np.dot`, and call it a day.
quickfix : how to get Symbol ( flag 55 ) from messages? Question: I'm running QuickFix with the Python API and connecting to a TT FIX Adapter using FIX4.2 I am logging on and sending a market data request for two instruments. That works fine and data from the instruments comes in as expected. I can get all kinds of information from the messages. However, I am having trouble getting the Symbol (flag 55) field. import quickfix as fix def fromApp(self, message, sessionID): ID = fix.Symbol() message.getField(ID) print ID This works for the very first message [the initial Market Data Snapshot (flag 35 = W)] that comes to me. Once I start getting incremental refreshes (flag 35 = X), I can no longer get the Symbol field. Every message that arrives results in a Field Not Found error. This is confusing me because in the logs, the Symbol field is always present, whether the message type is W or X. Thinking the Symbol is in the header of refresh messages, I tried `get.Field(ID)` when 35 = W and `get.Header().getField(ID)` when 35 = X, however this did not work. Can somebody help me figure out what is going on here? I would like to be able to explicitly tell my computer what instruments it is looking at. Thanks Answer: Your question is pretty simple, but you've mixed in some misconceptions as well. 1) Symbol will **never** be in the header. It is a body field. 2) In X messages, the symbol is in a repeating group. You first have to get a group object with `msg.GetGroup()`, then get the symbol from _that_. See [this example code](http://quickfixengine.org/quickfix/doc/html/python/repeating_groups_2.html), from the [repeating groups doc page](http://quickfixengine.org/quickfix/doc/html/repeating_groups.html). 3) In W messages, the symbol is not in a group. That's why it works for you there. It seems clear you are pretty new to QuickFIX and FIX in general. I think you should take few minutes and skim through the "Working with Messages" section of [the docs](http://quickfixengine.org/quickfix/doc/html/). Also, the [FIXimate](http://fixprotocol.org/FIXimate3.0/) website can be your best friend.
Python: cut equivalent in Python? Question: I want to parse a path (not filename) by the forward slash. Below takes the full path "filename" and reads up to the 7th "/". **EDIT: I realized the above was confusing when I stated filename. I meant, I needed to parse the full path. e.g. I could need the first 7 "/"s to the left and remove 5 trailing "/"s.** Python: "/".join(filename.split("/")[:7]) Bash: some command that prints filename | cut -d'/' -f1-7` It looks so much cleaner with the cut tool. Is there a better/ more efficient way to write this in Python? Answer: Usually I would recommend using functions from the [`os.path`](http://docs.python.org/3/library/os.path.html) module for handling paths. I prefer to let the library handle all of the edge cases that can occur with valid paths. As was you pointed out in the comments, [`os.path.split()`](http://docs.python.org/3/library/os.path.html#os.path.split) splits just the last path element. To use it, one could write: l = [] while True: head, tail = os.path.split(filename) l.insert(0, tail) if head == "/": l.insert(0, "") break filename = head "/".join(l[:7]) Although more verbose, this will correctly normalize artifacts such as duplicate slashes. On the other hand, your use of `string.split()` matches the semantics of `cut(1)`. * * * Sample test cases: $ echo '/a/b/c/d/e/f/g/h' | cut -d'/' -f1-7 /a/b/c/d/e/f $ echo '/a/b/c/d/e/f/g/h/' | cut -d'/' -f1-7 /a/b/c/d/e/f $ echo '/a//b///c/d/e/f/g/h' | cut -d'/' -f1-7 /a//b///c * * * # Tests and comparison to string.split() import os.path def cut_path(filename): l = [] while True: head, tail = os.path.split(filename) l.insert(0, tail) if head == "/": l.insert(0, "") break filename = head return "/".join(l[:7]) def cut_string(filename): return "/".join( filename.split("/")[:7] ) def test(filename): print("input:", filename) print("string.split:", cut_string(filename)) print("os.path.split:", cut_path(filename)) print() test("/a/b/c/d/e/f/g/h") test("/a/b/c/d/e/f/g/h/") test("/a//b///c/d/e/f/g/h") # input: /a/b/c/d/e/f/g/h # string.split: /a/b/c/d/e/f # os.path.split: /a/b/c/d/e/f # # input: /a/b/c/d/e/f/g/h/ # string.split: /a/b/c/d/e/f # os.path.split: /a/b/c/d/e/f # # input: /a//b///c/d/e/f/g/h # string.split: /a//b///c # os.path.split: /a/b/c/d/e/f
Python not displaying simplified Chinese properly in dos window Question: I have a python script that prints chinese output on command line. It works fine in eclipse. However, when I run it in dos window, it prints ? (question marks) and garbage characters. Could it be because of big-5 vs gb encoding? if so, how do I control it? btw, I already installed the Asian character sets, which is why it works in Eclipse edit:combining chcp, encode('utf-8'), and setting the non-unicode handler, I can now see the character, but a simple print results in a exception: chcp 65001 Active code page: 65001 Z:\src>c:\Python27\python.exe mobTest.py Traceback (most recent call last): File "mobTest.py", line 94, in <module> print u'哈哈'.encode('utf-8') IOError: [Errno 13] Permission denied Answer: What is your system locale? `English (United States)`, for example, uses code page 437 for the console, which doesn't support Chinese characters. `Chinese (Simplified, PRC)` makes it possible to print Chinese to the console. You can change the setting in `Region and Language` in Control Panel (Windows 7), `Administrative` tab and rebooting. After that, printing a _Unicode_ Chinese string to the console will work. You can even type in Chinese as an IME will be available. Changing the system locale will only affect the console and non-Unicode programs. Most modern programs won't notice. **Edit** : Example using Chinese PRC region and running in the Windows console: Python 2.7.3 (default, Apr 10 2012, 23:24:47) [MSC v.1500 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> print u'哈哈' 哈哈 >>> import sys >>> sys.stdout.encoding 'cp936' Example script using UTF-8 source encoding. Make sure to _save_ the source in UTF-8, as declared by the `#coding` comment: # coding: utf-8 print u'哈哈' print '哈哈' # this will be UTF-8 encoded, and NOT work Execution: C:\>python x.py 哈哈 鍝堝搱
Producing PDFs in landscape orientation with ReportLab Question: I am working on a Python script that produces a PDF report using ReportLab. I need to produce the pages in landscape orientation and I have already looked through the ReportLab manual but I can't find a way of doing this. Any ideas or suggestions? Answer: Make sure you've imported from reportlab.lib.pagesizes import letter, landscape And then: canvas.setPageSize(landscape(letter)) Or more generally, canvas.setPageSize(width, height) and you can set it to be any size you like. Remember reportlab uses points, where 1 point is 1/72 of an inch. You can also import: from reportlab.lib.units import inch Which lets you do things like: canvas.setPageSize(11*inch, 8.5*inch) EDIT: Added all the built in page sizes inspired by yentsun. Diving into the `reportlab.lib.pagesizes` source code, we find in all: A0,A1,A2,A3,A4,A5,A6 B0,B1,B2,B3,B4,B5,B6 LETTER, LEGAL, ELEVENSEVENTEEN The comments claims that the lowercase `letter` has been deprecated since 2001, but is still available. Additionally, two functions are avaialable, `portrait` and `landscape` that each take in a tuple pagesize, and portrait returns the tuple with the smaller dimension first, and landscape returns the tuple with the larger dimension first.
Is it possible to call a C Function by reference from python?? Question: I am a beginner in python and I need to test a C function which is being called by reference. Here is my C File : myfile.c #include<stdio.h> int my_function(int *x) { int A; printf("enter value of A"); scanf("%d",&A); *x = 10 * A; // this sets the value to the address x is referencing to return 0; } now, my python script should call my_function() and pass the argument so that I can check and verify the result. something like : `result = self.loaded_class.my_function(addressOf(some_variable))` `self.assertEqual(some_variable,10)` Is this possible ?? how can i achieve this. And I am writing scripts in python for auto tests , not using interactive python. Answer: If you compile your file as a shared library or dll (I don't know how to do that), you can use [ctypes](http://docs.python.org/2/library/ctypes.html) like this (assuming it's a dll for this example): import ctypes as ct mylib = ct.cdll.myfile c_int = ct.c_int(0) mylib.my_function(ct.byref(c_int)) print c_int.value
PyQt4-PySide - Formatting a table widget Question: In the following code, I would like to use thicker rule separator between the column 2 and 3 for example. How can I achieve this ? #! /usr/bin/env python2.7 # -*- coding: utf-8 -*- import sys from PySide import QtCore, QtGui class MainWindow(QtGui.QWidget): def __init__( self, parent = None ): super(MainWindow, self).__init__(parent) # General grid self.table = QtGui.QTableWidget(self) self.nbrow, self.nbcol = 9, 9 self.table.setRowCount(self.nbrow) self.table.setColumnCount(self.nbcol) # Each cell has dimension 50 pixels x 50 pixels for row in range(0, self.nbrow): self.table.setRowHeight(row, 50) for col in range(0, self.nbcol): self.table.setColumnWidth(col, 50) # Each cell contains one single QTableWidgetItem for row in range(0, self.nbrow): for col in range(0, self.nbcol): item = QtGui.QTableWidgetItem() item.setTextAlignment( QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter ) self.table.setItem(row, col, item) # Header formatting font = QtGui.QFont() font.setFamily(u"DejaVu Sans") font.setPointSize(12) self.table.horizontalHeader().setFont(font) self.table.verticalHeader().setFont(font) # Font used font = QtGui.QFont() font.setFamily(u"DejaVu Sans") font.setPointSize(20) self.table.setFont(font) # Global Size self.resize(60*9, 60*9 + 20) # Layout of the table layout = QtGui.QGridLayout() layout.addWidget(self.table, 0, 0) self.setLayout(layout) # Set the focus in the first cell self.table.setFocus() self.table.setCurrentCell(0, 0) if __name__ == "__main__": app = QtGui.QApplication(sys.argv) fen = MainWindow() fen.show() sys.exit(app.exec_()) Answer: You can use stylesheets to change the style of the cell borders. See examples: * <http://www.qtcentre.org/threads/27195-Border-around-selected-cell-in-qtablewidget> * [Set QTableWidget cell's borders to 0px](http://stackoverflow.com/questions/7341007/set-qtablewidget-cells-borders-to-0px)
Maximum value of first column Question: I have an array like this: elements=[['1', '1', '2'], ['2', '2', '3'], ['3', '3', '4'], ['4', '4', '5'], ['5', '5', '6'], ['6', '6', '7'], ['7', '7', '8'], ['8', '8', '9'], ['9', '9', '10'], ['10', '10', '11'], ['11', '11', '12'], ['12', '12', '13'], ['13', '13', '14'], ['14', '14', '15'], ['15', '15', '16'], ['16', '16', '17'], ['17', '17', '18'], ['18', '18', '19'], ['19', '19', '20'], ['20', '20', '21'], ['21', '21', '22'], ['22', '22', '23'], ['23', '23', '24'], ['24', '24', '25'], ['25', '25', '26'], ['26', '26', '27'], ['27', '27', '28'], ['28', '28', '29'], ['29', '29', '30'], ['30', '30', '31'], ['31', '32', '33'], ['32', '33', '34'], ['33', '34', '35'], ['34', '35', '36'], ['35', '36', '37'], ['36', '37', '38'], ['37', '38', '39'], ['38', '39', '40'], ['39', '40', '41'], ['40', '41', '42'], ['41', '42', '43'], ['42', '43', '44'], ['43', '44', '45'], ['44', '45', '46'], ['45', '46', '47'], ['46', '47', '48'], ['47', '48', '49'], ['48', '49', '50'], ['49', '50', '51'], ['50', '51', '52'], ['51', '52', '53'], ['52', '53', '54'], ['53', '54', '55'], ['54', '55', '56'], ['55', '56', '57'], ['56', '57', '58'], ['57', '58', '59'], ['58', '59', '60'], ['59', '60', '61'], ['60', '61', '62'], ['61', '63', '64'], ['62', '64', '65'], ['63', '65', '66'], ['64', '66', '67'], ['65', '67', '68'], ['66', '68', '69'], ['67', '69', '70'], ['68', '70', '71'], ['69', '71', '72'], ['70', '72', '73'], ['71', '73', '74'], ['72', '74', '75'], ['73', '75', '76'], ['74', '76', '77'], ['75', '77', '78'], ['76', '78', '79'], ['77', '79', '80'], ['78', '80', '81'], ['79', '81', '82'], ['80', '82', '83'], ['81', '83', '84'], ['82', '84', '85'], ['83', '85', '86'], ['84', '86', '87'], ['85', '87', '88'], ['86', '88', '89'], ['87', '89', '90'], ['88', '90', '91'], ['89', '91', '92'], ['90', '92', '93'], ['91', '94', '95'], ['92', '95', '96'], ['93', '96', '97'], ['94', '97', '98'], ['95', '98', '99'], ['96', '99', '100'], ['97', '100', '101'], ['98', '101', '102'], ['99', '102', '103'], ['100', '103', '104'], ['101', '104', '105'], ['102', '105', '106'], ['103', '106', '107'], ['104', '107', '108'], ['105', '108', '109'], ['106', '109', '110'], ['107', '110', '111'], ['108', '111', '112'], ['109', '112', '113'], ['110', '113', '114'], ['111', '114', '115'], ['112', '115', '116'], ['113', '116', '117'], ['114', '117', '118'], ['115', '118', '119'], ['116', '119', '120'], ['117', '120', '121'], ['118', '121', '122'], ['119', '122', '123'], ['120', '123', '124'], ['121', '125', '126'], ['122', '126', '127'], ['123', '127', '128'], ['124', '128', '129'], ['125', '129', '130'], ['126', '130', '131'], ['127', '131', '132'], ['128', '132', '133'], ['129', '133', '134'], ['130', '134', '135'], ['131', '135', '136'], ['132', '136', '137'], ['133', '137', '138'], ['134', '138', '139'], ['135', '139', '140'], ['136', '141', '142'], ['137', '142', '143'], ['138', '143', '144'], ['139', '144', '145'], ['140', '145', '146'], ['141', '146', '147'], ['142', '147', '148'], ['143', '148', '149'], ['144', '149', '150'], ['145', '150', '151'], ['146', '151', '152'], ['147', '152', '153'], ['148', '153', '154'], ['149', '154', '155'], ['150', '155', '156'], ['151', '157', '158'], ['152', '158', '159'], ['153', '159', '160'], ['154', '160', '161'], ['155', '161', '162'], ['156', '162', '163'], ['157', '163', '164'], ['158', '164', '165'], ['159', '165', '166'], ['160', '166', '167'], ['161', '167', '168'], ['162', '168', '169'], ['163', '169', '170'], ['164', '170', '171'], ['165', '171', '172'], ['166', '172', '173'], ['167', '173', '174'], ['168', '174', '175'], ['169', '175', '176'], ['170', '176', '177'], ['171', '177', '178'], ['172', '178', '179'], ['173', '179', '180'], ['174', '180', '181'], ['175', '181', '182'], ['176', '182', '183'], ['177', '183', '184'], ['178', '184', '185'], ['179', '185', '186'], ['180', '186', '187'], ['181', '188', '189'], ['182', '189', '190'], ['183', '190', '191'], ['184', '191', '192'], ['185', '192', '193'], ['186', '193', '194'], ['187', '194', '195'], ['188', '195', '196'], ['189', '196', '197'], ['190', '197', '198'], ['191', '198', '199'], ['192', '199', '200'], ['193', '200', '201'], ['194', '201', '202'], ['195', '202', '203'], ['196', '203', '204'], ['197', '204', '205'], ['198', '205', '206'], ['199', '206', '207'], ['200', '207', '208'], ['201', '208', '209'], ['202', '209', '210'], ['203', '210', '211'], ['204', '211', '212'], ['205', '212', '213'], ['206', '213', '214'], ['207', '214', '215'], ['208', '215', '216'], ['209', '216', '217'], ['210', '217', '218'], ['211', '219', '220'], ['212', '220', '221'], ['213', '221', '222'], ['214', '222', '223'], ['215', '223', '224'], ['216', '224', '225'], ['217', '225', '226'], ['218', '226', '227'], ['219', '227', '228'], ['220', '228', '229'], ['221', '229', '230'], ['222', '230', '231'], ['223', '231', '232'], ['224', '232', '233'], ['225', '233', '234'], ['226', '235', '236'], ['227', '236', '237'], ['228', '237', '238'], ['229', '238', '239'], ['230', '239', '240'], ['231', '240', '241'], ['232', '241', '242'], ['233', '242', '243'], ['234', '243', '244'], ['235', '244', '245'], ['236', '245', '246'], ['237', '246', '247'], ['238', '247', '248'], ['239', '248', '249'], ['240', '249', '250'], ['241', '251', '252'], ['242', '252', '253'], ['243', '253', '254'], ['244', '254', '255'], ['245', '255', '256'], ['246', '256', '257'], ['247', '257', '258'], ['248', '258', '259'], ['249', '259', '260'], ['250', '260', '261'], ['251', '261', '262'], ['252', '262', '263'], ['253', '263', '264'], ['254', '264', '265'], ['255', '265', '266'], ['256', '267', '268'], ['257', '268', '269'], ['258', '269', '270'], ['259', '270', '271'], ['260', '271', '272'], ['261', '272', '273'], ['262', '273', '274'], ['263', '274', '275'], ['264', '275', '276'], ['265', '276', '277'], ['266', '277', '278'], ['267', '278', '279'], ['268', '279', '280'], ['269', '280', '281'], ['270', '281', '282'], ['271', '283', '284'], ['272', '284', '285'], ['273', '285', '286'], ['274', '286', '287'], ['275', '287', '288'], ['276', '288', '289'], ['277', '289', '290'], ['278', '290', '291'], ['279', '291', '292'], ['280', '292', '293'], ['281', '293', '294'], ['282', '294', '295'], ['283', '295', '296'], ['284', '296', '297'], ['285', '297', '298'], ['286', '298', '299'], ['287', '299', '300'], ['288', '300', '301'], ['289', '301', '302'], ['290', '302', '303'], ['291', '303', '304'], ['292', '304', '305'], ['293', '305', '306'], ['294', '306', '307'], ['295', '307', '308'], ['296', '308', '309'], ['297', '309', '310'], ['298', '310', '311'], ['299', '311', '312'], ['300', '312', '313'], ['301', '314', '315'], ['302', '315', '316'], ['303', '316', '317'], ['304', '317', '318'], ['305', '318', '319'], ['306', '319', '320'], ['307', '320', '321'], ['308', '321', '322'], ['309', '322', '323'], ['310', '323', '324'], ['311', '324', '325'], ['312', '325', '326'], ['313', '326', '327'], ['314', '327', '328'], ['315', '328', '329'], ['316', '329', '330'], ['317', '330', '331'], ['318', '331', '332'], ['319', '332', '333'], ['320', '333', '334'], ['321', '334', '335'], ['322', '335', '336'], ['323', '336', '337'], ['324', '337', '338'], ['325', '338', '339'], ['326', '339', '340'], ['327', '340', '341'], ['328', '341', '342'], ['329', '342', '343'], ['330', '343', '344'], ['331', '345', '346'], ['332', '346', '347'], ['333', '347', '348'], ['334', '348', '349'], ['335', '349', '350'], ['336', '350', '351'], ['337', '351', '352'], ['338', '352', '353'], ['339', '353', '354'], ['340', '354', '355'], ['341', '355', '356'], ['342', '356', '357'], ['343', '357', '358'], ['344', '358', '359'], ['345', '359', '360'], ['346', '361', '362'], ['347', '362', '363'], ['348', '363', '364'], ['349', '364', '365'], ['350', '365', '366'], ['351', '366', '367'], ['352', '367', '368'], ['353', '368', '369'], ['354', '369', '370'], ['355', '370', '371'], ['356', '371', '372'], ['357', '372', '373'], ['358', '373', '374'], ['359', '374', '375'], ['360', '375', '376']] I'd like to know the maximum value of the first column of this array. However I've found that problematic since I'm not used to python. I've tried: import numpy as np a = np.array(elements) numEL = a[np.argmax(a)][0] but I get a wrong result. I know it is 360 but it returns 285... Any ideas? Answer: Your elements are strings, and therefore the comparisons are lexicographic. You want to work with integers: >>> elements=[['1', '1', '2'], ['99', '2', '3'],['360', '10', '11']] >>> a = np.array(elements,dtype=int) >>> a array([[ 1, 1, 2], [ 99, 2, 3], [360, 10, 11]]) >>> a.max(axis=0) array([360, 10, 11]) >>> a.max(axis=0)[0] 360 or simply >>> a[:,0] array([ 1, 99, 360]) >>> a[:,0].max() 360 [Note: this is how to get it to work. As for why the code was returning a strange answer in the first place, @mgilson explains that in the comments to this answer.]
Python is printing everything form module when imported into another module Question: I have a 2 files. 1. `funcattrib.py` 2. `test_import.py` **funcattrib.py** import sys def sum(a,b=5): "Adds two numbers" a = int(a) b = int(b) return a+b sum.version = "1.0" sum.author = "Prasad" k = sum(1,2) print(k) print("Function attributes: - ") print("Documentation string:",sum.__doc__) print("Function name:",sum.__name__) print("Default values:",sum.__defaults__) print("Code object for the function is:",sum.__code__) print("Dictionary of the function is:",sum.__dict__) #writing the same information to a file f = open('test.txt','w') f.write(sum.__doc__) f.close() print("\n\nthe file is successfully written with the documentation string") **test_import.py** import sys from funcattrib import sum input("press <enter> to continue") a = input("Enter a:") b = input("Enter b:") f = open('test.txt','a') matter_tuple = "Entered numbers are",a,b print(matter_tuple) print("Type of matter:",type(matter_tuple)) matter_list = list(matter_tuple) print(list(matter_list)) finalmatter = " ".join(matter_list) print(finalmatter) f.write(finalmatter) f.close() print("\n\nwriting done successfully from test_import.py") I imported `sum` function from `funcattrib.py`. when I try to execute test_import.py, I am seeing the output of the whole `funcattrib.py`. I just wanted to use the `sum` function. Please advise, what wrong I am doing, or is there another way of importing module without actually executing it? Answer: All statements in the 'top level' of a module are executed when imported. You you _don't_ want that to happen, you need to distinguish between the module being used as a script and a module. Use the following test for that: if __name__ == '__main__': # put code here to be run when this file is executed as a script Applying that to your module: import sys def sum(a,b=5): "Adds two numbers" a = int(a) b = int(b) return a+b sum.version = "1.0" sum.author = "Prasad" if __name__ == '__main__': k = sum(1,2) print(k) print("Function attributes: - ") print("Documentation string:",sum.__doc__) print("Function name:",sum.__name__) print("Default values:",sum.__defaults__) print("Code object for the function is:",sum.__code__) print("Dictionary of the function is:",sum.__dict__) #writing the same information to a file f = open('test.txt','w') f.write(sum.__doc__) f.close() print("\n\nthe file is successfully written with the documentation string")
DistributionNotFound error after upgrading pip Question: In reading about virtualenv [here](http://www.virtualenv.org/en/latest/index.html) I realized I didn't have pip 1.3+, so I ran `pip install --upgrade pip` and now when I run `pip --version` i get the following: Traceback (most recent call last): File "/usr/local/bin/pip", line 5, in <module> from pkg_resources import load_entry_point File "/usr/local/Cellar/python/2.7.3/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/distribute-0.6.34-py2.7.egg/pkg_resources.py", line 2807, in <module> parse_requirements(__requires__), Environment() File "/usr/local/Cellar/python/2.7.3/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/distribute-0.6.34-py2.7.egg/pkg_resources.py", line 594, in resolve raise DistributionNotFound(req) pkg_resources.DistributionNotFound: pip==1.2.1 If it helps, or is at all relevant, my `$PATH` looks like this: /usr/local/bin:/usr/local/share/python:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/local/git/bin Also, `which pip` gives me `/usr/local/bin/pip`. Not sure what to do about the error. Thanks. Answer: ### The brutal way: Assuming you are using homebrew for Mac (because I see /usr/local/Cellar), I suggest to * remove (or backup) `/usr/local/lib/python2.7`, and * `brew rm python && brew install python`. This will definitely install pip 1.3.3 alongside of python. Your distribute will also be 0.6.35. ### The soft way: From `/usr/local/lib/python2.7/site-packages` just remove: * `easy-install.pth` * `pip-1.2.1-py2.7.egg` _or other versions of pip you have._ * `distribute-0.6.34-py2.7.egg` _or other versions_ Then, `brew rm python && brew install python`. This will leave all your other bindings from brew and installed stuff intact. Python, pip and distribute will be replaced with up-to-date versions. ### additionally: Please check that you don't have a distribute or setuptools or pip located in `/Library/Python/2.7/site-packages`. That dir is re-used by all python 2.7 versions (brewed or from OS X) and will interferre with the pip/distribute already installed by Homebrew.
openssl not decrypted files encrypted by pycrypto Question: i encrypt file in python: from Crypto.Cipher import AES from Crypto import Random key = Random.new().read(16) iv = Random.new().read(AES.block_size) encryptor = AES.new(key, AES.MODE_CBC, iv) with open(in_file, 'rb') as fin, open(out_file, 'wb') as fout: fout.write(iv) while True: chunk = fin.read(16*1024) if len(chunk) == 0: break elif len(chunk) % 16 != 0: chunk += b' ' * (16 - len(chunk) % 16) fout.write(encryptor.encrypt(chunk) print base64.b32encode(key) but when after what i try decrypt it with openssl: `openssl aes-256-cbc -d -in enc -out new.zip` it returns bag magic number what i doing wrong? Answer: Program is using 128 bit AES key for encryption, as seen from the line: key = Random.new().read(16) So, instead of using openssl aes-256-cbc -d -in enc -out new.zip use this openssl aes-128-cbc -d -in enc -out new.zip
Include bash script in python compilation Question: I have a couple of bash scripts that I use in a Python program. The current solution is to browse to the file in the GUI and then run the script(s) like this (`pathToScript` is the String for the path to the script): INPUT = [pathToScript, input1, input2, input3, input4, input5, input6, input7, input8, input9, input10] subprocess.call(INPUT) To avoid always browsing to the script or hard coding the path, I am looking for a solution to somehow include the bash script in the compiled Python program and then run it inside the program. Is this possible? I'd rather not rewrite the bash scripts to Python if I can avoid it. Answer: You can always bundle the bash script with the rest of your program (like I suspect you are already doing), and reconstruct the path to these scripts at runtime. It is easy enough to get the location of any python module from within the module itself, then create path to the bash script from there: import os.path LOCATION = os.path.dirname(os.path.abspath(__file__)) pathToScript = os.path.join(LOCATION, 'bashscript.sh') and `pathToScript` would then be an absolute path to the file `bashscript.sh` sitting in the same directory as the current Python module.
Python Interpreter Behavior? Question: I am using Python 2.7. This is what happened: >>> 2+++2 4 I am not sure as to how the python interpreter interprets this expression. The only reason I can come up with is that successive "+" after the first "+" are considered as unary operators and the first "+" is considered as a binary operator, but what is actually the mechanism that is happening I am not sure of. I would want someone to answer the question in terms of the grammar specifics of Python programming language and also report some other ambiguous expressions. I came up with some other expressions which are listed below (with their results): >>> 2------------2 4 >>> 2+-2+-2+-2+-2+-2-------------------------2 -10 Answer: You're right; Python is interpreting this as `2 + (++2)`, as you might expect. You can see this by looking at the compiled bytecode for 2+2 and 2+++2, as follows: >>> dis.dis(lambda: 2+2) 1 0 LOAD_CONST 2 (4) 3 RETURN_VALUE >>> dis.dis(lambda: 2+++2) 1 0 LOAD_CONST 1 (2) 3 LOAD_CONST 1 (2) 6 UNARY_POSITIVE 7 UNARY_POSITIVE 8 BINARY_ADD 9 RETURN_VALUE * * * You might want to know why Python parses 2+++2 like this. First, the code gets split up into tokens: >>> from cStringIO import StringIO >>> import tokenize >>> tokenize.generate_tokens(StringIO("2+++2").readline) 9 <generator object generate_tokens at 0x0000000007BC7480> >>> list(tokenize.generate_tokens(StringIO("2+++2").readline)) 10 [(2, '2', (1, 0), (1, 1), '2+++2'), (51, '+', (1, 1), (1, 2), '2+++2'), (51, '+', (1, 2), (1, 3), '2+++2'), (51, '+', (1, 3), (1, 4), '2+++2'), (2, '2', (1, 4), (1, 5), '2+++2'), (0, '', (2, 0), (2, 0), '')] It's the parser that then associates the list of tokens into a syntax tree: >>> st = ast.parse("2+++2") >>> st 36 <_ast.Module at 0x7d2acc0> >>> ast.dump(st) 37 'Module(body=[Expr(value=BinOp(left=Num(n=2), op=Add(), right=UnaryOp(op=UAdd(), operand=UnaryOp(op=UAdd(), operand=Num(n=2)))))])' This follows standard disambiguation rules.
Pipe Output to Python File Question: How do a make a python script take input that has been piped to it. Is that a `sys.argv` moment. To be clear I want to figure out how to code the python side to receive input like this: cat someFile | domeSomething.py Can this be done? Again, to clarify, I'm not wanting to write this as passing a filename to my script and then using `open(filename)` I want to get piped input. Thanks for the help. Answer: To get piped input, you need to read from `stdin`: import sys print sys.stdin.read() `stdin` is a file, so feel free to use any of the [methods of a file object](http://docs.python.org/2/library/stdtypes.html#file-objects).
pythoninterpreter import error Question: I have problem with importing package in python module. That's what I do: from mega.mega import Mega if __name__ == "__main__": m = Mega() and from java I run: interpreter.execfile("api.py"); But I still get error: Exception in thread "main" Traceback (most recent call last): File "<string>", line 1, in <module> ImportError: No module named mega In mega folder I have mega.py file and `__init__.py` file to mark this folder as package. * * * Now I get: from mega.mega import Mega SyntaxError: ("'import *' not allowed with 'from .'", ...path... Answer: You'll need to add the parent directory of `mega` to `sys.path`: import sys import os PATH = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, PATH) from mega.mega import Mega `__file__` is the filename of the `api.py` module (can be relative).
Garbage collect a class with a reference to its instance? Question: Consider this code snippet: import gc from weakref import ref def leak_class(create_ref): class Foo(object): # make cycle non-garbage collectable def __del__(self): pass if create_ref: # create a strong reference cycle Foo.bar = Foo() return ref(Foo) # without reference cycle r = leak_class(False) gc.collect() print r() # prints None # with reference cycle r = leak_class(True) gc.collect() print r() # prints <class '__main__.Foo'> It creates a reference cycle that cannot be collected, because the referenced instance has a `__del__` method. The cycle is created here: # create a strong reference cycle Foo.bar = Foo() This is just a proof of concept, the reference could be added by some external code, a descriptor or anything. If that's not clear to you, remember that each objects mantains a reference to its class: +-------------+ +--------------------+ | | Foo.bar | | | Foo (class) +------------>| foo (Foo instance) | | | | | +-------------+ +----------+---------+ ^ | | foo.__class__ | +--------------------------------+ If I could guarantee that `Foo.bar` is only accessed from `Foo`, the cycle wouldn't be necessary, as theoretically the instance could hold only a weak reference to its class. Can you think of a practical way to make this work without a leak? * * * As some are asking why would external code modify a class but can't control its lifecycle, consider this example, similar to the real-life example I was working to: class Descriptor(object): def __get__(self, obj, kls=None): if obj is None: try: obj = kls._my_instance except AttributeError: obj = kls() kls._my_instance = obj return obj.something() # usage example # class Example(object): foo = Descriptor() def something(self): return 100 print Example.foo In this code only `Descriptor` (a [non-data descriptor](http://docs.python.org/2/reference/datamodel.html#invoking- descriptors)) is part of the API I'm implementing. `Example` class is an example of how the descriptor would be used. Why does the descriptor store a reference to an instance inside the class itself? Basically for caching purposes. `Descriptor` required this contract with the implementor: it would be used in any class assuming that 1. The class has a constructor with no args, that gives an "anonymous instance" (my definition) 2. The class has some behavior-specific methods (`something` here). 3. An instance of the class can stay alive for an undefined amount of time. It doesn't assume anything about: 1. How long it takes to construct an object 2. Whether the class implements **del** or other magic methods 3. How long the class is expected to live Moreover the API was designed to avoid any extra load on the class implementor. I could have moved the responsibility for caching the object to the implementor, but I wanted a standard behavior. There actually is a simple solution to this problem: make the default behavior to cache the instance (like it does in this code) but allow the implementor to override it if they have to implement `__del__`. Of course this wouldn't be as simple if we assumed that the class state _had_ to be preserved between calls. * * * As a starting point, I was coding a "weak object", an implementation of `object` that only kept a weak reference to its class: from weakref import proxy def make_proxy(strong_kls): kls = proxy(strong_kls) class WeakObject(object): def __getattribute__(self, name): try: attr = kls.__dict__[name] except KeyError: raise AttributeError(name) try: return attr.__get__(self, kls) except AttributeError: return attr def __setattr__(self, name, value): # TODO: implement... pass return WeakObject Foo.bar = make_proxy(Foo)() It appears to work for a limited number of use cases, but I'd have to reimplement the whole set of `object` methods, and I don't know how to deal with classes that override `__new__`. Answer: For your example, why don't you store `_my_instance` in a dict on the descriptor class, rather than on the class holding the descriptor? You could use a weakref or WeakValueDictionary in that dict, so that when the object disappears the dict will just lose its reference and the descriptor will create a new one on the next access. Edit: I think you have a misunderstanding about the possibility of collecting the class while the instance lives on. Methods in Python are stored on the class, not the instance (barring peculiar tricks). If you have an object `obj` of class `Class`, and you allowed `Class` to be garbage collected while `obj` still exists, then calling a method `obj.meth()` on the object would fail, because the method would have disappeared along with the class. That is why your only option is to weaken your class->obj reference; even if you could make objects weakly reference their class, all it would do is break the class if the weakness ever "took effect" (i.e., if the class were collected while an instance still existed).
Networkx Dataset Creation Question: I have data for a directed graph in the form of Node1 Node2 A B A C C A D A Which means, a directed edge/link between A --> B, A --> C and so on. I want to create this data into dataset supported by Networkx for modelling in Python. I want keep the file size as minimum as possible. I have edges/links of about 1 Million. Answer: import networkx as nx import matplotlib.pyplot as plt content = '''\ Node1 Node2 A B A C C A D A''' lines = content.splitlines() G = nx.DiGraph() for line in lines[1:]: # skip the first (header) line a, b = map(str.strip, line.split()) G.add_edge(a, b) nx.draw(G) plt.savefig('/tmp/graph.png') # plt.show() ![enter image description here](http://i.stack.imgur.com/qPOs3.png)
Data handling for matplotlib histogram with error bars Question: I've got a data set which is a list of tuples in python like this: dataSet = [(6.1248199999999997, 27), (6.4400500000000003, 4), (5.9150600000000004, 1), (5.5388400000000004, 38), (5.82559, 1), (7.6892199999999997, 2), (6.9047799999999997, 1), (6.3516300000000001, 76), (6.5168699999999999, 1), (7.4382099999999998, 1), (5.4493299999999998, 1), (5.6254099999999996, 1), (6.3227700000000002, 1), (5.3321899999999998, 11), (6.7402300000000004, 4), (7.6701499999999996, 1), (5.4589400000000001, 3), (6.3089700000000004, 1), (6.5926099999999996, 2), (6.0003000000000002, 5), (5.9845800000000002, 1), (6.4967499999999996, 2), (6.51227, 6), (7.0302600000000002, 1), (5.7271200000000002, 49), (7.5311300000000001, 7), (5.9495800000000001, 2), (5.1487299999999996, 18), (5.7637099999999997, 6), (5.5144500000000001, 44), (6.7988499999999998, 1), (5.2578399999999998, 1)] Where the first element of the tuple is an energy and the second a counter, how many sensor where affected. I want to create a histogram to study the relation between the number of affected sensors and the energy. I'm pretty new to matplotlib (and python), but this is what I've done so far: import math import matplotlib.pyplot as plt dataSet = [(6.1248199999999997, 27), (6.4400500000000003, 4), (5.9150600000000004, 1), (5.5388400000000004, 38), (5.82559, 1), (7.6892199999999997, 2), (6.9047799999999997, 1), (6.3516300000000001, 76), (6.5168699999999999, 1), (7.4382099999999998, 1), (5.4493299999999998, 1), (5.6254099999999996, 1), (6.3227700000000002, 1), (5.3321899999999998, 11), (6.7402300000000004, 4), (7.6701499999999996, 1), (5.4589400000000001, 3), (6.3089700000000004, 1), (6.5926099999999996, 2), (6.0003000000000002, 5), (5.9845800000000002, 1), (6.4967499999999996, 2), (6.51227, 6), (7.0302600000000002, 1), (5.7271200000000002, 49), (7.5311300000000001, 7), (5.9495800000000001, 2), (5.1487299999999996, 18), (5.7637099999999997, 6), (5.5144500000000001, 44), (6.7988499999999998, 1), (5.2578399999999998, 1)] binWidth = .2 binnedDataSet = [] #create another list and append the "binning-value" for item in dataSet: binnedDataSet.append((item[0], item[1], math.floor(item[0]/binWidth)*binWidth)) energies, sensorHits, binnedEnergy = [[q[i] for q in binnedDataSet] for i in (0,1,2)] plt.plot(binnedEnergy, sensorHits, 'ro') plt.show() This works so far (although it doesn't even look like a histogram ;-) but OK), but now I want to calculate the mean value for each bin and append some error bars. What's the way to do it? I looked at histogram examples for matplotlib, but they all use one-dimensional data which will be counted, so you get a frequency spectrum… That's not really what I want. Answer: I am somewhat confused by exactly what you are trying to do, but I think this (to first order) will do what I think you want: bin_width = .2 bottom = 5.0 top = 8.0 binned_data = [0.0] * int(math.ceil(((top - bottom) / bin_width))) binned_count = [0] * int(math.ceil(((top - bottom) / bin_width))) n_bins = len(binned_data) for E, cnt in dataSet: if E < bottom or E > top: print 'out of range' continue bin_id = int(math.floor(n_bins * (E - bottom) / (top - bottom))) binned_data[bin_id] += cnt binned_count[bin_id] += 1 binned_avergaed_data = [C_sum / hits if hits > 0 else 0 for C_sum, hits in zip(binned_data, binned_count)] bin_edges = [bottom + j * bin_width for j in range(len(binned_data))] plt.bar(bin_edges, binned_avergaed_data, width=bin_width) I would also suggest looking into `numpy`, it would make this much simpler to write.
My first Google App Engine/Python app Question: I am trying to write my first GAE/Python application that does the following three things: 1. Displays a form where the user can enter details about themself (index.html) 2. Stores the submitted form data in the datastore 3. Retrieves all data from datastore and displays all results above the form (index.html) However, I'm getting the following error > line 15, in MainPage 'people' : people NameError: name 'people' is not > defined Any advice on how to resolve this and get my app working will be appreciated! **main.py** import webapp2 import jinja2 import os jinja_environment = jinja2.Environment( loader=jinja2.FileSystemLoader(os.path.dirname(__file__))) class MainPage(webapp2.RequestHandler): def get(self): people_query = Person.all() people = people_query.fetch(10) template_values = { 'people': people } template = jinja_environment.get_template('index.html') self.response.out.write(template.render(template_values)) # retrieve the submitted form data and store in datastore class PeopleStore(webapp2.RequestHandler): def post(self): person = Person() person.first_name = self.request.get('first_name') person.last_name = self.request.get('last_name') person.city = self.request.get('city') person.birth_year = self.request.get('birth_year') person.birth_year = self.request.get('height') person.put() # models a person class class Person(db.Model): first_name = db.StringProperty() last_name = db.StringProperty() city = db.StringProperty() birth_year = db.IntegerProperty() height = db.IntegerProperty() app = webapp2.WSGIApplication([('/', MainPage), ('/new_person')], debug=True) **index.html** <html> <body> {% for person in people %} {% if person %} <b>{{ person.first_name }}</b> <b>{{ person.last_name }}</b> <b>{{ person.city }}</b> <b>{{ person.birth_year }}</b> <b>{{ person.height }}</b> <hr></hr> {% else %} No people found {% endfor %} <form action="/new_person" method="post"> <div><textarea name="first_name" rows="3" cols="60"></textarea></div> <div><textarea name="last_name" rows="3" cols="60"></textarea></div> <div><textarea name="city" rows="3" cols="60"></textarea></div> <div><textarea name="birth_year" rows="3" cols="60"></textarea></div> <div><textarea name="height" rows="3" cols="60"></textarea></div> <div><input type="submit" value="Submit"></div> </form> </body> </html> **app.yaml** application: some_name version: 1 runtime: python27 api_version: 1 threadsafe: true handlers: - url: /.* script: main.app libraries: - name: jinja2 version: latest * * * **EDIT 1** *_main.py_ * import webapp2 import jinja2 import os from google.appengine.ext import db jinja_environment = jinja2.Environment( loader=jinja2.FileSystemLoader(os.path.dirname(__file__))) class MainPage(webapp2.RequestHandler): def get(self): people_query = Person.all() people = people_query.fetch(10) template_values = { 'people': people } template = jinja_environment.get_template('index.html') self.response.out.write(template.render(template_values)) class PeopleStore(webapp2.RequestHandler): def post(self): person = Person() person.first_name = self.request.get('first_name') person.last_name = self.request.get('last_name') person.city = self.request.get('city') person.birth_year = self.request.get('birth_year') person.height = self.request.get('height') person.put() class Person(db.Model): first_name = db.StringProperty() last_name = db.StringProperty() city = db.StringProperty() birth_year = db.IntegerProperty() height = db.IntegerProperty() app = webapp2.WSGIApplication([('/', MainPage), ('/new_person')], debug=True) * * * **EDIT 2** *_main.py_ * The following edit fixed this error > AttributeError: 'str' object has no attribute 'get_match_routes' app = webapp2.WSGIApplication([('/', MainPage),('/new_person',PeopleStore)], debug=True) Ok great, the form displays in the browser, but when I submit the data, I get this error: > BadValueError: Property birth_year must be an int or long, not a unicode * * * **EDIT 3 main.py** person.birth_year = int(self.request.get('birth_year')) person.height = int(self.request.get('height')) resolved this error: > badvalueerror property must be an int or long, not a unicode Ok, good so far. The data stores in the data store. However, my page comes up blank... Answer: You have an indentation problem. Lines 3 and onwards of your `get` method should be indented at the same level as the first two lines. Otherwise, they are not part of the method, but the class definition itself, and will be executed when the class is defined - at which point there is no variable `people` in scope.
Disable automatic printing in Python interactive session Question: I am going to be holding a Python workshop to teach some beginner level programmers at my college Python. I am looking for a way to modify the default behavior of Python interactive sessions so that expressions do not automatically print out results. For example, take this following interactive session: wil@calcifer:~$ python Python 2.7.3 (default, Aug 1 2012, 05:16:07) [GCC 4.6.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> x = 5 >>> y = 7 >>> x + y 12 >>> first_name = "Test" >>> last_name = "Person" >>> first_name + last_name 'TestPerson' >>> This would enforce the use of the `print` statement to avoid confusion later on. This isn't crucial, but I was surprised that I was unable to find any settings for this anywhere. I would be able to preconfigure the machine beforehand, so any solutions would work. Does anyone know if this is possible, or what change to the interactive sessions creates this effect? Answer: The expression printing in interactive sessions is mediated via a call to `sys.displayhook`. Just override it to a NOP: >>> import sys >>> sys.displayhook = lambda x: None >>> 2 + 3 >>> print 2 + 3 5 >>> In a plain Python session it is wired to sys.stdout. Applications that offer a Python shell on a GUI are expcted to use it to print the expression values back to the user. You can write your pythonrc.py ( ~/.pythonrc.py file) to do this by default, each time the interpreter is called. Further documentation on sys.displayhook can be found here: <http://docs.python.org/3/library/sys.html#sys.displayhook>
Python Popen: Write to stdout AND log file simultaneously Question: I am using Popen to call a shell script that is continuously writing its stdout and stderr to a log file. Is there any way to simultaneously output the log file continuously (to the screen), or alternatively, make the shell script write to both the log file and stdout at the same time? I basically want to do something like this in Python: cat file 2>&1 | tee -a logfile #"cat file" will be replaced with some script Again, this pipes stderr/stdout together to tee, which writes it both to stdout and my logfile. I know how to write stdout and stderr to a logfile in Python. Where I'm stuck is how to duplicate these back to the screen: subprocess.Popen("cat file", shell=True, stdout=logfile, stderr=logfile) Of course I could just do something like this, but is there any way to do this without tee and shell file descriptor redirection?: subprocess.Popen("cat file 2>&1 | tee -a logfile", shell=True) Answer: You can use a pipe to read the data from the program's stdout and write it to all the places you want: import sys import subprocess logfile = open('logfile', 'w') proc=subprocess.Popen(['cat', 'file'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) for line in proc.stdout: sys.stdout.write(line) logfile.write(line) proc.wait() _UPDATE_ In python 3, the `universal_newlines` parameter controls how pipes are used. If `False`, pipe reads return `bytes` objects and may need to be decoded (e.g., `line.decode('utf-8')`) to get a string. If `True`, python does the decode for you > Changed in version 3.3: When universal_newlines is True, the class uses the > encoding locale.getpreferredencoding(False) instead of > locale.getpreferredencoding(). See the io.TextIOWrapper class for more > information on this change.
How to write a whole string to a file in Python and where does the file go? Question: I am doing an assignment on text formatting and alignment (text wrapping) and I need to write my formatted string to new file. But once I have written to the file (or think I've written) where does that file go? Does it actually create a file on my desktop or am I being stupid? This is my code: txtFile = open("Output.txt", "w") txtFile.write(string) txtFile.close() return txtFile Cheers, JT Answer: The text is written to a file called "Output.txt" in your working directory (which is usually the directory from which the script has been executed). To display the working directory, you can use: >>> import os >>> os.getcwd() '/home/adam'
How to Radix Sort using Queues? Question: How do you properly radix sort a list using queues? I'm using Python 3x. This is my attempt using queues as bins since queues are a first-in-first-out data structure. from my_queue import Queue def rsort(n): '''(list of int) -> list of int ''' list_length = len(n) val = 0 mod = 10 k = 1 bin_list = [] alist = n for bins in range(0,10): bin_list.append(Queue()) while val == 0: for num in alist: sig_dig = num % mod sig_dig = int(sig_dig / k) bin_list[sig_dig].enqueue(num) if bin_list[0].size() == list_length: alist.append(bin_list[0].dequeue()) else: mod = mod * 10 k = k * 10 new_list = [] for bins in bin_list: if not bins.is_empty(): new_list.append(bins.dequeue()) alist = new_list return alist My code works perfectly fine with small numbers such as: `[3,2,6,5,8,7]` but when values in the list become large like: `[240, 28, 5, 18, 140, 2]` my program no longer sorts the list, numbers end up missing and unordered. I've been playing around with my program a lot but I just can't fix it :( Answer: There are a couple of things that seem wrong in your code. I'm not sure exactly which of these is causing the issues you're seeing, but probably all of them need to be fixed before you will get the right results. First, a quick note: You can simplify the logic a bit by only using a single integer to find the right digit in each of your numbers. I suggest a value that starts at zero and goes up to some value (the number of digits you want to sort on). You can find that digit's value for a given list item with `sig_dig = num // 10**k % 10`. The `//` operator forces Python to use "floor division", truncating off the non-integer part of normal division. Anyway, the first issue is that you're looping on `val == 0`, but you never modify `val`, and you return a value before the end of the loop (so you'll never do it more than once anyway). You can fix this by calculating the number of digits in the longest value of your list with something like `max_digits = int(math.ceil(math.log(max(lst), 10)))`. Then you can make your loop much simpler: `for k in range(max_digits):` The next issue I see is that you're probably not getting the values from the bins back into a list properly. You're only calling `dequeue` once, but you should probably be calling it repeatedly until the queue is empty. Or, if I'm misunderstanding the `Queue` API you're using and `dequeue` returns all the queue's values, you need to use `extend` to add them all to the list at once. Here's what I think you want to have, in the end: import math from my_queue import Queue def rsort(n): '''(list of int) -> list of int ''' bin_list = [Queue for _ in range(10)] max_digits = int(math.ceil(math.log(max(lst), 10))) # calculate # of digits for k in range(max_digits): for num in alist: sig_dig = num / 10**k % 10 # find digit's value bin_list[sig_dig].enqueue(num) n = [] # we can reuse the name `n`, rather than using a different name for bins in bin_list: while not bins.is_empty(): # loop to dequeue all values n.append(bins.dequeue()) return n # the return statement is outside the loop!
Using own code in pyhook pumpmessages Question: i want to check if the file in which i am writing the keys is more than 2Kb . If it is more than 2KB then i need to make another file and stop writing in this one. I am a beginer in python please help me this. Please indicate where can i use the code for checking if file is more than 2kb. import win32api , win32console , win32gui , pythoncom , pyHook , sys, time ,os import datetime now = datetime.datetime.now() p = now.strftime("%Y-%m-%d %H-%M") temp_path = p fil = temp_path + '.txt' sys.stdout = open(fil,'w') lastWindow = None lastWindow=win32gui.GetWindowText (win32gui.GetForegroundWindow()) while True: def OnKeyboardEvent(event): global lastWindow window = event.WindowName key = chr(event.Ascii) if window != lastWindow: print window lastWindow = window print key hm = pyHook.HookManager() hm.KeyDown = OnKeyboardEvent hm.HookKeyboard() pythoncom.PumpMessages() Hope you can help Answer: you could use `.getsize`. >>> import os >>> b = os.path.getsize("/path/isa_005.mp3") >>> b 2071611L
Soappy error: Fault SOAP-ENV:Server: Cannot use object of type stdClass as array Question: I wanted to access with soappy a webservices of my internet provider. here is a example in php from the provider of the Soap Services: <http://kasapi.kasserver.com/dokumentation/?open=soap> but I am not getting smart, to get it to run in python. I always get this error message: "Cannot use object of type stdClass as array" Any ideas how to solve that?! My program has 34 lines.... Here is the code: from SOAPpy import WSDL from SOAPpy.Errors import HTTPError as SoapHTTPError from SOAPpy.Types import faultType import hashlib from array import array class KASSystem(object): def __init__(self): WSDL_AUTH = 'https://kasapi.kasserver.com/soap/wsdl/KasAuth.wsdl' WSDL_API = 'https://kasapi.kasserver.com/soap/wsdl/KasApi.wsdl' userpass = ['mylogin','mypassword'] m = hashlib.sha1() m.update(userpass[1]) userpass[1] = m.hexdigest() loginData = {'user':userpass[0],'pass':userpass[1]} self.__SoapServer = WSDL.Proxy(WSDL_AUTH) try: self.__CredentialToken = self.__SoapServer.KasAuth({ 'KasUser':loginData['user'], 'KasAuthType':'sha1', 'KasPassword':loginData['pass'], 'SessionLifeTime':1800,'SessionUpdateLifeTime':'Y'}) except (SoapHTTPError), e: print "Fehlermeldung:", e.code,e.msg KasObj = KASSystem() I got this error message: Traceback (most recent call last): File "/storage/PyProjects/toolsAPP/KASUpdate.py", line 33, in <module> KasObj = KASSystem() File "/storage/PyProjects/toolsAPP/KASUpdate.py", line 28, in __init__ 'SessionLifeTime':1800,'SessionUpdateLifeTime':'Y'}) File "build/bdist.linux-x86_64/egg/SOAPpy/Client.py", line 540, in __call__ File "build/bdist.linux-x86_64/egg/SOAPpy/Client.py", line 562, in __r_call File "build/bdist.linux-x86_64/egg/SOAPpy/Client.py", line 475, in __call SOAPpy.Types.faultType: <Fault SOAP-ENV:Server: Cannot use object of type stdClass as array> Answer: 1st paramter of method MUST be the message name, 2nd parameter the Dict with all it's parameters......
Shell Script Error | Works in Command Line - Not in Script Question: Background: I'm using NMAP, shell script, and a python script to run a scan on a list of IPs. The python portion parses the XML output of nmap to generate two lists, a list of alive hosts and down hosts. The python then re-executes the shell script(starting point) on the list of down hosts over and over until one becomes alive and the info gets appended onto the xml and the two lists of hosts gets corrected. Problem: This was once working but now I'm getting strange behavior(syntax error) when running the shell script on the list of down hosts. Script: # Grap Complete Info in XML file sudo nmap -v -sS -oX full-scan.xml --append-output --no-stylesheet -iL $1 # Set permissions of xml for python script to write sudo chmod a+rw full-scan.xml # Clean NMAP XML Root Appends sed '/<?xml/s/.*//' full-scan.xml > scan.tmp && mv scan.tmp full-scan.xml sed 's/<\/nmaprun>//g' full-scan.xml > scan.tmp && mv scan.tmp full-scan.xml sed '/<nmaprun/d' full-scan.xml > scan.tmp && mv scan.tmp full-scan.xml echo "<nmaprun>" | cat - full-scan.xml > temp && echo "</nmaprun>" >> temp mv temp full-scan.xml # Run python parser here ./parseXMLnmap.py full-scan.xml * * * Error: ./scanIPlist.sh ip.list.down Starting Nmap 5.00 ( http://nmap.org ) at 2013-03-21 11:55 EDT .... Nmap done: 8 IP addresses (0 hosts up) scanned in 0.59 seconds Raw packets sent: 16 (672B) | Rcvd: 0 (0B) de????@????:~/workspace/nmap-script$ File "./scanIPlist.sh", line 6 sudo nmap -v -sS -oX full-scan.xml --append-output --no-stylesheet -iL $1 ^ SyntaxError: invalid syntax I'm confused at pinpointing where the problem is... when I use this command: "sudo nmap -v -sS -oX full-scan.xml --append-output --no-stylesheet -iL ip.list.down" in the command line.. it works perfectly fine. You can see nmap doing the command so where is the error coming from that's stopping the rest of my script from continuing? If I comment out every line after the nmap command it works so I thought maybe a permission issue but I tried executing the sed and mv commands with sudo but that didn't fix the issue. Permissions are as follows after the first run on the ORIGINAL IP list: ls -l total 32 -rw------- 1 user user 11469 2013-03-21 12:03 full-scan.xml -rw------- 1 user user 110 2013-03-21 12:03 ip.list.down -rw------- 1 user user 238 2013-03-20 14:44 ip.list.orig -rw------- 1 user user 128 2013-03-21 12:03 ip.list.up -rwx--x--x 1 user user 1528 2013-03-21 10:26 parseXMLnmap.py -rwx--x--x 1 user user 676 2013-03-21 12:02 scanIPlist.sh So the problem is that I need a loop that never ends, but does not keep creating more and more processes. User Input Start -> Shell Script -> Python Script -> Shell Script -> .... and so on until interrupted by the user. Previously, In my python code I was using: subprocess.call(['./scanIPList.sh', 'ip.list.down']) This was no good because the processes would stay open and it would just keep creating them over and over until the computer would eventually crash. I needed it to detach from the child process and exit when it executes the next script. I tried using this: subprocess.Popen([sys.executable, './scanIPlist.sh', 'ip.list.down']) this must be the cause of issue I am getting now. any help appreciated. Answer: `SyntaxError: invalid syntax` is a `python` error. Looks like you are trying to run shell commands in a python program. You probably need `import subprocess`. Or maybe you have `#!/usr/bin/python` at the top of your shell script?
Python unzip AES-128 encrypted file Question: Is there a way to decompress an AES-128 encrypte file directly with python, since ZipFile throws a Bad Password error. If i use 7zip it works, so the password is correct, but then again 7zip needs to be installed as a dependency. What i tried: from ZipFile import ZipFile zip = ZipFile('test.zip') zip.extractall(pwd='password') This throws the Bad Password exception. Checking the file with 7zip 7z l -slt test.zip This returns: Encrypted = + Method = pkAES-128 Deflate Answer: The zipfile module from the Python standard library supports only CRC32 encrypted zip files (see here: <http://hg.python.org/cpython/file/71adf21421d9/Lib/zipfile.py#l420> ). So, there is no way around some 3rd party dependency. The easiest way would be to just install 7zip and call the commandline utility `7z` using the `subprocess` module from the standard lib: import subprocess subprocess.call(["7z", "x", "-ppassword", "test.zip"]) Another option would be the python module "PyLzma" which can also handle AES encrypted 7zip archives: <https://github.com/fancycode/pylzma> . It doesn't directly support decrypting classic zip files but you could use its routines to write your own decompressor function.
Pass enum to ndb.Model field in python Question: I find [What's the best way to implement an 'enum' in Python?](http://stackoverflow.com/questions/36932/whats-the-best-way-to- implement-an-enum-in-python) for how to create enum in python. I have a field in my `ndb.Model` that I want to accept one of my enum values. Do I simply set the field to `StringProperty`? My enum is def enum(**enums): return type('Enum', (), enums) ALPHA = enum(A="A", B="B", C="C", D="D") Answer: This is fully supported in the [ProtoRPC Python API](https://developers.google.com/appengine/docs/python/tools/protorpc/) and it's not worth rolling your own. A simple Enum would look like the following: from protorpc import messages class Alpha(messages.Enum): A = 0 B = 1 C = 2 D = 3 As it turns out, `ndb` has `msgprop` module for storing `protorpc` objects and this is [documented](https://developers.google.com/appengine/docs/python/ndb/properties#msgprop). So to store your `Alpha` enum, you'd do the following: from google.appengine.ext import ndb from google.appengine.ext.ndb import msgprop class Part(ndb.Model): alpha = msgprop.EnumProperty(Alpha, required=True) ... **EDIT** : As pointed out by [hadware](http://stackoverflow.com/users/1327143/hadware), a `msgprop.EnumProperty` is not indexed by default. If you want to perform queries over such properties you'd need to define the property as alpha = msgprop.EnumProperty(Alpha, required=True, indexed=True) and then perform queries ndb.query(Part.alpha == Alpha.B) or use any value other than `Alpha.B`.
turn scatter data into binned data with errors bars equal to standard deviation Question: I have a bunch of data scattered x, y. If I want to bin these according to x and put error bars equal to the standard deviation on them, how would I go about doing that? The only I know of in python is to loop over the data in x and group them according to bins (max(X)-min(X)/nbins) then loop over those blocks to find the std. I'm sure there are faster ways of doing this with numpy. I want it to look similar to "vert symmetric" in: <http://matplotlib.org/examples/pylab_examples/errorbar_demo.html> Answer: You can bin your data with `np.histogram`. I'm reusing code from [this other answer](http://stackoverflow.com/questions/15477857/mean-values-depending-on- binning-with-respect-to-second-variable/15478137#15478137) to calculate the mean and standard deviation of the binned `y`: import numpy as np import matplotlib.pyplot as plt x = np.random.rand(100) y = np.sin(2*np.pi*x) + 2 * x * (np.random.rand(100)-0.5) nbins = 10 n, _ = np.histogram(x, bins=nbins) sy, _ = np.histogram(x, bins=nbins, weights=y) sy2, _ = np.histogram(x, bins=nbins, weights=y*y) mean = sy / n std = np.sqrt(sy2/n - mean*mean) plt.plot(x, y, 'bo') plt.errorbar((_[1:] + _[:-1])/2, mean, yerr=std, fmt='r-') plt.show() ![enter image description here](http://i.stack.imgur.com/kHCS8.png)
Python: Parse web content for lines containing a specific character and store into a file Question: I am new to python. I have this webpage containing the contents: <Response> <Value type="ABC">107544</Value> <Value type="EFG">10544</Value> <Value type="ABC">77544</Value> I would like to parse lines containing ABC and store only the numbers within a temporary text file. How can I do this? Currently I have htmlpage = urllib2.urlopen(<URL>) result = htmlpage.read() Answer: Put your result into `BeautifulSoup`, and you will be able to extract any data very easily without regex # UPDATED: from bs4 import BeautifulSoup result = '''<div class="test"> <a href="example">Result 1</a> </div> <div class="test"> <a href="example2">Result 2</a> </div>''' soup = BeautifulSoup(result) for div in soup.findAll('div', attrs={'class':'test'}): print div.find('a').text Result 1 Result 2
rpy2 / R issue in loess function via Python? Question: I'm trying to call the R function `loess` via Rpy2 in Python on this datafile: <http://filebin.ca/azuz9Piv0z8/test.data> It works when I use a subset of the data (the first 1000 points) but when I try to use the entire file, I get an error. My code: import pandas from rpy2.robjects import r import rpy2.robjects as robjects data = pandas.read_table(os.path.expanduser("~/test2.data"), sep="\t").values small_data = data[0:1000, :] print "small data loess:" a, b = robjects.FloatVector(list(small_data[:, 0])), \ robjects.FloatVector(list(small_data[:, 1])) df = robjects.DataFrame({"a": a, "b": b}) loess_fit = r.loess("b ~ a", data=df) print loess_fit print "large data loess:" a, b = robjects.FloatVector(list(data[:, 0])), \ robjects.FloatVector(list(data[:, 1])) df = robjects.DataFrame({"a": a, "b": b}) loess_fit = r.loess("b ~ a", data=df) print loess_fit Fitting on `small_data` works but not `data`. I get the error: Error in simpleLoess(y, x, w, span, degree, parametric, drop.square, normalize, : NA/NaN/Inf in foreign function call (arg 1) loess_fit = r.loess("b ~ a", data=df) File "/usr/local/lib/python2.7/dist-packages/rpy2-2.3.3-py2.7-linux-x86_64.egg/rpy2/robjects/functions.py", line 86, in __call__ return super(SignatureTranslatedFunction, self).__call__(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/rpy2-2.3.3-py2.7-linux-x86_64.egg/rpy2/robjects/functions.py", line 35, in __call__ res = super(Function, self).__call__(*new_args, **new_kwargs) rpy2.rinterface.RRuntimeError: Error in simpleLoess(y, x, w, span, degree, parametric, drop.square, normalize, : NA/NaN/Inf in foreign function call (arg 1) How can this be fixed? I'm not sure if it's a problem with the R function `loess` or with the Rpy2 interface to it? thanks. Answer: The problem are `-Inf` values in your data: DF <- read.table('http://filebin.ca/azuz9Piv0z8/test.data') DF[!is.finite(DF[,1]) | !is.finite(DF[,2]),] # V1 V2 # 5952 -Inf -Inf
Processing XML With Hadoop Streaming failed Question: i did bin/hadoop jar contrib/streaming/hadoop-streaming-1.0.4.jar -inputreader "StreamXmlRecordReader, begin=<metaData>,end=</metaData>" -input /user/root/xmlpytext/metaData.xml -mapper /Users/amrita/desktop/hadoop/pythonpractise/mapperxml.py -file /Users/amrita/desktop/hadoop/pythonpractise/mapperxml.py -reducer /Users/amrita/desktop/hadoop/pythonpractise/reducerxml.py -file /Users/amrita/desktop/hadoop/pythonpractise/mapperxml.py -output /user/root/xmlpytext-output1 -numReduceTasks 1 but it shows 13/03/22 09:38:48 INFO mapred.FileInputFormat: Total input paths to process : 1 13/03/22 09:38:49 INFO streaming.StreamJob: getLocalDirs(): [/Users/amrita/desktop/hadoop/temp/mapred/local] 13/03/22 09:38:49 INFO streaming.StreamJob: Running job: job_201303220919_0001 13/03/22 09:38:49 INFO streaming.StreamJob: To kill this job, run: 13/03/22 09:38:49 INFO streaming.StreamJob: /private/var/root/hadoop-1.0.4/libexec/../bin/hadoop job -Dmapred.job.tracker=-kill job_201303220919_0001 13/03/22 09:38:49 INFO streaming.StreamJob: Tracking URL: http://localhost:50030/jobdetails.jsp?jobid=job_201303220919_0001 13/03/22 09:38:50 INFO streaming.StreamJob: map 0% reduce 0% 13/03/22 09:39:26 INFO streaming.StreamJob: map 100% reduce 100% 13/03/22 09:39:26 INFO streaming.StreamJob: To kill this job, run: 13/03/22 09:39:26 INFO streaming.StreamJob: /private/var/root/hadoop-1.0.4/libexec/../bin/hadoop job -Dmapred.job.tracker=-kill job_201303220919_0001 13/03/22 09:39:26 INFO streaming.StreamJob: Tracking URL: http:///jobdetails.jsp?jobid=job_201303220919_0001 13/03/22 09:39:26 ERROR streaming.StreamJob: Job not successful. Error: # of failed Map Tasks exceeded allowed limit. FailedCount: 1. LastFailedTask: task_201303220919_0001_m_000000 13/03/22 09:39:26 INFO streaming.StreamJob: killJob... Streaming Command Failed! when i went through jobdetails.jsp there it shows java.lang.RuntimeException: java.lang.reflect.InvocationTargetException at org.apache.hadoop.streaming.StreamInputFormat.getRecordReader(StreamInputFormat.java:77) at org.apache.hadoop.mapred.MapTask$TrackedRecordReader.<init>(MapTask.java:197) at org.apache.hadoop.mapred.MapTask.runOldMapper(MapTask.java:418) at org.apache.hadoop.mapred.MapTask.run(MapTask.java:372) at org.apache.hadoop.mapred.Child$4.run(Child.java:255) at java.security.AccessController.doPrivileged(Native Method) at javax.security.auth.Subject.doAs(Subject.java:396) at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1121) at org.apache.hadoop.mapred.Child.main(Child.java:249) Caused by: java.lang.reflect.InvocationTargetException at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27) at java.lang.reflect.Constructor.newInstance(Constructor.java:513) at org.apache.hadoop.streaming.StreamInputFormat.getRecordReader(StreamInputFormat.java:74) ... 8 more Caused by: java.io.IOException: JobConf: missing required property: stream.recordreader.begin at org.apache.hadoop.streaming.StreamXmlRecordReader.checkJobGet(StreamXmlRecordReader.java:278) at org.apache.hadoop.streaming.StreamXmlRecordReader.<init>(StreamXmlRecordReader.java:52) ... 13 more my mapper #!/usr/bin/env python import sys import cStringIO import xml.etree.ElementTree as xml def cleanResult(element): result = None if element is not None: result = element.text result = result.strip() else: result = "" return result def process(val): root = xml.fromstring(val) sceneID = cleanResult(root.find('sceneID')) cc = cleanResult(root.find('cloudCover')) returnval = ("%s,%s") % (sceneID,cc) return returnval.strip() if __name__ == '__main__': buff = None intext = False for line in sys.stdin: line = line.strip() if line.find("<metaData>") != -1: intext = True buff = cStringIO.StringIO() buff.write(line) elif line.find("</metaData>") != -1: intext = False buff.write(line) val = buff.getvalue() buff.close() buff = None print process(val) else: if intext: buff.write(line) and reducer #!/usr/bin/env python import sys if __name__ == '__main__': for line in sys.stdin: print line.strip() can anyone tell me why this happens. I am using hadoop-1.0.4 im mac. Is there any thing wrong. Should i change any thing . pls help me out. Answer: Remove space in between comma and begin `, begin=<`. The correct format is : hadoop jar hadoop-streaming.jar -inputreader "StreamXmlRecord,begin=BEGIN_STRING,end=END_STRING" ..... (rest of the command) This is due to the code surrounding the following lines in `org.apache.hadoop.streaming.StreamJob` for (int i = 1; i < args.length; i++) { String[] nv = args[i].split("=", 2); String k = "stream.recordreader." + nv[0]; String v = (nv.length > 1) ? nv[1] : ""; jobConf_.set(k, v); }
scikit learn SVM, how to save/load support vectors? Question: using python scikit svm, after running clf.fit(X, Y), you get your support vectors. could I load these support vectors directly (passing them as paramter) when instantiate a svm.SVC object? which means I do not need to running fit() method each time to do predication Answer: From the scikit manual: <http://scikit- learn.org/stable/modules/model_persistence.html> 1.2.4 Model persistence It is possible to save a model in the scikit by using Python’s built-in persistence model, namely pickle. >>> from sklearn import svm >>> from sklearn import datasets >>> clf = svm.SVC() >>> iris = datasets.load_iris() >>> X, y = iris.data, iris.target >>> clf.fit(X, y) SVC(kernel=’rbf’, C=1.0, probability=False, degree=3, coef0=0.0, eps=0.001, cache_size=100.0, shrinking=True, gamma=0.00666666666667) >>> import pickle >>> s = pickle.dumps(clf) >>> clf2 = pickle.loads(s) >>> clf2.predict(X[0]) array([ 0.]) >>> y[0] 0 In the specific case of the scikit, it may be more interesting to use joblib’s replacement of pickle, which is more efficient on big data, but can only pickle to the disk and not to a string: >>> from sklearn.externals import joblib >>> joblib.dump(clf, ’filename.pkl’)
Deploy Django project on Google App Engine Question: I have developed one example project in django1.4 & python 2.7, I want to deploy it on google app engine, but how to configure my project as per App Engine we didn't get. We have a site running on google app engine, but it is including with all html,js. How do we configure a database on google app engine to deploy our django project? Answer: Possibly the best option is to use Django Non-Rel. It's the only way (that I know of) to use the Django ORM (the django database interface) on Google App Engine without using Google's costly cloud SQL service. To do this, you'll need to use a customized version of Django and import several more libraries. It's a small project to get it up and running, but it's worth the effort. More information can be found on this website: <http://django-nonrel.org/> Note, that even though django-nonrel allows you to use the Django database interface, it will **not** allow you to use certain SQL features, such as joins. If you need joins, then your best option would be to use Google App Engine + Google Cloud SQL. [Documentation for that is here](https://developers.google.com/appengine/docs/python/cloud-sql/django). Regarding the comments: * Yes, it can run on windows, I run it on Windows. * Also, the site allbuttonspressed.com is old and out of date, use the one above for information.
ctypes reimplementation of rshift for c_ulong Question: i am accessing a C library via ctypes and i am stuck with the following problem: I am generating a "wrapper" (ctypes commands to access the library with ctypes) using ctypeslib. The C library contains macros which are converted to python functions in this step. (To be independent of the libraries internals as much as possible i want to use some of these macros in python.) One of these macros looks like this: # using the ctypes types myuint16_t = c_ushort myuint32_t = c_ulong def mymacro(x): return (myuint16_t)((myuint32_t)(x) >> 16) # macro I want to use the generated function in a seperate module in the following way (inside a function): return wrapper.mymacro(valueToBeConverted) # valueToBeConverted is an int But using this line i got the following error: .... def mymacro(x): return (myuint16_t)((myuint32_t)(x) >> 16) # macro TypeError: unsupported operand type(s) for >>: 'c_ulong' and 'int' (I know that the common way to shift a c_ulong is `c_ulongvar.value >> x` but i would have to patch the generated wrapper every time something changes in the C library. So i try to avoid this). It seems that the `__rshift__` implementation of c_ulong can not be used here. print c_ulong.__rshift__ # throws AttributeError: type object 'c_ulong' has no attribute '__rshift__' Hm, seems strange... So i decided to reimplement the `__rshift__` method of c_ulong to get it working: from ctypes import * from types import MethodType def rshift(self, val): print self.value >> val # create an unbound method which applies to all (even existing) instances c_ulong.__rshift__ = MethodType(rshift, None, c_ulong) a = c_ulong(1) a >> 16 But it does not fix the problem. I am still getting an error: a >> 16 TypeError: unsupported operand type(s) for >>: 'c_ulong' and 'int' Is it possible that the `__rshift__` method can be only used for two instances of the same class? I tried the following: def rshift(self, val): print self.value >> int(val.value) a = c_ulong(1) a >> c_ulong(16) and it works. But it would also mean i would still have to patch the generated wrapper. So: Does anybody know whats the trick here? **UPDATE** : The solution of @eryksun worked. I am using: from ctypes import * # from types import MethodType def _rshift(self, other): if hasattr(other, 'value'): other = other.value return c_ulong(self.value >> other) def _lshift(self, other): if hasattr(other, 'value'): other = other.value return c_ulong(self.value << other) def _coerce(self, other): try: return self, self.__class__(other) except TypeError: return NotImplemented # Add the functions to the type. A method is created when # accessed as an attribute of an instance. c_ulong.__lshift__ = _lshift c_ulong.__rshift__ = _rshift c_ulong.__coerce__ = _coerce Answer: Since the `_ctypes._SimpleCData` type doesn't have the `Py_TPFLAGS_CHECKTYPES` flag, 2.x subclasses are treated as old-style numbers that use `__coerce__` in binary operations. See [Objects/abstract.c](https://hg.python.org/cpython/file/v2.7.3/Objects/abstract.c#l900) for the calling scheme and the implementation in the function `binary_op1`. For demonstration purposes this flag can be toggled on the type object, which you only need to define (vaguely with a lot of `void *`) up to the `tp_flags` field. ## Hacking the `PyTypeObject` from ctypes import * import _ctypes Py_TPFLAGS_CHECKTYPES = 1 << 4 class PyTypeObject(Structure): _fields_ = (('ob_refcnt', c_ssize_t), ('ob_type', c_void_p), ('ob_size', c_ssize_t), ('tp_name', c_char_p), ('tp_basicsize', c_ssize_t), ('tp_itemsize', c_ssize_t), ('tp_dealloc', c_void_p), ('tp_print', c_void_p), ('tp_getattr', c_void_p), ('tp_setattr', c_void_p), ('tp_compare', c_void_p), ('tp_repr', c_void_p), ('tp_as_number', c_void_p), ('tp_as_sequence', c_void_p), ('tp_as_mapping', c_void_p), ('tp_hash', c_void_p), ('tp_call', c_void_p), ('tp_str', c_void_p), ('tp_getattro', c_void_p), ('tp_setattro', c_void_p), ('tp_as_buffer', c_void_p), ('tp_flags', c_long)) Next, create an `unsigned long` subclass, and use the `from_address` factory to create a `PyTypeObject` for it. Get the address with built-in `id`, which is an implementation detail specific to CPython: class c_ulong(_ctypes._SimpleCData): _type_ = "L" def __rshift__(self, other): print '__rshift__', self, other if hasattr(other, 'value'): other = other.value return c_ulong(self.value >> other) c_ulong_type = PyTypeObject.from_address(id(c_ulong)) ## Demo >>> a = c_ulong(16) >>> b = c_ulong(2) >>> a >> b __rshift__ c_ulong(16L) c_ulong(2L) c_ulong(4L) >>> a >> 2 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unsupported operand type(s) for >>: 'c_ulong' and 'int' The last step failed as expected. Now set the flag: >>> c_ulong_type.tp_flags |= Py_TPFLAGS_CHECKTYPES >>> a >> 2 __rshift__ c_ulong(16L) 2 c_ulong(4L) Problem solved? But that's a hack. Try again with `__coerce__` implemented. * * * ## Implement `__coerce__` class c_ulong(_ctypes._SimpleCData): _type_ = "L" def __rshift__(self, other): print '__rshift__', self, other if hasattr(other, 'value'): other = other.value return c_ulong(self.value >> other) def __coerce__(self, other): print '__coerce__', self, other try: return self, self.__class__(other) except TypeError: return NotImplemented ## Demo >>> a = c_ulong(16) >>> b = c_ulong(2) >>> a >> 2 __coerce__ c_ulong(16L) 2 __rshift__ c_ulong(16L) c_ulong(2L) c_ulong(4L) >>> 16 >> b __coerce__ c_ulong(2L) 16 __rshift__ c_ulong(16L) c_ulong(2L) c_ulong(4L) Of course it fails if a `c_ulong` can't be created, such as for a `float`: >>> a >> 2.0 __coerce__ c_ulong(16L) 2.0 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unsupported operand type(s) for >>: 'c_ulong' and 'float'
Simple indeterminate progress bar in Python Question: Even when I am afraid to be a bit off-topic, but I am not sure where else to ask this, sorry! I wish to build a `**simple** indeterminate progress bar` in Python there is a really valid p[rogression bar module](https://code.google.com/p/python-progressbar/) in Python, but my target is build a simple personal progress bar to add every time to my code the following my code it's a simple progress bar when you know the `maxvalue` of your data from __future__ import division import sys class Progress(object): def __init__(self, maxval): self._pct = 0 self.maxval = maxval def update(self, value): pct = int((value / self.maxval) * 100.0) if self._pct != pct: self._pct = pct self.display() def start(self): self.update(0) def finish(self): self.update(self.maxval) def display(self): sys.stdout.write("\r|%-73s| %d%%" % ('#' * int(self._pct*.73), self._pct)) sys.stdout.flush() import time toolbar_width = 300 pbar = Progress(toolbar_width) pbar.start() for i in xrange(toolbar_width): time.sleep(0.1) # do real work here pbar.update(i) pbar.finish() now i wish to create a new class IndeterminateProgress(object) in order to create a simple indeterminate progress bar when the maxvalue of your data is unknown. the basic idea is print from 0 to 100 and back from 100 to 0 and again until all data are all read or all processed (code update with the help of Ethan Coon, see below) class IndeterminateProgress(object): def __init__(self): self._pct = 0 self.maxval = 100 def update(self,value): abs_pct = value % self.maxval # this gives the percentage change from maxval phase = int(value / self.maxval) % 2 # this gives whether the bar is increasing or decreasing in size if phase == 0: rel_pct = abs_pct / self.maxval * 100 else: rel_pct = (self.maxval - abs_pct) / self.maxval * 100 if (rel_pct != self._pct): self._pct = rel_pct self.display() def start(self): self.update(0) def display(self): sys.stdout.write("\r|%-73s| %d%%" % ('#' * int(self._pct*.73), self._pct)) sys.stdout.flush() data_flush = 30000000 pbar = IndeterminateProgress() for i in xrange(data_flush): time.sleep(0.1) # do real work here pbar.update(i) Testing with the Command Prompt of windows, the progress bar after 100% back to 0%, go to 100% but after this a new under progress bar is created. ![enter image description here](http://i.stack.imgur.com/AH4lF.jpg) The idea is print only one line of indeterminate progress bar Answer: Basically you just want everything modulo the maxval. In python, modulo is done with the % operator. def update(self,value): abs_pct = value % self.maxval # this gives the percentage change from maxval phase = int(value / self.maxval) % 2 # this gives whether the bar is increasing or decreasing in size if phase == 0: rel_pct = abs_pct / self.maxval * 100 else: rel_pct = (self.maxval - abs_pct) / self.maxval * 100 if (rel_pct != self._pct): self._pct = rel_pct self.display() Note there is no requirement here that maxval is 100... you could set it to whatever a "reasonable increment size" is for your data. If you have 1billion data to read and do it at 1000 per second, maybe you don't want your increment size to be 100 ;)
re.split() with special cases Question: I am new to regular expression and have a problem with the re.split functionality. In my case the split has to care "special escapes". The text should be seperated at `;`, except there is a leading `?`. **Edit:** In that case the two parts shouldn't be splitted and the `?` has to be removed. Here an example and the result I wish: import re txt = 'abc;vwx?;yz;123' re.split(r'magical pattern', txt) ['abc', 'vwx;yz', '123'] I tried so far these attempt: re.split(r'(?<!\?);', txt) and got: ['abc', 'vwx?;yz', '123'] Sadly causes the not consumed `?` trouble and the following list comprehension is to performance critical: [part.replace('?;', ';') for part in re.split(r'(?<!\?);', txt)] ['abc', 'vwx;yz', '123'] Is there a "fast" way to reproduce that behavior with re? Could the re.findall function be the solution to take? For example a extended version of this code: re.findall(r'[^;]+', txt) I am using python 2.7.3. Thanking you in anticipation! Answer: Regex is not the tool for the job. Use the `csv` module instead: >>> txt = 'abc;vwx?;yz;123' >>> r = csv.reader([txt], delimiter=';', escapechar='?') >>> next(r) ['abc', 'vwx;yz', '123']