text
stringlengths
226
34.5k
Python IndentationError - How to refactor? Question: I am doing a [Project Euler](https://projecteuler.net) question for programming practice in order to self-teach myself. I know perfectly well _how_ to do the question mathematically, _as well as_ how to do it programmatically. However, I have to have come up with some insane code to do it; 100 nested loops and Python hilariously raises this error, and probably rightfully so, on 100 levels of indentation: IndentationError: too many levels of indentation tally = 0 ceiling = 100 for integer_1 in range(0, 100, 1): for integer_2 in range(0, 100 - integer_1, 2): for integer_3 in range(0, 100 - integer_1 - integer_2, 3): for integer_4 .... for integer_5 .... etc. etc. all the way to integer_100 I have looked through google for solutions but this issue is so rare it has almost no literature on the subject and I could only find this other stack overflow question ( [Python IndentationError: too many levels of indentation](http://stackoverflow.com/questions/8439572/python- indentationerror-too-many-levels-of-indentation) ) which I could not find much useful in for my question. My question is - is there a way to take my solution and find some workaround or refactor it in a way that has it work? I am truly stumped. **EDIT:** Thanks to nneonneo's answer, I was able to solve the question. My code is here just for future reference of people looking for ways to properly refactor their code. from time import time t = time() count_rec_dict = {} # for finding ways to sum to 100 def count_rec(cursum, level): global count_rec_dict # 99 is the last integer that we could be using, # so prevent the algorithm from going further. if level == 99: if cursum == 100: return 1 else: return 0 res = 0 for i in xrange(0, 101-cursum, level+1): # fetch branch value from the dictionary if (cursum+i, level+1) in count_rec_dict: res += count_rec_dict[(cursum+i, level+1)] # add branch value to the dictionary else: count_rec_dict[(cursum+i, level+1)] = count_rec(cursum+i, level+1) res += count_rec_dict[(cursum+i, level+1)] return res} print count_rec(0, 0) print time() - t which runs in an astonishing 0.041 seconds on my computer. WOW!!!!! I learned some new things today! Answer: A recursive solution should do nicely, though I'm certain there is an entirely different solution to the problem that doesn't require this kind of manipulation. def count_rec(cursum, level): if level == 100: return 1 res = 0 for i in xrange(0, 100-cursum, level+1): res += count_rec(cursum+i, level+1) return res print count_rec(0, 0) Interestingly enough, if you _memoize_ this function, it will actually have a reasonable running time (such is the power of _dynamic programming_). Have fun!
Open and preprocessing file in Python NLTK Question: Im new to Python NLTK and really need your advise. I want to open my own txt file and do some preprocessing like replacing words with its regex. I've tried to do it as in NLTK 2.0 Cookbook import re replacement_patterns = [ (r'won\'t', 'will not'), (r'can\'t', 'cannot'), (r'i\'m', 'i am'), (r'ain\'t', 'is not'), (r'(\w+)\'ll', '\g<1> will'), (r'(\w+)n\'t', '\g<1> not'), (r'(\w+)\'ve', '\g<1> have'), (r'(\w+t)\'s', '\g<1> is'), (r'(\w+)\'re', '\g<1> are'), (r'(\w+)\'d', '\g<1> would'), ] class RegexpReplacer(object): def __init__(self, patterns=replacement_patterns): self.patterns = [(re.compile(regex), repl) for (regex, repl) in patterns] def replace(self, line): s = line for (pattern, repl) in self.patterns: (s, count) = re.subn(pattern, repl, s) return s it works perfect but how can I use it with my txt file? I've tried to do my own way but I think its wrong import nltk f=open("C:/nltk_data/file.txt", "rU") raw=f.readlines() from replacers import RegexpReplacer replacer=RegexpReplacer() replacer.replace(raw) thx in advance!!! Answer: I think you want to use the [read method](http://docs.python.org/tutorial/inputoutput.html) to read all the file contents into a string first.
Eclipse Error: no jogl in java.library.path Question: So I'm quite new to eclipse (first week of actually trying to use it to develop stuff.) and I tried to import an example project from <http://unfoldingmaps.org/> and upon trying to compile their test project I'm greeted with the error: Eclipse Error: Exception in thread "Animation Thread" java.lang.UnsatisfiedLinkError: no jogl in java.library.path Right now my $path sys var looks like this: C:\csvn\Python25\;%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;%SYSTEMROOT%\System32\WindowsPowerShell\v1.0\;C:\Program Files\SourceGear\Common\DiffMerge\;C:\Program Files\TortoiseSVN\bin;C:\Program Files\MySQL\MySQL Server 6.0\bin; %JAVA_HOME%;%ANT_HOME%\bin Is there something that I'm missing? Jogl.jar is in the project but it seems like the project is just skipping over stuff.. help? Answer: It seems that your application requires some sort of native library, you need to specify the parameter -Djava.library.path=/path/to/libs on the VM args field on eclipse.
wxPython minimal size of Frame with a Panel Question: wxpython 2.8.11.0, python 2.7 If i put some `Sizer` with some controls directly into a `Frame` like import wx app=wx.App() frm = wx.Frame(None, title='title') sizer = wx.BoxSizer(wx.HORIZONTAL) sizer.Add(wx.SpinCtrl(frm)) sizer.Add(wx.SpinCtrl(frm)) frm.SetSizerAndFit(sizer) frm.Show() app.MainLoop() the `Frame` will automagically have a correct minimum size to contain the `Sizer` and it is not possible to make it smaller. If there is a `Panel` in between (as needed for tabbing between controls) this does not work, the window can be made too small. import wx app=wx.App() frm = wx.Frame(None, title='title') pan = wx.Panel(frm) sizer = wx.BoxSizer(wx.HORIZONTAL) sizer.Add(wx.SpinCtrl(pan)) sizer.Add(wx.SpinCtrl(pan)) pan.SetSizerAndFit(sizer) frm.Show() app.MainLoop() Additionally `frm.Fit()` and `frm.SetMinSize(frm.GetEffectiveMinSize())` are required to get the same behavior. Full Code: import wx app=wx.App() frm = wx.Frame(None, title='title') pan = wx.Panel(frm) sizer = wx.BoxSizer(wx.HORIZONTAL) sizer.Add(wx.SpinCtrl(pan)) sizer.Add(wx.SpinCtrl(pan)) pan.SetSizerAndFit(sizer) frm.Fit() frm.SetMinSize(frm.GetEffectiveMinSize()) frm.Show() app.MainLoop() I am okay with `frm.Fit()`, but i dislike `frm.SetMinSize(frm.GetEffectiveMinSize())`. Isn't there a better solution so that the `Frame` automatically considers the minimum size of the `Panel` just like with the `Sizer` before? I'm considered with what happens if the `EffectiveMinSize` changes after another control is added to the sizer. **Edit:** Apparently panel.SetSizerAndFit(sizer) frm.Fit() frm.SetMinSize(frm.GetEffectiveMinSize()) should be replaced by panel.SetSizer(sizer) sizer.SetSizeHints(frm) which looks somewhat cleaner. So in total this looks like import wx app=wx.App() frm = wx.Frame(None, title='title') pan = wx.Panel(frm) sizer = wx.BoxSizer(wx.HORIZONTAL) sizer.Add(wx.SpinCtrl(pan)) sizer.Add(wx.SpinCtrl(pan)) pan.SetSizer(sizer) sizer.SetSizeHints(frm) frm.Show() app.MainLoop() Is this the preferred way to do this? If widgets are added later on even the first approach with the `Sizer` directly on the `Frame` doesn't get it right without intervention, so i think that is a totally different question. Answer: The most elegant way (IMHO) is given in phineas' answer. It is slightly inefficient to have an extra otherwise unneeded sizer but I don't think it can really be noticeable. Some people do call `SetSizeHints()` manually, as in your last example, and this works as well and might be more clear (whenever I use an extra sizer I feel the need to leave a comment explaining why it shouldn't be removed). Unfortunately there is no better way and I am not sure if we can even add one because you need to do something with all of the panel, the sizer and the frame and this means that you can't do it with a single method call without passing unrelated parameters to it. I.e. we could have something like panel.SetSizerAndFitParent(sizer, frame); but it's not really clear whether this would be better.
seek to regex in a large file using python Question: I am trying to seek to a token ':path,' in a file, then read all the following (arbitrary digit count) numbers as a number (so for ':path,123' I seek to the , in file then read the integer 123). Then read the chars between the current seek position and pos+123 (store them in a list or whatever). Then seek until the next match for ':path,' and repeat the process. I would like a function a bit like: def fregseek(FILE, current_seek, /regex/): . . value_found = ? # result of reading next N chars after :path,[0-9]+ . . return next_start_seek, value_found There may be any number of matches for ':path,' in a line, and that string may occur within the number of chars specified after ','. I have written a messy bunch of rubbish which reads in each line, then for each line chomps of the first N chars indicated by the match, then continues processing the string until it is all eaten up. Then reads the next string and so on. This is horrible, I do not want to have to slurp off all the lines from a potentially huge file when all I really need to do is seek (especially since a newline is irrelevant, so having an extra processing step just because lines are easy to pull from files is ridiculous). So, there it is, that is my problem that I would like to solve. I need to seek to a match, read a value, continue from the end of that value looking for the next match and so on until the file is exhausted. If anybody can help me with this I will be happy to hear from them :) I would like to avoid non-standard libraries if possible, I would also like the shortest code but this is the least of my concerns (speed and memory consumption are the important factors, but I don't want 50 loc extra just to bootstrap some library with a small funciton in it I could just rip out if only I knew what it was). I would prefer python code, however, if perl beats python in this regard I will use perl instead, I am also open to clever sed/awk/bash scripts etc as long as they are not horribly slower. Thanks very much in advance. Answer: You can do it in nearly one line in python: with open('filename.txt') as f: text = f.read() results = [text[i[0]:i[0] + i[1]] for i in ((m.end(), int(m.group(1))) for m in re.finditer(':path,([0-9]+)', text))] Note: untested...
Python Fabric load config from separate file Question: I am use python fabric with all configuration in one .fab file. How can I put sensitive data as password to separate file and then import/load to fab main file? Answer: Define a simple function within your fabfile.py to read your passwords out of a separate file. Something along the lines of: def new_getpass(username): with open("/etc/passwd", "r") as f: for entry in [l.split(":") for l in f.readlines()]: if entry[0] == username: return entry return None This will return `None` in the event that the username cannot be found and the entire user's record as a list in the event the user is found. Obviously my example is getting its data from `/etc/passwd` but you can easily adapt this basic functionality to your own file: `credentials.dat` database1|abcd1234 database2|zyxw0987 And then the above code modified to use this file like this, with the slight variation to return only the password (since we know the database name): def getpass(database): with open("credentials.dat", "r") as f: for entry in [l.split("|") for l in f.readlines()]: if entry[0] == username: return entry[1] return None While not as simple as an import, it provides you flexibility to be able to use plaintext files to store your credentials in.
django/python variables inside strings? Question: I'm new to python and would like some assistance. I have a variable q = request.GET['q'] How do I insert the variable `q` inside this: url = "http://search.com/search?term="+q+"&location=sf" Now I'm not sure what the convention is? I'm used to PHP or javascript, but I'm learning python and how do you insert a variable dynamically? Answer: Use the format method of String: url = "http://search.com/search?term={0}&location=sf".format(q) But of course you should URL-encode the q: import urllib ... qencoded = urllib.quote_plus(q) url = "http://search.com/search?term={0}&location=sf".format(qencoded)
pyspotify Segmentation Fault (libspotify) Question: I am trying to work with pyspotify with but no luck. Setup: * Ubuntu - 12.04 TLS - fresh(ish) install * virtualenv - 1.8.2 * libspotify - 12.1.51 * pyspotiy - dev (1.8) I have the pyspotify example `jukebox.py` but when I run it it always gives Segmentation Fault _(I had this example was working on a separate VM before however need to replicate the functionality on a fresh VM.)_ $ python jukebox.py -uEMAIL_ADDRESS -pPASSWORD Logging in, please wait... Segmentation fault (core dumped) The `spotify_appkey.key` is in the same folder (it doesn't get as far as the SegFault without the key). Additionally I created a script to simply connect to Spotify but this also gives a Segmentation Fault. from spotify.manager import from spotify import SpotifySessionManager session = SpotifySessionManager(username=EMAIL_ADDRESS, password=PASSWORD) print('Connecting') session.connect() print('Connected') This also give: $ python test.py Session created Connecting Segmentation fault (core dumped) Answer: Try to run `jukebox.py` as root.
Virtualenv shell errors Question: I've just installed virtualenv (with Python 2.7.2) on my Mac, and I followed the guide here: <http://virtualenvwrapper.readthedocs.org/en/latest/install.html> But I now get the following errors when I start up my shell every time: stevedore.extension Could not load 'user_scripts': distribute stevedore.extension distribute Traceback (most recent call last): File "/Library/Python/2.7/site-packages/stevedore/extension.py", line 62, in __init__ invoke_kwds, File "/Library/Python/2.7/site-packages/stevedore/extension.py", line 74, in _load_one_plugin plugin = ep.load() File "/Library/Python/2.7/site-packages/setuptools-0.6c11-py2.7.egg/pkg_resources.py", line 1953, in load if require: self.require(env, installer) File "/Library/Python/2.7/site-packages/setuptools-0.6c11-py2.7.egg/pkg_resources.py", line 1966, in require working_set.resolve(self.dist.requires(self.extras),env,installer)) File "/Library/Python/2.7/site-packages/setuptools-0.6c11-py2.7.egg/pkg_resources.py", line 565, in resolve raise DistributionNotFound(req) # XXX put more info here DistributionNotFound: distribute stevedore.extension Could not load 'project': distribute stevedore.extension distribute Traceback (most recent call last): File "/Library/Python/2.7/site-packages/stevedore/extension.py", line 62, in __init__ invoke_kwds, File "/Library/Python/2.7/site-packages/stevedore/extension.py", line 74, in _load_one_plugin plugin = ep.load() File "/Library/Python/2.7/site-packages/setuptools-0.6c11-py2.7.egg/pkg_resources.py", line 1953, in load if require: self.require(env, installer) File "/Library/Python/2.7/site-packages/setuptools-0.6c11-py2.7.egg/pkg_resources.py", line 1966, in require working_set.resolve(self.dist.requires(self.extras),env,installer)) File "/Library/Python/2.7/site-packages/setuptools-0.6c11-py2.7.egg/pkg_resources.py", line 565, in resolve raise DistributionNotFound(req) # XXX put more info here DistributionNotFound: distribute stevedore.extension Could not load 'user_scripts': distribute stevedore.extension distribute Traceback (most recent call last): File "/Library/Python/2.7/site-packages/stevedore/extension.py", line 62, in __init__ invoke_kwds, File "/Library/Python/2.7/site-packages/stevedore/extension.py", line 74, in _load_one_plugin plugin = ep.load() File "/Library/Python/2.7/site-packages/setuptools-0.6c11-py2.7.egg/pkg_resources.py", line 1953, in load if require: self.require(env, installer) File "/Library/Python/2.7/site-packages/setuptools-0.6c11-py2.7.egg/pkg_resources.py", line 1966, in require working_set.resolve(self.dist.requires(self.extras),env,installer)) File "/Library/Python/2.7/site-packages/setuptools-0.6c11-py2.7.egg/pkg_resources.py", line 565, in resolve raise DistributionNotFound(req) # XXX put more info here DistributionNotFound: distribute I don't know if it is affecting this problem, but I am using ZSH. I tried to install stevedore through pip (sudo pip install stevedore), but I get the following error: sudo sh setuptools-0.6c11-py2.7.egg Processing setuptools-0.6c11-py2.7.egg removing '/Library/Python/2.7/site-packages/setuptools-0.6c11-py2.7.egg' (and everything under it) Copying setuptools-0.6c11-py2.7.egg to /Library/Python/2.7/site-packages setuptools 0.6c11 is already the active version in easy-install.pth Installing easy_install script to /usr/local/bin Installing easy_install-2.7 script to /usr/local/bin Installed /Library/Python/2.7/site-packages/setuptools-0.6c11-py2.7.egg Processing dependencies for setuptools==0.6c11 Finished processing dependencies for setuptools==0.6c11 TXSLs-MacBook-Pro% sudo pip install stevedore --upgrade Requirement already up-to-date: stevedore in /Library/Python/2.7/site-packages Downloading/unpacking distribute (from stevedore) Running setup.py egg_info for package distribute Installing collected packages: distribute Running setup.py install for distribute Before install bootstrap. Scanning installed packages Setuptools installation detected at /Library/Python/2.7/site-packages/setuptools-0.6c11-py2.7.egg Egg installation Patching... Renaming /Library/Python/2.7/site-packages/setuptools-0.6c11-py2.7.egg into /Library/Python/2.7/site-packages/setuptools-0.6c11-py2.7.egg.OLD.1348764450.4 Patched done. Relaunching... Traceback (most recent call last): File "<string>", line 1, in <module> NameError: name 'install' is not defined Complete output from command /usr/bin/python -c "import setuptools;__file__='/tmp/pip-build/distribute/setup.py';exec(compile(open(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-FAPgYH-record/install-record.txt --single-version-externally-managed: Before install bootstrap. Scanning installed packages Setuptools installation detected at /Library/Python/2.7/site-packages/setuptools-0.6c11-py2.7.egg Egg installation Patching... Renaming /Library/Python/2.7/site-packages/setuptools-0.6c11-py2.7.egg into /Library/Python/2.7/site-packages/setuptools-0.6c11-py2.7.egg.OLD.1348764450.4 Patched done. Relaunching... Traceback (most recent call last): File "<string>", line 1, in <module> NameError: name 'install' is not defined ---------------------------------------- Command /usr/bin/python -c "import setuptools;__file__='/tmp/pip-build/distribute/setup.py';exec(compile(open(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-FAPgYH-record/install-record.txt --single-version-externally-managed failed with error code 1 in /tmp/pip-build/distribute Storing complete log in /Users/txsl/Library/Logs/pip.log I manually installed setuptools as I couldn't install anything through pip without it. What has gone wrong here and how can i fix it? The internet doesn't seem to have many cases of the error with stevedore. I feel rather stuck at the moment! Many thanks! Answer: I also use zsh and had a similar problem. I solved with this: sudo pip install virtualenv virtualenvwrapper I have the package `python-pip` installed in my Ubuntu 12.04.
I want to fetch json data from a given url And that json data i have to convert into xml form Question: I want to fetch JSON data from a given url http://www.deanclatworthy.com/imdb/?=The+Green+Mile and convert the JSON data into XML. I have used [`urllib`](http://docs.python.org/library/urllib.html) and [`json`](http://docs.python.org/library/json.html) to convert JSON objects into python dictionary. Here is my code: import json json_string = '{"imdbid":"tt0120689","imdburl":"http:\/\/www.imdb.com\/title\/tt0120689\/","genres":"Crime,Drama,Fantasy,Mystery","languages":"English ,French","country":"USA","votes":"281023","stv":0,"series":0,"rating":"8.4","title":"The Green Mile","year":"1999","usascreens":2875,"ukscreens":340}' new_python_object = json.loads(json_string) print(json_string) print() print (new_python_object) And the result: {"imdbid":"tt0120689","imdburl":"http:\/\/www.imdb.com\/title\/tt0120689\/","genres":"Crime,Drama,Fantasy,Mystery","languages":"English ,French","country":"USA","votes":"281023","stv":0,"series":0,"rating":"8.4","title":"The Green Mile","year":"1999","usascreens":2875,"ukscreens":340} {'ukscreens': 340, 'rating': '8.4', 'genres': 'Crime,Drama,Fantasy,Mystery', 'title': 'The Green Mile', 'series': 0, 'imdbid': 'tt0120689', 'year': '1999', 'votes': '281023', 'languages': 'English ,French', 'stv': 0, 'country': 'USA', 'usascreens': 2875, 'imdburl': 'http://www.imdb.com/title/tt0120689/'} Answer: Using the [requests](http://docs.python-requests.org/en/latest/) and [dict2xml](https://github.com/quandyfactory/dict2xml) libraries: >>> import requests >>> r = requests.get("http://www.deanclatworthy.com/imdb/?q=The+Green+Mile") >>> import dict2xml >>> xml = dict2xml.dict2xml(r.json) >>> print xml <country>USA</country> <genres>Crime,Drama,Fantasy,Mystery</genres> <imdbid>tt0120689</imdbid> <imdburl>http://www.imdb.com/title/tt0120689/</imdburl> <languages>English,French</languages> <rating>8.5</rating> <runtime>189min</runtime> <series>0</series> <stv>0</stv> <title>The Green Mile</title> <ukscreens>340</ukscreens> <usascreens>2875</usascreens> <votes>344054</votes> <year>1999</year>
Trying to append items to a list in python but its acting odd Question: I have events, people can belong an event. So I have an event class that looks like: class Event(): name = "" people = [] I also have a global variable to hold all the events events = [] Now I'm trying to process my raw data into events and people going to them: # If there are missions, add the events for m in wiki.missions: foundEvent = False for e in events: if e.name == m: foundEvent = True foundPerson = False for p in e.people: if p.rawName == person.rawName: foundPerson = True if not foundPerson: e.people.append(person) print "Added " + person.display + " to " + m + " (" + str(len(e.people)) + ")" if foundEvent == False: event = Event() event.name = m event.people.append(person) print "New " + person.display + " to " + m + " (" + str(len(event.people)) + ")" events.append(event) event = None Based on my print statements I can see who is added to existing event and when and who makes a new event. The odd thing is the count of people in an event is always increments the people in all events. New Joseph M. Acaba to STS-119 (1) New Joseph M. Acaba to Soyuz TMA-04M (2) New Joseph M. Acaba to Expedition 31 Expedition 32 (3) Added Dominic A. Antonelli to STS-119 (4) New Dominic A. Antonelli to STS-132 (5) Added Richard R. Arnold to STS-119 (6) This makes no sense to me, what is it than I am doing wrong? (I'm sure there is a lot) Answer: You should be using instance variables instead of class variables. So set up your class something like this, and modify the rest of your code to fit it: class Event: def __init__(self, name): self.name = name self.people = [] The important difference here is just as you described: instance variables are set for a specific instance of the class, whereas class variables are set for _all_ instances of that class.
Python CGI in IIS: issue with urandom function Question: I’m having a very strange issue with running a python CGI script in IIS. The script is running in a custom application pool which uses a user account from the domain for identity. Impersonation is disabled for the site and Kerberos is used for authentication. * When the account is member of the `“Domain Admins”` group, everything works like a charm * When the account is **not** member of `“Domain Admins”`, I get an error on the very first line in the script: `“import cgi”`. It seems like that import eventually leads to a random number being generated and it’s the call to `_urandom()` which fails with a `“WindowsError: [Error 5] Access is denied”`. * If I run the same script from the command prompt, when logged in with the same user as the one from the application pool, everything works as a charm. When searching the web I have found out that the `_urandom` on windows is backed by the `CryptGenRandom` function in the operating system. Somehow it seems like my python CGI script does not have access to that function when running from the IIS, while it has access to that function when run from a command prompt. To complicate things further, when logging in as the account running the application pool and then invoking the CGI-script from the web browser it works. It turns out I have to be logged in with the same user as the application pool for it to work. As I previously stated, impersonation is disabled, but somehow it seems like the identity is somehow passed along to the security functions in windows. If I modify the `random.py` file that calls the `_urandom()` function to just return a fixed number, everything works fine, but then I have probably broken a lot of the security functions in python. So have anyone experienced anything like this? Any ideas of what is going on? Answer: I've solved the `_urandom()` error by changing IIS 7.5 settings to `Impersonate User = yes`. I'm not a Windows admin so I cannot elaborate. Afterwards `import cgi` inside python script worked just fine.
Stepping into a function in IPython Question: Is there a way to step into the first line of a function in ipython. I imagine something that would look like: %step foo(1, 2) which runs `ipdb` and sets a breakpoint at the first line of `foo`. If I want to do this now I have to go to the function's source code and add an `import ipdb; ipdb.set_trace()` line. Answer: ipdb has had support for runcall, runeval and run since 0.7, earlier this year. You can use it just like `pdb.runcall`: In [1]: def foo(a, b): ...: print a + b ...: In [2]: import ipdb In [3]: ipdb.runcall(foo, 1, 2) > <ipython-input-1-2e565fd9c4a4>(2)foo() 1 def foo(a, b): ----> 2 print a + b 3 ipdb>
indexing an array Question: I find myself frequently making indexed lists from flat ones in Python. This is such a common task that I was wondering if there's a standard utility that I should be using for it. The context is this: given an array, I need to create a dict of smaller arrays using some key for grouping. e.g: `["Andy","Alice","Bob","Beth","Charlie"]` becomes `{"A":["Andy","Alice"],"B":["Bob","Beth"],"C":["Charlie"]}` My solution looks like this: def make_index(data,key,value=lambda x:x): d={} for item in data: k = key(item) v = value(item) try: d[k].append(v) except KeyError: d[k]=[v] return d It's simple and all, but am I reinventing something that is implemented better elsewhere? Answer: You can do the same a little simpler with a [`defaultdict`](http://docs.python.org/library/collections.html#collections.defaultdict): from collections import defaultdict def make_index(data,key,value=lambda x:x): d=defaultdict(list) for item in data: d[key(item)].append(value(item)) return d Using a `defaultdict` is faster than using `.setdefault()`, which would be the other option.
start python program in the background that can prompt the user for password Question: Basically I wanted to start a daemon in the background that will still prompt the user in the console for a password. I created this with pexpect, but when this program ends it kills the daemon since it is a child process. So obviously pexpect isn't going to work for this. Does any body know of a way to do this? #!/usr/bin/env python import pexpect import getpass child = pexpect.spawn('python daemon.py &') child.expect_exact('Password:') passwd = getpass.getpass() child.sendline(passwd) index = child.expect_exact('Started Successfully') print index Answer: pexpect has a method [close(self, force=True)](http://pexpect.sourceforge.net/pexpect.html#spawn-close) which closes its connection to the child process. According to the documentation, the child pocess is terminated if force=True so child.close(force=False) should disconnect, but leave the application running.
Building an HTML Diff/Patch Algorithm Question: A description of what I'm going to accomplish: * Input 2 (N is not essential) HTML documents. * Standardize the HTML format * Diff the two documents -- external styles are not important but anything inline to the document will be included. * Determine delta at the HTML Block Element level. Expanding the last point: Imagine two pages of the same site that both share a sidebar with what was probably a common ancestor that has been copy/pasted. Each page has some minor changes to the sidebar. The diff will reveal these changes, then I can "walk up" the DOM to find the first common block element shared by them, or just default to `<body>`. In this case, I'd like to walk it up and find that, oh, they share a common `<div id="sidebar">`. I'm familiar with DaisyDiff and the application is similar -- in the CMS world. I've also begun playing with the google diff-patch library. I wanted to give ask this kind of non-specific question to hopefully solicit any advise or guidance that anybody thinks could be helpful. Currently if you put a gun to my head and said "CODE IT" I'd rewrite DaisyDiff in Python and add-in this block-level logic. But I thought maybe there's a better way and the answers to [Anyone have a diff algorithm for rendered HTML?](http://stackoverflow.com/questions/31722/anyone-have-a-diff-algorithm- for-rendered-html) made me feel warm and fuzzy. Answer: If you were going to start from scratch, a useful search term would be "tree diff". There's a pretty awesome blog post [here](http://useless- factor.blogspot.com/2008/01/matching-diffing-and-merging-xml.html), although I just found it by googling "daisydiff python" so I bet you've already seen it. Besides all the interesting theoretical stuff, he mentions the existence of [Logilab's `xmldiff`](http://www.logilab.org/859), an open-source XML differ written in Python. That might be a decent starting point — maybe less correct than trying to wrap or reimplement DaisyDiff, but probably easier to get up and running quickly. There's also [html-tree-diff](http://pypi.python.org/pypi/html-tree- diff/0.1.2) on pypi, which I found via this Quora link: <http://www.quora.com/Is-there-any-good-Python-implementation-of-a-tree-diff- algorithm> There's some theoretical stuff about tree diffing at [efficient diff algorithm for trees and Levenshtein distance](http://cstheory.stackexchange.com/questions/10205/efficient-diff- algorithm-for-trees-and-levenshtein-distance) on cstheory.stackexchange. BTW, just to clarify, you _are_ talking about diffing two DOM trees, but not necessarily rendering the diff/merge back into any particular HTML, right? **(EDIT: Right.)** A lot of the similarly-worded questions on here are really asking "how can I color deleted lines red and added lines green" or "how can I make matching paragraphs line up visually", skipping right over the theoretical hard part of "how do I diff two DOM trees in the first place" and the practical hard part of "how do I parse possibly malformed HTML into a DOM tree even before that". :)
Is it possible to extract preprocessor information from clang's parse tree? Question: Consider the following simple header, demo.h: #define PERSIST struct Serialised { int someTransientValue ; PERSIST int aNumberToPersist ; }; I use the following code and Clang's python API to iterate over the header: import sys, clang.cindex def callexpr_visitor(node, parent, userdata): if node.location.file: print node.location.file, node.displayname, node.kind return 2 tu = clang.cindex.Index.create().parse(sys.argv[1], args=['-x', 'c++']) clang.cindex.Cursor_visit(tu.cursor, clang.cindex.Cursor_visit_callback(callexpr_visitor), None) This prints out the elements of Clang's AST, producing the following output: > demo.h Serialised CursorKind.STRUCT_DECL > demo.h someTransientValue CursorKind.FIELD_DECL > demo.h aNumberToPersist CursorKind.FIELD_DECL Does anyone know how I can extract the preprocessor declaration associated with the member variable called 'aNumberToPersist'?, is there a better way to 'tag' variables in a manner that manifests clearly in the parse tree? Xubuntu 12.04, clang version 3.1 (tags/RELEASE_31/final), Target: x86_64-unknown-linux-gnu Thread model: posix. Answer: I would probably say: not this way. Macros are not represented in the AST per se. Types, Attributes, etc... all those elements that have _semantic_ values are represented (and comments), and optionally you can query whether some of them were expanded from a macro and get back that original macro spelling; however macros in themselves do not appear in the AST, at all. If you could, it might be more interesting to _extend_ Clang with a new **attribute** , especially in C++11: `[[gearoid::persist]]`. C++11 requires that compilers ignore attributes they know not about, so by "namespacing" your own attributes you pretty much guarantee that only you will care about their meaning. I know not, unfortunately, whether you will need to teach Clang about your attributes so they are represented in the AST ([Michael Han](http://lists.cs.uiuc.edu/pipermail/cfe-dev/2012-October/024637.html) is working on always memorizing them). In any case, you may get more useful answers on the [Clang DEV](http://lists.cs.uiuc.edu/mailman/listinfo/cfe-dev) mailing list (unfortunately, there is no Clang Users mailing list). **EDIT** : Just [landed today](http://llvm.org/viewvc/llvm- project?view=rev&revision=165082)! Clang will now retain all attributes (even those it does not understand) in its AST.
Problems with PYTHONPATH Question: From the command line (Mac OS), when I execute 'echo $PYTHONPATH' I get: > /opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7 If I then enter the Python interpreter and do the following: >>> import os >>> os.environ['PYTHONPATH'] Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/UserDict.py", line 23, in __getitem__ raise KeyError(key) KeyError: 'PYTHONPATH' Why would this happen? Answer: You forgot to export it to the environment so that subprocesses can access it; it's currently only a bash variable. export PYTHONPATH
numpy.shape gives inconsistent responses - why? Question: I'm a newbie to python. What I would like to know is, Why does the program import numpy as np c = np.array([1,2]) print(c.shape) d = np.array([[1],[2]]).transpose() print(d.shape) give (2,) (1,2) as its output? Shouldn't it be (1,2) (1,2) instead? I got this in both python 2.7.3 and python 3.2.3 Thanks! Answer: When you invoke the `.shape` attribute of a `ndarray`, you get a tuple with as many elements as dimensions of your array. The length, ie, the number of rows, is the first dimension (`shape[0]`) * You start with an array : `c=np.array([1,2])`. That's a plain 1D array, so its shape will be a 1-element tuple, and `shape[0]` is the number of elements, so `c.shape = (2,)` * Consider `c=np.array([[1,2]])`. That's a 2D array, with 1 row. The first and only row is `[1,2]`, that gives us two columns. Therefore, `c.shape=(1,2)` and `len(c)=1` * Consider `c=np.array([[1,],[2,]])`. Another 2D array, with 2 rows, 1 column: `c.shape=(2,1)` and `len(c)=2`. * Consider `d=np.array([[1,],[2,]]).transpose()`: this array is the same as `np.array([[1,2]])`, therefore its shape is `(1,2)`. Another useful attribute is `.size`: that's the number of elements across all dimensions, and you have for an array `c` `c.size = np.product(c.shape)`. More information on the shape in the [documentation](http://www.scipy.org/Tentative_NumPy_Tutorial#head-62ef2d3c0a5b4b7d6fdc48e4a60fe48b1ffe5006).
Add two 3D numpy arrays with a 2D mask Question: I would like to add two 3D numpy arrays (RGB image arrays) with a 2D mask generated by some algorithms on a greyscale image. What is the best way to do this? As an example of what I am trying to do: from PIL import Image, ImageChops, ImageOps import numpy as np img1=Image.open('./foo.jpg') img2=Image.open('./bar.jpg') img1Grey=ImageOps.grayscale(img1) img2Grey=ImageOps.grayscale(img2) # Some processing for example: diff=ImageChops.difference(img1Grey,img2Grey) mask=np.ma.masked_array(img1,diff>1) img1Array=np.asarray(im1) img2Array=np.asarray(im2) imgResult=img1Array+img2Array[mask] I was thinking: 1) break up the RGB image and do each color separately 2) duplicate the mask into a 3D array or is there a more pythonic way to do this? Thanks in advance! Answer: Wish I could add a comment instead of an answer. Anyhow: masked_array is _not_ for making masks. It's for including only the data outside the mask in calculations such as sum, mean, etc.. scientific statistical applications. It's comprised of an array and the mask for the array. It's probably NOT what you want. You probably just want a normal boolean mask, as in: mask = diff>1 Then you'll need to modify the shape so numpy broadcasts in the correct dimension, then broadcast it into the 3rd dimension: mask.shape = mask.shape + (1,) mask = np.broadcast_arrays(img1Array, mask)[1] After that, you can just add the pixels: img1Array[mask] += img2Array[mask] A further point of clarification: imgResult=img1Array+img2Array[mask] That could never work. You are saying 'add some of the pixels from img2Array to _all_ of the pixels in img1Array' 6_9 If you want to apply a ufunc between two or more arrays, they must be either the same shape, or broadcastable to the same shape.
Running a timer for few minutes in python Question: I am trying to run a certain function "foo" every second. I have to do this for a few minutes (say 5). The function foo() makes 100 HTTP Requests (which contains a JSON object) to the server and prints the JSON response. In short, I have to make 100 HTTP requests per second for 5 minutes. I have just started learning python, thus don't have extensive knowledge. This is what I have tried: import threading noOfSecondsPassed = 0 def foo(): global noOfSecondsPassed # piece of code which makes 100 HTTP requests (I use while loop) noOfSecondsPassed += 1 while True: if noOfSecondsPassed < (300) # 5 minutes t = threading.Timer(1.0, foo) t.start() Due to multiple threads, the function foo isn't called 300 times but much much more than that. I have tried setting a lock too: def foo(): l = threading.Lock() l.acquire() global noOfSecondsPassed # piece of code which makes 100 HTTP requests (I use while loop) noOfSecondsPassed += 1 l.release() Rest of code is same as the previous code snippet. But this also does not work. How do I do this? **Edit: Different Approach** I have tried this approach which worked for me: def foo(): noOfSecondsPassed = 0 while noOfSecondsPassed < 300: #Code to make 100 HTTP requests noOfSecondsPassed +=1 time.sleep(1.0) foo() Any disadvantages in doing so? Answer: I would use another approach which is easier I think. Create 300 timer thread, each running 1 sec after the previous. The main loop is executed in almost an instant so the error factor is very low. Here's a sample Demo: import datetime import thread import threading def foo(): print datetime.datetime.now() print threading.active_count() for x in range(0,300): t = threading.Timer(x + 1, foo) t.start() This code output should look like this: 2012-10-01 13:21:07.328029 301 2012-10-01 13:21:08.328281 300 2012-10-01 13:21:09.328449 299 2012-10-01 13:21:10.328615 298 2012-10-01 13:21:11.328768 297 2012-10-01 13:21:12.329006 296 2012-10-01 13:21:13.329289 295 2012-10-01 13:21:14.329369 294 2012-10-01 13:21:15.329580 293 2012-10-01 13:21:16.329793 292 2012-10-01 13:21:17.329958 291 2012-10-01 13:21:18.330138 290 2012-10-01 13:21:19.330300 289 ... As you can see, each thread is launched about 1 sec after the previous and you are starting exactly 300 threads.
How to Change Content-Type Python Question: I want to upload a file to a remote device. If i look up the connection with wireshark i get this POST /saveRestore.htm.cgi HTTP/1.1 Host: 10.128.115.214 User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:15.0) Gecko/20100101 Firefox/15.0.1 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Language: de-de,de;q=0.8,en-us;q=0.5,en;q=0.3 Accept-Encoding: gzip, deflate Connection: keep-alive Referer: http://10.128.115.214/saveRestore.htm Cache-Control: max-age=0 Content-Type: multipart/form-data; boundary=---------------------------961265085509552220604142744 Content-Length: 10708 -----------------------------961265085509552220604142744 Content-Disposition: form-data; name="restore"; filename="config(2).cfg" Content-Type: application/octet-stream Now this says that that the browser only accepts text/html,application/xhtml+xml,application/xml;q=0.9,_/_ ;q=0.8 If i upload the file with my script it says --0a7125aebb8845ba8ab9aa21306b01f6 Content-Disposition: form-data; name="restore"; filename="Config.cfg" Content-Type: text/plain; charset=utf-8 So it's a wrong file type.. so how do i change the content-type of the File ? My code looks so far as follows: #!/usr/bin/python import httplib import urllib2 from poster.encode import multipart_encode import poster from poster.streaminghttp import register_openers register_openers() params = {'restore': open("Config.cfg", "rb"), 'upload': 'PC ==>; Unit'} datagen, headers = multipart_encode(params) request = urllib2.Request('http://10.128.115.214/saveRestore.htm.cgi', datagen, headers) u = urllib2.urlopen(request) print u.read() Answer: In the [documentation for `poster.encode.MultipartParam`](http://atlee.ca/software/poster/poster.encode.html#poster.encode.MultipartParam) it says: > If `filetype` is set, it is used as the Content-Type for this parameter. If > unset it defaults to “text/plain; charset=utf8” So instead of specifying your parameters like this: params = {'restore': open("Config.cfg", "rb"), 'upload': 'PC ==>; Unit'} specify them like this: params = [MultipartParam('restore', open("Config.cfg", "rb"), filetype = 'application/octet-stream'), ('upload', 'PC ==>; Unit')]
Popen stdout reading pipe, deadlock using sleep Question: Well, I have two scripts. The a.py which prints the output of the b.py script as follows: #a.py from subprocess import Popen, PIPE, STDOUT p = Popen(['/Users/damian/Desktop/b.py'], shell=False, stdout=PIPE, stderr=STDOUT) while p.poll() is None: print p.stdout.readline() #b.py #!/usr/bin/env python import time while 1: print 'some output' #time.sleep(1) This works.But, Why do my scripts deadlock when I uncomment the time.sleep() line? Answer: Your output is probably buffered. Add a [.flush()](http://docs.python.org/library/stdtypes.html#file.flush) for stdout to clear it: import sys import time while 1: print 'someoutput' sys.stdout.flush() time.sleep(1)
python enums with attributes Question: Consider: class Item: def __init__(self, a, b): self.a = a self.b = b class Items: GREEN = Item('a', 'b') BLUE = Item('c', 'd') Is there a way to adapt the ideas for simple enums to this case? (see [this question](http://stackoverflow.com/questions/36932/whats-the-best-way-to- implement-an-enum-in-python)) Ideally, as in Java, I would like to cram it all into one class. Java model: enum EnumWithAttrs { GREEN("a", "b"), BLUE("c", "d"); EnumWithAttrs(String a, String b) { this.a = a; this.b = b; } private String a; private String b; /* accessors and other java noise */ } Answer: Use a [namedtuple](http://docs.python.org/library/collections.html#collections.namedtuple): from collections import namedtuple Item = namedtuple('abitem', ['a', 'b']) class Items: GREEN = Item('a', 'b') BLUE = Item('c', 'd')
Writing a python Dictionary to a CSV file with keys as column headers Question: I'm trying to write the elements in my dictionary into a text file where each key would be a column. Currently have I something that looks like import csv import numpy as np data1 = np.arange(10) data2 = np.arange(10)*2 data3 = np.arange(10)*3 writefile = '../Desktop/data.txt' datadict = {} datadict['data1'] = data1 datadict['data2'] = data2 datadict['data3'] = data3 f = open( writefile, 'w' ) fieldnames = ['data1','data2', 'data3'] data = csv.DictWriter(writefile, fieldnames, restval='', extrasaction='ignore', dialect='excel') f.close() but it gives me the error "argument 1 must have a "write" method". I'm not sure what that means. I'm also worried about the dialect = 'excel', but I'm not sure what else to put. In the end I'd like a file that has something looking like: ![enter image description here](http://i.stack.imgur.com/QJILB.png) Thanks Answer: No need to use DictWriter here at all: import csv import numpy as np data1 = np.arange(10) data2 = np.arange(10)*2 data3 = np.arange(10)*3 writefile = '../test.csv' fieldnames = ['data1','data2', 'data3'] with open( writefile, 'w' ) as f: writer = csv.writer(f) writer.writerow(fieldnames) writer.writerows(zip(data1, data2, data3))
Clean up code when Ctrl+C is caught in python Question: By registering the signal handler, I can put my clean up code in signal_handler signal.signal(signal.SIGINT, signal_handler) But the problem is when user presses ctrl+c multiple times, the signal handler run multiple times and the clean up goes crazy. **My problem is that, how can I make sure that the clean up handler is being ran once only before exit.** Here is my trial using lock, but deadlock is occured def cleanup_handler(): lock.acquire() if not done: try: cleanup() done = True finally: print "release lock" lock.release() The problem is that finally block is never ran (that is I can't see the "release lock" being printed). **Remark** After doing a little experiment, it seems that the signaler handler is not being ran at the same time. When new Ctrl+C is received, the old handler is killed and a new handler is ran. Am I correct? If yes, the problem becomes more complicated as I don't want my handler ends in the middle of the.... Answer: You could use a decorator that prevents your function from being run more than once: from functools import wraps def run_once(function): @wraps(function) def wrapper(*args): if not wrapper.has_run: wrapper.has_run = True return function() wrapper.has_run = False return wrapper Like so: @run_once def signal_handler(): print 'Exit'
Selectively dump object attributes with PyYAML Question: I can use YAML to dump a hierarchy of python objects, so: import yaml class C(): def __init__(self, x, y): self.x = x self.y = y class D(): def __init__(self, c, d): self.c = c self.d = d d = D(c=C(x=1, y='hi'), d='bye') print yaml.dump(d) produces the output: !!python/object:__main__.D c: !!python/object:__main__.C {x: 1, y: hi} d: bye But I want to selectively hide some attributes. So suppose I have a function `attribs_to_dump(obj)` which for any object returns the list of attribute names I want to dump, for example: def attribs_to_dump(obj): if obj.__class__ == C: return ['x'] if obj.__class__ == D: return ['c'] My question is, how do I hook `attribs_to_dump` into `yaml.dump` so that I get the following output? !!python/object:__main__.D c: !!python/object:__main__.C {x: 1} There's a complicating factor: I want to achieve the effect by hooking into Yaml as it crawls over the object hierarchy rather than by pre-processing the object hierarchy myself. The reason is that not all objects in the hierarchy are easily amenable to introspection due to `setattr/getattr/__dict__` magic that is present in some libraries I am using :-(... All help much appreciated! Answer: This is an interesting question, I enjoyed solving it, thanks :) from copy import deepcopy class C(object): def __init__(self, x, y): self.x = x self.y = y class D(object): def __init__(self, c, d): self.c = c self.d = d d = D( c=C(x=1, y='hi'), d='bye' ) FILTER_PARAMS = ( #(class_reference, process_recursively, ['attributes', 'on', 'whitelist']) (D, True, ['c']), (C, False, ['x']), ) def attr_filter(obj, filter_params): for attr in dir(obj): if attr.startswith('__'): # ignore builtins continue attr_val = obj.__getattribute__(attr) # loop through filter params for (cls, do_recursive, whitelist) in filter_params: if isinstance(obj, cls) and attr in whitelist: # filter class matches the current obj's class and # current attribute is on the whitelist if do_recursive: # must process this attribute the same way as the parent setattr(obj, attr, attr_filter(attr_val, filter_params)) # break will avoid the execution of the else clause meaning # the attribute was on the white list so don't delete it break else: # delete the current attribute of the instance as it was # not on the whitelist delattr(obj, attr) return obj # do a deepcopy of the object you pass in, so the original will be preserved filtered_instance = attr_filter(deepcopy(d), FILTER_PARAMS) print dir(filtered_instance) print dir(filtered_instance.c) # now pass filtered_instance to yaml's dump function
How to get the content from a certain <table> using python? Question: I have some `<tr>`s, like this: <tr align=center><td>10876151</td><td><a href=userstatus?user_id=yangfanhit>yangfanhit</a></td><td><a href=problem?id=3155>3155</a></td><td><font color=blue>Accepted</font></td><td>344K</td><td>219MS</td><td>C++</td><td>3940B</td><td>2012-10-02 16:42:45</td></tr> <tr align=center><td>10876150</td><td><a href=userstatus?user_id=BandBandRock>BandBandRock</a></td><td><a href=problem?id=2503>2503</a></td><td><font color=blue>Accepted</font></td><td>16348K</td><td>2750MS</td><td>G++</td><td>840B</td><td>2012-10-02 16:42:25</td></tr> I want to fetch the content without html tags, like: yangfanhit 3155 Accepted 344K 219MS C++ 3940B 2012-10-02 16:42:45 Now I'm using the following code to deal with it: response = urllib2.urlopen('http://poj.org/status', timeout=10) html = response.read() response.close() pattern = re.compile(r'<tr align.*</tr>') match = pattern.findall(html) pat = re.compile(r'<td>.*?</td>') p = re.compile(r'<[/]?.*?>') for item in match: for i in pat.findall(item): print p.sub(r'', i) print '=================================================' I'm new to regex and also new to python. So could you suggest some better methods to process it? Answer: You could use [`BeautifulSoup`](http://www.crummy.com/software/BeautifulSoup/bs4/doc/) to parse the html. To write the content of the table in csv format: #!/usr/bin/env python import csv import sys import urllib2 from bs4 import BeautifulSoup # $ pip install beautifulsoup4 soup = BeautifulSoup(urllib2.urlopen('http://poj.org/status')) writer = csv.writer(sys.stdout) for tr in soup.find('table', 'a')('tr'): writer.writerow([td.get_text() for td in tr('td')]) ### Output Run ID,User,Problem,Result,Memory,Time,Language,Code Length,Submit Time 10876151,yangfanhit,3155,Accepted,344K,219MS,C++,3940B,2012-10-02 16:42:45 10876150,BandBandRock,2503,Accepted,16348K,2750MS,G++,840B,2012-10-02 16:42:25
Communicating with a hardware offering a Python interface using iOS Question: I have to access a hardware component that exposes the following Python interface: $ python >>> from ***.***.***.*** import * >>> client = Client('http://*****') >>> client.getFirmwareVersion() How I can do it? Do I have to create new class in obj-c or I can use the python library and access the data using objective-c? Answer: You seem to be missing an important point; the hardware you are connecting actually stays entirely remote from the iOS perspective - even if it was connected via TCP/IP via a local wifi hotspot. Have a look at [NSURLConnection](https://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSURLConnection_Class/Reference/Reference.html), that is an iOS system component that allows you to remotely connect and transmit data via TCP/IP in both directions. Your first task will be finding a proper interface for your Python driven hardware. I would strongly suggest you to use some kind of an HTTP-interface.
How can I download only metadata from a Google Sites API content feed? Question: I want to download a list of URLs for pages in my Google Sites site. I'm using the Python API to do this. It seems to be slower than I would expect, and so I think it's actually downloading the whole content for each entry rather than just the metadata. Is there any way to download just the metadata? My code is below: import gdata.sites.client client = gdata.sites.client.SitesClient(site='mysite', domain='mydomain.com') client.ClientLogin('[email protected]', 'password', 'test') feed = client.GetContentFeed() for entry in feed.entry: print entry.GetAlternateLink().href Answer: The closest approximation is https://sites.google.com/site/(your site name)/system/feeds/sitemap Unfortunately, this API doesn't allow the use of `fields` as some newer Google APIs do.
time.sleep hangs multithread function in python Question: I am having trouble with a sleep statement hanging my multithreading function. I want my function to go about it's buisness while the rest of the program runs. Here is a toy that recreates my problem: import multiprocessing, sys, time def f(icount, _sleepTime = 1): for i in range(icount): time.sleep(_sleepTime) print(_sleepTime) def main(args): m = multiprocessing.Process(target = f, args=(4, )) m.run() # f should be sleeping for 1 second so this print statement should come first print(m.is_alive()) if __name__ == "__main__": sys.exit(main(sys.argv[1:])) can anyone explain why this code outputs: 1 1 1 1 False instead of: True 1 1 1 1 ## # EDIT ## # I eventually want to run this function on a schedual, and test if it is running before I execute the function. This is an example: import multiprocessing, sys, time def f(icount, _sleepTime = 1): for i in range(icount): time.sleep(_sleepTime) print(_sleepTime) def main(args): m = multiprocessing.Process(target = f, args=(4, )) for i in range(15): time.sleep(.5) if not m.is_alive(): # m.start throws an error after first run m.run() print("{}".format(m.is_alive())) if __name__ == "__main__": sys.exit(main(sys.argv[1:])) Answer: Use `start` and `join` instead of `run`: import multiprocessing, sys, time def f(icount, _sleepTime = 1): for i in range(icount): time.sleep(_sleepTime) print(_sleepTime) def main(args): m = multiprocessing.Process(target = f, args=(4, )) m.start() # f should be sleeping for 1 second so this print statement should come first print(m.is_alive()) m.join() if __name__ == "__main__": sys.exit(main(sys.argv[1:])) # EDIT # Again, use `start` and `join` instead of `run`: import multiprocessing, sys, time def f(icount, _sleepTime = 1): for i in range(icount): time.sleep(_sleepTime) print(_sleepTime) def create_process(): return multiprocessing.Process(target = f, args=(4, )) def main(args): m = create_process() m.start() for i in range(15): time.sleep(.5) if not m.is_alive(): # m.start throws an error after first run print("restarting") m.join() m = create_process() m.start() print("{}".format(m.is_alive())) m.join() if __name__ == "__main__": sys.exit(main(sys.argv[1:]))
Python PIL reading PNG from STDIN Question: I am having a problem reading png images from STDIN using PIL. When the image is written by PIL it is all [scrambled](http://cl.ly/image/3z1k2B1J3F0t), but if I write the file using simple file open, write and close the file is saved [perfectly](http://cl.ly/image/3i1w2C0I1o30). I have a program that dumps png files to stdout in a sequence, with no compression, and I read that stream using a python script which is suposed to read the data and do some routines on almost every png. The program that dumps the data writes a certain string to delimiter the PNGs files, the string is `"{fim:FILE_NAME.png}"` The script is something like: import sys import re from PIL import Image png = None for linha in sys.stdin: if re.search('{fim:', linha): fname = linha.replace('{fim:','')[:-2] # writes data directly to file, works fine #f = open("/tmp/%s" % fname , 'w') #f.write(png) #f.close() # create a PIL Image from data and writes to disk, fails fine im = Image.frombuffer("RGB",(640,480),png, "raw", "RGB", 0, 1) #im = Image.fromstring("RGB",(640,480),png) im.save("/tmp/%s" % fname) png = None else: if png is None: png = linha else: png+= linha imagemagick identify from a wrong image: > /tmp/1349194042-24.png PNG 640x480 640x480+0+0 8-bit DirectClass 361KiB > 0.010u 0:00.019 imagemagick identify from a working image: > /tmp/1349194586-01.png PNG 640x480 640x480+0+0 8-bit DirectClass 903KiB > 0.010u 0:00.010 Does any one have an idea of what is happening? Is it something about little/big endians? I have tried `Image.frombuffer`, `Image.fromstring`, different modes, but nothing. It seems that there is more information on the buffer that the PIL expects. Thanks, Answer: If the `png` variable contains the binary data from a PNG file, you can't read it using `frombuffer`: that is used for reading raw pixel data. Instead, use `StringIO` and `Image.open`, i.e.: img = Image.open(StringIO.StringIO(png))
App Engine, PIL and overlaying text Question: I'm trying to overlay some text over an image on GAE. Now they expose the PIL library it should not be problem. Here's what I have. It works, but I can't help think I should be writing directly to the background image rather than creating a separate overlay image and then merging. Can I use [Image.frombuffer](http://www.pythonware.com/library/pil/handbook/image.htm) or something, I've given it a go but I'm just not getting it... from PIL import Image, ImageDraw, ImageFont from google.appengine.api import images from google.appengine.ext import blobstore from google.appengine.api import files def compose(key): # create new image text_img = Image.new('RGBA', (800,600), (0, 0, 0, 0)) draw = ImageDraw.Draw(text_img) draw.text((0, 0), 'HELLO TEXT', font=ImageFont.load_default()) # no write access on GAE output = StringIO.StringIO() text_img.save(output, format="png") text_layer = output.getvalue() output.close() # read background image blob_reader = blobstore.BlobReader(key) background = images.Image(blob_reader.read()) # merge merged = images.composite([(background, 0, 0, 1.0, images.TOP_LEFT), (text_layer, 0, 0, 1.0, images.TOP_LEFT)], 800, 600) # save file_name = files.blobstore.create(mime_type='image/png') with files.open(file_name, 'a') as f: f.write(merged) files.finalize(file_name) Answer: You should use the `[Image.open][1]` method instead. `Image.frombuffer` and `Image.fromstring` decode pixel data not raw images. In your case you could use something like: blob_reader = blobstore.BlobReader(key) text_img = Image.open(blob_reader) .........
Cython and fortran - how to compile together without f2py Question: **FINAL UPDATE** This question is about how to write a `setup.py` that will compile a cython module which accesses FORTRAN code directly, like C would. It was a rather long and arduous journey to the solution, but the full mess is included below for context. **ORIGINAL QUESTION** I have an extension which is a Cython file, which sets up some heap memory and passes it to the fortran code, and a fortran file, which is a venerable old module that I'd like to avoid reimplementing if I can. The `.pyx` file compiles fine to C, but the cython compiler chokes on the `.f90` file with the following error: $ python setup.py build_ext --inplace running build_ext cythoning delaunay/__init__.pyx to delaunay/__init__.c building 'delaunay' extension error: unknown file type '.f90' (from 'delaunay/stripack.f90') Here's (the top half of) my setup file: from distutils.core import setup, Extension from Cython.Distutils import build_ext ext_modules = [ Extension("delaunay", sources=["delaunay/__init__.pyx", "delaunay/stripack.f90"]) ] setup( cmdclass = {'build_ext': build_ext}, ext_modules = ext_modules, ... ) _NOTE: I originally had the fortran file's location incorrectly specified (without the directory prefix) but this breaks in exactly the same way after I fixed that._ **Things I have tried:** I found [this](http://stackoverflow.com/questions/6523767/how-do-i-get-setup- py-test-to-use-a-specific-fortran-compiler), and tried passing in the name of the fortran compiler (i.e. gfortran) like this: $ python setup.py config --fcompiler=gfortran build_ext --inplace usage: setup.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...] or: setup.py --help [cmd1 cmd2 ...] or: setup.py --help-commands or: setup.py cmd --help error: option --fcompiler not recognized And I've also tried removing `--inplace`, in case that was the problem (it wasn't, same as the top error message). So, how do I compile this fortran? Can I hack it into a `.o` myself and get away with linking it? Or [is this a bug in Cython](https://groups.google.com/forum/?fromgroups=#!topic/cython- users/DP_FksDi6iM), which will force me to reimplement distutils or hack around with the preprocessor? **UPDATE** So, having checked out the `numpy.distutils` packages, I understand the problem a bit more. It seems that you have to 1. Use cython to convert the .pyx files to cpython .c files, 2. Then use an `Extension`/`setup()` combination that supports fortran, like `numpy`'s. Having tried this, my `setup.py` now looks like this: from numpy.distutils.core import setup from Cython.Build import cythonize from numpy.distutils.extension import Extension cy_modules = cythonize('delaunay/sphere.pyx') e = cy_modules[0] ext_modules = [ Extension("delaunay.sphere", sources=e.sources + ['delaunay/stripack.f90']) ] setup( ext_modules = ext_modules, name="delaunay", ... ) (note that I've also restructured the module a bit, since seemingly an `__init__.pyx` is disallowed...) Now is where things become buggy and platform-dependent. I have two testing systems available - one Mac OS X 10.6 (Snow Leopard), using Macports Python 2.7, and one Mac OS X 10.7 (Lion) using the system python 2.7. On Snow Leopard, the following applies: This means that the module compiles (hurray!) (although there's no `--inplace` for numpy, it seems, so I had to system-wide install the testing module :/) but I still get a crash on `import` as follows: >>> import delaunay Traceback (most recent call last): File "<input>", line 1, in <module> File "<snip>site-packages/delaunay/__init__.py", line 1, in <module> from sphere import delaunay_mesh ImportError: dlopen(<snip>site-packages/delaunay/sphere.so, 2): no suitable image found. Did find: <snip>site-packages/delaunay/sphere.so: mach-o, but wrong architecture and on Lion, I get a compile error, following a rather confusing looking compile line: gfortran:f77: build/src.macosx-10.7-intel-2.7/delaunay/sphere-f2pywrappers.f /usr/local/bin/gfortran -Wall -arch i686 -arch x86_64 -Wall -undefined dynamic_lookup -bundle build/temp.macosx-10.7-intel-2.7/delaunay/sphere.o build/temp.macosx-10.7-intel-2.7/build/src.macosx-10.7-intel-2.7/delaunay/spheremodule.o build/temp.macosx-10.7-intel-2.7/build/src.macosx-10.7-intel-2.7/fortranobject.o build/temp.macosx-10.7-intel-2.7/delaunay/stripack.o build/temp.macosx-10.7-intel-2.7/build/src.macosx-10.7-intel-2.7/delaunay/sphere-f2pywrappers.o -lgfortran -o build/lib.macosx-10.7-intel-2.7/delaunay/sphere.so ld: duplicate symbol _initsphere in build/temp.macosx-10.7-intel-2.7/build/src.macosx-10.7-intel-2.7/delaunay/spheremodule.o ldand :build /temp.macosx-10.7-intelduplicate- 2.7symbol/ delaunay/sphere.o _initsphere in forbuild architecture /i386 temp.macosx-10.7-intel-2.7/build/src.macosx-10.7-intel-2.7/delaunay/spheremodule.o and build/temp.macosx-10.7-intel-2.7/delaunay/sphere.o for architecture x86_64 Now let's just step back a moment before we pore over the details here. Firstly, I know there are a bunch of headaches over architecture clashes in 64-bit Mac OS X; I had to work very hard to get Macports Python working on the Snow Leopard machine (just to upgrade from system python 2.6). I also know that when you see `gfortran -arch i686 -arch x86_64` you are sending mixed messages to your compiler. There are all manner of platform-specific problems buried in there, that we don't need to worry about in the context of this question. _But let's just look at this line_ : `gfortran:f77: build/src.macosx-10.7-intel-2.7/delaunay/sphere-f2pywrappers.f` **what is numpy doing?!** I don't need any f2py features in this build! I actually wrote a cython module _in order to avoid_ dealing with f2py's insanity (I need to have 4 or 5 output variables, as well as neither-in-nor- out arguments - neither of which is well supported in f2py.) I just want it to compile `.c` -> `.o`, and `.f90` -> `.o` and link them. I could write this compiler line myself if I knew how to include all the relevant headers. Please tell me I don't need to write my own makefile for this... or that there's a way to translate fortran to (output-compatible) C so I can just avoid python ever seeing the .f90 extension (which fixes the whole problem.) Note that [`f2c`](http://www.netlib.org/f2c/) is not suitable for this as it only works on F77 and this is a more modern dialect (hence the `.f90` file extension). **UPDATE 2** The following bash script will happily compile and link the code in place: PYTHON_H_LOCATION="/opt/local/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7/" cython sphere.pyx gcc -arch x86_64 -c sphere.c -I$PYTHON_H_LOCATION gfortran -arch x86_64 -c stripack.f90 gfortran -arch x86_64 -bundle -undefined dynamic_lookup -L/opt/local/lib *.o -o sphere.so Any advice on how to make this kind of hack compatible with a setup.py? I don't anyone installing this module to have to go find `Python.h` manually... Answer: **UPDATE:** I've created a project on github which wraps up this generating of compile lines by hand. it's called [complicated_build](https://github.com/joe- jordan/complicated_build). **UPDATE 2:** in fact, "generating by hand" is a really bad idea as it's platform specific -- the project now reads the values from the `distutils.sysconfig` module, which is the settings used to compile python (i.e. exactly what we want,) the only setting which is guessed is fortran compiler and file extensions (which are user-configurable). I suspect it is reimplementing a fair bit of distutils now! * * * The way to do this is to write your own compiler lines, and hack them into your `setup.py`. I show an example below which works for my (very simple) case, which has the following strucutre: * imports * `cythonize()` any `.pyx` files, so you only have fortran and C files. * define a `build()` function which compiles your code: * maybe some easy-to-change constants, like compiler names and architecture * list up the fortran and C files * generate the shell commands that will build the modules * add the linker line * run the shell commands. * if the command was `install` and the target doesn't exist yet, build it. * run setup (which will build the pure python sections) * if the command was `build`, run the build now. my implementation of this is shown below. It's designed for only one extension module, and it recompiles all the files every time, so may require further extension to be of more general use. Also note that I've hard coded various unix `/`s, so if you're porting this to windows make sure you adapt or replace with `os.path.sep`. from distutils.core import setup from distutils.sysconfig import get_python_inc from Cython.Build import cythonize import sys, os, shutil cythonize('delaunay/sphere.pyx') target = 'build/lib/delaunay/sphere.so' def build(): fortran_compiler = 'gfortran' c_compiler = 'gcc' architecture = 'x86_64' python_h_location = get_python_inc() build_temp = 'build/custom_temp' global target try: shutil.rmtree(build_temp) except OSError: pass os.makedirs(build_temp) # if you get an error here, please ensure the build/ ... # folder is writable by this user. c_files = ['delaunay/sphere.c'] fortran_files = ['delaunay/stripack.f90'] c_compile_commands = [] for cf in c_files: # use the path (sans /s), without the extension, as the object file name: components = os.path.split(cf) name = components[0].replace('/', '') + '.'.join(components[1].split('.')[:-1]) c_compile_commands.append( c_compiler + ' -arch ' + architecture + ' -I' + python_h_location + ' -o ' + build_temp + '/' + name + '.o -c ' + cf ) fortran_compile_commands = [] for ff in fortran_files: # prefix with f in case of name collisions with c files: components = os.path.split(ff) name = components[0].replace('/', '') + 'f' + '.'.join(components[1].split('.')[:-1]) fortran_compile_commands.append( fortran_compiler + ' -arch ' + architecture + ' -o ' + build_temp + '/' + name + '.o -c ' + ff ) commands = c_compile_commands + fortran_compile_commands + [ fortran_compiler + ' -arch ' + architecture + ' -bundle -undefined dynamic_lookup ' + build_temp + '/*.o -o ' + target ] for c in commands: os.system(c) if 'install' in sys.argv and not os.path.exists(target): try: os.makedirs('build/lib/delaunay') except OSError: # we don't care if the containing folder already exists. pass build() setup( name="delaunay", version="0.1", ... packages=["delaunay"] ) if 'build' in sys.argv: build() This could be wrapped up into a new `Extension` class I guess, with it's own `build_ext` command - an exercise for the advanced student ;)
How to do multiple string replacements in a cleaner manner? - Python Question: What is a fast way of doing multiple string.replace? I'm trying to add spaces to shorten english words like he'll -> he 'll he's -> he 's we're -> we 're we've -> we 've also i'm adding spaces in between before and punctuation as such: "his majesty" -> " his majesty " his; majesty -> his ; majesty Is there a faster and cleaner way to do it? It's a little too slow for the purpose but I've been doing it this way: def removeDoubleSpace(sentence): sentence.replace(" ", " ") if " " in sentence: removeDoubleSpace(sentence) def prepro(sentence): sentence = sentence.replace(",", " ,") sentence = sentence.replace(";", " ; ") sentence = sentence.replace(":", " : ") sentence = sentence.replace("(", " ( ") sentence = sentence.replace("(", " ) ") sentence = sentence.replace("‘"," ‘ ") sentence = sentence.replace('"',' " ') sentence = sentence.replace("'re", " 're") sentence = sentence.replace("'s", " 's") sentence = sentence.replace("'ll", " 'll") sentence = removeDoubleSpace(sentence) return sentence Answer: You could use a few regular expressions to accomplish the same task: import re # Replace multiple consecutive spaces with a single space # Example: "One Two Three Four!" -> "One Two Three Four!" sentence = re.sub(' +', ' ', sentence) # Surround each instance ; : ( ) ‘ and " with spaces # Example: '"Hello;(w)o:r‘ld"' -> " Hello ; ( w ) o : r ‘ ld " sentence = re.sub('([;:()‘"])', ' \\1 ', sentence) # Insert a space before each instance of , 's 're and 'll # Example: "you'll they're, we're" -> "you 'll they 're , we 're" sentence = re.sub("(,|'s|'re|'ll)", ' \\1', sentence) return sentence
GAE can't import Web.py module in virtualenv Question: I'm trying to set up a Web.py (0.37) project in a virtualenv to run on Google App Engine (1.7.2) but I'm getting a `ImportError: No module named web` from the appserver. I've installed web.py using `python setup.py install` from inside my virtualenv and can confirm that it's installed properly because I can import it from the python interpreter. My actual GAE folder is outside the virtualenv but linked like so: `ln -s ~/Development/google_appengine $VIRTUAL_ENV/google_appengine` and added to my python path in `$VIRTUAL_ENV/lib/python2.7/site- packages/gae.pth` There must be an extra step I'm missing, heres the error message: ERROR 2012-10-03 09:03:17,442 wsgi.py:203] Traceback (most recent call last): File "/home/sett/Development/google_appengine/google/appengine/runtime/wsgi.py", line 195, in Handle handler = _config_handle.add_wsgi_middleware(self._LoadHandler()) File "/home/sett/Development/google_appengine/google/appengine/runtime/wsgi.py", line 239, in _LoadHandler handler = __import__(path[0]) File "/home/sett/Development/google_appengine/google/appengine/tools/dev_appserver_import_hook.py", line 719, in Decorate return func(self, *args, **kwargs) File "/home/sett/Development/google_appengine/google/appengine/tools/dev_appserver_import_hook.py", line 1923, in load_module return self.FindAndLoadModule(submodule, fullname, search_path) File "/home/sett/Development/google_appengine/google/appengine/tools/dev_appserver_import_hook.py", line 719, in Decorate return func(self, *args, **kwargs) File "/home/sett/Development/google_appengine/google/appengine/tools/dev_appserver_import_hook.py", line 1787, in FindAndLoadModule description) File "/home/sett/Development/google_appengine/google/appengine/tools/dev_appserver_import_hook.py", line 719, in Decorate return func(self, *args, **kwargs) File "/home/sett/Development/google_appengine/google/appengine/tools/dev_appserver_import_hook.py", line 1730, in LoadModuleRestricted description) File "/home/sett/wip/rigmarolesoup/main.py", line 1, in <module> import web ImportError: No module named web Answer: App engine won't let you import 3rd party modules from site-packages; you must copy web.py into your app directory.
How to reuse user's raw input in other function Question: I m making a 2D board game for python for hw. I asked user to input a integer for the board size. for example, 7. I have modified a bit (only show the important ones) before posting. the function is like follows def asksize(): while True: ask=raw_input("Input board size: ") try: size=int(ask) return size except ValueError: print "Please enter a integer" Because it is variable board size, I need reuse the variable size in other function, use it for checking user's move is valid or not, how can I reuse the variable? def checkmove(move): #move is sth like eg. A1:B2 move=move.split(":") #I split it so it becomes ['A','1']['B','2'] if size>=int(move[0][1]) and int(move[0][1])>=1 and size>=int(move[1][1]) and int(move[1][1])>=1: #for example if board size is 7, this is to check whether user input is between 1 to 7 within the board return True else: return False In my checkmove function, I can't use size in my argument because it is not defined, how can I make it workable? Thanks Answer: Making the variable size global is an option, but you should consider your functions as an API, and use them on the game main bucle. so storing the input like this: size = asksize() #store the data on to variable called size #then just call your check move checkmove(x) Anyway this is a bad exercise, its better to pass the variable through the function inside the game code: #definitions def asksize(): #your code here def checkmove(move, size): #your code here #game set up here size = asksize() #more set up stuff #end of game set up #Game Main code while True: #main game bucle #Game stuff here checkmove(move, size) #more game stuff
Automating virtualenv and Django development server startup with fabric? Question: > **Possible Duplicate:** > [Activate a virtualenv via fabric as deploy > user](http://stackoverflow.com/questions/1180411/activate-a-virtualenv-via- > fabric-as-deploy-user) I've been advised to try and use fabric for deploying Django to a production server, and automating tasks by using python instead of bash. I wanted to start easily and just automate the activation of my virtualenv, and start the Django development server in it. I've created a file named fabfile.py: from fabric.api import local def activate_env(): local("source /.../expofit_env/bin/activate") def run_local_server(): local("/.../server/manage.py runserver") def start(): activate_env() run_local_server() However, when I run fab start i get the following message: [localhost] local: source /.../expofit_env/bin/activate /bin/sh: 1: source: not found Fatal error: local() encountered an error (return code 127) while executin 'source /.../expofit_env/bin/activate' What am I doing wrong? * * * **Update** Based on Burhan Khalid's proposal, i tried the following: .... def activate_env(): local("/bin/bash /.../expofit_env/bin/activate") .... Running just fab activate_env results: [localhost] local: /bin/bash /.../expofit_env/bin/activate Done. However after execution, virtualenv isn't activated. For the following code: def start_env(): with prefix('/bin/bash /.../expofit_env/bin/activate'): local("yolk -l") I still get an error, as if virtualenv wasn't activated. alan@linux ~/Desktop/expofit $ fab start_env [localhost] local: yolk -l /bin/sh: 1: yolk: not found When i manually activate virtualenv, yolk workd fine: alan@linux ~/.../expofit_env $ source bin/activate (expofit_env)alan@linux ~/.../expofit_env $ yolk -l DateUtils - 0.5.2 - active Django - 1.4.1 - active Python - 2.7.3rc2 - active development (/usr/lib/python2.7/lib-dynload) .... * * * **Update** Tried a new approach from [this question](http://stackoverflow.com/questions/1180411/activate-a-virtualenv- via-fabric-as-deploy-user?rq=1). from __future__ import with_statement from fabric.api import * from contextlib import contextmanager as _contextmanager env.activate = 'source /.../expofit_env/bin/activate' @_contextmanager def virtualenv(): with prefix(env.activate): yield def deploy(): with virtualenv(): local('yolk -l') Gives the same error: [localhost] local: yolk -l /bin/sh: 1: source: not found Fatal error: local() encountered an error (return code 127) while executing 'yolk -l' Aborting. Even dough the first command passes without errors: alan@linux ~/.../expofit_env/bin $ fab virtualenv [servername] Executing task 'virtualenv' Done. **Update** It is possible to run the `local` with a custom shell. from fabric.api import local def start_env(): local('source env/bin/activate',shell='/bin/bash') However, that didn't activate the virtualenv as if it was done manually. Answer: To use enable a virtualenv from the fab file you need to run your commands as follow: def task(): # do some things outside the env if needed with prefix('source bin/activate'): # do some stuff inside the env pip install django-audiofield All the commands within the with bloc will be executed inside the virtualenv
QtSingleApplication for PySide or PyQt Question: Is there a Python version of the C++ class [`QtSingleApplication`](http://doc.qt.digia.com/solutions/4/qtsingleapplication/qtsingleapplication.html) from [Qt Solutions](http://qt.digia.com/Product/Qt-Add-Ons/Qt-Solutions- Archive/)? [`QtSingleApplication`](http://doc.qt.digia.com/solutions/4/qtsingleapplication/qtsingleapplication.html) is used to make sure that there can never be more than one instance of an application running at the same time. Answer: Here is my own implementation. It has been tested with Python 2.7 and PySide 1.1. It has essentially the same interface as the [C++ version of `QtSingleApplication`](http://doc.qt.digia.com/solutions/4/qtsingleapplication/qtsingleapplication.html). The main difference is that you must supply an application unique id to the constructor. (The C++ version by default uses the path to the executable as a unique id; that would not work here because the executable will most likely be `python.exe`.) from PySide.QtCore import * from PySide.QtGui import * from PySide.QtNetwork import * class QtSingleApplication(QApplication): messageReceived = Signal(unicode) def __init__(self, id, *argv): super(QtSingleApplication, self).__init__(*argv) self._id = id self._activationWindow = None self._activateOnMessage = False # Is there another instance running? self._outSocket = QLocalSocket() self._outSocket.connectToServer(self._id) self._isRunning = self._outSocket.waitForConnected() if self._isRunning: # Yes, there is. self._outStream = QTextStream(self._outSocket) self._outStream.setCodec('UTF-8') else: # No, there isn't. self._outSocket = None self._outStream = None self._inSocket = None self._inStream = None self._server = QLocalServer() self._server.listen(self._id) self._server.newConnection.connect(self._onNewConnection) def isRunning(self): return self._isRunning def id(self): return self._id def activationWindow(self): return self._activationWindow def setActivationWindow(self, activationWindow, activateOnMessage = True): self._activationWindow = activationWindow self._activateOnMessage = activateOnMessage def activateWindow(self): if not self._activationWindow: return self._activationWindow.setWindowState( self._activationWindow.windowState() & ~Qt.WindowMinimized) self._activationWindow.raise_() self._activationWindow.activateWindow() def sendMessage(self, msg): if not self._outStream: return False self._outStream << msg << '\n' self._outStream.flush() return self._outSocket.waitForBytesWritten() def _onNewConnection(self): if self._inSocket: self._inSocket.readyRead.disconnect(self._onReadyRead) self._inSocket = self._server.nextPendingConnection() if not self._inSocket: return self._inStream = QTextStream(self._inSocket) self._inStream.setCodec('UTF-8') self._inSocket.readyRead.connect(self._onReadyRead) if self._activateOnMessage: self.activateWindow() def _onReadyRead(self): while True: msg = self._inStream.readLine() if not msg: break self.messageReceived.emit(msg) Here is a simple test program: import sys from PySide.QtGui import * from QtSingleApplication import QtSingleApplication appGuid = 'F3FF80BA-BA05-4277-8063-82A6DB9245A2' app = QtSingleApplication(appGuid, sys.argv) if app.isRunning(): sys.exit(0) w = QWidget() w.show() app.setActivationWindow(w) sys.exit(app.exec_())
Writing and importing custom modules/classes Question: I've got a class that I'm trying to write called dbObject and I'm trying to import it from a script in a different folder. My structure is as follows: /var/www/html/py/testobj.py /var/www/html/py/obj/dbObject.py /var/www/html/py/obj/__init__.py Now, `__init__.py` is an empty file. Here are the contents of dbObject.py: class dbObject: def __init__(): print "Constructor?" def test(): print "Testing" And here's the contents of testobj.py: #!/usr/bin/python import sys sys.path.append("/var/www/html/py") import obj.dbObject db = dbObject() When I run this, I get: Traceback (most recent call last): File "testobj.py", line 7, in <module> db = dbObject() NameError: name 'dbObject' is not defined I'm new to Python, so I'm very confused as to what I'm doing wrong. Could someone please point me in the right direction? EDIT: Thanks to Martijn Pieters' answer I modified my testobj.py as follows: #!/usr/bin/python import sys sys.path.append("/var/www/html/py") sys.path.append("/var/www/html/py/dev") from obj.dbObject import dbObject db = dbObject() However, now when I run it I get this error: Traceback (most recent call last): File "testobj.py", line 7, in <module> db = dbObject() TypeError: __init__() takes no arguments (1 given) Is this referring to my **init**.py or the constructor within dbObject? EDIT(2): Solved that one myself, the constructor must be able to take at least one parameter - a reference to itself. Simple fix. Looks like this problem is solved! EDIT (Final): This is nice - I can cut out the import sys and sys.path.append lines and it still works in this instance. Lovely. Answer: You need to import the class from the module: from obj.dbObject import dbObject This adds the class `dbObject` directly to your local namespace. Your statement `import obj.dbObject` adds the name `obj` to the local namespace, so you could also do this instead: db = obj.dbObject.dbObject() because `obj.dbObject` is the `dbObject.py` module in your `obj` package directory.
Is it possible to use the Yahoo Query Language to download historical financial data? Question: I've used the Yahoo Finance site to download historical data, using queries like this: http://ichart.finance.yahoo.com/table.csv?s=AAPL&c=1962 and the accompanying Python code: import urllib.request with open("data.csv", "wb") as w: url = "http://ichart.finance.yahoo.com/table.csv?s=AAPL&c=1962" r = urllib.request.urlopen(url).read() w.write(r) I've also used the Yahoo Query Language to download pseudo-realtime data (i.e. data delayed by a few minutes) with queries like this: http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(%22AAPL%22)&env=store://datatables.org/alltableswithkeys However, I can't find documentation on how to download historical data (as shown in the first query) using the YQL (as shown in the second query). I'd like to do this before the tables returned by the YQL contain much more data than simply opening/closing prices, volume, etc. Is there a way to download historical data using the YQL in such a way that it contains the same depth of detail as the pseudo-realtime data? Answer: Unfortunately, the YQL table `yahoo.finance.historicaldata` contains the same fields as the CSV files, specifically the opening price, closing price, high, low, volume, etc. To download this data using YQL, this is an example of the proper query: select * from yahoo.finance.historicaldata where symbol = "IBM" and startDate = "2012-01-01" and endDate = "2012-01-11"
How to create REST API application using python Bottle framework and how to deploy it on apache server? Question: I want to create one sample application for api's using python Bottle framework, I want to deploy that application on apache server as well, I use following sample code, from bottle import route, run, template @route('/hello/:name') def index(name='World'): return template('<b>Hello {{name}}</b>!', name=name) @route('/events/:id', method='GET') def get_event(id): return dict(name = 'Event ' + str(id)) run(host='localhost', port=8082) by using above code, How I can create sample application and how I can deploy that sample application on server. How can achieve this? Answer: [**@phihag**](http://stackoverflow.com/users/35070/phihag), go through these articles by Miguel Grinberg, [@miguelgrinberg](http://twitter.com/miguelgrinberg) ~ <http://blog.miguelgrinberg.com/category/REST> Start with this article, "**[Designing a RESTful API with Python and Flask](http://blog.miguelgrinberg.com/post/designing-a-restful-api-with- python-and-flask)** " ~ and if need be install Flask, go through the steps. Then re-write the application in Bottle. Bottle is a simple framework to use and is so close to Flask I re-wrote the code reading through the example in Bottle. There is a more [detailed tutorial](http://blog.miguelgrinberg.com/post/designing-a-restful-api-using- flask-restful) that you can look at once you have the basics. It's worth the effort.
Python sum() returns negative value because the sum is too large for 32bit integer Question: x = [1, 2, 3, ... ] y = sum(x) The sum of `x` is 2165496761, which is larger than the limit of 32bit integer So `sum(x)` returns -2129470535. How can I get the correct value by converting it to long integer? Here is my import list: import math, csv, sys, re, time, datetime, pickle, os, gzip from numpy import * Answer: Twenty quatloos says you're using `numpy`'s sum function: >>> sum(xrange(10**7)) 49999995000000L >>> from numpy import sum >>> sum(xrange(10**7)) -2014260032 So I'd bet you did `from numpy import *` or are using some interface which does the equivalent. To verify this, try print type(sum(x)) On the example posted elsewhere in this thread: >>> sum([721832253, 721832254, 721832254]) -2129470535 >>> type(sum([721832253, 721832254, 721832254])) <type 'numpy.int32'> Edit: somebody owes me twenty quatloos! Either don't use the star import (best), manually set the `dtype`: >>> sum([721832253, 721832254, 721832254],dtype=object) 2165496761L or refer to the builtin `sum` explicitly (possibly giving it a more convenient binding): >>> __builtins__.sum([721832253, 721832254, 721832254]) 2165496761L
easy_install conflict for python2.4 and python2.7 Question: I have installed python under /opt/python2.7.1/ on CentOS machine which has already python2.4 and configure it to run python2.7 default. However, when I write 'easy_install' it raises error like Traceback (most recent call last): File "/opt/python2.7.1/bin/easy_install", line 5, in ? from pkg_resources import load_entry_point File "/usr/lib/python2.4/site-packages/pkg_resources.py", line 2482, in ? for dist in working_set.resolve( File "/usr/lib/python2.4/site-packages/pkg_resources.py", line 483, in resolve raise DistributionNotFound(req) # XXX put more info here pkg_resources.DistributionNotFound: setuptools==0.6c11 I think `easy_install` under `/usr/bin/` links to python2.4. How can I run `/opt/python2.7.1/bin/easy_install` default? For $PATH: /opt/python2.7.1/bin:/usr/devs/bin:/usr/local/bin:/bin:/usr/bin:/home/ops/bin For $LD_LIBRARY_PATH: /opt/python2.7.1/lib: For easy_install: Traceback (most recent call last): File "/opt/python2.7.1/bin/easy_install", line 5, in ? from pkg_resources import load_entry_point File "/usr/lib/python2.4/site-packages/pkg_resources.py", line 2482, in ? for dist in working_set.resolve( File "/usr/lib/python2.4/site-packages/pkg_resources.py", line 483, in resolve raise DistributionNotFound(req) # XXX put more info here pkg_resources.DistributionNotFound: setuptools==0.6c11 Answer: You have to make use of [virtualenv](http://www.virtualenv.org/en/latest/index.html) to get things working properly, and without worries in systems with more than one Python version. Actually, it is quite a help even in system qwith a single Python version, if you have muliple Python apps running. Visrtualenv will not only take care of setting up all the appropriate environment variables for you to use one Python or another, as it will allow you to use use a separate environment where you can safely "easy_install" Python 2.4 modules without conflicting with CentOS .rpm packages of those same modules.
Get absolute path of file why traversing through another directory Question: I have a small snipped in python which intends to traverse through all the directory , subdirectory and manitain a list of absolute path of all the files . code: import os , pickle root="/home/me/programs/" l = [] #Will have list of all the files parsed through for dname,subdirlist,flist in os.walk(root): for fname in flist: l.append(os.path.abspath(fname)) Even though i am parsing through all the files , my output is prefixing `/home/me/programs/` irrespective of the actual absolute path. For example, instead of having `'/home/me/programs/cpp/sample/test.c'` i will have `'/home/me/programs/test.c'` How do i fix this problem ? Answer: As mentioned in the [`os.walk` doc](http://docs.python.org/library/os.html#os.walk), you'll have to join the root path to your fname to get the absolute path : import os , pickle root="/home/me/programs/" l = [] #Will have list of all the files parsed through for dname,subdirlist,flist in os.walk(root): for fname in flist: l.append(os.path.join(dname, fname))
DNS server client communication protocol Question: I need to write a paper on how DNS works and build a small but functional DNS server in python. I have a simple UDP socket server that opens a thread when a packet is received like this: while 1: try: stream, addr = serversocket.recvfrom(buffr) threading.Thread(target=handler, args=(stream, addr, threading.activeCount(),)).start() except: exc_type, exc_value, exc_traceback = sys.exc_info() except_catch(exc_type.__name__, exc_value, exc_traceback, threading.current_thread().name) The handler function simply tries to find the record requested in memory and if it does not it will execute another function that runs a dns query on another server to fetch the record if he does not have it. This is somewhat of a fail-safe and where my problem is. def dnsrn(ip, type): try: mkr = dns.resolver.Resolver() mkr.nameservers = ['192.168.0.1'] res = mkr.query(ip, type) for rdata in res: return rdata.address # this works for A records # to do for other types of records except: exc_type, exc_value, exc_traceback = sys.exc_info() except_catch(exc_type.__name__, exc_value, exc_traceback, threading.current_thread().name) **I have not yet finished it as you can see but I already have a problem. Sometimes, this function will hand and the thread will never finish without it giving any error what so ever in the error log. I have tested and the error log should capture all errors thrown by the child. I have a simple client that is programmed to send a random request out a lit of presets every set time and there seems to be no pattern to when the child hangs. After about 24 hours of testing I'm left with about 1-3 zombie threads.** In case you are wondering this is what the exception function looks like: def except_catch(type, value, track, thread=None): if type != "SystemExit": import traceback rawreport = traceback.format_exception(type, value, track) report = "\n" . join(rawreport) errorlog = open(error_log_path + "/errors.log", "a") if thread != None: errorlog.write("Exception in thread: " + thread + "\n\n") errorlog.write(("%s\n" + "-" * 30 + "\n\n") % report) errorlog.close() sys.excepthook = except_catch Answer: I would check the RFC as this is the exact specification of the protocol. The problem with DNS is, that there is more than one RFC. For a simple start, I would check [RFC 1035](http://tools.ietf.org/html/rfc1035) which contains the basics. If you need advanced functionality, check the other related RFCs.
Append xml to xml using python.I have two xml files which i need to merge .so is there anyway i can merge both files Question: can anybody tell me how to append xml files using python this is my file1.xml <?xml version="1.0"?> <addressbook> <person> <name>Eric Idle</name> <phone type='fix'>999-999-999</phone> <phone type='mobile'>555-555-555</phone> <address> <street>12, spam road</street> <city>London</city> <zip>H4B 1X3</zip> </address> </person> </addressbook> and i want to append it to another xml file <?xml version="1.0"?> <note> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body> </note> Is there any module which can do this for me... and the output i needed is : <addressbook> <person> <name>Eric Idle</name> <phone type='fix'>999-999-999</phone> <phone type='mobile'>555-555-555</phone> <address> <street>12, spam road</street> <city>London</city> <zip>H4B 1X3</zip> </address> </person> <note> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body> </note> </addressbook> And for now i need to read xml from files but later i need to get the xml response from server and the convert it into one xml file .So please if any one know that to it will help me alot...... Answer: **EDIT** : Removed old answer as the question changed considerably. Using lxml: addressbook_xml = """<?xml version="1.0"?> <addressbook> <person> <name>Eric Idle</name> <phone type='fix'>999-999-999</phone> <phone type='mobile'>555-555-555</phone> <address> <street>12, spam road</street> <city>London</city> <zip>H4B 1X3</zip> </address> </person> </addressbook>""" note_xml = """<?xml version="1.0"?> <note> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body> </note> """ from lxml import etree # XML strings to etree addressbook_root = etree.fromstring(addressbook_xml) note_root = etree.fromstring(note_xml) # append the note addressbook_root.append(note_root) # print the new addressbook XML document print etree.tostring(addressbook_root)
PrintWriter flush not working? Question: I'm trying to get the following code working so that I can use it somewhere else. Effectively, it (is supposed to) start another process, run python in it, and feed python some commands. However, in practice, unless I close the stream to that process, the the python commands are never sent. I thought flush() was supposed to force this to happen, but it does not appear to be working. Could anyone provide any insight as to why flush() may not be working and what I could do to avoid this? Thanks. Note that if I call close() the command is sent. However, I want to be able to send more commands after this one command, so using close() here seems unacceptable. (I'll eventually close() everything) import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.Scanner; public class Foo { public static void main(String[] args) throws IOException { Process cmd = Runtime.getRuntime().exec("python"); InputStream inStream = cmd.getInputStream(); Thread stdout = new Thread(new stdOutReader(inStream)); stdout.start(); InputStream errStream = cmd.getErrorStream(); Thread stderr = new Thread(new stdOutReader(errStream)); stderr.start(); OutputStream outStream = cmd.getOutputStream(); OutputStreamWriter os = new OutputStreamWriter(outStream); PrintWriter pWriter = new PrintWriter(outStream, true); pWriter.println("print \"Testing..\""); pWriter.flush(); int x = 0; while (x < 100){ //Do stuff here (will not be an infinite loop in actual code) } pWriter.close(); } private static class stdOutReader implements Runnable{ InputStream inStream; public stdOutReader(InputStream inStream){ this.inStream = inStream; } public void run() { InputStreamReader reader = new InputStreamReader(this.inStream); Scanner scan = new Scanner(reader); while (scan.hasNext()) { System.out.println(scan.next()); System.out.flush(); } } } } Answer: Consider using [Apache Commons Executor](http://commons.apache.org/exec/index.html) instead of using the `Runtime.exec()` API directly.
Python Requests and persistent sessions Question: I am using the [requests](http://docs.python-requests.org/en/latest/) module (version 0.10.0 with Python 2.5). I have figured out how to submit data to a login form on a website and retrieve the session key, but I can't see an obvious way to use this session key in subsequent requests. Can someone fill in the ellipsis in the code below or suggest another approach? >>> import requests >>> login_data = {'formPosted':'1', 'login_email':'[email protected]', 'password':'pw'} >>> r = requests.post('https://localhost/login.py', login_data) >>> >>> r.text u'You are being redirected <a href="profilePage?_ck=1349394964">here</a>' >>> r.cookies {'session_id_myapp': '127-0-0-1-825ff22a-6ed1-453b-aebc-5d3cf2987065'} >>> >>> r2 = requests.get('https://localhost/profile_data.json', ...) Answer: You can easily create a persistent session using: s = requests.session() After that, continue with your requests as you would: s.post('https://localhost/login.py', login_data) #logged in! cookies saved for future requests. r2 = s.get('https://localhost/profile_data.json', ...) #cookies sent automatically! #do whatever, s will keep your cookies intact :) For more about sessions: <http://docs.python- requests.org/en/latest/user/advanced/#session-objects>
Post-EasyTether, PDANet Tethering Samsung Galaxy 4g to Mac OS X 10.7.4 to Implement Python Question: I'm using Mac OS X Version 10.7.4 and Python 3.2.3. I've read through many of the equally frustrated posts on Stack Overflow, this one was especially useful in helping me delete EasyTether after it didn't work, and turns out was blocking PDANet from working: [mac os x 10.6.6 and "adb devices" fails to list android devices](http://stackoverflow.com/questions/4680637/mac-os-x-10-6-6-and-adb- devices-fails-to-list-android-devices) I'm using Paul Ferrill's "Pro Android Python with SL4A" and for the past 4 hours I've just wanted to be able to type the following in my Mac's IDLE session: >>>import android >>>droid = android.Android() >>>droid.makeToast("Hello Android from Mac") I'm pretty stymied at this point. I've allowed USB debugging on my Samsung Galaxy 4g, I finally have the PDANet software working, but I have nothing to show for it. I've watched a bunch of Youtube tutorials, this one was helpful for installing PDANet: <http://www.youtube.com/watch?v=yR9GANNKUgo> A lot of other people had similar trouble with EasyTether, but now that I have PDANet working, I still can't seem to get this code to work. Right now, my I have the following: Python 3.2.3 Type "copyright", "credits" or "license()" for more information. > > > import android Traceback (most recent call last): File "", line 1, in import android ImportError: No module named android > > > I would be so very thankful for any help you can provide. **Correction** I understand that the reason the code throws an error is that the android module is not found on my computer. I'm simply wondering how I can get my Mac to connect with my Samsung Galaxy such that I can write the above code and have the file android.py that is on my android register with my script on my Mac, such that the program works. Answer: I'm not sure if that book is great for Python 3. There is a Python3 APK(http://code.google.com/p/python-for- android/downloads/detail?name=Python3ForAndroid_r6.apk), but the other one, the standard PythonForAndroid is 2.6(?) based. You need to use the same version of python across both your android device and your local machine for what you're trying to do. I'm not sure which Python 3 ve When I was playing with this and the same book, I had to install the same version of python on my local machine that was used in the APK I installed on my device. It was still a lot of screwing around to get it to work and wasn't really worth the effort in the end. However, I found that just pushing the script across and instantly running it was way easier than trying to play with IDLE remotely. This is now how I rapidly prototype any Android apps I'm planning to work on.
python epoll and nonblocking Question: simple client-server socket studying code,the server-end is: import socket,select,time s = socket.socket() host = socket.gethostname() port = 1234 s.bind((host,port)) s.listen(50) s.setblocking(0) # (1) fdmap = {s.fileno():s} p = select.epoll() p.register(s) while True: events = p.poll() for fd,event in events: if fd is s.fileno(): c,addr = s.accept() c.setblocking(0) #(2) print('Got connection from: ',addr) p.register(c) fdmap[c.fileno()] = c elif event & select.EPOLLIN: data = fdmap[fd].recv(1024) if not data: print('disconnected') p.unregister(fd) del fdmap[fd] else: print(data) and the client-end is import socket,time s = socket.socket() host = socket.gethostname() port = 1234 s.connect((host,port)) print(s.send(b'hello server')) My questions are: 1.AFAIK in the IO-multiplexing model,epoll.poll would block until one socket become available,so when operates on it,it shouldn't be block(should return directly),then why we should call setblocking(0) in (1),(2),what's the purpose? I tried put them off,it still works 2.when running,the client-end can be slow,it outputs 12(which is the bytes it send to server) after about 1s,I profiling it by use time.time() one by one statement,then found that the s.connect((host,port)) usually take about 1s,where am i wrong?(This happens on poll/epoll,when use select,the client-end goes very fast) Answer: If you check the [documentation](http://docs.python.org/library/select.html#select.epoll.poll) you will see that the epoll `poll` function takes a `timeout` parameter, which defaults to `-1` which means wait indefinitely. If you set the timeout to zero it will return immediately. As for the delay in `connect` it's probably because `connect` has to do a DNS lookup of the hostname to find the IP address.
how to launch a command window from Python Question: I'd like to use Python 2.6 on Windows to launch several **separate** command windows, each running their own Python script. The purpose is: these are clients, and I'm trying to load up the server with requests from multiple quasi-independent clients. I don't need to communicate with the client during or after the run, but I do need to send each a different commmandline arg, and I'd like each client's output to scroll in its own "console". From the DOS command line, the "start" command does what I'd like. I can either: start perf_test.py 2 or start cmd /c perf_test.py 3 or start cmd /c python perf_test.py 4 (These will work for you if you have your "file associations" setup correctly for *.py files. There are other threads on that, if you need help. Or, use full paths to the python exe and/or your script.) My challenge is: How do I get the same effect from Python? Using `subprocess` library, I've tried variations like this: from subprocess import * p = Popen(["perf_test.py", "4"], shell=True, stdin=PIPE) But even with `shell=True`, the output is commingled in the window I'm already running in. Adding `stdout=PIPE` stops that, but then I have to read `p.stdout` or use `p.communicate()`. Adding "cmd" to the Popen gets approximately the same: p = Popen(["cmd", "/c", "perf_test.py", "4"], shell=True, stdin=PIPE) None of the above achieve the effect I'm looking for, which is: "**pop open a new, distinct window for this script, and watch its output scroll by in its own console** " (because I really want to run N of these clients in parallel). One other thing I turned to _almost_ works, too. import os os.startfile("perf_test.py") This returns immediately, and an actual dosbox pops up. Yay! Success! That is, until I try to add an argument. This fails: os.startfile("perf_test.py 5") with error "The system cannot find the file specified"... because it is adding "[SPACE]5" to the filename. (The purpose of the argument is that each "perf_test" needs to have an assigned ID, so that they hit the server as different instances.) Other approaches I've considered, and really don't like for various reasons: * Run each "perf_test" in its own thread. (But I really want to see the output each in its own console.) * Make my own pseudo-consoles with Tk. (Figure I'll just hit different threading problems there.) * Dynamically write a .BAT file on the fly with the lines "start perf_test.py 1", "start perf_test.py 2", etc., then launch that .BAT file with `Popen` or `startfile`. I expect the last will work... and I guess is my last resort, if I can't get a Python script to do it directly. Thanks for any input / insights! Answer: You can use: import os os.system("start python perf_test.py 5")
python: combine values in one column on the basis of ids in another column Question: I need to combine values in second column of a tab delimited file based on the ids in first column. The example is given below. What is the fastest way to do this. I can do it using for loop, going through each line, but I am sure there is some smart way to do it, which I am not aware of. 596230 Other postop infection 596230 Disseminated candidiasis 596230 Int inf clstrdium dfcile 596230 Pressure ulcer, site NOS 2846079 Schizophrenia NOS-unspec 7800713 CHF NOS 7800713 Chr airway obstruct NEC 7800713 Polymyalgia rheumatica 7800713 DMII wo cmp nt st uncntr into 596230 Other postop infection, Disseminated candidiasis, Int inf clstrdium dfcile, Pressure ulcer, site NOS 2846079 Schizophrenia NOS-unspec 7800713 CHF NOS, Chr airway obstruct NEC, Polymyalgia rheumatica, DMII wo cmp nt st uncntr Answer: Assuming you have your text in a file: from collections import defaultdict items = defaultdict(list) with open("myfile.txt") as infile: for line in file: id, text = line.rstrip().split("\t") items[id].append(text) for id in items: print id + "\t" + ", ".join(items[id]) This does not keep the original order of your `id`s, but it does keep the order of the texts.
Python TypeError when using class (wx.Python) Question: This program is that wx.textctrl is written "clicked" when button is clicked. This code runs without error. import wx class Mainwindow(wx.Frame): def __init__(self, parent, id, title): wx.Frame.__init__(self, parent, id, title, size=(300, 300)) panel = wx.Panel(self, -1) vbox = wx.BoxSizer(wx.VERTICAL) hbox1 = wx.BoxSizer(wx.HORIZONTAL) btn = wx.Button(panel, -1, 'OK', size=(70, 30)) btn.Bind(wx.EVT_BUTTON, self.click_btn) #line 12 hbox1.Add(btn, 0) vbox.Add(hbox1, 0) hbox2 = wx.BoxSizer(wx.HORIZONTAL) self.tc = wx.TextCtrl(panel, -1, style=wx.TE_MULTILINE) hbox2.Add(self.tc, 1, wx.EXPAND) vbox.Add(hbox2, 1, wx.EXPAND) panel.SetSizer(vbox) self.Centre() self.Show(True) def click_btn(self, event): #line 27 self.tc.WriteText("clicked\n") #line 28 if __name__=="__main__": app = wx.App() Mainwindow(None, -1, u"sample") app.MainLoop() But if this code change in this way, it gets error. change to line 12. btn.Bind(wx.EVT_BUTTON, Click_btn.click_btn) change to line 27 and 28. class Click_btn: def click_btn(self, event): self.tc.WriteText("clicked\n") The error is: Typeerror: unbound method click_btn() must be called with Click_btn instance as first argument (got CommandEvent instance instead) I don't know how to cope with this error. *Postscript I read answer,and this code change. But it don't run... change to line 12. button = Click_btn() btn.Bind(wx.EVT_BUTTON, button.click_btn) change to line 27 and 28. class Click_btn(Mainwindow): def click_btn(self, event): Mainwindow.tc.WriteText("clicked\n") Please teach point that I should change. Answer: class Click_btn: @classmethod def click_btn(cls, event): cls.tc.WriteText("clicked\n") #this will probably break now this will allow you to call it on the class rather than an instance of the class the class is `Click_btn` an instance would be `btn = Click_btn()` (btn is the instance of Click_btn)
Merging similar dictionaries in a list together Question: New to python here. I've been pulling my hair for hours and still can't figure this out. I have a list of dictionaries: [ {'FX0XST001.MID5': '195', 'Name': 'Firmicutes', 'Taxonomy ID': '1239', 'Type': 'phylum'} {'FX0XST001.MID13': '4929', 'Name': 'Firmicutes', 'Taxonomy ID': '1239','Type': 'phylum'}, {'FX0XST001.MID6': '826', 'Name': 'Firmicutes', 'Taxonomy ID': '1239', 'Type': 'phylum'}, . . . . {'FX0XST001.MID6': '125', 'Name': 'Acidobacteria', 'Taxonomy ID': '57723', 'Type': 'phylum'} {'FX0XST001.MID25': '70', 'Name': 'Acidobacteria', 'Taxonomy ID': '57723', 'Type': 'phylum'} {'FX0XST001.MID40': '40', 'Name': 'Acidobacteria', 'Taxonomy ID': '57723', 'Type': 'phylum'} ] I want to merge the dictionaries in the list based on their Type, Name, and Taxonomy ID [ {'FX0XST001.MID5': '195', 'FX0XST001.MID13': '4929', 'FX0XST001.MID6': '826', 'Name': 'Firmicutes', 'Taxonomy ID': '1239', 'Type': 'phylum'} . . . . {'FX0XST001.MID6': '125', 'FX0XST001.MID25': '70', 'FX0XST001.MID40': '40', 'Name': 'Acidobacteria', 'Taxonomy ID': '57723', 'Type': 'phylum'}] I have the data structure setup like this because I need to write the data to CSV using csv.DictWriter later. Would anyone kindly point me to the right direction? Answer: You can use the groupby function for this: <http://docs.python.org/library/itertools.html#itertools.groupby> from itertools import groupby keyfunc = lambda row : (row['Type'], row['Taxonomy ID'], row['Name']) result = [] data = sorted(data, key=keyfunc) for k, g in groupby(data, keyfunc): # you can either add the matching rows to the item so you end up with what you wanted item = {} for row in g: item.update(row) result.append(item) # or you could just add the matched rows as subitems to a parent dictionary # which might come in handy if you need to work with just the parts that are # different item = {'Type': k[0], 'Taxonomy ID' : k[1], 'Name' : k[2], 'matches': []) for row in g: del row['Type'] del row['Taxonomy ID'] del row['Name'] item['matches'].append(row) result.append(item)
Modulo operator in Python Question: What does modulo in the following piece of code do? from math import * 3.14 % 2 * pi How do we calculate modulo on a floating point number? Answer: Mathematically, the modulo operator can be represented as: a % b = c a - n*b = c Where `n` is an integer that makes `c` as small as possible, but positive. In this case: 3.14 % 2 = 3.14 - 1 * 2 = 1.14 Also, `3.14 % 2 * pi` is interpreted as `(3.14 % 2) * pi`. I'm not sure if you meant to write `3.14 % (2 * pi)` (in either case, the algorithm is the same. Just subtract/add until the number is as small as possible).
Heroku Django: Redirect all requests for www. to root domain Question: I need to redirect all requests coming from `www.mysite.com` to `mysite.com` I have found the [solution in rails](http://blog.dynamic50.com/2011/02/22/redirect-all-requests-for-www-to- root-domain-with-heroku/), but how can I do that in django/python? The only solution I could fine, which was posted by a moderator on GoDaddy was the above. Seems like I cannot resolve this kind of problem through the DNS Manager of GoDaddy. Any hints or thoughts? Thanks in advance. Answer: Solved whit this: from django.http import HttpResponsePermanentRedirect class WWWRedirectMiddleware(object): def process_request(self, request): if request.META['HTTP_HOST'].startswith('www.'): return HttpResponsePermanentRedirect('http://mysite.com')
Use Python to Optimally find Top 10 recently created files Question: I am trying to find a optimal way of extracting most recently, say 10, created files from a directory tree using Python. I've found a number[1, 2] of interesting solutions, however, they only involved a single file. ├── d1 │   ├── d1-1 │   ├── d1-1 : ├── d2 │   ├── d2-1 │   └── d2-2 │   │   ├── f1.xxx : : │   │   ├── fn.xxx ├── d3 │   ├── d3-1 : : The only way I can think of doing that, at the moment, is iteratively appending results by looping through the same tree until I have desired 10 results; the problem with this approach is that it will clearly be time consuming... especially that my directory trees may be huge. An alternative solution I thought about involves parsing an entire directory tree and generating file name paths with their corresponding creation or modification dates and then possibly use that 'index' file to get top 10 recent files. A database would have perhaps been useful here, however, it's not an option at the moment. Does anyone know of an optimal way of achieving this? [1] [Python return filepath/filename of most recent csv file stored in directory](http://stackoverflow.com/q/11900038/664424) [2] [Find the most recent file in a directory without reading all the contents of it](http://stackoverflow.com/q/4709968/664424) Answer: You could write a generator function to return the creation time and the filename, and use the `heapq` module to automatically keep track of the latest 'n' entries rather efficiently - example: import os import heapq def iterfiles(root): for base, dirs, files in os.walk(root): for filename in files: fullname = os.path.join(base, filename) yield os.stat(fullname).st_ctime, fullname print heapq.nlargest(10, iterfiles('some path here')) Just an aside - you may have to handle an `IOError` (a try/except around the yield) if permissions aren't available to stat the file.
runserver must be manually restarted after error in models.py Question: I'm following the book The Definitive Guide to Django and one thing I've started noticing is that whenever I make a single error in my models file, the server just hangs and is not automatically restarted when the error is fixed. Here's an example: I save the file with a line like this email = models.EmailField(blank=Tru) Which raises the obvious error and stack trace Validating models... Unhandled exception in thread started by <bound method Command.inner_run of <django.core.management.commands.runserver.Command object at 0x00000000025B0400>> Traceback (most recent call last): File "C:\Python27\lib\site-packages\django\core\management\commands\runserver.py", line 91, in inner_run self.validate(display_num_errors=True) File "C:\Python27\lib\site-packages\django\core\management\base.py", line 266, in validate num_errors = get_validation_errors(s, app) File "C:\Python27\lib\site-packages\django\core\management\validation.py", line 30, in get_validation_errors for (app_name, error) in get_app_errors().items(): File "C:\Python27\lib\site-packages\django\db\models\loading.py", line 158, in get_app_errors self._populate() File "C:\Python27\lib\site-packages\django\db\models\loading.py", line 64, in _populate self.load_app(app_name, True) File "C:\Python27\lib\site-packages\django\db\models\loading.py", line 88, in load_app models = import_module('.models', app_name) File "C:\Python27\lib\site-packages\django\utils\importlib.py", line 35, in import_module __import__(name) File "C:\....\models.py", line 17, in <module> class Author(models.Model): File "C:\...\models.py", line 20, in Author email = models.EmailField(blank=Tru) NameError: name 'Tru' is not defined Now, if I change `Tru` to `True`, the server does not restart. Is this intentional? Or is there something wrong with my application? I've just started learning Django so I have no idea if this is common behaviour. I'm on Windows, running Python 2.7.3 and Django 1.4.1. Answer: Not just you- I also experience this on occasion. Although the development server is usually pretty good about restarting after code changes, some particularly egregious errors (especially in your `models.py`) can sometimes cause it to hang. Just need to terminate it (`Ctrl+C`), restart it, and continue along your merry way.
Unable to execute Django runserver and no suggested solution seems to work Question: I've run Django servers on localhost before and have never run into this problem. I'm desperately trying to figure out what I've done wrong. I'm using Django 1.4 with Python 2.7 on Ubuntu 12.04. As far as I can tell I've configured everything correctly - I'm actually using another functional Django project I built as a go-by. If I run the following command (or any recommended variation thereof) I receive an error. django-admin.py runserver localhost:8000 Here is the error: ImportError: Settings cannot be imported, because environment variable DJANGO_SETTINGS_MODULE is undefined. Can someone please enlighten me as to why this error is occurring, how to fix it and why it doesn't happen with my other Django project?!? I've found many posts regarding this problem just by doing some quick Google searches, but none of the suggested solutions have helped - nor do I truly understand them. Answer: I'm pretty sure you're supposed to run manage.py runserver from inside your project directory. It automatically loads your settings.py, etc. From the [Django docs](https://docs.djangoproject.com/en/dev/ref/django- admin/): > Generally, when working on a single Django project, it’s easier to use > manage.py. Use django-admin.py with DJANGO_SETTINGS_MODULE, or the > --settings command line option, if you need to switch between multiple > Django settings files
Weird select error in python Question: Ok, so I have Python 2.5 and Windows XP. I was using select.select with a socket object. I tried it again and again, but whenever I run it, the thread it is in gives me an error like select.error(9, "Bad file descriptor"). The code is something like this: import socket, select s = socket.socket() s.bind((socket.gethostbyname(socket.gethostname()), 1312)) s.listen(5) inputs = [s] outputs = [] while True: r, w, e = select.select(inputs, outputs, inputs) for sock in r: if sock is s: inputs.append(s.accept()[0]) else: print s print s.recv(1024) Any info would be appreciated. Thanks! Answer: 1. You called `select.select` with no arguments. It should be something like: `select.select(inputs, outputs, [])`. 2. In the `else` you need to use `sock`, not `s` (the server). 3. Once the peer disconnects from a previously connected socket, you should remove it from the `inputs` list. You can know the peer has disconnected if `sock.recv()` returns an empty string or raises a `socket.error` exception. If you don't do this, you might end up feeding an invalid socket descriptor to `select.select`, causing the error you talked about.
How to remove accents from strings using Python (encoding parameter)? Question: I'm trying to remove accents from data in a csv file. So I use the remove_accents function (See below) but for that I need to encode my csv files in utf-8. But I've got the error `'encoding' is an invalid keyword argument for this function` I've seen that I may have to use Python3 and then execute python3 ./myscript.py? Is this the right way to do it ? Or is there another way to remove accents wihtout having to install python3 ? Any help would be much appreciated #!/usr/bin/env python import re import string import csv import unicodedata def remove_accents(data): return ''.join(x for x in unicodedata.normalize('NFKD', data) if \ unicodedata.category(x)[0] == 'L').lower() reader=csv.reader(open('infile.csv', 'r', encoding='utf-8'), delimiter='\t') writer=csv.writer(open('outfile.csv', 'w', encoding='utf-8'), delimiter=',') for line in reader: if line[0] != '': person=re.split(' ',line[0]) first_name = person[0].strip().upper() first_name1=unicode(first_name) first_name2=remove_accents(first_name1) if len(person) == 2: last_name=person[1].strip().upper() line[0]=last_name line[15]=first_name2 writer.writerow(line) Answer: You need to use [`codecs.open()`](http://docs.python.org/library/codecs.html#codecs.open) if you want to be able to specify an encoding. Also, [`unidecode`](http://pypi.python.org/pypi/Unidecode/).
Issues with pyinstaller Question: I have created a working GUI program (using tkinter), but when I try to compile it using pyinstaller (py2exe only works for python 2.6 and I used 2.7 for the program), it doesn't work. I have 2 files: program.py, and data.xml. The program uses the xml document to retrieve information and display it to the window. I have looked all over, but no one seems to have had a similar problem, and the pyinstaller documentation is useless. the command I used was python pyinstaller.py -w -mdata.xml -nProgram program.py It appears to make the spec file fine, but generates an error with a large traceback upon build: pyinstaller.utils.winmanifest.invalidManifestError: Invalid root element <items> - has to be one of <assembly>, <assemblyBinding>, <configuration>, <dependentAssembly> and quits the build process. This is the first time I have tried to build an executable for a project, so I'm kind of shooting in the dark here. Did I forget to do something, or did I just find a bug in pyinstaller's program? Answer: Normally I wouldn't answer my own question, but I have solved the issue and I think others should know about this. When creating your program and using an xml with it, you must have the root tag (the first one) as `<assembly>`. Not sure why, but it works when I do that. also, don't forget to use the `--hidden-import=Module` command if you imported anything into your program.
python "import media" didn't work but there was "media.py" Question: I read a book to learn python programming, it showed the code : import media So I downloaded `gwpy-code.zip` from the link <http://pragprog.com/titles/gwpy/source_code> and installed `PyGraphics-2.0.win32.exe` . In the path `C:\Python27\Lib\site- packages\pygraphics` there really was `media.py` ! But why `import media` didn't work ? (ps: I also tried this `C:\Python27\Scripts\easy_install nose` in the DOS box, still not work...) Best Regards :) Answer: Try: from pygraphics import media If you're not familiar with importing modules in Python yet, a brief [primer](http://docs.python.org/reference/simple_stmts.html#grammar-token- import_stmt) might be useful. >>> import sys >>> print sys.path If you try the code above, you will see a bunch of directories on your system path. `C:\Python27\Lib\site-packages\` should be one of these. To import a file located on your system path, you can use `import filename` (for filename.py). If the file lies in a subdirectory, e.g. `dir1/dir2/filename.py`, it can be imported using `import dir1.dir2.filename`. Note: A directory acts as a 'package' if it contains a file called `__init__.py`. A file that can be imported is called a 'module'.
urllib "module object is not callable" Question: This is my third python project, and I've received an error message: `'module object' is not callable`. I know that this means I'm referencing a variable or function incorrectly. But trial and error hasn't been able to help me solve this. import urllib def get_url(url): '''get_url accepts a URL string and return the server response code, response headers, and contents of the file''' req_headers = { 'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/525.13 (KHTML, like Gecko) Chrome/0.A.B.C Safari/525.13', 'Referer': 'http://python.org'} #errors here on next line request = urllib.request(url, headers=req_headers) # create a request object for the URL opener = urllib.build_opener() # create an opener object response = opener.open(request) # open a connection and receive the http response headers + contents code = response.code headers = response.headers # headers object contents = response.read() # contents of the URL (HTML, javascript, css, img, etc.) return code , headers, contents testURL = get_url('http://www.urlhere.filename.zip') print ("outputs: %s" % (testURL,)) I've been using this link for reference: <http://docs.python.org/release/3.0.1/library/urllib.request.html> **Traceback:** Traceback (most recent call last): File "C:\Project\LinkCrawl\LinkCrawl.py", line 31, in <module> testURL = get_url('http://www.urlhere.filename.zip') File "C:\Project\LinkCrawl\LinkCrawl.py", line 21, in get_url request = urllib.request(url, headers=req_headers) # create a request object for the URL TypeError: 'module' object is not callable Answer: In python 3, the `urllib.request` object is a module. You need to call objects _contained_ in this module. This is an important change from Python 2, if you are using example code you need to take that into account. For example, creating the `Request` object and the opener: request = urllib.request.Request(url, headers=req_headers) opener = urllib.request.build_opener() response = opener.open(request) Read the [documentation](http://docs.python.org/py3k/library/urllib.request.html) carefully.
Unable to use raw_input() during event handeling in Matplotlib while running pylab -- RuntimeError: can't re-enter readline Question: I'm trying to write a script that allows the user to manipulate a graph via event handling in matplotlib, but I need to have them enter some additional information through the terminal Calling `raw_input()` seems to break the scripts, and throws a `RuntimeError: can't re-enter readline` error here's a simple piece of code to demonstrate this: import matplotlib.pyplot as plt import numpy as np fig = plt.figure() ax = fig.add_subplot(111) ax.plot(np.random.rand(10)) def keypress(event): print 'You press the "%s" key' %event.key print 'is this true? Type yes or no' y_or_n = raw_input() cid = fig.canvas.mpl_connect('key_press_event', keypress) plt.show() This works fine if I run it using python, but breaks using ipython --pylab. Unfortunately, I need the interactive mode I see other people have had this problem but I haven't seen a solution Answer: You're running into trouble because matplotlib is still listening for keypresses. Unfortunately, simply disconnecting its event listening did not work for me interactively. This solution, however, did work. Though it limits you in not being able to use the 'y', 'e', 's', 'n', or 'o' keys. There are workarounds for this if that is a necessity. import matplotlib.pyplot as plt import numpy as np #disable matplotlib keymaps keyMaps = [key for key in plt.rcParams.keys() if 'keymap.' in key] for keyMap in keyMaps: plt.rcParams[keyMap] = '' str = '' fig = plt.figure() ax = fig.add_subplot(111) ax.plot(np.random.rand(10)) def keypress(event): global str if event.key in ['y','e','s','n','o']: str += event.key else: print 'You press the "%s" key' %event.key print 'is this true? Type yes or no' if str == 'yes': print str str = '' elif str == 'no': print str str = '' cid = fig.canvas.mpl_connect('key_press_event', keypress) plt.show()
How to download a text file or some objects from webpage using Python? Question: I am writing a function that downloads and stores the today's list of pre- release domains .txt file from <http://www.namejet.com/pages/downloads.aspx>. I am trying to achieve it using json. import json import requests def hello(): r = requests.get('http://www.namejet.com/pages/downloads.aspx') #Replace with your website URL with open("a.txt", "w") as f: #Replace with your file name for item in r.json or []: try: f.write(item['name']['name'] + "\n") except KeyError: pass hello() I need to download the file which consist of pre-release domains using python. How can I do that? Is the above code right way to do it? Answer: I dont't think mechanize is much use for javascript, use [selenium](http://pypi.python.org/pypi/selenium). Here's an example: In [1]: from selenium import webdriver In [2]: browser=webdriver.Chrome() # Select browser that you want to automate In [3]: browser.get('http://www.namejet.com/pages/downloads.aspx') In [4]: element=browser.find_element_by_xpath( '//a[@id="ctl00_ContentPlaceHolder1_hlPreRelease1"]') In [5]: element.click() Now you can find `prerelease_10-08-2012.txt` in your download folder and you can open it in a usual way.
How to download text file from website using Python? Question: I need to write a function that downloads and stores the today's list of pre- release domains .txt file from `http://www.namejet.com/pages/downloads.aspx.` So as today is 8th of October you want to get the file "Monday, October 08, 2012". Tried with requests but didn't work. I'm having trouble because the file is not stored on a fixed URL but is hidden behind some Javascript. Answer: This one's a little tricky as you're dealing with ASP.NET's [postback](http://stackoverflow.com/questions/4251157/what-is-a-postback) system. If this is for anything other than a personal script, I'd be wary as you're effectively not only using another site's data, but reverse engineering their software as well (however, IANAL and have no idea about legalities around these issues in web systems). What you're going to want to do is check the POST data (using Firebug, Chrome developer tools, etc) and look for the `__EVENTTARGET` and `__VIEWSTATE` attributes of the form object. You'll have to decode the `__VIEWSTATE` to be readable (check out <http://ignatu.co.uk/ViewStateDecoder.aspx>). From there, I think you _should_ be able to figure out how to get the data you're looking for. From Python, it's as easy as: from urllib2 import urlopen from urllib import urlencode data = urlopen('url', urlencode({ '__VIEWSTATE': 'foo', '__EVENTTARGET': 'bar', })).read()
MacOSX python error on import Question: Ive recently installed SimpleCV using the osX-Lion setup instructions in page <https://github.com/ingenuitas/simplecv> Then I type python in Terminal and when I try the following I get an error. import SimpleCV Fatal Python error: (pygame parachute) Segmentation Fault Abort trap: 6 However I get no errors when i try to import pygame myself. Any fix for this? Thanks Answer: Use and follow this instructions of the [new](https://github.com/sightmachine/simplecv) repository, the you are [using](https://github.com/ingenuitas/simplecv) have this Alert messages. > THE SIMPLECV REPO HAS MOVED (As of 4/17/13) Says the repository title. > WARNING: The REPO here is for legacy purposes only
The right way to architect a cluster in EC2 Question: I'm working on open-source tool which will have to run on a cluster in EC2, organized in "one master - several slaves" manner. I need some advice on how to organize things correctly and in the most simple, yet reliable way. What I basically need is a code which will run on master instance (which user runs manually) and do the following: a) Run N slave instances (N came from user) b) After each instance is up and running - connect by SSH and start something. c) Keep track on slave instances being alive (by e.g. simply pinging them) d) If slave instance fails - make sure it is terminated, run another one and repeat step b) e) By signal from user - shutdown slave instances. All this looks pretty simple and straightforward yet I have some questions: 1) Ready solutions. First I'd taken a look at [Zookeeper](http://zookeeper.apache.org/), but I was frightened by its complexity. It seems to be an overkill for such a simple thing that I need. Another thing I found is [StarCluster](http://star.mit.edu/cluster/), it is also in Python which is nice (my tool is in Python too), but I'm not sure it does what I need (keeping track, rerunning instances). My question is: are there simple tools, libraries, frameworks that I'm not aware of? 2) Another way to go will be to implement things myself. The question here is: are there any pitfalls in my problem that I'm not aware of? It all looks simple: several calls to API plus some regular ping, but may be I don't see something here, so it would be really right to use the already written tool? 3) In case of coding it all by myself the question is: to use CloudWatch or not. Does it really makes any difference for managing internal computation clusters or it is only better for helping with high-load sites, etc?. 4) My simple architecture does not have any protection from master node failure. The user runs it, then connects to it via web interface and runs the cluster, but if master node fails - everything gets broken. The slaves can check the existence of master node and terminate themselves in case master node fails. This adds some protection from getting a headless running money- consuming cluster, but that doesn't solve the problem of graceful restart. How to solve this? 5) Are there any other thing to know or important materials to read that I should be familiar with before starting to code this project? Thank you in advance! Answer: You might want to take a look at amazon's autoscaling. Obviously this only handles EC2 instances but handles a lot of the complexity of starting, stopping and monitoring instances for you. With AutoScaling you create one or more groups. You tell amazon how to create more instances in your group (AMI, userData, type of instance, etc.) and how many instances you want in your group. Amazon will start up as many instances as required and replace them should they fail. You can use the api to change the number of required nodes (you can set it to 0 if you don't need any instances at that time) or you can have it based on cloudwatch metrics. For example if you used SQS to distribute jobs to your slaves you could configure autoscaling to increase the group size from 0 to the desired number when there are jobs available and to return the group size to 0 once the queue becomes empty. You can also have multiple groups, for example you might have a group that corresponds to the master node which always has 1 instance (and ec2 will replace it should it fail) and a second group for slaves which will have 0 instances when there is no work to be done and N instances when there is work available. I've not used the EC2 apis from python myself but I hear that boto does a good job of handling this for you.
How to parse YouTube XML using Python? Question: I am trying to parse the xml from YouTube that is embedded in the code below. I am trying to display all of the titles. However, I am running into trouble when I try to print the 'title' only enter lines appear. Any advice? #import library to do http requests: import urllib2 #import easy to use xml parser called minidom: from xml.dom.minidom import parseString #all these imports are standard on most modern python implementations #download the file: file = urllib2.urlopen('http://gdata.youtube.com/feeds/api/users/buzzfeed/uploads?v=2&max-results=50') #convert to string: data = file.read() #close file because we dont need it anymore: file.close() #parse the xml you downloaded dom = parseString(data) entry=dom.getElementsByTagName('entry') for node in entry: video_title=node.getAttribute('title') print video_title Answer: Title is not an attribute, it is a child element of an entry. here is an example how to extract it: for node in entry: video_title = node.getElementsByTagName('title')[0].firstChild.nodeValue print video_title
Execute code on App Engine application initialization Question: When running a Python Web Application on App Engine, we need to set up some mechanism to execute some code before (or during) the application's initialization. This means that, in the optimal solution, the code that we need to run is executed as early as possible. The purpose of this is to allow for the App Engine remote_api to be initialized before the **local** datastore is accessed, so as to prevent datastore access conflicts. This is a very rough example of what we're looking for: imports (including remote_api) def some_initialization_function_or_similar (args): some_init_function_calls(...) setup_remote_api(...) access_datastore_the_first_time(...) Please take this question as reference to the scenario we're looking at: [Using GAE remote api for debugging from localhost - Connecting too late?](http://stackoverflow.com/questions/12588327/using-gae-remote-api-for- debugging-from-localhost-connecting-too-late) Answer: Assuming you have a single entry point (== script named in app.yaml) you can just call the desired code after your imports but before you call your main() function. This means it will be run only when the main script is being imported, which is only on the first request (hitting that entry point). If you have multiple entry points, try putting it in appengine_config.py. That gets loaded pretty early.
python: how to store data in mongo via http put Question: I am trying to create a REST API application using python bottle framework I'd like to be able to insert data in mongodb via HTTP PUT request. So far I am able to get response from the mongodb using HTTP GET. Please help me INSERT data in mongodb via HTTP PUT. JSON format I have to insert as follows: {"_id": "id_1", "key_1": "value_1"} [i am using [this extension](https://chrome.google.com/webstore/detail/advanced-rest-client- appl/hgmloofddffdnphfgcellkdfbfbjeloo) to get and put http response] import json import bottle from bottle import route, run, request, abort from pymongo import Connection connection = Connection('localhost', 27017) db = connection.mydatabase @route('/documents', method='PUT') def put_document(): data = request.body.readline() if not data: abort(400, 'No data received') entity = json.loads(data) if not entity.has_key('_id'): abort(400, 'No _id specified') try: db['documents'].save(entity) except ValidationError as ve: abort(400, str(ve)) @route('/documents/:id', method='GET') def get_document(id): entity = db['documents'].find_one({'_id':id}) if not entity: abort(404, 'No document with id %s' % id) return entity run(host='localhost', port=8080) Answer: The following revised version of your code seems to work as you intended: import json from bottle import route, run, request, abort from pymongo import Connection connection = Connection('localhost', 27017) db = connection.mydatabase @route('/documents', method='PUT') def put_document(): data = request.body.readline() print(data) if not data: abort(400, 'No data received') entity = json.loads(data) if not entity.has_key('_id'): abort(400, 'No _id specified') try: db.documents.insert(entity) except ValidationError as ve: abort(400, str(ve)) @route('/documents/<_id>', method='GET') def get_document(_id): entity = db.documents.find_one({'_id': _id}) if not entity: abort(404, 'No document with id %s' % _id) return entity run(host='localhost', port=8080) I have _MongoDB_ running and executing the script, start the server on `localhost` port `8080`, I then execute the following commands on a shell with the expected results: $ echo '{"_id": "id_1", "key_1": "value_1", "key_2": "value_2"}' | curl -X PUT -d @- http://localhost:8080/documents $ curl http://localhost:8080/documents/id_1 {"_id": "id_1", "key_1": "value_1", "key_2": "value_2"}
How to run a DOS batch file in background using Python? Question: How to run a DOS batch file in background using Python? I have a test.bat file in say C:\ Now, I want to run this bat file using python in the background and then I want to return to the python command line. I run the batch file using `subprocess.call('path\to\test.bat')` from the python command line. It runs the batch file in the same window as the python command line. If still not clear/ TL.DR- What is happening: >>>subprocess.call('C:\test.bat') (Running test.bat. Can't use python in the same window) What I want: >>>subprocess.call('C:\test.bat') (New commandline window created in the background where test.bat runs in parallel.) >>> Answer: This seems to work for me: import subprocess p = subprocess.Popen(r'start cmd /c C:\test.bat', shell=True) p.wait() print 'done'
handling exceptions in settrace 'return' calls Question: In Python 2.x, the frame object passed into a [`settrace`](http://docs.python.org/py3k/library/sys.html#sys.settrace) handler had an `f_exc_type` attribute. In Python 3.x, this `f_exc_type` has been removed. If a function is propagating an exception, the trace 'return' is called but the argument is `None` and `sys.exc_info()` is `(None,None,None)`. This is described in the [docs](http://docs.python.org/py3k/library/sys.html#sys.settrace): > `[return]`A function (or other code block) is about to return. The local > trace function is called; arg is the value that will be returned, or None if > the event is caused by an exception being raised. The trace function’s > return value is ignored. In Python 3, how can a tracer determine in a `return` hook that an exception is being propagated? How can it differentiate it from a function returning `None` normally? Answer: This does seem fairly broken. It's a bit of a hack, but you can tell the difference by looking at the bytecode for the last instruction: import opcode def tracer(frame, event, arg): if event == 'return': if arg is not None or (opcode.opname[frame.f_code.co_code[frame.f_lasti]]] in ('RETURN_VALUE', 'YIELD_VALUE')): print('exit via return', arg) else: print('exit via exception')
re-implement __eq__ to compare sets with symmetric_difference in python Question: I have a set of filenames coming from two different directories. currList=set(['pathA/file1', 'pathA/file2', 'pathB/file3', etc.]) My code is processing the files, and need to change currList by comparing it to its content at the former iteration, say processLst. For that, I compute a symmetric difference: toProcess=set(currList).symmetric_difference(set(processList)) Actually, I need the symmetric_difference to operate on the basename (file1...) not on the complete filename (pathA/file1). I guess I need to reimplement the `__eq__` operator, but I have no clue how to do that in python. 1. is reimplementing `__eq__` the right approach? or 2. is there another better/equivalent approach? Answer: Here is a token (and likely poorly constructed) `itertools` version that should run a little bit faster if speed ever becomes a concern (although agree that @Zarkonnen's one-liner is pretty sweet, so +1 there :) ). from itertools import ifilter currList = set(['pathA/file1', 'pathA/file2', 'pathB/file3']) processList=set(['pathA/file1', 'pathA/file9', 'pathA/file3']) # This can also be a lambda inside the map functions - the speed stays the same def FileName(f): return f.split('/')[-1] # diff will be a set of filenames with no path that will be checked during # the ifilter process curr = map(FileName, list(currList)) process = map(FileName, list(processList)) diff = set(curr).symmetric_difference(set(process)) # This filters out any elements from the symmetric difference of the two sets # where the filename is not in the diff set results = set(ifilter(lambda x: x.split('/')[-1] in diff, currList.symmetric_difference(processList)))
Error while installing MySQLdb for Python on Mac OSX 10.6.8 with mysql inside XAMPP Question: I am trying to import MySQldb in python and call the python script from a php script in XAMPP. Here is what I did: Environment: 1\. Mac OSX 10.6.8 2\. Python version 2.6 (default)[64bit] Done so far: 1\. Installed XAMPP 2\. MySQL config path: /Applications/XAMPP/xamppfiles/bin/mysql_config 3\. Downloaded MySQL- python-1.2.4b4 4\. edited the site.cfg with config path for MySQL 5\. Ran following commands sudo python setup.py clean python setup.py build Got the following error: running build running build_py copying MySQLdb/release.py -> build/lib.macosx-10.6-universal-2.6/MySQLdb running build_ext building '_mysql' extension gcc-4.2 -fno-strict-aliasing -fno-common -dynamic -DNDEBUG -g -fwrapv -Os -Wall - Wstrict-prototypes -DENABLE_DTRACE -pipe -Dversion_info=(1,2,4,'beta',4) - D__version__=1.2.4b4 -I/Applications/XAMPP/xamppfiles/include/mysql - I/System/Library/Frameworks/Python.framework/Versions/2.6/include/python2.6 -c _mysql.c -o build/temp.macosx-10.6-universal-2.6/_mysql.o -mmacosx-version-min=10.4 -arch i386 -arch ppc -D_P1003_1B_VISIBLE -DSIGNAL_WITH_VIO_CLOSE -DSIGNALS_DONT_BREAK_READ - DIGNORE_SIGHUP_SIGQUIT -DDONT_DECLARE_CXA_PURE_VIRTUAL In file included from _mysql.c:44: /Applications/XAMPP/xamppfiles/include/mysql/my_config.h:1053:1: warning: "HAVE_WCSCOLL" redefined In file included from /System/Library/Frameworks/Python.framework/Versions/2.6/include/python2.6/Python.h:8, from _mysql.c:29: /System/Library/Frameworks/Python.framework/Versions/2.6/include/python2.6/pyconfig.h:803:1 : warning: this is the location of the previous definition /usr/libexec/gcc/powerpc-apple-darwin10/4.2.1/as: assembler (/usr/bin/../libexec/gcc/darwin/ppc/as or /usr/bin/../local/libexec/gcc/darwin/ppc/as) for architecture ppc not installed Installed assemblers are: /usr/bin/../libexec/gcc/darwin/x86_64/as for architecture x86_64 /usr/bin/../libexec/gcc/darwin/i386/as for architecture i386 In file included from _mysql.c:44: /Applications/XAMPP/xamppfiles/include/mysql/my_config.h:1053:1: warning: "HAVE_WCSCOLL" redefined In file included from /System/Library/Frameworks/Python.framework/Versions/2.6/include/python2.6/Python.h:8, from _mysql.c:29: /System/Library/Frameworks/Python.framework/Versions/2.6/include/python2.6/pyconfig.h:803:1: warning: this is the location of the previous definition _mysql.c:3131: fatal error: error writing to -: Broken pipe compilation terminated. lipo: can't open input file: /var/tmp//ccQsr7Lk.out (No such file or directory) error: command 'gcc-4.2' failed with exit status 1 Answer: yum install mysql-devel pip install MySQL-python
unable to get values from a login page in web.py Question: I am using python web.py framework to create a small web application which has just 1. Login screen (Authentication) 2. Screen with list of records(After succesfull login) Presently i am trying to create a login screen authentication I have created an `index.py` file with code as below **index.py** import os import sys import web from web import form from web.contrib.auth import DBAuth render = web.template.render('templates/') urls = ( '/', 'Login', ) app = web.application(urls, globals()) db = web.database(dbn='mysql', db='Python_Web', user='root', pw='redhat') class Login: login_form = form.Form( form.Textbox('username', form.notnull), form.Password('password', form.notnull), form.Button('Login'), ) def GET(self): form = self.login_form() return render.login(form) def POST(self): # if not self.login_form.validates(): # return render.login(self.login_form) post = self.login_form() username = post['username'].value print username,">>>>>>>>>>>>>>>>>>>>>>username" password = post['password'].value ident = db.select('user', where='user_login=$username', vars=locals()) if __name__ == "__main__": web.internalerror = web.debugerror app.run() My **login.html** code $def with (form) <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>Log in</title> </head> <body> <div id="container"> <h1>Log in Details</h1> <form action="" method="post" accept-charset="utf-8"> <p><label for="username">Username: <input type="text" name="username" id="username" maxlength="254" tabindex="1" /> </label></p> <p><label for="password">Password: <input type="password" name="password" id="password" maxlength="254" tabindex="2" /> </label></p> <p><label for="Login"></label><button id="Login" name="Login">Login</button></p> </form> </div> </body> When i run the above file with url `www.localhost:9080` in browser i can see the screen with fields `username, password and login` button , but when i enter username and password and clicked `login` button and tried to print the username i cannot fetch any data from the browser and the result showing is as below None >>>>>>>>>>>>>>>>>>>>>>username 0.0 (1): SELECT * FROM user WHERE user_login=NULL Can anyone let me why i am unable fetch the details entered through browser ?, am i missing anything in the above code and finally all my intention is to create a `login` page and `validate` the user details by checking in the database and `redirect` to the next page if user exits I request to please help me out in writing the code for fetching the details from the browser and checking in the database and redirecting to another html page if user exists. I am really stuck and breaking my heads to complete this process Answer: Make sure you validate the form before trying to access any of the inputs def POST(self): post = self.login_form() post.validates() username = post['username'].value print username,">>>>>>>>>>>>>>>>>>>>>>username" password = post['password'].value ident = db.select('user', where='user_login=$username', vars=locals()) After that change the code works for me. Good luck!
Pydev using wrong IPython version? Question: I have Pydev 2.7, Python 3.2 and IPython 0.13 installed. However, when I run the interactive console in Eclipse it says PyDev console: using IPython 0.11 I cannot imagine where IPython 0.11 is supposed to come from. How can I check? After running the console, `import IPython; IPython.__version__` also gives me the correct version 0.13. Is it IPython 0.13 in the console now or is something wrong? Answer: I think you're fine. I tried IPython.__version__ and also get 0.13 in the PyDev console: import sys; print('%s %s' % (sys.executable or sys.platform, sys.version)) C:\Python27\python.exe 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)] PyDev console: using IPython 0.11 import IPython IPython.__version__ Out[1]: '0.13.1'
Unable to switch between two boto.cfg files Question: I have two _boto.cfg_ files, one for QA and the other for Production. I can choose dynamically which _boto.cfg_ to choose. When I choose QA and call `get_all_buckets()` I get all the buckets of QA. But when I change to Production, it still returns QA buckets. My script is in python. Is there a way I can disable the boto connection? I have tried to exit from Python and create a new object but it still returns QA buckets although the _boto.cfg_ has been updated to Production credentials. Answer: Are you sure you are picking up different credentials? There is no state retained across different Python sessions. Try running this little script with each config file: >>> import boto >>> print boto.config.get_value('Credentials', 'aws_access_key_id') Do you get a different value printed each time? If not, you could try having two config files, boto1.cfg and boto2.cfg and then setting the environment variable BOTO_CONFIG to point to one or the other.
python, unittest, test a script with command line args Question: I've written a python script that takes command line arguments and plays one round of Tic Tac Toe. running it looks like this... > run ttt o#xo##x## x 0 1 If the move is legal it then prints the new board layout and whether anyone won the game I have to write tests for it using unittest. I dont know how to test the whole script with various command line parameters, all the examples I've seen seem to just test individual functions within the script. Also the script uses `argparse` to parse the parameters Thanks! Answer: Refactor your program so that its main action (minus the argparsing) happens in a "main" function: def main(args): ... if __name__ == '__main__': args = parse_args() main(args) Then you can write tests for the behavior of `main` and `parse_args`. PS. It is possible to use the `subprocess` module to call your program as an external process and then parse the output, but I think that would be uglier and unnecessary. PPS. As an added benefit of writing your program this way, you will be able to import your program as a module, and call its main function in other scripts. That might be useful if, for example, you would one day like to build a GUI for it.
What is the difference between Abstract classes and Mixins in Python django Question: Can anyone please tell what is the difference between Abstract class and Mixin in Django. I mean if we are to inherit some methods from base class why there is separate terminology like mixins if that is just a class. What is diff between baseclass and mixins Answer: In Python (and Django), **mixin** is a type of multiple inheritance. I tend to think of them as "specilist" classes that adds a particular functionality to the class that inheritates it (along with other classes). They aren't really meant to stand on their own. Example with Django's `SingleObjectMixin`, # views.py from django.http import HttpResponseForbidden, HttpResponseRedirect from django.core.urlresolvers import reverse from django.views.generic import View from django.views.generic.detail import SingleObjectMixin from books.models import Author class RecordInterest(View, SingleObjectMixin): """Records the current user's interest in an author.""" model = Author def post(self, request, *args, **kwargs): if not request.user.is_authenticated(): return HttpResponseForbidden() # Look up the author we're interested in. self.object = self.get_object() # Actually record interest somehow here! return HttpResponseRedirect(reverse('author-detail', kwargs={'pk': self.object.pk})) The added [`SingleObjectMixin`](https://docs.djangoproject.com/en/dev/ref/class-based- views/mixins-single-object/#django.views.generic.detail.SingleObjectMixin) will enable you to look up the `author` with just [`self.get_objects()`](https://docs.djangoproject.com/en/dev/ref/class-based- views/mixins-single- object/#django.views.generic.detail.SingleObjectMixin.get_object). * * * An abstract class in Python looks like this: class Base(object): # This is an abstract class # This is the method child classes need to implement def implement_me(self): raise NotImplementedError("told you so!") In languages like Java, there is an `Interface` contract which is an _interface_. However, Python doesn't have such and the _closest_ thing you can get is an abstract class (you can also read on [abc](http://docs.python.org/library/abc.html). This is mainly because Python utlizes [duck typing](http://en.wikipedia.org/wiki/Duck_typing#In_Python) which kind of removes the need for interfaces. Abstract class enables polymorphism just like interfaces do.
concept of session and cookie in web development python Question: I am very new to web development, i am working on `web.py` framework to develop a small web application. suppose the login screen is `localhost:9090/login`, after the succesfull login it is redirecting to next page `localhost:9090/details` and after clicking another button `add` its again redirecting to `localhost:9090/details/details_entry`. But when i tried directly `localhost:9090/details`on browser its working and able to see the page without even logged in . So after googling a lot came to know that i need to use `session concept` , but i am tired as of now for busy schedule on searching about web concepts in google. Can anyone let me know the concept of 1. `session` (Actually why it is created and how to use it after login through page in python) 2. Actually whats the complete concept of `user authentication` , What are the steps to follow to create a user login page And steps to follow after user logged in with details what happens when user logouts and how to session code in python I expect what ever the language it is but the concept of developing login screen and redirecting to next url by creating some sessions ids is same, so the user authentication concept is very important and may be this question is useful to others. **Edited Code** **\--------------** **Login.py** import os import sys import web from web import form render = web.template.render('templates/') urls = ( '/', 'Login', '/projects', 'Projects', '/project_details', 'Project_Details', ) app = web.application(urls, globals()) web.config.debug = False db = web.database(dbn='mysql', db='Python_Web', user='root', pw='redhat') settings = {} store = web.session.DBStore(db, 'sessions') session = web.session.Session(app, store, initializer={'user': None}) class Login: login_form = form.Form( form.Textbox('username', form.notnull), form.Password('password', form.notnull), form.Button('Login'), ) def GET(self): form = self.login_form() return render.login(form) def POST(self): if not self.login_form.validates(): return render.login(self.login_form) i = web.input() username = i.username password = i.password user = db.select('user', where = 'user_login = $username', vars = {'username': username} if username == user['username'] and password == user['password']: session.user = username raise web.seeother('/projects') else: return render.login_error(form) def auth_required(func): def proxyfunc(self, *args, **kw): print session.user,"=======> Session stored" try: if session.user: return func(self, *args, **kw) except: pass raise web.seeother("/") return proxyfunc class Projects: project_list = form.Form( form.Button('Add Project'), ) @auth_required def GET(self): project_form = self.project_list() return render.projects(project_form) def POST(self): raise web.seeother('/project_details') if __name__ == "__main__": web.internalerror = web.debugerror app.run() In the above code after successfull login the page is redirecting to next page. Here i need to implement session concept, but i was stuck on where to implement session code in the above code. Can anyone please point me to a right way on where to write session code in the above py code for login page. After this worked need to implement logout functionality in the same py file Edited code after implementing `auth_required` function and got the below error **Result:** Traceback (most recent call last): File "/usr/lib/python2.7/site-packages/web/application.py", line 239, in process return self.handle() File "/usr/lib/python2.7/site-packages/web/application.py", line 230, in handle return self._delegate(fn, self.fvars, args) File "/usr/lib/python2.7/site-packages/web/application.py", line 420, in _delegate return handle_class(cls) File "/usr/lib/python2.7/site-packages/web/application.py", line 396, in handle_class return tocall(*args) File "/home/local/user/python_webcode/index.py", line 102, in proxyfunc print session.user,"=======> Session Stored" File "/usr/lib/python2.7/site-packages/web/session.py", line 71, in __getattr__ return getattr(self._data, name) AttributeError: 'ThreadedDict' object has no attribute 'user' Answer: web.py provides [session](http://webpy.org/cookbook/sessions) abstraction and several session stores. What you have to do, is to write login controller, display the form on GET, and find user and perform password check on POST, then store the user in session and kill the session on logout. After it you may write decorator that checks if user exists in session to use it over controller methods. Anyway, user authentication concept is mostly the same in all web apps. If you need already working solution for web.py then you may take a look at this module: <http://jpscaletti.com/webpy_auth/> If you decided to implement login youself, the simplest auth decorator will probably look like this: def auth_required(func): def proxyfunc(self, *args, **kw): try: if session.user: # user is logged in return func(self, *args, **kw) except: pass # user is not logged in raise web.seeother("/login") return proxyfunc Then you will be able to use @auth_required before your GET and POST methods in controllers like this: class Projects: @auth_required def GET(self): pass
The __str__ method returning a unicode string works in one environment but fails in another Question: I thought, I understood unicode and python. But this issue confuses me a lot. Look at this small test program: # -*- coding: utf-8 -*- class TestC(object): def __str__(self): return u'äöü' import sys print sys.version print sys.stdin.encoding print sys.stdout.encoding print u'öäü' #this works x = TestC() print x #this doesn't always work When I run this from my bash terminal on ubuntu, I get the following result: 2.7.3 (default, Aug 1 2012, 05:14:39) [GCC 4.6.3] utf-8 utf-8 öäü Traceback (most recent call last): File "test_mod.py", line 14, in <module> print x #this doesn't ' UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-2: ordinal not in range(128) However, when I run the same thing from within eclipse (using the pydev module), both print statements work flawlessly. The console windows says: 2.7.3 (default, Aug 1 2012, 05:14:39) [GCC 4.6.3] utf-8 utf-8 öäü äöü Can someone please explain to me what the issue is? Why does the __str__ method work in one case but not in the other? What is the best way to fix this? Answer: See this related question: [Python __str__ versus __unicode__](http://stackoverflow.com/questions/1307014/python-str-versus- unicode) Basically, you should probably be implementing the special method `__unicode__` rather than `__str__`, and add a stub `__str__` that calls `__unicode__`: def __str__(self): return unicode(self).encode('utf-8')
permission denied when creating an .html file in python Question: so this is my first python experience. I have a list of images in folder that I'm trying to convert to html pages. For that I have the following code: import inspect, os, errno, markup path = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))+'/www/img/' print path for f in os.listdir(path): counter = 1 page = markup.page() page.init(charset="UTF-8") from markup import oneliner as e page.a(e.img(src='img/'+f, width=1024, height=768), href='') final = open('/index'+str(counter)+'.html','w') final.write(page) and I get an `IOError: [Errno 13] Permission denied: '/index1.html'` message.... any clues or ideas are much appreciated. thanks! Answer: I think the main problem is related to file permissions of root folder (`/`). Try running the script as root or pick some other directory that you are sure you have write access to.
How to send Python variable to bash variable? Question: I am trying to use Python to select a variable from a list, then speak it outloud using the bash command. Right now I have something like this foo = ["a","b","c","d"] from random import choice x = choice(foo) foo.remove(x) from os import system system('say x') This says "x", what I need is for it to say the value of the `x` variable. Answer: I suppose you can use `os.system`, but better might be `subprocess`: import subprocess subprocess.call(['say',x])
How to get all YouTube comments with Python's gdata module? Question: Looking to grab all the comments from a given video, rather than go one page at a time. from gdata import youtube as yt from gdata.youtube import service as yts client = yts.YouTubeService() client.ClientLogin(username, pwd) #the pwd might need to be application specific fyi comments = client.GetYouTubeVideoComments(video_id='the_id') a_comment = comments.entry[0] The above code with let you grab a single comment, likely the most recent comment, but I'm looking for a way to grab _all_ the comments at once. Is this possible with Python's `gdata` module? * * * The Youtube API docs for [comments](https://developers.google.com/youtube/2.0/developers_guide_protocol_comments), the comment feed [docs](http://gdata-python- client.googlecode.com/hg/pydocs/gdata.youtube.html#YouTubeVideoCommentFeed) and the Python API [docs](https://developers.google.com/youtube/1.0/developers_guide_python#Comments) Answer: The following achieves what you asked for using the [Python YouTube API](https://gdata-python-client.googlecode.com/hg/pydocs/gdata.youtube.html): from gdata.youtube import service USERNAME = '[email protected]' PASSWORD = 'a_very_long_password' VIDEO_ID = 'wf_IIbT8HGk' def comments_generator(client, video_id): comment_feed = client.GetYouTubeVideoCommentFeed(video_id=video_id) while comment_feed is not None: for comment in comment_feed.entry: yield comment next_link = comment_feed.GetNextLink() if next_link is None: comment_feed = None else: comment_feed = client.GetYouTubeVideoCommentFeed(next_link.href) client = service.YouTubeService() client.ClientLogin(USERNAME, PASSWORD) for comment in comments_generator(client, VIDEO_ID): author_name = comment.author[0].name.text text = comment.content.text print("{}: {}".format(author_name, text)) Unfortunately the API limits the number of entries that can be retrieved to **1000**. This was the error I got when I tried a tweaked version with a hand crafted `GetYouTubeVideoCommentFeed` URL parameter: gdata.service.RequestError: {'status': 400, 'body': 'You cannot request beyond item 1000.', 'reason': 'Bad Request'} Note that the same principle should apply to retrieve entries in other feeds of the API. If you want to hand craft the `GetYouTubeVideoCommentFeed` URL parameter, its format is: 'https://gdata.youtube.com/feeds/api/videos/{video_id}/comments?start-index={sta‌​rt_index}&max-results={max_results}' The following restrictions apply: `start-index <= 1000` and `max-results <= 50`.
Subversion Get Text Status Data in Python Commit Hooks Question: I'm looking for a way to extend Python Commit Hooks such that I can ONLY find out all the files that were modified excluding all the revision properties changed. Is there a SVN.Core or SVN.fs or another SVN import lib function that I could use? I'm currently looking into svn_fs_txn_prop but haven't had much luck. Thanks in Advance. Answer: Using Subversion Core library in Python you can create a class to read through different Subversion Properties associated with a commit. you can call something like: changeCollector = svn.repos.ChangeCollector(self.fs_obj,self.fsroot,self.pool); for path, change in changeCollector.changes.items(): # this is the property that i want change.text_changed
python listing and counting values Question: In the sample data given below (stored in a file), I need to find distinct 'ids' in each 'item' category in the fastest way possible. I can do this by going through each line and then finding all item sets and then count, but I am looking for a faster method such as 'Counter' or 'itemgetter'. "infile.txt" id item 444 Anemia 444 liver 444 Anemia 444 Anemia 222 liver 222 pancreas 222 liver 222 Anemia 444 pancreas 444 pancreas 444 Anemia 001 Iiver 001 pancreas 111 pancreas 111 liver 111 liver 111 pancreas 555 pancreas 555 liver 555 pancreas 555 liver 555 pancreas 555 liver I need the output something like the following item count ids pancreas 5 001, 111, 222, 444, 555 liver 5 111,222,444,555,001 Anemia 2 222,444 Answer: I'd use a defaultdict with a `set` from collections import defaultdict d = defaultdict(set) with open(datafile) as f: for line in f: my_id,item = line.split() d[item].add(my_id) for item in d: print item,len(d[item]),sorted(d[item])
Python web scraping pauses Question: I have the following code: #!/usr/bin/env python from mechanize import Browser from BeautifulSoup import BeautifulSoup mech = Browser() mech.set_handle_robots(False) url = "http://storage.googleapis.com/patents/retro/2011/ad20111231-02.zip" page = mech.open(url) html = page.read() soup = BeautifulSoup(html) print soup.prettify() really simple web scraper trying to download a .zip file from a web page. When I run this code, and bearing in mind this file is 4kb, the program just does not finish, as if it is in an infinite while loop. what I have done here? Answer: Try putting `print html` after you do your `page.read()`. You may not be getting what you think you are, it sounds like you're receiving an error page rather than the file itself. I'm not sure if you're even handling the file correctly, you might find a better approach here: [Download all the links(related documents) on a webpage using Python](http://stackoverflow.com/questions/5974595/download-all-the- linksrelated-documents-on-a-webpage-using-python). The zip file isn't 4KB, btw, it's ~87MB and contains a _784MB_ XML file, which you should be able to confirm by hitting that URL in a browser and downloading it. It may not be an infinite loop that's the problem, it's just taking a long time to load. You're also trying to pass the data in as HTML when it's zip-archived XML. If (once you actually _have_ the file) you store the response data in a `StringIO`, you'll be able to unzip it in memory ([as outlined here](http://stackoverflow.com/questions/10908877/extracting-a-zipfile-to- memory)). You will then need to [explicitly tell `BeautifulSoup`](http://www.crummy.com/software/BeautifulSoup/bs4/doc/#id11) that you're passing it XML. soup = BeautifulSoup(html, 'xml') This will require you to [install lxml](http://www.crummy.com/software/BeautifulSoup/bs4/doc/#parser- installation), but that will work out to your advantage, as it's possibly the fastest XML parser under Python. One last thing: mech.set_handle_robots(False) url = "http://storage.googleapis.com/patents/retro/2011/ad20111231-02.zip" I was under the impression Google set up their `robots.txt` to disallow scraping as much as possible. If you're still unable to even download a copy of the file, I'd recommend trying `Selenium`; it's a lot like `mechanize` but controls actual browsers, like Chrome & Firefox, so it will be a legitimate browser request.
cannot run python script file using windows prompt Question: I am trying to run a python script from the windows command prompt, but I receive the following error message: _"python: can't open file 'pacman.py': [Errno 2] No such file or directory"_ when I try the command: c:\Program Files (x86)\Python27>python pacman.py This particular python script file _pacman.py_ is located in the following folder: C:\Users\Chris\Dropbox\edX\CS188x\search So I added this folder to PYTHONPATH and confirmed that is was there using the following code: >>> import sys >>> sys.path ['', 'C:\\Program Files (x86)\\Python27\\Lib\\idlelib', 'C:\\Users\\Chris\\Dropbox\\edX\\CS188x\\search', 'C:\\windows\\syste... I also checked the permissions on this file: >>> os.access("C:\Users\Chris\Dropbox\edX\CS188x\search\pacman.py",os.W_OK) True >>> os.access("C:\Users\Chris\Dropbox\edX\CS188x\search\pacman.py",os.R_OK) True >>> os.access("C:\Users\Chris\Dropbox\edX\CS188x\search\pacman.py",os.X_OK) True So I am really not sure why I can't run this file, even though its path has been added to PYTHONPATH. Any help would be greatly appreciated. Thank you. Answer: PYTHONPATH is used by the python interpreter. It is not the same as Windows' PATH environment variable. You can't use it as a search path for passing files to the interpreter on the command line. So, you need to specify a valid path to the file. Either by using he same command as you've been trying with the difference being your current directory is the same as the location of pacman.py, or by specifying the full path to the file.
How python handles object instantiation in a ' for' loop Question: I've got a highly complex class : class C: pass And I've got this test code : for j in range(10): c = C() print c Which gives : <__main__.C instance at 0x7f7336a6cb00> <__main__.C instance at 0x7f7336a6cab8> <__main__.C instance at 0x7f7336a6cb00> <__main__.C instance at 0x7f7336a6cab8> <__main__.C instance at 0x7f7336a6cb00> <__main__.C instance at 0x7f7336a6cab8> <__main__.C instance at 0x7f7336a6cb00> <__main__.C instance at 0x7f7336a6cab8> <__main__.C instance at 0x7f7336a6cb00> <__main__.C instance at 0x7f7336a6cab8> One can easily see that Python switches on two different values. In some cases, this can be catastrophic (for example if we store the objects in some other complex object). Now, if I store the objects in a List : lst = [] for j in range(10): c = C() lst.append(c) print c I get this : <__main__.C instance at 0x7fd8f8f7eb00> <__main__.C instance at 0x7fd8f8f7eab8> <__main__.C instance at 0x7fd8f8f7eb48> <__main__.C instance at 0x7fd8f8f7eb90> <__main__.C instance at 0x7fd8f8f7ebd8> <__main__.C instance at 0x7fd8f8f7ec20> <__main__.C instance at 0x7fd8f8f7ec68> <__main__.C instance at 0x7fd8f8f7ecb0> <__main__.C instance at 0x7fd8f8f7ecf8> <__main__.C instance at 0x7fd8f8f7ed40> Which solves the case. So now, I have to ask a question... Does anyone could explain with complex words (I mean, deeply) how Python behave with the objects references ? I suppose, it is a matter of optimization (to spare memory, or prevent leaks, ...) Thank a lot. **EDIT :** Ok so, let's be more specific. I'm quite aware that python has to collect garbage sometimes... But, in my case : I had a list returned by a Cython defined class : class 'Network' that manages a 'Node's list (both Network and Node class are defined in a `Cython extension`). Each Node has a an object [then casted into (void *)] 'userdata' object. The Nodes list is populated from inside cython, while the UserData are populated inside the Python script. So in python, I had the following : ... def some_python_class_method(self): nodes = self.netBinding.GetNetwork().get_nodes() ... for item in it: a_site = PyLabSiteEvent() #l_site.append(a_site) # WARN : Required to get an instance on 'a_site' # that persits - workaround... item.SetUserData(a_site) Reusing this node list later on in the same python class using the same cython getter : def some_other_python_class_method(self, node): s_data = node.GetUserData() ... So, it seems that with the storage made in the node list's UserDatas, my python script was completely blind and was freeing/reusing memory. It worked by referencing a second time (but apparently a first one for python side), using an additional list (here : 'l_site'). This is why I had to know a bit more about Python itself, but it seems that the way I implemented the communication between Python and `Cython` is responsible for the issues a had to face. Answer: There is no need to be "complex" here: In the first example, you keep no other reference to the object referenced by the name "c" - when running the code in the line "c = C()" on subsequent iterations of the loop, the one reference previously held in "c" is lost. Since standard Python uses reference counting to keep track of when it should delete objects from memory, as at this moment the reference counting for the object of the previous loop interation reaches 0, it is destroyed, and its memory is made available for other objects. Why do you have 2 changing values? Because at the moment the object in the new iteration is created - i.e. when Python executes the expression to the right side of the `=` in `c = C()`, the object of the precvious iteration still exists, referenced by the name `c` \- so the new object is constructed at another memory locaton. Python then proceeds to the assignment of the new object to `c` at which point the previous object is destroyed as described above - which means that on the next (3rd) iteration, that memory will be available for a new instance of `C`. On the second example, the newly created objects never loose reference, and therefore their memory is not freed at all - new objects always take up a new memory location. **Most important of all:** The purpose of using a high level language such as Python or others, is _not_ having to worry about memory allocation. The language takes care of that to you. In this case, the CPython (standard) implementation does just the right thing, as you noticed. Other implementations such as Pypy or Jython can have completely different behavior in regards to the "memory location" of each instances in the above examples, but all conforming implementatons (including these 3) will behave exactly the same from the "point of view" of the Python program: (1) It does have access to the instances it keeps a reference to, (2) the data of these instances is not corrupted or mangled in anyway.
Loading Django apps for development Question: So, I've got this set-up in which I installed a django project (the directory containing the settings.py and manage.py) in the site-packages directory of my python installation. I've done this to use apps from other packages, which works nicely. I noticed however, that when I'm developing, the development server (manage.py runserver) loads files from the site-package directory. Example: There is a file, views.py, that loads models from models.py using: from models import Project, Test Because of a small error within the production code I tried to fix, still pops up within the development server, and the django error page (such a nice feature) shows the old code from the file that's installed in site-packages. So, I put in this line: import models print models.__file__ and the result of that is exactly the file I want, from my development directory. The next line, from models import Project, Test loads models from the site-package directory, which is totally not what I want. I guess I've polluted the namespace, I'm guessing that the from-import imports already loaded imports from memory, but that the normal import-line imports a module that isn't in memory yet. This apparently leads to the strange effect of being successfully able to change views.py and see the changes in the development server. Anybody's got any idea how to fix this? System info: * Python2.7 * Django1.3 * Debian Answer: This is what [virtualenv](http://www.virtualenv.org/en/latest/index.html) is for. It creates isolated development environments, and is indispensable for working on multiple projects/versions at once.
Django mod_python logging issues Question: I'm trying to debug my view file in Django. I'm using Django 1.3 with mod_python on server. How can I see some out from my view file. I already try to use standart logging configuration LOGGING = { 'version': 1, 'disable_existing_loggers': True, 'formatters': { 'standard': { 'format' : "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s", 'datefmt' : "%d/%b/%Y %H:%M:%S" }, }, 'handlers': { 'null': { 'level':'DEBUG', 'class':'django.utils.log.NullHandler', }, 'logfile': { 'level':'DEBUG', 'class':'logging.handlers.RotatingFileHandler', 'filename': SITE_ROOT + "/logfile", 'maxBytes': 50000, 'backupCount': 2, 'formatter': 'standard', }, 'console':{ 'level':'INFO', 'class':'logging.StreamHandler', 'formatter': 'standard' }, }, 'loggers': { 'django': { 'handlers':['console'], 'propagate': True, 'level':'WARN', }, 'django.db.backends': { 'handlers': ['console'], 'level': 'DEBUG', 'propagate': False, }, 'customer_portal': { 'handlers': ['console', 'logfile'], 'level': 'DEBUG', }, } } I'm write in my view file: import logging log = logging.getLogger('customer_portal') log.debug("Some data") But file with log is not created. Thanks for help. Answer: I cut/paste your code and it is working for me. Perhaps there are incorrect permissions on the directory and/or file you are trying to write to?
Why does this extremely simple wxPython AUI application crash on launch? Question: I'm making a Regular Expression testing tool for work. I would like it to be a simple AUI application, but after transferring what seems to me to be the **core** of an AUI application from the demo to my code, it crashes on startup. I can only see the wxPython log window for a fraction of a second before it disappears, and the code produces no errors in the console. Here is the troublesome frame. If I comment out all the `_mgr` lines, the application runs just fine. class RegexTesterFrame(wx.Frame): def __init__(self): wx.Frame.__init__( self, None, -1, 'Regex tester', (100, 100), (400, 400), wx.DEFAULT_FRAME_STYLE ) self.initialize_components() self.CreateStatusBar() def initialize_components(self): self._mgr = wx.aui.AuiManager() self._mgr.SetManagedWindow(self) self._perspectives = [] self._mgr.AddPane( wx.CheckBox(self, -1, 'test'), wx.aui.AuiPaneInfo().Name('Test pane').Caption('Test caption').Top() ) self._mgr.Update() self.Bind(wx.EVT_CLOSE, self.on_close) def on_close(self, event): self._mgr.UnInit() del self._mgr self.Destroy() Here is the full code (~100 lines): <http://pastebin.com/xZS2g1fq> And here is the demo I'm working from (LARGE): <http://pastebin.com/G26BMYZx> I'm curious about two things - why does the application crash, and why do I get no error output when wxPython applications crash in general. Answer: I've struggled with this since yesterday, but as usual, the minute I ask the question on StackOverflow I figure it out. First of all I got the application to output error information in a message box instead of stderr: def main(): try: app = RegexTesterApp(True) app.MainLoop() except: import traceback xc = traceback.format_exception(*sys.exc_info()) wx.MessageBox(''.join(xc)) Then the error revealed that `wx.aui` was a module that I hadn't imported. Importing it fixed the crash.
Build an Eclipse workspace with TeamCity Question: I am in the process of converting our existing custom continuous build system to use TeamCity. This appears to work well for most of our build scenarios but one. We have a hardware project that is set up to build using Eclipse configured with a specific set of tool chains. Developers run the IDE, and for lack of an Eclipse build runner, TeamCity builds the project from the commandline runner using python scripts. The TeamCity build process is as follows: * Delete the contents of the Eclipse workspace. * import all the Eclipse projects into the workspace. * build the workspace. The problems with this approach are as follows: * There is no build runner for Eclipse. The scripts work, but there is overhead in developing and maintaining the scripts. This is the very thing we are trying to get away from. * There is no TeamCity parsing of the output (gcc and eclipse). I have to redirect the eclipse output to file, and when the Eclipse process finishes, parse the file for errors, warnings, progress status, etc., in order to inject the appropriate TeamCity service message to stdout. Again this kind of overhead is the very thing we are trying to get away from. Given no Eclipse build runner just days away from release, is there a better mechanism for loading and building an Eclipse workspace with TeamCity? Given the commandline runner script solution, is there a better machnism for capturing and displaying errors, warnings, etc.? Answer: This may not be the best approach for you at this particular time in your release cycle, given that you are so close to your release deadline, but I would use Maven for the build and use the M2E plugin to provide Maven integration inside of Eclipse. While using Maven as a build tool is usually not overly complex, it is sometimes not trivial to convert an existing project to use it. I would suggest that you start off your next release cycle by enabling Maven as your build tool - TeamCity fully supports the Maven build runner.
Python telnetlib read's only print "bs" Question: I'm trying to do some telnet automation with Python (only _pure_ Python). When I try to print some of my read's in the function `read_until`, all I see are a series of `bs`'s -- that's `bs`, as in the `backspace` character, not something else. :-) Does anyone know if there's some kind of setting I can change in the on `tn`, my instance of the `Telnet` class, or correct this? Or is this something that my host is spewing back? I've done some Googling on the `telnetlib` library, and I haven't seen many examples where folks have output from the `Telnet.read_until` function. This is a cut-down version of my code: import getpass import sys import telnetlib HOST = "blahblah" def writeline(data): local.write(data + '\n') def read_until(tn, cue, timeout=2): print 'Before read until "%s"' % cue print tn.read_until(cue, timeout) print 'After read until "%s"' % cue def tn_write(tn, text, msg=''): if not msg: msg = text print 'Before writing "%s"' % msg tn.write(text) print 'After writing "%s"' % msg user = 'me' password = getpass.getpass() tn = telnetlib.Telnet(HOST) read_until(tn, "Username: ") tn_write(tn, user + "\n", user) if password: read_until(tn, "Password: ") tn_write(tn, password + "\n", 'password') read_until(tn, "continue") tn_write(tn, "\n", '<Enter>') #tn.write("vt100\n") tn_write(tn, 'main_menu' + '\n', 'start menu') read_until(tn, 'Selection: ') I don't think it matters, but I'm using Python 2.7 on Windows. Answer: I figured out the problem here. I tried writing my commands with both `\n` and `\r` but not both combined. When I changed to `'\r\n'`, I got the expected output.
Python read text files in numpy array when empty or single line Question: I am reading from text files with the code below: import numpy as np my_data = np.genfromtxt(resultsDirectory+'/Points.txt', delimiter=' ') PointX = my_data[:,5] PointY = my_data[:,11] My input files are typically like this - ParamA : 0 ParamB : 7 ParamC : 0 ParamD : 1 Result : FAIL Time : 0 Epsilon : 0.5 ParamA : 0 ParamB : 11 ParamC : 0 ParamD : 1 Result : FAIL Time : 2 Epsilon : 0.5 ParamA : 0 ParamB : 7 ParamC : 0 ParamD : 3 Result : FAIL Time : 2 Epsilon : 0.25 ParamA : 0 ParamB : 13 ParamC : 0 ParamD : 1 Result : FAIL Time : 7 Epsilon : 0.25 ParamA : 0 ParamB : 7 ParamC : 0 ParamD : 4 Result : FAIL Time : 8 Epsilon : 0.125 ParamA : 0 ParamB : 8 ParamC : 0 ParamD : 2 Result : FAIL Time : 1 Epsilon : 0.125 ParamA : 0 ParamB : 8 ParamC : 0 ParamD : 3 Result : FAIL Time : 3 Epsilon : 0.125 ParamA : 0 ParamB : 8 ParamC : 0 ParamD : 4 Result : FAIL Time : 6 Epsilon : 0.125 ParamA : 0 ParamB : 9 ParamC : 0 ParamD : 2 Result : FAIL Time : 6 Epsilon : 0.125 ParamA : 0 ParamB : 10 ParamC : 0 ParamD : 2 Result : FAIL Time : 5 Epsilon : 0.125 ParamA : 0 ParamB : 14 ParamC : 0 ParamD : 1 Result : FAIL Time : 6 Epsilon : 0.125 When I extract PointX from this I get PointX = [7 11 7 13 7 8 8 8 9 10 14] PointY = [1 1 3 1 4 2 3 4 2 2 1] Now, sometimes my text files contain only a single line or are even empty. For example, if the text file has only one line, the my_data array is like this - [ nan nan 0. nan nan 7. nan nan 0. nan nan 1. nan nan nan nan nan 0. nan nan 0.5] In this case, `my_data.shape` returns `(21,)`. However reading the array `PointX` or `PointY` gives me an error as `IndexError: invalid index`. I wanted `PointX=[7]` and `PointY=[1]`. Or if the text file is empty, it should be `PointX=[]` and `PointY=[]`. How exactly should I solve this problem? Also I need my `PointX` and `PointY` to be an array in order not to break the code which is dependent on it. Thank you. Answer: Unfortunately, `genfromtxt` returns a 1D array if given a file with only one line, and returns a 2D array if given more than one line. You could handle the discrepancy by reshaping: import numpy as np my_data = np.genfromtxt('data', delimiter=' ') if my_data.ndim == 1: my_data = my_data.reshape(1, -1) PointX = my_data[:,5] PointY = my_data[:,11] print(PointX) print(PointY) yields [ 7.] [ 1.]
Integer division: is a//b == int(a/b) true for all integers a,b? Question: I know that integer division will always return the same answer as truncation of a floating point result if the numbers are both positive. Is it true if one or both of them are negative? I was just curious to know if there was an integer division expression that would return the same results in Python 2 and Python 3 (and yes, I know about `from __future__ import division`). P.S. Let's ignore floating point overflow for the moment. Answer: It is not true in Python 3, and you can test it for yourself: >>> int(-1/3) == -1//3 False Integer division and modulo of `a` and `b` giving `q` (quotient) and `r` (remainder) respectively will always return numbers that satisfy `b*q + r == a` and `(a*b)>0 == q>0` (i.e. `a*b` and `q` have the same sign) and `abs(r) < abs(q)`. The expression `int(q)` simply always rounds towards 0 if `q` is a floating point number. It will always be true for Python 2 unless you do `from __future__ import division`, but that's because `a/b == a//b` if `a` and `b` are integers in Python 2.
Finding the square root using Newton's method (errors!) Question: I'm working to finish a math problem that approximates the square root of a number using Newton's guess and check method in Python. The user is supposed to enter a number, an initial guess for the number, and how many times they want to check their answer before returning. To make things easier and get to know Python (I've only just started learning the language a couple of months ago) I broke it up into a number of smaller functions; the problem now, though, is that I'm having trouble calling each function and passing the numbers through. Here is my code, with comments to help (each function is in order of use): # This program approximates the square root of a number (entered by the user) # using Newton's method (guess-and-check). I started with one long function, # but after research, have attempted to apply smaller functions on top of each # other. # * NEED TO: call functions properly; implement a counting loop so the # goodGuess function can only be accessed the certain # of times the user # specifies. Even if the - .001 range isn't reached, it should return. # sqrtNewt is basically the main, which initiates user input. def sqrtNewt(): # c equals a running count initiated at the beginning of the program, to # use variable count. print("This will approximate the square root of a number, using a guess-and-check process.") x = eval(input("Please type in a positive number to find the square root of: ")) guess = eval(input("Please type in a guess for the square root of the number you entered: ")) count = eval(input("Please enter how many times would you like this program to improve your initial guess: ")) avg = average(guess, x) g, avg = improveG(guess, x) final = goodGuess(avg, x) guess = square_root(guess, x, count) compare(guess, x) # Average function is called; is the first step that gives an initial average, # which implements through smaller layers of simple functions stacked on each # other. def average(guess, x) : return ((guess + x) / 2) # An improvement function which builds upon the original average function. def improveG(guess, x) : return average(guess, x/guess) # A function which determines if the difference between guess X guess minus the # original number results in an absolute vale less than 0.001. Not taking # absolute values (like if guess times guess was greater than x) might result # in errors from math import * def goodGuess(avg, x) : num = abs(avg * avg - x) return (num < 0.001) # A function that, if not satisfied, continues to "tap" other functions for # better guess outputs. i.e. as long as the guess is not good enough, keep # improving the guess. def square_root(guess, x, count) : while(not goodGuess(avg, x)): c = 0 c = c + 1 if (c < count): guess = improveG(guess, x) elif (c == count): return guess else : pass # Function is used to check the difference between guess and the sqrt method # applied to the user input. import math def compare(guess, x): diff = math.sqrt(x) - guess print("The following is the difference between the approximation") print("and the Math.sqrt method, not rounded:", diff) sqrtNewt() Currently, I get this error: `g, avg = improveG(guess, x) TypeError: 'float' object is not iterable.` The final function uses the final iteration of the guess to subtract from the math square root method, and returns the overall difference. Am I even doing this right? Working code would be appreciated, with suggestions, if you can provide it. Again, I'm a newbie, so I apologize for misconceptions or blind obvious errors. Answer: Implementation of the newton method: It should be fairly easy to add little tweaks to it when needed. Try, and tell us when you get stuck. from math import * def average(a, b): return (a + b) / 2.0 def improve(guess, x): return average(guess, x/guess) def good_enough(guess, x): d = abs(guess*guess - x) return (d < 0.001) def square_root(guess, x): while(not good_enough(guess, x)): guess = improve(guess, x) return guess def my_sqrt(x): r = square_root(1, x) return r >>> my_sqrt(16) 4.0000006366929393 NOTE: you will find enough exaples on how to use raw input here at SO or googling, BUT, if you are counting loops, the `c=0` has to be outside the loop, or you will be stuck in an infinite loop. Quiqk and dirty, lots of ways to improve: from math import * def average(a, b): return (a + b) / 2.0 def improve(guess, x): return average(guess, x/guess) def square_root(guess, x, c): guesscount=0 while guesscount < c : guesscount+=1 guess = improve(guess, x) return guess def my_sqrt(x,c): r = square_root(1, x, c) return r number=int(raw_input('Enter a positive number')) i_guess=int(raw_input('Enter an initial guess')) times=int(raw_input('How many times would you like this program to improve your initial guess:')) answer=my_sqrt(number,times) print 'sqrt is approximately ' + str(answer) print 'difference between your guess and sqrt is ' + str(abs(i_guess-answer))