title
stringlengths
12
150
question_id
int64
469
40.1M
question_score
int64
2
5.52k
question_date
stringdate
2008-08-02 15:11:16
2016-10-18 06:16:31
answer_id
int64
536
40.1M
answer_score
int64
7
8.38k
answer_date
stringdate
2008-08-02 18:49:07
2016-10-18 06:19:33
tags
listlengths
1
5
question_body_md
stringlengths
15
30.2k
answer_body_md
stringlengths
11
27.8k
Using python to develop web application
895,420
16
2009-05-21T21:58:58Z
897,434
21
2009-05-22T11:35:19Z
[ "python" ]
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](http://docs.djangoproject.com/en/dev/intro/tutorial01/), 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: 1. Something that takes care o...
Django App Dependency Cycle
895,454
19
2009-05-21T22:05:33Z
896,995
48
2009-05-22T09:08:17Z
[ "python", "django", "dependencies" ]
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 probl...
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 MyOtherMo...
Properly importing modules in Python
896,112
9
2009-05-22T02:09:07Z
897,186
19
2009-05-22T10:05:51Z
[ "python", "python-import" ]
How do I set up module imports so that each module can access the objects of all the others? I have a medium size Python application with modules files in various subdirectories. I have created modules that append these subdirectories to `sys.path` and imports a group of modules, using `import thisModule as tm`. Modul...
**"I have a medium size Python application with modules files in various subdirectories."** Good. Make absolutely sure that each directory include a `__init__.py` file, so that it's a package. **"I have created modules that append these subdirectories to `sys.path`"** Bad. Use `PYTHONPATH` or install the whole struc...
More efficient movements editing python files in vim
896,145
36
2009-05-22T02:25:37Z
1,315,239
11
2009-08-22T05:44:32Z
[ "python", "vim", "editing" ]
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 ...
More information on the Vim script refred to above: <http://www.vim.org/scripts/script.php?script_id=386> python\_match.vim : Extend the % motion and define g%, [%, and ]% motions for Python files description This script redefines the % motion so that (in addition to its usual behavior) it cycles through if/elif/els...
More efficient movements editing python files in vim
896,145
36
2009-05-22T02:25:37Z
1,394,173
16
2009-09-08T13:56:12Z
[ "python", "vim", "editing" ]
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 ...
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 * ]# ...
How to change default django User model to fit my needs?
896,421
10
2009-05-22T05:01:09Z
896,788
7
2009-05-22T07:59:39Z
[ "python", "django", "django-models", "user" ]
The default Django's `User` model has some fields, and validation rules, that I don't really need. I want to make registration as simple as possible, i.e. require either email or username, or phone number - all those being unique, hence good as user identifiers. I also don't like default character set for user name th...
The Django User model is structured very sensibly. You really don't want to allow arbitrary characters in a username, for instance, and there are ways to achieve [email address login](http://www.djangosnippets.org/snippets/74/), without hacking changes to the base model. To simply store additional information around a...
How to change default django User model to fit my needs?
896,421
10
2009-05-22T05:01:09Z
897,928
7
2009-05-22T13:47:00Z
[ "python", "django", "django-models", "user" ]
The default Django's `User` model has some fields, and validation rules, that I don't really need. I want to make registration as simple as possible, i.e. require either email or username, or phone number - all those being unique, hence good as user identifiers. I also don't like default character set for user name th...
**I misread the question. Hope this post is helpful to anyone else.** ``` #in models.py from django.db.models.signals import post_save class UserProfile(models.Model): user = models.ForeignKey(User) #other fields here def __str__(self): return "%s's profile" % self.user def crea...
How to change default django User model to fit my needs?
896,421
10
2009-05-22T05:01:09Z
898,313
8
2009-05-22T14:59:04Z
[ "python", "django", "django-models", "user" ]
The default Django's `User` model has some fields, and validation rules, that I don't really need. I want to make registration as simple as possible, i.e. require either email or username, or phone number - all those being unique, hence good as user identifiers. I also don't like default character set for user name th...
Rather than modify the User class directly or do subclassing, you can also just repurpose the existing fields. For one site I used the "first\_name" field as the "publicly displayed name" of a user and stuff a slugified version of that into the "username" field (for use in URLs). I wrote a custom auth backend to allow...
Checking folder/file ntfs permissions using python
896,638
6
2009-05-22T06:48:03Z
897,963
11
2009-05-22T13:56:50Z
[ "python", "winapi", "permissions", "acl", "ntfs" ]
As the question title might suggest, I would very much like to know of the way to check the ntfs permissions of the given file or folder (hint: those are the ones you see in the "security" tab). Basically, what I need is to take a path to a file or directory (on a local machine, or, preferrably, on a share on a remote ...
Unless you fancy rolling your own, win32security is the way to go. There's the beginnings of an example here: <http://timgolden.me.uk/python/win32_how_do_i/get-the-owner-of-a-file.html> If you want to live slightly dangerously (!) my in-progress winsys package is designed to do exactly what you're after. You can get ...
A good way to escape quotes in a database query string?
897,020
25
2009-05-22T09:16:28Z
897,061
23
2009-05-22T09:30:32Z
[ "python", "database", "escaping", "sql-injection" ]
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](http://python.projects.postgresql.org/docs/0.8/driver.html#parameterized-statements). As well as escaping your quotes, this will deal with all special characters and will protect you from [SQL injection attacks](http://stackover...
A good way to escape quotes in a database query string?
897,020
25
2009-05-22T09:16:28Z
14,930,615
19
2013-02-18T06:25:16Z
[ "python", "database", "escaping", "sql-injection" ]
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?
Use `json.dumps`. ``` >>> import json >>> print json.dumps('a"bc') "a\"bc" ```
What is the idiomatic way of invoking a list of functions in Python?
897,362
4
2009-05-22T11:09:53Z
897,373
17
2009-05-22T11:14:00Z
[ "python" ]
I have a list of callback functions that I need to invoke when an event is fired. Is this idiomatic python? ``` def first_callback(m): print 'first ' + m def second_callback(m): print 'second ' + m lst = [first_callback, second_callback] map(lambda x: x("event_info"),lst) #is this how you do it? ```
Use `map` only for functions without side effects (like `print`). That is, use it only for functions that just return something. In this case a regular loop is more idiomatic: ``` for f in lst: f("event_info") ``` **Edit**: also, as of Python 3.0, [`map`](http://docs.python.org/3.0/library/functions.html#map) ret...
Python's sys.path value
897,792
54
2009-05-22T13:19:05Z
897,810
28
2009-05-22T13:21:25Z
[ "python", "path", "sys" ]
Where is Python's sys.path initialized from? **UPD**: Python is adding some paths before refering to PYTHONPATH: ``` >>> import sys >>> from pprint import pprint as p >>> p(sys.path) ['', 'C:\\Python25\\lib\\site-packages\\setuptools-0.6c9-py2.5.egg', 'C:\\Python25\\lib\\site-packages\\orbit...
"Initialized from the environment variable PYTHONPATH, plus an installation-dependent default" -- <http://docs.python.org/library/sys.html#sys.path>
Python's sys.path value
897,792
54
2009-05-22T13:19:05Z
38,403,654
7
2016-07-15T19:19:54Z
[ "python", "path", "sys" ]
Where is Python's sys.path initialized from? **UPD**: Python is adding some paths before refering to PYTHONPATH: ``` >>> import sys >>> from pprint import pprint as p >>> p(sys.path) ['', 'C:\\Python25\\lib\\site-packages\\setuptools-0.6c9-py2.5.egg', 'C:\\Python25\\lib\\site-packages\\orbit...
Python really tries hard to intelligently set [`sys.path`](https://docs.python.org/2/library/sys.html#sys.path). How it is set can get [really](https://github.com/python/cpython/blob/master/Modules/getpath.c) [complicated](https://github.com/python/cpython/blob/master/PC/getpathp.c). The following guide is a watered-do...
Python equivalent of PHP's memory_get_usage()?
897,941
18
2009-05-22T13:49:41Z
898,406
23
2009-05-22T15:14:38Z
[ "python" ]
I've already [found the following question](http://stackoverflow.com/questions/110259/python-memory-profiler), but I was wondering if there was a quicker and dirtier way of grabbing an estimate of how much memory the python interpreter is currently using for my script that doesn't rely on external libraries. I'm comin...
A simple solution for Linux and other systems with `/proc/self/status` is the following code, which I use in a project of mine: ``` def memory_usage(): """Memory usage of the current process in kilobytes.""" status = None result = {'peak': 0, 'rss': 0} try: # This will only work on systems with...
Python equivalent of PHP's memory_get_usage()?
897,941
18
2009-05-22T13:49:41Z
7,669,279
15
2011-10-06T00:41:21Z
[ "python" ]
I've already [found the following question](http://stackoverflow.com/questions/110259/python-memory-profiler), but I was wondering if there was a quicker and dirtier way of grabbing an estimate of how much memory the python interpreter is currently using for my script that doesn't rely on external libraries. I'm comin...
You could also use the `getrusage()` function from the standard library module `resource`. The resulting object has the attribute `ru_maxrss`, which gives total memory usage for the calling process: ``` >>> import resource >>> resource.getrusage(resource.RUSAGE_SELF).ru_maxrss 2656 ``` The [Python docs](http://docs.p...
Python equivalent of PHP's memory_get_usage()?
897,941
18
2009-05-22T13:49:41Z
12,912,618
10
2012-10-16T10:26:49Z
[ "python" ]
I've already [found the following question](http://stackoverflow.com/questions/110259/python-memory-profiler), but I was wondering if there was a quicker and dirtier way of grabbing an estimate of how much memory the python interpreter is currently using for my script that doesn't rely on external libraries. I'm comin...
Accepted answer rules, but it might be easier (and more portable) to use [psutil](https://github.com/giampaolo/psutil). It does the same and a lot more. UPDATE: [muppy](http://packages.python.org/Pympler/muppy.html) is also very convenient (and much better documented than guppy/heapy).
Convert list of lists to delimited string
898,391
5
2009-05-22T15:11:44Z
898,404
17
2009-05-22T15:13:44Z
[ "python" ]
How do I do the following in Python 2.2 using built-in modules only? I have a list of lists like this: [['dog', 1], ['cat', 2, 'a'], ['rat', 3, 4], ['bat', 5]] And from it I'd like to produce a string representation of a table like this where the columns are delimited by tabs and the rows by newlines. ``` dog 1 ca...
Like this, perhaps: ``` lists = [['dog', 1], ['cat', 2, 'a'], ['rat', 3, 4], ['bat', 5]] result = "\n".join("\t".join(map(str,l)) for l in lists) ``` This joins all the inner lists using tabs, and concatenates the resulting list of strings using newlines. It uses a feature called [list comprehension](http://docs.pyt...
How can I detect if a file is binary (non-text) in python?
898,669
63
2009-05-22T16:09:50Z
898,723
25
2009-05-22T16:21:50Z
[ "python", "file", "binary" ]
How can I tell if a file is binary (non-text) in python? I am searching through a large set of files in python, and keep getting matches in binary files. This makes the output look incredibly messy. I know I could use grep -I, but I am doing more with the data than what grep allows for. In the past I would have just ...
You can also use the mimetypes module: ``` import mimetypes ... mime = mimetypes.guess_type(file) ``` It's fairly easy to compile a list of binary mime types. For example Apache distributes with a mime.types file that you could parse into a set of lists, binary and text and then check to see if the mime is in your te...
How can I detect if a file is binary (non-text) in python?
898,669
63
2009-05-22T16:09:50Z
898,729
8
2009-05-22T16:23:17Z
[ "python", "file", "binary" ]
How can I tell if a file is binary (non-text) in python? I am searching through a large set of files in python, and keep getting matches in binary files. This makes the output look incredibly messy. I know I could use grep -I, but I am doing more with the data than what grep allows for. In the past I would have just ...
If it helps, many many binary types begin with a magic numbers. [Here is a list](http://www.garykessler.net/library/file%5Fsigs.html) of file signatures.
How can I detect if a file is binary (non-text) in python?
898,669
63
2009-05-22T16:09:50Z
3,002,505
9
2010-06-09T01:14:54Z
[ "python", "file", "binary" ]
How can I tell if a file is binary (non-text) in python? I am searching through a large set of files in python, and keep getting matches in binary files. This makes the output look incredibly messy. I know I could use grep -I, but I am doing more with the data than what grep allows for. In the past I would have just ...
Try this: ``` def is_binary(filename): """Return true if the given filename is binary. @raise EnvironmentError: if the file does not exist or cannot be accessed. @attention: found @ http://bytes.com/topic/python/answers/21222-determine-file-type-binary-text on 6/08/2010 @author: Trent Mick <TrentM@Acti...
How can I detect if a file is binary (non-text) in python?
898,669
63
2009-05-22T16:09:50Z
7,392,391
34
2011-09-12T18:44:23Z
[ "python", "file", "binary" ]
How can I tell if a file is binary (non-text) in python? I am searching through a large set of files in python, and keep getting matches in binary files. This makes the output look incredibly messy. I know I could use grep -I, but I am doing more with the data than what grep allows for. In the past I would have just ...
Yet another method [based on file(1) behavior](https://github.com/file/file/blob/f2a6e7cb7db9b5fd86100403df6b2f830c7f22ba/src/encoding.c#L151-L228): ``` >>> textchars = bytearray({7,8,9,10,12,13,27} | set(range(0x20, 0x100)) - {0x7f}) >>> is_binary_string = lambda bytes: bool(bytes.translate(None, textchars)) ``` Exa...
In Python how do I sort a list of dictionaries by a certain value of the dictionary + alphabetically?
898,773
3
2009-05-22T16:33:27Z
898,791
10
2009-05-22T16:38:18Z
[ "python", "list", "sorting", "dictionary" ]
Ok, here's what I'm trying to do... I know that itemgetter() sort could to alphabetical sort easy, but if I have something like this: > [{'Name':'TOTAL', 'Rank':100}, > {'Name':'Woo Company', 'Rank':15}, > {'Name':'ABC Company', 'Rank':20}] And I want it sorted alphabetically (by Name) + include the condition that th...
The best approach here is to decorate the sort key... Python will sort a tuple by the tuple components in order, so build a tuple key with your sorting criteria: ``` sorted(list_of_dicts, key=lambda d: (d['Name'] == 'TOTAL', d['Name'].lower())) ``` This results in a sort key of: * (True, 'total') for {'Name': 'TOTAL...
How should I verify a log message when testing Python code under nose?
899,067
19
2009-05-22T17:42:46Z
1,049,375
15
2009-06-26T14:13:44Z
[ "python", "unit-testing", "mocking", "nose" ]
I'm trying to write a simple unit test that will verify that, under a certain condition, a class in my application will log an error via the standard logging API. I can't work out what the cleanest way to test this situation is. I know that nose already captures logging output through it's logging plugin, but this see...
I used to mock loggers, but in this situation I found best to use logging handlers, so I wrote this one based on [the document suggested by jkp](http://www.fubar.si/2009/3/4/mocking-logging-python-module-for-unittests): ``` class MockLoggingHandler(logging.Handler): """Mock logging handler to check for expected lo...
How should I verify a log message when testing Python code under nose?
899,067
19
2009-05-22T17:42:46Z
14,666,268
18
2013-02-02T20:36:27Z
[ "python", "unit-testing", "mocking", "nose" ]
I'm trying to write a simple unit test that will verify that, under a certain condition, a class in my application will log an error via the standard logging API. I can't work out what the cleanest way to test this situation is. I know that nose already captures logging output through it's logging plugin, but this see...
Fortunately this is not something that you have to write yourself; the `testfixtures` package provides a context manager that captures all logging output that occurs in the body of the `with` statement. You can find the package here: <http://pypi.python.org/pypi/testfixtures> And here are its docs about how to test l...
How should I verify a log message when testing Python code under nose?
899,067
19
2009-05-22T17:42:46Z
20,553,331
11
2013-12-12T20:15:41Z
[ "python", "unit-testing", "mocking", "nose" ]
I'm trying to write a simple unit test that will verify that, under a certain condition, a class in my application will log an error via the standard logging API. I can't work out what the cleanest way to test this situation is. I know that nose already captures logging output through it's logging plugin, but this see...
This answer extends the work done in <http://stackoverflow.com/a/1049375/1286628>. The handler is largely the same (the constructor is more idiomatic, using `super`, and `emit` is now thread safe for testing asynchronous code such as Celery tasks). Further, I add a demonstration of how to use the handler with the stand...
Writing a list to a file with Python
899,103
214
2009-05-22T17:52:18Z
899,149
115
2009-05-22T17:58:40Z
[ "python", "file", "list", "file-io", "newline" ]
Is this the cleanest way to write a list to a file, since `writelines()` doesn't insert newline characters? ``` file.writelines(["%s\n" % item for item in list]) ``` It seems like there would be a standard way...
The best way is: ``` outfile.write("\n".join(itemlist)) ```
Writing a list to a file with Python
899,103
214
2009-05-22T17:52:18Z
899,176
313
2009-05-22T18:04:21Z
[ "python", "file", "list", "file-io", "newline" ]
Is this the cleanest way to write a list to a file, since `writelines()` doesn't insert newline characters? ``` file.writelines(["%s\n" % item for item in list]) ``` It seems like there would be a standard way...
> **EDIT** Adding info from [Thomas](http://stackoverflow.com/users/306312/thomas)' comment > > Don't forget to open the file first > > thefile = open('test.txt', 'w') I'd use a loop: ``` for item in thelist: thefile.write("%s\n" % item) ``` or: ``` for item in thelist: print>>thefile, item ``` If you're keen ...
Writing a list to a file with Python
899,103
214
2009-05-22T17:52:18Z
899,199
130
2009-05-22T18:10:04Z
[ "python", "file", "list", "file-io", "newline" ]
Is this the cleanest way to write a list to a file, since `writelines()` doesn't insert newline characters? ``` file.writelines(["%s\n" % item for item in list]) ``` It seems like there would be a standard way...
What are you going to do with the file? Does this file exist for humans, or other programs with clear interoperability requirements, or are you just trying to serialize a list to disk for later use by the same python app. If the second case is it, you should be [pickleing](http://docs.python.org/library/pickle.html) th...
Writing a list to a file with Python
899,103
214
2009-05-22T17:52:18Z
899,254
46
2009-05-22T18:20:19Z
[ "python", "file", "list", "file-io", "newline" ]
Is this the cleanest way to write a list to a file, since `writelines()` doesn't insert newline characters? ``` file.writelines(["%s\n" % item for item in list]) ``` It seems like there would be a standard way...
Yet another way. Serialize to json using [simplejson](http://code.google.com/p/simplejson/) (included as [json](http://docs.python.org/library/json.html) in python 2.6): ``` >>> import simplejson >>> f = open('output.txt', 'w') >>> simplejson.dump([1,2,3,4], f) >>> f.close() ``` If you examine output.txt: > [1, 2, 3...
Writing a list to a file with Python
899,103
214
2009-05-22T17:52:18Z
899,301
8
2009-05-22T18:29:47Z
[ "python", "file", "list", "file-io", "newline" ]
Is this the cleanest way to write a list to a file, since `writelines()` doesn't insert newline characters? ``` file.writelines(["%s\n" % item for item in list]) ``` It seems like there would be a standard way...
``` file.write('\n'.join(list)) ```
Writing a list to a file with Python
899,103
214
2009-05-22T17:52:18Z
5,032,851
21
2011-02-17T18:13:19Z
[ "python", "file", "list", "file-io", "newline" ]
Is this the cleanest way to write a list to a file, since `writelines()` doesn't insert newline characters? ``` file.writelines(["%s\n" % item for item in list]) ``` It seems like there would be a standard way...
I thought it would be interesting to explore the benefits of using a genexp, so here's my take. The example in the question uses square brackets to create a temporary list, and so is equivalent to: ``` file.writelines( list( "%s\n" % item for item in list ) ) ``` Which needlessly constructs a temporary list of all t...
Writing a list to a file with Python
899,103
214
2009-05-22T17:52:18Z
6,791,534
28
2011-07-22T14:30:50Z
[ "python", "file", "list", "file-io", "newline" ]
Is this the cleanest way to write a list to a file, since `writelines()` doesn't insert newline characters? ``` file.writelines(["%s\n" % item for item in list]) ``` It seems like there would be a standard way...
Using **Python 3** syntax: ``` with open(filepath, 'w') as file_handler: for item in the_list: file_handler.write("{}\n".format(item)) ``` This is platform-independent.
Writing a list to a file with Python
899,103
214
2009-05-22T17:52:18Z
16,452,689
10
2013-05-09T01:01:40Z
[ "python", "file", "list", "file-io", "newline" ]
Is this the cleanest way to write a list to a file, since `writelines()` doesn't insert newline characters? ``` file.writelines(["%s\n" % item for item in list]) ``` It seems like there would be a standard way...
# In General Following is the syntax for **writelines()** method ``` fileObject.writelines( sequence ) ``` # Example ``` #!/usr/bin/python # Open a file fo = open("foo.txt", "rw+") seq = ["This is 6th line\n", "This is 7th line"] # Write sequence of lines at the end of the file. line = fo.writelines( seq ) # Clo...
Python-like list comprehension in Java
899,138
42
2009-05-22T17:57:13Z
899,165
15
2009-05-22T18:02:12Z
[ "java", "python", "parameters", "methods", "list-comprehension" ]
Since Java doesn't allow passing methods as parameters, what trick do you use to implement Python like list comprehension in Java ? I have a list (ArrayList) of Strings. I need to transform each element by using a function so that I get another list. I have several functions which take a String as input and return ano...
The [Google Collections library](http://code.google.com/p/google-collections/) has lots of classes for working with collections and iterators at a much higher level than plain Java supports, and in a functional manner (filter, map, fold, etc.). It defines Function and Predicate interfaces and methods that use them to p...
Python-like list comprehension in Java
899,138
42
2009-05-22T17:57:13Z
899,172
31
2009-05-22T18:03:05Z
[ "java", "python", "parameters", "methods", "list-comprehension" ]
Since Java doesn't allow passing methods as parameters, what trick do you use to implement Python like list comprehension in Java ? I have a list (ArrayList) of Strings. I need to transform each element by using a function so that I get another list. I have several functions which take a String as input and return ano...
Basically, you create a Function interface: ``` public interface Func<In, Out> { public Out apply(In in); } ``` and then pass in an anonymous subclass to your method. Your method could either apply the function to each element in-place: ``` public static <T> void applyToListInPlace(List<T> list, Func<T, T> f) {...
Python-like list comprehension in Java
899,138
42
2009-05-22T17:57:13Z
16,732,216
9
2013-05-24T09:52:55Z
[ "java", "python", "parameters", "methods", "list-comprehension" ]
Since Java doesn't allow passing methods as parameters, what trick do you use to implement Python like list comprehension in Java ? I have a list (ArrayList) of Strings. I need to transform each element by using a function so that I get another list. I have several functions which take a String as input and return ano...
In Java 8 you can use method references: ``` List<String> list = ...; list.replaceAll(String::toUpperCase); ``` Or, if you want to create a new list instance: ``` List<String> upper = list.stream().map(String::toUpperCase).collect(Collectors.toList()); ```
Python, how to parse strings to look like sys.argv
899,276
24
2009-05-22T18:24:25Z
899,314
44
2009-05-22T18:33:07Z
[ "python", "parsing", "argv" ]
I would like to parse a string like this: ``` -o 1 --long "Some long string" ``` into this: ``` ["-o", "1", "--long", 'Some long string'] ``` or similar. This is different than either getopt, or optparse, which *start* with sys.argv parsed input (like the output I have above). Is there a standard way to do this? ...
I believe you want the [shlex](http://docs.python.org/library/shlex.html) module. ``` >>> import shlex >>> shlex.split('-o 1 --long "Some long string"') ['-o', '1', '--long', 'Some long string'] ```
Getting the caller function name inside another function in Python?
900,392
57
2009-05-22T23:19:16Z
900,404
75
2009-05-22T23:24:18Z
[ "python", "debugging" ]
If you have 2 functions like: ``` def A def B ``` and A calls B, can you get who is calling B inside B, like: ``` def A () : B () def B () : this.caller.name ```
You can use the [inspect](http://docs.python.org/library/inspect.html) module to get the calling stack. It returns a list of frame records. The third element in each record is the caller name. What you want is this: ``` >>> import inspect >>> def f(): ... print inspect.stack()[1][3] ... >>> def g(): ... f() .....
Elegant way to compare sequences
900,420
9
2009-05-22T23:32:56Z
900,426
17
2009-05-22T23:36:48Z
[ "python" ]
Does python provide an elegant way to check for "equality" of sequences of different types? The following work, but they seem rather ugly and verbose for python code: ``` def comp1(a, b): if len(a) != len(b): return False for i, v in enumerate(a): if v != b[i]: return False retu...
Convert both sequences to lists, and use builtin list comparison. It should be sufficient, unless your sequences are really large. ``` list(a) == list(b) ``` Edit: Testing done by schickb shows that using tuples is slightly faster: ``` tuple(a) == tuple(b) ```
Elegant way to compare sequences
900,420
9
2009-05-22T23:32:56Z
900,444
11
2009-05-22T23:45:37Z
[ "python" ]
Does python provide an elegant way to check for "equality" of sequences of different types? The following work, but they seem rather ugly and verbose for python code: ``` def comp1(a, b): if len(a) != len(b): return False for i, v in enumerate(a): if v != b[i]: return False retu...
You can determine the equality of any two iterables (strings, tuples, lists, even custom sequences) without creating and storing duplicate lists by using the following: ``` all(x == y for x, y in itertools.izip_longest(a, b)) ``` Note that if the two iterables are not the same length, the shorter one will be padded w...
Understanding python imports
900,591
2
2009-05-23T01:04:11Z
900,724
7
2009-05-23T02:35:50Z
[ "python", "django", "import" ]
In the process of learning Django and Python. I can't make sense of this. (Example Notes:'helloworld' is the name of my project. It has 1 app called 'app'.) ``` from helloworld.views import * # <<-- this works from helloworld import views # <<-- this doesn't work from helloworld.app import views ...
Python imports can import two different kinds of things: modules and objects. ``` import x ``` Imports an entire module named `x`. ``` import x.y ``` Imports a module named `y` and it's container `x`. You refer to `x.y`. When you created it, however, you created this directory structure ``` x __init__.py ...
Need help with the class and instance concept in Python
900,929
2
2009-05-23T05:32:13Z
900,940
7
2009-05-23T05:40:03Z
[ "python" ]
I have read several documentation already but the definition of "class" and "instance" didnt get really clear for me yet. Looks like that "class" is like a combination of functions or methods that return some result is that correct? And how about the instance? I read that you work with the class you creat trough the i...
Your question is really rather broad as classes and instances/objects are vital parts of object-oriented programming, so this is not really Python specific. I recommend you buy some books on this as, while initially basic, it can get pretty in-depth. [In essense](http://en.wikipedia.org/wiki/Class-based%5Fprogramming),...
How do I include image files in Django templates?
901,551
39
2009-05-23T13:45:07Z
901,587
20
2009-05-23T14:04:01Z
[ "python", "django", "django-templates" ]
I'm new to Django and I'm trying to learn it through a simple project I'm developing called 'dubliners' and an app called 'book'. The directory structure is like this: ``` dubliners/book/ [includes models.py, views.py, etc.] dubliners/templates/book/ ``` I have a JPG file that needs to be displayed in the header of ...
In production, you'll just have the HTML generated from your template pointing to wherever the host has media files stored. So your template will just have for example ``` <img src="../media/foo.png"> ``` And then you'll just make sure that directory is there with the relevant file(s). during development is a differ...
How do I include image files in Django templates?
901,551
39
2009-05-23T13:45:07Z
1,235,542
53
2009-08-05T20:25:36Z
[ "python", "django", "django-templates" ]
I'm new to Django and I'm trying to learn it through a simple project I'm developing called 'dubliners' and an app called 'book'. The directory structure is like this: ``` dubliners/book/ [includes models.py, views.py, etc.] dubliners/templates/book/ ``` I have a JPG file that needs to be displayed in the header of ...
Try this, ## settings.py ``` # typically, os.path.join(os.path.dirname(__file__), 'media') MEDIA_ROOT = '<your_path>/media' MEDIA_URL = '/media/' ``` ## urls.py ``` urlpatterns = patterns('', (r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT...
How do I include image files in Django templates?
901,551
39
2009-05-23T13:45:07Z
4,284,974
8
2010-11-26T11:42:45Z
[ "python", "django", "django-templates" ]
I'm new to Django and I'm trying to learn it through a simple project I'm developing called 'dubliners' and an app called 'book'. The directory structure is like this: ``` dubliners/book/ [includes models.py, views.py, etc.] dubliners/templates/book/ ``` I have a JPG file that needs to be displayed in the header of ...
I have spent two solid days working on this so I just thought I'd share my solution as well. As of 26/11/10 the current branch is 1.2.X so that means you'll have to have the following in you *settings.py*: ``` MEDIA_ROOT = "<path_to_files>" (i.e. /home/project/django/app/templates/static) MEDIA_URL = "http://localhost...
python factory functions compared to class
901,892
13
2009-05-23T16:43:25Z
902,010
23
2009-05-23T17:38:58Z
[ "python", "function" ]
Just working through learning python and started to look at nested/factory functions (simple example): ``` def maker(N): def action(X): return X * N return action ``` Are there any advantages of factory functions over creating a class? performance? memory? clean up?
What I like most about nested functions is that it is less verbose than classes. The equivalent class definition to your maker function is: ``` class clsmaker(object): def __init__(self, N): self.N = N def __call__(self, X): return X * self.N ``` That doesn't seem so bad until you start adding more ...
python factory functions compared to class
901,892
13
2009-05-23T16:43:25Z
902,809
9
2009-05-24T00:55:57Z
[ "python", "function" ]
Just working through learning python and started to look at nested/factory functions (simple example): ``` def maker(N): def action(X): return X * N return action ``` Are there any advantages of factory functions over creating a class? performance? memory? clean up?
Comparing a function factory to a class is comparing apples and oranges. Use a class if you have a cohesive collection of data and functions, together called an object. Use a function factory if you need a function, and want to parameterize its creation. Your choice of the two techniques should depend on the meaning o...
Python OSError: [Errno 2]
901,982
31
2009-05-23T17:24:03Z
901,992
53
2009-05-23T17:31:21Z
[ "python", "subprocess" ]
I have the following code that is attempting to start each of the "commands" below in Linux. The module attempts to keep each of the 2 commands running if either should crash for whatever reason. ``` #!/usr/bin/env python import subprocess commands = [ ["screen -dmS RealmD top"], ["screen -DmS RealmD top -d 5"] ] pro...
Use `["screen", "-dmS", "RealmD", "top"]` instead of `["screen -dmS RealmD top"]`. Maybe also use the complete path to `screen`. If the program still cannot be found you can also go through your shell with `shell=True`, but then you need to quote and escape your parameters etc. Make sure to read the [information in t...
How to use variables in SQL statement in Python?
902,408
30
2009-05-23T20:20:33Z
902,417
33
2009-05-23T20:25:24Z
[ "python", "sql" ]
Ok so I'm not that experienced in Python. I have the following Python code: ``` cursor.execute("INSERT INTO table VALUES var1, var2, var3,") ``` where `var1` is an integer, `var2` & `var3` are strings. How can I write the variable names without python including them as part of the query text?
``` cursor.execute("INSERT INTO table VALUES (%s, %s, %s)", (var1, var2, var3)) ``` Note that the parameters are passed as a tuple. The database API does proper escaping and quoting of variables. Be careful not to use the string formatting operator (`%`), because 1. it does not do any escaping or quoting. 2. it is p...
How to use variables in SQL statement in Python?
902,408
30
2009-05-23T20:20:33Z
902,426
12
2009-05-23T20:28:11Z
[ "python", "sql" ]
Ok so I'm not that experienced in Python. I have the following Python code: ``` cursor.execute("INSERT INTO table VALUES var1, var2, var3,") ``` where `var1` is an integer, `var2` & `var3` are strings. How can I write the variable names without python including them as part of the query text?
<http://www.amk.ca/python/writing/DB-API.html> Be careful when you simply append values of variables to your statements: Imagine a user naming himself `';DROP TABLE Users;'` -- That's why you need to use sql escaping, which Python provides for you when you use the cursor.execute in a decent manner. Example in the url ...
How to use variables in SQL statement in Python?
902,408
30
2009-05-23T20:20:33Z
902,836
24
2009-05-24T01:14:23Z
[ "python", "sql" ]
Ok so I'm not that experienced in Python. I have the following Python code: ``` cursor.execute("INSERT INTO table VALUES var1, var2, var3,") ``` where `var1` is an integer, `var2` & `var3` are strings. How can I write the variable names without python including them as part of the query text?
Different implementations of the Python DB-API are allowed to use different placeholders, so you'll need to find out which one you're using -- it could be (e.g. with MySQLdb): ``` cursor.execute("INSERT INTO table VALUES (%s, %s, %s)", (var1, var2, var3)) ``` or (e.g. with sqlite3 from the Python standard library): ...
How to use variables in SQL statement in Python?
902,408
30
2009-05-23T20:20:33Z
21,734,918
11
2014-02-12T17:16:52Z
[ "python", "sql" ]
Ok so I'm not that experienced in Python. I have the following Python code: ``` cursor.execute("INSERT INTO table VALUES var1, var2, var3,") ``` where `var1` is an integer, `var2` & `var3` are strings. How can I write the variable names without python including them as part of the query text?
Many ways. **DON'T** use the most obvious one (`%s` with `%`) in real code, it's open to [attacks](http://en.wikipedia.org/wiki/SQL_injection). Here copy-paste'd **[from pydoc of sqlite3](http://docs.python.org/2/library/sqlite3.html)**: ``` # Never do this -- insecure! symbol = 'RHAT' c.execute("SELECT * FROM stocks...
Issue with adding new properties to existing Google AppEngine data models / entities
902,633
4
2009-05-23T22:24:15Z
902,672
8
2009-05-23T22:53:58Z
[ "python", "google-app-engine", "properties", "bigtable" ]
In GAE, I have a model called Foo, with existing entities, and attempt to add a new property called *memcached* to Foo that takes datetime values for the last time this value was set to memcache. If I try to query and sort on this property, or even filter for entities that do not have a value for *memcached*, entities ...
There's nothing for it but to go through each of your existing entities and add the property, [here is the official documentation which walks you through the process](http://code.google.com/appengine/articles/update%5Fschema.html).
Saving a Numpy array as an image
902,761
74
2009-05-24T00:08:50Z
902,774
21
2009-05-24T00:26:05Z
[ "python", "image", "numpy" ]
I have a matrix in the type of a Numpy array. How would I write it to disk it as an image? Any format works (png, jpeg, bmp...). One important constraint is that PIL is not present.
You can use [PyPNG](https://github.com/drj11/pypng/). It's a pure Python (no dependencies) open source PNG encoder/decoder and it [supports](http://packages.python.org/pypng/ex.html#numpy) writing NumPy arrays as images.
Saving a Numpy array as an image
902,761
74
2009-05-24T00:08:50Z
977,040
15
2009-06-10T17:29:37Z
[ "python", "image", "numpy" ]
I have a matrix in the type of a Numpy array. How would I write it to disk it as an image? Any format works (png, jpeg, bmp...). One important constraint is that PIL is not present.
If you have matplotlib, you can do: ``` import matplotlib.pyplot as plt plt.imshow(matrix) #Needs to be in row,col order plt.savefig(filename) ```
Saving a Numpy array as an image
902,761
74
2009-05-24T00:08:50Z
1,713,101
107
2009-11-11T04:53:29Z
[ "python", "image", "numpy" ]
I have a matrix in the type of a Numpy array. How would I write it to disk it as an image? Any format works (png, jpeg, bmp...). One important constraint is that PIL is not present.
This uses PIL, but maybe some might find it useful: ``` import scipy.misc scipy.misc.imsave('outfile.jpg', image_array) ``` **EDIT**: The current `scipy` version started to normalize all images so that min(data) become black and max(data) become white. This is unwanted if the data should be exact grey levels or exact...
Saving a Numpy array as an image
902,761
74
2009-05-24T00:08:50Z
8,538,444
32
2011-12-16T18:21:39Z
[ "python", "image", "numpy" ]
I have a matrix in the type of a Numpy array. How would I write it to disk it as an image? Any format works (png, jpeg, bmp...). One important constraint is that PIL is not present.
An answer using PIL (just in case it's useful). given a numpy array "A": ``` import Image im = Image.fromarray(A) im.save("your_file.jpeg") ``` you can replace "jpeg" with almost any format you want. More details about the formats [here](http://www.pythonware.com/library/pil/handbook/index.htm)
Saving a Numpy array as an image
902,761
74
2009-05-24T00:08:50Z
19,174,800
28
2013-10-04T06:33:01Z
[ "python", "image", "numpy" ]
I have a matrix in the type of a Numpy array. How would I write it to disk it as an image? Any format works (png, jpeg, bmp...). One important constraint is that PIL is not present.
Pure Python (2 & 3), a snippet without 3rd party dependencies. This function writes compressed, true-color (4 bytes per pixel) `RGBA` PNG's. ``` def write_png(buf, width, height): """ buf: must be bytes or a bytearray in Python3.x, a regular string in Python2.x. """ import zlib, struct # reve...
Saving a Numpy array as an image
902,761
74
2009-05-24T00:08:50Z
22,823,821
9
2014-04-02T21:51:28Z
[ "python", "image", "numpy" ]
I have a matrix in the type of a Numpy array. How would I write it to disk it as an image? Any format works (png, jpeg, bmp...). One important constraint is that PIL is not present.
With `matplotlib`: ``` import matplotlib matplotlib.image.imsave('name.png', array) ``` Works with matplotlib 1.3.1, I don't know about lower version. From the docstring: ``` Arguments: *fname*: A string containing a path to a filename, or a Python file-like object. If *format* is *None* and *fname* is a ...
Saving a Numpy array as an image
902,761
74
2009-05-24T00:08:50Z
27,115,931
10
2014-11-24T23:10:45Z
[ "python", "image", "numpy" ]
I have a matrix in the type of a Numpy array. How would I write it to disk it as an image? Any format works (png, jpeg, bmp...). One important constraint is that PIL is not present.
There's `opencv` for python (<http://docs.opencv.org/trunk/doc/py_tutorials/py_tutorials.html>). ``` import cv2 import numpy as np cv2.imwrite("filename.png", np.zeros((10,10))) ``` useful if you need to do more processing other than saving.
Data storage to ease data interpolation in Python
902,910
6
2009-05-24T02:14:27Z
903,071
7
2009-05-24T04:28:26Z
[ "python", "interpolation" ]
I have 20+ tables similar to table 1. Where all letters represent actual values. ``` Table 1: $ / cars |<1 | 2 | 3 | 4+ <10,000 | a | b | c | d 20,000 | e | f | g | h 30,000 | i | j | k | l 40,000+ | m | n | o | p ``` A user input could be for example, (2.4, 24594) which is a value between f, g, j, and k. My Py...
If you want the most computationally efficient solution I can think of and are not restricted to the standard library, then I would recommend scipy/numpy. First, store the a..p array as a 2D numpy array and then both the $4k-10k and 1-4 arrays as 1D numpy arrays. Use scipy's interpolate.interp1d if both 1D arrays are m...
hasattr() vs try-except block to deal with non-existent attributes
903,130
54
2009-05-24T05:11:59Z
903,138
60
2009-05-24T05:17:15Z
[ "python", "exception", "exception-handling", "attributes", "hasattr" ]
``` if hasattr(obj, 'attribute'): # do somthing ``` vs ``` try: # access obj.attribute except AttributeError, e: # deal with AttributeError ``` Which should be preferred and why?
`hasattr` internally and rapidly performs the same task as the `try/except` block: it's a very specific, optimized, one-task tool and thus should be preferred, when applicable, to the very general-purpose alternative.
hasattr() vs try-except block to deal with non-existent attributes
903,130
54
2009-05-24T05:11:59Z
903,162
13
2009-05-24T05:37:42Z
[ "python", "exception", "exception-handling", "attributes", "hasattr" ]
``` if hasattr(obj, 'attribute'): # do somthing ``` vs ``` try: # access obj.attribute except AttributeError, e: # deal with AttributeError ``` Which should be preferred and why?
I would say it depends on whether your function may accept objects without the attribute **by design**, e.g. if you have two callers to the function, one providing an object with the attribute and the other providing an object without it. If the only case where you'll get an object without the attribute is due to some...
hasattr() vs try-except block to deal with non-existent attributes
903,130
54
2009-05-24T05:11:59Z
903,238
66
2009-05-24T06:41:27Z
[ "python", "exception", "exception-handling", "attributes", "hasattr" ]
``` if hasattr(obj, 'attribute'): # do somthing ``` vs ``` try: # access obj.attribute except AttributeError, e: # deal with AttributeError ``` Which should be preferred and why?
*Any benches that illustrate difference in performance?* timeit it's your friend ``` $ python -mtimeit -s 'class C(object): a = 4 c = C()' 'hasattr(c, "nonexistent")' 1000000 loops, best of 3: 1.87 usec per loop $ python -mtimeit -s 'class C(object): a = 4 c = C()' 'hasattr(c, "a")' 1000000 loops, best of 3: 0.446 us...
hasattr() vs try-except block to deal with non-existent attributes
903,130
54
2009-05-24T05:11:59Z
16,186,050
15
2013-04-24T07:32:57Z
[ "python", "exception", "exception-handling", "attributes", "hasattr" ]
``` if hasattr(obj, 'attribute'): # do somthing ``` vs ``` try: # access obj.attribute except AttributeError, e: # deal with AttributeError ``` Which should be preferred and why?
I almost always use `hasattr`: it's the correct choice for most cases. The problematic case is when a class overrides `__getattr__`: `hasattr` will **catch all exceptions** instead of catching just `AttributeError` like you expect. In other words, the code below will print `b: False` even though it would be more appro...
hasattr() vs try-except block to deal with non-existent attributes
903,130
54
2009-05-24T05:11:59Z
16,727,179
12
2013-05-24T03:18:35Z
[ "python", "exception", "exception-handling", "attributes", "hasattr" ]
``` if hasattr(obj, 'attribute'): # do somthing ``` vs ``` try: # access obj.attribute except AttributeError, e: # deal with AttributeError ``` Which should be preferred and why?
There is a third, and often better, alternative: ``` attr = getattr(obj, 'attribute', None) if attr is not None: print attr ``` Advantages: 1. `getattr` does not have the bad [exception-swallowing behavior pointed out by Martin Geiser](http://stackoverflow.com/a/16186050/243712) - in old Pythons, `hasattr` will...
How to implement hotlinking prevention in Google App Engine
903,144
5
2009-05-24T05:21:29Z
903,307
11
2009-05-24T08:02:20Z
[ "python", "google-app-engine", "hotlinking" ]
My application is on GAE and I'm trying to figure out how to prevent hotlinking of images dynamically served (e.g. /image?id=E23432E) in Python. Please advise.
In Google webapp framework, you can extract the referer from the [Request class](http://code.google.com/appengine/docs/python/tools/webapp/requestclass.html): ``` def get(self): referer = self.request.headers.get("Referer") # Will be None if no referer given in header. ``` Note that's `referer`, not `referrer...
Python's 'with' statement versus 'with .. as'
903,557
14
2009-05-24T11:17:24Z
904,357
18
2009-05-24T18:18:37Z
[ "python", "syntax" ]
Having just pulled my hair off because of a difference, I'd like to know what the difference *really* is in Python 2.5. I had two blocks of code (`dbao.getConnection()` returns a MySQLdb connection). ``` conn = dbao.getConnection() with conn: # Do stuff ``` And ``` with dbao.getConnection() as conn: # Do st...
In general terms, the value assigned by the `as` part of a `with` statement is going to be whatever gets returned by the [`__enter__` method of the context manager](http://docs.python.org/library/stdtypes.html#contextmanager.%5F%5Fenter%5F%5F).
Python's 'with' statement versus 'with .. as'
903,557
14
2009-05-24T11:17:24Z
904,590
27
2009-05-24T20:34:40Z
[ "python", "syntax" ]
Having just pulled my hair off because of a difference, I'd like to know what the difference *really* is in Python 2.5. I had two blocks of code (`dbao.getConnection()` returns a MySQLdb connection). ``` conn = dbao.getConnection() with conn: # Do stuff ``` And ``` with dbao.getConnection() as conn: # Do st...
It may be a little confusing at first glance, but ``` with babby() as b: ... ``` is *not* equivalent to ``` b = babby() with b: ... ``` To see why, here's how the context manager would be implemented: ``` class babby(object): def __enter__(self): return 'frigth' def __exit__(self, type, va...
python, regular expressions, named groups and "logical or" operator
903,562
5
2009-05-24T11:18:20Z
903,567
12
2009-05-24T11:21:18Z
[ "python", "regex" ]
In python regular expression, named and unnamed groups are both defined with '(' and ')'. This leads to a weird behavior. Regexp ``` "(?P<a>1)=(?P<b>2)" ``` used with text "1=2" will find named group "a" with value "1" and named group "b" with value "2". But if i want to use "logical or" operator and concatenate mult...
Use `(?:)` to get rid of the unnamed group: ``` r"(?:(?P<a>1)=(?P<b>2))|(?P<c>3)" ``` From the documentation of [re](http://docs.python.org/library/re.html): > (?:...) A non-grouping version of > regular parentheses. Matches whatever > regular expression is inside the > parentheses, but the substring matched > by th...
How do you extract a column from a multi-dimensional array?
903,853
80
2009-05-24T14:19:47Z
903,867
75
2009-05-24T14:24:23Z
[ "python", "arrays", "multidimensional-array", "extraction" ]
Does anybody know how to extract a column from a multi-dimensional array in Python?
Could it be that you're using a [NumPy array](http://docs.scipy.org/doc/numpy/user/basics.indexing.html#indexing-multi-dimensional-arrays)? Python has the [array](http://docs.python.org/library/array.html) module, but that does not support multi-dimensional arrays. Normal Python lists are single-dimensional too. Howev...
How do you extract a column from a multi-dimensional array?
903,853
80
2009-05-24T14:19:47Z
904,532
8
2009-05-24T19:57:39Z
[ "python", "arrays", "multidimensional-array", "extraction" ]
Does anybody know how to extract a column from a multi-dimensional array in Python?
The itemgetter operator can help too, if you like map-reduce style python, rather than list comprehensions, for a little variety! ``` # tested in 2.4 from operator import itemgetter def column(matrix,i): f = itemgetter(i) return map(f,matrix) M = [range(x,x+5) for x in range(10)] assert column(M,1) == range(1...
How do you extract a column from a multi-dimensional array?
903,853
80
2009-05-24T14:19:47Z
7,578,114
76
2011-09-28T03:55:53Z
[ "python", "arrays", "multidimensional-array", "extraction" ]
Does anybody know how to extract a column from a multi-dimensional array in Python?
``` >>> import numpy as np >>> A = np.array([[1,2,3,4],[5,6,7,8]]) >>> A array([[1, 2, 3, 4], [5, 6, 7, 8]]) >>> A[:,2] # returns the third columm array([3, 7]) ``` See also: "numpy.arange" and "reshape" to allocate memory Example: (Allocating a array with shaping of matrix (3x4)) ``` nrows = 3 ncols = 4 my_ar...
How do you extract a column from a multi-dimensional array?
903,853
80
2009-05-24T14:19:47Z
7,766,288
32
2011-10-14T10:21:58Z
[ "python", "arrays", "multidimensional-array", "extraction" ]
Does anybody know how to extract a column from a multi-dimensional array in Python?
If you have an array like ``` a = [[1, 2], [2, 3], [3, 4]] ``` Then you extract the first column like that: ``` [row[0] for row in a] ``` So the result looks like this: ``` [1, 2, 3] ```
How do you extract a column from a multi-dimensional array?
903,853
80
2009-05-24T14:19:47Z
13,518,274
17
2012-11-22T18:25:45Z
[ "python", "arrays", "multidimensional-array", "extraction" ]
Does anybody know how to extract a column from a multi-dimensional array in Python?
check it out! ``` a = [[1, 2], [2, 3], [3, 4]] a2 = zip(*a) a2[0] ``` it is the same thing as above except somehow it is neater the zip does the work but requires single arrays as arguments, the \*a syntax unpacks the multidimensional array into single array arguments
Chain-calling parent constructors in python
904,036
211
2009-05-24T15:54:09Z
904,078
136
2009-05-24T16:12:27Z
[ "python", "oop", "inheritance", "constructor" ]
Consider this - a base class A, class B inheriting from A, class C inheriting from B. What is a generic way to call a parent class constructor in a constructor? If this still sounds too vague, here's some code. ``` class A(object): def __init__(self): print "Constructor A was called" class B(A): def _...
The way you are doing it is indeed the recommended one (for Python 2.x). The issue of whether the class is passed explicitly to `super` is a matter of style rather than functionality. Passing the class to `super` fits in with Python's philosophy of "explicit is better than implicit".
Chain-calling parent constructors in python
904,036
211
2009-05-24T15:54:09Z
904,081
134
2009-05-24T16:13:32Z
[ "python", "oop", "inheritance", "constructor" ]
Consider this - a base class A, class B inheriting from A, class C inheriting from B. What is a generic way to call a parent class constructor in a constructor? If this still sounds too vague, here's some code. ``` class A(object): def __init__(self): print "Constructor A was called" class B(A): def _...
Python 3 includes an improved super() which allows use like this: ``` super().__init__(args) ```
Chain-calling parent constructors in python
904,036
211
2009-05-24T15:54:09Z
17,398,819
12
2013-07-01T06:49:56Z
[ "python", "oop", "inheritance", "constructor" ]
Consider this - a base class A, class B inheriting from A, class C inheriting from B. What is a generic way to call a parent class constructor in a constructor? If this still sounds too vague, here's some code. ``` class A(object): def __init__(self): print "Constructor A was called" class B(A): def _...
You can simply write : ``` class A(object): def __init__(self): print "Constructor A was called" class B(A): def __init__(self): A.__init__(self) # A.__init__(self,<parameters>) if you want to call with parameters print "Constructor B was called" class C(B): def __init_...
Reading a UTF8 CSV file with Python
904,041
50
2009-05-24T15:56:31Z
904,085
79
2009-05-24T16:14:49Z
[ "python", "utf-8", "csv", "character-encoding" ]
I am trying to read a CSV file with accented characters with Python (only French and/or Spanish characters). Based on the Python 2.5 documentation for the csvreader (<http://docs.python.org/library/csv.html>), I came up with the following code to read the CSV file since the csvreader supports only ASCII. ``` def unico...
The `.encode` method gets applied to a Unicode string to make a byte-string; but you're calling it on a byte-string instead... the wrong way 'round! Look at the `codecs` module in the standard library and `codecs.open` in particular for better general solutions for reading UTF-8 encoded text files. However, for the `cs...
Reading a UTF8 CSV file with Python
904,041
50
2009-05-24T15:56:31Z
14,786,752
23
2013-02-09T09:37:14Z
[ "python", "utf-8", "csv", "character-encoding" ]
I am trying to read a CSV file with accented characters with Python (only French and/or Spanish characters). Based on the Python 2.5 documentation for the csvreader (<http://docs.python.org/library/csv.html>), I came up with the following code to read the CSV file since the csvreader supports only ASCII. ``` def unico...
### Python 2.X There is a [unicode-csv](https://github.com/jdunck/python-unicodecsv) library which should solve your problems, with added benefit of not naving to write any new csv-related code. Here is a example from their readme: ``` >>> import unicodecsv >>> from cStringIO import StringIO >>> f = StringIO() >>> w...
The wrong python interpreter is called
904,170
9
2009-05-24T16:55:25Z
904,185
16
2009-05-24T16:59:38Z
[ "python", "python-3.x" ]
I updated my python interpreter, but I think the old one is still called. When I check for the version I get: ``` $ python -V Python 3.0.1 ``` But I believe the old interpreter is still being called. When I run the command: ``` python myProg.py ``` The script runs properly. But when I invoke it with the command ``...
According to the first line of the script, `#!/usr/bin/python`, you are calling the Python interpreter at `/usr/bin/python` (which is most likely the one that ships with Mac OS X). You have to change that path to the path where you installed your Python 3 interpreter (likely `/usr/local/bin/python` or `/opt/local/bin/p...
How to parse malformed HTML in python
904,644
12
2009-05-24T20:59:27Z
904,655
22
2009-05-24T21:06:13Z
[ "python", "html", "lxml" ]
I need to browse the DOM tree of a parsed HTML document. I'm using uTidyLib before parsing the string with lxml a = tidy.parseString(html\_code, options) dom = etree.fromstring(str(a)) sometimes I get an error, it seems that tidylib is not able to repair malformed html. how can I parse every HTML file without getti...
[Beautiful Soup](http://www.crummy.com/software/BeautifulSoup/) does a good job with invalid/broken HTML ``` >>> from BeautifulSoup import BeautifulSoup >>> soup = BeautifulSoup("<htm@)($*><body><table <tr><td>hi</tr></td></body><html") >>> print soup.prettify() <htm> <body> <table> <tr> <td> hi </t...
How to parse malformed HTML in python
904,644
12
2009-05-24T20:59:27Z
904,821
13
2009-05-24T22:52:08Z
[ "python", "html", "lxml" ]
I need to browse the DOM tree of a parsed HTML document. I'm using uTidyLib before parsing the string with lxml a = tidy.parseString(html\_code, options) dom = etree.fromstring(str(a)) sometimes I get an error, it seems that tidylib is not able to repair malformed html. how can I parse every HTML file without getti...
Since you are already using lxml, have you tried [lxml's](http://lxml.de/) [ElementSoup](http://lxml.de/elementsoup.html) module? If ElementSoup can't repair the HTML then you'll probably need to apply your own filters first that are based on your own observations of how the data is broken.
How to remove all characters after a specific character in python?
904,746
33
2009-05-24T21:56:49Z
904,756
57
2009-05-24T22:01:34Z
[ "python", "replace", "python-2.6" ]
I have a string. How do I remove all text after a certain character? (*In this case `...`*) The text after will **`...`** change so I that's why I want to remove all characters after a certain one.
Split on your separator at most once, and take the first piece: ``` sep = '...' rest = text.split(sep, 1)[0] ``` You didn't say what should happen if the separator isn't present. Both this and Alex's solution will return the entire string in that case.
How to remove all characters after a specific character in python?
904,746
33
2009-05-24T21:56:49Z
904,758
35
2009-05-24T22:02:26Z
[ "python", "replace", "python-2.6" ]
I have a string. How do I remove all text after a certain character? (*In this case `...`*) The text after will **`...`** change so I that's why I want to remove all characters after a certain one.
Assuming your separator is '...', but it can be any string. ``` text = 'some string... this part will be removed.' head, sep, tail = text.partition('...') >>> print head some string ``` If the separator is not found, `head` will contain all of the original string. The partition function was added in Python 2.5. > ...
Python strftime - date without leading 0?
904,928
125
2009-05-25T00:11:49Z
904,954
30
2009-05-25T00:22:43Z
[ "python", "padding", "strftime" ]
When using Python `strftime`, is there a way to remove the first 0 of the date if it's before the 10th, ie. so `01` is `1`? Can't find a `%`thingy for that? Thanks!
Some platforms may support width and precision specification between `%` and the letter (such as 'd' for day of month), according to <http://docs.python.org/library/time.html> -- but it's definitely a non-portable solution (e.g. doesn't work on my Mac;-). Maybe you can use a string replace (or RE, for really nasty form...
Python strftime - date without leading 0?
904,928
125
2009-05-25T00:11:49Z
907,607
14
2009-05-25T18:13:36Z
[ "python", "padding", "strftime" ]
When using Python `strftime`, is there a way to remove the first 0 of the date if it's before the 10th, ie. so `01` is `1`? Can't find a `%`thingy for that? Thanks!
[Here](http://www.gnu.org/software/libc/manual/html%5Fnode/Formatting-Calendar-Time.html#index-strftime-2660) is the documentation of the modifiers supported by `strftime()` in the GNU C library. (Like people said before, it might not be portable.) Of interest to you might be: * `%e` instead of `%d` will replace leadi...
Python strftime - date without leading 0?
904,928
125
2009-05-25T00:11:49Z
1,428,227
8
2009-09-15T16:31:23Z
[ "python", "padding", "strftime" ]
When using Python `strftime`, is there a way to remove the first 0 of the date if it's before the 10th, ie. so `01` is `1`? Can't find a `%`thingy for that? Thanks!
I find the Django template date formatting filter to be quick and easy. It strips out leading zeros. If you don't mind importing the Django module, check it out. <http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date> ``` from django.template.defaultfilters import date as django_date_filter print django_d...
Python strftime - date without leading 0?
904,928
125
2009-05-25T00:11:49Z
2,073,189
271
2010-01-15T16:38:41Z
[ "python", "padding", "strftime" ]
When using Python `strftime`, is there a way to remove the first 0 of the date if it's before the 10th, ie. so `01` is `1`? Can't find a `%`thingy for that? Thanks!
Actually I had the same problem and I realized that, if you add a hyphen between the `%` and the letter, you can remove the leading zero. For example `%Y/%-m/%-d`. Only works on Unix (Linux, OS X). Doesn't work in Windows (including Cygwin).
Python strftime - date without leading 0?
904,928
125
2009-05-25T00:11:49Z
5,900,593
16
2011-05-05T15:46:24Z
[ "python", "padding", "strftime" ]
When using Python `strftime`, is there a way to remove the first 0 of the date if it's before the 10th, ie. so `01` is `1`? Can't find a `%`thingy for that? Thanks!
``` >>> import datetime >>> d = datetime.datetime.now() >>> d.strftime('X%d/X%m/%Y').replace('X0','X').replace('X','') '5/5/2011' ```
Python strftime - date without leading 0?
904,928
125
2009-05-25T00:11:49Z
16,097,385
115
2013-04-19T04:48:02Z
[ "python", "padding", "strftime" ]
When using Python `strftime`, is there a way to remove the first 0 of the date if it's before the 10th, ie. so `01` is `1`? Can't find a `%`thingy for that? Thanks!
We can do this sort of thing with the advent of the [`format`](https://docs.python.org/2/library/functions.html#format) method since python2.6: ``` >>> import datetime >>> '{dt.year}/{dt.month}/{dt.day}'.format(dt = datetime.datetime.now()) '2013/4/19' ``` Though perhaps beyond the scope of the original question, for...
Python strftime - date without leading 0?
904,928
125
2009-05-25T00:11:49Z
31,748,295
7
2015-07-31T14:12:53Z
[ "python", "padding", "strftime" ]
When using Python `strftime`, is there a way to remove the first 0 of the date if it's before the 10th, ie. so `01` is `1`? Can't find a `%`thingy for that? Thanks!
On Windows, add a '#', as in '%#m/%#d/%Y %#I:%M:%S %p' For reference: <https://msdn.microsoft.com/en-us/library/fe06s4ak.aspx>
Python and Intellisense
905,005
56
2009-05-25T01:02:23Z
905,036
30
2009-05-25T01:25:42Z
[ "python", "ide", "intellisense" ]
Is there an equivalent to 'intellisense' for Python? Perhaps i shouldn't admit it but I find having intellisense really speeds up the 'discovery phase' of learning a new language. For instance switching from VB.net to C# was a breeze due to snippets and intellisense helping me along.
[This](http://blog.dispatched.ch/2009/05/24/vim-as-python-ide/) blog entry explains setting Vim up as a Python IDE, he covers Intellisense-like functionality: ![Python Intellsense](http://blog.dispatched.ch/wp-content/uploads/2009/05/omnicompletion.png) This is standard in Vim 7. There are a number of other very usef...
Python and Intellisense
905,005
56
2009-05-25T01:02:23Z
905,053
19
2009-05-25T01:34:23Z
[ "python", "ide", "intellisense" ]
Is there an equivalent to 'intellisense' for Python? Perhaps i shouldn't admit it but I find having intellisense really speeds up the 'discovery phase' of learning a new language. For instance switching from VB.net to C# was a breeze due to snippets and intellisense helping me along.
The [PyDev](http://pydev.sf.net/) environment for Eclipse has intellisense-like functionality for Python. Keeping an interactive console open, along with the `help(item)` function is very helpful.
Python and Intellisense
905,005
56
2009-05-25T01:02:23Z
905,076
9
2009-05-25T01:54:20Z
[ "python", "ide", "intellisense" ]
Is there an equivalent to 'intellisense' for Python? Perhaps i shouldn't admit it but I find having intellisense really speeds up the 'discovery phase' of learning a new language. For instance switching from VB.net to C# was a breeze due to snippets and intellisense helping me along.
I strongly recommend [PyDev](http://pydev.sourceforge.net). In Pydev you can put the module you are using in the [**Forced Buildins**](http://www.fabioz.com/pydev/manual%5F101%5Finterpreter.html), mostly the code-completion will work better than in other IDEs like KOMODO EDIT. Also I think [IPython](http://ipython.sci...
Python and Intellisense
905,005
56
2009-05-25T01:02:23Z
905,167
8
2009-05-25T02:55:47Z
[ "python", "ide", "intellisense" ]
Is there an equivalent to 'intellisense' for Python? Perhaps i shouldn't admit it but I find having intellisense really speeds up the 'discovery phase' of learning a new language. For instance switching from VB.net to C# was a breeze due to snippets and intellisense helping me along.
The [IDLE editor](http://en.wikipedia.org/wiki/IDLE%5F%28Python%29) that comes with Python has an intellisense feature that auto-discovers imported modules, functions, classes and attributes.
Python and Intellisense
905,005
56
2009-05-25T01:02:23Z
905,206
13
2009-05-25T03:22:07Z
[ "python", "ide", "intellisense" ]
Is there an equivalent to 'intellisense' for Python? Perhaps i shouldn't admit it but I find having intellisense really speeds up the 'discovery phase' of learning a new language. For instance switching from VB.net to C# was a breeze due to snippets and intellisense helping me along.
The dynamic nature of the language tends to make autocomplete type analysis difficult, so the quality of the various completion facilities menitoned above varies wildly. While it's not exactly what you asked for, the ipython shell is very good for exploratory work. When I'm working with a new module, I tend to pull it...
Python and Intellisense
905,005
56
2009-05-25T01:02:23Z
6,963,061
18
2011-08-05T22:00:12Z
[ "python", "ide", "intellisense" ]
Is there an equivalent to 'intellisense' for Python? Perhaps i shouldn't admit it but I find having intellisense really speeds up the 'discovery phase' of learning a new language. For instance switching from VB.net to C# was a breeze due to snippets and intellisense helping me along.
Have a look at [python tools for visual studio](http://pytools.codeplex.com/), they provide code completion (a.k.a intellisense), debugging etc ... Below is a screenshot of the interactive shell for python showing code completion. ![enter image description here](http://i.stack.imgur.com/UhMnP.png)
Resources concerning Python scripting in Vim
905,020
34
2009-05-25T01:11:07Z
905,026
23
2009-05-25T01:16:08Z
[ "python", "vim" ]
I'm trying to learn a little about python scripting in GVim, but I'm having trouble with starting. Elementary things, really. Are there any resources / tutorials concerting python scripting in Vim out there ? Simple examples which show the basic principles, would be welcomed also.
Here is all I know of in terms of such docs: * [A nice presentation by Sean Reifschneider](http://www.tummy.com/Community/Presentations/vimpython-20070225/vim.html) * [The "official" VIM Python Interface reference](http://vimdoc.sourceforge.net/htmldoc/if_pyth.html) * [some shorter notes](http://zerokspot.com/weblog/2...