text
stringlengths
185
26.5k
<s>[INST] Accessing dict keys like an attribute in Python? I find it more conveniant to access dict keys as obj.foo instead of obj['foo'], so I wrote this snippet: class AttributeDict(dict): def __getattr__(self, attr): return self[attr] def __setattr__(self, attr, value): self[attr] = value Ho...
<s>[INST] Django: "projects" vs "apps" I have a fairly complex "product" I'm getting ready to build using Django. I'm going to avoid using the terms "project" and "application" in this context, because I'm not clear on their specific meaning in Django. Projects can have many apps. Apps can be shared among many projects...
<s>[INST] Python exit commands - why so many and when should each be used? It seems that python supports many different commands to stop script execution.The choices I've found are: quit(), exit(), sys.exit(), os._exit() Have I missed any? What's the difference between them? When would you use each? [/INST] Let me g...
<s>[INST] Get the name of current script with Python I'm trying to get the name of the Python script that is currently running. For example, I have a script called foo.py and I would like to do something like this inside it: print Scriptname and get: foo.py. [/INST] Use __file__. If you want to omit the directory pa...
<s>[INST] Sort a list of tuples by 2nd item (integer value) I have a list of tuples that looks something like this: [('abc', 121),('abc', 231),('abc', 148), ('abc',221)] I want to sort this list in ascending order by the integer value inside the tuples. Is it possible? [/INST] Try using the key keyword with sorted()....
<s>[INST] Print current call stack from a method in Python code In Python, how can I print the current call stack from within a method (for debugging purposes). [/INST] Here's an example of getting the stack via the traceback module, and printing it: import traceback def f(): g() def g(): for line in traceba...
<s>[INST] How can I tell PyCharm what type a parameter is expected to be? When it comes to constructors, and assignments, and method calls, the PyCharm IDE is pretty good at analyzing my source code and figuring out what type each variable should be. I like it when it's right, because it gives me good code-completion a...
<s>[INST] How to download image using requests I'm trying to download and save an image from the web using python's requests module. Here is the (working) code I used: img = urllib2.urlopen(settings.STATICMAP_URL.format(**data)) with open(path, 'w') as f: f.write(img.read()) Here is the new (non-working) code usin...
<s>[INST] How to initialize a two-dimensional array in Python? I'm beginning python and I'm trying to use a two-dimensional list, that I initially fill up with the same variable in every place. I came up with this: def initialize_twodlist(foo): twod_list = [] new = [] for i in range (0, 10): for j i...
<s>[INST] Else clause on Python while statement I've noticed the following code is legal in Python. My question is why? Is there a specific reason? n = 5 while n != 0: print n n -= 1 else: print "what the..." [/INST] The else clause is only executed when your while condition becomes false. If you break o...
<s>[INST] How do I get the parent directory in Python? Could someone tell me how to get the parent directory of a path in Python in a cross platform way. E.g. C:\Program Files ---> C:\ and C:\ ---> C:\ If the directory doesn't have a parent directory, it returns the directory itself. The question might seem simple bu...
<s>[INST] What's the bad magic number error? What's the "Bad magic number" ImportError in python, and how do I fix it? The only thing I can find online suggests this is caused by compiling a .py -> .pyc file and then trying to use it with the wrong version of python. In my case, however, the file seems to import fine s...
<s>[INST] How to check whether two lists are circularly identical in Python For instance, I have lists: a[0] = [1, 1, 1, 0, 0] a[1] = [1, 1, 0, 0, 1] a[2] = [0, 1, 1, 1, 0] # and so on They seem to be different, but if it is supposed that the start and the end are connected, then they are circularly identical. The pro...
<s>[INST] Pelican 3.3 pelican-quickstart error "ValueError: unknown locale: UTF-8" When I was trying to use pelican3.3, I typed the commend "pelican-quickstart", some errors showed up. These are the errors: (PelicanEnv)59-127-113-90:myblog Richo$ pelican-quickstart Traceback (most recent call last): File "/Users/Rich...
<s>[INST] How to get week number in Python? How to find out what week number is this year on June 16th (wk24) with Python? [/INST] datetime.date has a isocalendar() method, which returns a tuple containing the calendar week: >>> datetime.date(2010, 6, 16).isocalendar()[1] 24 datetime.date.isocalendar() is an instan...
<s>[INST] Programmatically saving image to Django ImageField Ok, I've tried about near everything and I cannot get this to work. I have a Django model with an ImageField on it I have code that downloads an image via HTTP (tested and works) The image is saved directly into the 'upload_to' folder (the upload_to being th...
<s>[INST] Can a line of Python code know its indentation nesting level? From something like this: print(get_indentation_level()) print(get_indentation_level()) print(get_indentation_level()) I would like to get something like this: 1 2 3 Can the code read itself in this way? All I want is the output fro...
<s>[INST] How do you log server errors on django sites So, when playing with the development I can just set settings.DEBUG to True and if an error occures I can see it nicely formatted, with good stack trace and request information. But on kind of production site I'd rather use DEBUG=False and show visitors some standa...
<s>[INST] Python: Check if a string represents an int, Without using Try/Except? Is there any way to tell whether a string represents an integer (e.g., '3', '-17' but not '3.14' or 'asfasfas') Without using a try/except mechanism? is_int('3.14') = False is_int('-7') = True [/INST] with positive integers you could u...
<s>[INST] Using javadoc for Python documentation I am currently beginning with Python and I have a strong PHP background and in PHP I have took the habit of using javadoc as a documentation template. I was wondering if javadoc has its place as docstring documentation in Python. Is something like this too elaborate to f...
<s>[INST] 'import module' or 'from module import' I've tried to find a comprehensive guide on whether it is best to use import module or from module import. I've just started with Python, with the intention for developing web applications with Django and I'm trying to start off with best practices in mind. Basically, I...
<s>[INST] Is it possible to use pip to install a package from a private github repository? As the title suggests I am trying to install a python package from a private github repo. For a public repository I can issue the following command which works fine: pip install git+git://github.com/django/django.git However if ...
<s>[INST] How to create a zip archive of a directory How can I create a zip archive of a directory structure in Python? [/INST] As others have pointed out, you should use zipfile. The documentation tells you what functions are available, but doesn't really explain how you can use them to zip an entire directory. I th...
<s>[INST] Hiding axis text in matplotlib plots I'm trying to plot a figure without tickmarks or numbers on either of the axes (I use axes in the traditional sense, not the matplotlib nomenclature!). An issue I have come across is where matplotlib adjusts the x(y)ticklabels by subtracting a value N, then adds N at the e...
<s>[INST] How do I split a multi-line string into multiple lines? I have a multi-line string literal that I want to do an operation on each line, like so: inputString = """Line 1 Line 2 Line 3""" I want to do something like the following: for line in inputString: doStuff() [/INST] inputString.splitlines() Will ...
<s>[INST] How do I get a Cron like scheduler in Python? I'm looking for a library in Python which will provide at and cron like functionality. I'd quite like have a pure Python solution, rather than relying on tools installed on the box; this way I run on machines with no cron. For those unfamiliar with cron: you can s...
<s>[INST] Django set default form values I have a Model as follows class TankJournal(models.Model): user = models.ForeignKey(User) tank = models.ForeignKey(TankProfile) ts = models.IntegerField(max_length=15) title = models.CharField(max_length=50) body = models.TextField() I have a modelform as follows for ...
<s>[INST] Flask - configure dev server to be visible across the network I'm not sure if this is Flask specific, but when I run an app in dev mode (http://localhost:5000), I cannot access it from other machines on the network (with http://[dev-host-ip]:5000). With Rails in dev mode, for example, it works fine. I couldn'...
<s>[INST] How can I get the whole request POST body in Python with Flask? I want to be able to get the whole POST body of the request as a string or file handle that I can read but I'm unable to find a way (I'm new to Flask and Python for web at all). This is what I got: from flask import Flask app = Flask(__name__) @...
<s>[INST] Postgres: INSERT if does not exist already I'm using Python to write to a postgres database: sql_string = "INSERT INTO hundred (name,name_slug,status) VALUES (" sql_string += hundred + ", '" + hundred_slug + "', " + status + ");" cursor.execute(sql_string) But because some of my rows are identical, I get the...
<s>[INST] Django auto_now and auto_now_add For Django 1.1. I have this in my models.py: class User(models.Model): created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) When updating a row I get: [Sun Nov 15 02:18:12 2009] [error] /home/ptarjan/projects/twitter-meme/dj...
<s>[INST] Calculating arithmetic mean (average) in Python Is there a built-in or standard library method in Python to calculate the arithmetic mean (average) of a list of numbers? [/INST] I am not aware of anything in the standard library. However, you could use something like: def mean(numbers): return float(sum(...
<s>[INST] Python variable scope error I've been programming for many years, and recently started learning Python. The following code works as expected in both python 2.5 and 3.0 (on OS X if that matters): a, b, c = (1, 2, 3) print(a, b, c) def test(): print(a) print(b) print(c) # (A) #c+=1 # ...
<s>[INST] What is the best way to call a Python script from another Python script? I have a script named test1.py which is not in a module. It just has code that should execute when the script itself is run. There are no functions, classes, methods, etc. I have another script which runs as a service. I want to call tes...
<s>[INST] Easiest way to rename a model using Django/South? I've been hunting for an answer to this on South's site, Google, and SO, but couldn't find a simple way to do this. I want to rename a Django model using South. Say you have the following: class Foo(models.Model): name = models.CharField() class FooTwo(m...
<s>[INST] In Python, how do I iterate over a dictionary in sorted order? There's an existing function that ends in: return dict.iteritems() that returns an unsorted iterator for a given dictionary. I would like to return an iterator that goes through the items in sorted order. How do I do that? [/INST] Haven't tested...
<s>[INST] Is there a way to use PhantomJS in Python? I want to use PhantomJS in Python. I googled this problem but couldn't find proper solutions. I find os.popen() may be a good choice. But I couldn't pass some arguments to it. Using subprocess.Popen() may be a proper solution for now. I want to know whether there's ...
<s>[INST] Convert a number range to another range, maintaining ratio I'm trying to convert one range of numbers to another, maintaining ratio. Maths is not my strong point. I have an image file where point values may range from -16000.00 to 16000.00 though the typical range may be much less. What I want to do is compre...
<s>[INST] How to start a background process in Python? I'm trying to port a shell script to the much more readable python version. The original shell script starts several processes (utilities, monitors, etc.) in the background with "&". How can I achieve the same effect in python? I'd like these processes not to die w...
<s>[INST] Why doesn't os.path.join() work in this case? The below code will not join, when debugged the command does not store the whole path but just the last entry. os.path.join('/home/build/test/sandboxes/', todaystr, '/new_sandbox/') When I test this it only stores the /new_sandbox/ part of the code. [/INST] The ...
<s>[INST] Python setup.py develop vs install Two options in setup.py develop and install are confusing me. According to this site, using develop creates a special link to site-packages directory. People have suggested that I use python setup.py install for a fresh installation and python setup.py develop after any chan...
<s>[INST] Is there a "not equal" operator in Python? How would you say does not equal? Like if hi == hi: print "hi" elif hi (does not equal) bye: print "no hi" Is there a replacement for == that means "not equal"? [/INST] Use != (preferred) or <> (deprecated). See comparison operators. For comparing object i...
<s>[INST] How to perform OR condition in django queryset? I want to write a Django query equivalent to this SQL query: SELECT * from user where income >= 5000 or income is NULL. How to construct the Djagno queryset filter? User.objects.filter(income__gte=5000, income=0) This doesn't work, because it ANDs the filters....
<s>[INST] Sort a list by multiple attributes? I have a list of lists: [[12, 'tall', 'blue', 1], [2, 'short', 'red', 9], [4, 'tall', 'blue', 13]] If I wanted to sort by one element, say the tall/short element, I could do it via s = sorted(s, key = itemgetter(1)). If I wanted to sort by both tall/short and colour, I cou...
<s>[INST] Is Python strongly typed? I've come across links that say Python is a strongly typed language. However, I thought in strongly typed languages you couldn't do this : bob = 1 bob = "bob" I thought a strongly typed language didn't accept type-changing at run-time. Maybe I've got a wrong (or too simplist) defini...
<s>[INST] Python string.join(list) on object array rather than string array In Python, I can do: >>> list = ['a', 'b', 'c'] >>> ', '.join(list) 'a, b, c' Is there any easy way to do the same when I have a list of objects? >>> class Obj: ... def __str__(self): ... return 'name' ... >>> list = [Obj(), Obj(),...
<s>[INST] Python multiprocessing pool.map for multiple arguments In the Python multiprocessing library, is there a variant of pool.map which support multiple arguments? text = "test" def harvester(text, case): X = case[0] return text+ str(X) if __name__ == '__main__': pool = multiprocessing.Pool(processes=...
<s>[INST] Why return NotImplemented instead of raising NotImplementedError Python has a singleton called NotImplemented. Why would someone want to ever return NotImplemented instead of raising the NotImplementedError exception? Won't it just make it harder to find bugs, such as code that executes invalid methods? [/...
<s>[INST] How to download large file in python with requests.py? Requests is a really nice library. I'd like to use it for download big files (>1GB). The problem is it's not possible to keep whole file in memory I need to read it in chunks. And this is a problem with the following code import requests def DownloadFile...
<s>[INST] Iterate a list with indexes in Python I could swear I've seen the function (or method) that takes a list, like this [3, 7, 19] and makes it into iterable list of tuples, like so: [(0,3), (1,7), (2,19)] to use it instead of: for i in range(len(name_of_list)): name_of_list[i] = something but I can't rememb...
<s>[INST] How to hide output of subprocess in Python 2.7 I'm using eSpeak on Ubuntu and have a Python 2.7 script that prints and speaks a message: import subprocess text = 'Hello World.' print text subprocess.call(['espeak', text]) eSpeak produces the desired sounds, but clutters the shell with some errors (ALSA lib.....
<s>[INST] Compact way of writing (a + b == c or a + c == b or b + c == a) Is there a more compact or pythonic way to write the boolean expression a + b == c or a + c == b or b + c == a I came up with a + b + c in (2*a, 2*b, 2*c) but that is a little strange. [/INST] If we look at the Zen of Python, emphasis mine: ...
<s>[INST] Python Infinity - Any caveats? So Python has positive and negative infinity: float("inf"), float("-inf") This just seems like the type of feature that has to have some caveat. Is there anything I should be aware of? [/INST] You can still get not-a-number (NaN) values from simple arithmetic involving inf: >...
<s>[INST] find nearest value in numpy array is there a numpy-thonic way, e.g. function, to find the 'nearest value' in an array? example: np.find_nearest( array, value ) [/INST] import numpy as np def find_nearest(array,value): idx = (np.abs(array-value)).argmin() return array[idx] array = np.random.random(...
<s>[INST] Case insensitive Python regular expression without re.compile In Python, I can compile a regular expression to be case-insensitive using re.compile: >>> s = 'TeSt' >>> casesensitive = re.compile('test') >>> ignorecase = re.compile('test', re.IGNORECASE) >>> >>> print casesensitive.match(s) None >>> print ign...
<s>[INST] Saving utf-8 texts in json.dumps as UTF8, not as \u escape sequence sample code: >>> import json >>> json_string = json.dumps("ברי צקלה") >>> print json_string "\u05d1\u05e8\u05d9 \u05e6\u05e7\u05dc\u05d4" The problem: it's not human readable. My (smart) users want to verify or even edit text files wi...
<s>[INST] How to delete items from a dictionary while iterating over it? Is it legitimate to delete items from a dictionary in Python while iterating over it? For example: for k, v in mydict.iteritems(): if k == val: del mydict[k] The idea is to remove elements that don't meet a certain condition from the dict...
<s>[INST] How to execute a file within the python interpreter? I'm trying to execute a file with python commands from within the interpreter. EDIT: I'm trying to use variables and settings from that file, not to invoke a separate process. [/INST] Several ways. From the shell python someFile.py From inside IDLE, hit ...
<s>[INST] Python dictionary: are keys() and values() always the same order? It looks like the lists returned by keys() and values() methods of a dictionary are always a 1-to-1 mapping (assuming the dictionary is not altered between calling the 2 methods). For example: >>> d = {'one':1, 'two': 2, 'three': 3} >>> k, v = ...
<s>[INST] Python: split a list based on a condition? What's the best way, both aesthetically and from a performance perspective, to split a list of items into multiple lists based on a conditional? The equivalent of: good = [x for x in mylist if x in goodvals] bad = [x for x in mylist if x not in goodvals] is there a...
<s>[INST] How to use a different version of python during NPM install? Salam (means Hello) :) I have terminal access to a VPS running centos 5.9 and default python 2.4.3 installed. I also installed python 2.7.3 via these commands: (I used make altinstall instead of make install) wget http://www.python.org/ftp/python/2....
<s>[INST] Getting method parameter names in python Given the python function: def aMethod(arg1, arg2): pass How can I extract the number and names of the arguments. Ie. given that I have a reference to func, I want the func.[something] to return ("arg1", "arg2") The usage scenario for this is that I have a decorat...
<s>[INST] python decorators with parameters I have a problem with the transfer of variable 'insurance_mode' by the decorator. I would do it by the following decorator statement: @execute_complete_reservation(True) def test_booking_gta_object(self): self.test_select_gta_object() but unfortunately, this statement...
<s>[INST] Rename a dictionary key Is there a way to rename a dictionary key, without reassigning its value to a new name and removing the old name key; and without iterating through dict key/value? In case of OrderedDict, do the same, while keeping that key's position. [/INST] For a regular dict, you can use: mydict[n...
<s>[INST] Python + Django page redirect How do I accomplish a simple redirect (e.g. cflocation in ColdFusion, or header(location:http://) in Django)? [/INST] It's simple: from django.http import HttpResponseRedirect def myview(request): ... return HttpResponseRedirect("/path/") More info in the official Djan...
<s>[INST] How to send email attachments with Python I am having problems understanding how to email an attachment using Python. I have successfully emailed simple messages with the smtplib. Could someone please explain how to send an attachment in an email. I know there are other posts online but as a Python beginner I...
<s>[INST] Python creating a dictionary of lists I want to create a dictionary whose values are lists. For example: { 1: ['1'], 2: ['1','2'], 3: ['2'] } If I do: d = dict() a = ['1', '2'] for i in a: for j in range(int(i), int(i) + 2): d[j].append(i) I get a KeyError, because d[...] isn't a list. ...
<s>[INST] Changing the "tick frequency" on x or y axis in matplotlib? I am trying to fix how python plots my data. Say x = [0,5,9,10,15] and y = [0,1,2,3,4] Then I would do: matplotlib.pyplot.plot(x,y) matplotlib.pyplot.show() and the x axis' ticks are plotted in intervals of 5. Is there a way to make it show inte...
<s>[INST] Get the cartesian product of a series of lists in Python How can I get the Cartesian product (every possible combination of values) from a group of lists? Input: somelists = [ [1, 2, 3], ['a', 'b'], [4, 5] ] Desired output: [(1, 'a', 4), (1, 'a', 5), (1, 'b', 4), (1, 'b', 5), (2, 'a', 4), (2, 'a', ...
<s>[INST] Why dict.get(key) instead of dict[key]? Today, I came across the dict method get which, given a key in the dictionary, returns the associated value. For what purpose is this function useful? If I wanted to find a value associated with a key in a dictionary, I can just do dict[key], and it returns the same thi...
<s>[INST] How do I override __getattr__ in Python without breaking the default behavior? I want to override the __getattr__ method on a class to do something fancy but I don't want to break the default behavior. What's the correct way to do this? [/INST] Overriding __getattr__ should be fine -- __getattr__ is only cal...
<s>[INST] Configuring so that pip install can work from github We'd like to use pip with github to install private packages to our production servers. This question concerns what needs to be in the github repo in order for the install to be successful. Assuming the following command line (which authenticates just fine...
<s>[INST] I can't install python-ldap When I run the following command: sudo pip install python-ldap I get this error: In file included from Modules/LDAPObject.c:9: Modules/errors.h:8: fatal error: lber.h: No such file or directory Any ideas how to fix this? [/INST] The website says that python-ldap is based on Ope...
<s>[INST] What do (lambda) function closures capture in Python? Recently I started playing around with Python and I came around something peculiar in the way closures work. Consider the following code: adders= [0,1,2,3] for i in [0,1,2,3]: adders[i]=lambda a: i+a print adders[1](3) It builds a simple array of func...
<s>[INST] How do I design a class in Python? I've had some really awesome help on my previous questions for detecting paws and toes within a paw, but all these solutions only work for one measurement at a time. Now I have data that consists off: about 30 dogs; each has 24 measurements (divided into several subgroups)...
<s>[INST] No Multiline Lambda in Python: Why not? I've heard it said that multiline lambdas can't be added in Python because they would clash syntactically with the other syntax constructs in Python. I was thinking about this on the bus today and realized I couldn't think of a single Python construct that multiline la...
<s>[INST] Reusable library to get human readable version of file size? There are various snippets on the web that would give you a function to return human readable size from bytes size: >>> human_readable(2048) '2 kilobytes' >>> But is there a Python library that provides this? [/INST] Addressing the above "too smal...
<s>[INST] How to check if a user is logged in (how to properly use user.is_authenticated)? I am looking over this website but just can't seem to figure out how to do this as it's not working. I need to check if the current site user is logged in (authenticated), and am trying: request.user.is_authenticated despite bei...
<s>[INST] How to change legend size with matplotlib.pyplot Simple question here: I'm just trying to get the size of my legend using matplotlib.pyplot to be smaller (ie, the text to be smaller). The code I'm using goes something like this: plot.figure() plot.scatter(k,sum_cf, color = 'black', label='Sum of Cause Fract...
<s>[INST] What is the correct syntax for 'else if'? I'm a new Python programmer who is making the leap from 2.6.4 to 3.1.1. Everything has gone fine until I tried to use the 'else if' statement. The interpreter gives me a syntax error after the 'if' in 'else if' for a reason I can't seem to figure out. def function(a):...
<s>[INST] Convert string representation of list to list in Python I was wondering what the simplest way is to convert a string list like the following to a list: x = u'[ "A","B","C" , " D"]' Even in case user puts spaces in between the commas, and spaces inside of the quotes. I need to handle that as well to: x = ["A"...
<s>[INST] Can't install PIL after Mac OS X 10.9 I've just updated my Mac OS to 10.9 and I discovered that some (all?) of my Python modules are not here anymore, especially the Image one. So I try to execute sudo pip install pil, but I get this error: /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/...
<s>[INST] Writing Unicode text to a text file? I'm pulling data out of a Google doc, processing it, and writing it to a file (that eventually I will paste into a Wordpress page). It has some non-ASCII symbols. How can I convert these safely to symbols that can be used in HTML source? Currently I'm converting everythin...
<s>[INST] How to install Python MySQLdb module using pip? How can I install the MySQLdb module for Python using pip? [/INST] It's easy to do, but hard to remember the correct spelling: pip install MySQL-python Note: Some dependencies might have to be in place when running the above command. Some hints on how to insta...
<s>[INST] Sleeping in a batch file When writing a batch file to automate something on a Windows box, I've needed to pause its execution for several seconds (usually in a test/wait loop, waiting for a process to start). At the time, the best solution I could find uses ping (I kid you not) to achieve the desired effect. ...
<s>[INST] Why are Python's arrays slow? I expected array.array to be faster than lists, as arrays seem to be unboxed. However, I get the following result: In [1]: import array In [2]: L = list(range(100000000)) In [3]: A = array.array('l', range(100000000)) In [4]: %timeit sum(L) 1 loop, best of 3: 667 ms per loop ...
<s>[INST] Binary search (bisection) in Python Is there a library function that performs binary search on a list/tuple and return the position of the item if found and 'False' (-1, None, etc.) if not? I found the functions bisect_left/right in the bisect module, but they still return a position even if the item is not i...
<s>[INST] Installing SetupTools on 64-bit Windows I'm running Python 2.7 on Windows 7 64-bit, and when I run the installer for setuptools it tells me that Python 2.7 is not installed. The specific error message is: `Python Version 2.7 required which was not found in the registry` My installed version of Python is: `P...
<s>[INST] How can I reference requirements.txt for the install_requires kwarg in setuptools' setup.py file? I have a requirements.txt file that I'm using with Travis-CI. It seems silly to duplicate the requirements in both requirements.txt and setup.py, so I was hoping to pass a file handle to the install_requires kwa...
<s>[INST] Catching an exception while using a Python 'with' statement To my shame, I can't figure out how to handle exception for python 'with' statement. If I have a code: with open("a.txt") as f: print f.readlines() I really want to handle 'file not found exception' in order to do somehing. But I can't write wit...
<s>[INST] Building a minimal plugin architecture in Python I have an application, written in Python, which is used by a fairly technical audience (scientists). I'm looking for a good way to make the application extensible by the users, i.e. a scripting/plugin architecture. I am looking for something extremely lightwe...
<s>[INST] Django: Redirect to previous page after login I'm trying to build a simple website with login functionality very similar to the one here on SO. The user should be able to browse the site as an anonymous user and there will be a login link on every page. When clicking on the login link the user will be taken t...
<s>[INST] Is False == 0 and True == 1 in Python an implementation detail or is it guaranteed by the language? Is it guaranteed that False == 0 and True == 1, in Python? For instance, is it in any way guaranteed that the following code will always produce the same results, whatever the version of Python (both existing ...
<s>[INST] Decode HTML entities in Python string? I'm parsing some HTML with Beautiful Soup 3, but it contains HTML entities which Beautiful Soup 3 doesn't automatically decode for me: >>> from BeautifulSoup import BeautifulSoup >>> soup = BeautifulSoup("<p>&pound;682m</p>") >>> text = soup.find("p").string >>> print ...
<s>[INST] Why is it slower to iterate over a small string than a small list? I was playing around with timeit and noticed that doing a simple list comprehension over a small string took longer than doing the same operation on a list of small single character strings. Any explanation? It's almost 1.35 times as much time...
<s>[INST] Django 1.7 throws django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet This is the traceback on my windows system. Traceback (most recent call last): File "D:\AMD\workspace\steelrumors\manage.py", line 9, in <module> django.setup() File "D:\AMD\Django\django-django-4c85a0d\django\__in...
<s>[INST] Escaping regex string in Python I want to use input from a user as a regex pattern for a search over some text. It works, but how I can handle cases where user puts characters that have meaning in regex? For example, the user wants to search for Word (s): regex engine will take the (s) as a group. I want i...
<s>[INST] Python subprocess/Popen with a modified environment I believe that running an external command with a slightly modified environment is a very common case. That's how I tend to do it: import subprocess, os my_env = os.environ my_env["PATH"] = "/usr/sbin:/sbin:" + my_env["PATH"] subprocess.Popen(my_command, env...
<s>[INST] Add Variables to Tuple I am learning Python and creating a database connection. While trying to add to the DB, I am thinking of creating tuples out of information and then add them to the DB. What I am Doing: I am taking information from the user and store it in variables. Can I add these variables into a t...
<s>[INST] What is the fastest way to send 100,000 HTTP requests in Python? I am opening a file which has 100,000 url's. I need to send an http request to each url and print the status code. I am using Python 2.6, and so far looked at the many confusing ways Python implements threading/concurrency. I have even looked ...