instruction
stringlengths
12
148
input
stringlengths
16
30.2k
output
stringlengths
11
27.3k
Convert a Python int into a big-endian string of bytes
I have a non-negative int and I would like to efficiently convert it to a big-endian string containing the same data. For example, the int 1245427 (which is 0x1300F3) should result in a string of length 3 containing three characters whose byte values are 0x13, 0x00, and 0xf3. My ints are on the scale of 35 (base-10) digits. How do I do this?
You can use the struct module: import struct print struct.pack('>I', your_int) '>I' is a format string. > means big endian and I means unsigned int. Check the documentation for more format chars.
Read Unicode characters from command-line arguments in Python 2.x on Windows
I want my Python script to be able to read Unicode command line arguments in Windows. But it appears that sys.argv is a string encoded in some local encoding, rather than Unicode. How can I read the command line in full Unicode? Example code: argv.py import sys first_arg = sys.argv[1] print first_arg print type(first_arg) print first_arg.encode("hex") print open(first_arg) On my PC set up for Japanese code page, I get: C:\temp>argv.py "PC・ソフト申請書08.09.24.doc" PC・ソフト申請書08.09.24.doc <type 'str'> 50438145835c83748367905c90bf8f9130382e30392e32342e646f63 <open file 'PC・ソフト申請書08.09.24.doc', mode 'r' at 0x00917D90> That's Shift-JIS encoded I believe, and it "works" for that filename. But it breaks for filenames with characters that aren't in the Shift-JIS character set—the final "open" call fails: C:\temp>argv.py Jörgen.txt Jorgen.txt <type 'str'> 4a6f7267656e2e747874 Traceback (most recent call last): File "C:\temp\argv.py", line 7, in <module> print open(first_arg) IOError: [Errno 2] No such file or directory: 'Jorgen.txt' Note—I'm talking about Python 2.x, not Python 3.0. I've found that Python 3.0 gives sys.argv as proper Unicode. But it's a bit early yet to transition to Python 3.0 (due to lack of 3rd party library support). Update: A few answers have said I should decode according to whatever the sys.argv is encoded in. The problem with that is that it's not full Unicode, so some characters are not representable. Here's the use case that gives me grief: I have enabled drag-and-drop of files onto .py files in Windows Explorer. I have file names with all sorts of characters, including some not in the system default code page. My Python script doesn't get the right Unicode filenames passed to it via sys.argv in all cases, when the characters aren't representable in the current code page encoding. There is certainly some Windows API to read the command line with full Unicode (and Python 3.0 does it). I assume the Python 2.x interpreter is not using it.
Here is a solution that is just what I'm looking for, making a call to the Windows GetCommandLineArgvW function: Get sys.argv with Unicode characters under Windows (from ActiveState) But I've made several changes, to simplify its usage and better handle certain uses. Here is what I use: win32_unicode_argv.py """ win32_unicode_argv.py Importing this will replace sys.argv with a full Unicode form. Windows only. From this site, with adaptations: http://code.activestate.com/recipes/572200/ Usage: simply import this module into a script. sys.argv is changed to be a list of Unicode strings. """ import sys def win32_unicode_argv(): """Uses shell32.GetCommandLineArgvW to get sys.argv as a list of Unicode strings. Versions 2.x of Python don't support Unicode in sys.argv on Windows, with the underlying Windows API instead replacing multi-byte characters with '?'. """ from ctypes import POINTER, byref, cdll, c_int, windll from ctypes.wintypes import LPCWSTR, LPWSTR GetCommandLineW = cdll.kernel32.GetCommandLineW GetCommandLineW.argtypes = [] GetCommandLineW.restype = LPCWSTR CommandLineToArgvW = windll.shell32.CommandLineToArgvW CommandLineToArgvW.argtypes = [LPCWSTR, POINTER(c_int)] CommandLineToArgvW.restype = POINTER(LPWSTR) cmd = GetCommandLineW() argc = c_int(0) argv = CommandLineToArgvW(cmd, byref(argc)) if argc.value > 0: # Remove Python executable and commands if present start = argc.value - len(sys.argv) return [argv[i] for i in xrange(start, argc.value)] sys.argv = win32_unicode_argv() Now, the way I use it is simply to do: import sys import win32_unicode_argv and from then on, sys.argv is a list of Unicode strings. The Python optparse module seems happy to parse it, which is great.
Cross-platform way of getting temp directory in Python
Is there a cross-platform way of getting the path to the temp directory in Python 2.6? For example, under Linux that would be /tmp, while under XP C:\Documents and settings\[user]\Application settings\Temp. Thanks!
That would be the tempfile module. It has functions to get the temporary directory, and also has some shortcuts to create temporary files and directories in it, either named or unnamed. Example: import tempfile print tempfile.gettempdir() # prints the current temporary directory f = tempfile.TemporaryFile() f.write('something on temporaryfile') f.seek(0) # return to beginning of file print f.read() # reads data back from the file f.close() # temporary file is automatically deleted here For completeness, here's how it searches for the temporary directory, according to the documentation: The directory named by the TMPDIR environment variable. The directory named by the TEMP environment variable. The directory named by the TMP environment variable. A platform-specific location: On RiscOS, the directory named by the Wimp$ScrapDir environment variable. On Windows, the directories C:\TEMP, C:\TMP, \TEMP, and \TMP, in that order. On all other platforms, the directories /tmp, /var/tmp, and /usr/tmp, in that order. As a last resort, the current working directory.
Writing/parsing a fixed width file using Python
I'm a newbie to Python and I'm looking at using it to write some hairy EDI stuff that our supplier requires. Basically they need an 80-character fixed width text file, with certain "chunks" of the field with data and others left blank. I have the documentation so I know what the length of each "chunk" is. The response that I get back is easier to parse since it will already have data and I can use Python's "slices" to extract what I need, but I can't assign to a slice - I tried that already because it sounded like a good solution, and it didn't work since Python strings are immutable :) Like I said I'm really a newbie to Python but I'm excited about learning it :) How would I go about doing this? Ideally I'd want to be able to say that range 10-20 is equal to "Foo" and have it be the string "Foo" with 7 additional whitespace characters (assuming said field has a length of 10) and have that be a part of the larger 80-character field, but I'm not sure how to do what I'm thinking.
You don't need to assign to slices, just build the string using % formatting. An example with a fixed format for 3 data items: >>> fmt="%4s%10s%10s" >>> fmt % (1,"ONE",2) ' 1 ONE 2' >>> Same thing, field width supplied with the data: >>> fmt2 = "%*s%*s%*s" >>> fmt2 % (4,1, 10,"ONE", 10,2) ' 1 ONE 2' >>> Separating data and field widths, and using zip() and str.join() tricks: >>> widths=(4,10,10) >>> items=(1,"ONE",2) >>> "".join("%*s" % i for i in zip(widths, items)) ' 1 ONE 2' >>>
How to limit the maximum value of a numeric field in a Django model?
Django has various numeric fields available for use in models, e.g. DecimalField and PositiveIntegerField. Although the former can be restricted to the number of decimal places stored and the overall number of characters stored, is there any way to restrict it to storing only numbers within a certain range, e.g. 0.0-5.0 ? Failing that, is there any way to restrict a PositiveIntegerField to only store, for instance, numbers up to 50? Update: now that Bug 6845 has been closed, this StackOverflow question may be moot. - sampablokuper
You can use Django's built-in validators— from django.db.models import IntegerField, Model from django.core.validators import MaxValueValidator, MinValueValidator class CoolModelBro(Model): limited_integer_field = IntegerField( default=1, validators=[ MaxValueValidator(100), MinValueValidator(1) ] ) Edit: Although these only work when you're using the model in a ModelForm, not if you're using the model "on its own", sigh.
How do I enumerate() over a list of tuples in Python?
I've got some code like this: letters = [('a', 'A'), ('b', 'B')] i = 0 for (lowercase, uppercase) in letters: print "Letter #%d is %s/%s" % (i, lowercase, uppercase) i += 1 I've been told that there's an enumerate() function that can take care of the "i" variable for me: for i, l in enumerate(['a', 'b', 'c']): print "%d: %s" % (i, l) However, I can't figure out how to combine the two: How do I use enumerate when the list in question is made of tuples? Do i have to do this? letters = [('a', 'A'), ('b', 'B')] for i, tuple in enumerate(letters): (lowercase, uppercase) = tuple print "Letter #%d is %s/%s" % (i, lowercase, uppercase) Or is there a more elegant way?
This is a neat way to do it: letters = [('a', 'A'), ('b', 'B')] for i, (lowercase, uppercase) in enumerate(letters): print "Letter #%d is %s/%s" % (i, lowercase, uppercase)
Simple threading in Python 2.6 using thread.start_new_thread()
I'm following a tutorial on simple threading. They give this example and when I try to use it I'm getting unintelligible errors from the interpreter. Can you please tell me why this isn't working? I'm on WinXP SP3 w/ Python 2.6 current import thread def myfunction(mystring,*args): print mystring if __name__ == '__main__': try: thread.start_new_thread(myfunction,('MyStringHere',1)) except Exception as errtxt: print errtxt Executing this results in:: Unhandled exception in thread started by Error in sys.excepthook: Original exception was: The information missing in the error is actually missing in the output.
The problem is that your main thread has quit before your new thread has time to finish. The solution is to wait at your main thread. import thread, time def myfunction(mystring,*args): print mystring if __name__ == '__main__': try: thread.start_new_thread(myfunction,('MyStringHere',1)) except Exception, errtxt: print errtxt time.sleep(5) As a side note, you probably want to use the threading module. Your main thread will wait for all of those types of threads to be closed before exiting: from threading import Thread def myfunction(mystring,*args): print mystring if __name__ == '__main__': try: Thread(target=myfunction, args=('MyStringHere',1)).start() except Exception, errtxt: print errtxt
What's the most efficient way to insert thousands of records into a table (MySQL, Python, Django)
I have a database table with a unique string field and a couple of integer fields. The string field is usually 10-100 characters long. Once every minute or so I have the following scenario: I receive a list of 2-10 thousand tuples corresponding to the table's record structure, e.g. [("hello", 3, 4), ("cat", 5, 3), ...] I need to insert all these tuples to the table (assume I verified neither of these strings appear in the database). For clarification, I'm using InnoDB, and I have an auto-incremental primary key for this table, the string is not the PK. My code currently iterates through this list, for each tuple creates a Python module object with the appropriate values, and calls ".save()", something like so: @transaction.commit_on_success def save_data_elements(input_list): for (s, i1, i2) in input_list: entry = DataElement(string=s, number1=i1, number2=i2) entry.save() This code is currently one of the performance bottlenecks in my system, so I'm looking for ways to optimize it. For example, I could generate SQL codes each containing an INSERT command for 100 tuples ("hard-coded" into the SQL) and execute it, but I don't know if it will improve anything. Do you have any suggestion to optimize such a process? Thanks
For MySQL specifically, the fastest way to load data is using LOAD DATA INFILE, so if you could convert the data into the format that expects, it'll probably be the fastest way to get it into the table.
Clearing Python lists
Is there any reason to do anything more complicated than one of these two lines when you want to clear a list in Python: old_list = [] old_list = list() The reason I ask is that I just saw this in some running code: del old_list[ 0:len(old_list) ]
Clearing a list in place will affect all other references of the same list. For example, this method doesn't affect other references: >>> a = [1, 2, 3] >>> b = a >>> a = [] >>> print(a) [] >>> print(b) [1, 2, 3] But this one does: >>> a = [1, 2, 3] >>> b = a >>> del a[:] # equivalent to del a[0:len(a)] >>> print(a) [] >>> print(b) [] >>> a is b True You could also do: >>> a[:] = []
How does Python import modules from .egg files?
How can I open __init__.pyc here? >>> import stompservice <module 'stompservice' from 'C:\Python25\lib\site-packages\stompservice-0.1.0-py2.5.egg\stompservice\__init__.pyc'> All I see in C:\Python25\lib\site-packages\ is the .egg file, but where are the internal files of the package?
http://peak.telecommunity.com/DevCenter/PythonEggs .egg files are simply renamed zip files. Open the egg with your zip program, or just rename the extension to .zip, and extract.
Django -- User.DoesNotExist does not exist?
I'm trying to get hold of Django. I use Pydev on Eclipse. I have written a simple signup page that I can't get to work. Eclipse complains that User.DoesNotExist is undefined. Most likely, I am missing something trivial. Here's the relevant portion of the code: from django.contrib.auth.models import User ... class SignUpForm (forms.Form): ... def clean_username (self): try: User.objects.get(username=self.cleaned_data['username']) except User.DoesNotExist: return self.cleaned_data['username'] raise forms.ValidationError(USERNAME_ALREADY_IN_USE) ...
I just discovered Pydev actually has a nice workaround for this. Go to Window > Preferences, then Pydev > Editor > Code Analysis. Click the Undefined tab and add "DoesNotExist" to the text box titled Consider the following names as globals.
Python: getting a reference to a function from inside itself
If I define a function: def f(x): return x+3 I can later store objects as attributes of the function, like so: f.thing="hello!" I would like to do this from inside the code of the function itself. Problem is, how do I get a reference to the function from inside itself?
The same way, just use its name. >>> def g(x): ... g.r = 4 ... >>> g <function g at 0x0100AD68> >>> g(3) >>> g.r 4
How to dynamically compose an OR query filter in Django?
From an example you can see a multiple OR query filter: Article.objects.filter(Q(pk=1) | Q(pk=2) | Q(pk=3)) For example, this results in: [<Article: Hello>, <Article: Goodbye>, <Article: Hello and goodbye>] However, I want to create this query filter from a list. How to do that? e.g. [1, 2, 3] -> Article.objects.filter(Q(pk=1) | Q(pk=2) | Q(pk=3))
You could chain your queries as follows: values = [1,2,3] # Turn list of values into list of Q objects queries = [Q(pk=value) for value in values] # Take one Q object from the list query = queries.pop() # Or the Q object with the ones remaining in the list for item in queries: query |= item # Query the model Article.objects.filter(query)
Django ORM: Selecting related set
Say I have 2 models: class Poll(models.Model): category = models.CharField(u"Category", max_length = 64) [...] class Choice(models.Model): poll = models.ForeignKey(Poll) [...] Given a Poll object, I can query its choices with: poll.choice_set.all() But, is there a utility function to query all choices from a set of Poll? Actually, I'm looking for something like the following (which is not supported, and I don't seek how it could be): polls = Poll.objects.filter(category = 'foo').select_related('choice_set') for poll in polls: print poll.choice_set.all() # this shouldn't perform a SQL query at each iteration I made an (ugly) function to help me achieve that: def qbind(objects, target_name, model, field_name): objects = list(objects) objects_dict = dict([(object.id, object) for object in objects]) for foreign in model.objects.filter(**{field_name + '__in': objects_dict.keys()}): id = getattr(foreign, field_name + '_id') if id in objects_dict: object = objects_dict[id] if hasattr(object, target_name): getattr(object, target_name).append(foreign) else: setattr(object, target_name, [foreign]) return objects which is used as follow: polls = Poll.objects.filter(category = 'foo') polls = qbind(polls, 'choices', Choice, 'poll') # Now, each object in polls have a 'choices' member with the list of choices. # This was achieved with 2 SQL queries only. Is there something easier already provided by Django? Or at least, a snippet doing the same thing in a better way. How do you handle this problem usually?
Time has passed and this functionality is now available in Django 1.4 with the introduction of the prefetch_related() QuerySet function. This function effectively does what is performed by the suggested qbind function. ie. Two queries are performed and the join occurs in Python land, but now this is handled by the ORM. The original query request would now become: polls = Poll.objects.filter(category = 'foo').prefetch_related('choice_set') As is shown in the following code sample, the polls QuerySet can be used to obtain all Choice objects per Poll without requiring any further database hits: for poll in polls: for choice in poll.choice_set: print choice
What do I need to read Microsoft Access databases using Python?
How can I access Microsoft Access databases in Python? With SQL? I'd prefere a solution that works with Linux, but I could also settle for Windows. I only require read access.
On Linux, MDBTools is your only chance as of now. [disputed] On Windows, you can deal with mdb files with pypyodbc. To create an Access mdb file: import pypyodbc pypyodbc.win_create_mdb( "D:\\Your_MDB_file_path.mdb" ) Here is an Hello World script that fully demostate pypyodbc's Access support functions. Disclaimer: I'm the developer of pypyodbc.
Change keyboard locks in Python
Is there any way, in Python, to programmatically change the CAPS LOCK/NUM LOCK/SCROLL LOCK states? This isn't really a joke question - more like a real question for a joke program. I intend to use it for making the lights do funny things...
If you're using windows you can use SendKeys for this I believe. http://www.rutherfurd.net/python/sendkeys import SendKeys SendKeys.SendKeys(""" {CAPSLOCK} {SCROLLOCK} {NUMLOCK} """)
Can I restrict nose coverage output to directory (rather than package)?
My SUT looks like: foo.py bar.py tests/__init__.py [empty] tests/foo_tests.py tests/bar_tests.py tests/integration/__init__.py [empty] tests/integration/foo_tests.py tests/integration/bar_tests.py When I run nosetests --with-coverage, I get details for all sorts of modules that I'd rather ignore. But I can't use the --cover-package=PACKAGE option because foo.py & bar.py are not in a package. (See the thread after http://lists.idyll.org/pipermail/testing-in-python/2008-November/001091.html for my reasons for not putting them in a package.) Can I restrict coverage output to just foo.py & bar.py? Update - Assuming that there isn't a better answer than Nadia's below, I've asked a follow up question: "How do I write some (bash) shell script to convert all matching filenames in directory to command-line options?"
You can use it like this: --cover-package=foo --cover-package=bar I had a quick look at nose source code to confirm: This is the line if options.cover_packages: for pkgs in [tolist(x) for x in options.cover_packages]:
How Big can a Python Array Get?
In Python, how big can an array/list get? I need an array of about 12000 elements. Will I still be able to run array/list methods such as sorting, etc?
According to the source code, the maximum size of a list is PY_SSIZE_T_MAX/sizeof(PyObject*). PY_SSIZE_T_MAX is defined in pyport.h to be ((size_t) -1)>>1 On a regular 32bit system, this is (4294967295 / 2) / 4 or 536870912. Therefore the maximum size of a python list on a 32 bit system is 536,870,912 elements. As long as the number of elements you have is equal or below this, all list functions should operate correctly.
referenced before assignment error in python
In Python I'm getting the following error: UnboundLocalError: local variable 'total' referenced before assignment At the start of the file (before the function where the error comes from), I declare 'total' using the global keyword. Then, in the body of the program, before the function that uses 'total' is called, I assign it to 0. I've tried setting it to 0 in various places (including the top of the file, just after it is declared), but I can't get it to work. Does anyone see what I'm doing wrong?
I think you are using 'global' incorrectly. See Python reference. You should declare variable without global and then inside the function when you want to access global variable you declare it 'global yourvar'. #!/usr/bin/python total def checkTotal(): global total total = 0 See this example: #!/usr/bin/env python total = 0 def doA(): # not accessing global total total = 10 def doB(): global total total = total + 1 def checkTotal(): # global total - not required as global is required # only for assignment - thanks for comment Greg print total def main(): doA() doB() checkTotal() if __name__ == '__main__': main() Because doA() does not modify the global total the output is 1 not 11.
Python try-else
What is the intended use of the optional else clause of the try statement?
The statements in the else block are executed if execution falls off the bottom of the try - if there was no exception. Honestly, I've never found a need. However, Handling Exceptions notes: The use of the else clause is better than adding additional code to the try clause because it avoids accidentally catching an exception that wasn’t raised by the code being protected by the try ... except statement. So, if you have a method that could, for example, throw an IOError, and you want to catch exceptions it raises, but there's something else you want to do if the first operation succeeds, and you don't want to catch an IOError from that operation, you might write something like this: try: operation_that_can_throw_ioerror() except IOError: handle_the_exception_somehow() else: # we don't want to catch the IOError if it's raised another_operation_that_can_throw_ioerror() finally: something_we_always_need_to_do() If you just put another_operation_that_can_throw_ioerror() after operation_that_can_throw_ioerror, the except would catch the second call's errors. And if you put it after the whole try block, it'll always be run, and not until after the finally. The else lets you make sure the second operation's only run if there's no exception, it's run before the finally block, and any IOErrors it raises aren't caught here
Auto-populating created_by field with Django admin site
I want to use the Django admin interface for a very simple web application but I can't get around a problem that should not be that hard to resolve .. Consider the following: class Contact(models.Model): name = models.CharField(max_length=250, blank=False) created_by = models.ForeignKey(User, blank=False) I can't find a way to auto-populate the created_by field and make the Django admin aware of it. Most of the method I've seen implies overloading the Object's save method and pass it the request user. They all requires to build your custom views and/or forms. Optimally the form to create new contacts in the admin site should not show the created_by field (which is quite easy) and auto-populate it with the current user (which seems harder than it should).
http://code.djangoproject.com/wiki/CookBookNewformsAdminAndUser Involves implementing save methods on your ModelAdmin objects.
Changing LD_LIBRARY_PATH at runtime for ctypes
How do you update this environment variable at runtime so that ctypes can load a library wherever? I've tried the following and neither seem to work. from ctypes import * os.environ['LD_LIBRARY_PATH'] = "/home/starlon/Projects/pyCFA635/lib" os.putenv('LD_LIBRARY_PATH', "/home/starlon/Projects/pyCFA635/lib") lib = CDLL("libevaluator.so")
By the time a program such as Python is running, the dynamic loader (ld.so.1 or something similar) has already read LD_LIBRARY_PATH and won't notice any changes thereafter. So, unless the Python software itself evaluates LD_LIBRARY_PATH and uses it to build the possible path name of the library for dlopen() or an equivalent function to use, setting the variable in the script will have no effect. Given that you say it doesn't work, it seems plausible to suppose that Python does not build and try all the possible library names; it probably relies on LD_LIBRARY_PATH alone.
2D arrays in Python
What's the best way to create 2D arrays in Python? What I want is want is to store values like this: X , Y , Z so that I access data like X[2],Y[2],Z[2] or X[n],Y[n],Z[n] where n is variable. I don't know in the beginning how big n would be so I would like to append values at the end.
>>> a = [] >>> for i in xrange(3): ... a.append([]) ... for j in xrange(3): ... a[i].append(i+j) ... >>> a [[0, 1, 2], [1, 2, 3], [2, 3, 4]] >>>
How to recognize whether a script is running on a tty?
I would like my script to act differently in an interactive shell session and when running with redirected stdout (for example when piped to some other command). How do I recognize which of these two happen in a Python script? Example of such behavior in existing program: grep --color=auto highlights matches when running in interactive shell, but doesn't when piped to something else.
import os, sys os.isatty(sys.stdout.fileno()) or sys.stdout.isatty()
About 20 models in 1 django app
I have started work on a local app for myself that runs through the browser. Having recently gone through the django tutorial I'm thinking that it might be better to use django rather than just plain python. There's one problem: I have at least 20 models and each will have many functions. Quite simply it's going to create one huge models file and probably huge views too. How do I split them up? The models are all related so I can't simply make them into separate apps can I?
This is a pretty common need... I can't imagine wading through a models.py file that's 10,000 lines long :-) You can split up the models.py file (and views.py too) into a pacakge. In this case, your project tree will look like: /my_proj /myapp /models __init__.py person.py The __init__.py file makes the folder into a package. The only gotcha is to be sure to define an inner Meta class for your models that indicate the app_label for the model, otherwise Django will have trouble building your schema: class Person(models.Model): name = models.CharField(max_length=128) class Meta: app_label = 'myapp' Once that's done, import the model in your __init__.py file so that Django and sync db will find it: from person import Person This way you can still do from myapp.models import Person
whoami in python
What is the best way to find out the user that a python process is running under? I could do this: name = os.popen('whoami').read() But that has to start a whole new process. os.environ["USER"] works sometimes, but sometimes that environment variable isn't set.
import getpass print getpass.getuser() See the documentation of the getpass module. getpass.getuser() Return the “login name” of the user. Availability: Unix, Windows. This function checks the environment variables LOGNAME, USER, LNAME and USERNAME, in order, and returns the value of the first one which is set to a non-empty string. If none are set, the login name from the password database is returned on systems which support the pwd module, otherwise, an exception is raised.
A class method which behaves differently when called as an instance method?
I'm wondering if it's possible to make a method which behaves differently when called as a class method than when called as an instance method. For example, as a skills-improvement project, I'm writing a Matrix class (yes, I know there are perfectly good matrix classes already out there). I've created a class method for it called identity which returns an identity matrix of a specified size. Now, when called on an instance of Matrix, it seems logical that the size shouldn't need to be specified; it should return an identity matrix of the same size as the Matrix it's called on. In other words, I'd like to define a method which can determine whether it was called via an instance and, if so, access that instance's attributes. Unfortunately, even after digging through the documentation and a few Google searches, I haven't found anything which suggests this is possible. Does anyone know differently? Edit: Wow! Clearly, I'm still not quite used to first-class functions. Here's what I ended up with — thanks to Unknown for providing the key! class Foo(object): def __init__(self, bar): self.baz = bar self.bar = MethodType(lambda self: self.__class__.bar(self.baz), self, self.__class__) @classmethod def bar(cls, baz): return 5 * baz Foo.bar(3) # returns 15 foo = Foo(7) foo.bar() # returns 35 Edit 2: Just a quick note — this technique (and most of those presented below) won't work on classes which define __slots__, as you cannot reassign the method.
Questionably useful Python hacks are my forte. from types import * class Foo(object): def __init__(self): self.bar = methodize(bar, self) self.baz = 999 @classmethod def bar(cls, baz): return 2 * baz def methodize(func, instance): return MethodType(func, instance, instance.__class__) def bar(self): return 4*self.baz >>> Foo.bar(5) 10 >>> a=Foo() >>> a.bar() 3996
How to download a file using python in a 'smarter' way?
I need to download several files via http in Python. The most obvious way to do it is just using urllib2: import urllib2 u = urllib2.urlopen('http://server.com/file.html') localFile = open('file.html', 'w') localFile.write(u.read()) localFile.close() But I'll have to deal with the URLs that are nasty in some way, say like this: http://server.com/!Run.aspx/someoddtext/somemore?id=121&m=pdf. When downloaded via the browser, the file has a human-readable name, ie. accounts.pdf. Is there any way to handle that in python, so I don't need to know the file names and hardcode them into my script?
Download scripts like that tend to push a header telling the user-agent what to name the file: Content-Disposition: attachment; filename="the filename.ext" If you can grab that header, you can get the proper filename. There's another thread that has a little bit of code to offer up for Content-Disposition-grabbing. remotefile = urllib2.urlopen('http://example.com/somefile.zip') remotefile.info()['Content-Disposition']
Is it possible to have multiple statements in a python lambda expression?
I am a python newbie trying to achieve the following: I have a list of lists: lst = [[567,345,234],[253,465,756, 2345],[333,777,111, 555]] I want map lst into another list containing only the second smallest number from each sublist. So the result should be: [345, 465, 333] For example if I were just interested in the smallest number, I could do: map(lambda x: min(x),lst) I wish I could do this: map(lambda x: sort(x)[1],lst) but sort does not chain. (returns None) neither is something like this allowed: map(lambda x: sort(x); x[1],lst) #hence the multiple statement question Is there a way to do this with map in python but without defining a named function? (it is easy with anonymous blocks in ruby, for example)
There are several different answers I can give here, from your specific question to more general concerns. so from most specific to most general: Q. Can you put multiple statements in a lambda? A. No. But you don't actually need to use a lambda. You can put the statements in a def instead. ie: def second_lowest(l): l.sort() return l[1] map(second_lowest, lst) Q. Can you get the second lowest item from a lambda by sorting the list? A. Yes. As alex's answer poinst out, sorted() is a version of sort that creates a new list, rather than sorting in-place, and can be chained. Note that this is probably what you should be using - it's bad practice for your map to have side effects on the original list. Q. How should I get the second lowest item from each list in a sequence of lists. A. sorted(l)[1] is not actually the best way for this. It has O(N log(N)) complexity, while an O(n) solution exists. This can be found in the heapq module. >>> import heapq >>> l = [5,2,6,8,3,5] >>> heapq.nsmallest(l, 2) [2, 3] So just use: map(lambda x: heapq.nsmallest(x,2)[1], list_of_lists) It's also usually considered clearer to use a list comprehension, which avoids the lambda altogether: [heapq.nsmallest(x,2)[1] for x in list_of_lists]
How to generate XML documents with namespaces in Python
I'm trying to generate an XML document with namespaces, currently with Python's xml.dom.minidom: import xml.dom.minidom doc = xml.dom.minidom.Document() el = doc.createElementNS('http://example.net/ns', 'el') doc.appendChild(el) print(doc.toprettyxml()) The namespace is saved (doc.childNodes[0].namespaceURI is 'http://example.net/ns'), but why is it missing in the output? <?xml version="1.0" ?> <el/> I expect: <?xml version="1.0" ?> <el xmlns="http://example.net/ns" /> or <?xml version="1.0" ?> <randomid:el xmlns:randomid="http://example.net/ns" />
createElementNS() is defined as: def createElementNS(self, namespaceURI, qualifiedName): prefix, localName = _nssplit(qualifiedName) e = Element(qualifiedName, namespaceURI, prefix) e.ownerDocument = self return e so… import xml.dom.minidom doc = xml.dom.minidom.Document() el = doc.createElementNS('http://example.net/ns', 'ex:el') #--------------------------------------------------^^^^^ doc.appendChild(el) print(doc.toprettyxml()) yields: <?xml version="1.0" ?> <ex:el/> …not quite there… import xml.dom.minidom doc = xml.dom.minidom.Document() el = doc.createElementNS('http://example.net/ns', 'ex:el') el.setAttribute("xmlns:ex", "http://example.net/ns") doc.appendChild(el) print(doc.toprettyxml()) yields: <?xml version="1.0" ?> <ex:el xmlns:ex="http://example.net/ns"/> alternatively: import xml.dom.minidom doc = xml.dom.minidom.Document() el = doc.createElementNS('http://example.net/ns', 'el') el.setAttribute("xmlns", "http://example.net/ns") doc.appendChild(el) print(doc.toprettyxml()) wich produces: <?xml version="1.0" ?> <el xmlns="http://example.net/ns"/> It looks like you'd have to do it manually. Element.writexml() shows no indication that namespaces would get any special treatment. EDIT: This answer is targeted at xml.dom.minidom only, since the OP used it in the question. I do not indicate that it was impossible to use XML namespaces in Python generally. ;-)
A data-structure for 1:1 mappings in python?
I have a problem which requires a reversable 1:1 mapping of keys to values. That means sometimes I want to find the value given a key, but at other times I want to find the key given the value. Both keys and values are guaranteed unique. x = D[y] y == D.inverse[x] The obvious solution is to simply invert the dictionary every time I want a reverse-lookup: Inverting a dictionary is very easy, there's a recipe here but for a large dictionary it can be very slow. The other alternative is to make a new class which unites two dictionaries, one for each kind of lookup. That would most likely be fast but would use up twice as much memory as a single dict. So is there a better structure I can use? My application requires that this should be very fast and use as little as possible memory. The structure must be mutable, and it's strongly desirable that mutating the object should not cause it to be slower (e.g. to force a complete re-index) We can guarantee that either the key or the value (or both) will be an integer It's likely that the structure will be needed to store thousands or possibly millions of items. Keys & Valus are guaranteed to be unique, i.e. len(set(x)) == len(x) for for x in [D.keys(), D.valuies()]
The other alternative is to make a new class which unites two dictionaries, one for each kind of lookup. That would most likely be fast but would use up twice as much memory as a single dict. Not really. Have you measured that? Since both dictionaries would use references to the same objects as keys and values, then the memory spent would be just the dictionary structure. That's a lot less than twice and is a fixed ammount regardless of your data size. What I mean is that the actual data wouldn't be copied. So you'd spend little extra memory. Example: a = "some really really big text spending a lot of memory" number_to_text = {1: a} text_to_number = {a: 1} Only a single copy of the "really big" string exists, so you end up spending just a little more memory. That's generally affordable. I can't imagine a solution where you'd have the key lookup speed when looking by value, if you don't spend at least enough memory to store a reverse lookup hash table (which is exactly what's being done in your "unite two dicts" solution).
Problems using nose in a virtualenv
I am unable to use nose (nosetests) in a virtualenv project - it can't seem to find the packages installed in the virtualenv environment. The odd thing is that i can set test_suite = 'nose.collector' in setup.py and run the tests just fine as python setup.py test but when running nosetests straight, there are all sorts of import errors. I've tried it with both a system-wide installation of nose and a virtualenv nose package and no luck. Any thoughts? Thanks!!
You need to have a copy of nose installed in the virtual environment. In order to force installation of nose into the virtualenv, even though it is already installed in the global site-packages, run pip install with the -I flag: (env1)$ pip install nose -I From then on you can just run nosetests as usual.
How do I correctly clean up a Python object?
class Package: def __init__(self): self.files = [] # ... def __del__(self): for file in self.files: os.unlink(file) __del__(self) above fails with an AttributeError exception. I understand Python doesn't guarantee the existence of "global variables" (member data in this context?) when __del__() is invoked. If that is the case and this is the reason for the exception, how do I make sure the object destructs properly?
I'd recommend using Python's with statement for managing resources that need to be cleaned up. The problem with using an explicit close() statement is that you have to worry about people forgetting to call it at all or forgetting to place it in a finally block to prevent a resource leak when an exception occurs. To use the with statement, create a class with the following methods: def __enter__(self) def __exit__(self, exc_type, exc_value, traceback) In your example above, you'd use class Package: def __init__(self): self.files = [] def __enter__(self): return self # ... def __exit__(self, exc_type, exc_value, traceback): for file in self.files: os.unlink(file) Then, when someone wanted to use your class, they'd do the following: with Package() as package_obj: # use package_obj The variable package_obj will be an instance of type Package (it's the value returned by the __enter__ method). Its __exit__ method will automatically be called, regardless of whether or not an exception occurs. You could even take this approach a step further. In the example above, someone could still instantiate Package using its constructor without using the with clause. You don't want that to happen. You can fix this by creating a PackageResource class that defines the __enter__ and __exit__ methods. Then, the Package class would be defined strictly inside the __enter__ method and returned. That way, the caller never could instantiate the Package class without using a with statement: class PackageResource: def __enter__(self): class Package: ... self.package_obj = Package() return self.package_obj def __exit__(self, exc_type, exc_value, traceback): self.package_obj.cleanup() You'd use this as follows: with PackageResource() as package_obj: # use package_obj
How do you grep through code that lives in many different directories?
I'm working on a Python program that makes heavy use of eggs (Plone). That means there are 198 directories full of Python code I might want to search through while debugging. Is there a good way to search only the .py files in only those directories, avoiding unrelated code and large binary files?
I would strongly recommend ack, a grep substitute, "aimed at programmers with large trees of heterogeneous source code" (from the website)
how to isinstance(x, module)?
I need to test if a variable is a module or not. How to do this in the cleanest way? I need this for initializing some dispatcher function and I want that the function can accept either dict or module as an argument.
>>> import os, types >>> isinstance(os, types.ModuleType) True (It also works for your own Python modules, as well as built-in ones like os.)
How can I perform divison on a datetime.timedelta in python?
I'd like to be able to do the following: num_intervals = (cur_date - previous_date) / interval_length or print (datetime.now() - (datetime.now() - timedelta(days=5))) / timedelta(hours=12) # won't run, would like it to print '10' but the division operation is unsupported on timedeltas. Is there a way that I can implement divison for timedeltas? Edit: Looks like this was added to Python 3.2 (thanks rincewind!): http://bugs.python.org/issue2706
Division and multiplication by integers seems to work out of the box: >>> from datetime import timedelta >>> timedelta(hours=6) datetime.timedelta(0, 21600) >>> timedelta(hours=6) / 2 datetime.timedelta(0, 10800)
"else" considered harmful in Python?
In an answer (by S.Lott) to a question about Python's try...else statement: Actually, even on an if-statement, the else: can be abused in truly terrible ways creating bugs that are very hard to find. [...] Think twice about else:. It is generally a problem. Avoid it except in an if-statement and even then consider documenting the else- condition to make it explicit. Is this a widely held opinion? Is else considered harmful? Of course you can write confusing code with it but that's true of any other language construct. Even Python's for...else seems to me a very handy thing to have (less so for try...else).
S.Lott has obviously seen some bad code out there. Haven't we all? I do not consider else harmful, though I've seen it used to write bad code. In those cases, all the surrounding code has been bad as well, so why blame poor else?
Is everything an object in python like ruby?
A comment on another Stack Overflow question states that Python was just like Ruby, as it relates to "everything's an object," and everything in Python was an object, just like Ruby. Is this true? Is everything an object in python like ruby? How are the two different in this respect or are they really the same? For example, can you take a number and do the ruby stuff I've seen like: y = 5.plus 6 Can that be done the same way in Python?
DiveIntoPython - Everything Is an Object Everything in Python is an object, and almost everything has attributes and methods. All functions have a built-in attribute __doc__, which returns the doc string defined in the function's source code. The sys module is an object which has (among other things) an attribute called path. And so forth. Still, this begs the question. What is an object? Different programming languages define “object” in different ways. In some, it means that all objects must have attributes and methods; in others, it means that all objects are subclassable. In Python, the definition is looser; some objects have neither attributes nor methods (more on this in Chapter 3), and not all objects are subclassable (more on this in Chapter 5). But everything is an object in the sense that it can be assigned to a variable or passed as an argument to a function (more in this in Chapter 4). Ruby Docs - To Ruby From Python As with Python, in Ruby,... Everything is an object So there you have it from Ruby's own website: in Python everything is an object.
Using BeautifulSoup to find a HTML tag that contains certain text
I'm trying to get the elements in an HTML doc that contain the following pattern of text: #\S{11} <h2> this is cool #12345678901 </h2> So, the previous would match by using: soup('h2',text=re.compile(r' #\S{11}')) And the results would be something like: [u'blahblah #223409823523', u'thisisinteresting #293845023984'] I'm able to get all the text that matches (see line above). But I want the parent element of the text to match, so I can use that as a starting point for traversing the document tree. In this case, I'd want all the h2 elements to return, not the text matches. Ideas?
from BeautifulSoup import BeautifulSoup import re html_text = """ <h2>this is cool #12345678901</h2> <h2>this is nothing</h2> <h1>foo #126666678901</h1> <h2>this is interesting #126666678901</h2> <h2>this is blah #124445678901</h2> """ soup = BeautifulSoup(html_text) for elem in soup(text=re.compile(r' #\S{11}')): print elem.parent Prints: <h2>this is cool #12345678901</h2> <h2>this is interesting #126666678901</h2> <h2>this is blah #124445678901</h2>
How can I build multiple submit buttons django form?
I have form with one input for email and two submit buttons to subscribe and unsubscribe from newsletter: <form action="" method="post"> {{ form_newsletter }} <input type="submit" name="newsletter_sub" value="Subscribe" /> <input type="submit" name="newsletter_unsub" value="Unsubscribe" /> </form> I have also class form: class NewsletterForm(forms.ModelForm): class Meta: model = Newsletter fields = ('email',) I must write my own clean_email method and I need to know by which button was form submited. But the value of submit buttons aren't in self.cleaned_data dictionary. Could I get values of buttons otherwise?
Eg: if 'newsletter_sub' in request.POST: # do subscribe elif 'newsletter_unsub' in request.POST: # do unsubscribe
Python Class Members Initialization
I have just recently battled a bug in Python. It was one of those silly newbie bugs, but it got me thinking about the mechanisms of Python (I'm a long time C++ programmer, new to Python). I will lay out the buggy code and explain what I did to fix it, and then I have a couple of questions... The scenario: I have a class called A, that has a dictionary data member, following is its code (this is simplification of course): class A: dict1={} def add_stuff_to_1(self, k, v): self.dict1[k]=v def print_stuff(self): print(self.dict1) The class using this code is class B: class B: def do_something_with_a1(self): a_instance = A() a_instance.print_stuff() a_instance.add_stuff_to_1('a', 1) a_instance.add_stuff_to_1('b', 2) a_instance.print_stuff() def do_something_with_a2(self): a_instance = A() a_instance.print_stuff() a_instance.add_stuff_to_1('c', 1) a_instance.add_stuff_to_1('d', 2) a_instance.print_stuff() def do_something_with_a3(self): a_instance = A() a_instance.print_stuff() a_instance.add_stuff_to_1('e', 1) a_instance.add_stuff_to_1('f', 2) a_instance.print_stuff() def __init__(self): self.do_something_with_a1() print("---") self.do_something_with_a2() print("---") self.do_something_with_a3() Notice that every call to do_something_with_aX() initializes a new "clean" instance of class A, and prints the dictionary before and after the addition. The bug (in case you haven't figured it out yet): >>> b_instance = B() {} {'a': 1, 'b': 2} --- {'a': 1, 'b': 2} {'a': 1, 'c': 1, 'b': 2, 'd': 2} --- {'a': 1, 'c': 1, 'b': 2, 'd': 2} {'a': 1, 'c': 1, 'b': 2, 'e': 1, 'd': 2, 'f': 2} In the second initialization of class A, the dictionaries are not empty, but start with the contents of the last initialization, and so forth. I expected them to start "fresh". What solves this "bug" is obviously adding: self.dict1 = {} In the __init__ constructor of class A. However, that made me wonder: What is the meaning of the "dict1 = {}" initialization at the point of dict1's declaration (first line in class A)? It is meaningless? What's the mechanism of instantiation that causes copying the reference from the last initialization? If I add "self.dict1 = {}" in the constructor (or any other data member), how does it not affect the dictionary member of previously initialized instances? EDIT: Following the answers I now understand that by declaring a data member and not referring to it in the __init__ or somewhere else as self.dict1, I'm practically defining what's called in C++/Java a static data member. By calling it self.dict1 I'm making it "instance-bound".
What you keep referring to as a bug is the documented, standard behavior of Python classes. Declaring a dict outside of __init__ as you initially did is declaring a class-level variable. It is only created once at first, whenever you create new objects it will reuse this same dict. To create instance variables, you declare them with self in __init__; its as simple as that.
Convert unicode codepoint to UTF8 hex in python
I want to convert a number of unicode codepoints read from a file to their UTF8 encoding. e.g I want to convert the string 'FD9B' to the string 'EFB69B'. I can do this manually using string literals like this: u'\uFD9B'.encode('utf-8') but I cannot work out how to do it programatically.
Use the built-in function unichr() to convert the number to character, then encode that: >>> unichr(int('fd9b', 16)).encode('utf-8') '\xef\xb6\x9b' This is the string itself. If you want the string as ASCII hex, you'd need to walk through and convert each character c to hex, using hex(ord(c)) or similar.
Why is looping over range() in Python faster than using a while loop?
The other day I was doing some Python benchmarking and I came across something interesting. Below are two loops that do more or less the same thing. Loop 1 takes about twice as long as loop 2 to execute. Loop 1: int i = 0 while i < 100000000: i += 1 Loop 2: for n in range(0,100000000): pass Why is the first loop so much slower? I know it's a trivial example but it's piqued my interest. Is there something special about the range() function that makes it more efficient than incrementing a variable the same way?
see the disassembly of python byte code, you may get a more concrete idea use while loop: 1 0 LOAD_CONST 0 (0) 3 STORE_NAME 0 (i) 2 6 SETUP_LOOP 28 (to 37) >> 9 LOAD_NAME 0 (i) # <- 12 LOAD_CONST 1 (100000000) # <- 15 COMPARE_OP 0 (<) # <- 18 JUMP_IF_FALSE 14 (to 35) # <- 21 POP_TOP # <- 3 22 LOAD_NAME 0 (i) # <- 25 LOAD_CONST 2 (1) # <- 28 INPLACE_ADD # <- 29 STORE_NAME 0 (i) # <- 32 JUMP_ABSOLUTE 9 # <- >> 35 POP_TOP 36 POP_BLOCK The loop body has 10 op use range: 1 0 SETUP_LOOP 23 (to 26) 3 LOAD_NAME 0 (range) 6 LOAD_CONST 0 (0) 9 LOAD_CONST 1 (100000000) 12 CALL_FUNCTION 2 15 GET_ITER >> 16 FOR_ITER 6 (to 25) # <- 19 STORE_NAME 1 (n) # <- 2 22 JUMP_ABSOLUTE 16 # <- >> 25 POP_BLOCK >> 26 LOAD_CONST 2 (None) 29 RETURN_VALUE The loop body has 3 op The time to run C code is much shorter than intepretor and can be ignored.
Populating a list/array by index in Python?
Is this possible: myList = [] myList[12] = 'a' myList[22] = 'b' myList[32] = 'c' myList[42] = 'd' When I try, I get: # IndexError: list assignment index out of range #
You'll have to pre-fill it with something (e.g. 0 or None) before you can index it: myList = [None] * 100 # Create list of 100 'None's myList[12] = 'a' # etc. Alternatively, use a dict instead of a list, as Alex Martelli suggested.
Loop backwards using indices in Python?
I am trying to loop from 100 to 0. How do I do this in Python? for i in range (100,0) doesn't work.
Try range(100,-1,-1), the 3rd argument being the increment to use (documented here).
In Python, How Do You Filter a String Such That Only Characters in Your List Are Returned?
Imagine a string, like 'Agh#$%#%2341- -!zdrkfd' and I only wish to perform some operating on it such that only the lowercase letters are returned (as an example), which in this case would bring 'ghzdrkfd'. How do you do this in Python? The obvious way would be to create a list, of characters, 'a' through 'z', then iterate over the characters in my string and build a new string, character by character, of those in my list only. This seems primitive. I was wondering if regular expressions are appropriate. Replacing unwanted characters seems problematic and I tend to prefer whitelisting over blacklisting. The .match function does not seem appropriate. I have looked over the appropriate page on the Python site, but have not found a method which seems to fit. If regular expressions are not appropriate and the correct approach is looping, is there a simple function which "explodes" a string into a list? Or am I just hitting another for loop there?
If you are looking for efficiency. Using the translate function is the fastest you can get. It can be used to quickly replace characters and/or delete them. import string delete_table = string.maketrans( string.ascii_lowercase, ' ' * len(string.ascii_lowercase) ) table = string.maketrans('', '') "Agh#$%#%2341- -!zdrkfd".translate(table, delete_table) In python 2.6: you don't need the second table anymore import string delete_table = string.maketrans( string.ascii_lowercase, ' ' * len(string.ascii_lowercase) ) "Agh#$%#%2341- -!zdrkfd".translate(None, delete_table) This is method is way faster than any other. Of course you need to store the delete_table somewhere and use it. But even if you don't store it and build it every time, it is still going to be faster than other suggested methods so far. To confirm my claims here are the results: for i in xrange(10000): ''.join(c for c in s if c.islower()) real 0m0.189s user 0m0.176s sys 0m0.012s While running the regular expression solution: for i in xrange(10000): re.sub(r'[^a-z]', '', s) real 0m0.172s user 0m0.164s sys 0m0.004s [Upon request] If you pre-compile the regular expression: r = re.compile(r'[^a-z]') for i in xrange(10000): r.sub('', s) real 0m0.166s user 0m0.144s sys 0m0.008s Running the translate method the same number of times took: real 0m0.075s user 0m0.064s sys 0m0.012s
Pythonic way to split comma separated numbers into pairs
I'd like to split a comma separated value into pairs: >>> s = '0,1,2,3,4,5,6,7,8,9' >>> pairs = # something pythonic >>> pairs [(0, 1), (2, 3), (4, 5), (6, 7), (8, 9)] What would # something pythonic look like? How would you detect and handle a string with an odd set of numbers?
Something like: zip(t[::2], t[1::2]) Full example: >>> s = ','.join(str(i) for i in range(10)) >>> s '0,1,2,3,4,5,6,7,8,9' >>> t = [int(i) for i in s.split(',')] >>> t [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> p = zip(t[::2], t[1::2]) >>> p [(0, 1), (2, 3), (4, 5), (6, 7), (8, 9)] >>> If the number of items is odd, the last element will be ignored. Only complete pairs will be included.
Django: Overriding __init__ for Custom Forms
I am making a custom form object in Django which has an overrided __init__ method. The purpose of overriding the method is to dynamically generate drop-down boxes based on the new parameters. For example, class TicketForm(forms.Form): Type = Type.GetTicketTypeField() def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None, initial=None, label_suffix=':', empty_permitted=False, ticket=None): if ticket: self.__class__.State = State.GetTicketStateField(ticket.Type) super(forms.BaseForm, self ).__init__(data=data, files=files, auto_id=auto_id, prefix=prefix, initial=initial, label_suffix=label_suffix, empty_permitted=empty_permitted) This solution does not work. It appears that the fields are created before the __init__ is called. I would assume this problem would be pretty common. What would be the Django way of handling these classes of problems.
You can dynamically modify your form by using the self.fields dict. Something like this may work for you: class TicketForm(forms.Form): Type = Type.GetTicketTypeField() def __init__(self, ticket, *args, **kwargs): super(TicketForm, self).__init__(*args, **kwargs) self.fields['state'] = State.GetTicketStateField(ticket.Type)
Python vs. C# Twitter API libraries
I have experience with both .NET(5yrs) and Python(1yr) and I want to create a simple web project with Twitter as the backbone. I have experience with AppEngine, and have always wanted to try Azure. I'm going to make extensive use of sending and parsing tweets from lots of users at a time, and since I've set a short deadline for this I'd like to take the shortest path possible. So does anyone have any experience with both of these, or have any advice? A quick look at the twitter API libraries(http://apiwiki.twitter.com/Libraries) gave me this for python: python-twitter by DeWitt Clinton. This library provides a pure Python interface for the Twitter API. python-twyt by Andrew Price. BSD licensed Twitter API interface library and command line client. twitty-twister by Dustin Sallings. A Twisted interface to Twitter. and this for C#: Yedda Twitter Library by Yedda. Every Twitter API method has an equivalent .NET method in this wrapper library. TwitterooCore API by Eric Willis/RareEdge Design Group. Binary .NET library that can be used in any .NET project. Twitterizer originally by DigitallyBorn, but now open source. Written for .NET 2.0. tweet# by Daniel Crenna. "100% coverage of the REST and Search APIs".
The best advice is to use whatever language you are most comfortable with. Myself and a colleague have recently re-written our Twitter web-app's entire back-end with a C# service, and the decision for us came down to which library best suited the purpose. A number of the libraries have varying 'features', some are more complete than others: we decided which to select based purely on trying them out, and seeing which were the best-optimised, and made our job easiest. I would make a recommendation for a C# library, but the playing field changes so very quickly, and we've changed implementations a couple of times, as Twitter has deprecated various aspects of their API, and some have updated more quickly than others.
Visual Editor for Django Templates?
Is there a tool out there for visually building Django templates? Thanks
I haven't tried it personally, but a co-worker uses the free ActiveState Komodo Edit to edit Django templates, and the page I linked claims support for Django template editing. There's also netbeans-django that is building a Django plugin for Netbeans, but no idea how complete or how well it works. I've read that TextMate has a "Django bundle" for editing code and templates if you're on a Mac.
Pythonic Way to Initialize (Complex) Static Data Members
I have a class with a complex data member that I want to keep "static". I want to initialize it once, using a function. How Pythonic is something like this: def generate_data(): ... do some analysis and return complex object e.g. list ... class Coo: data_member = generate_data() ... rest of class code ... The function generate_data takes a long while to complete and returns data that remains constant in the scope of a running program. I don't want it to run every time class Coo is instantiated. Also, to verify, as long as I don't assign anything to data_member in __init__, it will remain "static"? What if a method in Coo appends some value to data_member (assuming it's a list) - will this addition be available to the rest of the instances? Thanks
You're right on all counts. data_member will be created once, and will be available to all instances of coo. If any instance modifies it, that modification will be visible to all other instances. Here's an example that demonstrates all this, with its output shown at the end: def generate_data(): print "Generating" return [1,2,3] class coo: data_member = generate_data() def modify(self): self.data_member.append(4) def display(self): print self.data_member x = coo() y = coo() y.modify() x.display() # Output: # Generating # [1, 2, 3, 4]
Python's most efficient way to choose longest string in list?
I have a list of variable length and am trying to find a way to test if the list item currently being evaluated is the longest string contained in the list. And I am using Python 2.6.1 For example: mylist = ['123','123456','1234'] for each in mylist: if condition1: do_something() elif ___________________: #else if each is the longest string contained in mylist: do_something_else() I'm brand new to python and I'm sure I'm just having a brain fart. Surely there's a simple list comprehension that's short and elegant that I'm overlooking? Thanks!
From the Python documentation itself, you can use max: >>> mylist = ['123','123456','1234'] >>> print max(mylist, key=len) 123456
Python: load words from file into a set
I have a simple text file with several thousands of words, each in its own line, e.g. aardvark hello piper I use the following code to load the words into a set (I need the list of words to test membership, so set is the data structure I chose): my_set = set(open('filename.txt')) The above code produces a set with the following entries (each word is followed by a space and new-line character: ("aardvark \n", "hello \n", "piper \n") What's the simplest way to load the file into a set but get rid of the space and \n? Thanks
The strip() method of strings removes whitespace from both ends. set(line.strip() for line in open('filename.txt'))
Read .mat files in Python
Does anyone have successful experience reading binary Matlab .mat files in Python? (I've seen that scipy has alleged support for reading .mat files, but I'm unsuccessful with it. I installed scipy version 0.7.0, and I can't find the loadmat() method)
Silly me. Forgot to import io... import scipy.io mat = scipy.io.loadmat('file.mat')
Python - install script to system
how can I make setup.py file for my own script? I have to make my script global. (add it to /usr/bin) so I could run it from console just type: scriptName arguments. OS: Linux. EDIT: Now my script is installable, but how can i make it global? So that i could run it from console just name typing.
EDIT: This answer deals only with installing executable scripts into /usr/bin. I assume you have basic knowledge on how setup.py files work. Create your script and place it in your project like this: yourprojectdir/ setup.py scripts/ myscript.sh In your setup.py file do this: from setuptools import setup # you may need setuptools instead of distutils setup( # basic stuff here scripts = [ 'scripts/myscript.sh' ] ) Then type python setup.py install Basically that's it. There's a chance that your script will land not exactly in /usr/bin, but in some other directory. If this is the case, type python setup.py install --help and search for --install-scripts parameter and friends.
How do I get 'real-time' information back from a subprocess.Popen in python (2.5)
I'd like to use the subprocess module in the following way: create a new process that potentially takes a long time to execute. capture stdout (or stderr, or potentially both, either together or separately) Process data from the subprocess as it comes in, perhaps firing events on every line received (in wxPython say) or simply printing them out for now. I've created processes with Popen, but if I use communicate() the data comes at me all at once, once the process has terminated. If I create a separate thread that does a blocking readline() of myprocess.stdout (using stdout = subprocess.PIPE) I don't get any lines with this method either, until the process terminates. (no matter what I set as bufsize) Is there a way to deal with this that isn't horrendous, and works well on multiple platforms?
Update with code that appears not to work (on windows anyway) class ThreadWorker(threading.Thread): def __init__(self, callable, *args, **kwargs): super(ThreadWorker, self).__init__() self.callable = callable self.args = args self.kwargs = kwargs self.setDaemon(True) def run(self): try: self.callable(*self.args, **self.kwargs) except wx.PyDeadObjectError: pass except Exception, e: print e if __name__ == "__main__": import os from subprocess import Popen, PIPE def worker(pipe): while True: line = pipe.readline() if line == '': break else: print line proc = Popen("python subprocess_test.py", shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE) stdout_worker = ThreadWorker(worker, proc.stdout) stderr_worker = ThreadWorker(worker, proc.stderr) stdout_worker.start() stderr_worker.start() while True: pass
How to print a list, dict or collection of objects, in Python
I have written a class in python that implements __str__(self) but when I use print on a list containing instances of this class, I just get the default output <__main__.DSequence instance at 0x4b8c10>. Is there another magic function I need to implement to get this to work, or do I have to write a custom print function? Here's the class: class DSequence: def __init__(self, sid, seq): """Sequence object for a dummy dna string""" self.sid = sid self.seq = seq def __iter__(self): return self def __str__(self): return '[' + str(self.sid) + '] -> [' + str(self.seq) + ']' def next(self): if self.index == 0: raise StopIteration self.index = self.index - 1 return self.seq[self.index]
Yes, you need to use __repr__. A quick example of its behavior: >>> class Foo: ... def __str__(self): ... return '__str__' ... def __repr__(self): ... return '__repr__' ... >>> bar = Foo() >>> bar __repr__ >>> print bar __str__ >>> repr(bar) '__repr__' >>> str(bar) '__str__' However, if you don't define a __str__, it falls back to __repr__, although this isn't recommended: >>> class Foo: ... def __repr__(self): ... return '__repr__' ... >>> bar = Foo() >>> bar __repr__ >>> print bar __repr__ All things considered, as the manual recommends, __repr__ is used for debugging and should return something representative of the object.
How can I create an local webserver for my python scripts?
I'm looking to use a local webserver to run a series of python scripts for the user. For various unavoidable reasons, the python script must run locally, not on a server. As a result, I'll be using HTML+browser as the UI, which I'm comfortable with, for the front end. I've been looking, therefore, for a lightweight web server that can execute python scripts, sitting in the background on a machine, ideally as a Windows service. Security and extensibility are not high priorities as it's all running internally on a small network. Should I run a native python webserver as a Windows service (in which case, how)? Or is it just as easy to install Apache onto the user's machine and run as CGI? Since this is all local, performance is not an issue either. Or am I missing something obvious?
Don't waste a lot of time creating Windows service. Don't waste a lot of time on Windows Apache. Just make a Python service that responds to HTTP requests. Look at http://docs.python.org/library/basehttpserver.html Python offers an HTTP server that you can extend with your server-side methods. Look at http://docs.python.org/library/wsgiref.html Python offers a WSGI reference implementation that makes your server easy and standards-compliant. Also http://fragments.turtlemeat.com/pythonwebserver.php "I'm trying to avoid making the user run python stuff from the command prompt." I don't see how clicking a web page is any different from clicking desktop icons. Starting a web server based on Python is relatively easy, once you have the web server. First, build the server. Later, you can make sure the server starts. Let's look at some ways. Your user can't use a random browser to open your local page. They need a bookmark to launch "localhost:8000/myspecialserverinsteadofthedestop/" That bookmark can be a .BAT file that (1) runs the server, (2) runs firefox with the proper initial URL. You can put the server in the user's start-this menu. You can make your Python program a windows "service".
What's the simplest way to extend a numpy array in 2 dimensions?
I have a 2d array that looks like this: XX xx What's the most efficient way to add an extra row and column: xxy xxy yyy For bonus points, I'd like to also be able to knock out single rows and columns, so for example in the matrix below I'd like to be able to knock out all of the a's leaving only the x's - specifically I'm trying to delete the nth row and the nth column at the same time - and I want to be able to do this as quickly as possible: xxaxx xxaxx aaaaa xxaxx xxaxx
The shortest in terms of lines of code i can think of is for the first question. >>> import numpy as np >>> p = np.array([[1,2],[3,4]]) >>> p = np.append(p, [[5,6]], 0) >>> p = np.append(p, [[7],[8],[9]],1) >>> p array([[1, 2, 7], [3, 4, 8], [5, 6, 9]]) And the for the second question p = np.array(range(20)) >>> p.shape = (4,5) >>> p array([[ 0, 1, 2, 3, 4], [ 5, 6, 7, 8, 9], [10, 11, 12, 13, 14], [15, 16, 17, 18, 19]]) >>> n = 2 >>> p = np.append(p[:n],p[n+1:],0) >>> p = np.append(p[...,:n],p[...,n+1:],1) >>> p array([[ 0, 1, 3, 4], [ 5, 6, 8, 9], [15, 16, 18, 19]])
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?
It's because __lt__() and related comparison methods are quite commonly used indirectly in list sorts and such. Sometimes the algorithm will choose to try another way or pick a default winner. Raising an exception would break out of the sort unless caught, whereas NotImplemented doesn't get raised and can be used in further tests. http://jcalderone.livejournal.com/32837.html To summarise that link: "NotImplemented signals to the runtime that it should ask someone else to satisfy the operation. In the expression a == b, if a.__eq__(b) returns NotImplemented, then Python tries b.__eq__(a). If b knows enough to return True or False, then the expression can succeed. If it doesn't, then the runtime will fall back to the built-in behavior (which is based on identity for == and !=)."
Windows cmd encoding change causes Python crash
First I change Windows CMD encoding to utf-8 and run Python interpreter: chcp 65001 python Then I try to print a unicode sting inside it and when i do this Python crashes in a peculiar way (I just get a cmd prompt in the same window). >>> import sys >>> print u'ëèæîð'.encode(sys.stdin.encoding) Any ideas why it happens and how to make it work? UPD: sys.stdin.encoding returns 'cp65001' UPD2: It just came to me that the issue might be connected with the fact that utf-8 uses multi-byte character set (kcwu made a good point on that). I tried running the whole example with 'windows-1250' and got 'ëeaî?'. Windows-1250 uses single-character set so it worked for those characters it understands. However I still have no idea how to make 'utf-8' work here. UPD3: Oh, I found out it is a known Python bug. I guess what happens is that Python copies the cmd encoding as 'cp65001 to sys.stdin.encoding and tries to apply it to all the input. Since it fails to understand 'cp65001' it crashes on any input that contains non-ascii characters.
Here's how to alias cp65001 to UTF-8 without changing encodings\aliases.py: import codecs codecs.register(lambda name: codecs.lookup('utf-8') if name == 'cp65001' else None) (IMHO, don't pay any attention to the silliness about cp65001 not being identical to UTF-8 at http://bugs.python.org/issue6058#msg97731 . It's intended to be the same, even if Microsoft's codec has some minor bugs.) Here is some code (written for Tahoe-LAFS, tahoe-lafs.org) that makes console output work regardless of the chcp code page, and also reads Unicode command-line arguments. Credit to Michael Kaplan for the idea behind this solution. If stdout or stderr are redirected, it will output UTF-8. If you want a Byte Order Mark, you'll need to write it explicitly. [Edit: This version uses WriteConsoleW instead of the _O_U8TEXT flag in the MSVC runtime library, which is buggy. WriteConsoleW is also buggy relative to the MS documentation, but less so.] import sys if sys.platform == "win32": import codecs from ctypes import WINFUNCTYPE, windll, POINTER, byref, c_int from ctypes.wintypes import BOOL, HANDLE, DWORD, LPWSTR, LPCWSTR, LPVOID original_stderr = sys.stderr # If any exception occurs in this code, we'll probably try to print it on stderr, # which makes for frustrating debugging if stderr is directed to our wrapper. # So be paranoid about catching errors and reporting them to original_stderr, # so that we can at least see them. def _complain(message): print >>original_stderr, message if isinstance(message, str) else repr(message) # Work around <http://bugs.python.org/issue6058>. codecs.register(lambda name: codecs.lookup('utf-8') if name == 'cp65001' else None) # Make Unicode console output work independently of the current code page. # This also fixes <http://bugs.python.org/issue1602>. # Credit to Michael Kaplan <http://www.siao2.com/2010/04/07/9989346.aspx> # and TZOmegaTZIOY # <http://stackoverflow.com/questions/878972/windows-cmd-encoding-change-causes-python-crash/1432462#1432462>. try: # <http://msdn.microsoft.com/en-us/library/ms683231(VS.85).aspx> # HANDLE WINAPI GetStdHandle(DWORD nStdHandle); # returns INVALID_HANDLE_VALUE, NULL, or a valid handle # # <http://msdn.microsoft.com/en-us/library/aa364960(VS.85).aspx> # DWORD WINAPI GetFileType(DWORD hFile); # # <http://msdn.microsoft.com/en-us/library/ms683167(VS.85).aspx> # BOOL WINAPI GetConsoleMode(HANDLE hConsole, LPDWORD lpMode); GetStdHandle = WINFUNCTYPE(HANDLE, DWORD)(("GetStdHandle", windll.kernel32)) STD_OUTPUT_HANDLE = DWORD(-11) STD_ERROR_HANDLE = DWORD(-12) GetFileType = WINFUNCTYPE(DWORD, DWORD)(("GetFileType", windll.kernel32)) FILE_TYPE_CHAR = 0x0002 FILE_TYPE_REMOTE = 0x8000 GetConsoleMode = WINFUNCTYPE(BOOL, HANDLE, POINTER(DWORD))(("GetConsoleMode", windll.kernel32)) INVALID_HANDLE_VALUE = DWORD(-1).value def not_a_console(handle): if handle == INVALID_HANDLE_VALUE or handle is None: return True return ((GetFileType(handle) & ~FILE_TYPE_REMOTE) != FILE_TYPE_CHAR or GetConsoleMode(handle, byref(DWORD())) == 0) old_stdout_fileno = None old_stderr_fileno = None if hasattr(sys.stdout, 'fileno'): old_stdout_fileno = sys.stdout.fileno() if hasattr(sys.stderr, 'fileno'): old_stderr_fileno = sys.stderr.fileno() STDOUT_FILENO = 1 STDERR_FILENO = 2 real_stdout = (old_stdout_fileno == STDOUT_FILENO) real_stderr = (old_stderr_fileno == STDERR_FILENO) if real_stdout: hStdout = GetStdHandle(STD_OUTPUT_HANDLE) if not_a_console(hStdout): real_stdout = False if real_stderr: hStderr = GetStdHandle(STD_ERROR_HANDLE) if not_a_console(hStderr): real_stderr = False if real_stdout or real_stderr: # BOOL WINAPI WriteConsoleW(HANDLE hOutput, LPWSTR lpBuffer, DWORD nChars, # LPDWORD lpCharsWritten, LPVOID lpReserved); WriteConsoleW = WINFUNCTYPE(BOOL, HANDLE, LPWSTR, DWORD, POINTER(DWORD), LPVOID)(("WriteConsoleW", windll.kernel32)) class UnicodeOutput: def __init__(self, hConsole, stream, fileno, name): self._hConsole = hConsole self._stream = stream self._fileno = fileno self.closed = False self.softspace = False self.mode = 'w' self.encoding = 'utf-8' self.name = name self.flush() def isatty(self): return False def close(self): # don't really close the handle, that would only cause problems self.closed = True def fileno(self): return self._fileno def flush(self): if self._hConsole is None: try: self._stream.flush() except Exception as e: _complain("%s.flush: %r from %r" % (self.name, e, self._stream)) raise def write(self, text): try: if self._hConsole is None: if isinstance(text, unicode): text = text.encode('utf-8') self._stream.write(text) else: if not isinstance(text, unicode): text = str(text).decode('utf-8') remaining = len(text) while remaining: n = DWORD(0) # There is a shorter-than-documented limitation on the # length of the string passed to WriteConsoleW (see # <http://tahoe-lafs.org/trac/tahoe-lafs/ticket/1232>. retval = WriteConsoleW(self._hConsole, text, min(remaining, 10000), byref(n), None) if retval == 0 or n.value == 0: raise IOError("WriteConsoleW returned %r, n.value = %r" % (retval, n.value)) remaining -= n.value if not remaining: break text = text[n.value:] except Exception as e: _complain("%s.write: %r" % (self.name, e)) raise def writelines(self, lines): try: for line in lines: self.write(line) except Exception as e: _complain("%s.writelines: %r" % (self.name, e)) raise if real_stdout: sys.stdout = UnicodeOutput(hStdout, None, STDOUT_FILENO, '<Unicode console stdout>') else: sys.stdout = UnicodeOutput(None, sys.stdout, old_stdout_fileno, '<Unicode redirected stdout>') if real_stderr: sys.stderr = UnicodeOutput(hStderr, None, STDERR_FILENO, '<Unicode console stderr>') else: sys.stderr = UnicodeOutput(None, sys.stderr, old_stderr_fileno, '<Unicode redirected stderr>') except Exception as e: _complain("exception %r while fixing up sys.stdout and sys.stderr" % (e,)) # While we're at it, let's unmangle the command-line arguments: # This works around <http://bugs.python.org/issue2128>. GetCommandLineW = WINFUNCTYPE(LPWSTR)(("GetCommandLineW", windll.kernel32)) CommandLineToArgvW = WINFUNCTYPE(POINTER(LPWSTR), LPCWSTR, POINTER(c_int))(("CommandLineToArgvW", windll.shell32)) argc = c_int(0) argv_unicode = CommandLineToArgvW(GetCommandLineW(), byref(argc)) argv = [argv_unicode[i].encode('utf-8') for i in xrange(0, argc.value)] if not hasattr(sys, 'frozen'): # If this is an executable produced by py2exe or bbfreeze, then it will # have been invoked directly. Otherwise, unicode_argv[0] is the Python # interpreter, so skip that. argv = argv[1:] # Also skip option arguments to the Python interpreter. while len(argv) > 0: arg = argv[0] if not arg.startswith(u"-") or arg == u"-": break argv = argv[1:] if arg == u'-m': # sys.argv[0] should really be the absolute path of the module source, # but never mind break if arg == u'-c': argv[0] = u'-c' break # if you like: sys.argv = argv Finally, it is possible to grant ΤΖΩΤΖΙΟΥ's wish to use DejaVu Sans Mono, which I agree is an excellent font, for the console. You can find information on the font requirements and how to add new fonts for the windows console in the 'Necessary criteria for fonts to be available in a command window' Microsoft KB But basically, on Vista (probably also Win7): under HKEY_LOCAL_MACHINE_SOFTWARE\Microsoft\Windows NT\CurrentVersion\Console\TrueTypeFont, set "0" to "DejaVu Sans Mono"; for each of the subkeys under HKEY_CURRENT_USER\Console, set "FaceName" to "DejaVu Sans Mono". On XP, check the thread 'Changing Command Prompt fonts?' in LockerGnome forums.
How to install python-dateutil on Windows?
I'm trying to convert some date/times to UTC, which I thought would be dead simple in Python - batteries included, right? Well, it would be simple except that Python (2.6) doesn't include any tzinfo classes. No problem, a quick search turns up python-dateutil which should do exactly what I need. The problem is that I need to install it on Windows. I was able to upack the .tar.gz2 distribution using 7-zip, but now I'm left with a collection of files and no guidance on how to proceed. When I try to run setup.py I get the error "No module named setuptools".
If dateutil is missing install it via: pip install python-dateutil Or on Ubuntu: sudo apt-get install python-dateutil
How to ignore deprecation warnings in Python
I keep getting this : DeprecationWarning: integer argument expected, got float How do I make this message go away? Is there a way to avoid warnings in Python?
I had these: /home/eddyp/virtualenv/lib/python2.6/site-packages/Twisted-8.2.0-py2.6-linux-x86_64.egg/twisted/persisted/sob.py:12: DeprecationWarning: the md5 module is deprecated; use hashlib instead import os, md5, sys /home/eddyp/virtualenv/lib/python2.6/site-packages/Twisted-8.2.0-py2.6-linux-x86_64.egg/twisted/python/filepath.py:12: DeprecationWarning: the sha module is deprecated; use the hashlib module instead import sha Fixed it with: import warnings with warnings.catch_warnings(): warnings.filterwarnings("ignore",category=DeprecationWarning) import md5, sha yourcode() Now you still get all the other DeprecationWarnings, but not the ones caused by import md5, sha
logging with filters
I'm using Logging (import logging) to log messages. Within 1 single module, I am logging messages at the debug level (my_logger.debug('msg')); Some of these debug messages come from function_a() and others from function_b(); I'd like to be able to enable/disable logging based on whether they come from a or from b; I'm guessing that I have to use Logging's filtering mechanism. Can someone please show me how the code below would need to be instrumented to do what I want? thanks. import logging logger= logging.getLogger( "module_name" ) def function_a( ... ): logger.debug( "a message" ) def function_b( ... ): logger.debug( "another message" ) if __name__ == "__main__": logging.basicConfig( stream=sys.stderr, level=logging.DEBUG ) #don't want function_a()'s noise -> .... #somehow filter-out function_a's logging function_a() #don't want function_b()'s noise -> .... #somehow filter-out function_b's logging function_b() If I scaled this simple example to more modules and more funcs per module, I'd be concerned about lots of loggers; Can I keep it down to 1 logger per module? Note that the log messages are "structured", i.e. if the function(s) logging it are doing some parsing work, they all contain a prefix logger.debug("parsing: xxx") - can I somehow with a single line just shut-off all "parsing" messages (regardless of the module/function emitting the message?)
Just implement a subclass of logging.Filter: http://docs.python.org/library/logging.html#filter-objects. It will have one method, filter(record), that examines the log record and returns True to log it or False to discard it. Then you can install the filter on either a Logger or a Handler by calling its addFilter(filter) method. Example: class NoParsingFilter(logging.Filter): def filter(self, record): return not record.getMessage().startswith('parsing') logger.addFilter(NoParsingFilter()) Or something like that, anyway.
How to strip html/javascript from text input in django
What is the easiest way to strip all html/javascript from a string?
If you want to strip tags in the python, you can use: from django.utils.html import strip_tags strip_tags(string_value) EDIT: If you are using strip_tags, than you should update your django. Because security researchers found a way in order to bypass strip_tags . Further information : http://www.mehmetince.net/django-strip_tags-bypass-vulnerability-exploit/
Can modules have properties the same way that objects can?
With python properties, I can make it such that obj.y calls a function rather than just returning a value. Is there a way to do this with modules? I have a case where I want module.y to call a function, rather than just returning the value stored there.
Only instances of new-style classes can have properties. You can make Python believe such an instance is a module by stashing it in sys.modules[thename] = theinstance. So, for example, your m.py module file could be: import sys class _M(object): def __init__(self): self.c = 0 def afunction(self): self.c += 1 return self.c y = property(afunction) sys.modules[__name__] = _M() Edited: removed an implicit dependency on globals (had nothing to do with the point of the example but did confuse things by making the original code fail!).
How to redirect the output of .exe to a file in python?
In a script , I want to run a .exe with some command line parameters as "-a",and then redirect the standard output of the program to a file? How can I implement that?
You can redirect directly to a file using subprocess. import subprocess with open('output.txt', 'w') as output_f: p = subprocess.Popen('Text/to/execute with-arg', stdout=output_f, stderr=output_f)
What is the reason for performing a double fork when creating a daemon?
I'm trying to create a daemon in python. I've found the following question, which has some good resources in it which I am currently following, but I'm curious as to why a double fork is necessary. I've scratched around google and found plenty of resources declaring that one is necessary, but not why. Some mention that it is to prevent the daemon from acquiring a controlling terminal. How would it do this without the second fork? What are the repercussions?
I was trying to understand the double fork and stumbled upon this question here. After a lot of research this is what I figured out. Hopefully it will help clarify things better for anyone who has the same question. In Unix every process belongs to a group which in turn belongs to a session. Here is the hierarchy… Session (SID) → Process Group (PGID) → Process (PID) The first process in the process group becomes the process group leader and the first process in the session becomes the session leader. Every session can have one TTY associated with it. Only a session leader can take control of a TTY. For a process to be truly daemonized (ran in the background) we should ensure that the session leader is killed so that there is no possibility of the session ever taking control of the TTY. I ran Sander Marechal's python example daemon program from this site on my Ubuntu. Here are the results with my comments. 1. `Parent` = PID: 28084, PGID: 28084, SID: 28046 2. `Fork#1` = PID: 28085, PGID: 28084, SID: 28046 3. `Decouple#1`= PID: 28085, PGID: 28085, SID: 28085 4. `Fork#2` = PID: 28086, PGID: 28085, SID: 28085 Note that the process is the session leader after Decouple#1, because it's PID = SID. It could still take control of a TTY. Note that Fork#2 is no longer the session leader PID != SID. This process can never take control of a TTY. Truly daemonized. I personally find terminology fork-twice to be confusing. A better idiom might be fork-decouple-fork. Additional links of interest: Unix processes - http://www.win.tue.nl/~aeb/linux/lk/lk-10.html
How to tell if a class is descended from another class
I have a function that accepts a class (not an instance) and, depending on whether or not it's a specific class or a subclass of that, I need to pass it in to one of two other (third-party) factory functions. (To forestall any objections, I'm aware this is not very Pythonic, but I'm dependent on what the third-party library accepts.) issubclass only works for instances, not class objects themselves. I suppose I could instantiate the class, do issubclass and throw away the instance, but that seems a bit wasteful. Here's what I'm doing at the moment, relying on the built-in mro attribute to tell if a certain class is in the list of ancestors of my class. Is this safe, and is there any better way of doing it? if GenericClass in myclass.__mro__: result = generic_factory(myclass) else: result = other_factory(myclass)
issubclass only works for instances, not class objects themselves. It works fine for me: >>> class test(object):pass ... >>> issubclass(test,object) True
How to use dynamic foreignkey in Django?
I want to connect a single ForeignKey to two different models. For example: I have two models named Casts and Articles, and a third model, Faves, for favoriting either of the other models. How can I make the ForeignKey dynamic? class Articles(models.Model): title = models.CharField(max_length=100) body = models.TextField() class Casts(models.Model): title = models.CharField(max_length=100) body = models.TextField() class Faves(models.Model): post = models.ForeignKey(**---CASTS-OR-ARTICLES---**) user = models.ForeignKey(User,unique=True) Is this possible?
Here is how I do it: from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes import fields class Photo(models.Model): picture = models.ImageField(null=True, upload_to='./images/') caption = models.CharField(_("Optional caption"),max_length=100,null=True, blank=True) content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = fields.GenericForeignKey('content_type', 'object_id') class Article(models.Model): .... images = fields.GenericRelation(Photo) You would add something like content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = fields.GenericForeignKey('content_type', 'object_id') to Faves and fields.GenericRelation(Faves) to Article and Cast contenttypes docs
Rendering JSON objects using a Django template after an Ajax call
I've been trying to understand what's the optimal way to do Ajax in Django. By reading stuff here and there I gathered that the common process is: formulate your Ajax call using some JavaScript library (e.g., jQuery), set up a URL pattern in Django that catches the call and passes it to a view function in the Python view function retrieve the objects you are interested in and send them back to the client in JSON format or similar (by using the built in serializer module, or simplejson) define a callback function in JavaScript that receives the JSON data and parses them, so to create whatever HTML is needed to be displayed. Finally, the JavaScript script puts the HTML wherever it should stay. Now, what I still don't get is how are Django templates related to all of this? Apparently, we're not making use of the power of templates at all. Ideally, I thought it'd be nice to pass back a JSON object and a template name, so that the data could be iterated over and an HTML block is created. But maybe I'm totally wrong here... The only resource I found that goes in this direction is this snippet (769) but I haven't tried it yet. Obviously, what's going to happen in this case is that all the resulting HTML is created on the server side, then passed to the client. The JavaScript-callback function only has to display it in the right place. Does this cause performance problems? If not, even without using the snippet above, why not formatting the HTML directly in the backend using Python instead of the front-end? Many thanks! UPDATE: please use snippet 942 because it is an enhanced version of the one above! I found that the inheritance support works much better this way..
Hey thanks vikingosegundo! I like using decorators too :-). But in the meanwhile I've been following the approach suggested by the snippet I was mentioning above. Only thing, use instead the snippet n. 942 cause it's an improved version of the original one. Here's how it works: Imagine you have a template (e.g., 'subtemplate.html') of whatever size that contains a useful block you can reuse: ........ <div id="results"> {% block results %} {% for el in items %} <li>{{el|capfirst}}</li> {% endfor %} {% endblock %} </div><br /> ........ By importing in your view file the snippet above you can easily reference to any block in your templates. A cool feature is that the inheritance relations among templates are taken into consideration, so if you reference to a block that includes another block and so on, everything should work just fine. So, the ajax-view looks like this: from django.template import loader # downloaded from djangosnippets.com[942] from my_project.snippets.template import render_block_to_string def ajax_view(request): # some random context context = Context({'items': range(100)}) # passing the template_name + block_name + context return_str = render_block_to_string('standard/subtemplate.html', 'results', context) return HttpResponse(return_str)
How to hide "cgi-bin", ".py", etc from my URLs?
Brand new to web design, using python. Got Apache up and running, test python script working in cgi-bin directory. Get valid results when I type in the URL explicitly: ".../cgi-bin/showenv.py" But I don't want the URL to look that way. Here at stackoverflow, for example, the URLs that display in my address bar never have the messy details showing the script that was used to run them. They're clean of cgi-bin, .py, etc. extensions. How do I do that? EDIT: Thanks for responses, every single one helpful, lots to learn. I'm going with URL Rewriting for now; example in the docs looks extremely close to what I actually want to do. But I'm committed to python, so will have to look at WSGI down the road.
The python way of writing web applications is not cgi-bin. It is by using WSGI. WSGI is a standard interface between web servers and Python web applications or frameworks. The PEP 0333 defines it. There are no disadvantages in using it instead of CGI. And you'll gain a lot. Beautiful URLs is just one of the neat things you can do easily. Also, writing a WSGI application means you can deploy on any web server that supports the WSGI interface. Apache does so by using mod_wsgi. You can configure it in apache like that: WSGIScriptAlias /myapp /usr/local/www/wsgi-scripts/myapp.py Then all requests on http://myserver.domain/myapp will go to myapp.py's application callable, including http://myserver.domain/myapp/something/here. example myapp.py: def application(environ, start_response): start_response('200 OK', [('Content-type', 'text/plain')]) return ['Hello World!']
Sending HTML email using Python
How can I send the HTML content in an email using Python? I can send simple text.
From Python v2.6.2 documentation - 19.1.11. email: Examples: Here’s an example of how to create an HTML message with an alternative plain text version: #! /usr/bin/python import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText # me == my email address # you == recipient's email address me = "my@email.com" you = "your@email.com" # Create message container - the correct MIME type is multipart/alternative. msg = MIMEMultipart('alternative') msg['Subject'] = "Link" msg['From'] = me msg['To'] = you # Create the body of the message (a plain-text and an HTML version). text = "Hi!\nHow are you?\nHere is the link you wanted:\nhttp://www.python.org" html = """\ <html> <head></head> <body> <p>Hi!<br> How are you?<br> Here is the <a href="http://www.python.org">link</a> you wanted. </p> </body> </html> """ # Record the MIME types of both parts - text/plain and text/html. part1 = MIMEText(text, 'plain') part2 = MIMEText(html, 'html') # Attach parts into message container. # According to RFC 2046, the last part of a multipart message, in this case # the HTML message, is best and preferred. msg.attach(part1) msg.attach(part2) # Send the message via local SMTP server. s = smtplib.SMTP('localhost') # sendmail function takes 3 arguments: sender's address, recipient's address # and message to send - here it is sent as one string. s.sendmail(me, you, msg.as_string()) s.quit()
django excel xlwt
On a django site, I want to generate an excel file based on some data in the database. I'm thinking of using xlwt, but it only has a method to save the data to a file. How can get the file to the HttpResponse object? Or maybe do you know a better library? I've also found this snippet but it doesn't do what I need. All I want is a way to get the stream from the xlwt object to the response object (without writing to a temporary file)
neat package! i didn't know about this According to the doc, the save(filename_or_stream) method takes either a filename to save on, or a file-like stream to write on. And a Django response object happens to be a file-like stream! so just do xls.save(response). Look the Django docs about generating PDFs with ReportLab to see a similar situation. edit: (adapted from ShawnMilo's comment): def xls_to_response(xls, fname): response = HttpResponse(mimetype="application/ms-excel") response['Content-Disposition'] = 'attachment; filename=%s' % fname xls.save(response) return response then, from your view function, just create the xls object and finish with return xls_to_response(xls,'foo.xls')
Custom ordering in Django
How do you define a specific ordering in Django QuerySets? Specifically, if I have a QuerySet like so: ['a10', 'a1', 'a2']. Regular order (using Whatever.objects.order_by('someField')) will give me ['a1', 'a10', 'a2'], while I am looking for: ['a1', 'a2', 'a10']. What is the proper way to define my own ordering technique?
As far as I'm aware, there's no way to specify database-side ordering in this way as it would be too backend-specific. You may wish to resort to good old-fashioned Python sorting: class Foo(models.Model): name = models.CharField(max_length=128) Foo.objects.create(name='a10') Foo.objects.create(name='a1') Foo.objects.create(name='a2') ordered = sorted(Foo.objects.all(), key=lambda n: (n[0], int(n[1:]))) print ordered # yields a1, a2, 10 If you find yourself needing this kind of sorting a lot, I'd recommend making a custom models.Manager subclass for your model that performs the ordering. Something like: class FooManager(models.Manager): def in_a_number_order(self, *args, **kwargs): qs = self.get_query_set().filter(*args, **kwargs) return sorted(qs, key=lambda n: (n[0], int(n[1:]))) class Foo(models.Model): ... as before ... objects = FooManager() print Foo.objects.in_a_number_order() print Foo.objects.in_a_number_order(id__in=[5, 4, 3]) # or any filtering expression
How to spawn parallel child processes on a multi-processor system?
I have a Python script that I want to use as a controller to another Python script. I have a server with 64 processors, so want to spawn up to 64 child processes of this second Python script. The child script is called: $ python create_graphs.py --name=NAME where NAME is something like XYZ, ABC, NYU etc. In my parent controller script I retrieve the name variable from a list: my_list = [ 'XYZ', 'ABC', 'NYU' ] So my question is, what is the best way to spawn off these processes as children? I want to limit the number of children to 64 at a time, so need to track the status (if the child process has finished or not) so I can efficiently keep the whole generation running. I looked into using the subprocess package, but rejected it because it only spawns one child at a time. I finally found the multiprocessor package, but I admit to being overwhelmed by the whole threads vs. subprocesses documentation. Right now, my script uses subprocess.call to only spawn one child at a time and looks like this: #!/path/to/python import subprocess, multiprocessing, Queue from multiprocessing import Process my_list = [ 'XYZ', 'ABC', 'NYU' ] if __name__ == '__main__': processors = multiprocessing.cpu_count() for i in range(len(my_list)): if( i < processors ): cmd = ["python", "/path/to/create_graphs.py", "--name="+ my_list[i]] child = subprocess.call( cmd, shell=False ) I really want it to spawn up 64 children at a time. In other stackoverflow questions I saw people using Queue, but it seems like that creates a performance hit?
What you are looking for is the process pool class in multiprocessing. import multiprocessing import subprocess def work(cmd): return subprocess.call(cmd, shell=False) if __name__ == '__main__': count = multiprocessing.cpu_count() pool = multiprocessing.Pool(processes=count) print pool.map(work, ['ls'] * count) And here is a calculation example to make it easier to understand. The following will divide 10000 tasks on N processes where N is the cpu count. Note that I'm passing None as the number of processes. This will cause the Pool class to use cpu_count for the number of processes (reference) import multiprocessing import subprocess def calculate(value): return value * 10 if __name__ == '__main__': pool = multiprocessing.Pool(None) tasks = range(10000) results = [] r = pool.map_async(calculate, tasks, callback=results.append) r.wait() # Wait on the results print results
How to parse a RFC 2822 date/time into a Python datetime?
I have a date of the form specified by RFC 2822 -- say Fri, 15 May 2009 17:58:28 +0000, as a string. Is there a quick and/or standard way to get it as a datetime object in Python 2.5? I tried to produce a strptime format string, but the +0000 timezone specifier confuses the parser.
The problem is that parsedate will ignore the offset. Do this instead: from email.utils import parsedate_tz print parsedate_tz('Fri, 15 May 2009 17:58:28 +0700')
Machine vision in Python
I would like to perform a few basic machine vision tasks using Python and I'd like to know where I could find tutorials to help me get started. As far as I know, the only free library for Python that does machine vision is PyCV (which is a wrapper for OpenCV apparently), but I can't find any appropriate tutorials. My main tasks are to acquire an image from FireWire. Segment the image in different regions. And then perform statistics on each regions to determine pixel area and center of mass. Previously, I've used Matlab's Image Processing Tootlbox without any problems. The functions I would like to find an equivalent in Python are graythresh, regionprops and gray2ind. Thanks!
OpenCV is probably your best bet for a library; you have your choice of wrappers for them. I looked at the SWIG wrapper that comes with the standard OpenCV install, but ended up using ctypes-opencv because the memory management seemed cleaner. They are both very thin wrappers around the C code, so any C references you can find will be applicable to the Python. OpenCV is huge and not especially well documented, but there are some decent samples included in the samples directory that you can use to get started. A searchable OpenCV API reference is here. You didn't mention if you were looking for online or print sources, but I have the O'Reilly book and it's quite good (examples in C, but easily translatable). The FindContours function is a bit similar to regionprops; it will get you a list of the connected components, which you can then inspect to get their info. For thresholding you can try Threshold. I was sure you could pass a flag to it to use Otsu's method, but it doesn't seem to be listed in the docs there. I haven't come across specific functions corresponding to gray2ind, but they may be in there.
Is there support for the IN-operator in the "SQL Expression Language" used in SQLAlchemy?
Is it possible to express a query like the one below in the "SQL Expression Language" used in SQLAlchemy? SELECT * FROM foo WHERE foo.bar IN (1,2,3) I want to avoid writing the WHERE-clause in plain text. Is there a way to express this similar to my examples below or in any way that doesn't use plain text? select([foo], in(foo.c.bar, [1, 2, 3])) select([foo]).in(foo.c.bar, [1, 2, 3])
select([foo], foo.c.bar.in_([1, 2, 3])) You can use the .in_() method with Columns or with Instrumented attributes. Both work. It is mentioned here on SQLAlchemy's first tutorial.
How to check if a file is a valid image file?
I am currently using PIL. import Image try: im=Image.open(filename) # do stuff except IOError: # filename not an image file However, while this sufficiently covers most cases, some image files like, xcf, svg and psd are not being detected. Psd files throws an OverflowError exception. Is there someway I could include them as well?
I have just found the builtin imghdr module. From python documentation: The imghdr module determines the type of image contained in a file or byte stream. This is how it works: >>> import imghdr >>> imghdr.what('/tmp/bass') 'gif' Using a module is much better than reimplementing similar functionality
Accurate timing of functions in python
I'm programming in python on windows and would like to accurately measure the time it takes for a function to run. I have written a function "time_it" that takes another function, runs it, and returns the time it took to run. def time_it(f, *args): start = time.clock() f(*args) return (time.clock() - start)*1000 i call this 1000 times and average the result. (the 1000 constant at the end is to give the answer in milliseconds.) This function seems to work but i have this nagging feeling that I'm doing something wrong, and that by doing it this way I'm using more time than the function actually uses when its running. Is there a more standard or accepted way to do this? When i changed my test function to call a print so that it takes longer, my time_it function returns an average of 2.5 ms while the cProfile.run('f()') returns and average of 7.0 ms. I figured my function would overestimate the time if anything, what is going on here? One additional note, it is the relative time of functions compared to each other that i care about, not the absolute time as this will obviously vary depending on hardware and other factors.
Use the timeit module from the Python standard library. Basic usage: from timeit import Timer # first argument is the code to be run, the second "setup" argument is only run once, # and it not included in the execution time. t = Timer("""x.index(123)""", setup="""x = range(1000)""") print t.timeit() # prints float, for example 5.8254 # ..or.. print t.timeit(1000) # repeat 1000 times instead of the default 1million
How do I generate circular thumbnails with PIL?
How do I generate circular image thumbnails using PIL? The space outside the circle should be transparent. Snippets would be highly appreciated, thank you in advance.
The easiest way to do it is by using masks. Create a black and white mask with any shape you want. And put that shape as an alpha layer from PIL import Image, ImageOps mask = Image.open('mask.png').convert('L') im = Image.open('image.png') output = ImageOps.fit(im, mask.size, centering=(0.5, 0.5)) output.putalpha(mask) output.save('output.png') Here is the mask I used If you want the thumbnail size to be variable you can use the ImageDraw and draw the mask. from PIL import Image, ImageOps, ImageDraw size = (128, 128) mask = Image.new('L', size, 0) draw = ImageDraw.Draw(mask) draw.ellipse((0, 0) + size, fill=255) im = Image.open('image.jpg') output = ImageOps.fit(im, mask.size, centering=(0.5, 0.5)) output.putalpha(mask) output.save('output.png') If you want the output in GIF then you need to use the paste function instead of putalpha: from PIL import Image, ImageOps, ImageDraw size = (128, 128) mask = Image.new('L', size, 255) draw = ImageDraw.Draw(mask) draw.ellipse((0, 0) + size, fill=0) im = Image.open('image.jpg') output = ImageOps.fit(im, mask.size, centering=(0.5, 0.5)) output.paste(0, mask=mask) output.convert('P', palette=Image.ADAPTIVE) output.save('output.gif', transparency=0) Note that I did the following changes: The mask is now inverted. The white was replace with black and vis-versa. I'm converting into 'P' with an 'adaptive' palette. Otherwise PIL will only use web-safe colors and the result will look bad. I'm adding transparency info with to the image Please note: There is a big issue with this approach. If the gif image contained black parts, all of them will become transparent as well. You can work around this by choosing another color for the transparency. I would strongly advice you to use PNG format for this. But if you can't then that is the best you could do.
Algorithm to Divide a list of numbers into 2 equal sum lists
There is a list of numbers. The list is to be divided into 2 equal sized lists, with a minimal difference in sum. The sums have to be printed. #Example: >>>que = [2,3,10,5,8,9,7,3,5,2] >>>make_teams(que) 27 27 Is there an error in the following code algorithm for some case? How do I optimize and/or pythonize this? def make_teams(que): que.sort() if len(que)%2: que.insert(0,0) t1,t2 = [],[] while que: val = (que.pop(), que.pop()) if sum(t1)>sum(t2): t2.append(val[0]) t1.append(val[1]) else: t1.append(val[0]) t2.append(val[1]) print min(sum(t1),sum(t2)), max(sum(t1),sum(t2)), "\n" Question is from http://www.codechef.com/problems/TEAMSEL/
Dynamic programming is the solution you're looking for. Example with {3,4,10,3,2,5} X-Axis: Reachable sum of group. max = sum(all numbers) / 2 (rounded up) Y-Axis: Count elements in group. max = count numbers / 2 (rounded up) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 1 | | | | 4| | | | | | | | | | | // 4 2 | | | | | | | | | | | | | | | 3 | | | | | | | | | | | | | | | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 1 | | | 3| 4| | | | | | | | | | | // 3 2 | | | | | | | 3| | | | | | | | 3 | | | | | | | | | | | | | | | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 1 | | | 3| 4| | | | | |10| | | | | // 10 2 | | | | | | | 3| | | | | |10|10| 3 | | | | | | | | | | | | | | | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 1 | | | 3| 4| | | | | |10| | | | | // 3 2 | | | | | | 3| 3| | | | | |10|10| 3 | | | | | | | | | | 3| | | | | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 1 | | 2| 3| 4| | | | | |10| | | | | // 2 2 | | | | | 2| 3| 3| | | | | 2|10|10| 3 | | | | | | | | 2| 2| 3| | | | | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 1 | | 2| 3| 4| 5| | | | |10| | | | | // 5 2 | | | | | 2| 3| 3| 5| 5| | | 2|10|10| 3 | | | | | | | | 2| 2| 3| 5| 5| | | ^ 12 is our lucky number! Backtracing to get the group: 12 - 5 = 7 {5} 7 - 3 = 4 {5, 3} 4 - 4 = 0 {5, 3, 4} The other set can then be calculated: {4,3,10,3,2,5} - {5,3,4} = {10,3,2} All fields with a number are possible solutions for one bag. Choose the one that is furthest in the bottom right corner. BTW: It's called the knapsack-problem. If all weights (w1, ..., wn and W) are nonnegative integers, the knapsack problem can be solved in pseudo-polynomial time using dynamic programming.
Explain to me what the big deal with tail call optimization is and why Python needs it
So apparently, there's been a big brouhaha over whether or not Python needs tail call optimization. This came to a head when someone shipped Guido a copy of SICP because he didn't "get it." I'm in the same boat as Guido. I understand the concept of tail call optimization. I just can't think of any reason why Python really needs it. To make this easier for me to understand, could someone give me a snippet of code that would be greatly simplified using TCO?
Personally, i put great value on tail call optimization; but mainly because it makes recursion as efficient as iteration (or makes iteration a subset of recursion). On minimalistic languages you get huge expressive power without sacrificing performance. On a 'practical' language (like Python), OTOH, you usually have a lot of other constructions for almost every situation imaginable, so it's less critical. Always a good thing to have, to allow for unforeseen situations, of course
Python: How do I write a list to file and then pull it back into memory (dict represented as a string convert to dict) later?
More specific dupe of 875228—Simple data storing in Python. I have a rather large dict (6 GB) and I need to do some processing on it. I'm trying out several document clustering methods, so I need to have the whole thing in memory at once. I have other functions to run on this data, but the contents will not change. Currently, every time I think of new functions I have to write them, and then re-generate the dict. I'm looking for a way to write this dict to a file, so that I can load it into memory instead of recalculating all it's values. to oversimplify things it looks something like: {((('word','list'),(1,2),(1,3)),(...)):0.0, ....} I feel that python must have a better way than me looping around through some string looking for : and ( trying to parse it into a dictionary.
Why not use python pickle? Python has a great serializing module called pickle it is very easy to use. import cPickle cPickle.dump(obj, open('save.p', 'wb')) obj = cPickle.load(open('save.p', 'rb')) There are two disadvantages with pickle: It's not secure against erroneous or maliciously constructed data. Never unpickle data received from an untrusted or unauthenticated source. The format is not human readable. If you are using python 2.6 there is a builtin module called json. It is as easy as pickle to use: import json encoded = json.dumps(obj) obj = json.loads(encoded) Json format is human readable and is very similar to the dictionary string representation in python. And doesn't have any security issues like pickle. But might be slower than cPickle.
How do you reload a Django model module using the interactive interpreter via "manage.py shell"?
I know how to reload a regular Python module within a regular Python interpreter session. This question documents how to do that pretty well: How do I unload (reload) a Python module? For some reason, I am having trouble doing that within Django's "manage.py shell" interpreter session. To recreate my issue, start the basic Django tutorial found here: Writing your first Django app, part 1 After creating the "polls" application and "Poll" class, start up the interpreter via "manage.py shell" and import the "polls" app into it. import polls.models as pm Create a new "Poll" object: p = pm.Poll() All is well and good so far. Now go back to your source and add any arbitrary method or attribute. For example, I've added: def x(self): return 2+2 Now go back to the interpreter and "reload" the module: reload(pm) Now try to use your new method or attribute: p1 = pm.Poll() p1.x() You'll get this message: 'Poll' object has no attribute 'x' What gives? I've also tried rerunning the import command, importing the module using different syntax, deleting all references to any "Poll" objects or to the "Poll" class. I've also tried this with both the IPython interpreter and with the plain Python (v2.6) interpreter. Nothing seems to work. Using the same techniques with an arbitrary Python module in a regular interpreter session works perfectly. I just can't seem to get it to work in Django's "shell" session. By the way, if it makes any difference, I'm doing this on a Ubuntu 9.04 machine.
Well, I think I have to answer to this. The problem is that Django caches its models in a singleton (singleton like structure) called AppCache. Basically, to reload Django models you need to first reload and re-import all the model modules stored in the AppCache. Then you need to wipe out the AppCache. Here's the code for it: import os from django.db.models.loading import AppCache cache = AppCache() curdir = os.getcwd() for app in cache.get_apps(): f = app.__file__ if f.startswith(curdir) and f.endswith('.pyc'): os.remove(f) __import__(app.__name__) reload(app) from django.utils.datastructures import SortedDict cache.app_store = SortedDict() cache.app_models = SortedDict() cache.app_errors = {} cache.handled = {} cache.loaded = False I've put all of this in a separate file called reloadmodels.py in the root directory of my Django site. Using IPython I can reload everything by running: %run ~/mysite/reloadmodels.py
Detect & Record Audio in Python
I need to capture audio clips as WAV files that I can then pass to another bit of python for processing. The problem is that I need to determine when there is audio present and then record it, stop when it goes silent and then pass that file to the processing module. I'm thinking it should be possible with the wave module to detect when there is pure silence and discard it then as soon as something other than silence is detected start recording, then when the line goes silent again stop the recording. Just can't quite get my head around it, can anyone get me started with a basic example.
As a follow up to Nick Fortescue's answer, here's a more complete example of how to record from the microphone and process the resulting data: from sys import byteorder from array import array from struct import pack import pyaudio import wave THRESHOLD = 500 CHUNK_SIZE = 1024 FORMAT = pyaudio.paInt16 RATE = 44100 def is_silent(snd_data): "Returns 'True' if below the 'silent' threshold" return max(snd_data) < THRESHOLD def normalize(snd_data): "Average the volume out" MAXIMUM = 16384 times = float(MAXIMUM)/max(abs(i) for i in snd_data) r = array('h') for i in snd_data: r.append(int(i*times)) return r def trim(snd_data): "Trim the blank spots at the start and end" def _trim(snd_data): snd_started = False r = array('h') for i in snd_data: if not snd_started and abs(i)>THRESHOLD: snd_started = True r.append(i) elif snd_started: r.append(i) return r # Trim to the left snd_data = _trim(snd_data) # Trim to the right snd_data.reverse() snd_data = _trim(snd_data) snd_data.reverse() return snd_data def add_silence(snd_data, seconds): "Add silence to the start and end of 'snd_data' of length 'seconds' (float)" r = array('h', [0 for i in xrange(int(seconds*RATE))]) r.extend(snd_data) r.extend([0 for i in xrange(int(seconds*RATE))]) return r def record(): """ Record a word or words from the microphone and return the data as an array of signed shorts. Normalizes the audio, trims silence from the start and end, and pads with 0.5 seconds of blank sound to make sure VLC et al can play it without getting chopped off. """ p = pyaudio.PyAudio() stream = p.open(format=FORMAT, channels=1, rate=RATE, input=True, output=True, frames_per_buffer=CHUNK_SIZE) num_silent = 0 snd_started = False r = array('h') while 1: # little endian, signed short snd_data = array('h', stream.read(CHUNK_SIZE)) if byteorder == 'big': snd_data.byteswap() r.extend(snd_data) silent = is_silent(snd_data) if silent and snd_started: num_silent += 1 elif not silent and not snd_started: snd_started = True if snd_started and num_silent > 30: break sample_width = p.get_sample_size(FORMAT) stream.stop_stream() stream.close() p.terminate() r = normalize(r) r = trim(r) r = add_silence(r, 0.5) return sample_width, r def record_to_file(path): "Records from the microphone and outputs the resulting data to 'path'" sample_width, data = record() data = pack('<' + ('h'*len(data)), *data) wf = wave.open(path, 'wb') wf.setnchannels(1) wf.setsampwidth(sample_width) wf.setframerate(RATE) wf.writeframes(data) wf.close() if __name__ == '__main__': print("please speak a word into the microphone") record_to_file('demo.wav') print("done - result written to demo.wav")
Overriding a static method in python
Referring to the first answer about python's bound and unbound methods here, I have a question: class Test: def method_one(self): print "Called method_one" @staticmethod def method_two(): print "Called method_two" @staticmethod def method_three(): Test.method_two() class T2(Test): @staticmethod def method_two(): print "T2" a_test = Test() a_test.method_one() a_test.method_two() a_test.method_three() b_test = T2() b_test.method_three() produces output: Called method_one Called method_two Called method_two Called method_two Is there a way to override a static method in python? I expected b_test.method_three() to print "T2", but it doesn't (prints "Called method_two" instead).
In the form that you are using there, you are explicitly specifying what class's static method_two to call. If method_three was a classmethod, and you called cls.method_two, you would get the results that you wanted: class Test: def method_one(self): print "Called method_one" @staticmethod def method_two(): print "Called method_two" @classmethod def method_three(cls): cls.method_two() class T2(Test): @staticmethod def method_two(): print "T2" a_test = Test() a_test.method_one() a_test.method_two() a_test.method_three() b_test = T2() b_test.method_three() Test.method_two() T2.method_three()
Seeing escape characters when pressing the arrow keys in python shell
In shells like the interactive python shell, you can usually use the arrow keys to move around in the current line or get previous commands (with arrow-up) etc. But after I ssh into another machine and start python there, I get sessions like: >>> import os >>> ^[[A where the last character comes from arrow-up. Or, using arrow-left: >>> impor^[[D How can I fix this? In the regular bash, arrow keys work fine. The weird behavior is just in the interactive python (or perl etc.) shell.
I've solved this issue by installing readline package: pip install readline
Multiple variables in Python 'with' statement
Is it possible to declare more than one variable using a with statement in Python? Something like: from __future__ import with_statement with open("out.txt","wt"), open("in.txt") as file_out, file_in: for line in file_in: file_out.write(line) ... or is cleaning up two resources at the same time the problem?
It is possible in Python 3 since v3.1 and Python 2.7. The new with syntax supports multiple context managers: with A() as a, B() as b, C() as c: doSomething(a,b,c) Unlike the contextlib.nested, this guarantees that a and b will have their __exit__()'s called even if C() or it's __enter__() method raises an exception.
item frequency count in python
I'm a python newbie, so maybe my question is very noob. Assume I have a list of words, and I want to find the number of times each word appears in that list. Obvious way to do this is: words = "apple banana apple strawberry banana lemon" uniques = set(words.split()) freqs = [(item, words.split.count(item)) for item in uniques] print(freqs) But I find this code not very good, because this way program runs through words list twice, once to build the set, and second time counting the number of appearances. Of course, I could write a function to run through list and do the counting, but that wouldn't be so pythonic. So, is there a more efficient and pythonic way?
If you are using python 2.7+/3.1+, there is a Counter Class in the collections module which is purpose built to solve this type of problem: >>> from collections import Counter >>> words = "apple banana apple strawberry banana lemon" >>> freqs = Counter(words.split()) >>> print(freqs) Counter({'apple': 2, 'banana': 2, 'strawberry': 1, 'lemon': 1}) >>> Since both 2.7 and 3.1 are still in beta it's unlikely you're using it, so just keep in mind that a standard way of doing this kind of work will soon be readily available.
How do I calculate r-squared using Python and Numpy?
I'm using Python and Numpy to calculate a best fit polynomial of arbitrary degree. I pass a list of x values, y values, and the degree of the polynomial I want to fit (linear, quadratic, etc.). This much works, but I also want to calculate r (coefficient of correlation) and r-squared(coefficient of determination). I am comparing my results with Excel's best-fit trendline capability, and the r-squared value it calculates. Using this, I know I am calculating r-squared correctly for linear best-fit (degree equals 1). However, my function does not work for polynomials with degree greater than 1. Excel is able to do this. How do I calculate r-squared for higher-order polynomials using Numpy? Here's my function: import numpy # Polynomial Regression def polyfit(x, y, degree): results = {} coeffs = numpy.polyfit(x, y, degree) # Polynomial Coefficients results['polynomial'] = coeffs.tolist() correlation = numpy.corrcoef(x, y)[0,1] # r results['correlation'] = correlation # r-squared results['determination'] = correlation**2 return results
A very late reply, but just in case someone needs a ready function for this: scipy.stats.stats.linregress i.e. slope, intercept, r_value, p_value, std_err = scipy.stats.linregress(x, y) as in @Adam Marples's answer.
PyQt: Show menu in a system tray application
First of all, I'm an experienced C programmer but new to python. I want to create a simple application in python using pyqt. Let's imagine this application it is as simple as when it is run it has to put an icon in the system tray and it has offer an option in its menu to exit the application. This code works, it shows the menu (I don't connect the exit action and so on to keep it simple) import sys from PyQt4 import QtGui def main(): app = QtGui.QApplication(sys.argv) trayIcon = QtGui.QSystemTrayIcon(QtGui.QIcon("Bomb.xpm"), app) menu = QtGui.QMenu() exitAction = menu.addAction("Exit") trayIcon.setContextMenu(menu) trayIcon.show() sys.exit(app.exec_()) if __name__ == '__main__': main() But this doesn't: import sys from PyQt4 import QtGui class SystemTrayIcon(QtGui.QSystemTrayIcon): def __init__(self, icon, parent=None): QtGui.QSystemTrayIcon.__init__(self, icon, parent) menu = QtGui.QMenu() exitAction = menu.addAction("Exit") self.setContextMenu(menu) def main(): app = QtGui.QApplication(sys.argv) trayIcon = SystemTrayIcon(QtGui.QIcon("Bomb.xpm"), app) trayIcon.show() sys.exit(app.exec_()) if __name__ == '__main__': main() I probably missing something. There are no errors but in the second case when I click with the right button it doesn't show the menu. Thanks a lot for your help!!!
Well, after some debugging I found the problem. The QMenu object it is destroyed after finish __init__ function because it doesn't have a parent. While the parent of a QSystemTrayIcon can be an object for the QMenu it has to be a Qwidget. This code works (see how QMenu gets the same parent as the QSystemTrayIcon which is an QWidget): import sys from PyQt4 import QtGui class SystemTrayIcon(QtGui.QSystemTrayIcon): def __init__(self, icon, parent=None): QtGui.QSystemTrayIcon.__init__(self, icon, parent) menu = QtGui.QMenu(parent) exitAction = menu.addAction("Exit") self.setContextMenu(menu) def main(): app = QtGui.QApplication(sys.argv) w = QtGui.QWidget() trayIcon = SystemTrayIcon(QtGui.QIcon("Bomb.xpm"), w) trayIcon.show() sys.exit(app.exec_()) if __name__ == '__main__': main()
How do I get the current file, current class, and current method with Python?
Name of the file from where code is running Name of the class from where code is running Name of the method (attribute of the class) where code is running
Here is an example of each: from inspect import stack class Foo: def __init__(self): print __file__ print self.__class__.__name__ print stack()[0][3] f = Foo()
Circular dependency in Python
I have two files, node.py and path.py, which define two classes, Node and Path, respectively. Up to today, the definition for Path referenced the Node object, and therefore I had done from node.py import * in the path.py file. However, as of today I created a new method for Node that references the Path object. I had problems when trying to import path.py: I tried it, and when the program ran and called the Path method that uses Node, an exception rose about Node not being defined. What do I do?
Importing Python Modules is a great article that explains circular imports in Python. The easiest way to fix this is to move the path import to the end of the node module.
Bubble Sort Homework
In class we are doing sorting algorithms and, although I understand them fine when talking about them and writing pseudocode, I am having problems writing actual code for them. This is my attempt in Python: mylist = [12, 5, 13, 8, 9, 65] def bubble(badList): length = len(badList) - 1 unsorted = True while unsorted: for element in range(0,length): unsorted = False if badList[element] > badList[element + 1]: hold = badList[element + 1] badList[element + 1] = badList[element] badList[element] = hold print badList else: unsorted = True print bubble(mylist) Now, this (as far as I can tell) sorts correctly, but once it finishes it just loops indefinitely. How can this code be fixed so the function finishes properly and correctly sorts a list of any (reasonable) size? P.S. I know I should not really have prints in a function and I should have a return, but I just have not done that yet as my code does not really work yet.
To explain why your script isn't working right now, I'll rename the variable unsorted to sorted. At first, your list isn't yet sorted. Of course, we set sorted to False. As soon as we start the while loop, we assume that the list is already sorted. The idea is this: as soon as we find two elements that are not in the right order, we set sorted back to False. sorted will remain True only if there were no elements in the wrong order. sorted = False # We haven't started sorting yet while not sorted: sorted = True # Assume the list is now sorted for element in range(0, length): if badList[element] > badList[element + 1]: sorted = False # We found two elements in the wrong order hold = badList[element + 1] badList[element + 1] = badList[element] badList[element] = hold # We went through the whole list. At this point, if there were no elements # in the wrong order, sorted is still True. Otherwise, it's false, and the # while loop executes again. There are also minor little issues that would help the code be more efficient or readable. In the for loop, you use the variable element. Technically, element is not an element; it's a number representing a list index. Also, it's quite long. In these cases, just use a temporary variable name, like i for "index". for i in range(0, length): The range command can also take just one argument (named stop). In that case, you get a list of all the integers from 0 to that argument. for i in range(length): The Python Style Guide recommends that variables be named in lowercase with underscores. This is a very minor nitpick for a little script like this; it's more to get you accustomed to what Python code most often resembles. def bubble(bad_list): To swap the values of two variables, write them as a tuple assignment. The right hand side gets evaluated as a tuple (say, (badList[i+1], badList[i]) is (3, 5)) and then gets assigned to the two variables on the left hand side ((badList[i], badList[i+1])). bad_list[i], bad_list[i+1] = bad_list[i+1], bad_list[i] Put it all together, and you get this: my_list = [12, 5, 13, 8, 9, 65] def bubble(bad_list): length = len(bad_list) - 1 sorted = False while not sorted: sorted = True for i in range(length): if bad_list[i] > bad_list[i+1]: sorted = False bad_list[i], bad_list[i+1] = bad_list[i+1], bad_list[i] bubble(my_list) print my_list (I removed your print statement too, by the way.)
Using python to develop web application
I have been doing some work in python, but that was all for stand alone applications. I'm curious to know whether any offshoot of python supports web development? Would some one also suggest a good tutorial or a website from where I can pick up some of the basics of web development using python?
Now that everyone has said Django, I can add my two cents: I would argue that you might learn more by looking at the different components first, before using Django. For web development with Python, you often want 3 components: Something that takes care of the HTTP stuff (e.g. CherryPy) A templating language to create your web pages. Mako is very pythonic and works with Cherrpy. If you get your data from a database, an ORM comes in handy. SQLAlchemy would be an example. All the links above have good tutorials. For many real-world use-cases, Django will be a better solution than such a stack as it seamlessly integrates this functionality (and more). And if you need a CMS, Django is your best bet short of Zope. Nevertheless, to get a good grasp of what's going on, a stack of loosely coupled programs might be better. Django hides a lot of the details.
Django App Dependency Cycle
I am in the middle of developing a Django application, which has quite complicated models (it models a university - courses, modules, lectures, students etc.) I have separated the project into apps, to make the whole thing more organised (apps are courses, schools, people, modules and timeperiods). I am having a problem whereby a model in one app may depend on a model in another - so I must import it. The second app then in turn depends on a model in the first, so there is a cycle and Python throws up an error. How do people deal with this? I understand that apps should be relatively "independent", but in a system like this it doesn't make sense, for example, to use ContentTypes to link students to a module. Does anyone have a similar project that could comment on this case?
If your dependency is with foreign keys referencing models in other applications, you don't need to import the other model. You can use a string in your ForeignKey definition: class MyModel(models.Model): myfield = models.ForeignKey('myotherapp.MyOtherModel') This way there's no need to import MyOtherModel, so no circular reference. Django resolves the string internally, and it all works as expected.
More efficient movements editing python files in vim
Given a python file with the following repeated endlessly: def myFunction(a, b, c): if a: print b elif c: print 'hello' I'd like to move around and edit this file using familiar vim movements. For instance, using (, ), [[, ]], {, } or deleting/yanking/changing text using commands like di}. In other languages (like C++, Java, C#, etc) you've got curly brackets abound, so using a movement like di} can easily find a matching curly brace and act on that block. And in fact if I am on the 'b' character on the above text and do a di) in vim, it successfully deletes the text between the two parens. The issue is in python's detection of code blocks, I think. Using (, ), [[, ]], {, or } as movements all pretty much do the same thing, bringing you to the start (above or on the def line) or end (after the last line of the function) of the function. And there is no way, as far as I know, to easily tell vim "select everything for this indentation block." In the above example, I'd like to be on in 'i' of the if line, type di} and have it delete the entire if block (to the end of this particular function). I'm sure it should be possible to tell vim to operate on an indentation basis for such movements (well, maybe not that particular movement, but some user defined action). Any thoughts on how to accomplish this?
Here is a VIM script http://www.vim.org/scripts/script.php?script_id=30 which makes it much easier to navigate around python code blocks. Shortcuts: ]t -- Jump to beginning of block ]e -- Jump to end of block ]v -- Select (Visual Line Mode) block ]< -- Shift block to left ]> -- Shift block to right ]# -- Comment selection ]u -- Uncomment selection ]c -- Select current/previous class ]d -- Select current/previous function ]<up> -- Jump to previous line with the same/lower indentation ]<down> -- Jump to next line with the same/lower indentation
A good way to escape quotes in a database query string?
I've tried all manner of Python modules and they either escape too much or in the wrong way. What's the best way you've found to escape quotes (", ') in Python?
If it's part of a Database query you should be able to use a Parameterized SQL Statement. As well as escaping your quotes, this will deal with all special characters and will protect you from SQL injection attacks.